Merge "Stagefright: Return error if codec takes too long to return a buffer."
diff --git a/Android.mk b/Android.mk
index 7bf5db5..e7271304 100644
--- a/Android.mk
+++ b/Android.mk
@@ -113,6 +113,7 @@
 	core/java/android/content/pm/IPackageMoveObserver.aidl \
 	core/java/android/content/pm/IPackageStatsObserver.aidl \
 	core/java/android/database/IContentObserver.aidl \
+	core/java/android/hardware/usb/IUsbManager.aidl \
 	core/java/android/net/IConnectivityManager.aidl \
 	core/java/android/net/INetworkManagementEventObserver.aidl \
 	core/java/android/net/IThrottleManager.aidl \
@@ -120,10 +121,10 @@
 	core/java/android/nfc/ILlcpServiceSocket.aidl \
 	core/java/android/nfc/ILlcpSocket.aidl \
 	core/java/android/nfc/INfcAdapter.aidl \
+	core/java/android/nfc/INfcAdapterExtras.aidl \
 	core/java/android/nfc/INfcTag.aidl \
 	core/java/android/nfc/IP2pInitiator.aidl \
 	core/java/android/nfc/IP2pTarget.aidl \
-    core/java/android/nfc/INfcSecureElement.aidl \
 	core/java/android/os/IHardwareService.aidl \
 	core/java/android/os/IMessenger.aidl \
 	core/java/android/os/INetworkManagementService.aidl \
diff --git a/CleanSpec.mk b/CleanSpec.mk
index 2ee8f31..8c3b17e 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -73,6 +73,7 @@
 $(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/core/java/com/trustedlogic)
 $(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/android_stubs_current_intermediates/src/com/trustedlogic)
 $(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/core/java/android/nfc/INdefTag.java)
+$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/core/java/android/nfc)
 
 # ************************************************
 # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
diff --git a/api/current.xml b/api/current.xml
index c43075b..f76a216 100644
--- a/api/current.xml
+++ b/api/current.xml
@@ -77615,6 +77615,17 @@
  visibility="public"
 >
 </field>
+<field name="TYPE_RELATIVE_HUMIDITY"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="12"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="TYPE_ROTATION_VECTOR"
  type="int"
  transient="false"
@@ -192791,6 +192802,17 @@
  visibility="public"
 >
 </method>
+<method name="getScaledLargeTouchSlop"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
 <method name="getScaledMaximumDrawingCacheSize"
  return="int"
  abstract="false"
diff --git a/cmds/pm/src/com/android/commands/pm/Pm.java b/cmds/pm/src/com/android/commands/pm/Pm.java
index d764aa9..f2b6fce 100644
--- a/cmds/pm/src/com/android/commands/pm/Pm.java
+++ b/cmds/pm/src/com/android/commands/pm/Pm.java
@@ -30,14 +30,15 @@
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageItemInfo;
 import android.content.pm.PackageManager;
+import android.content.pm.ParceledListSlice;
 import android.content.pm.PermissionGroupInfo;
 import android.content.pm.PermissionInfo;
 import android.content.res.AssetManager;
 import android.content.res.Resources;
 import android.net.Uri;
+import android.os.Parcel;
 import android.os.RemoteException;
 import android.os.ServiceManager;
-import android.provider.Settings;
 
 import java.io.File;
 import java.lang.reflect.Field;
@@ -223,7 +224,7 @@
         String filter = nextArg();
 
         try {
-            List<PackageInfo> packages = mPm.getInstalledPackages(getFlags);
+            final List<PackageInfo> packages = getInstalledPackages(mPm, getFlags);
 
             int count = packages.size();
             for (int p = 0 ; p < count ; p++) {
@@ -247,6 +248,22 @@
         }
     }
 
+    @SuppressWarnings("unchecked")
+    private List<PackageInfo> getInstalledPackages(IPackageManager pm, int flags)
+            throws RemoteException {
+        final List<PackageInfo> packageInfos = new ArrayList<PackageInfo>();
+        PackageInfo lastItem = null;
+        ParceledListSlice<PackageInfo> slice;
+
+        do {
+            final String lastKey = lastItem != null ? lastItem.packageName : null;
+            slice = pm.getInstalledPackages(flags, lastKey);
+            lastItem = slice.populateList(packageInfos, PackageInfo.CREATOR);
+        } while (!slice.isLastSlice());
+
+        return packageInfos;
+    }
+
     /**
      * Lists all of the features supported by the current device.
      *
diff --git a/core/java/android/accounts/AccountAuthenticatorCache.java b/core/java/android/accounts/AccountAuthenticatorCache.java
index d2b3bc7..5ee1f60 100644
--- a/core/java/android/accounts/AccountAuthenticatorCache.java
+++ b/core/java/android/accounts/AccountAuthenticatorCache.java
@@ -18,17 +18,22 @@
 
 import android.content.pm.PackageManager;
 import android.content.pm.RegisteredServicesCache;
+import android.content.pm.ResolveInfo;
 import android.content.pm.XmlSerializerAndParser;
 import android.content.res.Resources;
 import android.content.res.TypedArray;
+import android.content.ComponentName;
 import android.content.Context;
+import android.content.Intent;
 import android.util.AttributeSet;
+import android.util.Log;
 import android.text.TextUtils;
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlSerializer;
 import org.xmlpull.v1.XmlPullParserException;
 
 import java.io.IOException;
+import java.util.List;
 
 /**
  * A cache of services that export the {@link IAccountAuthenticator} interface. This cache
@@ -63,11 +68,40 @@
                     com.android.internal.R.styleable.AccountAuthenticator_smallIcon, 0);
             final int prefId = sa.getResourceId(
                     com.android.internal.R.styleable.AccountAuthenticator_accountPreferences, 0);
+            
+            boolean customTokens = false;
+            try {
+                // In HC this will be an attribute in authenticator.xml, this is a workaround
+                // using meta-data to avoid changes to the API. 
+                // If meta-data is absent the old behavior is preserved. 
+                // Authenticator will know if AccountManager supports customTokens or not.
+                PackageManager pm = mContext.getPackageManager();
+                List<ResolveInfo> resolveInfos = pm.queryIntentServices(
+                        new Intent(AccountManager.ACTION_AUTHENTICATOR_INTENT),
+                        PackageManager.GET_META_DATA);
+                for (ResolveInfo resolveInfo: resolveInfos) {
+                    android.content.pm.ServiceInfo si = resolveInfo.serviceInfo;
+                    if (!packageName.equals(si.packageName)) {
+                        continue;
+                    }
+                    Object ctString = si.metaData.get(AccountManager.ACTION_AUTHENTICATOR_INTENT 
+                            + ".customTokens");
+                    if (ctString != null) {
+                        customTokens = true;
+                    }
+                }
+            } catch (Throwable t) {
+                // Protected against invalid data in meta or unexpected 
+                // conditions - the authenticator will not have the new 
+                // features. 
+                Log.e(TAG, "Error getting customTokens metadata " + t);
+            }
+            
             if (TextUtils.isEmpty(accountType)) {
                 return null;
             }
-            return new AuthenticatorDescription(accountType, packageName, labelId, iconId, 
-                    smallIconId, prefId);
+            return new AuthenticatorDescription(accountType, packageName, labelId, iconId,
+                    smallIconId, prefId, customTokens);
         } finally {
             sa.recycle();
         }
diff --git a/core/java/android/accounts/AccountManager.java b/core/java/android/accounts/AccountManager.java
index fd3a0d0..677b959 100644
--- a/core/java/android/accounts/AccountManager.java
+++ b/core/java/android/accounts/AccountManager.java
@@ -188,6 +188,24 @@
     public static final String KEY_ERROR_CODE = "errorCode";
     public static final String KEY_ERROR_MESSAGE = "errorMessage";
     public static final String KEY_USERDATA = "userdata";
+    /**
+     * Authenticators using 'customTokens' option will also get the UID of the
+     * caller
+     * @hide
+     */
+    public static final String KEY_CALLER_UID = "callerUid";
+
+    /**
+     * @hide 
+     */
+    public static final String KEY_CALLER_PID = "callerPid";
+
+    /**
+     * Boolean, if set and 'customTokens' the authenticator is responsible for
+     * notifications.
+     * @hide
+     */
+    public static final String KEY_NOTIFY_ON_FAILURE = "notifyOnAuthFailure";
 
     public static final String ACTION_AUTHENTICATOR_INTENT =
             "android.accounts.AccountAuthenticator";
diff --git a/core/java/android/accounts/AccountManagerService.java b/core/java/android/accounts/AccountManagerService.java
index 9a8cc15..5796042 100644
--- a/core/java/android/accounts/AccountManagerService.java
+++ b/core/java/android/accounts/AccountManagerService.java
@@ -91,6 +91,8 @@
 
     private final Context mContext;
 
+    private final PackageManager mPackageManager;
+
     private HandlerThread mMessageThread;
     private final MessageHandler mMessageHandler;
 
@@ -99,7 +101,6 @@
 
     private final AccountAuthenticatorCache mAuthenticatorCache;
     private final DatabaseHelper mOpenHelper;
-    private final SimWatcher mSimWatcher;
 
     private static final String TABLE_ACCOUNTS = "accounts";
     private static final String ACCOUNTS_ID = "_id";
@@ -214,6 +215,7 @@
 
     public AccountManagerService(Context context) {
         mContext = context;
+        mPackageManager = context.getPackageManager();
 
         mOpenHelper = new DatabaseHelper(mContext);
 
@@ -224,7 +226,6 @@
         mAuthenticatorCache = new AccountAuthenticatorCache(mContext);
         mAuthenticatorCache.setListener(this, null /* Handler */);
 
-        mSimWatcher = new SimWatcher(mContext);
         sThis.set(this);
 
         validateAccounts();
@@ -520,6 +521,18 @@
         if (account == null) throw new IllegalArgumentException("account is null");
         checkManageAccountsPermission();
         long identityToken = clearCallingIdentity();
+
+        cancelNotification(getSigninRequiredNotificationId(account));
+        synchronized(mCredentialsPermissionNotificationIds) {
+            for (Pair<Pair<Account, String>, Integer> pair:
+                mCredentialsPermissionNotificationIds.keySet()) {
+                if (account.equals(pair.first.first)) {
+                    int id = mCredentialsPermissionNotificationIds.get(pair);
+                    cancelNotification(id);
+                }
+            }
+        }
+
         try {
             new RemoveAccountSession(response, account).bind();
         } finally {
@@ -842,19 +855,49 @@
 
     public void getAuthToken(IAccountManagerResponse response, final Account account,
             final String authTokenType, final boolean notifyOnAuthFailure,
-            final boolean expectActivityLaunch, final Bundle loginOptions) {
+            final boolean expectActivityLaunch, Bundle loginOptionsIn) {
+        if (Log.isLoggable(TAG, Log.VERBOSE)) {
+            Log.v(TAG, "getAuthToken: " + account
+                    + ", response " + response
+                    + ", authTokenType " + authTokenType
+                    + ", notifyOnAuthFailure " + notifyOnAuthFailure
+                    + ", expectActivityLaunch " + expectActivityLaunch
+                    + ", caller's uid " + Binder.getCallingUid()
+                    + ", pid " + Binder.getCallingPid());
+        }
         if (response == null) throw new IllegalArgumentException("response is null");
         if (account == null) throw new IllegalArgumentException("account is null");
         if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
         checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
         final int callerUid = Binder.getCallingUid();
-        final boolean permissionGranted = permissionIsGranted(account, authTokenType, callerUid);
+        final int callerPid = Binder.getCallingPid();
+
+        AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo =
+            mAuthenticatorCache.getServiceInfo(
+                    AuthenticatorDescription.newKey(account.type));
+        final boolean customTokens =
+            authenticatorInfo != null && authenticatorInfo.type.customTokens;
+
+        // skip the check if customTokens
+        final boolean permissionGranted = customTokens ||
+            permissionIsGranted(account, authTokenType, callerUid);
+
+        final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
+            loginOptionsIn;
+        if (customTokens) {
+            // let authenticator know the identity of the caller
+            loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
+            loginOptions.putInt(AccountManager.KEY_CALLER_PID, callerPid);
+            if (notifyOnAuthFailure) {
+                loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
+            }
+        }
 
         long identityToken = clearCallingIdentity();
         try {
             // if the caller has permission, do the peek. otherwise go the more expensive
             // route of starting a Session
-            if (permissionGranted) {
+            if (!customTokens && permissionGranted) {
                 String authToken = readAuthTokenFromDatabase(account, authTokenType);
                 if (authToken != null) {
                     Bundle result = new Bundle();
@@ -908,12 +951,14 @@
                                         "the type and name should not be empty");
                                 return;
                             }
-                            saveAuthTokenToDatabase(new Account(name, type),
-                                    authTokenType, authToken);
+                            if (!customTokens) {
+                                saveAuthTokenToDatabase(new Account(name, type),
+                                        authTokenType, authToken);
+                            }
                         }
 
                         Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
-                        if (intent != null && notifyOnAuthFailure) {
+                        if (intent != null && notifyOnAuthFailure && !customTokens) {
                             doNotification(
                                     account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
                                     intent);
@@ -972,6 +1017,10 @@
             AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
 
         Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
+        // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
+        // Since it was set in Eclair+ we can't change it without breaking apps using
+        // the intent from a non-Activity context.
+        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         intent.addCategory(
                 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
 
@@ -1640,95 +1689,6 @@
         }
     }
 
-    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.
-            TelephonyManager telephonyManager =
-                (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
-            if (telephonyManager == null) {
-                Log.w(TAG, "failed to get TelephonyManager");
-                return;
-            }
-            String imsi = telephonyManager.getSubscriberId();
-
-            // If the subscriber ID is an empty string, don't do anything.
-            if (TextUtils.isEmpty(imsi)) return;
-
-            // If the current IMSI matches what's stored, don't do anything.
-            String storedImsi = getMetaValue("imsi");
-            if (Log.isLoggable(TAG, Log.VERBOSE)) {
-                Log.v(TAG, "current IMSI=" + imsi + "; stored IMSI=" + storedImsi);
-            }
-            if (imsi.equals(storedImsi)) return;
-
-            // If a CDMA phone is unprovisioned, getSubscriberId()
-            // will return a different value, but we *don't* erase the
-            // passwords.  We only erase them if it has a different
-            // subscriber ID once it's provisioned.
-            if (telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
-                IBinder service = ServiceManager.checkService(Context.TELEPHONY_SERVICE);
-                if (service == null) {
-                    Log.w(TAG, "call to checkService(TELEPHONY_SERVICE) failed");
-                    return;
-                }
-                ITelephony telephony = ITelephony.Stub.asInterface(service);
-                if (telephony == null) {
-                    Log.w(TAG, "failed to get ITelephony interface");
-                    return;
-                }
-                boolean needsProvisioning;
-                try {
-                    needsProvisioning = telephony.getCdmaNeedsProvisioning();
-                } catch (RemoteException e) {
-                    Log.w(TAG, "exception while checking provisioning", e);
-                    // default to NOT wiping out the passwords
-                    needsProvisioning = true;
-                }
-                if (needsProvisioning) {
-                    // if the phone needs re-provisioning, don't do anything.
-                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
-                        Log.v(TAG, "current IMSI=" + imsi + " (needs provisioning); stored IMSI=" +
-                              storedImsi);
-                    }
-                    return;
-                }
-            }
-
-            if (!imsi.equals(storedImsi) && !TextUtils.isEmpty(storedImsi)) {
-                Log.w(TAG, "wiping all passwords and authtokens because IMSI changed ("
-                        + "stored=" + storedImsi + ", current=" + imsi + ")");
-                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();
     }
@@ -1849,12 +1809,12 @@
     }
 
     private boolean inSystemImage(int callerUid) {
-        String[] packages = mContext.getPackageManager().getPackagesForUid(callerUid);
+        String[] packages = mPackageManager.getPackagesForUid(callerUid);
         for (String name : packages) {
             try {
-                PackageInfo packageInfo =
-                        mContext.getPackageManager().getPackageInfo(name, 0 /* flags */);
-                if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
+                PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
+                if (packageInfo != null
+                        && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                     return true;
                 }
             } catch (PackageManager.NameNotFoundException e) {
@@ -1872,7 +1832,7 @@
                 && hasExplicitlyGrantedPermission(account, authTokenType);
         if (Log.isLoggable(TAG, Log.VERBOSE)) {
             Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
-                    + callerUid + ", account " + account
+                    + callerUid + ", " + account
                     + ": is authenticator? " + fromAuthenticator
                     + ", has explicit permission? " + hasExplicitGrants);
         }
@@ -1884,7 +1844,7 @@
                 mAuthenticatorCache.getAllServices()) {
             if (serviceInfo.type.type.equals(accountType)) {
                 return (serviceInfo.uid == callingUid) ||
-                        (mContext.getPackageManager().checkSignatures(serviceInfo.uid, callingUid)
+                        (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
                                 == PackageManager.SIGNATURE_MATCH);
             }
         }
diff --git a/core/java/android/accounts/AuthenticatorDescription.java b/core/java/android/accounts/AuthenticatorDescription.java
index c6515672..4d3769a 100644
--- a/core/java/android/accounts/AuthenticatorDescription.java
+++ b/core/java/android/accounts/AuthenticatorDescription.java
@@ -44,9 +44,16 @@
     /** The package name that can be used to lookup the resources from above. */
     final public String packageName;
 
-    /** A constructor for a full AuthenticatorDescription */
+    /** Authenticator handles its own token caching and permission screen 
+      * @hide
+      */
+    final public boolean customTokens;
+
+    /** A constructor for a full AuthenticatorDescription
+     *  @hide 
+     */
     public AuthenticatorDescription(String type, String packageName, int labelId, int iconId,
-            int smallIconId, int prefId) {
+            int smallIconId, int prefId, boolean customTokens) {
         if (type == null) throw new IllegalArgumentException("type cannot be null");
         if (packageName == null) throw new IllegalArgumentException("packageName cannot be null");
         this.type = type;
@@ -55,6 +62,12 @@
         this.iconId = iconId;
         this.smallIconId = smallIconId;
         this.accountPreferencesId = prefId;
+        this.customTokens = customTokens;
+    }
+
+    public AuthenticatorDescription(String type, String packageName, int labelId, int iconId,
+            int smallIconId, int prefId) {
+        this(type, packageName, labelId, iconId, smallIconId, prefId, false);
     }
 
     /**
@@ -74,6 +87,7 @@
         this.iconId = 0;
         this.smallIconId = 0;
         this.accountPreferencesId = 0;
+        this.customTokens = false;
     }
 
     private AuthenticatorDescription(Parcel source) {
@@ -83,6 +97,7 @@
         this.iconId = source.readInt();
         this.smallIconId = source.readInt();
         this.accountPreferencesId = source.readInt();
+        this.customTokens = source.readByte() == 1;
     }
 
     /** @inheritDoc */
@@ -115,6 +130,7 @@
         dest.writeInt(iconId);
         dest.writeInt(smallIconId);
         dest.writeInt(accountPreferencesId);
+        dest.writeByte((byte) (customTokens ? 1 : 0));
     }
 
     /** Used to create the object from a parcel. */
diff --git a/core/java/android/app/ContextImpl.java b/core/java/android/app/ContextImpl.java
index f535d61..fe4bfcf 100644
--- a/core/java/android/app/ContextImpl.java
+++ b/core/java/android/app/ContextImpl.java
@@ -48,6 +48,7 @@
 import android.content.pm.InstrumentationInfo;
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
+import android.content.pm.ParceledListSlice;
 import android.content.pm.PermissionGroupInfo;
 import android.content.pm.PermissionInfo;
 import android.content.pm.ProviderInfo;
@@ -61,6 +62,8 @@
 import android.graphics.Bitmap;
 import android.graphics.drawable.Drawable;
 import android.hardware.SensorManager;
+import android.hardware.usb.IUsbManager;
+import android.hardware.usb.UsbManager;
 import android.location.ILocationManager;
 import android.location.LocationManager;
 import android.media.AudioManager;
@@ -81,6 +84,7 @@
 import android.os.IBinder;
 import android.os.IPowerManager;
 import android.os.Looper;
+import android.os.Parcel;
 import android.os.PowerManager;
 import android.os.Process;
 import android.os.RemoteException;
@@ -188,6 +192,7 @@
     private SearchManager mSearchManager = null;
     private SensorManager mSensorManager = null;
     private StorageManager mStorageManager = null;
+    private UsbManager mUsbManager = null;
     private Vibrator mVibrator = null;
     private LayoutInflater mLayoutInflater = null;
     private StatusBarManager mStatusBarManager = null;
@@ -951,6 +956,8 @@
             return getSensorManager();
         } else if (STORAGE_SERVICE.equals(name)) {
             return getStorageManager();
+        } else if (USB_SERVICE.equals(name)) {
+            return getUsbManager();
         } else if (VIBRATOR_SERVICE.equals(name)) {
             return getVibrator();
         } else if (STATUS_BAR_SERVICE.equals(name)) {
@@ -1145,6 +1152,17 @@
         return mStorageManager;
     }
 
+    private UsbManager getUsbManager() {
+        synchronized (mSync) {
+            if (mUsbManager == null) {
+                IBinder b = ServiceManager.getService(USB_SERVICE);
+                IUsbManager service = IUsbManager.Stub.asInterface(b);
+                mUsbManager = new UsbManager(this, service);
+            }
+        }
+        return mUsbManager;
+    }
+
     private Vibrator getVibrator() {
         synchronized (mSync) {
             if (mVibrator == null) {
@@ -1982,19 +2000,41 @@
             throw new NameNotFoundException("No shared userid for user:"+sharedUserName);
         }
 
+        @SuppressWarnings("unchecked")
         @Override
         public List<PackageInfo> getInstalledPackages(int flags) {
             try {
-                return mPM.getInstalledPackages(flags);
+                final List<PackageInfo> packageInfos = new ArrayList<PackageInfo>();
+                PackageInfo lastItem = null;
+                ParceledListSlice<PackageInfo> slice;
+
+                do {
+                    final String lastKey = lastItem != null ? lastItem.packageName : null;
+                    slice = mPM.getInstalledPackages(flags, lastKey);
+                    lastItem = slice.populateList(packageInfos, PackageInfo.CREATOR);
+                } while (!slice.isLastSlice());
+
+                return packageInfos;
             } catch (RemoteException e) {
                 throw new RuntimeException("Package manager has died", e);
             }
         }
 
+        @SuppressWarnings("unchecked")
         @Override
         public List<ApplicationInfo> getInstalledApplications(int flags) {
             try {
-                return mPM.getInstalledApplications(flags);
+                final List<ApplicationInfo> applicationInfos = new ArrayList<ApplicationInfo>();
+                ApplicationInfo lastItem = null;
+                ParceledListSlice<ApplicationInfo> slice;
+
+                do {
+                    final String lastKey = lastItem != null ? lastItem.packageName : null;
+                    slice = mPM.getInstalledApplications(flags, lastKey);
+                    lastItem = slice.populateList(applicationInfos, ApplicationInfo.CREATOR);
+                } while (!slice.isLastSlice());
+
+                return applicationInfos;
             } catch (RemoteException e) {
                 throw new RuntimeException("Package manager has died", e);
             }
diff --git a/core/java/android/app/Dialog.java b/core/java/android/app/Dialog.java
index da8c9e5..d70ec0b 100644
--- a/core/java/android/app/Dialog.java
+++ b/core/java/android/app/Dialog.java
@@ -823,7 +823,7 @@
 
         // associate search with owner activity
         final ComponentName appName = getAssociatedActivity();
-        if (appName != null) {
+        if (appName != null && searchManager.getSearchableInfo(appName) != null) {
             searchManager.startSearch(null, false, appName, null, false);
             dismiss();
             return true;
diff --git a/core/java/android/bluetooth/BluetoothA2dp.java b/core/java/android/bluetooth/BluetoothA2dp.java
index 7e5f858..8218c03 100644
--- a/core/java/android/bluetooth/BluetoothA2dp.java
+++ b/core/java/android/bluetooth/BluetoothA2dp.java
@@ -269,6 +269,22 @@
         }
     }
 
+    /**
+     * Allow or disallow incoming connection
+     * @param device Sink
+     * @param value True / False
+     * @return Success or Failure of the binder call.
+     */
+    public boolean allowIncomingConnect(BluetoothDevice device, boolean value) {
+        if (DBG) log("allowIncomingConnect(" + device + ":" + value + ")");
+        try {
+            return mService.allowIncomingConnect(device, value);
+        } catch (RemoteException e) {
+            Log.e(TAG, "", e);
+            return false;
+        }
+    }
+
     /** Helper for converting a state to a string.
      * For debug use only - strings are not internationalized.
      * @hide
diff --git a/core/java/android/bluetooth/BluetoothAdapter.java b/core/java/android/bluetooth/BluetoothAdapter.java
index a7175e3..5eafc09 100644
--- a/core/java/android/bluetooth/BluetoothAdapter.java
+++ b/core/java/android/bluetooth/BluetoothAdapter.java
@@ -628,7 +628,7 @@
     public boolean cancelDiscovery() {
         if (getState() != STATE_ON) return false;
         try {
-            mService.cancelDiscovery();
+            return mService.cancelDiscovery();
         } catch (RemoteException e) {Log.e(TAG, "", e);}
         return false;
     }
@@ -799,10 +799,10 @@
 
     /**
      * Create a listening, insecure RFCOMM Bluetooth socket with Service Record.
-     * <p>The link key will be unauthenticated i.e the communication is
+     * <p>The link key is not required to be authenticated, i.e the communication may be
      * vulnerable to Man In the Middle attacks. For Bluetooth 2.1 devices,
-     * the link key will be encrypted, as encryption is mandartory.
-     * For legacy devices (pre Bluetooth 2.1 devices) the link key will not
+     * the link will be encrypted, as encryption is mandartory.
+     * For legacy devices (pre Bluetooth 2.1 devices) the link will not
      * be encrypted. Use {@link #listenUsingRfcommWithServiceRecord}, if an
      * encrypted and authenticated communication channel is desired.
      * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
@@ -828,6 +828,44 @@
         return createNewRfcommSocketAndRecord(name, uuid, false, false);
     }
 
+     /**
+     * Create a listening, encrypted,
+     * RFCOMM Bluetooth socket with Service Record.
+     * <p>The link will be encrypted, but the link key is not required to be authenticated
+     * i.e the communication is vulnerable to Man In the Middle attacks. Use
+     * {@link #listenUsingRfcommWithServiceRecord}, to ensure an authenticated link key.
+     * <p> Use this socket if authentication of link key is not possible.
+     * For example, for Bluetooth 2.1 devices, if any of the devices does not have
+     * an input and output capability or just has the ability to display a numeric key,
+     * a secure socket connection is not possible and this socket can be used.
+     * Use {@link #listenUsingInsecureRfcommWithServiceRecord}, if encryption is not required.
+     * For Bluetooth 2.1 devices, the link will be encrypted, as encryption is mandartory.
+     * For more details, refer to the Security Model section 5.2 (vol 3) of
+     * Bluetooth Core Specification version 2.1 + EDR.
+     * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
+     * connections from a listening {@link BluetoothServerSocket}.
+     * <p>The system will assign an unused RFCOMM channel to listen on.
+     * <p>The system will also register a Service Discovery
+     * Protocol (SDP) record with the local SDP server containing the specified
+     * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
+     * can use the same UUID to query our SDP server and discover which channel
+     * to connect to. This SDP record will be removed when this socket is
+     * closed, or if this application closes unexpectedly.
+     * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
+     * connect to this socket from another device using the same {@link UUID}.
+     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
+     * @param name service name for SDP record
+     * @param uuid uuid for SDP record
+     * @return a listening RFCOMM BluetoothServerSocket
+     * @throws IOException on error, for example Bluetooth not available, or
+     *                     insufficient permissions, or channel in use.
+     * @hide
+     */
+    public BluetoothServerSocket listenUsingEncryptedRfcommWithServiceRecord(
+            String name, UUID uuid) throws IOException {
+        return createNewRfcommSocketAndRecord(name, uuid, false, true);
+    }
+
     private BluetoothServerSocket createNewRfcommSocketAndRecord(String name, UUID uuid,
             boolean auth, boolean encrypt) throws IOException {
         RfcommChannelPicker picker = new RfcommChannelPicker(uuid);
@@ -898,6 +936,28 @@
         return socket;
     }
 
+     /**
+     * Construct an encrypted, 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.
+     * @hide
+     */
+    public BluetoothServerSocket listenUsingEncryptedRfcommOn(int port)
+            throws IOException {
+        BluetoothServerSocket socket = new BluetoothServerSocket(
+                BluetoothSocket.TYPE_RFCOMM, false, true, port);
+        int errno = socket.mSocket.bindListen();
+        if (errno != 0) {
+            try {
+                socket.close();
+            } catch (IOException e) {}
+            socket.mSocket.throwErrnoNative(errno);
+        }
+        return socket;
+    }
+
     /**
      * Construct a SCO server socket.
      * Call #accept to retrieve connections to this socket.
diff --git a/core/java/android/bluetooth/BluetoothDevice.java b/core/java/android/bluetooth/BluetoothDevice.java
index aee6ad8..e67ace0 100644
--- a/core/java/android/bluetooth/BluetoothDevice.java
+++ b/core/java/android/bluetooth/BluetoothDevice.java
@@ -276,6 +276,33 @@
     public static final String ACTION_PAIRING_CANCEL =
             "android.bluetooth.device.action.PAIRING_CANCEL";
 
+    /** @hide */
+    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
+    public static final String ACTION_CONNECTION_ACCESS_REQUEST =
+            "android.bluetooth.device.action.CONNECTION_ACCESS_REQUEST";
+
+    /** @hide */
+    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
+    public static final String ACTION_CONNECTION_ACCESS_REPLY =
+            "android.bluetooth.device.action.CONNECTION_ACCESS_REPLY";
+
+    /** @hide */
+    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
+    public static final String ACTION_CONNECTION_ACCESS_CANCEL =
+            "android.bluetooth.device.action.CONNECTION_ACCESS_CANCEL";
+    /**
+     * Used as an extra field in {@link #ACTION_CONNECTION_ACCESS_REPLY} intent.
+     * @hide
+     */
+    public static final String EXTRA_CONNECTION_ACCESS_RESULT =
+        "android.bluetooth.device.extra.CONNECTION_ACCESS_RESULT";
+
+    /**@hide*/
+    public static final int CONNECTION_ACCESS_YES = 1;
+
+    /**@hide*/
+    public static final int CONNECTION_ACCESS_NO = 2;
+
     /** A bond attempt succeeded
      * @hide */
     public static final int BOND_SUCCESS = 0;
diff --git a/core/java/android/bluetooth/BluetoothDeviceProfileState.java b/core/java/android/bluetooth/BluetoothDeviceProfileState.java
index 9d7e641..8896451 100644
--- a/core/java/android/bluetooth/BluetoothDeviceProfileState.java
+++ b/core/java/android/bluetooth/BluetoothDeviceProfileState.java
@@ -21,9 +21,11 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.os.Message;
+import android.os.PowerManager;
 import android.server.BluetoothA2dpService;
 import android.server.BluetoothService;
 import android.util.Log;
+import android.util.Pair;
 
 import com.android.internal.util.HierarchicalState;
 import com.android.internal.util.HierarchicalStateMachine;
@@ -73,9 +75,17 @@
     public static final int AUTO_CONNECT_PROFILES = 101;
     public static final int TRANSITION_TO_STABLE = 102;
     public static final int CONNECT_OTHER_PROFILES = 103;
+    private static final int CONNECTION_ACCESS_REQUEST_REPLY = 104;
+    private static final int CONNECTION_ACCESS_REQUEST_EXPIRY = 105;
 
     private static final int AUTO_CONNECT_DELAY = 6000; // 6 secs
     private static final int CONNECT_OTHER_PROFILES_DELAY = 4000; // 4 secs
+    private static final int CONNECTION_ACCESS_REQUEST_EXPIRY_TIMEOUT = 7000; // 7 secs
+    private static final int CONNECTION_ACCESS_UNDEFINED = -1;
+    private static final long INIT_INCOMING_REJECT_TIMER = 1000; // 1 sec
+    private static final long MAX_INCOMING_REJECT_TIMER = 3600 * 1000 * 4; // 4 hours
+
+    private static final String PREFS_NAME = "ConnectionAccess";
 
     private BondedDevice mBondedDevice = new BondedDevice();
     private OutgoingHandsfree mOutgoingHandsfree = new OutgoingHandsfree();
@@ -90,10 +100,16 @@
     private BluetoothPbap     mPbapService;
     private boolean mHeadsetServiceConnected;
     private boolean mPbapServiceConnected;
+    private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
 
     private BluetoothDevice mDevice;
     private int mHeadsetState;
     private int mA2dpState;
+    private long mIncomingRejectTimer;
+    private boolean mConnectionAccessReplyReceived = false;
+    private Pair<Integer, String> mIncomingConnections;
+    private PowerManager.WakeLock mWakeLock;
+    private PowerManager mPowerManager;
 
     private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
         @Override
@@ -108,6 +124,10 @@
                 int initiator = intent.getIntExtra(
                     BluetoothHeadset.EXTRA_DISCONNECT_INITIATOR,
                     BluetoothHeadset.LOCAL_DISCONNECT);
+                // We trust this device now
+                if (newState == BluetoothHeadset.STATE_CONNECTED) {
+                    setTrust(BluetoothDevice.CONNECTION_ACCESS_YES);
+                }
                 mHeadsetState = newState;
                 if (newState == BluetoothHeadset.STATE_DISCONNECTED &&
                     initiator == BluetoothHeadset.REMOTE_DISCONNECT) {
@@ -121,6 +141,10 @@
                 int newState = intent.getIntExtra(BluetoothA2dp.EXTRA_SINK_STATE, 0);
                 int oldState = intent.getIntExtra(BluetoothA2dp.EXTRA_PREVIOUS_SINK_STATE, 0);
                 mA2dpState = newState;
+                // We trust this device now
+                if (newState == BluetoothA2dp.STATE_CONNECTED) {
+                    setTrust(BluetoothDevice.CONNECTION_ACCESS_YES);
+                }
                 if ((oldState == BluetoothA2dp.STATE_CONNECTED ||
                            oldState == BluetoothA2dp.STATE_PLAYING) &&
                            newState == BluetoothA2dp.STATE_DISCONNECTED) {
@@ -134,6 +158,13 @@
                 // This is technically not needed, but we can get stuck sometimes.
                 // For example, if incoming A2DP fails, we are not informed by Bluez
                 sendMessage(TRANSITION_TO_STABLE);
+            } else if (action.equals(BluetoothDevice.ACTION_CONNECTION_ACCESS_REPLY)) {
+                mWakeLock.release();
+                int val = intent.getIntExtra(BluetoothDevice.EXTRA_CONNECTION_ACCESS_RESULT,
+                                             BluetoothDevice.CONNECTION_ACCESS_NO);
+                Message msg = obtainMessage(CONNECTION_ACCESS_REQUEST_REPLY);
+                msg.arg1 = val;
+                sendMessage(msg);
             }
       }
     };
@@ -174,11 +205,20 @@
         filter.addAction(BluetoothHeadset.ACTION_STATE_CHANGED);
         filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
         filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
+        filter.addAction(BluetoothDevice.ACTION_CONNECTION_ACCESS_REPLY);
 
         mContext.registerReceiver(mBroadcastReceiver, filter);
 
         HeadsetServiceListener l = new HeadsetServiceListener();
         PbapServiceListener p = new PbapServiceListener();
+
+        mIncomingConnections = mService.getIncomingState(address);
+        mIncomingRejectTimer = readTimerValue();
+        mPowerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
+        mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK |
+                                              PowerManager.ACQUIRE_CAUSES_WAKEUP |
+                                              PowerManager.ON_AFTER_RELEASE, TAG);
+        mWakeLock.setReferenceCounted(false);
     }
 
     private class HeadsetServiceListener implements BluetoothHeadset.ServiceListener {
@@ -438,6 +478,24 @@
                     // Ignore
                     Log.e(TAG, "Error: Incoming connection with a pending incoming connection");
                     break;
+                case CONNECTION_ACCESS_REQUEST_REPLY:
+                    int val = message.arg1;
+                    mConnectionAccessReplyReceived = true;
+                    boolean value = false;
+                    if (val == BluetoothDevice.CONNECTION_ACCESS_YES) {
+                        value = true;
+                    }
+                    setTrust(val);
+
+                    handleIncomingConnection(CONNECT_HFP_INCOMING, value);
+                    break;
+                case CONNECTION_ACCESS_REQUEST_EXPIRY:
+                    if (!mConnectionAccessReplyReceived) {
+                        handleIncomingConnection(CONNECT_HFP_INCOMING, false);
+                        sendConnectionAccessRemovalIntent();
+                        sendMessage(TRANSITION_TO_STABLE);
+                    }
+                    break;
                 case CONNECT_A2DP_INCOMING:
                     // Serialize the commands.
                     deferMessage(message);
@@ -607,6 +665,25 @@
                 case CONNECT_A2DP_INCOMING:
                     // ignore
                     break;
+                case CONNECTION_ACCESS_REQUEST_REPLY:
+                    int val = message.arg1;
+                    mConnectionAccessReplyReceived = true;
+                    boolean value = false;
+                    if (val == BluetoothDevice.CONNECTION_ACCESS_YES) {
+                        value = true;
+                    }
+                    setTrust(val);
+                    handleIncomingConnection(CONNECT_A2DP_INCOMING, value);
+                    break;
+                case CONNECTION_ACCESS_REQUEST_EXPIRY:
+                    // The check protects the race condition between REQUEST_REPLY
+                    // and the timer expiry.
+                    if (!mConnectionAccessReplyReceived) {
+                        handleIncomingConnection(CONNECT_A2DP_INCOMING, false);
+                        sendConnectionAccessRemovalIntent();
+                        sendMessage(TRANSITION_TO_STABLE);
+                    }
+                    break;
                 case CONNECT_A2DP_OUTGOING:
                     // Defer message and retry
                     deferMessage(message);
@@ -662,8 +739,138 @@
         deferMessage(msg);
     }
 
+    private void updateIncomingAllowedTimer() {
+        // Not doing a perfect exponential backoff because
+        // we want two different rates. For all practical
+        // purposes, this is good enough.
+        if (mIncomingRejectTimer == 0) mIncomingRejectTimer = INIT_INCOMING_REJECT_TIMER;
+
+        mIncomingRejectTimer *= 5;
+        if (mIncomingRejectTimer > MAX_INCOMING_REJECT_TIMER) {
+            mIncomingRejectTimer = MAX_INCOMING_REJECT_TIMER;
+        }
+        writeTimerValue(mIncomingRejectTimer);
+    }
+
+    private boolean handleIncomingConnection(int command, boolean accept) {
+        boolean ret = false;
+        Log.i(TAG, "handleIncomingConnection:" + command + ":" + accept);
+        switch (command) {
+            case CONNECT_HFP_INCOMING:
+                if (!accept) {
+                    ret = mHeadsetService.rejectIncomingConnect(mDevice);
+                    sendMessage(TRANSITION_TO_STABLE);
+                    updateIncomingAllowedTimer();
+                } else if (mHeadsetState == BluetoothHeadset.STATE_CONNECTING) {
+                    writeTimerValue(0);
+                    ret =  mHeadsetService.acceptIncomingConnect(mDevice);
+                } else if (mHeadsetState == BluetoothHeadset.STATE_DISCONNECTED) {
+                    writeTimerValue(0);
+                    handleConnectionOfOtherProfiles(command);
+                    ret = mHeadsetService.createIncomingConnect(mDevice);
+                }
+                break;
+            case CONNECT_A2DP_INCOMING:
+                if (!accept) {
+                    ret = mA2dpService.allowIncomingConnect(mDevice, false);
+                    sendMessage(TRANSITION_TO_STABLE);
+                    updateIncomingAllowedTimer();
+                } else {
+                    writeTimerValue(0);
+                    ret = mA2dpService.allowIncomingConnect(mDevice, true);
+                    handleConnectionOfOtherProfiles(command);
+                }
+                break;
+            default:
+                Log.e(TAG, "Waiting for incoming connection but state changed to:" + command);
+                break;
+       }
+       return ret;
+    }
+
+    private void sendConnectionAccessIntent() {
+        mConnectionAccessReplyReceived = false;
+
+        if (!mPowerManager.isScreenOn()) mWakeLock.acquire();
+
+        Intent intent = new Intent(BluetoothDevice.ACTION_CONNECTION_ACCESS_REQUEST);
+        intent.putExtra(BluetoothDevice.EXTRA_DEVICE, mDevice);
+        mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM);
+    }
+
+    private void sendConnectionAccessRemovalIntent() {
+        mWakeLock.release();
+        Intent intent = new Intent(BluetoothDevice.ACTION_CONNECTION_ACCESS_CANCEL);
+        intent.putExtra(BluetoothDevice.EXTRA_DEVICE, mDevice);
+        mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM);
+    }
+
+    private int getTrust() {
+        String address = mDevice.getAddress();
+        if (mIncomingConnections != null) return mIncomingConnections.first;
+        return CONNECTION_ACCESS_UNDEFINED;
+    }
+
+
+    private String getStringValue(long value) {
+        StringBuilder sbr = new StringBuilder();
+        sbr.append(Long.toString(System.currentTimeMillis()));
+        sbr.append("-");
+        sbr.append(Long.toString(value));
+        return sbr.toString();
+    }
+
+    private void setTrust(int value) {
+        String second;
+        if (mIncomingConnections == null) {
+            second = getStringValue(INIT_INCOMING_REJECT_TIMER);
+        } else {
+            second = mIncomingConnections.second;
+        }
+
+        mIncomingConnections = new Pair(value, second);
+        mService.writeIncomingConnectionState(mDevice.getAddress(), mIncomingConnections);
+    }
+
+    private void writeTimerValue(long value) {
+        Integer first;
+        if (mIncomingConnections == null) {
+            first = CONNECTION_ACCESS_UNDEFINED;
+        } else {
+            first = mIncomingConnections.first;
+        }
+        mIncomingConnections = new Pair(first, getStringValue(value));
+        mService.writeIncomingConnectionState(mDevice.getAddress(), mIncomingConnections);
+    }
+
+    private long readTimerValue() {
+        if (mIncomingConnections == null)
+            return 0;
+        String value = mIncomingConnections.second;
+        String[] splits = value.split("-");
+        if (splits != null && splits.length == 2) {
+            return Long.parseLong(splits[1]);
+        }
+        return 0;
+    }
+
+    private boolean readIncomingAllowedValue() {
+        if (readTimerValue() == 0) return true;
+        String value = mIncomingConnections.second;
+        String[] splits = value.split("-");
+        if (splits != null && splits.length == 2) {
+            long val1 = Long.parseLong(splits[0]);
+            long val2 = Long.parseLong(splits[1]);
+            if (val1 + val2 <= System.currentTimeMillis()) {
+                return true;
+            }
+        }
+        return false;
+    }
+
     synchronized boolean processCommand(int command) {
-        Log.i(TAG, "Processing command:" + command);
+        Log.e(TAG, "Processing command:" + command);
+        Message msg;
         switch(command) {
             case  CONNECT_HFP_OUTGOING:
                 if (mHeadsetService != null) {
@@ -673,11 +880,21 @@
             case CONNECT_HFP_INCOMING:
                 if (!mHeadsetServiceConnected) {
                     deferProfileServiceMessage(command);
-                } else if (mHeadsetState == BluetoothHeadset.STATE_CONNECTING) {
-                    return mHeadsetService.acceptIncomingConnect(mDevice);
-                } else if (mHeadsetState == BluetoothHeadset.STATE_DISCONNECTED) {
-                    handleConnectionOfOtherProfiles(command);
-                    return mHeadsetService.createIncomingConnect(mDevice);
+                } else {
+                    // Check if device is already trusted
+                    int access = getTrust();
+                    if (access == BluetoothDevice.CONNECTION_ACCESS_YES) {
+                        handleIncomingConnection(command, true);
+                    } else if (access == BluetoothDevice.CONNECTION_ACCESS_NO &&
+                               !readIncomingAllowedValue()) {
+                        handleIncomingConnection(command, false);
+                    } else {
+                        sendConnectionAccessIntent();
+                        msg = obtainMessage(CONNECTION_ACCESS_REQUEST_EXPIRY);
+                        sendMessageDelayed(msg,
+                                CONNECTION_ACCESS_REQUEST_EXPIRY_TIMEOUT);
+                    }
+                    return true;
                 }
                 break;
             case CONNECT_A2DP_OUTGOING:
@@ -686,8 +903,19 @@
                 }
                 break;
             case CONNECT_A2DP_INCOMING:
-                handleConnectionOfOtherProfiles(command);
-                // ignore, Bluez takes care
+                // Check if device is already trusted
+                int access = getTrust();
+                if (access == BluetoothDevice.CONNECTION_ACCESS_YES) {
+                    handleIncomingConnection(command, true);
+                } else if (access == BluetoothDevice.CONNECTION_ACCESS_NO &&
+                           !readIncomingAllowedValue()) {
+                    handleIncomingConnection(command, false);
+                } else {
+                    sendConnectionAccessIntent();
+                    msg = obtainMessage(CONNECTION_ACCESS_REQUEST_EXPIRY);
+                    sendMessageDelayed(msg,
+                            CONNECTION_ACCESS_REQUEST_EXPIRY_TIMEOUT);
+                }
                 return true;
             case DISCONNECT_HFP_OUTGOING:
                 if (!mHeadsetServiceConnected) {
@@ -728,6 +956,8 @@
                 }
                 break;
             case UNPAIR:
+                writeTimerValue(INIT_INCOMING_REJECT_TIMER);
+                setTrust(CONNECTION_ACCESS_UNDEFINED);
                 return mService.removeBondInternal(mDevice.getAddress());
             default:
                 Log.e(TAG, "Error: Unknown Command");
diff --git a/core/java/android/bluetooth/BluetoothHeadset.java b/core/java/android/bluetooth/BluetoothHeadset.java
index da1aa45..f64f826 100644
--- a/core/java/android/bluetooth/BluetoothHeadset.java
+++ b/core/java/android/bluetooth/BluetoothHeadset.java
@@ -494,6 +494,23 @@
     }
 
     /**
+     * Reject the incoming connection.
+     * @hide
+     */
+    public boolean rejectIncomingConnect(BluetoothDevice device) {
+        if (DBG) log("rejectIncomingConnect");
+        if (mService != null) {
+            try {
+                return mService.rejectIncomingConnect(device);
+            } catch (RemoteException e) {Log.e(TAG, e.toString());}
+        } else {
+            Log.w(TAG, "Proxy not attached to service");
+            if (DBG) Log.d(TAG, Log.getStackTraceString(new Throwable()));
+        }
+        return false;
+    }
+
+    /**
      * Connect to a Bluetooth Headset.
      * Note: This is an internal function and shouldn't be exposed
      * @hide
diff --git a/core/java/android/bluetooth/IBluetoothA2dp.aidl b/core/java/android/bluetooth/IBluetoothA2dp.aidl
index 40f1058..0c2cf1b 100644
--- a/core/java/android/bluetooth/IBluetoothA2dp.aidl
+++ b/core/java/android/bluetooth/IBluetoothA2dp.aidl
@@ -36,4 +36,6 @@
 
     boolean connectSinkInternal(in BluetoothDevice device);
     boolean disconnectSinkInternal(in BluetoothDevice device);
+    boolean allowIncomingConnect(in BluetoothDevice device, boolean value);
+
 }
diff --git a/core/java/android/bluetooth/IBluetoothHeadset.aidl b/core/java/android/bluetooth/IBluetoothHeadset.aidl
index d96f0ca..62bceee 100644
--- a/core/java/android/bluetooth/IBluetoothHeadset.aidl
+++ b/core/java/android/bluetooth/IBluetoothHeadset.aidl
@@ -37,6 +37,7 @@
 
     boolean createIncomingConnect(in BluetoothDevice device);
     boolean acceptIncomingConnect(in BluetoothDevice device);
+    boolean rejectIncomingConnect(in BluetoothDevice device);
     boolean cancelConnectThread();
     boolean connectHeadsetInternal(in BluetoothDevice device);
     boolean disconnectHeadsetInternal(in BluetoothDevice device);
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index 85c29b8..ec2d640 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -1567,6 +1567,17 @@
     public static final String SIP_SERVICE = "sip";
 
     /**
+     * Use with {@link #getSystemService} to retrieve a {@link
+     * android.hardware.usb.UsbManager} for access to USB devices (as a USB host)
+     * and for controlling this device's behavior as a USB device.
+     *
+     * @see #getSystemService
+     * @see android.harware.usb.UsbManager
+     * @hide
+     */
+    public static final String USB_SERVICE = "usb";
+
+    /**
      * Determine whether the given permission is allowed for a particular
      * process and user ID running in the system.
      *
diff --git a/core/java/android/content/SyncManager.java b/core/java/android/content/SyncManager.java
index 26b6ad7..5a83604 100644
--- a/core/java/android/content/SyncManager.java
+++ b/core/java/android/content/SyncManager.java
@@ -258,6 +258,7 @@
             // DISCONNECTED for GPRS in any order.  if we receive the CONNECTED first, and then
             // a DISCONNECTED, we want to make sure we set mDataConnectionIsConnected to true
             // since we still have a WiFi connection.
+            final boolean wasConnected = mDataConnectionIsConnected;
             switch (state) {
                 case CONNECTED:
                     mDataConnectionIsConnected = true;
@@ -273,6 +274,12 @@
                     // ignore the rest of the states -- leave our boolean alone.
             }
             if (mDataConnectionIsConnected) {
+                if (!wasConnected) {
+                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                        Log.v(TAG, "Reconnection detected: clearing all backoffs");
+                    }
+                    mSyncStorageEngine.clearAllBackoffs();
+                }
                 sendCheckAlarmsMessage();
             }
         }
diff --git a/core/java/android/content/SyncStorageEngine.java b/core/java/android/content/SyncStorageEngine.java
index e1a9dbb..faf1365 100644
--- a/core/java/android/content/SyncStorageEngine.java
+++ b/core/java/android/content/SyncStorageEngine.java
@@ -525,6 +525,32 @@
         }
     }
 
+    public void clearAllBackoffs() {
+        boolean changed = false;
+        synchronized (mAuthorities) {
+            for (AccountInfo accountInfo : mAccounts.values()) {
+                for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
+                    if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
+                            || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
+                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                            Log.v(TAG, "clearAllBackoffs:"
+                                    + " authority:" + authorityInfo.authority
+                                    + " account:" + accountInfo.account.name
+                                    + " backoffTime was: " + authorityInfo.backoffTime
+                                    + " backoffDelay was: " + authorityInfo.backoffDelay);
+                        }
+                        authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
+                        authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
+                        changed = true;
+                    }
+                }
+            }
+        }
+
+        if (changed) {
+            reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
+        }
+    }
     public void setDelayUntilTime(Account account, String providerName, long delayUntil) {
         if (Log.isLoggable(TAG, Log.VERBOSE)) {
             Log.v(TAG, "setDelayUntil: " + account + ", provider " + providerName
diff --git a/core/java/android/content/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl
index bfc9185..5df5eba 100644
--- a/core/java/android/content/pm/IPackageManager.aidl
+++ b/core/java/android/content/pm/IPackageManager.aidl
@@ -30,6 +30,7 @@
 import android.content.pm.IPackageStatsObserver;
 import android.content.pm.InstrumentationInfo;
 import android.content.pm.PackageInfo;
+import android.content.pm.ParceledListSlice;
 import android.content.pm.ProviderInfo;
 import android.content.pm.PermissionGroupInfo;
 import android.content.pm.PermissionInfo;
@@ -109,9 +110,21 @@
     List<ResolveInfo> queryIntentServices(in Intent intent,
             String resolvedType, int flags);
 
-    List<PackageInfo> getInstalledPackages(int flags);
+    /**
+     * This implements getInstalledPackages via a "last returned row"
+     * mechanism that is not exposed in the API. This is to get around the IPC
+     * limit that kicks in when flags are included that bloat up the data
+     * returned.
+     */
+    ParceledListSlice getInstalledPackages(int flags, in String lastRead);
 
-    List<ApplicationInfo> getInstalledApplications(int flags);
+    /**
+     * This implements getInstalledApplications via a "last returned row"
+     * mechanism that is not exposed in the API. This is to get around the IPC
+     * limit that kicks in when flags are included that bloat up the data
+     * returned.
+     */
+    ParceledListSlice getInstalledApplications(int flags, in String lastRead);
 
     /**
      * Retrieve all applications that are marked as persistent.
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index 922f8cd..a779925 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -785,6 +785,13 @@
 
     /**
      * Feature for {@link #getSystemAvailableFeatures} and
+     * {@link #hasSystemFeature}: The device supports connecting to USB accessories.
+     * @hide
+     */
+    public static final String FEATURE_USB_ACCESSORY = "android.hardware.usb.accessory";
+
+    /**
+     * Feature for {@link #getSystemAvailableFeatures} and
      * {@link #hasSystemFeature}: The SIP API is enabled on the device.
      */
     @SdkConstant(SdkConstantType.FEATURE)
diff --git a/core/java/android/content/pm/ParceledListSlice.aidl b/core/java/android/content/pm/ParceledListSlice.aidl
new file mode 100755
index 0000000..c02cc6a
--- /dev/null
+++ b/core/java/android/content/pm/ParceledListSlice.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright 2011, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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;
+
+parcelable ParceledListSlice;
diff --git a/core/java/android/content/pm/ParceledListSlice.java b/core/java/android/content/pm/ParceledListSlice.java
new file mode 100644
index 0000000..f3a98db4
--- /dev/null
+++ b/core/java/android/content/pm/ParceledListSlice.java
@@ -0,0 +1,170 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.os.Parcel;
+import android.os.Parcelable;
+
+import java.util.List;
+
+/**
+ * Builds up a parcel that is discarded when written to another parcel or
+ * written to a list. This is useful for API that sends huge lists across a
+ * Binder that may be larger than the IPC limit.
+ *
+ * @hide
+ */
+public class ParceledListSlice<T extends Parcelable> implements Parcelable {
+    /*
+     * TODO get this number from somewhere else. For now set it to a quarter of
+     * the 1MB limit.
+     */
+    private static final int MAX_IPC_SIZE = 256 * 1024;
+
+    private Parcel mParcel;
+
+    private int mNumItems;
+
+    private boolean mIsLastSlice;
+
+    public ParceledListSlice() {
+        mParcel = Parcel.obtain();
+    }
+
+    private ParceledListSlice(Parcel p, int numItems, boolean lastSlice) {
+        mParcel = p;
+        mNumItems = numItems;
+        mIsLastSlice = lastSlice;
+    }
+
+    @Override
+    public int describeContents() {
+        return 0;
+    }
+
+    /**
+     * Write this to another Parcel. Note that this discards the internal Parcel
+     * and should not be used anymore. This is so we can pass this to a Binder
+     * where we won't have a chance to call recycle on this.
+     */
+    @Override
+    public void writeToParcel(Parcel dest, int flags) {
+        dest.writeInt(mNumItems);
+        dest.writeInt(mIsLastSlice ? 1 : 0);
+
+        if (mNumItems > 0) {
+            final int parcelSize = mParcel.dataSize();
+            dest.writeInt(parcelSize);
+            dest.appendFrom(mParcel, 0, parcelSize);
+        }
+
+        mNumItems = 0;
+        mParcel.recycle();
+        mParcel = null;
+    }
+
+    /**
+     * Appends a parcel to this list slice.
+     *
+     * @param item Parcelable item to append to this list slice
+     * @return true when the list slice is full and should not be appended to
+     *         anymore
+     */
+    public boolean append(T item) {
+        if (mParcel == null) {
+            throw new IllegalStateException("ParceledListSlice has already been recycled");
+        }
+
+        item.writeToParcel(mParcel, PARCELABLE_WRITE_RETURN_VALUE);
+        mNumItems++;
+
+        return mParcel.dataSize() > MAX_IPC_SIZE;
+    }
+
+    /**
+     * Populates a list and discards the internal state of the
+     * ParceledListSlice in the process. The instance should
+     * not be used anymore.
+     *
+     * @param list list to insert items from this slice.
+     * @param creator creator that knows how to unparcel the
+     *        target object type.
+     * @return the last item inserted into the list or null if none.
+     */
+    public T populateList(List<T> list, Creator<T> creator) {
+        mParcel.setDataPosition(0);
+
+        T item = null;
+        for (int i = 0; i < mNumItems; i++) {
+            item = creator.createFromParcel(mParcel);
+            list.add(item);
+        }
+
+        mParcel.recycle();
+        mParcel = null;
+
+        return item;
+    }
+
+    /**
+     * Sets whether this is the last list slice in the series.
+     *
+     * @param lastSlice
+     */
+    public void setLastSlice(boolean lastSlice) {
+        mIsLastSlice = lastSlice;
+    }
+
+    /**
+     * Returns whether this is the last slice in a series of slices.
+     *
+     * @return true if this is the last slice in the series.
+     */
+    public boolean isLastSlice() {
+        return mIsLastSlice;
+    }
+
+    @SuppressWarnings("unchecked")
+    public static final Parcelable.Creator<ParceledListSlice> CREATOR =
+            new Parcelable.Creator<ParceledListSlice>() {
+        public ParceledListSlice createFromParcel(Parcel in) {
+            final int numItems = in.readInt();
+            final boolean lastSlice = in.readInt() == 1;
+
+            if (numItems > 0) {
+                final int parcelSize = in.readInt();
+
+                // Advance within this Parcel
+                int offset = in.dataPosition();
+                in.setDataPosition(offset + parcelSize);
+
+                Parcel p = Parcel.obtain();
+                p.setDataPosition(0);
+                p.appendFrom(in, offset, parcelSize);
+                p.setDataPosition(0);
+
+                return new ParceledListSlice(p, numItems, lastSlice);
+            } else {
+                return new ParceledListSlice();
+            }
+        }
+
+        public ParceledListSlice[] newArray(int size) {
+            return new ParceledListSlice[size];
+        }
+    };
+}
diff --git a/core/java/android/content/res/AssetManager.java b/core/java/android/content/res/AssetManager.java
index 73d9458..4702327 100644
--- a/core/java/android/content/res/AssetManager.java
+++ b/core/java/android/content/res/AssetManager.java
@@ -234,6 +234,7 @@
             StringBlock[] blocks = mStringBlocks;
             if (blocks == null) {
                 ensureStringBlocks();
+                blocks = mStringBlocks;
             }
             outValue.string = blocks[block].get(outValue.data);
             return true;
diff --git a/core/java/android/hardware/Sensor.java b/core/java/android/hardware/Sensor.java
index f2b907b..595c7d1 100644
--- a/core/java/android/hardware/Sensor.java
+++ b/core/java/android/hardware/Sensor.java
@@ -97,6 +97,13 @@
      */
     public static final int TYPE_ROTATION_VECTOR = 11;
 
+    /**
+     * A constant describing a relative humidity sensor type.
+     * See {@link android.hardware.SensorEvent SensorEvent}
+     * for more details.
+     */
+    public static final int TYPE_RELATIVE_HUMIDITY = 12;
+
     /** 
      * A constant describing all sensor types.
      */
diff --git a/core/java/android/hardware/SensorEvent.java b/core/java/android/hardware/SensorEvent.java
index 8c55bf3..4a7991fc 100644
--- a/core/java/android/hardware/SensorEvent.java
+++ b/core/java/android/hardware/SensorEvent.java
@@ -304,7 +304,65 @@
      * in the clockwise direction (mathematically speaking, it should be
      * positive in the counter-clockwise direction).
      * </p>
-     * 
+     *
+     * <h4>{@link android.hardware.Sensor#TYPE_RELATIVE_HUMIDITY
+     * Sensor.TYPE_RELATIVE_HUMIDITY}:</h4>
+     * <ul>
+     * <p>
+     * values[0]: Relative ambient air humidity in percent
+     * </p>
+     * </ul>
+     * <p>
+     * When relative ambient air humidity and ambient temperature are
+     * measured, the dew point and absolute humidity can be calculated.
+     * </p>
+     * <u>Dew Point</u>
+     * <p>
+     * The dew point is the temperature to which a given parcel of air must be
+     * cooled, at constant barometric pressure, for water vapor to condense
+     * into water.
+     * </p>
+     * <center><pre>
+     *                    ln(RH/100%) + m&#183;t/(T<sub>n</sub>+t)
+     * t<sub>d</sub>(t,RH) = T<sub>n</sub> &#183; ------------------------------
+     *                 m - [ln(RH/100%) + m&#183;t/(T<sub>n</sub>+t)]
+     * </pre></center>
+     * <dl>
+     * <dt>t<sub>d</sub></dt> <dd>dew point temperature in &deg;C</dd>
+     * <dt>t</dt>             <dd>actual temperature in &deg;C</dd>
+     * <dt>RH</dt>            <dd>actual relative humidity in %</dd>
+     * <dt>m</dt>             <dd>17.62</dd>
+     * <dt>T<sub>n</sub></dt> <dd>243.12 &deg;C</dd>
+     * </dl>
+     * <p>for example:</p>
+     * <pre class="prettyprint">
+     * h = Math.log(rh / 100.0) + (17.62 * t) / (243.12 + t);
+     * td = 243.12 * h / (17.62 - h);
+     * </pre>
+     * <u>Absolute Humidity</u>
+     * <p>
+     * The absolute humidity is the mass of water vapor in a particular volume
+     * of dry air. The unit is g/m<sup>3</sup>.
+     * </p>
+     * <center><pre>
+     *                    RH/100%&#183;A&#183;exp(m&#183;t/(T<sub>n</sub>+t))
+     * d<sub>v</sub>(t,RH) = 216.7 &#183; -------------------------
+     *                           273.15 + t
+     * </pre></center>
+     * <dl>
+     * <dt>d<sub>v</sub></dt> <dd>absolute humidity in g/m<sup>3</sup></dd>
+     * <dt>t</dt>             <dd>actual temperature in &deg;C</dd>
+     * <dt>RH</dt>            <dd>actual relative humidity in %</dd>
+     * <dt>m</dt>             <dd>17.62</dd>
+     * <dt>T<sub>n</sub></dt> <dd>243.12 &deg;C</dd>
+     * <dt>A</dt>             <dd>6.112 hPa</dd>
+     * </dl>
+     * <p>for example:</p>
+     * <pre class="prettyprint">
+     * dv = 216.7 *
+     * (rh / 100.0 * 6.112 * Math.exp(17.62 * t / (243.12 + t)) / (273.15 + t));
+     * </pre>
+     *
      * @see SensorEvent
      * @see GeomagneticField
      */
diff --git a/core/java/android/hardware/SensorManager.java b/core/java/android/hardware/SensorManager.java
index f079e42..b1a9349 100644
--- a/core/java/android/hardware/SensorManager.java
+++ b/core/java/android/hardware/SensorManager.java
@@ -1970,7 +1970,8 @@
         if (rotationVector.length == 4) {
             q0 = rotationVector[3];
         } else {
-            q0 = (float)Math.sqrt(1 - q1*q1 - q2*q2 - q3*q3);
+            q0 = 1 - q1*q1 - q2*q2 - q3*q3;
+            q0 = (q0 > 0) ? (float)Math.sqrt(q0) : 0;
         }
 
         float sq_q1 = 2 * q1 * q1;
@@ -2026,8 +2027,8 @@
         if (rv.length == 4) {
             Q[0] = rv[3];
         } else {
-            //In this case, the w component of the quaternion is known to be a positive number
-            Q[0] = (float)Math.sqrt(1 - rv[0]*rv[0] - rv[1]*rv[1] - rv[2]*rv[2]);
+            Q[0] = 1 - rv[0]*rv[0] - rv[1]*rv[1] - rv[2]*rv[2];
+            Q[0] = (Q[0] > 0) ? (float)Math.sqrt(Q[0]) : 0;
         }
         Q[1] = rv[0];
         Q[2] = rv[1];
diff --git a/core/java/android/hardware/Usb.java b/core/java/android/hardware/Usb.java
deleted file mode 100644
index 57271d4..0000000
--- a/core/java/android/hardware/Usb.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-package android.hardware;
-
-/**
- * Class for accessing USB state information.
- * @hide
- */
-public class Usb {
-   /**
-     * Broadcast Action:  A broadcast for USB connected events.
-     *
-     * The extras bundle will name/value pairs with the name of the function
-     * and a value of either {@link #USB_FUNCTION_ENABLED} or {@link #USB_FUNCTION_DISABLED}.
-     * Possible USB function names include {@link #USB_FUNCTION_MASS_STORAGE},
-     * {@link #USB_FUNCTION_ADB}, {@link #USB_FUNCTION_RNDIS} and {@link #USB_FUNCTION_MTP}.
-     */
-    public static final String ACTION_USB_CONNECTED =
-            "android.hardware.action.USB_CONNECTED";
-
-   /**
-     * Broadcast Action:  A broadcast for USB disconnected events.
-     */
-    public static final String ACTION_USB_DISCONNECTED =
-            "android.hardware.action.USB_DISCONNECTED";
-
-   /**
-     * Broadcast Action:  A sticky broadcast for USB state change events.
-     *
-     * This is a sticky broadcast for clients that are interested in both USB connect and
-     * disconnect events.  If you are only concerned with one or the other, you can use
-     * {@link #ACTION_USB_CONNECTED} or {@link #ACTION_USB_DISCONNECTED} to avoid receiving
-     * unnecessary broadcasts.  The boolean {@link #USB_CONNECTED} extra indicates whether
-     * USB is connected or disconnected.
-     * The extras bundle will also contain name/value pairs with the name of the function
-     * and a value of either {@link #USB_FUNCTION_ENABLED} or {@link #USB_FUNCTION_DISABLED}.
-     * Possible USB function names include {@link #USB_FUNCTION_MASS_STORAGE},
-     * {@link #USB_FUNCTION_ADB}, {@link #USB_FUNCTION_RNDIS} and {@link #USB_FUNCTION_MTP}.
-     */
-    public static final String ACTION_USB_STATE =
-            "android.hardware.action.USB_STATE";
-
-    /**
-     * Boolean extra indicating whether USB is connected or disconnected.
-     * Used in extras for the {@link #ACTION_USB_STATE} broadcast.
-     */
-    public static final String USB_CONNECTED = "connected";
-
-    /**
-     * Name of the USB mass storage USB function.
-     * Used in extras for the {@link #ACTION_USB_CONNECTED} broadcast
-     */
-    public static final String USB_FUNCTION_MASS_STORAGE = "mass_storage";
-
-    /**
-     * Name of the adb USB function.
-     * Used in extras for the {@link #ACTION_USB_CONNECTED} broadcast
-     */
-    public static final String USB_FUNCTION_ADB = "adb";
-
-    /**
-     * Name of the RNDIS ethernet USB function.
-     * Used in extras for the {@link #ACTION_USB_CONNECTED} broadcast
-     */
-    public static final String USB_FUNCTION_RNDIS = "rndis";
-
-    /**
-     * Name of the MTP USB function.
-     * Used in extras for the {@link #ACTION_USB_CONNECTED} broadcast
-     */
-    public static final String USB_FUNCTION_MTP = "mtp";
-
-    /**
-     * Value indicating that a USB function is enabled.
-     * Used in extras for the {@link #ACTION_USB_CONNECTED} broadcast
-     */
-    public static final String USB_FUNCTION_ENABLED = "enabled";
-
-    /**
-     * Value indicating that a USB function is disabled.
-     * Used in extras for the {@link #ACTION_USB_CONNECTED} broadcast
-     */
-    public static final String USB_FUNCTION_DISABLED = "disabled";
-}
diff --git a/core/java/android/hardware/usb/IUsbManager.aidl b/core/java/android/hardware/usb/IUsbManager.aidl
new file mode 100644
index 0000000..ffe557c
--- /dev/null
+++ b/core/java/android/hardware/usb/IUsbManager.aidl
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hardware.usb;
+
+import android.app.PendingIntent;
+import android.hardware.usb.UsbAccessory;
+import android.os.Bundle;
+import android.os.ParcelFileDescriptor;
+
+/** @hide */
+interface IUsbManager
+{
+    /* Returns the currently attached USB accessory */
+    UsbAccessory getCurrentAccessory();
+
+    /* Returns a file descriptor for communicating with the USB accessory.
+     * This file descriptor can be used with standard Java file operations.
+     */
+    ParcelFileDescriptor openAccessory(in UsbAccessory accessory);
+
+    /* Sets the default package for a USB accessory
+     * (or clears it if the package name is null)
+     */
+    void setAccessoryPackage(in UsbAccessory accessory, String packageName);
+
+    /* Returns true if the caller has permission to access the accessory. */
+    boolean hasAccessoryPermission(in UsbAccessory accessory);
+
+    /* Requests permission for the given package to access the accessory.
+     * Will display a system dialog to query the user if permission
+     * had not already been given. Result is returned via pi.
+     */
+    void requestAccessoryPermission(in UsbAccessory accessory, String packageName,
+            in PendingIntent pi);
+
+    /* Grants permission for the given UID to access the accessory */
+    void grantAccessoryPermission(in UsbAccessory accessory, int uid);
+
+    /* Returns true if the USB manager has default preferences or permissions for the package */
+    boolean hasDefaults(String packageName);
+
+    /* Clears default preferences and permissions for the package */
+    void clearDefaults(String packageName);
+}
diff --git a/core/java/android/hardware/usb/UsbAccessory.aidl b/core/java/android/hardware/usb/UsbAccessory.aidl
new file mode 100644
index 0000000..1c15f1c
--- /dev/null
+++ b/core/java/android/hardware/usb/UsbAccessory.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2011, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.hardware.usb;
+
+parcelable UsbAccessory;
diff --git a/core/java/android/hardware/usb/UsbAccessory.java b/core/java/android/hardware/usb/UsbAccessory.java
new file mode 100644
index 0000000..8938463
--- /dev/null
+++ b/core/java/android/hardware/usb/UsbAccessory.java
@@ -0,0 +1,192 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.hardware.usb;
+
+import android.os.Bundle;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.util.Log;
+
+/**
+ * A class representing a USB accessory.
+ * @hide
+ */
+public class UsbAccessory implements Parcelable {
+
+    private static final String TAG = "UsbAccessory";
+
+    private final String mManufacturer;
+    private final String mModel;
+    private final String mDescription;
+    private final String mVersion;
+    private final String mUri;
+    private final String mSerial;
+
+    /**
+     * UsbAccessory should only be instantiated by UsbService implementation
+     * @hide
+     */
+    public UsbAccessory(String manufacturer, String model, String description,
+            String version, String uri, String serial) {
+        mManufacturer = manufacturer;
+        mModel = model;
+        mDescription = description;
+        mVersion = version;
+        mUri = uri;
+        mSerial = serial;
+    }
+
+    /**
+     * UsbAccessory should only be instantiated by UsbService implementation
+     * @hide
+     */
+    public UsbAccessory(String[] strings) {
+        mManufacturer = strings[0];
+        mModel = strings[1];
+        mDescription = strings[2];
+        mVersion = strings[3];
+        mUri = strings[4];
+        mSerial = strings[5];
+    }
+
+    /**
+     * Returns the manufacturer of the accessory.
+     *
+     * @return the accessory manufacturer
+     */
+    public String getManufacturer() {
+        return mManufacturer;
+    }
+
+    /**
+     * Returns the model name of the accessory.
+     *
+     * @return the accessory model
+     */
+    public String getModel() {
+        return mModel;
+    }
+
+    /**
+     * Returns a user visible description of the accessory.
+     *
+     * @return the accessory description
+     */
+    public String getDescription() {
+        return mDescription;
+    }
+
+    /**
+     * Returns the version of the accessory.
+     *
+     * @return the accessory version
+     */
+    public String getVersion() {
+        return mVersion;
+    }
+
+    /**
+     * Returns the URI for the accessory.
+     * This is an optional URI that might show information about the accessory
+     * or provide the option to download an application for the accessory
+     *
+     * @return the accessory URI
+     */
+    public String getUri() {
+        return mUri;
+    }
+
+    /**
+     * Returns the unique serial number for the accessory.
+     * This is an optional serial number that can be used to differentiate
+     * between individual accessories of the same model and manufacturer
+     *
+     * @return the unique serial number
+     */
+    public String getSerial() {
+        return mSerial;
+    }
+
+    private static boolean compare(String s1, String s2) {
+        if (s1 == null) return (s2 == null);
+        return s1.equals(s2);
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (obj instanceof UsbAccessory) {
+            UsbAccessory accessory = (UsbAccessory)obj;
+            return (compare(mManufacturer, accessory.getManufacturer()) &&
+                    compare(mModel, accessory.getModel()) &&
+                    compare(mDescription, accessory.getDescription()) &&
+                    compare(mVersion, accessory.getVersion()) &&
+                    compare(mUri, accessory.getUri()) &&
+                    compare(mSerial, accessory.getSerial()));
+        }
+        return false;
+    }
+
+    @Override
+    public int hashCode() {
+        return ((mManufacturer == null ? 0 : mManufacturer.hashCode()) ^
+                (mModel == null ? 0 : mModel.hashCode()) ^
+                (mDescription == null ? 0 : mDescription.hashCode()) ^
+                (mVersion == null ? 0 : mVersion.hashCode()) ^
+                (mUri == null ? 0 : mUri.hashCode()) ^
+                (mSerial == null ? 0 : mSerial.hashCode()));
+    }
+
+    @Override
+    public String toString() {
+        return "UsbAccessory[mManufacturer=" + mManufacturer +
+                            ", mModel=" + mModel +
+                            ", mDescription=" + mDescription +
+                            ", mVersion=" + mVersion +
+                            ", mUri=" + mUri +
+                            ", mSerial=" + mSerial + "]";
+    }
+
+    public static final Parcelable.Creator<UsbAccessory> CREATOR =
+        new Parcelable.Creator<UsbAccessory>() {
+        public UsbAccessory createFromParcel(Parcel in) {
+            String manufacturer = in.readString();
+            String model = in.readString();
+            String description = in.readString();
+            String version = in.readString();
+            String uri = in.readString();
+            String serial = in.readString();
+            return new UsbAccessory(manufacturer, model, description, version, uri, serial);
+        }
+
+        public UsbAccessory[] newArray(int size) {
+            return new UsbAccessory[size];
+        }
+    };
+
+    public int describeContents() {
+        return 0;
+    }
+
+    public void writeToParcel(Parcel parcel, int flags) {
+        parcel.writeString(mManufacturer);
+        parcel.writeString(mModel);
+        parcel.writeString(mDescription);
+        parcel.writeString(mVersion);
+        parcel.writeString(mUri);
+        parcel.writeString(mSerial);
+   }
+}
diff --git a/core/java/android/hardware/usb/UsbManager.java b/core/java/android/hardware/usb/UsbManager.java
new file mode 100644
index 0000000..ea820f9
--- /dev/null
+++ b/core/java/android/hardware/usb/UsbManager.java
@@ -0,0 +1,295 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package android.hardware.usb;
+
+import android.app.PendingIntent;
+import android.content.Context;
+import android.os.Bundle;
+import android.os.ParcelFileDescriptor;
+import android.os.RemoteException;
+import android.util.Log;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.HashMap;
+
+/**
+ * This class allows you to access the state of USB.
+ *
+ * <p>You can obtain an instance of this class by calling
+ * {@link android.content.Context#getSystemService(java.lang.String) Context.getSystemService()}.
+ *
+ * {@samplecode
+ * UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
+ * }
+ * @hide
+ */
+public class UsbManager {
+    private static final String TAG = "UsbManager";
+
+   /**
+     * Broadcast Action:  A sticky broadcast for USB state change events when in device mode.
+     *
+     * This is a sticky broadcast for clients that includes USB connected/disconnected state,
+     * <ul>
+     * <li> {@link #USB_CONNECTED} boolean indicating whether USB is connected or disconnected.
+     * <li> {@link #USB_CONFIGURATION} a Bundle containing name/value pairs where the name
+     * is the name of a USB function and the value is either {@link #USB_FUNCTION_ENABLED}
+     * or {@link #USB_FUNCTION_DISABLED}.  The possible function names include
+     * {@link #USB_FUNCTION_MASS_STORAGE}, {@link #USB_FUNCTION_ADB}, {@link #USB_FUNCTION_RNDIS},
+     * {@link #USB_FUNCTION_MTP} and {@link #USB_FUNCTION_ACCESSORY}.
+     * </ul>
+     */
+    public static final String ACTION_USB_STATE =
+            "android.hardware.usb.action.USB_STATE";
+
+   /**
+     * Broadcast Action:  A broadcast for USB accessory attached event.
+     *
+     * This intent is sent when a USB accessory is attached.
+     * <ul>
+     * <li> {@link #EXTRA_ACCESSORY} containing the {@link android.hardware.usb.UsbAccessory}
+     * for the attached accessory
+     * </ul>
+     */
+    public static final String ACTION_USB_ACCESSORY_ATTACHED =
+            "android.hardware.usb.action.USB_ACCESSORY_ATTACHED";
+
+   /**
+     * Broadcast Action:  A broadcast for USB accessory detached event.
+     *
+     * This intent is sent when a USB accessory is detached.
+     * <ul>
+     * <li> {@link #EXTRA_ACCESSORY} containing the {@link UsbAccessory}
+     * for the attached accessory that was detached
+     * </ul>
+     */
+    public static final String ACTION_USB_ACCESSORY_DETACHED =
+            "android.hardware.usb.action.USB_ACCESSORY_DETACHED";
+
+    /**
+     * Boolean extra indicating whether USB is connected or disconnected.
+     * Used in extras for the {@link #ACTION_USB_STATE} broadcast.
+     */
+    public static final String USB_CONNECTED = "connected";
+
+    /**
+     * Integer extra containing currently set USB configuration.
+     * Used in extras for the {@link #ACTION_USB_STATE} broadcast.
+     */
+    public static final String USB_CONFIGURATION = "configuration";
+
+    /**
+     * Name of the USB mass storage USB function.
+     * Used in extras for the {@link #ACTION_USB_STATE} broadcast
+     */
+    public static final String USB_FUNCTION_MASS_STORAGE = "mass_storage";
+
+    /**
+     * Name of the adb USB function.
+     * Used in extras for the {@link #ACTION_USB_STATE} broadcast
+     */
+    public static final String USB_FUNCTION_ADB = "adb";
+
+    /**
+     * Name of the RNDIS ethernet USB function.
+     * Used in extras for the {@link #ACTION_USB_STATE} broadcast
+     */
+    public static final String USB_FUNCTION_RNDIS = "rndis";
+
+    /**
+     * Name of the MTP USB function.
+     * Used in extras for the {@link #ACTION_USB_STATE} broadcast
+     */
+    public static final String USB_FUNCTION_MTP = "mtp";
+
+    /**
+     * Name of the Accessory USB function.
+     * Used in extras for the {@link #ACTION_USB_STATE} broadcast
+     */
+    public static final String USB_FUNCTION_ACCESSORY = "accessory";
+
+    /**
+     * Value indicating that a USB function is enabled.
+     * Used in {@link #USB_CONFIGURATION} extras bundle for the
+     * {@link #ACTION_USB_STATE} broadcast
+     */
+    public static final String USB_FUNCTION_ENABLED = "enabled";
+
+    /**
+     * Value indicating that a USB function is disabled.
+     * Used in {@link #USB_CONFIGURATION} extras bundle for the
+     * {@link #ACTION_USB_STATE} broadcast
+     */
+    public static final String USB_FUNCTION_DISABLED = "disabled";
+
+    /**
+     * Name of extra for {@link #ACTION_USB_ACCESSORY_ATTACHED} and
+     * {@link #ACTION_USB_ACCESSORY_DETACHED} broadcasts
+     * containing the UsbAccessory object for the accessory.
+     */
+    public static final String EXTRA_ACCESSORY = "accessory";
+
+    /**
+     * Name of extra added to the {@link android.app.PendingIntent}
+     * passed into {@link #requestPermission(UsbDevice, PendingIntent)}
+     * or {@link #requestPermission(UsbAccessory, PendingIntent)}
+     * containing a boolean value indicating whether the user granted permission or not.
+     */
+    public static final String EXTRA_PERMISSION_GRANTED = "permission";
+
+    private final Context mContext;
+    private final IUsbManager mService;
+
+    /**
+     * {@hide}
+     */
+    public UsbManager(Context context, IUsbManager service) {
+        mContext = context;
+        mService = service;
+    }
+
+    /**
+     * Returns a list of currently attached USB accessories.
+     * (in the current implementation there can be at most one)
+     *
+     * @return list of USB accessories, or null if none are attached.
+     */
+    public UsbAccessory[] getAccessoryList() {
+        try {
+            UsbAccessory accessory = mService.getCurrentAccessory();
+            if (accessory == null) {
+                return null;
+            } else {
+                return new UsbAccessory[] { accessory };
+            }
+        } catch (RemoteException e) {
+            Log.e(TAG, "RemoteException in getAccessoryList", e);
+            return null;
+        }
+    }
+
+    /**
+     * Opens a file descriptor for reading and writing data to the USB accessory.
+     *
+     * @param accessory the USB accessory to open
+     * @return file descriptor, or null if the accessor could not be opened.
+     */
+    public ParcelFileDescriptor openAccessory(UsbAccessory accessory) {
+        try {
+            return mService.openAccessory(accessory);
+        } catch (RemoteException e) {
+            Log.e(TAG, "RemoteException in openAccessory", e);
+            return null;
+        }
+    }
+
+    /**
+     * Returns true if the caller has permission to access the accessory.
+     * Permission might have been granted temporarily via
+     * {@link #requestPermission(UsbAccessory, PendingIntent)} or
+     * by the user choosing the caller as the default application for the accessory.
+     *
+     * @param accessory to check permissions for
+     * @return true if caller has permission
+     */
+    public boolean hasPermission(UsbAccessory accessory) {
+        try {
+            return mService.hasAccessoryPermission(accessory);
+        } catch (RemoteException e) {
+            Log.e(TAG, "RemoteException in hasPermission", e);
+            return false;
+        }
+    }
+
+    /**
+     * Requests temporary permission for the given package to access the accessory.
+     * This may result in a system dialog being displayed to the user
+     * if permission had not already been granted.
+     * Success or failure is returned via the {@link android.app.PendingIntent} pi.
+     * If successful, this grants the caller permission to access the accessory only
+     * until the device is disconnected.
+     *
+     * The following extras will be added to pi:
+     * <ul>
+     * <li> {@link #EXTRA_ACCESSORY} containing the accessory passed into this call
+     * <li> {@link #EXTRA_PERMISSION_GRANTED} containing boolean indicating whether
+     * permission was granted by the user
+     * </ul>
+     *
+     * @param accessory to request permissions for
+     * @param pi PendingIntent for returning result
+     */
+    public void requestPermission(UsbAccessory accessory, PendingIntent pi) {
+        try {
+            mService.requestAccessoryPermission(accessory, mContext.getPackageName(), pi);
+        } catch (RemoteException e) {
+            Log.e(TAG, "RemoteException in requestPermission", e);
+        }
+    }
+
+    private static File getFunctionEnableFile(String function) {
+        return new File("/sys/class/usb_composite/" + function + "/enable");
+    }
+
+    /**
+     * Returns true if the specified USB function is supported by the kernel.
+     * Note that a USB function maybe supported but disabled.
+     *
+     * @param function name of the USB function
+     * @return true if the USB function is supported.
+     */
+    public static boolean isFunctionSupported(String function) {
+        return getFunctionEnableFile(function).exists();
+    }
+
+    /**
+     * Returns true if the specified USB function is currently enabled.
+     *
+     * @param function name of the USB function
+     * @return true if the USB function is enabled.
+     */
+    public static boolean isFunctionEnabled(String function) {
+        try {
+            FileInputStream stream = new FileInputStream(getFunctionEnableFile(function));
+            boolean enabled = (stream.read() == '1');
+            stream.close();
+            return enabled;
+        } catch (IOException e) {
+            return false;
+        }
+    }
+
+    /**
+     * Enables or disables a USB function.
+     *
+     * @hide
+     */
+    public static boolean setFunctionEnabled(String function, boolean enable) {
+        try {
+            FileOutputStream stream = new FileOutputStream(getFunctionEnableFile(function));
+            stream.write(enable ? '1' : '0');
+            stream.close();
+            return true;
+        } catch (IOException e) {
+            return false;
+        }
+    }
+}
diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java
index a43914a..494e922 100644
--- a/core/java/android/net/ConnectivityManager.java
+++ b/core/java/android/net/ConnectivityManager.java
@@ -222,9 +222,9 @@
     /** {@hide} */
     public static final int TYPE_ETHERNET    = 9;
     /** {@hide} TODO: Need to adjust this for WiMAX. */
-    public static final int MAX_RADIO_TYPE   = TYPE_WIFI;
+    public static final int MAX_RADIO_TYPE   = TYPE_ETHERNET;
     /** {@hide} TODO: Need to adjust this for WiMAX. */
-    public static final int MAX_NETWORK_TYPE = TYPE_MOBILE_HIPRI;
+    public static final int MAX_NETWORK_TYPE = TYPE_ETHERNET;
 
     public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
 
diff --git a/core/java/android/net/InterfaceConfiguration.java b/core/java/android/net/InterfaceConfiguration.java
index 915c5d7..dcea3af 100644
--- a/core/java/android/net/InterfaceConfiguration.java
+++ b/core/java/android/net/InterfaceConfiguration.java
@@ -51,6 +51,24 @@
             append(addr & 0xff);
     }
 
+    /**
+     * This function determines if the interface is up and has a valid IP
+     * configuration (IP address has a non zero octet).
+     *
+     * Note: It is supposed to be quick and hence should not initiate
+     * any network activity
+     */
+    public boolean isActive() {
+        try {
+            if(interfaceFlags.contains("up")) {
+                if (ipAddr != 0) return true;
+            }
+        } catch (NullPointerException e) {
+            return false;
+        }
+        return false;
+    }
+
     /** Implement the Parcelable interface {@hide} */
     public int describeContents() {
         return 0;
diff --git a/core/java/android/net/MobileDataStateTracker.java b/core/java/android/net/MobileDataStateTracker.java
index 32c2d64..04b0f12 100644
--- a/core/java/android/net/MobileDataStateTracker.java
+++ b/core/java/android/net/MobileDataStateTracker.java
@@ -247,6 +247,9 @@
                                     Log.d(TAG, "CONNECTED event did not supply interface name.");
                                 }
                                 mDefaultGatewayAddr = intent.getIntExtra(Phone.DATA_GATEWAY_KEY, 0);
+                                if (mDefaultGatewayAddr == 0) {
+                                    Log.d(TAG, "CONNECTED event did not supply a default gateway.");
+                                }
                                 setDetailedState(DetailedState.CONNECTED, reason, apnName);
                                 break;
                         }
@@ -385,6 +388,7 @@
                 intent.putExtra(Phone.DATA_APN_KEY, mApnName);
                 intent.putExtra(Phone.DATA_IFACE_NAME_KEY, mInterfaceName);
                 intent.putExtra(Phone.NETWORK_UNAVAILABLE_KEY, false);
+                intent.putExtra(Phone.DATA_GATEWAY_KEY, mDefaultGatewayAddr);
                 if (mStateReceiver != null) mStateReceiver.onReceive(mContext, intent);
                 break;
             case Phone.APN_REQUEST_STARTED:
diff --git a/core/java/android/net/NetworkStateTracker.java b/core/java/android/net/NetworkStateTracker.java
index 9140dc9..233ad21 100644
--- a/core/java/android/net/NetworkStateTracker.java
+++ b/core/java/android/net/NetworkStateTracker.java
@@ -172,6 +172,7 @@
             if (inetAddress == null) {
                 if (DBG) Log.d(TAG, " Unable to add default route. mDefaultGatewayAddr Error");
             } else {
+                NetworkUtils.addHostRoute(mInterfaceName, inetAddress, null);
                 if (!NetworkUtils.addDefaultRoute(mInterfaceName, inetAddress) && DBG) {
                     Log.d(TAG, "  Unable to add default route.");
                 }
@@ -423,4 +424,7 @@
     public void interpretScanResultsAvailable() {
     }
 
+    public String getInterfaceName() {
+        return mInterfaceName;
+    }
 }
diff --git a/core/java/android/net/NetworkUtils.java b/core/java/android/net/NetworkUtils.java
index 5d4b099..8bdfdf9 100644
--- a/core/java/android/net/NetworkUtils.java
+++ b/core/java/android/net/NetworkUtils.java
@@ -209,4 +209,16 @@
         }
         return result;
     }
+
+    /**
+     * Start the DHCP renew service for wimax,
+     * This call blocks until it obtains a result (either success
+     * or failure) from the daemon.
+     * @param interfaceName the name of the interface to configure
+     * @param ipInfo if the request succeeds, this object is filled in with
+     * the IP address information.
+     * @return {@code true} for success, {@code false} for failure
+     * {@hide}
+     */
+    public native static boolean runDhcpRenew(String interfaceName, DhcpInfo ipInfo);
 }
diff --git a/core/java/android/net/wimax/WimaxManagerConstants.java b/core/java/android/net/wimax/WimaxManagerConstants.java
new file mode 100644
index 0000000..5ec4e96
--- /dev/null
+++ b/core/java/android/net/wimax/WimaxManagerConstants.java
@@ -0,0 +1,103 @@
+package android.net.wimax;
+
+/**
+ * {@hide}
+ */
+public class WimaxManagerConstants
+{
+
+    /**
+     * Used by android.net.wimax.WimaxManager for handling management of
+     * Wimax access.
+     */
+    public static final String WIMAX_SERVICE = "WiMax";
+
+    /**
+     * Broadcast intent action indicating that Wimax has been enabled, disabled,
+     * enabling, disabling, or unknown. One extra provides this state as an int.
+     * Another extra provides the previous state, if available.
+     */
+    public static final String WIMAX_ENABLED_STATUS_CHANGED =
+        "android.net.wimax.WIMAX_STATUS_CHANGED";
+
+    /**
+     * The lookup key for an int that indicates whether Wimax is enabled,
+     * disabled, enabling, disabling, or unknown.
+     */
+    public static final String EXTRA_WIMAX_STATUS = "wimax_status";
+
+    /**
+     * Broadcast intent action indicating that Wimax state has been changed
+     * state could be scanning, connecting, connected, disconnecting, disconnected
+     * initializing, initialized, unknown and ready. One extra provides this state as an int.
+     * Another extra provides the previous state, if available.
+     */
+    public static final String  WIMAX_STATE_CHANGED_ACTION =
+        "android.net.wimax.WIMAX_STATE_CHANGE";
+
+    /**
+     * Broadcast intent action indicating that Wimax signal level has been changed.
+     * Level varies from 0 to 3.
+     */
+    public static final String SIGNAL_LEVEL_CHANGED_ACTION =
+        "android.net.wimax.SIGNAL_LEVEL_CHANGED";
+
+    /**
+     * The lookup key for an int that indicates whether Wimax state is
+     * scanning, connecting, connected, disconnecting, disconnected
+     * initializing, initialized, unknown and ready.
+     */
+    public static final String EXTRA_WIMAX_STATE = "WimaxState";
+
+    /**
+     * The lookup key for an int that indicates whether state of Wimax
+     * is idle.
+     */
+    public static final String EXTRA_WIMAX_STATE_DETAIL = "WimaxStateDetail";
+
+    /**
+     * The lookup key for an int that indicates Wimax signal level.
+     */
+    public static final String EXTRA_NEW_SIGNAL_LEVEL = "newSignalLevel";
+
+    /**
+     * Indicatates Wimax is disabled.
+     */
+    public static final int WIMAX_STATUS_DISABLED = 1;
+
+    /**
+     * Indicatates Wimax is enabled.
+     */
+    public static final int WIMAX_STATUS_ENABLED = 3;
+
+    /**
+     * Indicatates Wimax status is known.
+     */
+    public static final int WIMAX_STATUS_UNKNOWN = 4;
+
+    /**
+     * Indicatates Wimax is in idle state.
+     */
+    public static final int WIMAX_IDLE = 6;
+
+    /**
+     * Indicatates Wimax is being deregistered.
+     */
+    public static final int WIMAX_DEREGISTRATION = 8;
+
+    /**
+     * Indicatates wimax state is unknown.
+     */
+    public static final int WIMAX_STATE_UNKNOWN = 0;
+
+    /**
+     * Indicatates wimax state is connected.
+     */
+    public static final int WIMAX_STATE_CONNECTED = 7;
+
+    /**
+     * Indicatates wimax state is disconnected.
+     */
+    public static final int WIMAX_STATE_DISCONNECTED = 9;
+
+}
diff --git a/core/java/android/nfc/INfcSecureElement.aidl b/core/java/android/nfc/ApduList.aidl
old mode 100755
new mode 100644
similarity index 61%
copy from core/java/android/nfc/INfcSecureElement.aidl
copy to core/java/android/nfc/ApduList.aidl
index aa98dd2..f6236b2
--- a/core/java/android/nfc/INfcSecureElement.aidl
+++ b/core/java/android/nfc/ApduList.aidl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010 The Android Open Source Project
+ * Copyright (C) 2011 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -16,13 +16,4 @@
 
 package android.nfc;
 
-/**
- * {@hide}
- */
-interface INfcSecureElement {
-    int openSecureElementConnection();
-    int closeSecureElementConnection(int nativeHandle);
-    byte[] exchangeAPDU(int nativeHandle, in byte[] data);
-    int[] getSecureElementTechList(int nativeHandle);
-    byte[] getSecureElementUid(int nativeHandle);
-}
\ No newline at end of file
+parcelable ApduList;
\ No newline at end of file
diff --git a/core/java/android/nfc/ApduList.java b/core/java/android/nfc/ApduList.java
new file mode 100644
index 0000000..85b0547
--- /dev/null
+++ b/core/java/android/nfc/ApduList.java
@@ -0,0 +1,68 @@
+package android.nfc;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @hide
+ */
+public class ApduList implements Parcelable {
+
+    private ArrayList<byte[]> commands = new ArrayList<byte[]>();
+
+    public ApduList() {
+    }
+
+    public void add(byte[] command) {
+        commands.add(command);
+    }
+
+    public List<byte[]> get() {
+        return commands;
+    }
+
+    public static final Parcelable.Creator<ApduList> CREATOR =
+        new Parcelable.Creator<ApduList>() {
+        @Override
+        public ApduList createFromParcel(Parcel in) {
+            return new ApduList(in);
+        }
+
+        @Override
+        public ApduList[] newArray(int size) {
+            return new ApduList[size];
+        }
+    };
+
+    private ApduList(Parcel in) {
+        int count = in.readInt();
+
+        for (int i = 0 ; i < count ; i++) {
+
+            int length = in.readInt();
+            byte[] cmd = new byte[length];
+            in.readByteArray(cmd);
+            commands.add(cmd);
+        }
+    }
+
+    @Override
+    public int describeContents() {
+        return 0;
+    }
+
+    @Override
+    public void writeToParcel(Parcel dest, int flags) {
+        dest.writeInt(commands.size());
+
+        for (byte[] cmd : commands) {
+            dest.writeInt(cmd.length);
+            dest.writeByteArray(cmd);
+        }
+    }
+}
+
+
diff --git a/core/java/android/nfc/INfcAdapter.aidl b/core/java/android/nfc/INfcAdapter.aidl
index d439a48..870127c 100644
--- a/core/java/android/nfc/INfcAdapter.aidl
+++ b/core/java/android/nfc/INfcAdapter.aidl
@@ -28,7 +28,7 @@
 import android.nfc.INfcTag;
 import android.nfc.IP2pTarget;
 import android.nfc.IP2pInitiator;
-import android.nfc.INfcSecureElement;
+import android.nfc.INfcAdapterExtras;
 
 /**
  * @hide
@@ -41,13 +41,12 @@
     INfcTag getNfcTagInterface();
     IP2pTarget getP2pTargetInterface();
     IP2pInitiator getP2pInitiatorInterface();
-    INfcSecureElement getNfcSecureElementInterface();
+    INfcAdapterExtras getNfcAdapterExtrasInterface();
 
     // NfcAdapter-class related methods
     boolean isEnabled();
     NdefMessage localGet();
     void localSet(in NdefMessage message);
-    void openTagConnection(in Tag tag);
     void enableForegroundDispatch(in ComponentName activity, in PendingIntent intent,
             in IntentFilter[] filters, in TechListParcel techLists);
     void disableForegroundDispatch(in ComponentName activity);
@@ -59,12 +58,8 @@
     int createLlcpConnectionlessSocket(int sap);
     int createLlcpServiceSocket(int sap, String sn, int miu, int rw, int linearBufferLength);
     int createLlcpSocket(int sap, int miu, int rw, int linearBufferLength);
-    int deselectSecureElement();
     boolean disable();
     boolean enable();
     String getProperties(String param);
-    int[] getSecureElementList();
-    int getSelectedSecureElement();
-    int selectSecureElement(int seId);
     int setProperties(String param, String value);
-}
\ No newline at end of file
+}
diff --git a/core/java/android/nfc/INfcSecureElement.aidl b/core/java/android/nfc/INfcAdapterExtras.aidl
similarity index 63%
copy from core/java/android/nfc/INfcSecureElement.aidl
copy to core/java/android/nfc/INfcAdapterExtras.aidl
index aa98dd2..0c2a2fd 100755
--- a/core/java/android/nfc/INfcSecureElement.aidl
+++ b/core/java/android/nfc/INfcAdapterExtras.aidl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010 The Android Open Source Project
+ * Copyright (C) 2011 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -16,13 +16,17 @@
 
 package android.nfc;
 
+import android.os.Bundle;
+
+
 /**
  * {@hide}
  */
-interface INfcSecureElement {
-    int openSecureElementConnection();
-    int closeSecureElementConnection(int nativeHandle);
-    byte[] exchangeAPDU(int nativeHandle, in byte[] data);
-    int[] getSecureElementTechList(int nativeHandle);
-    byte[] getSecureElementUid(int nativeHandle);
-}
\ No newline at end of file
+interface INfcAdapterExtras {
+    Bundle open(IBinder b);
+    Bundle close();
+    Bundle transceive(in byte[] data_in);
+    int getCardEmulationRoute();
+    void setCardEmulationRoute(int route);
+    void authenticate(in byte[] token);
+}
diff --git a/core/java/android/nfc/NfcAdapter.java b/core/java/android/nfc/NfcAdapter.java
index 622bcdb..4689804 100644
--- a/core/java/android/nfc/NfcAdapter.java
+++ b/core/java/android/nfc/NfcAdapter.java
@@ -157,31 +157,6 @@
     public static final String EXTRA_ID = "android.nfc.extra.ID";
 
     /**
-     * Broadcast Action: a transaction with a secure element has been detected.
-     * <p>
-     * Always contains the extra field
-     * {@link android.nfc.NfcAdapter#EXTRA_AID}
-     * @hide
-     */
-    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
-    public static final String ACTION_TRANSACTION_DETECTED =
-            "android.nfc.action.TRANSACTION_DETECTED";
-
-    /**
-     * Broadcast Action: an RF field ON has been detected.
-     * @hide
-     */
-    public static final String ACTION_RF_FIELD_ON_DETECTED =
-            "android.nfc.action.RF_FIELD_ON_DETECTED";
-
-    /**
-     * Broadcast Action: an RF Field OFF has been detected.
-     * @hide
-     */
-    public static final String ACTION_RF_FIELD_OFF_DETECTED =
-            "android.nfc.action.RF_FIELD_OFF_DETECTED";
-
-    /**
      * Broadcast Action: an adapter's state changed between enabled and disabled.
      *
      * The new value is stored in the extra EXTRA_NEW_BOOLEAN_STATE and just contains
@@ -201,15 +176,6 @@
     public static final String EXTRA_NEW_BOOLEAN_STATE = "android.nfc.isEnabled";
 
     /**
-     * Mandatory byte array extra field in
-     * {@link android.nfc.NfcAdapter#ACTION_TRANSACTION_DETECTED}.
-     * <p>
-     * Contains the AID of the applet involved in the transaction.
-     * @hide
-     */
-    public static final String EXTRA_AID = "android.nfc.extra.AID";
-
-    /**
      * LLCP link status: The LLCP link is activated.
      * @hide
      */
@@ -691,14 +657,13 @@
     }
 
     /**
-     * Create an Nfc Secure Element Connection
      * @hide
      */
-    public NfcSecureElement createNfcSecureElementConnection() {
+    public INfcAdapterExtras getNfcAdapterExtrasInterface() {
         try {
-            return new NfcSecureElement(sService.getNfcSecureElementInterface());
+            return sService.getNfcAdapterExtrasInterface();
         } catch (RemoteException e) {
-            Log.e(TAG, "createNfcSecureElementConnection failed", e);
+            attemptDeadServiceRecovery(e);
             return null;
         }
     }
diff --git a/core/java/android/nfc/NfcSecureElement.java b/core/java/android/nfc/NfcSecureElement.java
deleted file mode 100755
index 3b5f39e..0000000
--- a/core/java/android/nfc/NfcSecureElement.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.nfc;
-
-import android.nfc.tech.TagTechnology;
-import android.os.RemoteException;
-import android.util.Log;
-
-import java.io.IOException;
-
-//import android.util.Log;
-
-/**
- * This class provides the primary API for managing all aspects Secure Element.
- * Get an instance of this class by calling
- * Context.getSystemService(Context.NFC_SERVICE).
- * @hide
- */
-public final class NfcSecureElement {
-
-    private static final String TAG = "NfcSecureElement";
-
-    private INfcSecureElement mService;
-
-
-    /**
-     * @hide
-     */
-    public NfcSecureElement(INfcSecureElement mSecureElementService) {
-        mService = mSecureElementService;
-    }
-
-    public int openSecureElementConnection(String seType) throws IOException {
-        if (seType.equals("SmartMX")) {
-            try {
-                int handle = mService.openSecureElementConnection();
-                // Handle potential errors
-                if (handle != 0) {
-                    return handle;
-                } else {
-                    throw new IOException("SmartMX connection not allowed");
-                }
-            } catch (RemoteException e) {
-                Log.e(TAG, "RemoteException in openSecureElementConnection(): ", e);
-                return 0;
-            }
-
-        } else if (seType.equals("UICC")) {
-            return 0;
-        } else {
-        	throw new IOException("Wrong Secure Element type");
-        }
-    }
-
-
-    public byte [] exchangeAPDU(int handle,byte [] data) throws IOException {
-
-
-        // Perform exchange APDU
-        try {
-            byte[] response = mService.exchangeAPDU(handle, data);
-            // Handle potential errors
-            if (response == null) {
-            	throw new IOException("Exchange APDU failed");
-            }
-            return response;
-        } catch (RemoteException e) {
-            Log.e(TAG, "RemoteException in exchangeAPDU(): ", e);
-            return null;
-        }
-    }
-
-    public void closeSecureElementConnection(int handle) throws IOException {
-
-        try {
-            int status = mService.closeSecureElementConnection(handle);
-            // Handle potential errors
-            if (ErrorCodes.isError(status)) {
-            	throw new IOException("Error during the conection close");
-            };
-        } catch (RemoteException e) {
-            Log.e(TAG, "RemoteException in closeSecureElement(): ", e);
-        }
-    }
-
-
-    /**
-     * Returns target type. constants.
-     *
-     * @return Secure Element technology type. The possible values are defined in
-     * {@link TagTechnology}
-     *
-     */
-    public int[] getSecureElementTechList(int handle) throws IOException {
-        try {
-            return mService.getSecureElementTechList(handle);
-        } catch (RemoteException e) {
-            Log.e(TAG, "RemoteException in getType(): ", e);
-            return null;
-        }
-    }
-
-    /**
-     * Returns Secure Element UID.
-     *
-     * @return Secure Element UID.
-     */
-    public byte[] getSecureElementUid(int handle) throws IOException {
-
-        byte[] uid = null;
-        try {
-            uid = mService.getSecureElementUid(handle);
-            // Handle potential errors
-            if (uid == null) {
-                throw new IOException("Get Secure Element UID failed");
-            }
-            return uid;
-        } catch (RemoteException e) {
-            Log.e(TAG, "RemoteException in getType(): ", e);
-            return null;
-        }
-    }
-
-}
diff --git a/core/java/android/nfc/tech/Ndef.java b/core/java/android/nfc/tech/Ndef.java
index 6727d6a..e4daa57 100644
--- a/core/java/android/nfc/tech/Ndef.java
+++ b/core/java/android/nfc/tech/Ndef.java
@@ -103,6 +103,8 @@
     public static final int TYPE_4 = 4;
     /** @hide */
     public static final int TYPE_MIFARE_CLASSIC = 101;
+    /** @hide */
+    public static final int TYPE_ICODE_SLI = 102;
 
     /** @hide */
     public static final String UNKNOWN = "android.ndef.unknown";
@@ -117,6 +119,11 @@
     public static final String NFC_FORUM_TYPE_4 = "org.nfcforum.ndef.type4";
     /** NDEF on MIFARE Classic */
     public static final String MIFARE_CLASSIC = "com.nxp.ndef.mifareclassic";
+    /**
+     * NDEF on iCODE SLI
+     * @hide
+     */
+    public static final String ICODE_SLI = "com.nxp.ndef.icodesli";
 
     private final int mMaxNdefSize;
     private final int mCardState;
@@ -200,6 +207,8 @@
                 return NFC_FORUM_TYPE_4;
             case TYPE_MIFARE_CLASSIC:
                 return MIFARE_CLASSIC;
+            case TYPE_ICODE_SLI:
+                return ICODE_SLI;
             default:
                 return UNKNOWN;
         }
diff --git a/core/java/android/nfc/tech/package.html b/core/java/android/nfc/tech/package.html
new file mode 100644
index 0000000..a99828f
--- /dev/null
+++ b/core/java/android/nfc/tech/package.html
@@ -0,0 +1,13 @@
+<HTML>
+<BODY>
+<p>
+These classes provide access to a tag technology's features, which vary by the type
+of tag that is scanned. A scanned tag can support multiple technologies, and you can find
+out what they are by calling {@link android.nfc.Tag#getTechList getTechList()}.</p>
+
+<p>For more information on dealing with tag technologies and handling the ones that you care about, see
+<a href="{@docRoot}guide/topics/nfc/index.html#dispatch">The Tag Dispatch System</a>.
+The {@link android.nfc.tech.TagTechnology} interface provides an overview of the
+supported technologies.</p>
+</BODY>
+</HTML>
diff --git a/core/java/android/os/BatteryStats.java b/core/java/android/os/BatteryStats.java
index e4485d1..4ff3572 100644
--- a/core/java/android/os/BatteryStats.java
+++ b/core/java/android/os/BatteryStats.java
@@ -132,6 +132,7 @@
     private static final String NETWORK_DATA = "nt";
     private static final String USER_ACTIVITY_DATA = "ua";
     private static final String BATTERY_DATA = "bt";
+    private static final String BATTERY_DISCHARGE_DATA = "dc";
     private static final String BATTERY_LEVEL_DATA = "lv";
     private static final String WIFI_LOCK_DATA = "wfl";
     private static final String MISC_DATA = "m";
@@ -801,6 +802,30 @@
     public abstract int getHighDischargeAmountSinceCharge();
 
     /**
+     * Get the amount the battery has discharged while the screen was on,
+     * since the last time power was unplugged.
+     */
+    public abstract int getDischargeAmountScreenOn();
+
+    /**
+     * Get the amount the battery has discharged while the screen was on,
+     * since the last time the device was charged.
+     */
+    public abstract int getDischargeAmountScreenOnSinceCharge();
+
+    /**
+     * Get the amount the battery has discharged while the screen was off,
+     * since the last time power was unplugged.
+     */
+    public abstract int getDischargeAmountScreenOff();
+
+    /**
+     * Get the amount the battery has discharged while the screen was off,
+     * since the last time the device was charged.
+     */
+    public abstract int getDischargeAmountScreenOffSinceCharge();
+
+    /**
      * Returns the total, last, or current battery uptime in microseconds.
      *
      * @param curTime the elapsed realtime in microseconds.
@@ -1095,6 +1120,17 @@
                     getDischargeCurrentLevel());
         }
         
+        if (which == STATS_SINCE_UNPLUGGED) {
+            dumpLine(pw, 0 /* uid */, category, BATTERY_DISCHARGE_DATA,
+                    getDischargeStartLevel()-getDischargeCurrentLevel(),
+                    getDischargeStartLevel()-getDischargeCurrentLevel(),
+                    getDischargeAmountScreenOn(), getDischargeAmountScreenOff());
+        } else {
+            dumpLine(pw, 0 /* uid */, category, BATTERY_DISCHARGE_DATA,
+                    getLowDischargeAmountSinceCharge(), getHighDischargeAmountSinceCharge(),
+                    getDischargeAmountScreenOn(), getDischargeAmountScreenOff());
+        }
+        
         if (reqUid < 0) {
             Map<String, ? extends BatteryStats.Timer> kernelWakelocks = getKernelWakelockStats();
             if (kernelWakelocks.size() > 0) {
@@ -1451,6 +1487,10 @@
                 pw.print(prefix); pw.print("    Last discharge cycle end level: "); 
                         pw.println(getDischargeCurrentLevel());
             }
+            pw.print(prefix); pw.print("    Amount discharged while screen on: ");
+                    pw.println(getDischargeAmountScreenOn());
+            pw.print(prefix); pw.print("    Amount discharged while screen off: ");
+                    pw.println(getDischargeAmountScreenOff());
             pw.println(" ");
         } else {
             pw.print(prefix); pw.println("  Device battery use since last full charge");
@@ -1458,6 +1498,10 @@
                     pw.println(getLowDischargeAmountSinceCharge());
             pw.print(prefix); pw.print("    Amount discharged (upper bound): ");
                     pw.println(getHighDischargeAmountSinceCharge());
+            pw.print(prefix); pw.print("    Amount discharged while screen on: ");
+                    pw.println(getDischargeAmountScreenOnSinceCharge());
+            pw.print(prefix); pw.print("    Amount discharged while screen off: ");
+                    pw.println(getDischargeAmountScreenOffSinceCharge());
             pw.println(" ");
         }
         
@@ -1847,7 +1891,6 @@
         final int NU = uidStats.size();
         boolean didPid = false;
         long nowRealtime = SystemClock.elapsedRealtime();
-        StringBuilder sb = new StringBuilder(64);
         for (int i=0; i<NU; i++) {
             Uid uid = uidStats.valueAt(i);
             SparseArray<? extends Uid.Pid> pids = uid.getPidStats();
diff --git a/core/java/android/os/INetworkManagementService.aidl b/core/java/android/os/INetworkManagementService.aidl
index 212c5fb..08403af 100644
--- a/core/java/android/os/INetworkManagementService.aidl
+++ b/core/java/android/os/INetworkManagementService.aidl
@@ -207,4 +207,23 @@
      */
     int getInterfaceTxThrottle(String iface);
 
+    /**
+     * Sets the name of the default interface in the DNS resolver.
+     */
+    void setDefaultInterfaceForDns(String iface);
+
+    /**
+     * Bind name servers to an interface in the DNS resolver.
+     */
+    void setDnsServersForInterface(String iface, in String[] servers);
+
+    /**
+     * Flush the DNS cache associated with the default interface
+     */
+    void flushDefaultDnsCache();
+
+    /**
+     * Flush the DNS cache associated with the specified interface
+     */
+    void flushInterfaceDnsCache(String iface);
 }
diff --git a/core/java/android/os/Looper.java b/core/java/android/os/Looper.java
index d360140..2a66616 100644
--- a/core/java/android/os/Looper.java
+++ b/core/java/android/os/Looper.java
@@ -17,6 +17,7 @@
 package android.os;
 
 import android.util.Config;
+import android.util.Log;
 import android.util.Printer;
 
 /**
@@ -106,6 +107,12 @@
     public static final void loop() {
         Looper me = myLooper();
         MessageQueue queue = me.mQueue;
+        
+        // Make sure the identity of this thread is that of the local process,
+        // and keep track of what that identity token actually is.
+        Binder.clearCallingIdentity();
+        final long ident = Binder.clearCallingIdentity();
+        
         while (true) {
             Message msg = queue.next(); // might block
             //if (!me.mRun) {
@@ -124,6 +131,18 @@
                 if (me.mLogging!= null) me.mLogging.println(
                         "<<<<< Finished to    " + msg.target + " "
                         + msg.callback);
+                
+                // Make sure that during the course of dispatching the
+                // identity of the thread wasn't corrupted.
+                final long newIdent = Binder.clearCallingIdentity();
+                if (ident != newIdent) {
+                    Log.wtf("Looper", "Thread identity changed from 0x"
+                            + Long.toHexString(ident) + " to 0x"
+                            + Long.toHexString(newIdent) + " while dispatching to "
+                            + msg.target.getClass().getName() + " "
+                            + msg.callback + " what=" + msg.what);
+                }
+                
                 msg.recycle();
             }
         }
diff --git a/core/java/android/os/Process.java b/core/java/android/os/Process.java
index a718fc6..e1fdfb6 100644
--- a/core/java/android/os/Process.java
+++ b/core/java/android/os/Process.java
@@ -89,7 +89,7 @@
      * Defines the UID/GID for the NFC service process.
      * @hide
      */
-    public static final int NFC_UID = 1022;
+    public static final int NFC_UID = 1025;
 
     /**
      * Defines the start of a range of UIDs (and GIDs), going from this
diff --git a/core/java/android/os/RecoverySystem.java b/core/java/android/os/RecoverySystem.java
index 6d19f41..74b4fcb 100644
--- a/core/java/android/os/RecoverySystem.java
+++ b/core/java/android/os/RecoverySystem.java
@@ -16,6 +16,11 @@
 
 package android.os;
 
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
 import java.io.ByteArrayInputStream;
 import java.io.File;
 import java.io.FileNotFoundException;
@@ -37,9 +42,6 @@
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipFile;
 
-import android.content.Context;
-import android.util.Log;
-
 import org.apache.harmony.security.asn1.BerInputStream;
 import org.apache.harmony.security.pkcs7.ContentInfo;
 import org.apache.harmony.security.pkcs7.SignedData;
@@ -336,8 +338,21 @@
      * @throws IOException  if writing the recovery command file
      * fails, or if the reboot itself fails.
      */
-    public static void rebootWipeUserData(Context context)
-        throws IOException {
+    public static void rebootWipeUserData(Context context) throws IOException {
+        final ConditionVariable condition = new ConditionVariable();
+
+        Intent intent = new Intent("android.intent.action.MASTER_CLEAR_NOTIFICATION");
+        context.sendOrderedBroadcast(intent, android.Manifest.permission.MASTER_CLEAR,
+                new BroadcastReceiver() {
+                    @Override
+                    public void onReceive(Context context, Intent intent) {
+                        condition.open();
+                    }
+                }, null, 0, null, null);
+
+        // Block until the ordered broadcast has completed.
+        condition.block();
+
         bootCommand(context, "--wipe_data");
     }
 
diff --git a/core/java/android/pim/ICalendar.java b/core/java/android/pim/ICalendar.java
index cc0f45e..9c4eaf4 100644
--- a/core/java/android/pim/ICalendar.java
+++ b/core/java/android/pim/ICalendar.java
@@ -578,6 +578,23 @@
                             + text);
                 }
                 parameter.name = text.substring(startIndex + 1, equalIndex);
+            } else if (c == '"') {
+                if (parameter == null) {
+                    throw new FormatException("Expected parameter before '\"' in " + text);
+                }
+                if (equalIndex == -1) {
+                    throw new FormatException("Expected '=' within parameter in " + text);
+                }
+                if (state.index > equalIndex + 1) {
+                    throw new FormatException("Parameter value cannot contain a '\"' in " + text);
+                }
+                final int endQuote = text.indexOf('"', state.index + 1);
+                if (endQuote < 0) {
+                    throw new FormatException("Expected closing '\"' in " + text);
+                }
+                parameter.value = text.substring(state.index + 1, endQuote);
+                state.index = endQuote + 1;
+                return parameter;
             }
             ++state.index;
         }
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 2a13d520..75bdc2b 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -1101,6 +1101,12 @@
         public static final String RADIO_CELL = "cell";
 
         /**
+         * Constant for use in AIRPLANE_MODE_RADIOS to specify WiMAX radio.
+         * @hide
+         */
+        public static final String RADIO_WIMAX = "wimax";
+
+        /**
          * A comma separated list of radios that need to be disabled when airplane mode
          * is on. This overrides WIFI_ON and BLUETOOTH_ON, if Wi-Fi and bluetooth are
          * included in the comma separated list.
@@ -2559,6 +2565,14 @@
                 "wifi_networks_available_repeat_delay";
 
         /**
+         * Whether to nofity the user of WiMAX network.
+         * If WiMAX is connected or disconnected, we will put this notification up.
+         * @hide
+         */
+        public static final String WIMAX_NETWORKS_AVAILABLE_NOTIFICATION_ON =
+                "wimax_networks_available_notification_on";
+
+        /**
          * The number of radio channels that are allowed in the local
          * 802.11 regulatory domain.
          * @hide
@@ -2586,27 +2600,6 @@
         public static final String WIFI_SAVED_STATE = "wifi_saved_state";
 
         /**
-         * AP SSID
-         *
-         * @hide
-         */
-        public static final String WIFI_AP_SSID = "wifi_ap_ssid";
-
-        /**
-         * AP security
-         *
-         * @hide
-         */
-        public static final String WIFI_AP_SECURITY = "wifi_ap_security";
-
-        /**
-         * AP passphrase
-         *
-         * @hide
-         */
-        public static final String WIFI_AP_PASSWD = "wifi_ap_passwd";
-
-        /**
          * The acceptable packet loss percentage (range 0 - 100) before trying
          * another AP on the same network.
          */
@@ -2695,6 +2688,12 @@
             "wifi_mobile_data_transition_wakelock_timeout_ms";
 
         /**
+         * Whether the Wimax should be on.  Only the WiMAX service should touch this.
+         * @hide
+         */
+        public static final String WIMAX_ON = "wimax_on";
+
+        /**
          * Whether background data usage is allowed by the user. See
          * ConnectivityManager for more info.
          */
diff --git a/core/java/android/provider/Telephony.java b/core/java/android/provider/Telephony.java
index 1a35112..2e480e8 100755
--- a/core/java/android/provider/Telephony.java
+++ b/core/java/android/provider/Telephony.java
@@ -542,7 +542,7 @@
              * values:</p>
              *
              * <ul>
-             *   <li><em>pdus</em> - An Object[] od byte[]s containing the PDUs
+             *   <li><em>pdus</em> - An Object[] of byte[]s containing the PDUs
              *   that make up the message.</li>
              * </ul>
              *
@@ -586,6 +586,46 @@
                     "android.provider.Telephony.WAP_PUSH_RECEIVED";
 
             /**
+             * Broadcast Action: A new Cell Broadcast message has been received
+             * by the device. The intent will have the following extra
+             * values:</p>
+             *
+             * <ul>
+             *   <li><em>pdus</em> - An Object[] of byte[]s containing the PDUs
+             *   that make up the message.</li>
+             * </ul>
+             *
+             * <p>The extra values can be extracted using
+             * {@link #getMessagesFromIntent(Intent)}.</p>
+             *
+             * <p>If a BroadcastReceiver encounters an error while processing
+             * this intent it should set the result code appropriately.</p>
+             */
+            @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
+            public static final String SMS_CB_RECEIVED_ACTION =
+                    "android.provider.Telephony.SMS_CB_RECEIVED";
+
+            /**
+             * Broadcast Action: A new Emergency Broadcast message has been received
+             * by the device. The intent will have the following extra
+             * values:</p>
+             *
+             * <ul>
+             *   <li><em>pdus</em> - An Object[] of byte[]s containing the PDUs
+             *   that make up the message.</li>
+             * </ul>
+             *
+             * <p>The extra values can be extracted using
+             * {@link #getMessagesFromIntent(Intent)}.</p>
+             *
+             * <p>If a BroadcastReceiver encounters an error while processing
+             * this intent it should set the result code appropriately.</p>
+             */
+            @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
+            public static final String SMS_EMERGENCY_CB_RECEIVED_ACTION =
+                    "android.provider.Telephony.SMS_EMERGENCY_CB_RECEIVED";
+
+            /**
              * Broadcast Action: The SIM storage for SMS messages is full.  If
              * space is not freed, messages targeted for the SIM (class 2) may
              * not be saved.
@@ -618,7 +658,7 @@
              * @param intent the intent to read from
              * @return an array of SmsMessages for the PDUs
              */
-            public static final SmsMessage[] getMessagesFromIntent(
+            public static SmsMessage[] getMessagesFromIntent(
                     Intent intent) {
                 Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
                 byte[][] pduObjs = new byte[messages.length][];
@@ -1723,6 +1763,21 @@
 
         public static final String TYPE = "type";
 
+        /**
+         * The protocol to be used to connect to this APN.
+         *
+         * One of the PDP_type values in TS 27.007 section 10.1.1.
+         * For example, "IP", "IPV6", "IPV4V6", or "PPP".
+         */
+        public static final String PROTOCOL = "protocol";
+
+        /**
+          * The protocol to be used to connect to this APN when roaming.
+          *
+          * The syntax is the same as protocol.
+          */
+        public static final String ROAMING_PROTOCOL = "roaming_protocol";
+
         public static final String CURRENT = "current";
     }
 
diff --git a/core/java/android/server/BluetoothA2dpService.java b/core/java/android/server/BluetoothA2dpService.java
index 6e221c8..bea01f3 100644
--- a/core/java/android/server/BluetoothA2dpService.java
+++ b/core/java/android/server/BluetoothA2dpService.java
@@ -457,6 +457,22 @@
                 Settings.Secure.getBluetoothA2dpSinkPriorityKey(device.getAddress()), priority);
     }
 
+    public synchronized boolean allowIncomingConnect(BluetoothDevice device, boolean value) {
+        mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
+                                                "Need BLUETOOTH_ADMIN permission");
+        String address = device.getAddress();
+        if (!BluetoothAdapter.checkBluetoothAddress(address)) {
+            return false;
+        }
+        Integer data = mBluetoothService.getAuthorizationAgentRequestData(address);
+        if (data == null) {
+            Log.w(TAG, "allowIncomingConnect(" + device + ") called but no native data available");
+            return false;
+        }
+        log("allowIncomingConnect: A2DP: " + device + ":" + value);
+        return mBluetoothService.setAuthorizationNative(address, value, data.intValue());
+    }
+
     private synchronized void onSinkPropertyChanged(String path, String []propValues) {
         if (!mBluetoothService.isEnabled()) {
             return;
diff --git a/core/java/android/server/BluetoothEventLoop.java b/core/java/android/server/BluetoothEventLoop.java
index 568d465..5cc9144 100644
--- a/core/java/android/server/BluetoothEventLoop.java
+++ b/core/java/android/server/BluetoothEventLoop.java
@@ -50,6 +50,7 @@
     private boolean mInterrupted;
 
     private final HashMap<String, Integer> mPasskeyAgentRequestData;
+    private final HashMap<String, Integer> mAuthorizationAgentRequestData;
     private final BluetoothService mBluetoothService;
     private final BluetoothAdapter mAdapter;
     private final Context mContext;
@@ -109,6 +110,7 @@
         mBluetoothService = bluetoothService;
         mContext = context;
         mPasskeyAgentRequestData = new HashMap();
+        mAuthorizationAgentRequestData = new HashMap<String, Integer>();
         mAdapter = adapter;
         //WakeLock instantiation in BluetoothEventLoop class
         PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
@@ -130,6 +132,10 @@
         return mPasskeyAgentRequestData;
     }
 
+    /* package */ HashMap<String, Integer> getAuthorizationAgentRequestData() {
+        return mAuthorizationAgentRequestData;
+    }
+
     /* package */ void start() {
 
         if (!isEventLoopRunningNative()) {
@@ -518,27 +524,29 @@
         mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM);
     }
 
-    private boolean onAgentAuthorize(String objectPath, String deviceUuid) {
+    private void  onAgentAuthorize(String objectPath, String deviceUuid, int nativeData) {
         String address = mBluetoothService.getAddressFromObjectPath(objectPath);
         if (address == null) {
             Log.e(TAG, "Unable to get device address in onAuthAgentAuthorize");
-            return false;
+            return;
         }
 
         boolean authorized = false;
         ParcelUuid uuid = ParcelUuid.fromString(deviceUuid);
         BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
 
+        BluetoothDevice device = mAdapter.getRemoteDevice(address);
+        mAuthorizationAgentRequestData.put(address, new Integer(nativeData));
+
         // Bluez sends the UUID of the local service being accessed, _not_ the
         // remote service
         if (mBluetoothService.isEnabled() &&
                 (BluetoothUuid.isAudioSource(uuid) || BluetoothUuid.isAvrcpTarget(uuid)
                         || BluetoothUuid.isAdvAudioDist(uuid)) &&
                         !isOtherSinkInNonDisconnectingState(address)) {
-            BluetoothDevice device = mAdapter.getRemoteDevice(address);
             authorized = a2dp.getSinkPriority(device) > BluetoothA2dp.PRIORITY_OFF;
             if (authorized) {
-                Log.i(TAG, "Allowing incoming A2DP / AVRCP connection from " + address);
+                Log.i(TAG, "First check pass for incoming A2DP / AVRCP connection from " + address);
                 // Some headsets try to connect AVCTP before AVDTP - against the recommendation
                 // If AVCTP connection fails, we get stuck in IncomingA2DP state in the state
                 // machine.  We don't handle AVCTP signals currently. We only send
@@ -546,6 +554,8 @@
                 // some cases. For now, just don't move to incoming state in this case.
                 if (!BluetoothUuid.isAvrcpTarget(uuid)) {
                     mBluetoothService.notifyIncomingA2dpConnection(address);
+                } else {
+                    a2dp.allowIncomingConnect(device, authorized);
                 }
             } else {
                 Log.i(TAG, "Rejecting incoming A2DP / AVRCP connection from " + address);
@@ -554,7 +564,7 @@
             Log.i(TAG, "Rejecting incoming " + deviceUuid + " connection from " + address);
         }
         log("onAgentAuthorize(" + objectPath + ", " + deviceUuid + ") = " + authorized);
-        return authorized;
+        if (!authorized) a2dp.allowIncomingConnect(device, authorized);
     }
 
     private boolean onAgentOutOfBandDataAvailable(String objectPath) {
diff --git a/core/java/android/server/BluetoothService.java b/core/java/android/server/BluetoothService.java
old mode 100644
new mode 100755
index 4d4d309..643581e
--- a/core/java/android/server/BluetoothService.java
+++ b/core/java/android/server/BluetoothService.java
@@ -27,8 +27,8 @@
 import android.bluetooth.BluetoothAdapter;
 import android.bluetooth.BluetoothClass;
 import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothHeadset;
 import android.bluetooth.BluetoothDeviceProfileState;
+import android.bluetooth.BluetoothHeadset;
 import android.bluetooth.BluetoothProfileState;
 import android.bluetooth.BluetoothSocket;
 import android.bluetooth.BluetoothUuid;
@@ -67,6 +67,7 @@
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.PrintWriter;
+import java.io.RandomAccessFile;
 import java.io.UnsupportedEncodingException;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -103,7 +104,6 @@
     private static final int MESSAGE_REGISTER_SDP_RECORDS = 1;
     private static final int MESSAGE_FINISH_DISABLE = 2;
     private static final int MESSAGE_UUID_INTENT = 3;
-    private static final int MESSAGE_DISCOVERABLE_TIMEOUT = 4;
     private static final int MESSAGE_AUTO_PAIRING_FAILURE_ATTEMPT_DELAY = 5;
 
     // The time (in millisecs) to delay the pairing attempt after the first
@@ -143,6 +143,11 @@
     private static String mDockAddress;
     private String mDockPin;
 
+    private static final String INCOMING_CONNECTION_FILE =
+      "/data/misc/bluetooth/incoming_connection.conf";
+    private HashMap<String, Pair<Integer, String>> mIncomingConnections;
+
+
     private static class RemoteService {
         public String address;
         public ParcelUuid uuid;
@@ -210,6 +215,7 @@
 
         filter.addAction(Intent.ACTION_DOCK_EVENT);
         mContext.registerReceiver(mReceiver, filter);
+        mIncomingConnections = new HashMap<String, Pair<Integer, String>>();
     }
 
     public static synchronized String readDockBluetoothAddress() {
@@ -501,15 +507,6 @@
                     makeServiceChannelCallbacks(address);
                 }
                 break;
-            case MESSAGE_DISCOVERABLE_TIMEOUT:
-                int mode = msg.arg1;
-                if (isEnabledInternal()) {
-                    // TODO: Switch back to the previous scan mode
-                    // This is ok for now, because we only use
-                    // CONNECTABLE and CONNECTABLE_DISCOVERABLE
-                    setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE, -1);
-                }
-                break;
             case MESSAGE_AUTO_PAIRING_FAILURE_ATTEMPT_DELAY:
                 address = (String)msg.obj;
                 if (address != null) {
@@ -743,8 +740,6 @@
 
             if (state == BluetoothDevice.BOND_BONDED) {
                 addProfileState(address);
-            } else if (state == BluetoothDevice.BOND_NONE) {
-                removeProfileState(address);
             }
 
             if (DBG) log(address + " bond state " + oldState + " -> " + state + " (" +
@@ -1078,21 +1073,17 @@
 
         switch (mode) {
         case BluetoothAdapter.SCAN_MODE_NONE:
-            mHandler.removeMessages(MESSAGE_DISCOVERABLE_TIMEOUT);
             pairable = false;
             discoverable = false;
             break;
         case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
-            mHandler.removeMessages(MESSAGE_DISCOVERABLE_TIMEOUT);
             pairable = true;
             discoverable = false;
             break;
         case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
-            mHandler.removeMessages(MESSAGE_DISCOVERABLE_TIMEOUT);
+            setDiscoverableTimeout(duration);
             pairable = true;
             discoverable = true;
-            Message msg = mHandler.obtainMessage(MESSAGE_DISCOVERABLE_TIMEOUT);
-            mHandler.sendMessageDelayed(msg, duration * 1000);
             if (DBG) Log.d(TAG, "BT Discoverable for " + duration + " seconds");
             break;
         default:
@@ -1326,6 +1317,8 @@
     }
 
     public synchronized boolean removeBondInternal(String address) {
+        // Unset the trusted device state and then unpair
+        setTrust(address, false);
         return removeDeviceNative(getObjectPathFromAddress(address));
     }
 
@@ -1351,7 +1344,7 @@
     }
 
     /*package*/ synchronized boolean setBondState(String address, int state, int reason) {
-        mBondState.setBondState(address.toUpperCase(), state);
+        mBondState.setBondState(address.toUpperCase(), state, reason);
         return true;
     }
 
@@ -2175,10 +2168,6 @@
         return state;
     }
 
-    private void removeProfileState(String address) {
-        mDeviceProfileState.remove(address);
-    }
-
     private void initProfileState() {
         String []bonds = null;
         String val = getPropertyInternal("Devices");
@@ -2227,6 +2216,11 @@
         mA2dpService = a2dpService;
     }
 
+    /*package*/ Integer getAuthorizationAgentRequestData(String address) {
+        Integer data = mEventLoop.getAuthorizationAgentRequestData().remove(address);
+        return data;
+    }
+
     public void sendProfileStateMessage(int profile, int cmd) {
         Message msg = new Message();
         msg.what = cmd;
@@ -2237,6 +2231,116 @@
         }
     }
 
+    private void createIncomingConnectionStateFile() {
+        File f = new File(INCOMING_CONNECTION_FILE);
+        if (!f.exists()) {
+            try {
+                f.createNewFile();
+            } catch (IOException e) {
+                Log.e(TAG, "IOException: cannot create file");
+            }
+        }
+    }
+
+    /** @hide */
+    public Pair<Integer, String> getIncomingState(String address) {
+        if (mIncomingConnections.isEmpty()) {
+            createIncomingConnectionStateFile();
+            readIncomingConnectionState();
+        }
+        return mIncomingConnections.get(address);
+    }
+
+    private void readIncomingConnectionState() {
+        synchronized(mIncomingConnections) {
+            FileInputStream fstream = null;
+            try {
+              fstream = new FileInputStream(INCOMING_CONNECTION_FILE);
+              DataInputStream in = new DataInputStream(fstream);
+              BufferedReader file = new BufferedReader(new InputStreamReader(in));
+              String line;
+              while((line = file.readLine()) != null) {
+                  line = line.trim();
+                  if (line.length() == 0) continue;
+                  String[] value = line.split(",");
+                  if (value != null && value.length == 3) {
+                      Integer val1 = Integer.parseInt(value[1]);
+                      Pair<Integer, String> val = new Pair(val1, value[2]);
+                      mIncomingConnections.put(value[0], val);
+                  }
+              }
+            } catch (FileNotFoundException e) {
+                log("FileNotFoundException: readIncomingConnectionState" + e.toString());
+            } catch (IOException e) {
+                log("IOException: readIncomingConnectionState" + e.toString());
+            } finally {
+                if (fstream != null) {
+                    try {
+                        fstream.close();
+                    } catch (IOException e) {
+                        // Ignore
+                    }
+                }
+            }
+        }
+    }
+
+    private void truncateIncomingConnectionFile() {
+        RandomAccessFile r = null;
+        try {
+            r = new RandomAccessFile(INCOMING_CONNECTION_FILE, "rw");
+            r.setLength(0);
+        } catch (FileNotFoundException e) {
+            log("FileNotFoundException: truncateIncomingConnectionState" + e.toString());
+        } catch (IOException e) {
+            log("IOException: truncateIncomingConnectionState" + e.toString());
+        } finally {
+            if (r != null) {
+                try {
+                    r.close();
+                } catch (IOException e) {
+                    // ignore
+                 }
+            }
+        }
+    }
+
+    /** @hide */
+    public void writeIncomingConnectionState(String address, Pair<Integer, String> data) {
+        synchronized(mIncomingConnections) {
+            mIncomingConnections.put(address, data);
+
+            truncateIncomingConnectionFile();
+            BufferedWriter out = null;
+            StringBuilder value = new StringBuilder();
+            try {
+                out = new BufferedWriter(new FileWriter(INCOMING_CONNECTION_FILE, true));
+                for (String devAddress: mIncomingConnections.keySet()) {
+                  Pair<Integer, String> val = mIncomingConnections.get(devAddress);
+                  value.append(devAddress);
+                  value.append(",");
+                  value.append(val.first.toString());
+                  value.append(",");
+                  value.append(val.second);
+                  value.append("\n");
+                }
+                out.write(value.toString());
+            } catch (FileNotFoundException e) {
+                log("FileNotFoundException: writeIncomingConnectionState" + e.toString());
+            } catch (IOException e) {
+                log("IOException: writeIncomingConnectionState" + e.toString());
+            } finally {
+                if (out != null) {
+                    try {
+                        out.close();
+                    } catch (IOException e) {
+                        // Ignore
+                    }
+                }
+            }
+        }
+    }
+
     private static void log(String msg) {
         Log.d(TAG, msg);
     }
@@ -2287,4 +2391,5 @@
             short channel);
     private native boolean removeServiceRecordNative(int handle);
     private native boolean setLinkTimeoutNative(String path, int num_slots);
+    native boolean setAuthorizationNative(String address, boolean value, int data);
 }
diff --git a/core/java/android/speech/RecognitionService.java b/core/java/android/speech/RecognitionService.java
index 75a5ed5..32b2d8f 100644
--- a/core/java/android/speech/RecognitionService.java
+++ b/core/java/android/speech/RecognitionService.java
@@ -68,6 +68,8 @@
 
     private static final int MSG_CANCEL = 3;
 
+    private static final int MSG_RESET = 4;
+
     private final Handler mHandler = new Handler() {
         @Override
         public void handleMessage(Message msg) {
@@ -81,6 +83,10 @@
                     break;
                 case MSG_CANCEL:
                     dispatchCancel((IRecognitionListener) msg.obj);
+                    break;
+                case MSG_RESET:
+                    dispatchClearCallback();
+                    break;
             }
         }
     };
@@ -128,6 +134,10 @@
         }
     }
 
+    private void dispatchClearCallback() {
+        mCurrentCallback = null;
+    }
+
     private class StartListeningArgs {
         public final Intent mIntent;
 
@@ -241,7 +251,7 @@
          * @param error code is defined in {@link SpeechRecognizer}
          */
         public void error(int error) throws RemoteException {
-            mCurrentCallback = null;
+            Message.obtain(mHandler, MSG_RESET).sendToTarget();
             mListener.onError(error);
         }
 
@@ -278,7 +288,7 @@
          *        {@link SpeechRecognizer#RESULTS_RECOGNITION} as a parameter
          */
         public void results(Bundle results) throws RemoteException {
-            mCurrentCallback = null;
+            Message.obtain(mHandler, MSG_RESET).sendToTarget();
             mListener.onResults(results);
         }
 
diff --git a/core/java/android/text/Layout.java b/core/java/android/text/Layout.java
index 4e197cd..b62aa40 100755
--- a/core/java/android/text/Layout.java
+++ b/core/java/android/text/Layout.java
@@ -1154,7 +1154,7 @@
         if (h2 < 0.5f)
             h2 = 0.5f;
 
-        if (h1 == h2) {
+        if (Float.compare(h1, h2) == 0) {
             dest.moveTo(h1, top);
             dest.lineTo(h1, bottom);
         } else {
diff --git a/core/java/android/text/TextUtils.java b/core/java/android/text/TextUtils.java
index 8675d05..0d7aa02 100644
--- a/core/java/android/text/TextUtils.java
+++ b/core/java/android/text/TextUtils.java
@@ -627,10 +627,16 @@
         public  CharSequence createFromParcel(Parcel p) {
             int kind = p.readInt();
 
-            if (kind == 1)
-                return p.readString();
+            String string = p.readString();
+            if (string == null) {
+                return null;
+            }
 
-            SpannableString sp = new SpannableString(p.readString());
+            if (kind == 1) {
+                return string;
+            }
+
+            SpannableString sp = new SpannableString(string);
 
             while (true) {
                 kind = p.readInt();
diff --git a/core/java/android/text/method/MultiTapKeyListener.java b/core/java/android/text/method/MultiTapKeyListener.java
index 6d94788..2a739fa 100644
--- a/core/java/android/text/method/MultiTapKeyListener.java
+++ b/core/java/android/text/method/MultiTapKeyListener.java
@@ -116,7 +116,7 @@
                     content.replace(selStart, selEnd,
                                     String.valueOf(current).toUpperCase());
                     removeTimeouts(content);
-                    Timeout t = new Timeout(content);
+                    new Timeout(content); // for its side effects
 
                     return true;
                 }
@@ -124,7 +124,7 @@
                     content.replace(selStart, selEnd,
                                     String.valueOf(current).toLowerCase());
                     removeTimeouts(content);
-                    Timeout t = new Timeout(content);
+                    new Timeout(content); // for its side effects
 
                     return true;
                 }
@@ -140,7 +140,7 @@
 
                     content.replace(selStart, selEnd, val, ix, ix + 1);
                     removeTimeouts(content);
-                    Timeout t = new Timeout(content);
+                    new Timeout(content); // for its side effects
 
                     return true;
                 }
@@ -206,7 +206,7 @@
             }
 
             removeTimeouts(content);
-            Timeout t = new Timeout(content);
+            new Timeout(content); // for its side effects
 
             // Set up the callback so we can remove the timeout if the
             // cursor moves.
diff --git a/core/java/android/text/style/DrawableMarginSpan.java b/core/java/android/text/style/DrawableMarginSpan.java
index 3c471a5..c2564d5 100644
--- a/core/java/android/text/style/DrawableMarginSpan.java
+++ b/core/java/android/text/style/DrawableMarginSpan.java
@@ -50,9 +50,6 @@
         int dw = mDrawable.getIntrinsicWidth();
         int dh = mDrawable.getIntrinsicHeight();
 
-        if (dir < 0)
-            x -= dw;
-
         // XXX What to do about Paint?
         mDrawable.setBounds(ix, itop, ix+dw, itop+dh);
         mDrawable.draw(c);
diff --git a/core/java/android/util/SparseArray.java b/core/java/android/util/SparseArray.java
index 1c8b330..4c13460 100644
--- a/core/java/android/util/SparseArray.java
+++ b/core/java/android/util/SparseArray.java
@@ -90,6 +90,17 @@
         delete(key);
     }
 
+    /**
+     * Removes the mapping at the specified index.
+     * @hide
+     */
+    public void removeAt(int index) {
+        if (mValues[index] != DELETED) {
+            mValues[index] = DELETED;
+            mGarbage = true;
+        }
+    }
+    
     private void gc() {
         // Log.e("SparseArray", "gc start with " + mSize);
 
diff --git a/core/java/android/view/GestureDetector.java b/core/java/android/view/GestureDetector.java
old mode 100644
new mode 100755
index c1e1049..79b3d42
--- a/core/java/android/view/GestureDetector.java
+++ b/core/java/android/view/GestureDetector.java
@@ -193,10 +193,8 @@
         }
     }
 
-    // TODO: ViewConfiguration
-    private int mBiggerTouchSlopSquare = 20 * 20;
-
     private int mTouchSlopSquare;
+    private int mLargeTouchSlopSquare;
     private int mDoubleTapSlopSquare;
     private int mMinimumFlingVelocity;
     private int mMaximumFlingVelocity;
@@ -384,10 +382,11 @@
         mIgnoreMultitouch = ignoreMultitouch;
 
         // Fallback to support pre-donuts releases
-        int touchSlop, doubleTapSlop;
+        int touchSlop, largeTouchSlop, doubleTapSlop;
         if (context == null) {
             //noinspection deprecation
             touchSlop = ViewConfiguration.getTouchSlop();
+            largeTouchSlop = touchSlop + 2;
             doubleTapSlop = ViewConfiguration.getDoubleTapSlop();
             //noinspection deprecation
             mMinimumFlingVelocity = ViewConfiguration.getMinimumFlingVelocity();
@@ -395,11 +394,13 @@
         } else {
             final ViewConfiguration configuration = ViewConfiguration.get(context);
             touchSlop = configuration.getScaledTouchSlop();
+            largeTouchSlop = configuration.getScaledLargeTouchSlop();
             doubleTapSlop = configuration.getScaledDoubleTapSlop();
             mMinimumFlingVelocity = configuration.getScaledMinimumFlingVelocity();
             mMaximumFlingVelocity = configuration.getScaledMaximumFlingVelocity();
         }
         mTouchSlopSquare = touchSlop * touchSlop;
+        mLargeTouchSlopSquare = largeTouchSlop * largeTouchSlop;
         mDoubleTapSlopSquare = doubleTapSlop * doubleTapSlop;
     }
 
@@ -534,7 +535,7 @@
                     mHandler.removeMessages(SHOW_PRESS);
                     mHandler.removeMessages(LONG_PRESS);
                 }
-                if (distance > mBiggerTouchSlopSquare) {
+                if (distance > mLargeTouchSlopSquare) {
                     mAlwaysInBiggerTapRegion = false;
                 }
             } else if ((Math.abs(scrollX) >= 1) || (Math.abs(scrollY) >= 1)) {
diff --git a/core/java/android/view/ViewConfiguration.java b/core/java/android/view/ViewConfiguration.java
old mode 100644
new mode 100755
index 924c9d4..5397449
--- a/core/java/android/view/ViewConfiguration.java
+++ b/core/java/android/view/ViewConfiguration.java
@@ -102,6 +102,12 @@
     private static final int TOUCH_SLOP = 16;
     
     /**
+     * Distance a touch can wander before we think the user is the first touch
+     * in a sequence of double tap
+     */
+    private static final int LARGE_TOUCH_SLOP = 18;
+
+    /**
      * Distance a touch can wander before we think the user is attempting a paged scroll
      * (in dips)
      */
@@ -156,6 +162,7 @@
     private final int mMaximumFlingVelocity;
     private final int mScrollbarSize;
     private final int mTouchSlop;
+    private final int mLargeTouchSlop;
     private final int mPagingTouchSlop;
     private final int mDoubleTapSlop;
     private final int mWindowTouchSlop;
@@ -177,6 +184,7 @@
         mMaximumFlingVelocity = MAXIMUM_FLING_VELOCITY;
         mScrollbarSize = SCROLL_BAR_SIZE;
         mTouchSlop = TOUCH_SLOP;
+        mLargeTouchSlop = LARGE_TOUCH_SLOP;
         mPagingTouchSlop = PAGING_TOUCH_SLOP;
         mDoubleTapSlop = DOUBLE_TAP_SLOP;
         mWindowTouchSlop = WINDOW_TOUCH_SLOP;
@@ -206,6 +214,7 @@
         mMaximumFlingVelocity = (int) (density * MAXIMUM_FLING_VELOCITY + 0.5f);
         mScrollbarSize = (int) (density * SCROLL_BAR_SIZE + 0.5f);
         mTouchSlop = (int) (density * TOUCH_SLOP + 0.5f);
+        mLargeTouchSlop =  (int) (density * LARGE_TOUCH_SLOP + 0.5f);
         mPagingTouchSlop = (int) (density * PAGING_TOUCH_SLOP + 0.5f);
         mDoubleTapSlop = (int) (density * DOUBLE_TAP_SLOP + 0.5f);
         mWindowTouchSlop = (int) (density * WINDOW_TOUCH_SLOP + 0.5f);
@@ -367,6 +376,14 @@
     }
     
     /**
+     * @return Distance a touch can wander before we think the user is the first touch
+     *         in a sequence of double tap
+     */
+    public int getScaledLargeTouchSlop() {
+        return mLargeTouchSlop;
+    }
+
+    /**
      * @return Distance a touch can wander before we think the user is scrolling a full page
      *         in dips
      */
diff --git a/core/java/android/view/ViewRoot.java b/core/java/android/view/ViewRoot.java
index ccaef40..afec1c3 100644
--- a/core/java/android/view/ViewRoot.java
+++ b/core/java/android/view/ViewRoot.java
@@ -176,6 +176,7 @@
     private final Surface mSurface = new Surface();
 
     boolean mAdded;
+    private boolean mAttached;
     boolean mAddedTouchMode;
 
     /*package*/ int mAddNesting;
@@ -762,7 +763,10 @@
             attachInfo.mKeepScreenOn = false;
             viewVisibilityChanged = false;
             mLastConfiguration.setTo(host.getResources().getConfiguration());
-            host.dispatchAttachedToWindow(attachInfo, 0);
+            if (!mAttached) {
+                host.dispatchAttachedToWindow(attachInfo, 0);
+                mAttached = true;
+            }
             //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
 
         } else {
@@ -1743,8 +1747,9 @@
     void dispatchDetachedFromWindow() {
         if (Config.LOGV) Log.v(TAG, "Detaching in " + this + " of " + mSurface);
 
-        if (mView != null) {
+        if (mView != null && mAttached) {
             mView.dispatchDetachedFromWindow();
+            mAttached = false;
         }
 
         mView = null;
diff --git a/core/java/android/webkit/FrameLoader.java b/core/java/android/webkit/FrameLoader.java
index 021b53c..4bc12d4 100644
--- a/core/java/android/webkit/FrameLoader.java
+++ b/core/java/android/webkit/FrameLoader.java
@@ -186,7 +186,8 @@
                                 settings.getAllowFileAccess())).sendToTarget();
             }
             return true;
-        } else if (URLUtil.isContentUrl(url)) {
+        } else if (settings.getAllowContentAccess() &&
+                   URLUtil.isContentUrl(url)) {
             // Send the raw url to the ContentLoader because it will do a
             // permission check and the url has to match.
             if (loadListener.isSynchronous()) {
diff --git a/core/java/android/webkit/WebSettings.java b/core/java/android/webkit/WebSettings.java
index 4d70e7c..a82b7b8 100644
--- a/core/java/android/webkit/WebSettings.java
+++ b/core/java/android/webkit/WebSettings.java
@@ -206,6 +206,7 @@
     private boolean         mSupportZoom = true;
     private boolean         mBuiltInZoomControls = false;
     private boolean         mAllowFileAccess = true;
+    private boolean         mAllowContentAccess = true;
     private boolean         mLoadWithOverviewMode = false;
     private boolean         mUseWebViewBackgroundOverscrollBackground = true;
 
@@ -458,7 +459,9 @@
     
     /**
      * Enable or disable file access within WebView. File access is enabled by
-     * default.
+     * default. Note that this enables or disables file system access only.
+     * Assets and resources are still accessible using file:///android_asset and
+     * file:///android_res.
      */
     public void setAllowFileAccess(boolean allow) {
         mAllowFileAccess = allow;
@@ -472,6 +475,24 @@
     }
 
     /**
+     * Enable or disable content url access within WebView.  Content url access
+     * allows WebView to load content from a content provider installed in the
+     * system.  The default is enabled.
+     * @hide
+     */
+    public void setAllowContentAccess(boolean allow) {
+        mAllowContentAccess = allow;
+    }
+
+    /**
+     * Returns true if this WebView supports content url access.
+     * @hide
+     */
+    public boolean getAllowContentAccess() {
+        return mAllowContentAccess;
+    }
+
+    /**
      * Set whether the WebView loads a page with overview mode.
      */
     public void setLoadWithOverviewMode(boolean overview) {
@@ -1031,7 +1052,7 @@
      */
     @Deprecated
     public synchronized void setPluginsEnabled(boolean flag) {
-        setPluginState(PluginState.ON);
+        setPluginState(flag ? PluginState.ON : PluginState.OFF);
     }
 
     /**
diff --git a/core/java/android/widget/DatePicker.java b/core/java/android/widget/DatePicker.java
index a371290..595b487 100644
--- a/core/java/android/widget/DatePicker.java
+++ b/core/java/android/widget/DatePicker.java
@@ -22,6 +22,7 @@
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.text.format.DateFormat;
+import android.text.format.DateUtils;
 import android.util.AttributeSet;
 import android.util.SparseArray;
 import android.view.LayoutInflater;
@@ -33,6 +34,7 @@
 import java.text.DateFormatSymbols;
 import java.text.SimpleDateFormat;
 import java.util.Calendar;
+import java.util.Locale;
 
 /**
  * A view for selecting a month / year / day based on a calendar like layout.
@@ -47,7 +49,10 @@
 
     private static final int DEFAULT_START_YEAR = 1900;
     private static final int DEFAULT_END_YEAR = 2100;
-    
+
+    // This ignores Undecimber, but we only support real Gregorian calendars.
+    private static final int NUMBER_OF_MONTHS = 12;
+
     /* UI Components */
     private final NumberPicker mDayPicker;
     private final NumberPicker mMonthPicker;
@@ -62,6 +67,10 @@
     private int mMonth;
     private int mYear;
 
+    private Object mMonthUpdateLock = new Object();
+    private volatile Locale mMonthLocale;
+    private String[] mShortMonths;
+
     /**
      * The callback used to indicate the user changes the date.
      */
@@ -102,8 +111,7 @@
         });
         mMonthPicker = (NumberPicker) findViewById(R.id.month);
         mMonthPicker.setFormatter(NumberPicker.TWO_DIGIT_FORMATTER);
-        DateFormatSymbols dfs = new DateFormatSymbols();
-        String[] months = dfs.getShortMonths();
+        final String[] months = getShortMonths();
 
         /*
          * If the user is in a locale where the month names are numeric,
@@ -114,9 +122,9 @@
             for (int i = 0; i < months.length; i++) {
                 months[i] = String.valueOf(i + 1);
             }
-            mMonthPicker.setRange(1, 12);
+            mMonthPicker.setRange(1, NUMBER_OF_MONTHS);
         } else {
-            mMonthPicker.setRange(1, 12, months);
+            mMonthPicker.setRange(1, NUMBER_OF_MONTHS, months);
         }
 
         mMonthPicker.setSpeed(200);
@@ -246,11 +254,30 @@
             mMonth = monthOfYear;
             mDay = dayOfMonth;
             updateSpinners();
-            reorderPickers(new DateFormatSymbols().getShortMonths());
+            reorderPickers(getShortMonths());
             notifyDateChanged();
         }
     }
 
+    private String[] getShortMonths() {
+        final Locale currentLocale = Locale.getDefault();
+        if (currentLocale.equals(mMonthLocale) && mShortMonths != null) {
+            return mShortMonths;
+        } else {
+            synchronized (mMonthUpdateLock) {
+                if (!currentLocale.equals(mMonthLocale)) {
+                    mShortMonths = new String[NUMBER_OF_MONTHS];
+                    for (int i = 0; i < NUMBER_OF_MONTHS; i++) {
+                        mShortMonths[i] = DateUtils.getMonthString(Calendar.JANUARY + i,
+                                DateUtils.LENGTH_MEDIUM);
+                    }
+                    mMonthLocale = currentLocale;
+                }
+            }
+            return mShortMonths;
+        }
+    }
+
     private static class SavedState extends BaseSavedState {
 
         private final int mYear;
diff --git a/core/java/android/widget/PopupWindow.java b/core/java/android/widget/PopupWindow.java
index 76755de..66524ab 100644
--- a/core/java/android/widget/PopupWindow.java
+++ b/core/java/android/widget/PopupWindow.java
@@ -1421,6 +1421,10 @@
         @Override
         public boolean dispatchKeyEvent(KeyEvent event) {
             if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
+                if (getKeyDispatcherState() == null) {
+                    return super.dispatchKeyEvent(event);
+                }
+
                 if (event.getAction() == KeyEvent.ACTION_DOWN
                         && event.getRepeatCount() == 0) {
                     getKeyDispatcherState().startTracking(event, this);
diff --git a/core/java/android/widget/ScrollView.java b/core/java/android/widget/ScrollView.java
index de38d05d..b1e1fbc 100644
--- a/core/java/android/widget/ScrollView.java
+++ b/core/java/android/widget/ScrollView.java
@@ -832,7 +832,7 @@
             int count = getChildCount();
             if (count > 0) {
                 View view = getChildAt(count - 1);
-                mTempRect.bottom = view.getBottom();
+                mTempRect.bottom = view.getBottom() + mPaddingBottom;
                 mTempRect.top = mTempRect.bottom - height;
             }
         }
@@ -912,9 +912,7 @@
             } else if (direction == View.FOCUS_DOWN) {
                 if (getChildCount() > 0) {
                     int daBottom = getChildAt(0).getBottom();
-    
-                    int screenBottom = getScrollY() + getHeight();
-    
+                    int screenBottom = getScrollY() + getHeight() - mPaddingBottom;
                     if (daBottom - screenBottom < maxJump) {
                         scrollDelta = daBottom - screenBottom;
                     }
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 97b05af..68600cf 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -301,6 +301,8 @@
     // Set when this TextView gained focus with some text selected. Will start selection mode.
     private boolean mCreatedWithASelection = false;
 
+    private boolean mNoContextMenuOnUp = false;
+
     /*
      * Kick-start the font cache for the zygote process (to pay the cost of
      * initializing freetype for our default font only once).
@@ -6798,8 +6800,9 @@
                 // Restore previous selection
                 Selection.setSelection((Spannable)mText, prevStart, prevEnd);
 
-                // Tapping inside the selection displays the cut/copy/paste context menu
-                showContextMenu();
+                // Tapping inside the selection displays the cut/copy/paste context menu, unless
+                // this is a double tap that should simply trigger text selection mode.
+                if (!mNoContextMenuOnUp) showContextMenu();
             } else {
                 // Tapping outside stops selection mode, if any
                 stopTextSelectionMode();
@@ -6857,7 +6860,7 @@
             mScrolled = false;
         }
 
-        final boolean superResult = super.onTouchEvent(event);
+        boolean result = super.onTouchEvent(event);
 
         /*
          * Don't handle the release after a long press, because it will
@@ -6866,11 +6869,8 @@
          */
         if (mEatTouchRelease && action == MotionEvent.ACTION_UP) {
             mEatTouchRelease = false;
-            return superResult;
-        }
-
-        if ((mMovement != null || onCheckIsTextEditor()) && isEnabled() &&
-                mText instanceof Spannable && mLayout != null) {
+        } else if ((mMovement != null || onCheckIsTextEditor()) && mText instanceof Spannable &&
+                mLayout != null) {
             boolean handled = false;
 
             // Save previous selection, in case this event is used to show the IME.
@@ -6911,12 +6911,14 @@
                 }
             }
 
-            if (handled) {
-                return true;
-            }
+            if (handled) result = true;
         }
 
-        return superResult;
+        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
+            mNoContextMenuOnUp = false;
+        }
+
+        return result;
     }
 
     private void prepareCursorControllers() {
@@ -8200,9 +8202,8 @@
                             final int slopSquared = doubleTapSlop * doubleTapSlop;
                             if (distanceSquared < slopSquared) {
                                 startTextSelectionMode();
-                                // Hacky: onTapUpEvent will open a context menu with cut/copy
-                                // Prevent this by hiding handles which will be revived instead.
-                                hide();
+                                // prevents onTapUpEvent from opening a context menu with cut/copy
+                                mNoContextMenuOnUp = true;
                             }
                         }
                         mPreviousTapPositionX = x;
diff --git a/core/java/com/android/internal/app/ResolverActivity.java b/core/java/com/android/internal/app/ResolverActivity.java
index 841de06..fb2a72b 100644
--- a/core/java/com/android/internal/app/ResolverActivity.java
+++ b/core/java/com/android/internal/app/ResolverActivity.java
@@ -68,7 +68,7 @@
 
     protected void onCreate(Bundle savedInstanceState, Intent intent,
             CharSequence title, Intent[] initialIntents, List<ResolveInfo> rList,
-            boolean alwaysUseOption) {
+            boolean alwaysUseOption, boolean alwaysChoose) {
         super.onCreate(savedInstanceState);
         mPm = getPackageManager();
         intent.setComponent(null);
@@ -90,9 +90,10 @@
             mClearDefaultHint.setVisibility(View.GONE);
         }
         mAdapter = new ResolveListAdapter(this, intent, initialIntents, rList);
-        if (mAdapter.getCount() > 1) {
+        int count = mAdapter.getCount();
+        if (count > 1 || (count == 1 && alwaysChoose)) {
             ap.mAdapter = mAdapter;
-        } else if (mAdapter.getCount() == 1) {
+        } else if (count == 1) {
             startActivity(mAdapter.intentForPosition(0));
             finish();
             return;
@@ -103,11 +104,22 @@
         setupAlert();
     }
 
+    protected void onCreate(Bundle savedInstanceState, Intent intent,
+            CharSequence title, Intent[] initialIntents, List<ResolveInfo> rList,
+            boolean alwaysUseOption) {
+        onCreate(savedInstanceState, intent, title, initialIntents, rList, alwaysUseOption, false);
+      }
+
     public void onClick(DialogInterface dialog, int which) {
         ResolveInfo ri = mAdapter.resolveInfoForPosition(which);
         Intent intent = mAdapter.intentForPosition(which);
+        boolean alwaysCheck = (mAlwaysCheck != null && mAlwaysCheck.isChecked());
+        onIntentSelected(ri, intent, alwaysCheck);
+        finish();
+    }
 
-        if ((mAlwaysCheck != null) && mAlwaysCheck.isChecked()) {
+    protected void onIntentSelected(ResolveInfo ri, Intent intent, boolean alwaysCheck) {
+        if (alwaysCheck) {
             // Build a reasonable intent filter, based on what matched.
             IntentFilter filter = new IntentFilter();
 
@@ -190,7 +202,6 @@
         if (intent != null) {
             startActivity(intent);
         }
-        finish();
     }
 
     private final class DisplayResolveInfo {
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index 9ec9610..7220983 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -68,7 +68,7 @@
     private static final int MAGIC = 0xBA757475; // 'BATSTATS' 
 
     // Current on-disk Parcel version
-    private static final int VERSION = 52;
+    private static final int VERSION = 53;
 
     // Maximum number of items we will record in the history.
     private static final int MAX_HISTORY_ITEMS = 2000;
@@ -235,6 +235,12 @@
     int mDischargeCurrentLevel;
     int mLowDischargeAmountSinceCharge;
     int mHighDischargeAmountSinceCharge;
+    int mDischargeScreenOnUnplugLevel;
+    int mDischargeScreenOffUnplugLevel;
+    int mDischargeAmountScreenOn;
+    int mDischargeAmountScreenOnSinceCharge;
+    int mDischargeAmountScreenOff;
+    int mDischargeAmountScreenOffSinceCharge;
 
     long mLastWriteTime = 0; // Milliseconds
 
@@ -1567,6 +1573,11 @@
             // Fake a wake lock, so we consider the device waked as long
             // as the screen is on.
             noteStartWakeLocked(-1, -1, "dummy", WAKE_TYPE_PARTIAL);
+            
+            // Update discharge amounts.
+            if (mOnBatteryInternal) {
+                updateDischargeScreenLevels(false, true);
+            }
         }
     }
     
@@ -1583,6 +1594,11 @@
             }
 
             noteStopWakeLocked(-1, -1, "dummy", WAKE_TYPE_PARTIAL);
+            
+            // Update discharge amounts.
+            if (mOnBatteryInternal) {
+                updateDischargeScreenLevels(true, false);
+            }
         }
     }
     
@@ -3899,8 +3915,7 @@
         mDischargeStartLevel = 0;
         mDischargeUnplugLevel = 0;
         mDischargeCurrentLevel = 0;
-        mLowDischargeAmountSinceCharge = 0;
-        mHighDischargeAmountSinceCharge = 0;
+        initDischarge();
     }
 
     public BatteryStatsImpl(Parcel p) {
@@ -3970,6 +3985,15 @@
         mUnpluggedBatteryUptime = getBatteryUptimeLocked(mUptimeStart);
         mUnpluggedBatteryRealtime = getBatteryRealtimeLocked(mRealtimeStart);
     }
+
+    void initDischarge() {
+        mLowDischargeAmountSinceCharge = 0;
+        mHighDischargeAmountSinceCharge = 0;
+        mDischargeAmountScreenOn = 0;
+        mDischargeAmountScreenOnSinceCharge = 0;
+        mDischargeAmountScreenOff = 0;
+        mDischargeAmountScreenOffSinceCharge = 0;
+    }
     
     public void resetAllStatsLocked() {
         mStartCount = 0;
@@ -4007,11 +4031,33 @@
             mKernelWakelockStats.clear();
         }
         
-        mLowDischargeAmountSinceCharge = 0;
-        mHighDischargeAmountSinceCharge = 0;
+        initDischarge();
 
         clearHistoryLocked();
     }
+
+    void updateDischargeScreenLevels(boolean oldScreenOn, boolean newScreenOn) {
+        if (oldScreenOn) {
+            int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
+            if (diff > 0) {
+                mDischargeAmountScreenOn += diff;
+                mDischargeAmountScreenOnSinceCharge += diff;
+            }
+        } else {
+            int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
+            if (diff > 0) {
+                mDischargeAmountScreenOff += diff;
+                mDischargeAmountScreenOffSinceCharge += diff;
+            }
+        }
+        if (newScreenOn) {
+            mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
+            mDischargeScreenOffUnplugLevel = 0;
+        } else {
+            mDischargeScreenOnUnplugLevel = 0;
+            mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
+        }
+    }
     
     void setOnBattery(boolean onBattery, int oldStatus, int level) {
         synchronized(this) {
@@ -4047,6 +4093,15 @@
                 mUnpluggedBatteryUptime = getBatteryUptimeLocked(uptime);
                 mUnpluggedBatteryRealtime = getBatteryRealtimeLocked(realtime);
                 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
+                if (mScreenOn) {
+                    mDischargeScreenOnUnplugLevel = level;
+                    mDischargeScreenOffUnplugLevel = 0;
+                } else {
+                    mDischargeScreenOnUnplugLevel = 0;
+                    mDischargeScreenOffUnplugLevel = level;
+                }
+                mDischargeAmountScreenOn = 0;
+                mDischargeAmountScreenOff = 0;
                 doUnplugLocked(mUnpluggedBatteryUptime, mUnpluggedBatteryRealtime);
             } else {
                 updateKernelWakelocksLocked();
@@ -4062,6 +4117,7 @@
                     mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
                     mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
                 }
+                updateDischargeScreenLevels(mScreenOn, mScreenOn);
                 doPlugLocked(getBatteryUptimeLocked(uptime), getBatteryRealtimeLocked(realtime));
             }
             if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
@@ -4350,6 +4406,50 @@
             return val;
         }
     }
+    
+    public int getDischargeAmountScreenOn() {
+        synchronized(this) {
+            int val = mDischargeAmountScreenOn;
+            if (mOnBattery && mScreenOn
+                    && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
+                val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
+            }
+            return val;
+        }
+    }
+
+    public int getDischargeAmountScreenOnSinceCharge() {
+        synchronized(this) {
+            int val = mDischargeAmountScreenOnSinceCharge;
+            if (mOnBattery && mScreenOn
+                    && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
+                val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
+            }
+            return val;
+        }
+    }
+
+    public int getDischargeAmountScreenOff() {
+        synchronized(this) {
+            int val = mDischargeAmountScreenOff;
+            if (mOnBattery && !mScreenOn
+                    && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
+                val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
+            }
+            return val;
+        }
+    }
+
+    public int getDischargeAmountScreenOffSinceCharge() {
+        synchronized(this) {
+            int val = mDischargeAmountScreenOffSinceCharge;
+            if (mOnBattery && !mScreenOn
+                    && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
+                val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
+            }
+            return val;
+        }
+    }
 
     @Override
     public int getCpuSpeedSteps() {
@@ -4608,7 +4708,7 @@
         mHistory = mHistoryEnd = mHistoryCache = null;
         mHistoryBaseTime = 0;
         long time;
-        while ((time=in.readLong()) >= 0) {
+        while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
             HistoryItem rec = new HistoryItem(time, in);
             addHistoryRecordLocked(rec);
             if (rec.time > mHistoryBaseTime) {
@@ -4656,7 +4756,9 @@
         mDischargeCurrentLevel = in.readInt();
         mLowDischargeAmountSinceCharge = in.readInt();
         mHighDischargeAmountSinceCharge = in.readInt();
-        
+        mDischargeAmountScreenOnSinceCharge = in.readInt();
+        mDischargeAmountScreenOffSinceCharge = in.readInt();
+
         mStartCount++;
         
         mScreenOn = false;
@@ -4851,6 +4953,8 @@
         out.writeInt(mDischargeCurrentLevel);
         out.writeInt(getLowDischargeAmountSinceCharge());
         out.writeInt(getHighDischargeAmountSinceCharge());
+        out.writeInt(getDischargeAmountScreenOnSinceCharge());
+        out.writeInt(getDischargeAmountScreenOffSinceCharge());
         
         mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL);
         for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
@@ -5090,6 +5194,10 @@
         mDischargeCurrentLevel = in.readInt();
         mLowDischargeAmountSinceCharge = in.readInt();
         mHighDischargeAmountSinceCharge = in.readInt();
+        mDischargeAmountScreenOn = in.readInt();
+        mDischargeAmountScreenOnSinceCharge = in.readInt();
+        mDischargeAmountScreenOff = in.readInt();
+        mDischargeAmountScreenOffSinceCharge = in.readInt();
         mLastWriteTime = in.readLong();
 
         mMobileDataRx[STATS_LAST] = in.readLong();
@@ -5191,6 +5299,10 @@
         out.writeInt(mDischargeCurrentLevel);
         out.writeInt(mLowDischargeAmountSinceCharge);
         out.writeInt(mHighDischargeAmountSinceCharge);
+        out.writeInt(mDischargeAmountScreenOn);
+        out.writeInt(mDischargeAmountScreenOnSinceCharge);
+        out.writeInt(mDischargeAmountScreenOff);
+        out.writeInt(mDischargeAmountScreenOffSinceCharge);
         out.writeLong(mLastWriteTime);
 
         out.writeLong(getMobileTcpBytesReceived(STATS_SINCE_UNPLUGGED));
diff --git a/core/java/com/android/internal/os/ZygoteInit.java b/core/java/com/android/internal/os/ZygoteInit.java
index f0e5517..060f858 100644
--- a/core/java/com/android/internal/os/ZygoteInit.java
+++ b/core/java/com/android/internal/os/ZygoteInit.java
@@ -511,7 +511,7 @@
         String args[] = {
             "--setuid=1000",
             "--setgid=1000",
-            "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,3001,3002,3003",
+            "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003",
             "--capabilities=130104352,130104352",
             "--runtime-init",
             "--nice-name=system_server",
diff --git a/core/java/com/google/android/mms/pdu/PduParser.java b/core/java/com/google/android/mms/pdu/PduParser.java
old mode 100644
new mode 100755
index 8edfe52..3f185aa
--- a/core/java/com/google/android/mms/pdu/PduParser.java
+++ b/core/java/com/google/android/mms/pdu/PduParser.java
@@ -29,6 +29,8 @@
 import java.util.Arrays;
 import java.util.HashMap;
 
+import android.content.res.Resources;
+
 public class PduParser {
     /**
      *  The next are WAP values defined in WSP specification.
@@ -1557,43 +1559,55 @@
                          * Attachment = <Octet 129>
                          * Inline = <Octet 130>
                          */
-                        int len = parseValueLength(pduDataStream);
-                        pduDataStream.mark(1);
-                        int thisStartPos = pduDataStream.available();
-                        int thisEndPos = 0;
-                        int value = pduDataStream.read();
 
-                        if (value == PduPart.P_DISPOSITION_FROM_DATA ) {
-                            part.setContentDisposition(PduPart.DISPOSITION_FROM_DATA);
-                        } else if (value == PduPart.P_DISPOSITION_ATTACHMENT) {
-                            part.setContentDisposition(PduPart.DISPOSITION_ATTACHMENT);
-                        } else if (value == PduPart.P_DISPOSITION_INLINE) {
-                            part.setContentDisposition(PduPart.DISPOSITION_INLINE);
-                        } else {
-                            pduDataStream.reset();
-                            /* Token-text */
-                            part.setContentDisposition(parseWapString(pduDataStream, TYPE_TEXT_STRING));
-                        }
+                        /*
+                         * some carrier mmsc servers do not support content_disposition
+                         * field correctly
+                         */
+                        boolean contentDisposition = Resources.getSystem().getBoolean(com
+                                .android.internal.R.bool.config_mms_content_disposition_support);
 
-                        /* get filename parameter and skip other parameters */
-                        thisEndPos = pduDataStream.available();
-                        if (thisStartPos - thisEndPos < len) {
-                            value = pduDataStream.read();
-                            if (value == PduPart.P_FILENAME) { //filename is text-string
-                                part.setFilename(parseWapString(pduDataStream, TYPE_TEXT_STRING));
+                        if (contentDisposition) {
+                            int len = parseValueLength(pduDataStream);
+                            pduDataStream.mark(1);
+                            int thisStartPos = pduDataStream.available();
+                            int thisEndPos = 0;
+                            int value = pduDataStream.read();
+
+                            if (value == PduPart.P_DISPOSITION_FROM_DATA ) {
+                                part.setContentDisposition(PduPart.DISPOSITION_FROM_DATA);
+                            } else if (value == PduPart.P_DISPOSITION_ATTACHMENT) {
+                                part.setContentDisposition(PduPart.DISPOSITION_ATTACHMENT);
+                            } else if (value == PduPart.P_DISPOSITION_INLINE) {
+                                part.setContentDisposition(PduPart.DISPOSITION_INLINE);
+                            } else {
+                                pduDataStream.reset();
+                                /* Token-text */
+                                part.setContentDisposition(parseWapString(pduDataStream
+                                        , TYPE_TEXT_STRING));
                             }
 
-                            /* skip other parameters */
+                            /* get filename parameter and skip other parameters */
                             thisEndPos = pduDataStream.available();
                             if (thisStartPos - thisEndPos < len) {
-                                int last = len - (thisStartPos - thisEndPos);
-                                byte[] temp = new byte[last];
-                                pduDataStream.read(temp, 0, last);
-                            }
-                        }
+                                value = pduDataStream.read();
+                                if (value == PduPart.P_FILENAME) { //filename is text-string
+                                    part.setFilename(parseWapString(pduDataStream
+                                            , TYPE_TEXT_STRING));
+                                }
 
-                        tempPos = pduDataStream.available();
-                        lastLen = length - (startPos - tempPos);
+                                /* skip other parameters */
+                                thisEndPos = pduDataStream.available();
+                                if (thisStartPos - thisEndPos < len) {
+                                    int last = len - (thisStartPos - thisEndPos);
+                                    byte[] temp = new byte[last];
+                                    pduDataStream.read(temp, 0, last);
+                                }
+                            }
+
+                            tempPos = pduDataStream.available();
+                            lastLen = length - (startPos - tempPos);
+                        }
                         break;
                     default:
                         if (LOCAL_LOGV) {
diff --git a/core/jni/Android.mk b/core/jni/Android.mk
index 12b9ca5..bd0d9b9 100644
--- a/core/jni/Android.mk
+++ b/core/jni/Android.mk
@@ -96,6 +96,7 @@
 	android/graphics/Movie.cpp \
 	android/graphics/NinePatch.cpp \
 	android/graphics/NinePatchImpl.cpp \
+	android/graphics/NinePatchPeeker.cpp \
 	android/graphics/Paint.cpp \
 	android/graphics/Path.cpp \
 	android/graphics/PathMeasure.cpp \
@@ -176,7 +177,6 @@
 	libgui \
 	libsurfaceflinger_client \
 	libcamera_client \
-	libskiagl \
 	libskia \
 	libsqlite \
 	libdvm \
diff --git a/core/jni/android/graphics/Bitmap.cpp b/core/jni/android/graphics/Bitmap.cpp
index 88bbafd..56f1ebf 100644
--- a/core/jni/android/graphics/Bitmap.cpp
+++ b/core/jni/android/graphics/Bitmap.cpp
@@ -261,7 +261,8 @@
 // These must match the int values in Bitmap.java

 enum JavaEncodeFormat {

     kJPEG_JavaEncodeFormat = 0,

-    kPNG_JavaEncodeFormat = 1

+    kPNG_JavaEncodeFormat = 1,

+    kWEBP_JavaEncodeFormat = 2

 };

 

 static bool Bitmap_compress(JNIEnv* env, jobject clazz, SkBitmap* bitmap,

@@ -276,6 +277,9 @@
     case kPNG_JavaEncodeFormat:

         fm = SkImageEncoder::kPNG_Type;

         break;

+    case kWEBP_JavaEncodeFormat:

+        fm = SkImageEncoder::kWEBP_Type;

+        break;

     default:

         return false;

     }

@@ -363,12 +367,12 @@
     }

 

     if (!GraphicsJNI::setJavaPixelRef(env, bitmap, ctable, true)) {

-        ctable->safeUnref();

+        SkSafeUnref(ctable);

         delete bitmap;

         return NULL;

     }

 

-    ctable->safeUnref();

+    SkSafeUnref(ctable);

 

     size_t size = bitmap->getSize();

     bitmap->lockPixels();

@@ -626,4 +630,3 @@
     return android::AndroidRuntime::registerNativeMethods(env, kClassPathName,

                                 gBitmapMethods, SK_ARRAY_COUNT(gBitmapMethods));

 }

-

diff --git a/core/jni/android/graphics/BitmapRegionDecoder.cpp b/core/jni/android/graphics/BitmapRegionDecoder.cpp
index 91a8202..cb2ad74 100644
--- a/core/jni/android/graphics/BitmapRegionDecoder.cpp
+++ b/core/jni/android/graphics/BitmapRegionDecoder.cpp
@@ -94,7 +94,7 @@
         return nullObjectReturn("decoder->buildTileIndex returned false");
     }
 
-    SkBitmapRegionDecoder *bm = new SkBitmapRegionDecoder(decoder, width, height);
+    SkBitmapRegionDecoder *bm = new SkBitmapRegionDecoder(decoder, stream, width, height);
 
     return GraphicsJNI::createBitmapRegionDecoder(env, bm);
 }
diff --git a/core/jni/android/graphics/Canvas.cpp b/core/jni/android/graphics/Canvas.cpp
index e1e9536..5212548 100644
--- a/core/jni/android/graphics/Canvas.cpp
+++ b/core/jni/android/graphics/Canvas.cpp
@@ -61,12 +61,11 @@
     }
     
     static SkCanvas* initGL(JNIEnv* env, jobject) {
-        return new SkGLCanvas;
+        return 0;
     }
     
     static void freeCaches(JNIEnv* env, jobject) {
         // these are called in no particular order
-        SkGLCanvas::DeleteAllTextures();
         SkImageRef_GlobalPool::SetRAMUsed(0);
         SkGraphics::SetFontCacheUsed(0);
     }
@@ -74,20 +73,6 @@
     static jboolean isOpaque(JNIEnv* env, jobject jcanvas) {
         NPE_CHECK_RETURN_ZERO(env, jcanvas);
         SkCanvas* canvas = GraphicsJNI::getNativeCanvas(env, jcanvas);
-
-        /*
-            Currently we cannot support transparency in GL-based canvas' at
-            the view level. Therefore we cannot base our answer on the device's
-            bitmap, but need to hard-code the answer. If we relax this
-            limitation in views, we can simplify the following code as well.
-         
-            Use the getViewport() call to find out if we're gl-based...
-        */
-        if (canvas->getViewport(NULL)) {
-            return true;
-        }
-        
-        // normal technique, rely on the device's bitmap for the answer
         return canvas->getDevice()->accessBitmap(false).isOpaque();
     }
     
@@ -105,7 +90,6 @@
 
     static void setViewport(JNIEnv* env, jobject, SkCanvas* canvas,
                             int width, int height) {
-        canvas->setViewport(width, height);
     }
     
     static void setBitmap(JNIEnv* env, jobject, SkCanvas* canvas,
@@ -680,7 +664,7 @@
         }
         SkShader* shader = SkShader::CreateBitmapShader(*bitmap,
                         SkShader::kClamp_TileMode, SkShader::kClamp_TileMode);
-        tmpPaint.setShader(shader)->safeUnref();
+        SkSafeUnref(tmpPaint.setShader(shader));
 
         canvas->drawVertices(SkCanvas::kTriangles_VertexMode, ptCount, verts,
                              texs, (const SkColor*)colorA.ptr(), NULL, indices,
diff --git a/core/jni/android/graphics/ColorFilter.cpp b/core/jni/android/graphics/ColorFilter.cpp
index ebfb209..5fbf73b 100644
--- a/core/jni/android/graphics/ColorFilter.cpp
+++ b/core/jni/android/graphics/ColorFilter.cpp
@@ -29,7 +29,7 @@
 public:
 
     static void finalizer(JNIEnv* env, jobject clazz, SkColorFilter* obj) {
-        obj->safeUnref();
+        SkSafeUnref(obj);
     }
 
     static SkColorFilter* CreatePorterDuffFilter(JNIEnv* env, jobject,
diff --git a/core/jni/android/graphics/DrawFilter.cpp b/core/jni/android/graphics/DrawFilter.cpp
index 496e712..2f9fe7e 100644
--- a/core/jni/android/graphics/DrawFilter.cpp
+++ b/core/jni/android/graphics/DrawFilter.cpp
@@ -34,7 +34,7 @@
 public:
 
     static void finalizer(JNIEnv* env, jobject clazz, SkDrawFilter* obj) {
-        obj->safeUnref();
+        SkSafeUnref(obj);
     }
 
     static SkDrawFilter* CreatePaintFlagsDF(JNIEnv* env, jobject clazz,
diff --git a/core/jni/android/graphics/MaskFilter.cpp b/core/jni/android/graphics/MaskFilter.cpp
index 455449e..d3f9b78 100644
--- a/core/jni/android/graphics/MaskFilter.cpp
+++ b/core/jni/android/graphics/MaskFilter.cpp
@@ -14,7 +14,7 @@
 class SkMaskFilterGlue {
 public:
     static void destructor(JNIEnv* env, jobject, SkMaskFilter* filter) {
-        filter->safeUnref();
+        SkSafeUnref(filter);
     }
 
     static SkMaskFilter* createBlur(JNIEnv* env, jobject, float radius, int blurStyle) {
diff --git a/core/jni/android/graphics/Movie.cpp b/core/jni/android/graphics/Movie.cpp
index de18f9f..d1a5546 100644
--- a/core/jni/android/graphics/Movie.cpp
+++ b/core/jni/android/graphics/Movie.cpp
@@ -115,6 +115,10 @@
     return create_jmovie(env, moov);
 }
 
+static void movie_destructor(JNIEnv* env, jobject, SkMovie* movie) {
+    delete movie;
+}
+
 //////////////////////////////////////////////////////////////////////////////////////////////
 
 #include <android_runtime/AndroidRuntime.h>
@@ -129,6 +133,7 @@
                             (void*)movie_draw  },
     { "decodeStream", "(Ljava/io/InputStream;)Landroid/graphics/Movie;",
                             (void*)movie_decodeStream },
+    { "nativeDestructor","(I)V", (void*)movie_destructor },
     { "decodeByteArray", "([BII)Landroid/graphics/Movie;",
                             (void*)movie_decodeByteArray },
 };
diff --git a/core/jni/android/graphics/NinePatchImpl.cpp b/core/jni/android/graphics/NinePatchImpl.cpp
index ff24a87..a3e36ee 100644
--- a/core/jni/android/graphics/NinePatchImpl.cpp
+++ b/core/jni/android/graphics/NinePatchImpl.cpp
@@ -116,9 +116,9 @@
         paint = &defaultPaint;
     }
     
-    // if our canvas is GL, draw this as a mesh, which will be faster than
-    // in parts (which is faster for raster)
-    if (canvas && canvas->getViewport(NULL)) {
+    // if our SkCanvas were back by GL we should enable this and draw this as
+    // a mesh, which will be faster in most cases.
+    if (false) {
         SkNinePatch::DrawMesh(canvas, bounds, bitmap,
                               chunk.xDivs, chunk.numXDivs,
                               chunk.yDivs, chunk.numYDivs,
diff --git a/core/jni/android/graphics/NinePatchPeeker.cpp b/core/jni/android/graphics/NinePatchPeeker.cpp
new file mode 100644
index 0000000..365d985
--- /dev/null
+++ b/core/jni/android/graphics/NinePatchPeeker.cpp
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 "NinePatchPeeker.h"
+
+#include "SkBitmap.h"
+
+using namespace android;
+
+bool NinePatchPeeker::peek(const char tag[], const void* data, size_t length) {
+    if (strcmp("npTc", tag) == 0 && length >= sizeof(Res_png_9patch)) {
+        Res_png_9patch* patch = (Res_png_9patch*) data;
+        size_t patchSize = patch->serializedSize();
+        assert(length == patchSize);
+        // You have to copy the data because it is owned by the png reader
+        Res_png_9patch* patchNew = (Res_png_9patch*) malloc(patchSize);
+        memcpy(patchNew, patch, patchSize);
+        // this relies on deserialization being done in place
+        Res_png_9patch::deserialize(patchNew);
+        patchNew->fileToDevice();
+        if (fPatchIsValid) {
+            free(fPatch);
+        }
+        fPatch = patchNew;
+        //printf("9patch: (%d,%d)-(%d,%d)\n",
+        //       fPatch.sizeLeft, fPatch.sizeTop,
+        //       fPatch.sizeRight, fPatch.sizeBottom);
+        fPatchIsValid = true;
+
+        // now update our host to force index or 32bit config
+        // 'cause we don't want 565 predithered, since as a 9patch, we know
+        // we will be stretched, and therefore we want to dither afterwards.
+        static const SkBitmap::Config gNo565Pref[] = {
+            SkBitmap::kIndex8_Config,
+            SkBitmap::kIndex8_Config,
+            SkBitmap::kARGB_8888_Config,
+            SkBitmap::kARGB_8888_Config,
+            SkBitmap::kARGB_8888_Config,
+            SkBitmap::kARGB_8888_Config,
+        };
+        fHost->setPrefConfigTable(gNo565Pref);
+    } else {
+        fPatch = NULL;
+    }
+    return true;    // keep on decoding
+}
diff --git a/core/jni/android/graphics/NinePatchPeeker.h b/core/jni/android/graphics/NinePatchPeeker.h
new file mode 100644
index 0000000..8567e23
--- /dev/null
+++ b/core/jni/android/graphics/NinePatchPeeker.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 NinePatchPeeker_h
+#define NinePatchPeeker_h
+
+#include "SkImageDecoder.h"
+#include <utils/ResourceTypes.h>
+
+using namespace android;
+
+class NinePatchPeeker : public SkImageDecoder::Peeker {
+    SkImageDecoder* fHost;
+public:
+    NinePatchPeeker(SkImageDecoder* host) {
+        // the host lives longer than we do, so a raw ptr is safe
+        fHost = host;
+        fPatchIsValid = false;
+    }
+
+    ~NinePatchPeeker() {
+        if (fPatchIsValid) {
+            free(fPatch);
+        }
+    }
+
+    bool    fPatchIsValid;
+    Res_png_9patch*  fPatch;
+
+    virtual bool peek(const char tag[], const void* data, size_t length);
+};
+
+#endif // NinePatchPeeker_h
diff --git a/core/jni/android/graphics/PathEffect.cpp b/core/jni/android/graphics/PathEffect.cpp
index 0ecb004..cfa9ce4 100644
--- a/core/jni/android/graphics/PathEffect.cpp
+++ b/core/jni/android/graphics/PathEffect.cpp
@@ -12,7 +12,7 @@
 public:
 
     static void destructor(JNIEnv* env, jobject, SkPathEffect* effect) {
-        effect->safeUnref();
+        SkSafeUnref(effect);
     }
 
     static SkPathEffect* Compose_constructor(JNIEnv* env, jobject,
diff --git a/core/jni/android/graphics/Rasterizer.cpp b/core/jni/android/graphics/Rasterizer.cpp
index db70b57..4e1b36a 100644
--- a/core/jni/android/graphics/Rasterizer.cpp
+++ b/core/jni/android/graphics/Rasterizer.cpp
@@ -32,7 +32,7 @@
 public:
 
     static void finalizer(JNIEnv* env, jobject clazz, SkRasterizer* obj) {
-        obj->safeUnref();
+        SkSafeUnref(obj);
     }
  
 };
diff --git a/core/jni/android/graphics/Shader.cpp b/core/jni/android/graphics/Shader.cpp
index b09c62b..8dbe83f 100644
--- a/core/jni/android/graphics/Shader.cpp
+++ b/core/jni/android/graphics/Shader.cpp
@@ -43,7 +43,7 @@
 
 static void Shader_destructor(JNIEnv* env, jobject, SkShader* shader)
 {
-    shader->safeUnref();
+    SkSafeUnref(shader);
 }
 
 static bool Shader_getLocalMatrix(JNIEnv* env, jobject, const SkShader* shader, SkMatrix* matrix)
diff --git a/core/jni/android/graphics/Xfermode.cpp b/core/jni/android/graphics/Xfermode.cpp
index 2b53d28..976a91f 100644
--- a/core/jni/android/graphics/Xfermode.cpp
+++ b/core/jni/android/graphics/Xfermode.cpp
@@ -28,7 +28,7 @@
 
     static void finalizer(JNIEnv* env, jobject, SkXfermode* obj)
     {
-        obj->safeUnref();
+        SkSafeUnref(obj);
     }
     
     static SkXfermode* avoid_create(JNIEnv* env, jobject, SkColor opColor,
diff --git a/core/jni/android_net_NetUtils.cpp b/core/jni/android_net_NetUtils.cpp
index 6575b9a..4d9bb3b 100644
--- a/core/jni/android_net_NetUtils.cpp
+++ b/core/jni/android_net_NetUtils.cpp
@@ -43,6 +43,15 @@
 int dhcp_stop(const char *ifname);
 int dhcp_release_lease(const char *ifname);
 char *dhcp_get_errmsg();
+
+int dhcp_do_request_renew(const char *ifname,
+                    in_addr_t *ipaddr,
+                    in_addr_t *gateway,
+                    in_addr_t *mask,
+                    in_addr_t *dns1,
+                    in_addr_t *dns2,
+                    in_addr_t *server,
+                    uint32_t  *lease);
 }
 
 #define NETUTILS_PKG_NAME "android/net/NetworkUtils"
@@ -211,6 +220,28 @@
     return (jboolean)(result == 0);
 }
 
+static jboolean android_net_utils_runDhcpRenew(JNIEnv* env, jobject clazz, jstring ifname, jobject info)
+{
+    int result = -1;
+    in_addr_t ipaddr, gateway, mask, dns1, dns2, server;
+    uint32_t lease;
+
+    const char *nameStr = env->GetStringUTFChars(ifname, NULL);
+    result = ::dhcp_do_request_renew(nameStr, &ipaddr, &gateway, &mask,
+            &dns1, &dns2, &server, &lease);
+    env->ReleaseStringUTFChars(ifname, nameStr);
+    if (result == 0 && dhcpInfoFieldIds.dhcpInfoClass != NULL) {
+        env->SetIntField(info, dhcpInfoFieldIds.ipaddress, ipaddr);
+        env->SetIntField(info, dhcpInfoFieldIds.gateway, gateway);
+        env->SetIntField(info, dhcpInfoFieldIds.netmask, mask);
+        env->SetIntField(info, dhcpInfoFieldIds.dns1, dns1);
+        env->SetIntField(info, dhcpInfoFieldIds.dns2, dns2);
+        env->SetIntField(info, dhcpInfoFieldIds.serverAddress, server);
+        env->SetIntField(info, dhcpInfoFieldIds.leaseDuration, lease);
+    }
+
+    return (jboolean)(result == 0);
+}
 // ----------------------------------------------------------------------------
 
 /*
@@ -232,6 +263,7 @@
     { "releaseDhcpLease", "(Ljava/lang/String;)Z",  (void *)android_net_utils_releaseDhcpLease },
     { "configureNative", "(Ljava/lang/String;IIIII)Z",  (void *)android_net_utils_configureInterface },
     { "getDhcpError", "()Ljava/lang/String;", (void*) android_net_utils_getDhcpError },
+    { "runDhcpRenew", "(Ljava/lang/String;Landroid/net/DhcpInfo;)Z",  (void *)android_net_utils_runDhcpRenew}
 };
 
 int register_android_net_NetworkUtils(JNIEnv* env)
diff --git a/core/jni/android_net_wifi_Wifi.cpp b/core/jni/android_net_wifi_Wifi.cpp
index fb029e6..35d8dc3 100644
--- a/core/jni/android_net_wifi_Wifi.cpp
+++ b/core/jni/android_net_wifi_Wifi.cpp
@@ -402,7 +402,9 @@
     }
     // reply comes back in the form "powermode = XX" where XX is the
     // number we're interested in.
-    sscanf(reply, "%*s = %u", &power);
+    if (sscanf(reply, "%*s = %u", &power) != 1) {
+        return (jint)-1;
+    }
     return (jint)power;
 }
 
diff --git a/core/jni/android_nfc_NdefMessage.cpp b/core/jni/android_nfc_NdefMessage.cpp
index 9beef2a..aff8aa6 100644
--- a/core/jni/android_nfc_NdefMessage.cpp
+++ b/core/jni/android_nfc_NdefMessage.cpp
@@ -102,6 +102,19 @@
         }
         TRACE("phFriNfc_NdefRecord_Parse() returned 0x%04x", status);
 
+        // We don't exactly know what *is* a valid length, but a simple
+        // sanity check is to make sure that the length of the header
+        // plus all fields does not exceed raw_msg_size. The min length
+        // of the header is 3 bytes: TNF, Type Length, Payload Length
+        // (ID length field is optional!)
+        uint64_t indicatedMsgLength = 3 + record.TypeLength + record.IdLength +
+                (uint64_t)record.PayloadLength;
+        if (indicatedMsgLength >
+                (uint64_t)raw_msg_size) {
+            LOGE("phFri_NdefRecord_Parse: invalid length field");
+            goto end;
+        }
+
         type = e->NewByteArray(record.TypeLength);
         if (type == NULL) {
             LOGD("NFC_Set Record Type Error\n");
diff --git a/core/jni/android_server_BluetoothEventLoop.cpp b/core/jni/android_server_BluetoothEventLoop.cpp
index d8e049d..73dfdbe1 100644
--- a/core/jni/android_server_BluetoothEventLoop.cpp
+++ b/core/jni/android_server_BluetoothEventLoop.cpp
@@ -106,7 +106,7 @@
                                                          "(Ljava/lang/String;Z)V");
 
     method_onAgentAuthorize = env->GetMethodID(clazz, "onAgentAuthorize",
-                                               "(Ljava/lang/String;Ljava/lang/String;)Z");
+                                               "(Ljava/lang/String;Ljava/lang/String;I)V");
     method_onAgentOutOfBandDataAvailable = env->GetMethodID(clazz, "onAgentOutOfBandDataAvailable",
                                                "(Ljava/lang/String;)Z");
     method_onAgentCancel = env->GetMethodID(clazz, "onAgentCancel", "()V");
@@ -311,7 +311,7 @@
 {
     DBusMessage *msg, *reply;
     DBusError err;
-    bool oob = TRUE;
+    dbus_bool_t oob = TRUE;
 
     if (!dbus_connection_register_object_path(nat->conn, agent_path,
             &agent_vtable, nat)) {
@@ -917,29 +917,11 @@
         LOGV("... object_path = %s", object_path);
         LOGV("... uuid = %s", uuid);
 
-        bool auth_granted =
-            env->CallBooleanMethod(nat->me, method_onAgentAuthorize,
-                env->NewStringUTF(object_path), env->NewStringUTF(uuid));
+        dbus_message_ref(msg);  // increment refcount because we pass to java
+        env->CallBooleanMethod(nat->me, method_onAgentAuthorize,
+                env->NewStringUTF(object_path), env->NewStringUTF(uuid),
+                int(msg));
 
-        // reply
-        if (auth_granted) {
-            DBusMessage *reply = dbus_message_new_method_return(msg);
-            if (!reply) {
-                LOGE("%s: Cannot create message reply\n", __FUNCTION__);
-                goto failure;
-            }
-            dbus_connection_send(nat->conn, reply, NULL);
-            dbus_message_unref(reply);
-        } else {
-            DBusMessage *reply = dbus_message_new_error(msg,
-                    "org.bluez.Error.Rejected", "Authorization rejected");
-            if (!reply) {
-                LOGE("%s: Cannot create message reply\n", __FUNCTION__);
-                goto failure;
-            }
-            dbus_connection_send(nat->conn, reply, NULL);
-            dbus_message_unref(reply);
-        }
         goto success;
     } else if (dbus_message_is_method_call(msg,
             "org.bluez.Agent", "OutOfBandAvailable")) {
diff --git a/core/jni/android_server_BluetoothService.cpp b/core/jni/android_server_BluetoothService.cpp
index daa59a6..248b942 100644
--- a/core/jni/android_server_BluetoothService.cpp
+++ b/core/jni/android_server_BluetoothService.cpp
@@ -242,15 +242,15 @@
 #endif
 }
 
-static void stopDiscoveryNative(JNIEnv *env, jobject object) {
+static jboolean stopDiscoveryNative(JNIEnv *env, jobject object) {
     LOGV(__FUNCTION__);
 #ifdef HAVE_BLUETOOTH
     DBusMessage *msg = NULL;
     DBusMessage *reply = NULL;
     DBusError err;
     const char *name;
-    jstring ret;
     native_data_t *nat;
+    jboolean ret = JNI_FALSE;
 
     dbus_error_init(&err);
 
@@ -280,11 +280,16 @@
         } else {
             LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
         }
+        goto done;
     }
 
+    ret = JNI_TRUE;
 done:
     if (msg) dbus_message_unref(msg);
     if (reply) dbus_message_unref(reply);
+    return ret;
+#else
+    return JNI_FALSE;
 #endif
 }
 
@@ -599,6 +604,35 @@
     return JNI_FALSE;
 }
 
+static jboolean setAuthorizationNative(JNIEnv *env, jobject object, jstring address,
+                         jboolean val, 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 (val) {
+            reply = dbus_message_new_method_return(msg);
+        } else {
+            reply = dbus_message_new_error(msg,
+                    "org.bluez.Error.Rejected", "Authorization rejected");
+        }
+        if (!reply) {
+            LOGE("%s: Cannot create message reply 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 setPinNative(JNIEnv *env, jobject object, jstring address,
                          jstring pin, int nativeData) {
 #ifdef HAVE_BLUETOOTH
@@ -1029,6 +1063,7 @@
             (void *)setPairingConfirmationNative},
     {"setPasskeyNative", "(Ljava/lang/String;II)Z", (void *)setPasskeyNative},
     {"setRemoteOutOfBandDataNative", "(Ljava/lang/String;[B[BI)Z", (void *)setRemoteOutOfBandDataNative},
+    {"setAuthorizationNative", "(Ljava/lang/String;ZI)Z", (void *)setAuthorizationNative},
     {"setPinNative", "(Ljava/lang/String;Ljava/lang/String;I)Z", (void *)setPinNative},
     {"cancelPairingUserInputNative", "(Ljava/lang/String;I)Z",
             (void *)cancelPairingUserInputNative},
diff --git a/core/jni/android_util_Binder.cpp b/core/jni/android_util_Binder.cpp
index 7a53874..8db2553 100644
--- a/core/jni/android_util_Binder.cpp
+++ b/core/jni/android_util_Binder.cpp
@@ -603,6 +603,15 @@
 
 static void android_os_Binder_restoreCallingIdentity(JNIEnv* env, jobject clazz, jlong token)
 {
+    // XXX temporary sanity check to debug crashes.
+    int uid = (int)(token>>32);
+    if (uid > 0 && uid < 999) {
+        // In Android currently there are no uids in this range.
+        char buf[128];
+        sprintf(buf, "Restoring bad calling ident: 0x%Lx", token);
+        jniThrowException(env, "java/lang/IllegalStateException", buf);
+        return;
+    }
     IPCThreadState::self()->restoreCallingIdentity(token);
 }
 
diff --git a/core/jni/android_view_ViewRoot.cpp b/core/jni/android_view_ViewRoot.cpp
index 5173bb8..0b13ef9 100644
--- a/core/jni/android_view_ViewRoot.cpp
+++ b/core/jni/android_view_ViewRoot.cpp
@@ -77,7 +77,6 @@
 }
 
 static void android_view_ViewRoot_abandonGlCaches(JNIEnv* env, jobject) {
-    SkGLCanvas::AbandonAllTextures();
 }
 
 
diff --git a/core/jni/com_google_android_gles_jni_EGLImpl.cpp b/core/jni/com_google_android_gles_jni_EGLImpl.cpp
index 941ed63..e7ea8c8 100644
--- a/core/jni/com_google_android_gles_jni_EGLImpl.cpp
+++ b/core/jni/com_google_android_gles_jni_EGLImpl.cpp
@@ -290,7 +290,7 @@
         return;
     }
 
-    ref->safeRef();
+    SkSafeRef(ref);
     ref->lockPixels();
 
     egl_native_pixmap_t pixmap;
@@ -310,7 +310,7 @@
         _env->SetIntField(out_sur, gSurface_NativePixelRefFieldID, (int)ref);
     } else {
         ref->unlockPixels();
-        ref->safeUnref();
+        SkSafeUnref(ref);
     }
 }
 
@@ -430,7 +430,7 @@
                 gSurface_NativePixelRefFieldID));
         if (ref) {
             ref->unlockPixels();
-            ref->safeUnref();
+            SkSafeUnref(ref);
         }
     }
     return eglDestroySurface(dpy, sur);
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index a130bf5..55cb6c8 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -55,6 +55,7 @@
     <protected-broadcast android:name="android.intent.action.NEW_OUTGOING_CALL" />
     <protected-broadcast android:name="android.intent.action.REBOOT" />
     <protected-broadcast android:name="android.intent.action.DOCK_EVENT" />
+    <protected-broadcast android:name="android.intent.action.MASTER_CLEAR_NOTIFICATION" />
 
     <protected-broadcast android:name="android.app.action.ENTER_CAR_MODE" />
     <protected-broadcast android:name="android.app.action.EXIT_CAR_MODE" />
@@ -82,12 +83,14 @@
     <protected-broadcast android:name="android.bluetooth.device.action.PAIRING_REQUEST" />
     <protected-broadcast android:name="android.bluetooth.device.action.PAIRING_CANCEL" />
 
-    <protected-broadcast android:name="android.hardware.action.USB_CONNECTED" />
-    <protected-broadcast android:name="android.hardware.action.USB_DISCONNECTED" />
-    <protected-broadcast android:name="android.hardware.action.USB_STATE" />
+    <protected-broadcast android:name="android.hardware.usb.action.USB_STATE" />
+    <protected-broadcast android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
+    <protected-broadcast android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
 
     <protected-broadcast android:name="android.nfc.action.LLCP_LINK_STATE_CHANGED" />
-    <protected-broadcast android:name="android.nfc.action.TRANSACTION_DETECTED" />
+    <protected-broadcast android:name="com.android.nfc_extras.action.RF_FIELD_ON_DETECTED" />
+    <protected-broadcast android:name="com.android.nfc_extras.action.RF_FIELD_OFF_DETECTED" />
+    <protected-broadcast android:name="com.android.nfc_extras.action.AID_SELECTED" />
 
     <!-- ====================================== -->
     <!-- Permissions for things that cost money -->
@@ -147,6 +150,15 @@
         android:label="@string/permlab_receiveMms"
         android:description="@string/permdesc_receiveMms" />
 
+    <!-- Allows an application to receive emergency cell broadcast messages,
+         to record or display them to the user. Reserved for system apps.
+         @hide Pending API council approval -->
+    <permission android:name="android.permission.RECEIVE_EMERGENCY_BROADCAST"
+        android:permissionGroup="android.permission-group.MESSAGES"
+        android:protectionLevel="signatureOrSystem"
+        android:label="@string/permlab_receiveEmergencyBroadcast"
+        android:description="@string/permdesc_receiveEmergencyBroadcast" />
+
     <!-- Allows an application to read SMS messages. -->
     <permission android:name="android.permission.READ_SMS"
         android:permissionGroup="android.permission-group.MESSAGES"
@@ -332,6 +344,14 @@
         android:description="@string/permdesc_accessWifiState"
         android:label="@string/permlab_accessWifiState" />
 
+    <!-- Allows applications to access information about WiMAX networks
+         @hide -->
+    <permission android:name="android.permission.ACCESS_WIMAX_STATE"
+        android:permissionGroup="android.permission-group.NETWORK"
+        android:protectionLevel="normal"
+        android:description="@string/permdesc_accessWimaxState"
+        android:label="@string/permlab_accessWimaxState" />
+
     <!-- Allows applications to connect to paired bluetooth devices -->
     <permission android:name="android.permission.BLUETOOTH"
         android:permissionGroup="android.permission-group.NETWORK"
@@ -339,7 +359,7 @@
         android:description="@string/permdesc_bluetooth"
         android:label="@string/permlab_bluetooth" />
 
-    <!-- Allows applications to directly communicate over NFC -->
+    <!-- Allows applications to perform I/O operations over NFC -->
     <permission android:name="android.permission.NFC"
         android:permissionGroup="android.permission-group.NETWORK"
         android:protectionLevel="dangerous"
@@ -453,13 +473,13 @@
         android:label="@string/permlab_flashlight"
         android:description="@string/permdesc_flashlight" />
 
-    <!-- Allows an application to access USB devices
+    <!-- Allows an application to manage preferences and permissions for USB devices
          @hide -->
-    <permission android:name="android.permission.ACCESS_USB"
+    <permission android:name="android.permission.MANAGE_USB"
         android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
         android:protectionLevel="signatureOrSystem"
-        android:label="@string/permlab_accessUsb"
-        android:description="@string/permdesc_accessUsb" />
+        android:label="@string/permlab_manageUsb"
+        android:description="@string/permdesc_manageUsb" />
 
     <!-- Allows access to hardware peripherals.  Intended only for hardware testing -->
     <permission android:name="android.permission.HARDWARE_TEST"
@@ -842,6 +862,14 @@
         android:description="@string/permdesc_changeWifiState"
         android:label="@string/permlab_changeWifiState" />
 
+    <!-- Allows applications to change WiMAX connectivity state
+         @hide -->
+    <permission android:name="android.permission.CHANGE_WIMAX_STATE"
+        android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
+        android:protectionLevel="dangerous"
+        android:description="@string/permdesc_changeWimaxState"
+        android:label="@string/permlab_changeWimaxState" />
+
     <!-- Allows applications to enter Wi-Fi Multicast mode -->
     <permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"
         android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
@@ -1004,7 +1032,7 @@
     <permission android:name="android.permission.STOP_APP_SWITCHES"
         android:label="@string/permlab_stopAppSwitches"
         android:description="@string/permdesc_stopAppSwitches"
-        android:protectionLevel="signature" />
+        android:protectionLevel="signatureOrSystem" />
 
     <!-- Allows an application to retrieve the current state of keys and
          switches.  This is only for use by the system.-->
@@ -1330,6 +1358,12 @@
                 android:excludeFromRecents="true">
         </activity>
 
+        <activity android:name="com.android.server.usb.UsbResolverActivity"
+                android:theme="@style/Theme.Dialog.Alert"
+                android:finishOnCloseSystemDialogs="true"
+                android:excludeFromRecents="true">
+        </activity>
+
         <service android:name="com.android.server.LoadAverageService"
                 android:exported="true" />
 
diff --git a/core/res/res/drawable-hdpi/stat_sys_data_fully_inandout_4g.png b/core/res/res/drawable-hdpi/stat_sys_data_fully_inandout_4g.png
new file mode 100644
index 0000000..4ff7db3
--- /dev/null
+++ b/core/res/res/drawable-hdpi/stat_sys_data_fully_inandout_4g.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/stat_sys_data_inandout_4g.png b/core/res/res/drawable-hdpi/stat_sys_data_inandout_4g.png
new file mode 100644
index 0000000..c5edf2c
--- /dev/null
+++ b/core/res/res/drawable-hdpi/stat_sys_data_inandout_4g.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/stat_sys_data_wimax_signal_3_fully.png b/core/res/res/drawable-hdpi/stat_sys_data_wimax_signal_3_fully.png
new file mode 100644
index 0000000..c2e4b78
--- /dev/null
+++ b/core/res/res/drawable-hdpi/stat_sys_data_wimax_signal_3_fully.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/stat_sys_data_wimax_signal_disconnected.png b/core/res/res/drawable-hdpi/stat_sys_data_wimax_signal_disconnected.png
new file mode 100644
index 0000000..51b839f
--- /dev/null
+++ b/core/res/res/drawable-hdpi/stat_sys_data_wimax_signal_disconnected.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/stat_sys_data_fully_inandout_4g.png b/core/res/res/drawable-mdpi/stat_sys_data_fully_inandout_4g.png
new file mode 100644
index 0000000..de8c5ee
--- /dev/null
+++ b/core/res/res/drawable-mdpi/stat_sys_data_fully_inandout_4g.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/stat_sys_data_inandout_4g.png b/core/res/res/drawable-mdpi/stat_sys_data_inandout_4g.png
new file mode 100644
index 0000000..f407bc9
--- /dev/null
+++ b/core/res/res/drawable-mdpi/stat_sys_data_inandout_4g.png
Binary files differ
diff --git a/core/res/res/layout/contact_header.xml b/core/res/res/layout/contact_header.xml
index bf467d3..dfa9af4 100644
--- a/core/res/res/layout/contact_header.xml
+++ b/core/res/res/layout/contact_header.xml
@@ -27,7 +27,6 @@
         android:layout_marginRight="8dip"
         android:layout_marginLeft="-1dip"
         style="@*android:style/Widget.QuickContactBadge.WindowSmall" />
-    />
 
     <LinearLayout
         android:layout_width="0dip"
diff --git a/core/res/res/values-ar/strings.xml b/core/res/res/values-ar/strings.xml
index 6446675..748223f 100644
--- a/core/res/res/values-ar/strings.xml
+++ b/core/res/res/values-ar/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"للسماح للتطبيق بالتحكم في الهزاز."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"التحكم في الضوء الوامض"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"للسماح للتطبيق بالتحكم في الضوء الوامض."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"الدخول إلى أجهزة USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"للسماح للتطبيق بالدخول إلى أجهزة USB."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"إدارة التفضيلات والأذونات لأجهزة USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"للسماح للتطبيق بإدارة التفضيلات والأذونات لأجهزة USB."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"اختبار الأجهزة"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"للسماح للتطبيق بالتحكم في الأجهزة الطرفية المتنوعة بغرض اختبار الأجهزة."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"اتصال مباشر بأرقام الهواتف"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"للسماح لتطبيق ما بالاتصال وفصل الاتصال بنقاط الدخول إلى Wi-Fi، وإجراء تغييرات على شبكات Wi-Fi المهيأة."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"السماح باستقبال بث Wi-Fi متعدد"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"للسماح لتطبيق ما باستلام حزم غير موجهة مباشرة إلى جهازك. يمكن أن يكون ذلك مفيدًا عند اكتشاف خدمات معروضة بالقرب منك. يستخدم ذلك الطاقة أكثر من وضع البث غير المتعدد."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"عرض حالة WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"للسماح لتطبيق ما بعرض معلومات حول حالة WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"تغيير حالة WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"للسماح لتطبيق ما بالاتصال بشبكة WiMAX وقطع الاتصال بها."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"إدارة البلوتوث"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"للسماح لتطبيق ما بتهيئة هاتف البلوتوث المحلي، واكتشاف أجهزة التحكم عن بعد والاقتران معها."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"إنشاء اتصالات بلوتوث"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"الاستخدام بشكل افتراضي لهذا الإجراء."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"محو الإعداد الافتراضي في الإعدادات الرئيسية &gt; التطبيقات &gt; إدارة التطبيقات."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"تحديد إجراء"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"تحديد تطبيق لجهاز USB"</string>
     <string name="noApplications" msgid="1691104391758345586">"ليس هناك تطبيقات يمكنها تنفيذ هذا الإجراء."</string>
     <string name="aerr_title" msgid="653922989522758100">"عذرًا!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"توقف التطبيق <xliff:g id="APPLICATION">%1$s</xliff:g> (العملية <xliff:g id="PROCESS">%2$s</xliff:g>) على نحو غير متوقع. الرجاء المحاولة مرة أخرى."</string>
diff --git a/core/res/res/values-bg/strings.xml b/core/res/res/values-bg/strings.xml
index 793b033..5a33fe7 100644
--- a/core/res/res/values-bg/strings.xml
+++ b/core/res/res/values-bg/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Разрешава на приложението да контролира устройството за вибрация."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"контролиране на фенерчето"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Разрешава на приложението да контролира фенерчето."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"достъп до USB устройства"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Разрешава на приложението достъп до USB устройства."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"управление на предпочитанията и разрешенията за USB устройства"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Разрешава на приложението да управлява предпочитанията и разрешенията за USB устройства."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"тест на хардуера"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Разрешава на приложението да контролира различни периферни устройства с цел тестване на хардуера."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"директно обаждане до телефонни номера"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Разрешава на приложението да се свързва към Wi-Fi точки за достъп и да прекратява връзката с тях, както и да извършва промени в конфигурирани Wi-Fi мрежи."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"разрешаване на приемане на мултикаст през Wi-Fi мрежата"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Разрешава на приложението да получава пакети, които не са адресирани директно към устройството ви. Това може да е полезно при откриване на предлагани в района услуги. Консумира се повече мощност, отколкото в режим без мултикаст."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"преглед на състоянието на WiMAX мрежата"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Разрешава на приложението да вижда информацията за състоянието на WiMAX мрежата."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"промяна на състоянието на WiMAX мрежата"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Разрешава на приложението да се свързва към WiMAX мрежа и да прекратява връзката с нея."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"администриране на Bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Разрешава на приложението да конфигурира локалния Bluetooth телефон, както и да открива и да се сдвоява с отдалечени устройства."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"създаване на връзки през Bluetooth"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Използване по подразбиране за това действие."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Изчистване на стандартната стойност в „Начални настройки“ &gt; „Приложения“ &gt; „Управление на приложенията“."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Избиране на действие"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Избор на приложение за USB устройството"</string>
     <string name="noApplications" msgid="1691104391758345586">"Това действие не може да се изпълни от нито едно приложение."</string>
     <string name="aerr_title" msgid="653922989522758100">"Съжаляваме!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"Приложението „<xliff:g id="APPLICATION">%1$s</xliff:g>“ (процес „<xliff:g id="PROCESS">%2$s</xliff:g>“) спря неочаквано. Моля, опитайте отново."</string>
diff --git a/core/res/res/values-ca/strings.xml b/core/res/res/values-ca/strings.xml
index d10b4d4..43d3186 100644
--- a/core/res/res/values-ca/strings.xml
+++ b/core/res/res/values-ca/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Permet a l\'aplicació controlar el vibrador."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"controlar el flaix"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Permet a l\'aplicació controlar el flaix."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"accedeix a dispositius USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Permet que l\'aplicació accedeixi als dispositius USB."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"gestiona les preferències i els permisos dels dispositius USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Permet que l\'aplicació gestioni les preferències i els permisos dels dispositius USB."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"provar el maquinari"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Permet a l\'aplicació controlar diversos perifèrics per fer proves de maquinari."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"trucar directament a números de telèfon"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Permet a una aplicació connectar-se i desconnectar-se de punts d\'accés Wi-fi i fer canvis a les xarxes Wi-fi configurades."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"permetre la recepció de multidifusió Wi-fi"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Permet a una aplicació rebre paquets no adreçats directament al vostre dispositiu. Això pot ser útil en detectar serveis oferts a prop. Utilitza més energia que el mode que no utilitza la multidifusió."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"visualitza l\'estat de WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Permet que una aplicació visualitzi la informació sobre l\'estat de WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"canvia l\'estat de WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Permet que una aplicació es connecti i es desconnecti d\'una xarxa WiMAX."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"administració de Bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Permet a una aplicació configurar el telèfon Bluetooth local i detectar dispositius remots i emparellar-se amb ells."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"crear connexions Bluetooth"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Utilitza-ho de manera predeterminada per a aquesta acció."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Esborra el valor predeterminat a Configuració de la pantalla d\'inici &gt; Aplicacions &gt; Gestiona les aplicacions."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Seleccioneu una acció"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Selecciona una aplicació per al dispositiu USB"</string>
     <string name="noApplications" msgid="1691104391758345586">"No hi ha cap aplicació que pugui dur a terme aquesta acció."</string>
     <string name="aerr_title" msgid="653922989522758100">"Ho sentim."</string>
     <string name="aerr_application" msgid="4683614104336409186">"L\'aplicació <xliff:g id="APPLICATION">%1$s</xliff:g> (procés <xliff:g id="PROCESS">%2$s</xliff:g>) s\'ha aturat inesperadament. Torneu-ho a provar."</string>
@@ -762,17 +767,17 @@
     <string name="volume_ringtone" msgid="6885421406845734650">"Volum del timbre"</string>
     <string name="volume_music" msgid="5421651157138628171">"Volum de multimèdia"</string>
     <string name="volume_music_hint_playing_through_bluetooth" msgid="9165984379394601533">"S\'està reproduint a través de Bluetooth"</string>
-    <string name="volume_music_hint_silent_ringtone_selected" msgid="6158339745293431194">"So de trucada silenciós seleccionat"</string>
+    <string name="volume_music_hint_silent_ringtone_selected" msgid="6158339745293431194">"To de silenci seleccionat"</string>
     <string name="volume_call" msgid="3941680041282788711">"Volum en trucada"</string>
     <string name="volume_bluetooth_call" msgid="2002891926351151534">"Volum en trucada Bluetooth"</string>
     <string name="volume_alarm" msgid="1985191616042689100">"Volum de l\'alarma"</string>
     <string name="volume_notification" msgid="2422265656744276715">"Volum de notificació"</string>
     <string name="volume_unknown" msgid="1400219669770445902">"Volum"</string>
-    <string name="ringtone_default" msgid="3789758980357696936">"So de trucada predeterminat"</string>
-    <string name="ringtone_default_with_actual" msgid="8129563480895990372">"So de trucada predeterminat (<xliff:g id="ACTUAL_RINGTONE">%1$s</xliff:g>)"</string>
+    <string name="ringtone_default" msgid="3789758980357696936">"To predeterminat"</string>
+    <string name="ringtone_default_with_actual" msgid="8129563480895990372">"To predeterminat (<xliff:g id="ACTUAL_RINGTONE">%1$s</xliff:g>)"</string>
     <string name="ringtone_silent" msgid="4440324407807468713">"Silenci"</string>
     <string name="ringtone_picker_title" msgid="3515143939175119094">"Sons de trucada"</string>
-    <string name="ringtone_unknown" msgid="5477919988701784788">"So de trucada desconegut"</string>
+    <string name="ringtone_unknown" msgid="5477919988701784788">"To desconegut"</string>
   <plurals name="wifi_available">
     <item quantity="one" msgid="6654123987418168693">"Xarxa Wi-fi disponible"</item>
     <item quantity="other" msgid="4192424489168397386">"Xarxes Wi-fi disponibles"</item>
@@ -790,7 +795,7 @@
     <string name="date_time_set" msgid="5777075614321087758">"Defineix"</string>
     <string name="default_permission_group" msgid="2690160991405646128">"Predeterminat"</string>
     <string name="no_permissions" msgid="7283357728219338112">"No cal cap permís"</string>
-    <string name="perms_hide" msgid="7283915391320676226"><b>"Oculta"</b></string>
+    <string name="perms_hide" msgid="7283915391320676226"><b>"Oamaga"</b></string>
     <string name="perms_show_all" msgid="2671791163933091180"><b>"Mostra\'ls tots"</b></string>
     <string name="usb_storage_activity_title" msgid="2399289999608900443">"Emmagatzematge massiu USB"</string>
     <string name="usb_storage_title" msgid="5901459041398751495">"USB connectat"</string>
diff --git a/core/res/res/values-cs/strings.xml b/core/res/res/values-cs/strings.xml
index 0e57306d..41c60f7 100644
--- a/core/res/res/values-cs/strings.xml
+++ b/core/res/res/values-cs/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Umožňuje aplikaci ovládat vibrace."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"ovládání kontrolky"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Umožňuje aplikaci ovládat kontrolku."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"přístup k zařízením USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Umožní aplikaci přístup k zařízením USB."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"spravovat nastavení a oprávnění pro zařízení USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Umožňuje aplikaci spravovat nastavení a oprávnění pro zařízení USB."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"testování hardwaru"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Umožňuje aplikaci ovládat různé periferie pro účely testování hardwaru."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"přímé volání na telefonní čísla"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Umožňuje aplikaci připojit se k přístupovým bodům WiFi či se od nich odpojit a provádět změny nakonfigurovaných sítí WiFi."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"povolení příjmu Wi-Fi Multicast"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Povoluje aplikaci přijímat pakety, které nebyly adresovány přímo vašemu zařízení. Pomocí této možnosti můžete objevit služby nabízené ve vaší blízkosti. Spotřeba energie je vyšší než u režimu bez vícesměrového vysílání (multicast)."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"zobrazit stav připojení WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Umožňuje aplikaci zobrazit informace o stavu připojení WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"měnit stav připojení WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Umožňuje aplikaci připojovat se k síti WiMAX a odpojovat se od ní."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"správa rozhraní Bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Umožňuje aplikaci konfigurovat místní telefon s rozhraním Bluetooth a vyhledávat a párovat vzdálená zařízení."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"vytvoření připojení Bluetooth"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Použít jako výchozí nastavení pro tuto činnost."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Vymažte výchozí hodnoty v Nastavení plochy &gt; Aplikace &gt; Správa aplikací."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Vyberte akci"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Zvolte aplikaci pro zařízení USB"</string>
     <string name="noApplications" msgid="1691104391758345586">"Tuto činnost nemohou provádět žádné aplikace."</string>
     <string name="aerr_title" msgid="653922989522758100">"Omlouváme se"</string>
     <string name="aerr_application" msgid="4683614104336409186">"Aplikace <xliff:g id="APPLICATION">%1$s</xliff:g> (proces <xliff:g id="PROCESS">%2$s</xliff:g>) byla neočekávaně ukončena. Zkuste to znovu."</string>
diff --git a/core/res/res/values-da/strings.xml b/core/res/res/values-da/strings.xml
index 520e0b0..87c8c55 100644
--- a/core/res/res/values-da/strings.xml
+++ b/core/res/res/values-da/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Lader programmet kontrollere vibratoren."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"kontroller lommelygte"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Tillader, at programmet kontrollerer lommelygten."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"adgang til USB-enheder."</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Tillader, at programmet har adgang til USB-enheder."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"administrer præferencer og tilladelser for USB-enheder"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Tillader, at programmet administrerer præferencer og tilladelser for USB-enheder."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"test hardware"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Tillader, at et program kontrollerer forskellige perifere enheder for at teste hardwaren."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"ring direkte op til telefonnumre"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Tillader, at et program opretter og afbryder forbindelsen fra Wi-Fi-adgangspunkter og foretager ændringer i konfigurerede Wi-Fi-netværk."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"tillad Wi-Fi-multicastmodtagelse"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Tillader, at et program modtager pakker, der ikke er direkte adresseret til din enhed. Dette kan være nyttigt, hvis du finder tjenester, der tilbydes i nærheden. Det bruger mere strøm end multicasttilstanden."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"vise WiMAX-tilstand"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Tillader, at en applikation viser oplysninger om WiMAX-tilstanden."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"skifte WiMAX-tilstand"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Tillader, at en applikation opretter og afbryder forbindelsen til WiMAX-netværk."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"bluetooth-administration"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Tillader, at et program konfigurerer den lokale Bluetooth-telefon samt opdager og parrer med fjerne enheder."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"opret Bluetooth-forbindelser"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Brug som standard til denne handling."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Ryd standard i Startindstillinger &gt; Programmer &gt; Administrer programmer."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Vælg en handling"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Vælg et program for USB-enheden"</string>
     <string name="noApplications" msgid="1691104391758345586">"Der er ingen programmer, der kan foretage denne handling."</string>
     <string name="aerr_title" msgid="653922989522758100">"Beklager!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"Programmet <xliff:g id="APPLICATION">%1$s</xliff:g> (proces <xliff:g id="PROCESS">%2$s</xliff:g>) er standset uventet. Prøv igen."</string>
diff --git a/core/res/res/values-de/strings.xml b/core/res/res/values-de/strings.xml
index 7819c6d..9a9023b 100644
--- a/core/res/res/values-de/strings.xml
+++ b/core/res/res/values-de/strings.xml
@@ -49,7 +49,7 @@
     <string name="needPuk" msgid="919668385956251611">"Ihre SIM-Karte ist mit einem PUK gesperrt. Geben Sie zum Entsperren den PUK-Code ein."</string>
     <string name="needPuk2" msgid="4526033371987193070">"Geben Sie zum Entsperren der SIM-Karte den PUK2 ein."</string>
     <string name="ClipMmi" msgid="6952821216480289285">"Anrufer-ID für eingehenden Anruf"</string>
-    <string name="ClirMmi" msgid="7784673673446833091">"Anrufer-ID für abgehenden Anruf"</string>
+    <string name="ClirMmi" msgid="7784673673446833091">"Anrufer-ID für ausgehenden Anruf"</string>
     <string name="CfMmi" msgid="5123218989141573515">"Rufweiterleitung"</string>
     <string name="CwMmi" msgid="9129678056795016867">"Anklopfen"</string>
     <string name="BaMmi" msgid="455193067926770581">"Anrufsperre"</string>
@@ -147,17 +147,17 @@
     <string name="global_actions_airplane_mode_on_status" msgid="2719557982608919750">"Flugmodus ist AN."</string>
     <string name="global_actions_airplane_mode_off_status" msgid="5075070442854490296">"Flugmodus ist AUS."</string>
     <string name="safeMode" msgid="2788228061547930246">"Abgesicherter Modus"</string>
-    <string name="android_system_label" msgid="6577375335728551336">"Android System"</string>
+    <string name="android_system_label" msgid="6577375335728551336">"Android-System"</string>
     <string name="permgrouplab_costMoney" msgid="5429808217861460401">"Kostenpflichtige Dienste"</string>
-    <string name="permgroupdesc_costMoney" msgid="8193824940620517189">"Ermöglicht Anwendungen die Ausführung eventuell kostenpflichtiger Aktionen."</string>
+    <string name="permgroupdesc_costMoney" msgid="8193824940620517189">"Ermöglicht Anwendungen die Ausführung eventuell kostenpflichtiger Aktionen"</string>
     <string name="permgrouplab_messages" msgid="7521249148445456662">"Ihre Nachrichten"</string>
     <string name="permgroupdesc_messages" msgid="7045736972019211994">"Lesen und schreiben Sie Ihre SMS, E-Mails und anderen Nachrichten."</string>
     <string name="permgrouplab_personalInfo" msgid="3519163141070533474">"Ihre persönlichen Informationen"</string>
-    <string name="permgroupdesc_personalInfo" msgid="5488050357388806068">"Direkter Zugriff auf die Kontakte und den Kalender Ihres Telefons."</string>
-    <string name="permgrouplab_location" msgid="635149742436692049">"Ihren Standort"</string>
+    <string name="permgroupdesc_personalInfo" msgid="5488050357388806068">"Direkter Zugriff auf die Kontakte und den Kalender Ihres Telefons"</string>
+    <string name="permgrouplab_location" msgid="635149742436692049">"Meinen Standort"</string>
     <string name="permgroupdesc_location" msgid="2430258821648348660">"Ihren physischen Standort überwachen"</string>
     <string name="permgrouplab_network" msgid="5808983377727109831">"Netzwerkkommunikation"</string>
-    <string name="permgroupdesc_network" msgid="5035763698958415998">"Ermöglicht Anwendungen den Zugriff auf verschiedene Netzwerkfunktionen."</string>
+    <string name="permgroupdesc_network" msgid="5035763698958415998">"Ermöglicht Anwendungen den Zugriff auf verschiedene Netzwerkfunktionen"</string>
     <string name="permgrouplab_accounts" msgid="3359646291125325519">"Ihre Konten"</string>
     <string name="permgroupdesc_accounts" msgid="4948732641827091312">"Zugriff auf verfügbare Konten"</string>
     <string name="permgrouplab_hardwareControls" msgid="7998214968791599326">"Hardware-Steuerelemente"</string>
@@ -170,14 +170,14 @@
     <string name="permgroupdesc_developmentTools" msgid="9056431193893809814">"Funktionen nur für Anwendungsentwickler vorgesehen."</string>
     <string name="permgrouplab_storage" msgid="1971118770546336966">"Speicher"</string>
     <string name="permgroupdesc_storage" product="nosdcard" msgid="7442318502446874999">"Zugriff auf USB-Speicher"</string>
-    <string name="permgroupdesc_storage" product="default" msgid="9203302214915355774">"Greift auf die SD-Karte zu."</string>
+    <string name="permgroupdesc_storage" product="default" msgid="9203302214915355774">"Zugriff auf SD-Karte"</string>
     <string name="permlab_statusBar" msgid="7417192629601890791">"Statusleiste deaktivieren oder ändern"</string>
-    <string name="permdesc_statusBar" msgid="1365473595331989732">"Ermöglicht der Anwendung, die Statusanzeige zu deaktivieren oder Systemsymbole hinzuzufügen oder zu entfernen."</string>
+    <string name="permdesc_statusBar" msgid="1365473595331989732">"Ermöglicht der Anwendung, die Statusanzeige zu deaktivieren oder Systemsymbole hinzuzufügen oder zu entfernen"</string>
     <string name="permlab_statusBarService" msgid="7247281911387931485">"Statusleiste"</string>
-    <string name="permdesc_statusBarService" msgid="4097605867643520920">"Ermöglicht der Anwendung, zur Statusleiste zu werden."</string>
+    <string name="permdesc_statusBarService" msgid="4097605867643520920">"Ermöglicht der Anwendung, zur Statusleiste zu werden"</string>
     <string name="permlab_expandStatusBar" msgid="1148198785937489264">"Statusleiste ein-/ausblenden"</string>
-    <string name="permdesc_expandStatusBar" msgid="7088604400110768665">"Ermöglicht der Anwendung, die Statusleiste ein- oder auszublenden."</string>
-    <string name="permlab_processOutgoingCalls" msgid="1136262550878335980">"Abgehende Anrufe abfangen"</string>
+    <string name="permdesc_expandStatusBar" msgid="7088604400110768665">"Ermöglicht der Anwendung, die Statusleiste ein- oder auszublenden"</string>
+    <string name="permlab_processOutgoingCalls" msgid="1136262550878335980">"Ausgehende Anrufe abfangen"</string>
     <string name="permdesc_processOutgoingCalls" msgid="2228988201852654461">"Ermöglicht einer Anwendung, abgehende Anrufe zu verarbeiten und die zu wählende Nummer zu ändern. Schädliche Anwendungen können so abgehende Anrufe eventuell überwachen, umleiten oder verhindern."</string>
     <string name="permlab_receiveSms" msgid="2697628268086208535">"SMS empfangen"</string>
     <string name="permdesc_receiveSms" msgid="6298292335965966117">"Ermöglicht der Anwendung, Kurzmitteilungen zu empfangen und zu verarbeiten. Schädliche Anwendungen können Ihre Nachrichten möglicherweise überwachen oder löschen, bevor sie angezeigt werden."</string>
@@ -198,13 +198,13 @@
     <string name="permlab_setDebugApp" msgid="4339730312925176742">"Fehlerbeseitigung für Anwendung aktivieren"</string>
     <string name="permdesc_setDebugApp" msgid="5584310661711990702">"Ermöglicht einer Anwendung, die Fehlerbeseitigung für eine andere Anwendung zu aktivieren. Schädliche Anwendungen können so andere Anwendungen löschen."</string>
     <string name="permlab_changeConfiguration" msgid="8214475779521218295">"UI-Einstellungen ändern"</string>
-    <string name="permdesc_changeConfiguration" msgid="3465121501528064399">"Ermöglicht einer Anwendung, die aktuelle Konfiguration zu ändern, etwa das Gebietsschema oder die Schriftgröße."</string>
+    <string name="permdesc_changeConfiguration" msgid="3465121501528064399">"Ermöglicht einer Anwendung, die aktuelle Konfiguration zu ändern, etwa das Gebietsschema oder die Schriftgröße"</string>
     <string name="permlab_enableCarMode" msgid="5684504058192921098">"Automodus aktivieren"</string>
-    <string name="permdesc_enableCarMode" msgid="5673461159384850628">"Ermöglicht einer Anwendung, den Automodus zu aktivieren."</string>
+    <string name="permdesc_enableCarMode" msgid="5673461159384850628">"Ermöglicht einer Anwendung, den Automodus zu aktivieren"</string>
     <string name="permlab_killBackgroundProcesses" msgid="8373714752793061963">"Hintergrundprozesse beenden"</string>
     <string name="permdesc_killBackgroundProcesses" msgid="2908829602869383753">"Ermöglicht einer Anwendung, Hintergrundprozesse anderer Anwendungen auch bei ausreichendem Speicher zu beenden."</string>
     <string name="permlab_forceStopPackages" msgid="1447830113260156236">"Beenden anderer Anwendungen erzwingen"</string>
-    <string name="permdesc_forceStopPackages" msgid="7263036616161367402">"Ermöglicht einer Anwendung, das Beenden anderer Anwendungen zu erzwingen."</string>
+    <string name="permdesc_forceStopPackages" msgid="7263036616161367402">"Ermöglicht einer Anwendung, das Beenden anderer Anwendungen zu erzwingen"</string>
     <string name="permlab_forceBack" msgid="1804196839880393631">"Schließen von Anwendung erzwingen"</string>
     <string name="permdesc_forceBack" msgid="6534109744159919013">"Ermöglicht einer Anwendung, alle Aktivitäten, die im Vordergrund ablaufen, zu beenden und in den Hintergrund zu schieben. Sollte nicht für normale Anwendungen benötigt werden."</string>
     <string name="permlab_dump" msgid="1681799862438954752">"Systeminternen Status abrufen"</string>
@@ -234,7 +234,7 @@
     <string name="permlab_systemAlertWindow" msgid="3372321942941168324">"Warnungen auf Systemebene anzeigen"</string>
     <string name="permdesc_systemAlertWindow" msgid="5109622689323490558">"Ermöglicht einer Anwendung, Fenster mit Systemwarnungen anzuzeigen. Schädliche Anwendungen können so das gesamte Display des Telefons einnehmen."</string>
     <string name="permlab_setAnimationScale" msgid="2805103241153907174">"Allgemeine Animationsgeschwindigkeit einstellen"</string>
-    <string name="permdesc_setAnimationScale" msgid="7181522138912391988">"Ermöglicht einer Anwendung, die allgemeine Animationsgeschwindigkeit (schnellere oder langsamere Animationen) jederzeit anzupassen."</string>
+    <string name="permdesc_setAnimationScale" msgid="7181522138912391988">"Ermöglicht einer Anwendung, die allgemeine Animationsgeschwindigkeit (schnellere oder langsamere Animationen) jederzeit anzupassen"</string>
     <string name="permlab_manageAppTokens" msgid="17124341698093865">"Anwendungs-Tokens verwalten"</string>
     <string name="permdesc_manageAppTokens" msgid="977127907524195988">"Ermöglicht Anwendungen, Ihre eigenen Tokens zu erstellen und zu verwalten. Hierbei wird die normale Z-Reihenfolge umgangen. Dies sollte nicht für normale Anwendungen benötigt werden."</string>
     <string name="permlab_injectEvents" msgid="1378746584023586600">"Tasten und Steuerungstasten drücken"</string>
@@ -250,23 +250,23 @@
     <string name="permlab_setOrientation" msgid="3365947717163866844">"Bildschirmausrichtung ändern"</string>
     <string name="permdesc_setOrientation" msgid="6335814461615851863">"Ermöglicht der Anwendung, die Bildschirmdrehung jederzeit zu ändern. Sollte nicht für normale Anwendungen benötigt werden."</string>
     <string name="permlab_signalPersistentProcesses" msgid="4255467255488653854">"Linux-Signale an Anwendungen senden"</string>
-    <string name="permdesc_signalPersistentProcesses" msgid="3565530463215015289">"Ermöglicht der Anwendung, das Senden des gelieferten Signals an alle anhaltenden Prozesse zu fordern."</string>
+    <string name="permdesc_signalPersistentProcesses" msgid="3565530463215015289">"Ermöglicht der Anwendung, das Senden des gelieferten Signals an alle anhaltenden Prozesse zu fordern"</string>
     <string name="permlab_persistentActivity" msgid="8659652042401085862">"Anwendungen permanent ausführen"</string>
-    <string name="permdesc_persistentActivity" msgid="5037199778265006008">"Ermöglicht einer Anwendung, eigene Komponenten persistent zu machen, damit das System diese nicht für andere Anwendungen nutzen kann."</string>
+    <string name="permdesc_persistentActivity" msgid="5037199778265006008">"Ermöglicht einer Anwendung, eigene Komponenten persistent zu machen, damit das System diese nicht für andere Anwendungen nutzen kann"</string>
     <string name="permlab_deletePackages" msgid="3343439331576348805">"Anwendungen löschen"</string>
     <string name="permdesc_deletePackages" msgid="3634943677518723314">"Ermöglicht einer Anwendung, Android-Pakete zu löschen. Schädliche Anwendungen können so wichtige Anwendungen löschen."</string>
     <string name="permlab_clearAppUserData" msgid="2192134353540277878">"Daten anderer Anwendungen löschen"</string>
-    <string name="permdesc_clearAppUserData" msgid="7546345080434325456">"Ermöglicht einer Anwendung das Löschen von Nutzerdaten."</string>
+    <string name="permdesc_clearAppUserData" msgid="7546345080434325456">"Ermöglicht einer Anwendung das Löschen von Nutzerdaten"</string>
     <string name="permlab_deleteCacheFiles" msgid="1518556602634276725">"Caches anderer Anwendungen löschen"</string>
-    <string name="permdesc_deleteCacheFiles" msgid="2283074077168165971">"Ermöglicht einer Anwendung, Cache-Dateien zu löschen."</string>
+    <string name="permdesc_deleteCacheFiles" msgid="2283074077168165971">"Ermöglicht einer Anwendung, Cache-Dateien zu löschen"</string>
     <string name="permlab_getPackageSize" msgid="4799785352306641460">"Speicherplatz der Anwendung abrufen"</string>
-    <string name="permdesc_getPackageSize" msgid="5557253039670753437">"Ermöglicht einer Anwendung, ihre Code-, Daten- und Cache-Größe abzurufen."</string>
+    <string name="permdesc_getPackageSize" msgid="5557253039670753437">"Ermöglicht einer Anwendung, ihre Code-, Daten- und Cache-Größe abzurufen"</string>
     <string name="permlab_installPackages" msgid="335800214119051089">"Anwendungen direkt installieren"</string>
     <string name="permdesc_installPackages" msgid="526669220850066132">"Ermöglicht einer Anwendung, neue oder aktualisierte Android-Pakete zu installieren. Schädliche Anwendungen können so neue Anwendungen mit beliebig umfangreichen Berechtigungen hinzufügen."</string>
     <string name="permlab_clearAppCache" msgid="4747698311163766540">"Alle Cache-Daten der Anwendung löschen"</string>
     <string name="permdesc_clearAppCache" msgid="7740465694193671402">"Ermöglicht einer Anwendung, Telefonspeicher durch das Löschen von Dateien im Cache-Verzeichnis der Anwendung freizugeben. Der Zugriff beschränkt sich in der Regel auf Systemprozesse."</string>
     <string name="permlab_movePackage" msgid="728454979946503926">"Anwendungsressourcen verschieben"</string>
-    <string name="permdesc_movePackage" msgid="6323049291923925277">"Ermöglicht einer Anwendung, Anwendungsressourcen von interne auf externe Medien zu verschieben und umgekehrt."</string>
+    <string name="permdesc_movePackage" msgid="6323049291923925277">"Ermöglicht einer Anwendung, Anwendungsressourcen von internen auf externe Medien zu verschieben und umgekehrt"</string>
     <string name="permlab_readLogs" msgid="6615778543198967614">"Lesen vertraulicher Protokolldaten"</string>
     <string name="permdesc_readLogs" msgid="8896449437464867766">"Ermöglicht einer Anwendung, die verschiedenen Protokolldateien des Systems zu lesen. So können allgemeine Informationen zu den auf Ihrem Telefon durchgeführten Aktionen eingesehen werden. Diese können persönliche oder geheime Daten enthalten."</string>
     <string name="permlab_diagnostic" msgid="8076743953908000342">"Lese-/Schreibberechtigung für zu Diagnosegruppe gehörige Elemente"</string>
@@ -284,7 +284,7 @@
     <string name="permlab_receiveBootCompleted" msgid="7776779842866993377">"Automatisch nach dem Booten starten"</string>
     <string name="permdesc_receiveBootCompleted" msgid="698336728415008796">"Ermöglicht einer Anwendung, sich selbst zu starten, sobald das System gebootet wurde. Dadurch kann es länger dauern, bis das Telefon gestartet wird, und durch die ständige Aktivität der Anwendung wird die gesamte Leistung des Telefons beeinträchtigt."</string>
     <string name="permlab_broadcastSticky" msgid="7919126372606881614">"dauerhaften Broadcast senden"</string>
-    <string name="permdesc_broadcastSticky" msgid="1920045289234052219">"Ermöglicht einer Anwendung, dauerhafte Broadcasts zu senden, die auch nach dem Ende des Broadcasts bestehen bleiben. Schädliche Anwendungen können das Telefon langsam oder unstabil machen, da zuviel Speicherplatz belegt ist."</string>
+    <string name="permdesc_broadcastSticky" msgid="1920045289234052219">"Ermöglicht einer Anwendung, dauerhafte Broadcasts zu senden, die auch nach dem Ende des Broadcasts bestehen bleiben. Schädliche Anwendungen können das Telefon langsam oder unstabil machen, da zuviel Speicherplatz belegt wird."</string>
     <string name="permlab_readContacts" msgid="6219652189510218240">"Kontaktdaten lesen"</string>
     <string name="permdesc_readContacts" msgid="3371591512896545975">"Ermöglicht einer Anwendung, alle auf Ihrem Telefon gespeicherten Kontaktdaten (Adressen) zu lesen. Schädliche Anwendungen können so Ihre Daten an andere Personen senden."</string>
     <string name="permlab_writeContacts" msgid="644616215860933284">"Kontaktdaten schreiben"</string>
@@ -292,8 +292,8 @@
     <string name="permlab_readCalendar" msgid="6898987798303840534">"Kalendereinträge lesen"</string>
     <string name="permdesc_readCalendar" msgid="5533029139652095734">"Ermöglicht einer Anwendung, alle auf Ihrem Telefon gespeicherten Kalenderereignisse zu lesen. Schädliche Anwendungen können so Ihre Kalenderereignisse an andere Personen senden."</string>
     <string name="permlab_writeCalendar" msgid="3894879352594904361">"Kalendereinträge hinzufügen oder ändern und E-Mails an Gäste senden"</string>
-    <string name="permdesc_writeCalendar" msgid="2988871373544154221">"Ermöglicht einer Anwendung, Einträge auf Ihrem Kalender hinzuzufügen oder zu ändern, die E-Mails an Gäste senden können. Schädliche Anwendungen können so Ihre Kalenderdaten löschen oder verändern oder E-Mails versenden."</string>
-    <string name="permlab_accessMockLocation" msgid="8688334974036823330">"Falsche Standortquellen für Testzwecke"</string>
+    <string name="permdesc_writeCalendar" msgid="2988871373544154221">"Ermöglicht einer Anwendung, Einträge in Ihrem Kalender hinzuzufügen oder zu ändern, wodurch E-Mails an Gäste gesendet werden können. Schädliche Anwendungen können so Ihre Kalenderdaten löschen oder verändern oder E-Mails versenden."</string>
+    <string name="permlab_accessMockLocation" msgid="8688334974036823330">"Simulierte Standortquellen für Testzwecke"</string>
     <string name="permdesc_accessMockLocation" msgid="7648286063459727252">"Erstellt falsche Standortquellen für Testzwecke. Schädliche Anwendungen können so den von den echten Standortquellen wie GPS oder Netzwerkanbieter zurückgegebenen Standort und/oder Status überschreiben."</string>
     <string name="permlab_accessLocationExtraCommands" msgid="2836308076720553837">"Auf zusätzliche Dienstanbieterbefehle für Standort zugreifen"</string>
     <string name="permdesc_accessLocationExtraCommands" msgid="1948144701382451721">"Zugriff auf zusätzliche Dienstanbieterbefehle für Standort. Schädliche Anwendungen könnten so die Funktionsweise von GPS oder anderen Standortquellen beeinträchtigen."</string>
@@ -302,25 +302,25 @@
     <string name="permlab_accessFineLocation" msgid="8116127007541369477">"genauer (GPS-) Standort"</string>
     <string name="permdesc_accessFineLocation" msgid="7411213317434337331">"Zugriff auf genaue Standortquellen wie GPS auf dem Telefon (falls verfügbar). Schädliche Anwendungen können damit bestimmen, so Sie sich befinden und so Ihren Akku zusätzlich belasten."</string>
     <string name="permlab_accessCoarseLocation" msgid="4642255009181975828">"ungefährer (netzwerkbasierter) Standort"</string>
-    <string name="permdesc_accessCoarseLocation" msgid="8235655958070862293">"Greift auf Quellen mit ungefähren Standortbestimmungen wie die Datenbank des Mobilfunknetzwerks zu, um falls möglich den ungefähren Standort des Telefons zu bestimmen. Schädliche Anwendungen können damit herauszufinden, wo Sie sich ungefähr befinden."</string>
+    <string name="permdesc_accessCoarseLocation" msgid="8235655958070862293">"Greift auf Quellen mit ungefähren Standortbestimmungen wie die Datenbank des Mobilfunknetzes zu, um falls möglich den ungefähren Standort des Tablets festzustellen. Schädliche Anwendungen können damit herausfinden, wo Sie sich ungefähr befinden"</string>
     <string name="permlab_accessSurfaceFlinger" msgid="2363969641792388947">"Auf SurfaceFlinger zugreifen"</string>
-    <string name="permdesc_accessSurfaceFlinger" msgid="6805241830020733025">"Ermöglicht einer Anwendung, die systemnahen SurfaceFlinger-Funktionen zu verwenden."</string>
+    <string name="permdesc_accessSurfaceFlinger" msgid="6805241830020733025">"Ermöglicht einer Anwendung, die systemnahen SurfaceFlinger-Funktionen zu verwenden"</string>
     <string name="permlab_readFrameBuffer" msgid="6690504248178498136">"Frame-Puffer lesen"</string>
-    <string name="permdesc_readFrameBuffer" msgid="7530020370469942528">"Ermöglicht einer Anwendung, den Content des Frame-Puffers zu lesen."</string>
+    <string name="permdesc_readFrameBuffer" msgid="7530020370469942528">"Ermöglicht einer Anwendung, den Content des Frame-Puffers zu lesen"</string>
     <string name="permlab_modifyAudioSettings" msgid="6095859937069146086">"Audio-Einstellungen ändern"</string>
-    <string name="permdesc_modifyAudioSettings" msgid="5793461287365991922">"Ermöglicht der Anwendung, Änderungen an allgemeinen Audioeinstellungen wie Lautstärke und Weiterleitung vorzunehmen."</string>
+    <string name="permdesc_modifyAudioSettings" msgid="5793461287365991922">"Ermöglicht der Anwendung, Änderungen an allgemeinen Audioeinstellungen wie Lautstärke und Weiterleitung vorzunehmen"</string>
     <string name="permlab_recordAudio" msgid="3876049771427466323">"Audio aufnehmen"</string>
-    <string name="permdesc_recordAudio" msgid="6493228261176552356">"Ermöglicht der Anwendung, auf den Pfad für Audioaufzeichnungen zuzugreifen."</string>
+    <string name="permdesc_recordAudio" msgid="6493228261176552356">"Ermöglicht der Anwendung, auf den Pfad für Audioaufzeichnungen zuzugreifen"</string>
     <string name="permlab_camera" msgid="3616391919559751192">"Bilder und Videos aufnehmen"</string>
     <string name="permdesc_camera" msgid="6004878235852154239">"Ermöglicht der Anwendung, Fotos und Videos mit der Kamera aufzunehmen. So kann die Anwendung jederzeit Bilder aus dem Sichtfeld der Kamera erfassen."</string>
-    <string name="permlab_brick" msgid="8337817093326370537">"Telefon dauerhaft deaktivieren."</string>
+    <string name="permlab_brick" msgid="8337817093326370537">"Telefon dauerhaft deaktivieren"</string>
     <string name="permdesc_brick" msgid="5569526552607599221">"Ermöglicht der Anwendung, das gesamte Telefon dauerhaft zu deaktivieren. Dies birgt hohe Risiken."</string>
     <string name="permlab_reboot" msgid="2898560872462638242">"Neustart des Telefons erzwingen"</string>
-    <string name="permdesc_reboot" msgid="7914933292815491782">"Ermöglicht der Anwendung, einen Neustart des Telefons zu erzwingen."</string>
+    <string name="permdesc_reboot" msgid="7914933292815491782">"Ermöglicht der Anwendung, einen Neustart des Telefons zu erzwingen"</string>
     <string name="permlab_mount_unmount_filesystems" msgid="1761023272170956541">"Dateisysteme bereitstellen oder Bereitstellung aufheben"</string>
-    <string name="permdesc_mount_unmount_filesystems" msgid="6253263792535859767">"Ermöglicht der Anwendung, Dateisysteme für austauschbare Datenträger bereitzustellen oder die Bereitstellung aufzuheben."</string>
+    <string name="permdesc_mount_unmount_filesystems" msgid="6253263792535859767">"Ermöglicht der Anwendung, Dateisysteme für austauschbare Datenträger bereitzustellen oder die Bereitstellung aufzuheben"</string>
     <string name="permlab_mount_format_filesystems" msgid="5523285143576718981">"Externen Speicher formatieren"</string>
-    <string name="permdesc_mount_format_filesystems" msgid="574060044906047386">"Ermöglicht der Anwendung, austauschbare Datenträger zu formatieren."</string>
+    <string name="permdesc_mount_format_filesystems" msgid="574060044906047386">"Ermöglicht der Anwendung, austauschbare Datenträger zu formatieren"</string>
     <string name="permlab_asec_access" msgid="3411338632002193846">"Informationen zum internen Speicher abrufen"</string>
     <string name="permdesc_asec_access" msgid="8820326551687285439">"Ermöglicht der Anwendung, Informationen zum internen Speicher abzurufen."</string>
     <string name="permlab_asec_create" msgid="6414757234789336327">"Internen Speicher erstellen"</string>
@@ -332,13 +332,13 @@
     <string name="permlab_asec_rename" msgid="7496633954080472417">"Internen Speicher umbenennen"</string>
     <string name="permdesc_asec_rename" msgid="2152829985238876790">"Ermöglicht der Anwendung, den internen Speicher umzubenennen."</string>
     <string name="permlab_vibrate" msgid="7768356019980849603">"Vibrationsalarm steuern"</string>
-    <string name="permdesc_vibrate" msgid="2886677177257789187">"Ermöglicht der Anwendung, den Vibrationsalarm zu steuern."</string>
+    <string name="permdesc_vibrate" msgid="2886677177257789187">"Ermöglicht der Anwendung, den Vibrationsalarm zu steuern"</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"Lichtanzeige steuern"</string>
-    <string name="permdesc_flashlight" msgid="6433045942283802309">"Ermöglicht der Anwendung, die Lichtanzeige zu steuern."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"auf USB-Geräte zugreifen"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Ermöglicht der Anwendung den Zugriff auf USB-Geräte."</string>
+    <string name="permdesc_flashlight" msgid="6433045942283802309">"Ermöglicht der Anwendung, die Lichtanzeige zu steuern"</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"Einstellungen und Berechtigungen für USB-Geräte verwalten"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Ermöglicht der Anwendung das Verwalten von Einstellungen und Berechtigungen für USB-Geräte"</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"Hardware testen"</string>
-    <string name="permdesc_hardware_test" msgid="3668894686500081699">"Ermöglicht einer Anwendung, verschiedene Peripherie-Geräte zu Hardware-Testzwecken zu steuern."</string>
+    <string name="permdesc_hardware_test" msgid="3668894686500081699">"Ermöglicht einer Anwendung, verschiedene Peripherie-Geräte zu Hardware-Testzwecken zu steuern"</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"Telefonnummern direkt anrufen"</string>
     <string name="permdesc_callPhone" msgid="3369867353692722456">"Ermöglicht dem Anwendungen, Rufnummern ohne Ihr Eingreifen zu wählen. Schädliche Anwendungen können für unerwartete Anrufe auf Ihrer Telefonrechnung verantwortlich sein. Das Wählen von Notrufnummern ist allerdings nicht möglich."</string>
     <string name="permlab_callPrivileged" msgid="4198349211108497879">"Alle Telefonnummern direkt anrufen"</string>
@@ -356,79 +356,83 @@
     <string name="permlab_readPhoneState" msgid="2326172951448691631">"Telefonstatus lesen und identifizieren"</string>
     <string name="permdesc_readPhoneState" msgid="188877305147626781">"Ermöglicht der Anwendung, auf die Telefonfunktionen des Gerätes zuzugreifen. Eine Anwendung mit dieser Berechtigung kann unter anderem bestimmen, welche Telefonnummer dieses Telefon verwendet, ob ein Anruf aktiv ist oder mit welcher Nummer der Anrufer verbunden ist."</string>
     <string name="permlab_wakeLock" msgid="573480187941496130">"Standby-Modus deaktivieren"</string>
-    <string name="permdesc_wakeLock" msgid="7584036471227467099">"Ermöglicht einer Anwendung, den Standby-Modus des Telefons zu deaktivieren."</string>
+    <string name="permdesc_wakeLock" msgid="7584036471227467099">"Ermöglicht einer Anwendung, den Standby-Modus des Telefons zu deaktivieren"</string>
     <string name="permlab_devicePower" msgid="4928622470980943206">"Gerät ein- oder ausschalten"</string>
-    <string name="permdesc_devicePower" msgid="4577331933252444818">"Ermöglicht der Anwendung, das Telefon ein- oder auszuschalten."</string>
+    <string name="permdesc_devicePower" msgid="4577331933252444818">"Ermöglicht der Anwendung, das Telefon ein- oder auszuschalten"</string>
     <string name="permlab_factoryTest" msgid="3715225492696416187">"In Werkstestmodus ausführen"</string>
-    <string name="permdesc_factoryTest" msgid="8136644990319244802">"Führt einen systemnahen Herstellertest durch, in dessen Rahmen auf die gesamte Telefonhardware zugegriffen werden kann. Nur verfügbar, wenn ein Telefon im Werkstestmodus ausgeführt wird."</string>
+    <string name="permdesc_factoryTest" msgid="8136644990319244802">"Führt einen systemnahen Herstellertest durch, in dessen Rahmen auf die gesamte Telefon-Hardware zugegriffen werden kann. Nur verfügbar, wenn ein Telefon im Herstellertestmodus ausgeführt wird."</string>
     <string name="permlab_setWallpaper" msgid="6627192333373465143">"Hintergrund festlegen"</string>
-    <string name="permdesc_setWallpaper" msgid="6417041752170585837">"Ermöglicht der Anwendung, den System-Hintergrund festzulegen."</string>
+    <string name="permdesc_setWallpaper" msgid="6417041752170585837">"Ermöglicht der Anwendung, den System-Hintergrund festzulegen"</string>
     <string name="permlab_setWallpaperHints" msgid="3600721069353106851">"Größenhinweise für Hintergrund festlegen"</string>
-    <string name="permdesc_setWallpaperHints" msgid="6019479164008079626">"Ermöglicht der Anwendung, die Größenhinweise für den Hintergrund festzulegen."</string>
+    <string name="permdesc_setWallpaperHints" msgid="6019479164008079626">"Ermöglicht der Anwendung, die Größenhinweise für den Hintergrund festzulegen"</string>
     <string name="permlab_masterClear" msgid="2315750423139697397">"System auf Werkseinstellung zurücksetzen"</string>
     <string name="permdesc_masterClear" msgid="5033465107545174514">"Ermöglicht einer Anwendung, das System komplett auf Werkseinstellung zurückzusetzen. Hierbei werden alle Daten, Konfigurationen und installierten Anwendungen gelöscht."</string>
     <string name="permlab_setTime" msgid="2021614829591775646">"Zeit einstellen"</string>
-    <string name="permdesc_setTime" msgid="667294309287080045">"Ermöglicht einer Anwendung, die Uhrzeit des Telefons zu ändern."</string>
+    <string name="permdesc_setTime" msgid="667294309287080045">"Ermöglicht einer Anwendung, die Uhrzeit des Telefons zu ändern"</string>
     <string name="permlab_setTimeZone" msgid="2945079801013077340">"Zeitzone festlegen"</string>
-    <string name="permdesc_setTimeZone" msgid="1902540227418179364">"Ermöglicht einer Anwendung, die Zeitzone des Telefons zu ändern."</string>
+    <string name="permdesc_setTimeZone" msgid="1902540227418179364">"Ermöglicht einer Anwendung, die Zeitzone des Telefons zu ändern"</string>
     <string name="permlab_accountManagerService" msgid="4829262349691386986">"Als Konto-Manager fungieren"</string>
-    <string name="permdesc_accountManagerService" msgid="6056903274106394752">"Ermöglicht einer Anwendung, Anrufe an Konto-Authentifizierer zu tätigen."</string>
+    <string name="permdesc_accountManagerService" msgid="6056903274106394752">"Ermöglicht einer Anwendung, Anrufe an Konto-Authentifizierer zu tätigen"</string>
     <string name="permlab_getAccounts" msgid="4549918644233460103">"bekannte Konten suchen"</string>
-    <string name="permdesc_getAccounts" msgid="6839262446413155394">"Ermöglicht einer Anwendung, eine Liste der dem Telefon bekannten Konten abzurufen."</string>
+    <string name="permdesc_getAccounts" msgid="6839262446413155394">"Ermöglicht einer Anwendung, eine Liste der dem Telefon bekannten Konten abzurufen"</string>
     <string name="permlab_authenticateAccounts" msgid="3940505577982882450">"Als Kontoauthentifizierer fungieren"</string>
-    <string name="permdesc_authenticateAccounts" msgid="4006839406474208874">"Ermöglicht einer Anwendung, die Kontoauthentifizierungsfunktionen des Konto-Managers zu verwenden, einschließlich die Funktionen zum Erstellen von Konten und zum Abrufen und Einstellen der entsprechenden Passwörter."</string>
+    <string name="permdesc_authenticateAccounts" msgid="4006839406474208874">"Ermöglicht einer Anwendung, die Kontoauthentifizierungsfunktionen des Konto-Managers zu verwenden, einschließlich die Funktionen zum Erstellen von Konten und zum Abrufen und Einstellen der entsprechenden Passwörter"</string>
     <string name="permlab_manageAccounts" msgid="4440380488312204365">"Kontoliste verwalten"</string>
-    <string name="permdesc_manageAccounts" msgid="8804114016661104517">"Ermöglicht einer Anwendung, Konten hinzuzufügen und zu entfernen oder deren Passwörter zu löschen."</string>
+    <string name="permdesc_manageAccounts" msgid="8804114016661104517">"Ermöglicht einer Anwendung, Konten hinzuzufügen und zu entfernen oder deren Passwörter zu löschen"</string>
     <string name="permlab_useCredentials" msgid="6401886092818819856">"Authentifizierungsinformationen eines Kontos verwenden"</string>
-    <string name="permdesc_useCredentials" msgid="7416570544619546974">"Ermöglicht einer Anwendung, Authentifizierungs-Token anzufordern."</string>
+    <string name="permdesc_useCredentials" msgid="7416570544619546974">"Ermöglicht einer Anwendung, Authentifizierungs-Token anzufordern"</string>
     <string name="permlab_accessNetworkState" msgid="6865575199464405769">"Netzwerkstatus anzeigen"</string>
-    <string name="permdesc_accessNetworkState" msgid="558721128707712766">"Ermöglicht einer Anwendung, den Status aller Netzwerke anzuzeigen."</string>
+    <string name="permdesc_accessNetworkState" msgid="558721128707712766">"Ermöglicht einer Anwendung, den Status aller Netzwerke anzuzeigen"</string>
     <string name="permlab_createNetworkSockets" msgid="9121633680349549585">"uneingeschränkter Internetzugriff"</string>
-    <string name="permdesc_createNetworkSockets" msgid="4593339106921772192">"Ermöglicht einer Anwendung, Netzwerk-Sockets einzurichten."</string>
+    <string name="permdesc_createNetworkSockets" msgid="4593339106921772192">"Ermöglicht einer Anwendung, Netzwerk-Sockets einzurichten"</string>
     <string name="permlab_writeApnSettings" msgid="7823599210086622545">"Einstellungen für Zugriffspunktname schreiben"</string>
-    <string name="permdesc_writeApnSettings" msgid="7443433457842966680">"Ermöglicht einer Anwendung, die APN-Einstellungen wie Proxy und Port eines Zugriffspunkts zu ändern."</string>
+    <string name="permdesc_writeApnSettings" msgid="7443433457842966680">"Ermöglicht einer Anwendung, die APN-Einstellungen wie Proxy und Port eines Zugriffspunkts zu ändern"</string>
     <string name="permlab_changeNetworkState" msgid="958884291454327309">"Netzwerkkonnektivität ändern"</string>
-    <string name="permdesc_changeNetworkState" msgid="4199958910396387075">"Ermöglicht einer Anwendung, den Status der Netzwerkkonnektivität zu ändern."</string>
+    <string name="permdesc_changeNetworkState" msgid="4199958910396387075">"Ermöglicht einer Anwendung, den Status der Netzwerkkonnektivität zu ändern"</string>
     <string name="permlab_changeTetherState" msgid="2702121155761140799">"Tethering-Konnektivität ändern"</string>
-    <string name="permdesc_changeTetherState" msgid="8905815579146349568">"Ermöglicht einer Anwendung, den Status der Tethering-Konnektivität zu ändern."</string>
+    <string name="permdesc_changeTetherState" msgid="8905815579146349568">"Ermöglicht einer Anwendung, den Status der Tethering-Konnektivität zu ändern"</string>
     <string name="permlab_changeBackgroundDataSetting" msgid="1400666012671648741">"Einstellung zur Verwendung von Hintergrunddaten ändern"</string>
-    <string name="permdesc_changeBackgroundDataSetting" msgid="1001482853266638864">"Ermöglicht einer Anwendung, die Einstellung der Verwendung von Hintergrunddaten zu ändern."</string>
+    <string name="permdesc_changeBackgroundDataSetting" msgid="1001482853266638864">"Ermöglicht einer Anwendung, die Einstellung der Verwendung von Hintergrunddaten zu ändern"</string>
     <string name="permlab_accessWifiState" msgid="8100926650211034400">"WLAN-Status anzeigen"</string>
-    <string name="permdesc_accessWifiState" msgid="485796529139236346">"Ermöglicht einer Anwendung, die Informationen zum WLAN-Status einzusehen."</string>
+    <string name="permdesc_accessWifiState" msgid="485796529139236346">"Ermöglicht einer Anwendung, die Informationen zum WLAN-Status einzusehen"</string>
     <string name="permlab_changeWifiState" msgid="7280632711057112137">"WLAN-Status ändern"</string>
-    <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Ermöglicht einer Anwendung, eine Verbindung zu den WLAN-Zugangspunkten herzustellen und diese zu trennen oder Änderungen an den konfigurierten WLAN-Netzwerken vorzunehmen."</string>
+    <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Ermöglicht einer Anwendung, eine Verbindung zu den WLAN-Zugangspunkten herzustellen und diese zu trennen oder Änderungen an den konfigurierten WLAN-Netzwerken vorzunehmen"</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"WLAN-Multicast-Empfang zulassen"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Ermöglicht einer Anwendung, Datenpakete zu empfangen, die nicht direkt an Ihr Gerät gerichtet sind. Dies kann bei der Erkennung von in der Nähe angebotenen Diensten hilfreich sein. Diese Einstellung verbraucht mehr Energie als der Nicht-Multicast-Modus."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"WiMAX-Status anzeigen"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Ermöglicht einer Anwendung, die Informationen zum WiMAX-Status einzusehen"</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"WiMAX-Status ändern"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Ermöglicht einer Anwendung, eine Verbindung mit dem WiMAX-Netzwerk herzustellen bzw. zu trennen"</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"Bluetooth-Verwaltung"</string>
-    <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Ermöglicht einer Anwendung, das lokale Bluetooth-Telefon zu konfigurieren, Remote-Geräte zu erkennen und eine Verbindung zu diesen herzustellen."</string>
+    <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Ermöglicht einer Anwendung, das lokale Bluetooth-Telefon zu konfigurieren, Remote-Geräte zu erkennen und eine Verbindung zu diesen herzustellen"</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"Bluetooth-Verbindungen herstellen"</string>
-    <string name="permdesc_bluetooth" msgid="762515380679392945">"Ermöglicht einer Anwendung, die Konfiguration des lokalen Bluetooth-Telefons einzusehen und Verbindungen mit Partnergeräten herzustellen und zu akzeptieren."</string>
+    <string name="permdesc_bluetooth" msgid="762515380679392945">"Ermöglicht einer Anwendung, die Konfiguration des lokalen Bluetooth-Telefons einzusehen und Verbindungen mit Partnergeräten herzustellen und zu akzeptieren"</string>
     <string name="permlab_nfc" msgid="4423351274757876953">"Nahfeldkommunikation steuern"</string>
-    <string name="permdesc_nfc" msgid="9171401851954407226">"Ermöglicht einer Anwendung die Kommunikation mit Tags für die Nahfeldkommunikation, Karten und Readern."</string>
+    <string name="permdesc_nfc" msgid="9171401851954407226">"Ermöglicht einer Anwendung die Kommunikation mit Tags für Nahfeldkommunikation, Karten und Lesegeräte"</string>
     <string name="permlab_disableKeyguard" msgid="4977406164311535092">"Tastensperre deaktivieren"</string>
     <string name="permdesc_disableKeyguard" msgid="3189763479326302017">"Ermöglicht einer Anwendung, die Tastensperre sowie den damit verbundenen Passwortschutz zu deaktivieren. So wird die Tastensperre vom Telefon deaktiviert, wenn ein Anruf eingeht, und nach Beendigung des Anrufs wieder aktiviert."</string>
     <string name="permlab_readSyncSettings" msgid="6201810008230503052">"Synchronisierungseinstellungen lesen"</string>
-    <string name="permdesc_readSyncSettings" msgid="5315925706353341823">"Ermöglicht einer Anwendung, die Synchronisierungseinstellungen zu lesen, etwa ob die Synchronisierung für Kontakte aktiviert ist oder nicht."</string>
+    <string name="permdesc_readSyncSettings" msgid="5315925706353341823">"Ermöglicht einer Anwendung, die Synchronisierungseinstellungen zu lesen, etwa ob die Synchronisierung für Kontakte aktiviert ist oder nicht"</string>
     <string name="permlab_writeSyncSettings" msgid="6297138566442486462">"Synchronisierungseinstellungen schreiben"</string>
-    <string name="permdesc_writeSyncSettings" msgid="2498201614431360044">"Ermöglicht einer Anwendung, die Synchronisierungseinstellungen zu ändern, etwa ob die Synchronisierung für Kontakte aktiviert ist oder nicht."</string>
+    <string name="permdesc_writeSyncSettings" msgid="2498201614431360044">"Ermöglicht einer Anwendung, die Synchronisierungseinstellungen zu ändern, etwa ob die Synchronisierung für Kontakte aktiviert ist oder nicht"</string>
     <string name="permlab_readSyncStats" msgid="7396577451360202448">"Synchronisierungsstatistiken lesen"</string>
-    <string name="permdesc_readSyncStats" msgid="7511448343374465000">"Ermöglicht einer Anwendung, die Synchronisierungsstatistiken zu lesen, etwa den Verlauf der bereits durchgeführten Synchronisierungen."</string>
+    <string name="permdesc_readSyncStats" msgid="7511448343374465000">"Ermöglicht einer Anwendung, die Synchronisierungsstatistiken zu lesen, etwa den Verlauf der bereits durchgeführten Synchronisierungen"</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"abonnierte Feeds lesen"</string>
-    <string name="permdesc_subscribedFeedsRead" msgid="3622200625634207660">"Ermöglicht einer Anwendung, Details zu den zurzeit synchronisierten Feeds abzurufen."</string>
+    <string name="permdesc_subscribedFeedsRead" msgid="3622200625634207660">"Ermöglicht einer Anwendung, Details zu den zurzeit synchronisierten Feeds abzurufen"</string>
     <string name="permlab_subscribedFeedsWrite" msgid="9015246325408209296">"abonnierte Feeds schreiben"</string>
     <string name="permdesc_subscribedFeedsWrite" msgid="8121607099326533878">"Ermöglicht einer Anwendung, Änderungen an den kürzlich synchronisierten Feeds vorzunehmen. Schädliche Anwendungen könnten so Ihre synchronisierten Feeds ändern."</string>
     <string name="permlab_readDictionary" msgid="432535716804748781">"nutzerdefiniertes Wörterbuch lesen"</string>
-    <string name="permdesc_readDictionary" msgid="1082972603576360690">"Ermöglicht einer Anwendung, alle privaten Wörter, Namen und Ausdrücke zu lesen, die ein Nutzer in seinem Wörterbuch gespeichert hat."</string>
+    <string name="permdesc_readDictionary" msgid="1082972603576360690">"Ermöglicht einer Anwendung, alle privaten Wörter, Namen und Ausdrücke zu lesen, die ein Nutzer in seinem Wörterbuch gespeichert hat"</string>
     <string name="permlab_writeDictionary" msgid="6703109511836343341">"in nutzerdefiniertes Wörterbuch schreiben"</string>
-    <string name="permdesc_writeDictionary" msgid="2241256206524082880">"Ermöglicht einer Anwendung, Ihrem Wörterbuch neue Einträge hinzuzufügen."</string>
-    <string name="permlab_sdcardWrite" product="nosdcard" msgid="85430876310764752">"USB-Speicherinh. ändern/lösch."</string>
+    <string name="permdesc_writeDictionary" msgid="2241256206524082880">"Ermöglicht einer Anwendung, Ihrem Wörterbuch neue Einträge hinzuzufügen"</string>
+    <string name="permlab_sdcardWrite" product="nosdcard" msgid="85430876310764752">"USB-Speicherinhalt ändern/löschen"</string>
     <string name="permlab_sdcardWrite" product="default" msgid="8079403759001777291">"SD-Karten-Inhalt ändern/löschen"</string>
     <string name="permdesc_sdcardWrite" product="nosdcard" msgid="6594393334785738252">"Ermöglicht der Anwendung Schreiben in USB-Speicher"</string>
     <string name="permdesc_sdcardWrite" product="default" msgid="6643963204976471878">"Ermöglicht einer Anwendung, auf die SD-Karte zu schreiben"</string>
     <string name="permlab_cache_filesystem" msgid="5656487264819669824">"Zugriff auf das Cache-Dateisystem"</string>
     <string name="permdesc_cache_filesystem" msgid="1624734528435659906">"Gewährt einer Anwendung Lese- und Schreibzugriff auf das Cache-Dateisystem."</string>
     <string name="permlab_use_sip" msgid="5986952362795870502">"Internetanrufe tätigen/annehmen"</string>
-    <string name="permdesc_use_sip" msgid="6320376185606661843">"Ermöglicht einer Anwendung die Verwendung des SIP-Dienstes zum Tätigen/Annehmen von Internetanrufen."</string>
+    <string name="permdesc_use_sip" msgid="6320376185606661843">"Ermöglicht einer Anwendung die Verwendung des SIP-Dienstes zum Tätigen/Annehmen von Internetanrufen"</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Passwortregeln festlegen"</string>
     <string name="policydesc_limitPassword" msgid="9083400080861728056">"Zulässige Länge und Zeichen für Passwörter zum Entsperren des Displays festlegen"</string>
     <string name="policylab_watchLogin" msgid="914130646942199503">"Versuche zum Entsperren des Displays überwachen"</string>
@@ -436,7 +440,7 @@
     <string name="policylab_resetPassword" msgid="2620077191242688955">"Passwort zum Entsperren des Displays ändern"</string>
     <string name="policydesc_resetPassword" msgid="5391240616981297361">"Passwort zum Entsperren des Displays ändern"</string>
     <string name="policylab_forceLock" msgid="2274085384704248431">"Display sperren"</string>
-    <string name="policydesc_forceLock" msgid="5696964126226028442">"Steuern Sie, wie und wann das Display gesperrt wird."</string>
+    <string name="policydesc_forceLock" msgid="5696964126226028442">"Festlegen, wie und wann das Display gesperrt wird"</string>
     <string name="policylab_wipeData" msgid="3910545446758639713">"Alle Daten löschen"</string>
     <string name="policydesc_wipeData" msgid="7669895333814222586">"Auf Werkseinstellungen zurücksetzen und Daten auf dem Telefon ohne Warnung löschen"</string>
   <string-array name="phoneTypes">
@@ -446,19 +450,19 @@
     <item msgid="1103601433382158155">"Fax (geschäftl.)"</item>
     <item msgid="1735177144948329370">"Fax (privat)"</item>
     <item msgid="603878674477207394">"Pager"</item>
-    <item msgid="1650824275177931637">"Sonstige"</item>
+    <item msgid="1650824275177931637">"Andere"</item>
     <item msgid="9192514806975898961">"Benutzerdefiniert"</item>
   </string-array>
   <string-array name="emailAddressTypes">
     <item msgid="8073994352956129127">"Privat"</item>
     <item msgid="7084237356602625604">"Geschäftlich"</item>
-    <item msgid="1112044410659011023">"Sonstige"</item>
+    <item msgid="1112044410659011023">"Andere"</item>
     <item msgid="2374913952870110618">"Benutzerdefiniert"</item>
   </string-array>
   <string-array name="postalAddressTypes">
     <item msgid="6880257626740047286">"Privat"</item>
     <item msgid="5629153956045109251">"Geschäftlich"</item>
-    <item msgid="4966604264500343469">"Sonstige"</item>
+    <item msgid="4966604264500343469">"Andere"</item>
     <item msgid="4932682847595299369">"Benutzerdefiniert"</item>
   </string-array>
   <string-array name="imAddressTypes">
@@ -469,7 +473,7 @@
   </string-array>
   <string-array name="organizationTypes">
     <item msgid="7546335612189115615">"Geschäftlich"</item>
-    <item msgid="4378074129049520373">"Sonstige"</item>
+    <item msgid="4378074129049520373">"Andere"</item>
     <item msgid="3455047468583965104">"Benutzerdefiniert"</item>
   </string-array>
   <string-array name="imProtocols">
@@ -544,7 +548,7 @@
     <string name="keyguard_label_text" msgid="861796461028298424">"Drücken Sie zum Entsperren die Menütaste und dann auf \"0\"."</string>
     <string name="emergency_call_dialog_number_for_display" msgid="696192103195090970">"Notrufnummer"</string>
     <string name="lockscreen_carrier_default" msgid="8812714795156374435">"(kein Dienst)"</string>
-    <string name="lockscreen_screen_locked" msgid="7288443074806832904">"Display gesperrt."</string>
+    <string name="lockscreen_screen_locked" msgid="7288443074806832904">"Display gesperrt"</string>
     <string name="lockscreen_instructions_when_pattern_enabled" msgid="46154051614126049">"Drücken Sie die Menütaste, um das Telefon zu entsperren oder einen Notruf zu tätigen."</string>
     <string name="lockscreen_instructions_when_pattern_disabled" msgid="686260028797158364">"Zum Entsperren die Menütaste drücken"</string>
     <string name="lockscreen_pattern_instructions" msgid="7478703254964810302">"Muster zum Entsperren zeichnen"</string>
@@ -561,7 +565,7 @@
     <string name="lockscreen_missing_sim_instructions" msgid="8874620818937719067">"Bitte legen Sie eine SIM-Karte ein."</string>
     <string name="emergency_calls_only" msgid="6733978304386365407">"Nur Notrufe"</string>
     <string name="lockscreen_network_locked_message" msgid="143389224986028501">"Netzwerk gesperrt"</string>
-    <string name="lockscreen_sim_puk_locked_message" msgid="7441797339976230">"SIM-Karte ist gesperrt. PUK-Eingabe erforderlich."</string>
+    <string name="lockscreen_sim_puk_locked_message" msgid="7441797339976230">"PUK-Sperre auf SIM"</string>
     <string name="lockscreen_sim_puk_locked_instructions" msgid="635967534992394321">"Weitere Informationen finden Sie in der Bedienungsanleitung oder wenden Sie sich an den Kundendienst."</string>
     <string name="lockscreen_sim_locked_message" msgid="8066660129206001039">"Bitte PIN-Code eingeben"</string>
     <string name="lockscreen_sim_unlock_progress_dialog_message" msgid="595323214052881264">"SIM-Karte wird entsperrt..."</string>
@@ -588,14 +592,14 @@
     <string name="factorytest_failed" msgid="5410270329114212041">"Werkstest fehlgeschlagen"</string>
     <string name="factorytest_not_system" msgid="4435201656767276723">"Die Aktion FACTORY_TEST wird nur für unter \"/system/app\" gespeicherte Pakete unterstützt."</string>
     <string name="factorytest_no_action" msgid="872991874799998561">"Es wurden kein Paket mit der Aktion FACTORY_TEST gefunden."</string>
-    <string name="factorytest_reboot" msgid="6320168203050791643">"Neu booten"</string>
+    <string name="factorytest_reboot" msgid="6320168203050791643">"Neustart"</string>
     <string name="js_dialog_title" msgid="8143918455087008109">"Die Seite auf \'<xliff:g id="TITLE">%s</xliff:g>\' sagt:"</string>
     <string name="js_dialog_title_default" msgid="6961903213729667573">"JavaScript"</string>
     <string name="js_dialog_before_unload" msgid="1901675448179653089">"Von dieser Seite navigieren?"\n\n"<xliff:g id="MESSAGE">%s</xliff:g>"\n\n"Wählen Sie \"OK\", um fortzufahren, oder wählen Sie \"Abbrechen\", um auf der aktuellen Seite zu bleiben."</string>
     <string name="save_password_label" msgid="6860261758665825069">"Bestätigen"</string>
     <string name="double_tap_toast" msgid="1068216937244567247">"Tipp: Zum Heranzoomen und Vergrößern zweimal tippen"</string>
     <string name="permlab_readHistoryBookmarks" msgid="1284843728203412135">"Browserverlauf und Lesezeichen lesen"</string>
-    <string name="permdesc_readHistoryBookmarks" msgid="4981489815467617191">"Ermöglicht der Anwendung, alle URLs, die mit dem Browser besucht wurden, sowie alle Lesezeichen des Browsers zu lesen."</string>
+    <string name="permdesc_readHistoryBookmarks" msgid="4981489815467617191">"Ermöglicht der Anwendung, alle URLs, die mit dem Browser besucht wurden, sowie alle Lesezeichen des Browsers zu lesen"</string>
     <string name="permlab_writeHistoryBookmarks" msgid="9009434109836280374">"Browserverlauf und Lesezeichen schreiben"</string>
     <string name="permdesc_writeHistoryBookmarks" msgid="945571990357114950">"Ermöglicht einer Anwendung, den auf Ihrem Telefon gespeicherten Browserverlauf und die Lesezeichen zu ändern. Schädliche Anwendungen können so Ihre Browserdaten löschen oder ändern."</string>
     <string name="permlab_setAlarm" msgid="5924401328803615165">"Alarm im Wecker festlegen"</string>
@@ -605,7 +609,7 @@
     <string name="save_password_message" msgid="767344687139195790">"Möchten Sie, dass der Browser dieses Passwort speichert?"</string>
     <string name="save_password_notnow" msgid="6389675316706699758">"Nicht jetzt"</string>
     <string name="save_password_remember" msgid="6491879678996749466">"Speichern"</string>
-    <string name="save_password_never" msgid="8274330296785855105">"Niemals"</string>
+    <string name="save_password_never" msgid="8274330296785855105">"Nie"</string>
     <string name="open_permission_deny" msgid="5661861460947222274">"Sie sind zum Öffnen dieser Seite nicht berechtigt."</string>
     <string name="text_copied" msgid="4985729524670131385">"Text in Zwischenablage kopiert."</string>
     <string name="more_item_label" msgid="4650918923083320495">"Mehr"</string>
@@ -613,7 +617,7 @@
     <string name="menu_space_shortcut_label" msgid="2410328639272162537">"Leerzeichen"</string>
     <string name="menu_enter_shortcut_label" msgid="2743362785111309668">"Enter"</string>
     <string name="menu_delete_shortcut_label" msgid="3658178007202748164">"löschen"</string>
-    <string name="search_go" msgid="8298016669822141719">"Suche"</string>
+    <string name="search_go" msgid="8298016669822141719">"Suchen"</string>
     <string name="oneMonthDurationPast" msgid="7396384508953779925">"Vor 1 Monat"</string>
     <string name="beforeOneMonthDurationPast" msgid="909134546836499826">"Vor mehr als 1 Monat"</string>
   <plurals name="num_seconds_ago">
@@ -721,18 +725,19 @@
     <string name="addToDictionary" msgid="8793624991686948709">"\"<xliff:g id="WORD">%s</xliff:g>\" zum Wörterbuch hinzufügen"</string>
     <string name="editTextMenuTitle" msgid="1672989176958581452">"Text bearbeiten"</string>
     <string name="low_internal_storage_view_title" msgid="1399732408701697546">"Geringer Speicher"</string>
-    <string name="low_internal_storage_view_text" msgid="635106544616378836">"Kaum noch Telefonspeicher frei."</string>
+    <string name="low_internal_storage_view_text" msgid="635106544616378836">"Kaum noch Telefonspeicher frei"</string>
     <string name="ok" msgid="5970060430562524910">"OK"</string>
     <string name="cancel" msgid="6442560571259935130">"Abbrechen"</string>
     <string name="yes" msgid="5362982303337969312">"OK"</string>
     <string name="no" msgid="5141531044935541497">"Abbrechen"</string>
     <string name="dialog_alert_title" msgid="2049658708609043103">"Achtung"</string>
     <string name="capital_on" msgid="1544682755514494298">"EIN"</string>
-    <string name="capital_off" msgid="6815870386972805832">"Aus"</string>
+    <string name="capital_off" msgid="6815870386972805832">"AUS"</string>
     <string name="whichApplication" msgid="4533185947064773386">"Aktion durchführen mit"</string>
-    <string name="alwaysUse" msgid="4583018368000610438">"Standardmäßig für diese Aktion verwenden."</string>
-    <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Standardeinstellung zurücksetzen unter \"Einstellungen &gt; Anwendungen &gt; Anwendungen verwalten\"."</string>
+    <string name="alwaysUse" msgid="4583018368000610438">"Standardmäßig für diese Aktion verwenden"</string>
+    <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Standardeinstellung zurücksetzen unter \"Einstellungen &gt; Anwendungen &gt; Anwendungen verwalten\""</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Aktion auswählen"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Anwendung für das USB-Gerät auswählen"</string>
     <string name="noApplications" msgid="1691104391758345586">"Diese Aktion kann von keiner Anwendung ausgeführt werden."</string>
     <string name="aerr_title" msgid="653922989522758100">"Tut uns leid!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"Die Anwendung <xliff:g id="APPLICATION">%1$s</xliff:g> (Prozess <xliff:g id="PROCESS">%2$s</xliff:g>) wurde unerwartet beendet. Versuchen Sie es erneut."</string>
@@ -751,13 +756,13 @@
     <string name="smv_application" msgid="295583804361236288">"Die Anwendung <xliff:g id="APPLICATION">%1$s</xliff:g> (Prozess <xliff:g id="PROCESS">%2$s</xliff:g>) hat gegen ihre selbsterzwungene StrictMode-Richtlinie verstoßen."</string>
     <string name="smv_process" msgid="5120397012047462446">"Der Prozess <xliff:g id="PROCESS">%1$s</xliff:g> hat gegen seine selbsterzwungene StrictMode-Richtlinie verstoßen."</string>
     <string name="heavy_weight_notification" msgid="9087063985776626166">"<xliff:g id="APP">%1$s</xliff:g> läuft"</string>
-    <string name="heavy_weight_notification_detail" msgid="2423977499339403402">"Auswählen zum Wechseln in die Anwendung"</string>
+    <string name="heavy_weight_notification_detail" msgid="2423977499339403402">"Zum Wechseln in die Anwendung auswählen"</string>
     <string name="heavy_weight_switcher_title" msgid="1135403633766694316">"Anwendung wechseln?"</string>
     <string name="heavy_weight_switcher_text" msgid="4592075610079319667">"Es läuft gerade eine andere Anwendung, die vor dem Start einer neuen beendet werden muss."</string>
     <string name="old_app_action" msgid="493129172238566282">"Zu <xliff:g id="OLD_APP">%1$s</xliff:g> zurückkehren"</string>
-    <string name="old_app_description" msgid="942967900237208466">"Die neue Anwendung nicht starten."</string>
+    <string name="old_app_description" msgid="942967900237208466">"Die neue Anwendung nicht starten"</string>
     <string name="new_app_action" msgid="5472756926945440706">"<xliff:g id="OLD_APP">%1$s</xliff:g> starten"</string>
-    <string name="new_app_description" msgid="6830398339826789493">"Anwendung beenden, ohne zu speichern."</string>
+    <string name="new_app_description" msgid="6830398339826789493">"Anwendung beenden, ohne zu speichern"</string>
     <string name="sendText" msgid="5132506121645618310">"Aktion für Text auswählen"</string>
     <string name="volume_ringtone" msgid="6885421406845734650">"Klingeltonlautstärke"</string>
     <string name="volume_music" msgid="5421651157138628171">"Medienlautstärke"</string>
@@ -802,14 +807,14 @@
     <string name="usb_storage_notification_title" msgid="8175892554757216525">"USB-Verbindung"</string>
     <string name="usb_storage_notification_message" msgid="7380082404288219341">"Zum Kopieren von Dateien zum/vom Computer"</string>
     <string name="usb_storage_stop_notification_title" msgid="2336058396663516017">"USB-Speicher deaktivieren"</string>
-    <string name="usb_storage_stop_notification_message" msgid="2591813490269841539">"Auswählen, um USB-Speicher zu deaktivieren."</string>
+    <string name="usb_storage_stop_notification_message" msgid="2591813490269841539">"USB-Speicher deaktivieren: auswählen"</string>
     <string name="usb_storage_stop_title" msgid="660129851708775853">"USB-Speicher in Verwendung"</string>
     <string name="usb_storage_stop_message" product="nosdcard" msgid="1368842269463745067">"Stellen Sie vor dem Deaktivieren des USB-Speichers sicher, dass Sie den Android-USB-Speicher von Ihrem Computer getrennt (\"ausgeworfen\") haben."</string>
-    <string name="usb_storage_stop_message" product="default" msgid="3613713396426604104">"Stellen Sie vor dem Deaktivieren des USB-Speichers sicher, dass Sie Ihre Android-SD-Karte von Ihrem Computer getrennt (\"ausgeworfen\") haben."</string>
+    <string name="usb_storage_stop_message" product="default" msgid="3613713396426604104">"Achten Sie vor dem Deaktivieren des USB-Speichers darauf, dass Sie die Android-SD-Karte von Ihrem Computer getrennt (\"ausgeworfen\") haben."</string>
     <string name="usb_storage_stop_button_mount" msgid="7060218034900696029">"USB-Speicher deaktivieren"</string>
     <string name="usb_storage_stop_error_message" msgid="143881914840412108">"Beim Deaktivieren des USB-Speichers ist ein Problem aufgetreten. Überprüfen Sie, ob Sie den USB-Host getrennt haben, und versuchen Sie es erneut."</string>
     <string name="dlg_confirm_kill_storage_users_title" msgid="963039033470478697">"USB-Speicher aktivieren"</string>
-    <string name="dlg_confirm_kill_storage_users_text" msgid="3202838234780505886">"Wenn Sie den USB-Speicher aktivieren, werden einige von Ihnen verwendeten Anwendungen angehalten und sind möglicherweise nicht verfügbar, bis Sie den USB-Speicher wieder deaktivieren."</string>
+    <string name="dlg_confirm_kill_storage_users_text" msgid="3202838234780505886">"Wenn Sie den USB-Speicher aktivieren, werden einige von Ihnen verwendete Anwendungen angehalten und sind möglicherweise nicht verfügbar, bis Sie den USB-Speicher wieder deaktivieren."</string>
     <string name="dlg_error_title" msgid="8048999973837339174">"USB-Vorgang fehlgeschlagen"</string>
     <string name="dlg_ok" msgid="7376953167039865701">"OK"</string>
     <string name="extmedia_format_title" product="nosdcard" msgid="7980995592595097841">"USB-Sp. formatieren"</string>
@@ -818,39 +823,39 @@
     <string name="extmedia_format_message" product="default" msgid="3621369962433523619">"Möchten Sie die SD-Karte wirklich formatieren? Alle Daten auf Ihrer Karte gehen dann verloren."</string>
     <string name="extmedia_format_button_format" msgid="4131064560127478695">"Format"</string>
     <string name="adb_active_notification_title" msgid="6729044778949189918">"USB-Debugging verbunden"</string>
-    <string name="adb_active_notification_message" msgid="8470296818270110396">"Auswählen, um USB-Debugging zu deaktivieren."</string>
+    <string name="adb_active_notification_message" msgid="8470296818270110396">"USB-Debugging deaktivieren: auswählen"</string>
     <string name="select_input_method" msgid="6865512749462072765">"Eingabemethode auswählen"</string>
     <string name="fast_scroll_alphabet" msgid="5433275485499039199">" ABCDEFGHIJKLMNOPQRSTUVWXYZ"</string>
     <string name="fast_scroll_numeric_alphabet" msgid="4030170524595123610">" 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"</string>
     <string name="candidates_style" msgid="4333913089637062257"><u>"Kandidaten"</u></string>
     <string name="ext_media_checking_notification_title" product="nosdcard" msgid="3449816005351468560">"USB-Speicher wird vorbereitet."</string>
-    <string name="ext_media_checking_notification_title" product="default" msgid="5457603418970994050">"SD-Karte wird vorbereitet"</string>
+    <string name="ext_media_checking_notification_title" product="default" msgid="5457603418970994050">"SD-Karte wird vorbereitet..."</string>
     <string name="ext_media_checking_notification_message" msgid="8287319882926737053">"Suche nach Fehlern"</string>
     <string name="ext_media_nofs_notification_title" product="nosdcard" msgid="7788040745686229307">"USB-Speicher leer"</string>
     <string name="ext_media_nofs_notification_title" product="default" msgid="780477838241212997">"SD-Karte leer"</string>
     <string name="ext_media_nofs_notification_message" product="nosdcard" msgid="8623130522556087311">"USB-Speicher ist leer oder verfügt über ein nicht unterstütztes Dateisystem."</string>
     <string name="ext_media_nofs_notification_message" product="default" msgid="3817704088027829380">"SD-Karte ist leer oder verfügt über ein nicht unterstütztes Dateisystem."</string>
     <string name="ext_media_unmountable_notification_title" product="nosdcard" msgid="2090046769532713563">"USB-Speicher beschädigt"</string>
-    <string name="ext_media_unmountable_notification_title" product="default" msgid="6410723906019100189">"Beschädigte SD-Karte"</string>
-    <string name="ext_media_unmountable_notification_message" product="nosdcard" msgid="529021299294450667">"USB-Speicher ist beschädigt. Sie müssen ihn neu formatieren."</string>
-    <string name="ext_media_unmountable_notification_message" product="default" msgid="6902531775948238989">"Die SD-Karte ist beschädigt. Sie müssen Ihre Karte eventuell neu formatieren."</string>
-    <string name="ext_media_badremoval_notification_title" product="nosdcard" msgid="1661683031330951073">"USB-Speicher unerw. entfernt"</string>
+    <string name="ext_media_unmountable_notification_title" product="default" msgid="6410723906019100189">"SD-Karte beschädigt"</string>
+    <string name="ext_media_unmountable_notification_message" product="nosdcard" msgid="529021299294450667">"Der USB-Speicher ist beschädigt. Sie müssen ihn eventuell neu formatieren."</string>
+    <string name="ext_media_unmountable_notification_message" product="default" msgid="6902531775948238989">"Die SD-Karte ist beschädigt. Sie müssen sie eventuell neu formatieren."</string>
+    <string name="ext_media_badremoval_notification_title" product="nosdcard" msgid="1661683031330951073">"USB-Speicher unerwartet entfernt"</string>
     <string name="ext_media_badremoval_notification_title" product="default" msgid="6872152882604407837">"SD-Karte unerwartet entfernt"</string>
     <string name="ext_media_badremoval_notification_message" product="nosdcard" msgid="4329848819865594241">"Trennen Sie den USB-Speicher vor dem Entfernen, um Datenverlust zu vermeiden."</string>
     <string name="ext_media_badremoval_notification_message" product="default" msgid="7260183293747448241">"SD-Karte vor dem Entnehmen trennen, um Datenverlust zu vermeiden."</string>
-    <string name="ext_media_safe_unmount_notification_title" product="nosdcard" msgid="3967973893270360230">"USB-Speicher kann entf. werden"</string>
+    <string name="ext_media_safe_unmount_notification_title" product="nosdcard" msgid="3967973893270360230">"USB-Speicher kann entfernt werden."</string>
     <string name="ext_media_safe_unmount_notification_title" product="default" msgid="6729801130790616200">"SD-Karte kann entfernt werden."</string>
     <string name="ext_media_safe_unmount_notification_message" product="nosdcard" msgid="6142195361606493530">"Der USB-Speicher kann entfernt werden."</string>
     <string name="ext_media_safe_unmount_notification_message" product="default" msgid="568841278138377604">"Die SD-Karte kann entfernt werden."</string>
     <string name="ext_media_nomedia_notification_title" product="nosdcard" msgid="4486377230140227651">"USB-Speicher entfernt"</string>
     <string name="ext_media_nomedia_notification_title" product="default" msgid="8902518030404381318">"SD-Karte entfernt"</string>
     <string name="ext_media_nomedia_notification_message" product="nosdcard" msgid="6921126162580574143">"USB-Speicher entfernt. Neuen Datenträger einlegen"</string>
-    <string name="ext_media_nomedia_notification_message" product="default" msgid="3870120652983659641">"SD-Karte entfernt. Legen Sie eine neue ein."</string>
+    <string name="ext_media_nomedia_notification_message" product="default" msgid="3870120652983659641">"SD-Karte entfernt. Neue Karte einlegen"</string>
     <string name="activity_list_empty" msgid="4168820609403385789">"Keine passenden Aktivitäten gefunden"</string>
     <string name="permlab_pkgUsageStats" msgid="8787352074326748892">"Nutzungsstatistik der Komponente aktualisieren"</string>
     <string name="permdesc_pkgUsageStats" msgid="891553695716752835">"Ermöglicht die Änderung von gesammelten Nutzungsstatistiken der Komponente. Nicht für normale Anwendungen vorgesehen."</string>
-    <string name="permlab_copyProtectedData" msgid="1660908117394854464">"Ermöglicht das Aufrufen des Standard-Containerdienstes zum Kopieren von Inhalt. Keine Verwendung bei normalen Anwendungen."</string>
-    <string name="permdesc_copyProtectedData" msgid="537780957633976401">"Ermöglicht das Aufrufen des Standard-Containerdienstes zum Kopieren von Inhalt. Keine Verwendung bei normalen Anwendungen."</string>
+    <string name="permlab_copyProtectedData" msgid="1660908117394854464">"Ermöglicht das Aufrufen des Standard-Containerdienstes zum Kopieren von Inhalt. Nicht zum Gebrauch mit normalen Anwendungen."</string>
+    <string name="permdesc_copyProtectedData" msgid="537780957633976401">"Ermöglicht das Aufrufen des Standard-Containerdienstes zum Kopieren von Inhalt. Nicht zum Gebrauch mit normalen Anwendungen."</string>
     <string name="tutorial_double_tap_to_zoom_message_short" msgid="1311810005957319690">"Für Zoomeinstellung zweimal berühren"</string>
     <string name="gadget_host_error_inflating" msgid="2613287218853846830">"Fehler beim Vergrößern des Widgets"</string>
     <string name="ime_action_go" msgid="8320845651737369027">"Los"</string>
@@ -878,7 +883,7 @@
     <string name="pptp_vpn_description" msgid="2688045385181439401">"Point-to-Point-Tunneling-Protokoll"</string>
     <string name="l2tp_vpn_description" msgid="3750692169378923304">"Layer-2-Tunneling-Protokoll"</string>
     <string name="l2tp_ipsec_psk_vpn_description" msgid="3945043564008303239">"L2TP/IPSec-VPN mit vorinstalliertem Schlüssel"</string>
-    <string name="l2tp_ipsec_crt_vpn_description" msgid="5382714073103653577">"Zertifikat mit vorinstalliertem Schlüssel"</string>
+    <string name="l2tp_ipsec_crt_vpn_description" msgid="5382714073103653577">"L2TP/IPSec-VPN mit Zertifikat"</string>
     <string name="upload_file" msgid="2897957172366730416">"Datei auswählen"</string>
     <string name="reset" msgid="2448168080964209908">"Zurücksetzen"</string>
     <string name="submit" msgid="1602335572089911941">"Senden"</string>
@@ -888,9 +893,9 @@
     <string name="tethered_notification_title" msgid="3146694234398202601">"Tethering oder Hotspot aktiv"</string>
     <string name="tethered_notification_message" msgid="3067108323903048927">"Zum Konfigurieren berühren"</string>
     <string name="throttle_warning_notification_title" msgid="4890894267454867276">"Hohe Mobildatennutzung"</string>
-    <string name="throttle_warning_notification_message" msgid="2609734763845705708">"Weitere Informationen über die Mobildatennutzung durch Berühren aufrufen"</string>
+    <string name="throttle_warning_notification_message" msgid="2609734763845705708">"Durch Berühren weitere Informationen zur Mobildatennutzung aufrufen"</string>
     <string name="throttled_notification_title" msgid="6269541897729781332">"Mobildatenlimit überschritten"</string>
-    <string name="throttled_notification_message" msgid="4712369856601275146">"Weitere Informationen über die Mobildatennutzung durch Berühren aufrufen"</string>
+    <string name="throttled_notification_message" msgid="4712369856601275146">"Durch Berühren weitere Informationen zur Mobildatennutzung aufrufen"</string>
     <string name="progress_unmounting" product="nosdcard" msgid="535863554318797377">"USB-Speicher wird getrennt..."</string>
     <string name="progress_unmounting" product="default" msgid="5556813978958789471">"SD-Karte wird getrennt..."</string>
     <string name="progress_erasing" product="nosdcard" msgid="4183664626203056915">"USB-Speicher wird gelöscht..."</string>
diff --git a/core/res/res/values-el/strings.xml b/core/res/res/values-el/strings.xml
index 4244aa5..b4f6a76 100644
--- a/core/res/res/values-el/strings.xml
+++ b/core/res/res/values-el/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Επιτρέπει στην εφαρμογή τον έλεγχο του δονητή."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"έλεγχος φακού"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Επιτρέπει στην εφαρμογή τον έλεγχο του φακού."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"πρόσβαση σε συσκευές USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Επιτρέπει στην εφαρμογή την πρόσβαση σε συσκευές USB."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"διαχείριση προτιμήσεων και αδειών για συσκευές USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Επιτρέπει στην εφαρμογή να διαχειρίζεται προτιμήσεις και άδειες για συσκευές USB."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"δοκιμή υλικού"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Επιτρέπει σε μια εφαρμογή τον έλεγχο διαφόρων περιφερειακών για την εκτέλεση δοκιμών υλικού."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"απευθείας κλήση τηλεφωνικών αριθμών"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Επιτρέπει σε μια εφαρμογή τη σύνδεση σε σημεία πρόσβασης Wi-Fi και την αποσύνδεση από αυτά, καθώς και την πραγματοποίηση αλλαγών σε διαμορφωμένα δίκτυα Wi-Fi."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"να επιτρέπεται η λήψη πολλαπλής διανομής Wi-Fi"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Επιτρέπει στην εφαρμογή να λαμβάνει πακέτα τα οποία δεν αποστέλλονται απευθείας στη συσκευή σας. Αυτό μπορεί να φανεί χρήσιμο κατά την ανακάλυψη υπηρεσιών που προσφέρονται σε κοντινές τοποθεσίες. Χρησιμοποιεί περισσότερη ενέργεια σε σχέση με την κατάσταση μη πολλαπλής διανομής."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"προβολή κατάστασης WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Επιτρέπει σε μια εφαρμογή την προβολή των πληροφοριών σχετικά με την κατάσταση του WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"αλλαγή κατάστασης WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Επιτρέπει σε μια εφαρμογή τη σύνδεση και αποσύνδεση από το δίκτυο WiMAX."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"διαχείριση Bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Επιτρέπει σε μια εφαρμογή τη διαμόρφωση του τοπικού τηλεφώνου Bluetooth και την ανακάλυψη και σύζευξη με απομακρυσμένες συσκευές."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"δημιουργία συνδέσεων Bluetooth"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Χρήση από προεπιλογή για αυτήν την ενέργεια."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Εκκαθάριση προεπιλεγμένων σε Ρυθμίσεις αρχικής σελίδας &gt; Εφαρμογές &gt; Διαχείριση εφαρμογών."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Επιλέξτε μια ενέργεια"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Επιλέξτε μια εφαρμογή για τη συσκευή USB"</string>
     <string name="noApplications" msgid="1691104391758345586">"Δεν υπάρχουν εφαρμογές, οι οποίες μπορούν να εκτελέσουν αυτήν την ενέργεια."</string>
     <string name="aerr_title" msgid="653922989522758100">"Λυπούμαστε!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"Υπήρξε μη αναμενόμενη διακοπή της εφαρμογής <xliff:g id="APPLICATION">%1$s</xliff:g> (διαδικασία <xliff:g id="PROCESS">%2$s</xliff:g>). Προσπαθήστε ξανά."</string>
diff --git a/core/res/res/values-en-rGB/strings.xml b/core/res/res/values-en-rGB/strings.xml
index 5cc7a63..4175bb0 100644
--- a/core/res/res/values-en-rGB/strings.xml
+++ b/core/res/res/values-en-rGB/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Allows the application to control the vibrator."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"control flashlight"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Allows the application to control the flashlight."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"access USB devices"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Allows the application to access USB devices."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"manage preferences and permissions for USB devices"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Allows the application to manage preferences and permissions for USB devices."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"test hardware"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Allows the application to control various peripherals for the purpose of hardware testing."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"directly call phone numbers"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Allows an application to connect to and disconnect from Wi-Fi access points and to make changes to configured Wi-Fi networks."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"allow Wi-Fi Multicast reception"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Allows an application to receive packets not directly addressed to your device. This can be useful when discovering services offered nearby. It uses more power than the non-multicast mode."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"view WiMAX state"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Allows an application to view the information about the state of WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"change WiMAX state"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Allows an application to connect to and disconnect from WiMAX network."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"bluetooth administration"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Allows an application to configure the local Bluetooth phone and to discover and pair with remote devices."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"create Bluetooth connections"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Use by default for this action."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Clear default in Home Settings &gt; Applications &gt; Manage applications."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Select an action"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Select an application for the USB device"</string>
     <string name="noApplications" msgid="1691104391758345586">"No applications can perform this action."</string>
     <string name="aerr_title" msgid="653922989522758100">"Sorry!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"The application <xliff:g id="APPLICATION">%1$s</xliff:g> (process <xliff:g id="PROCESS">%2$s</xliff:g>) has stopped unexpectedly. Please try again."</string>
@@ -796,7 +801,7 @@
     <string name="usb_storage_title" msgid="5901459041398751495">"USB connected"</string>
     <string name="usb_storage_message" product="nosdcard" msgid="115779324551502062">"You have connected your phone to your computer via USB. Select the button below if you want to copy files between your computer and your Android‘s USB storage."</string>
     <string name="usb_storage_message" product="default" msgid="4796759646167247178">"You have connected your phone to your computer via USB. Select the button below if you want to copy files between your computer and your Android\'s SD card."</string>
-    <string name="usb_storage_button_mount" msgid="1052259930369508235">"Turn off USB storage"</string>
+    <string name="usb_storage_button_mount" msgid="1052259930369508235">"Turn on USB storage"</string>
     <string name="usb_storage_error_message" product="nosdcard" msgid="3276413764430468454">"There is a problem with using your USB storage for USB mass storage."</string>
     <string name="usb_storage_error_message" product="default" msgid="120810397713773275">"There is a problem with using your SD card for USB mass storage."</string>
     <string name="usb_storage_notification_title" msgid="8175892554757216525">"USB connected"</string>
diff --git a/core/res/res/values-es-rUS/strings.xml b/core/res/res/values-es-rUS/strings.xml
index 504b828..f0299af 100644
--- a/core/res/res/values-es-rUS/strings.xml
+++ b/core/res/res/values-es-rUS/strings.xml
@@ -202,7 +202,7 @@
     <string name="permlab_enableCarMode" msgid="5684504058192921098">"habilitar el modo de auto"</string>
     <string name="permdesc_enableCarMode" msgid="5673461159384850628">"Permite que una aplicación habilite el modo auto."</string>
     <string name="permlab_killBackgroundProcesses" msgid="8373714752793061963">"eliminar los procesos de fondo"</string>
-    <string name="permdesc_killBackgroundProcesses" msgid="2908829602869383753">"Permite que una aplicación elimine los procesos de fondo de otras aplicaciones, aun si la memoria no es baja."</string>
+    <string name="permdesc_killBackgroundProcesses" msgid="2908829602869383753">"Permite que una aplicación elimine los procesos de fondo de otras aplicaciones, aun si la no queda poco espacio en la memoria."</string>
     <string name="permlab_forceStopPackages" msgid="1447830113260156236">"forzar la detención de otras aplicaciones"</string>
     <string name="permdesc_forceStopPackages" msgid="7263036616161367402">"Permite que una aplicación provoque la detención de otras aplicaciones."</string>
     <string name="permlab_forceBack" msgid="1804196839880393631">"provocar que la aplicación se acerque"</string>
@@ -245,7 +245,7 @@
     <string name="permdesc_bindInputMethod" msgid="3734838321027317228">"Permite al propietario vincularse a la interfaz de nivel superior de un método de entrada. Se debe evitar utilizarlo en aplicaciones normales."</string>
     <string name="permlab_bindWallpaper" msgid="8716400279937856462">"vincular a un fondo de pantalla"</string>
     <string name="permdesc_bindWallpaper" msgid="5287754520361915347">"Permite al propietario vincularse a la interfaz de nivel superior de un fondo de pantalla. Se debe evitar utilizarlo en aplicaciones normales."</string>
-    <string name="permlab_bindDeviceAdmin" msgid="8704986163711455010">"interactuar con un administrador de dispositivo"</string>
+    <string name="permlab_bindDeviceAdmin" msgid="8704986163711455010">"interactuar con un administrador de dispositivos"</string>
     <string name="permdesc_bindDeviceAdmin" msgid="8714424333082216979">"Permite que el propietario envíe sus intentos a un administrador de dispositivos. No se necesita para las aplicaciones normales."</string>
     <string name="permlab_setOrientation" msgid="3365947717163866844">"cambiar la orientación de la pantalla"</string>
     <string name="permdesc_setOrientation" msgid="6335814461615851863">"Admite una aplicación que cambia la rotación de la pantalla en cualquier momento. Se debe evitar utilizarlo en aplicaciones normales."</string>
@@ -264,11 +264,11 @@
     <string name="permlab_installPackages" msgid="335800214119051089">"instalar aplicaciones directamente"</string>
     <string name="permdesc_installPackages" msgid="526669220850066132">"Admite una aplicación que instala paquetes de Android nuevos o actualizados. Las aplicaciones maliciosas pueden utilizarlo para agregar aplicaciones nuevas con permisos arbitrariamente potentes."</string>
     <string name="permlab_clearAppCache" msgid="4747698311163766540">"eliminar todos los datos de memoria caché de la aplicación"</string>
-    <string name="permdesc_clearAppCache" msgid="7740465694193671402">"Admite una aplicación que libera espacio de almacenamiento en el teléfono al eliminar archivos del directorio de memoria caché de la aplicación. En general, el acceso es muy restringido para el proceso del sistema."</string>
+    <string name="permdesc_clearAppCache" msgid="7740465694193671402">"Permite que una aplicación libere espacio de almacenamiento en el teléfono borrando archivos del directorio de memoria caché de la aplicación. En general el acceso está muy restringido al proceso del sistema."</string>
     <string name="permlab_movePackage" msgid="728454979946503926">"Mover recursos de la aplicación"</string>
     <string name="permdesc_movePackage" msgid="6323049291923925277">"Permite a una aplicación mover recursos de aplicación de medios internos a externos y viceversa."</string>
     <string name="permlab_readLogs" msgid="6615778543198967614">"lee los datos confidenciales del registro"</string>
-    <string name="permdesc_readLogs" msgid="8896449437464867766">"Admite una aplicación que lee diversos archivos de registro del sistema. Esto te permite descubrir información general acerca de lo que haces con el teléfono, y puede potencialmente incluir información personal o privada."</string>
+    <string name="permdesc_readLogs" msgid="8896449437464867766">"Permite que una aplicación lea los diversos archivos de registro del sistema. Esto le permite descubrir información general acerca de lo que haces con el teléfono, y puede potencialmente incluir información personal o privada."</string>
     <string name="permlab_diagnostic" msgid="8076743953908000342">"leer y escribir a recursos dentro del grupo de diagnóstico"</string>
     <string name="permdesc_diagnostic" msgid="3121238373951637049">"Admite una aplicación que lee y escribe a cualquier recurso dentro del grupo de diagnóstico; por ejemplo, archivos con /dev. Esto puede afectar potencialmente la estabilidad y la seguridad del sistema. Debe utilizarlo SÓLO el fabricante o el operador en los diagnósticos específicos del hardware."</string>
     <string name="permlab_changeComponentState" msgid="79425198834329406">"activar o desactivar componentes de la aplicación"</string>
@@ -281,12 +281,12 @@
     <string name="permdesc_writeSecureSettings" msgid="5497873143539034724">"Permite a una aplicación modificar los datos de la configuración segura de los sistemas. Las aplicaciones normales no deben utilizarlo."</string>
     <string name="permlab_writeGservices" msgid="2149426664226152185">"modificar el mapa de servicios de Google"</string>
     <string name="permdesc_writeGservices" msgid="6602362746516676175">"Admite una aplicación que modifica el mapa de servicios de Google. Las aplicaciones normales no deben utilizarlo."</string>
-    <string name="permlab_receiveBootCompleted" msgid="7776779842866993377">"iniciar automáticamente durante la inicialización"</string>
-    <string name="permdesc_receiveBootCompleted" msgid="698336728415008796">"Admite una aplicación que se inicia cuando el sistema haya finalizado la inicialización. Esto puede ocasionar que se demore más tiempo en inicializar el teléfono y que la aplicación retarde el funcionamiento total del teléfono al estar en ejecución constante."</string>
+    <string name="permlab_receiveBootCompleted" msgid="7776779842866993377">"ejecutar automáticamente al iniciar"</string>
+    <string name="permdesc_receiveBootCompleted" msgid="698336728415008796">"Permite que una aplicación se inicie en cuanto el sistema haya finalizado la inicialización. Esto puede ocasionar que el teléfono tarde más en inicializarse y que la aplicación demore el funcionamiento total del teléfono al estar en ejecución constante."</string>
     <string name="permlab_broadcastSticky" msgid="7919126372606881614">"enviar emisiones pegajosas"</string>
     <string name="permdesc_broadcastSticky" msgid="1920045289234052219">"Admite una aplicación que envía emisiones pegajosas, las cuales permanecen luego de que finaliza la emisión. Las aplicaciones maliciosas pueden hacer lento e inestable al teléfono, ya que ocasiona que utilice demasiada memoria."</string>
     <string name="permlab_readContacts" msgid="6219652189510218240">"leer datos de contacto"</string>
-    <string name="permdesc_readContacts" msgid="3371591512896545975">"Admite una aplicación que lee todos los datos de (direcciones) de contactos almacenados en tu teléfono. Las aplicaciones maliciosas pueden utilizarlo para enviar tus eventos de calendario a otras personas."</string>
+    <string name="permdesc_readContacts" msgid="3371591512896545975">"Permite que una aplicación lea todos los datos (direcciones) de contactos almacenados en tu tablet. Las aplicaciones maliciosas pueden utilizarlo para enviar tus datos a otras personas."</string>
     <string name="permlab_writeContacts" msgid="644616215860933284">"escribir datos de contacto"</string>
     <string name="permdesc_writeContacts" msgid="3924383579108183601">"Admite una aplicación que modifica los datos de (dirección de) contacto guardados en tu teléfono. Las aplicaciones maliciosas pueden utilizarlo para borrar o modificar los datos de contacto."</string>
     <string name="permlab_readCalendar" msgid="6898987798303840534">"Leer eventos del calendario"</string>
@@ -315,8 +315,8 @@
     <string name="permdesc_camera" msgid="6004878235852154239">"Admite una aplicación que toma fotografías y graba video con la cámara. Esto permite que la aplicación en cualquier momento recopile imágenes que esté viendo la cámara."</string>
     <string name="permlab_brick" msgid="8337817093326370537">"desactivar teléfono de manera permanente"</string>
     <string name="permdesc_brick" msgid="5569526552607599221">"Admite que la aplicación desactive todo el teléfono de manera permanente. Esto es muy peligroso."</string>
-    <string name="permlab_reboot" msgid="2898560872462638242">"provocar el reinicio del teléfono"</string>
-    <string name="permdesc_reboot" msgid="7914933292815491782">"Admite que la aplicación provoque que el teléfono se reinicie."</string>
+    <string name="permlab_reboot" msgid="2898560872462638242">"forzar reinicio del teléfono"</string>
+    <string name="permdesc_reboot" msgid="7914933292815491782">"Permite que la aplicación fuerce el reinicio del tablet."</string>
     <string name="permlab_mount_unmount_filesystems" msgid="1761023272170956541">"montar y desmontar filesystems"</string>
     <string name="permdesc_mount_unmount_filesystems" msgid="6253263792535859767">"Admite que la aplicación monte y desmonte filesystems para obtener almacenamiento extraíble."</string>
     <string name="permlab_mount_format_filesystems" msgid="5523285143576718981">"espacio de almacenamiento externo del formato"</string>
@@ -335,15 +335,15 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Admite que la aplicación controle el vibrador."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"controlar linterna"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Admite que la aplicación controle la linterna."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"acceder a dispositivos USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Permite que la aplicación acceda a dispositivos USB."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"administrar preferencias y permisos para los dispositivos USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Permite a la aplicación administrar preferencias y permisos para los dispositivos USB."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"probar el hardware"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Admite que la aplicación controle diversos periféricos con el fin de probar el hardware."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"llamar directamente a números de teléfono"</string>
     <string name="permdesc_callPhone" msgid="3369867353692722456">"Admite que la aplicación llame a ciertos números de teléfono sin tu permiso. Las aplicaciones maliciosas pueden ocasionar llamadas imprevistas en tu factura telefónica. Ten en cuenta que esto no admite que la aplicación llame a los números de emergencia."</string>
     <string name="permlab_callPrivileged" msgid="4198349211108497879">"llamar directamente a cualquier número de teléfono"</string>
     <string name="permdesc_callPrivileged" msgid="244405067160028452">"Admite que la aplicación llame a cualquier número de teléfono, incluidos los números de emergencia, sin tu intervención. Las aplicaciones maliciosas pueden realizar llamadas innecesarias e ilegales a los servicios de emergencia."</string>
-    <string name="permlab_performCdmaProvisioning" msgid="5604848095315421425">"comienza directamente la configuración CDMA del teléfono"</string>
+    <string name="permlab_performCdmaProvisioning" msgid="5604848095315421425">"iniciar directamente la configuración CDMA del teléfono"</string>
     <string name="permdesc_performCdmaProvisioning" msgid="6457447676108355905">"Admite la aplicación para comenzar con el aprovisionamiento CDMA. Las aplicaciones maliciosas pueden comenzar con el aprovisionamiento CDMA sin necesidad."</string>
     <string name="permlab_locationUpdates" msgid="7785408253364335740">"controlar las notificaciones de actualización de ubicación"</string>
     <string name="permdesc_locationUpdates" msgid="2300018303720930256">"Permite activar y desactivar las notificaciones de actualización de ubicación de la radio. Las aplicaciones normales no deben utilizarlo."</string>
@@ -390,7 +390,7 @@
     <string name="permlab_changeNetworkState" msgid="958884291454327309">"cambiar la conectividad de la red"</string>
     <string name="permdesc_changeNetworkState" msgid="4199958910396387075">"Permite que una aplicación cambie el estado de la conectividad de red."</string>
     <string name="permlab_changeTetherState" msgid="2702121155761140799">"Cambiar la conectividad de anclaje a red"</string>
-    <string name="permdesc_changeTetherState" msgid="8905815579146349568">"Permite que una aplicación cambie el estado de la conectividad de red del anclaje."</string>
+    <string name="permdesc_changeTetherState" msgid="8905815579146349568">"ermite que una aplicación cambie el estado de la conectividad de anclaje a red."</string>
     <string name="permlab_changeBackgroundDataSetting" msgid="1400666012671648741">"cambiar la configuración del uso de datos del fondo"</string>
     <string name="permdesc_changeBackgroundDataSetting" msgid="1001482853266638864">"Admite una aplicación que cambia la configuración del uso de datos del fondo."</string>
     <string name="permlab_accessWifiState" msgid="8100926650211034400">"ver el estado de Wi-Fi"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Admite una aplicación que se conecta y desconecta de los puntos de acceso de Wi-Fi y que hace cambios en las redes de Wi-Fi configuradas."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"permitir recepción de multidifusión Wi-Fi"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Permite a una aplicación recibir paquetes que no están dirigidos directamente a tu dispositivo. Esta opción puede ser útil al descubrir servicios ofrecidos. Además, ejerce más potencia que el modo que no es de multidifusión."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"ver el estado de WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Permite que una aplicación vea la información acerca del estado de WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"cambiar estado de WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Permite que una aplicación se conecte a una red WiMAX y se desconecte de esta."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"administración de bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Admite una aplicación que configura el teléfono Bluetooth local y descubre y se vincula con dispositivos remotos."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"crear conexiones de Bluetooth"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Utilizar de manera predeterminada en esta acción."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Borrar la predeterminación en Configuración de la página principal &gt; Aplicaciones &gt; Administrar aplicaciones."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Seleccionar una acción"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Selecciona una aplicación para el dispositivo USB."</string>
     <string name="noApplications" msgid="1691104391758345586">"Ninguna aplicación puede realizar esta acción."</string>
     <string name="aerr_title" msgid="653922989522758100">"¡Lo sentimos!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"La aplicación <xliff:g id="APPLICATION">%1$s</xliff:g> (proceso <xliff:g id="PROCESS">%2$s</xliff:g>) se ha detenido de forma imprevista. Vuelve a intentarlo."</string>
@@ -750,7 +755,7 @@
     <string name="launch_warning_original" msgid="188102023021668683">"<xliff:g id="APP_NAME">%1$s</xliff:g> se inició originalmente."</string>
     <string name="smv_application" msgid="295583804361236288">"La aplicación <xliff:g id="APPLICATION">%1$s</xliff:g> (proceso <xliff:g id="PROCESS">%2$s</xliff:g>) ha violado su política StrictMode autoimpuesta."</string>
     <string name="smv_process" msgid="5120397012047462446">"El proceso <xliff:g id="PROCESS">%1$s</xliff:g> ha violado su política StrictMode autoimpuesta."</string>
-    <string name="heavy_weight_notification" msgid="9087063985776626166">"<xliff:g id="APP">%1$s</xliff:g> Correr"</string>
+    <string name="heavy_weight_notification" msgid="9087063985776626166">"<xliff:g id="APP">%1$s</xliff:g> en ejecución"</string>
     <string name="heavy_weight_notification_detail" msgid="2423977499339403402">"Selecciona cambiar la aplicación"</string>
     <string name="heavy_weight_switcher_title" msgid="1135403633766694316">"¿Deseas cambiar aplicaciones?"</string>
     <string name="heavy_weight_switcher_text" msgid="4592075610079319667">"Ya se está ejecutando una aplicación que debe detenerse antes de iniciar una nueva."</string>
@@ -835,17 +840,17 @@
     <string name="ext_media_unmountable_notification_message" product="nosdcard" msgid="529021299294450667">"Almacenamiento USB dañado. Es posible que debas reformatearlo."</string>
     <string name="ext_media_unmountable_notification_message" product="default" msgid="6902531775948238989">"Tarjeta SD dañada. Es posible que debas reformatearla."</string>
     <string name="ext_media_badremoval_notification_title" product="nosdcard" msgid="1661683031330951073">"Almacenamiento USB extraído inesperadamente"</string>
-    <string name="ext_media_badremoval_notification_title" product="default" msgid="6872152882604407837">"Tarjeta SD extraída de forma imprevista"</string>
+    <string name="ext_media_badremoval_notification_title" product="default" msgid="6872152882604407837">"Almacenamiento USB extraído de forma imprevista"</string>
     <string name="ext_media_badremoval_notification_message" product="nosdcard" msgid="4329848819865594241">"Desmontar el almacenamiento USB antes de extraerlo para evitar la pérdida de datos."</string>
     <string name="ext_media_badremoval_notification_message" product="default" msgid="7260183293747448241">"Desmontar la tarjeta SD antes de extraerla para evitar la pérdida de datos."</string>
     <string name="ext_media_safe_unmount_notification_title" product="nosdcard" msgid="3967973893270360230">"Es seguro extraer el almacenamiento USB"</string>
-    <string name="ext_media_safe_unmount_notification_title" product="default" msgid="6729801130790616200">"Tarjeta SD fácil de extraer"</string>
+    <string name="ext_media_safe_unmount_notification_title" product="default" msgid="6729801130790616200">"Es seguro extraer la tarjeta SD"</string>
     <string name="ext_media_safe_unmount_notification_message" product="nosdcard" msgid="6142195361606493530">"Puedes extraer de forma segura el almacenamiento USB."</string>
-    <string name="ext_media_safe_unmount_notification_message" product="default" msgid="568841278138377604">"Puedes eliminar la tarjeta SD sin riesgos."</string>
+    <string name="ext_media_safe_unmount_notification_message" product="default" msgid="568841278138377604">"Puedes extraer de forma segura la tarjeta SD."</string>
     <string name="ext_media_nomedia_notification_title" product="nosdcard" msgid="4486377230140227651">"Almacenamiento USB extraído"</string>
     <string name="ext_media_nomedia_notification_title" product="default" msgid="8902518030404381318">"Tarjeta SD extraída"</string>
     <string name="ext_media_nomedia_notification_message" product="nosdcard" msgid="6921126162580574143">"Almacenamiento USB eliminado. Insertar nuevos medios."</string>
-    <string name="ext_media_nomedia_notification_message" product="default" msgid="3870120652983659641">"Tarjeta SD eliminada. Inserta una nueva."</string>
+    <string name="ext_media_nomedia_notification_message" product="default" msgid="3870120652983659641">"Tarjeta SD extraída. Insertar una nueva."</string>
     <string name="activity_list_empty" msgid="4168820609403385789">"No se encontraron actividades coincidentes"</string>
     <string name="permlab_pkgUsageStats" msgid="8787352074326748892">"actualizar la estadística de uso de los componentes"</string>
     <string name="permdesc_pkgUsageStats" msgid="891553695716752835">"Permite la modificación de estadísticas recopiladas sobre el uso de componentes. Las aplicaciones normales no deben utilizarlo."</string>
@@ -877,8 +882,8 @@
     <string name="chooser_wallpaper" msgid="7873476199295190279">"Cambiar fondo de pantalla"</string>
     <string name="pptp_vpn_description" msgid="2688045385181439401">"Protocolo de túnel punto a punto"</string>
     <string name="l2tp_vpn_description" msgid="3750692169378923304">"Protocolo de túnel de nivel 2"</string>
-    <string name="l2tp_ipsec_psk_vpn_description" msgid="3945043564008303239">"Clave previamente compartida según L2TP/IPSec VPN"</string>
-    <string name="l2tp_ipsec_crt_vpn_description" msgid="5382714073103653577">"Certificado según L2TP/IPSec VPN"</string>
+    <string name="l2tp_ipsec_psk_vpn_description" msgid="3945043564008303239">"VPN L2TP/IPSec basada en clave compartida previamente"</string>
+    <string name="l2tp_ipsec_crt_vpn_description" msgid="5382714073103653577">"VPN L2TP/IPSec basada en certificado"</string>
     <string name="upload_file" msgid="2897957172366730416">"Elegir archivo"</string>
     <string name="reset" msgid="2448168080964209908">"Restablecer"</string>
     <string name="submit" msgid="1602335572089911941">"Enviar"</string>
@@ -896,7 +901,7 @@
     <string name="progress_erasing" product="nosdcard" msgid="4183664626203056915">"Borrando almacenamiento USB..."</string>
     <string name="progress_erasing" product="default" msgid="2115214724367534095">"Borrando tarjeta SD..."</string>
     <string name="format_error" product="nosdcard" msgid="4320339096529911637">"No pudo borrar el almacenamiento USB."</string>
-    <string name="format_error" product="default" msgid="1343380371925238343">"No pudo borrar la tarjeta SD."</string>
+    <string name="format_error" product="default" msgid="1343380371925238343">"No se pudo borrar la tarjeta SD."</string>
     <string name="media_bad_removal" msgid="7960864061016603281">"Se ha extraído la tarjeta SD antes de ser desmontada."</string>
     <string name="media_checking" product="nosdcard" msgid="418188720009569693">"Se está verificando el almacenamiento USB en este momento."</string>
     <string name="media_checking" product="default" msgid="7334762503904827481">"Se está verificando la tarjeta SD en este momento."</string>
diff --git a/core/res/res/values-es/strings.xml b/core/res/res/values-es/strings.xml
index 543b53e..efff15b 100644
--- a/core/res/res/values-es/strings.xml
+++ b/core/res/res/values-es/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Permite que la aplicación controle la función de vibración."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"controlar linterna"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Permite que la aplicación controle la función de linterna."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"acceso a dispositivos USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"La aplicación puede acceder a dispositivos USB."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"administrar preferencias y permisos de dispositivos USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Permite que la aplicación administre las preferencias y los permisos de los dispositivos USB."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"probar hardware"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Permite que la aplicación controle distintos periféricos con fines de prueba del hardware."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"llamar directamente a números de teléfono"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Permite que una aplicación se conecte a puntos de acceso Wi-Fi y se desconecte de ellos, y realice modificaciones en las redes Wi-Fi configuradas."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"permitir recepción multidifusión Wi-Fi"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Permite que una aplicación reciba paquetes no dirigidos directamente a tu dispositivo. Esta función puede resultar útil para descubrir servicios cercanos. Utiliza más energía que el modo de no multidifusión."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"ver estado de WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Permite que una aplicación acceda a la información sobre el estado de la conectividad WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"cambiar estado de WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Permite a una aplicación conectarse a una red WiMAX y desconectarse de ella."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"administración de Bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Permite que una aplicación configure el teléfono Bluetooth local, y vea dispositivos remotos y sincronice el teléfono con ellos."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"crear conexiones de Bluetooth"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Utilizar de forma predeterminada para esta acción"</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Borrar valores predeterminados en la página de configuración de la pantalla de inicio del teléfono &gt; Aplicaciones &gt; Administrar aplicaciones\"."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Seleccionar una acción"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Seleccionar una aplicación para el dispositivo USB"</string>
     <string name="noApplications" msgid="1691104391758345586">"Ninguna aplicación puede realizar esta acción."</string>
     <string name="aerr_title" msgid="653922989522758100">"Lo sentimos."</string>
     <string name="aerr_application" msgid="4683614104336409186">"La aplicación <xliff:g id="APPLICATION">%1$s</xliff:g> (proceso <xliff:g id="PROCESS">%2$s</xliff:g>) se ha interrumpido inesperadamente. Inténtalo de nuevo."</string>
diff --git a/core/res/res/values-fa/strings.xml b/core/res/res/values-fa/strings.xml
index 6c77768..114a6dd 100644
--- a/core/res/res/values-fa/strings.xml
+++ b/core/res/res/values-fa/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"به برنامه کاربردی اجازه می دهد لرزاننده را کنترل کند."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"کنترل چراغ قوه"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"به برنامه کاربردی اجازه می دهد چراغ قوه را کنترل کند."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"دسترسی به دستگاه های USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"به برنامه کاربردی اجازه می دهد به دستگاه های USB دسترسی پیدا کند."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"مدیریت تنظیمات برگزیده و مجوزها برای دستگاه های USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"به برنامه کاربردی جهت مدیریت تنظیمات برگزیده و مجوزها برای دستگاه های USB اجازه می دهد."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"تست سخت افزار"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"به برنامه کاربردی اجازه می دهد سایر برنامه های جانبی را برای تست سخت افزاری کنترل کند."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"تماس مستقیم با شماره تلفن ها"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"به یک برنامه کاربردی اجازه می دهد به نقاط دسترسی Wi-Fi متصل شده و از آنها جدا شود، همچنین تغییراتی را در مورد شبکه های Wi-Fi پیکربندی شده ایجاد کند."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"دریافت چندگانه Wi-Fi را مجاز می کند"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"به یک برنامه کاربردی اجازه می دهد بسته هایی را دریافت کند که مستقیماً برای دستگاه شما ارسال نشده باشد. این امر زمانی که در حال شناسایی سرویس های نزدیک به خود هستید، می تواند مؤثر باشد. در این حالت در مقایسه با حالت غیر چندگانه، از انرژِی بیشتری استفاده می شود."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"مشاهده وضعیت WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"به یک برنامه کاربردی امکان می دهد اطلاعات مربوط به وضعیت WiMAX را مشاهده کند."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"تغییر وضعیت WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"به یک برنامه کاربردی امکان می دهد به شبکه WiMAX متصل یا از آن قطع شود."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"سرپرست بلوتوث"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"به یک برنامه کاربردی اجازه می دهد تا تلفن محلی بلوتوث را پیکربندی کرده، دستگاه های راه دور را شناسایی کرده و با آنها جفت شود."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"ایجاد اتصال های بلوتوث"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"استفاده به صورت پیش فرض برای این عملکرد."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"پاک کردن موارد پیش فرض در تنظیمات صفحه اصلی &gt; برنامه های کاربردی &gt; مدیریت برنامه ها."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"انتخاب یک عملکرد"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"انتخاب یک برنامه کاربردی برای دستگاه USB"</string>
     <string name="noApplications" msgid="1691104391758345586">"هیچ برنامه ای نمی تواند این عملکرد را اجرا کند."</string>
     <string name="aerr_title" msgid="653922989522758100">"متأسفیم!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"برنامه کاربردی <xliff:g id="APPLICATION">%1$s</xliff:g> ( فرآیند <xliff:g id="PROCESS">%2$s</xliff:g>) به طور غیر منتظره ای متوقف شد. لطفاً دوباره امتحان کنید."</string>
diff --git a/core/res/res/values-fi/strings.xml b/core/res/res/values-fi/strings.xml
index 192bf13..6603d15 100644
--- a/core/res/res/values-fi/strings.xml
+++ b/core/res/res/values-fi/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Antaa sovelluksen hallita värinää."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"hallitse taskulamppua"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Antaa sovelluksen hallita lamppua."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"käytä USB-tiloja"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Antaa sovelluksen käyttää USB-tiloja."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"hallinnoi USB-laitteiden asetuksia ja käyttöoikeuksia"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Antaa sovelluksen hallinnoida USB-laitteiden asetuksia ja käyttöoikeuksia"</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"testaa laitteistoa"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Antaa sovelluksen hallita useita liitännäislaitteita laitteistotestaustarkoituksessa."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"soittaa puhelinnumeroihin suoraan"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Antaa sovelluksen muodostaa ja katkaista yhteyden wifi-tukiasemista ja tehdä muutoksia määritettyihin wifi-verkkoihin."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"anna ottaa vastaan wifi-ryhmälähetyksiä"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Antaa sovelluksen vastaanottaa paketteja, joita ei ole osoitettu suoraan laitteellesi. Tämän toiminnon avulla voit löytää lähistöllä tarjolla olevia palveluita. Toiminto käyttää enemmän akkua kuin ei-ryhmälähetystila."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"tarkastele WiMAX-verkon tilaa"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Antaa sovelluksen tarkastella WiMAX-verkon tilaa."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"vaihda WiMAX-verkon tilaa"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Antaa sovelluksen muodostaa yhteyden WiMAX-verkkoon ja katkaista yhteyden."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"hallitse bluetooth-yhteyttä"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Antaa sovelluksen määrittää paikallisen Bluetooth-puhelimen ja etsiä muita laitteita ja muodostaa niihin laitepariyhteyden."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"luo Bluetooth-yhteyksiä"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Käytä oletuksena tälle toiminnolle."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Tyhjennä oletusasetus kohdassa Etusivun asetukset &gt; Sovellukset &gt; Hallinnoi sovelluksia."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Valitse toiminto"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Valitse sovellus USB-laitteelle"</string>
     <string name="noApplications" msgid="1691104391758345586">"Yksikään sovellus ei voi suorittaa tätä toimintoa."</string>
     <string name="aerr_title" msgid="653922989522758100">"Pahoittelemme!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"Sovellus <xliff:g id="APPLICATION">%1$s</xliff:g> (prosessi <xliff:g id="PROCESS">%2$s</xliff:g>) pysähtyi yllättäen. Yritä uudelleen."</string>
diff --git a/core/res/res/values-fr/strings.xml b/core/res/res/values-fr/strings.xml
index ee9b97f..a1939e4 100644
--- a/core/res/res/values-fr/strings.xml
+++ b/core/res/res/values-fr/strings.xml
@@ -125,7 +125,7 @@
     <string name="contentServiceSync" msgid="8353523060269335667">"Synchroniser"</string>
     <string name="contentServiceSyncNotificationTitle" msgid="397743349191901458">"Synchronisation"</string>
     <string name="contentServiceTooManyDeletesNotificationDesc" msgid="8100981435080696431">"Trop de contenus supprimés (<xliff:g id="CONTENT_TYPE">%s</xliff:g>)."</string>
-    <string name="low_memory" msgid="6632412458436461203">"La mémoire du téléphone est pleine ! Supprimez des fichiers pour libérer de l\'espace."</string>
+    <string name="low_memory" msgid="6632412458436461203">"La mémoire du téléphone est pleine. Supprimez des fichiers pour libérer de l\'espace."</string>
     <string name="me" msgid="6545696007631404292">"Moi"</string>
     <string name="power_dialog" msgid="1319919075463988638">"Options du téléphone"</string>
     <string name="silent_mode" msgid="7167703389802618663">"Mode silencieux"</string>
@@ -153,7 +153,7 @@
     <string name="permgrouplab_messages" msgid="7521249148445456662">"Vos messages"</string>
     <string name="permgroupdesc_messages" msgid="7045736972019211994">"Permet de lire et rédiger vos SMS, e-mails et autres messages."</string>
     <string name="permgrouplab_personalInfo" msgid="3519163141070533474">"Vos informations personnelles"</string>
-    <string name="permgroupdesc_personalInfo" msgid="5488050357388806068">"Accédez directement aux contacts et à l\'agenda enregistrés sur votre téléphone."</string>
+    <string name="permgroupdesc_personalInfo" msgid="5488050357388806068">"Accéder directement aux contacts et à l\'agenda enregistrés sur votre téléphone"</string>
     <string name="permgrouplab_location" msgid="635149742436692049">"Votre position"</string>
     <string name="permgroupdesc_location" msgid="2430258821648348660">"Suivre votre position géographique"</string>
     <string name="permgrouplab_network" msgid="5808983377727109831">"Communications réseau"</string>
@@ -170,7 +170,7 @@
     <string name="permgroupdesc_developmentTools" msgid="9056431193893809814">"Ces fonctionnalités sont réservées aux développeurs d\'applications."</string>
     <string name="permgrouplab_storage" msgid="1971118770546336966">"Stockage"</string>
     <string name="permgroupdesc_storage" product="nosdcard" msgid="7442318502446874999">"Accéder à la  mémoire de stockage USB"</string>
-    <string name="permgroupdesc_storage" product="default" msgid="9203302214915355774">"Accès à la carte SD"</string>
+    <string name="permgroupdesc_storage" product="default" msgid="9203302214915355774">"Accéder à la carte SD"</string>
     <string name="permlab_statusBar" msgid="7417192629601890791">"Désactivation ou modification de la barre d\'état"</string>
     <string name="permdesc_statusBar" msgid="1365473595331989732">"Permet à une application de désactiver la barre d\'état ou d\'ajouter/supprimer des icônes système."</string>
     <string name="permlab_statusBarService" msgid="7247281911387931485">"barre d\'état"</string>
@@ -246,7 +246,7 @@
     <string name="permlab_bindWallpaper" msgid="8716400279937856462">"Se fixer sur un fond d\'écran"</string>
     <string name="permdesc_bindWallpaper" msgid="5287754520361915347">"Permet au support de se fixer sur l\'interface de plus haut niveau d\'un fond d\'écran. Les applications normales ne devraient jamais avoir recours à cette fonctionnalité."</string>
     <string name="permlab_bindDeviceAdmin" msgid="8704986163711455010">"interagir avec l\'administrateur du périphérique"</string>
-    <string name="permdesc_bindDeviceAdmin" msgid="8714424333082216979">"Permet à l\'application d\'envoyer des intentions à l\'administrateur du périphérique. Les applications standard ne devraient jamais avoir recours à cette fonctionnalité."</string>
+    <string name="permdesc_bindDeviceAdmin" msgid="8714424333082216979">"Permet à l\'application d\'envoyer des intentions à l\'administrateur de l\'appareil. Les applications standard ne devraient jamais avoir recours à cette fonctionnalité."</string>
     <string name="permlab_setOrientation" msgid="3365947717163866844">"Changement d\'orientation de l\'écran"</string>
     <string name="permdesc_setOrientation" msgid="6335814461615851863">"Permet à une application de modifier la rotation de l\'écran à tout moment. Les applications normales ne devraient jamais avoir recours à cette fonctionnalité."</string>
     <string name="permlab_signalPersistentProcesses" msgid="4255467255488653854">"Envoi de signaux Linux aux applications"</string>
@@ -290,9 +290,9 @@
     <string name="permlab_writeContacts" msgid="644616215860933284">"Édition des données d\'un contact"</string>
     <string name="permdesc_writeContacts" msgid="3924383579108183601">"Permet à une application de modifier toutes les données de contact (adresses) enregistrées sur le téléphone. Des applications malveillantes peuvent utiliser cette fonctionnalité pour effacer ou modifier vos données de contact."</string>
     <string name="permlab_readCalendar" msgid="6898987798303840534">"lire des événements de l\'agenda"</string>
-    <string name="permdesc_readCalendar" msgid="5533029139652095734">"Permet à une application de lire tous les événements de l\'agenda enregistrés sur votre téléphone. Des applications malveillantes peuvent utiliser cette fonctionnalité pour envoyer les événements de votre agenda à d\'autres personnes."</string>
+    <string name="permdesc_readCalendar" msgid="5533029139652095734">"Permet à une application de lire tous les événements de l\'agenda enregistrés sur votre téléphone. Des applications malveillantes peuvent exploiter cette fonctionnalité pour envoyer les événements de votre agenda à d\'autres personnes."</string>
     <string name="permlab_writeCalendar" msgid="3894879352594904361">"ajouter ou modifier des événements d\'agenda et envoyer des e-mails aux invités"</string>
-    <string name="permdesc_writeCalendar" msgid="2988871373544154221">"Autorise les applications à ajouter ou à modifier des événements dans votre agenda, qui pourra envoyer des e-mails aux invités. Des logiciels malveillants peuvent utiliser cette fonctionnalité pour supprimer ou modifier des événements de l\'agenda ou envoyer des e-mails aux invités."</string>
+    <string name="permdesc_writeCalendar" msgid="2988871373544154221">"Permet aux applications d\'ajouter ou de modifier des événements dans votre agenda, qui est susceptible d\'envoyer des e-mails aux invités. Des applications malveillantes peuvent exploiter cette fonctionnalité pour supprimer ou modifier des événements de l\'agenda ou envoyer des e-mails aux invités."</string>
     <string name="permlab_accessMockLocation" msgid="8688334974036823330">"Création de sources de localisation fictives à des fins de test"</string>
     <string name="permdesc_accessMockLocation" msgid="7648286063459727252">"Permet de créer des sources de localisation fictives à des fins de test. Des applications malveillantes peuvent utiliser cette fonctionnalité pour remplacer la position géographique et/ou l\'état fournis par des sources réelles comme le GPS ou les fournisseurs d\'accès."</string>
     <string name="permlab_accessLocationExtraCommands" msgid="2836308076720553837">"Accès aux commandes de fournisseur de position géographique supplémentaires"</string>
@@ -300,9 +300,9 @@
     <string name="permlab_installLocationProvider" msgid="6578101199825193873">"autoriser l\'installation d\'un fournisseur de services de localisation"</string>
     <string name="permdesc_installLocationProvider" msgid="5449175116732002106">"Créer des sources de données de localisation factices à des fins de test. Les applications malveillantes peuvent exploiter cette fonction pour remplacer la position géographique et/ou l\'état renvoyé par les sources de données de localisation réelles, telles que le GPS ou les fournisseurs réseau, ou pour surveiller et transmettre votre position géographique à une source externe."</string>
     <string name="permlab_accessFineLocation" msgid="8116127007541369477">"Localisation OK (GPS)"</string>
-    <string name="permdesc_accessFineLocation" msgid="7411213317434337331">"Permet d\'accéder à des sources de localisation précises comme le Global Positioning System (GPS) sur le téléphone, lorsque ces services sont disponibles. Des applications malveillantes peuvent utiliser cette fonctionnalité pour déterminer l\'endroit où vous vous trouvez et augmenter la consommation de la batterie de votre téléphone."</string>
+    <string name="permdesc_accessFineLocation" msgid="7411213317434337331">"Permet d\'accéder à des sources de localisation précises telles que le système GPS du téléphone, lorsque ces services sont disponibles. Des applications malveillantes peuvent exploiter cette fonctionnalité pour déterminer votre position, ce qui peut entraîner une utilisation accrue de la batterie."</string>
     <string name="permlab_accessCoarseLocation" msgid="4642255009181975828">"Position géo. approximative (selon le réseau)"</string>
-    <string name="permdesc_accessCoarseLocation" msgid="8235655958070862293">"Accès à des sources de localisation approximative (par ex. des bases de données de réseaux mobiles) pour déterminer la position géographique du téléphone, lorsque cette option est disponible. Des applications malveillantes peuvent utiliser cette fonctionnalité pour déterminer approximativement l\'endroit où vous vous trouvez."</string>
+    <string name="permdesc_accessCoarseLocation" msgid="8235655958070862293">"Permet d\'accéder à des sources de localisation approximatives telles que des bases de données de réseaux mobiles pour déterminer la position géographique du téléphone, lorsque cette option est disponible. Des applications malveillantes peuvent exploiter cette fonctionnalité pour déterminer votre position approximative."</string>
     <string name="permlab_accessSurfaceFlinger" msgid="2363969641792388947">"Accès à SurfaceFlinger"</string>
     <string name="permdesc_accessSurfaceFlinger" msgid="6805241830020733025">"Permet à certaines applications d\'utiliser les fonctionnalités SurfaceFlinger de bas niveau."</string>
     <string name="permlab_readFrameBuffer" msgid="6690504248178498136">"Lecture de la mémoire tampon graphique"</string>
@@ -313,30 +313,30 @@
     <string name="permdesc_recordAudio" msgid="6493228261176552356">"Permet à l\'application d\'accéder au chemin de l\'enregistrement audio."</string>
     <string name="permlab_camera" msgid="3616391919559751192">"prendre des photos et enregistrer des vidéos"</string>
     <string name="permdesc_camera" msgid="6004878235852154239">"Permet de prendre des photos et d\'enregistrer des vidéos avec l\'appareil photo. Cette fonctionnalité permet à l\'application de récupérer à tout moment les images perçues par l\'appareil."</string>
-    <string name="permlab_brick" msgid="8337817093326370537">"Désactivation définitive du téléphone"</string>
+    <string name="permlab_brick" msgid="8337817093326370537">"désactiver définitivement le téléphone"</string>
     <string name="permdesc_brick" msgid="5569526552607599221">"Permet à l\'application de désactiver définitivement le téléphone. Cette fonctionnalité est très dangereuse."</string>
-    <string name="permlab_reboot" msgid="2898560872462638242">"Redémarrage forcé du téléphone"</string>
+    <string name="permlab_reboot" msgid="2898560872462638242">"forcer le redémarrage du téléphone"</string>
     <string name="permdesc_reboot" msgid="7914933292815491782">"Permet à l\'application de forcer le redémarrage du téléphone."</string>
-    <string name="permlab_mount_unmount_filesystems" msgid="1761023272170956541">"Monter et démonter des systèmes de fichiers"</string>
-    <string name="permdesc_mount_unmount_filesystems" msgid="6253263792535859767">"Permet à l\'application de monter et démonter des systèmes de fichiers pour des périphériques de stockage amovibles."</string>
+    <string name="permlab_mount_unmount_filesystems" msgid="1761023272170956541">"Installer et désinstaller des systèmes de fichiers"</string>
+    <string name="permdesc_mount_unmount_filesystems" msgid="6253263792535859767">"Permet à l\'application d\'installer et de désinstaller des systèmes de fichiers pour des périphériques de stockage amovibles."</string>
     <string name="permlab_mount_format_filesystems" msgid="5523285143576718981">"Formatage du périphérique de stockage externe"</string>
     <string name="permdesc_mount_format_filesystems" msgid="574060044906047386">"Permet à l\'application de formater le périphérique de stockage amovible."</string>
     <string name="permlab_asec_access" msgid="3411338632002193846">"obtenir des informations sur la mémoire de stockage interne"</string>
-    <string name="permdesc_asec_access" msgid="8820326551687285439">"Permet à l\'application d\'obtenir des informations sur le stockage interne."</string>
-    <string name="permlab_asec_create" msgid="6414757234789336327">"créer un stockage interne"</string>
+    <string name="permdesc_asec_access" msgid="8820326551687285439">"Permet à l\'application d\'obtenir des informations sur la mémoire de stockage interne."</string>
+    <string name="permlab_asec_create" msgid="6414757234789336327">"créer une mémoire de stockage interne"</string>
     <string name="permdesc_asec_create" msgid="2621346764995731250">"Permet à l\'application de créer une mémoire de stockage interne."</string>
     <string name="permlab_asec_destroy" msgid="526928328301618022">"détruire la mémoire de stockage interne"</string>
-    <string name="permdesc_asec_destroy" msgid="2746706889208066256">"Permet à l\'application de détruire le stockage interne."</string>
+    <string name="permdesc_asec_destroy" msgid="2746706889208066256">"Permet à l\'application de détruire la mémoire de stockage interne."</string>
     <string name="permlab_asec_mount_unmount" msgid="2456287623689029744">"installer/désinstaller la mémoire de stockage interne"</string>
     <string name="permdesc_asec_mount_unmount" msgid="5934375590189368200">"Permet l\'installation ou la désinstallation de la mémoire de stockage interne par l\'application."</string>
     <string name="permlab_asec_rename" msgid="7496633954080472417">"renommer la mémoire de stockage interne"</string>
-    <string name="permdesc_asec_rename" msgid="2152829985238876790">"Permet à l\'application de renommer le stockage interne."</string>
+    <string name="permdesc_asec_rename" msgid="2152829985238876790">"Permet à l\'application de renommer la mémoire de stockage interne."</string>
     <string name="permlab_vibrate" msgid="7768356019980849603">"Contrôle du vibreur"</string>
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Permet à l\'application de contrôler le vibreur."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"Contrôle de la lampe de poche"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Permet à l\'application de contrôler la lampe de poche."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"accéder aux périphériques USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Autorise l\'application à accéder aux périphériques USB"</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"gérer les préférences et les autorisations des périphériques USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Permet à l\'application de gérer les préférences et les autorisations des périphériques USB."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"Tests du matériel"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Permet à l\'application de contrôler différents périphériques à des fins de test matériel."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"Appel direct des numéros de téléphone"</string>
@@ -355,12 +355,12 @@
     <string name="permdesc_modifyPhoneState" msgid="3302284561346956587">"Permet à une application de contrôler les fonctionnalités téléphoniques de l\'appareil. Une application bénéficiant de cette autorisation peut changer de réseau, éteindre et allumer le signal radio du téléphone, etc., sans vous en avertir."</string>
     <string name="permlab_readPhoneState" msgid="2326172951448691631">"Lire l\'état et l\'identité du téléphone"</string>
     <string name="permdesc_readPhoneState" msgid="188877305147626781">"Permet à l\'application d\'accéder aux fonctionnalités d\'appel du téléphone. L\'application peut alors déterminer le numéro de téléphone et le numéro de série de l\'appareil, savoir si un appel est en cours, identifier le numéro appelé, etc."</string>
-    <string name="permlab_wakeLock" msgid="573480187941496130">"Arrêt du mode veille sur le téléphone"</string>
-    <string name="permdesc_wakeLock" msgid="7584036471227467099">"Permet à une application d\'empêcher votre téléphone de passer en mode veille."</string>
+    <string name="permlab_wakeLock" msgid="573480187941496130">"empêcher le téléphone de passer en mode veille"</string>
+    <string name="permdesc_wakeLock" msgid="7584036471227467099">"Permet à une application d\'empêcher le téléphone de passer en mode veille."</string>
     <string name="permlab_devicePower" msgid="4928622470980943206">"Éteindre ou allumer le téléphone"</string>
     <string name="permdesc_devicePower" msgid="4577331933252444818">"Permet à l\'application d\'éteindre et d\'allumer le téléphone."</string>
     <string name="permlab_factoryTest" msgid="3715225492696416187">"Exécution en mode Test d\'usine"</string>
-    <string name="permdesc_factoryTest" msgid="8136644990319244802">"Permet d\'exécuter en tant que test fabricant de faible niveau en autorisant l\'accès au matériel du téléphone. Cette fonctionnalité est uniquement disponible lorsque le téléphone est en mode de test fabricant."</string>
+    <string name="permdesc_factoryTest" msgid="8136644990319244802">"Permet d\'exécuter une application en mode test fabricant de faible niveau en autorisant ainsi l\'accès au téléphone. Cette fonctionnalité est uniquement disponible lorsque le téléphone est en mode test fabricant."</string>
     <string name="permlab_setWallpaper" msgid="6627192333373465143">"Configuration du fond d\'écran"</string>
     <string name="permdesc_setWallpaper" msgid="6417041752170585837">"Permet à une application de définir le fond d\'écran du système."</string>
     <string name="permlab_setWallpaperHints" msgid="3600721069353106851">"Sélection de la la taille du fond d\'écran"</string>
@@ -399,12 +399,16 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Permet à une application de se connecter à des points d\'accès Wi-Fi, de s\'en déconnecter et de modifier des réseaux Wi-Fi configurés."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"autoriser la réception de données en Wi-Fi multidiffusion"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Autorise une application à recevoir des paquets qui ne sont pas directement adressés à votre mobile. Cela peut être utile pour la recherche de services disponibles à proximité. Consomme plus que le mode non multidiffusion."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"afficher l\'état du WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Permet à une application d\'afficher les informations concernant l\'état du WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"modifier l\'état du WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Permet à une application de se connecter au réseau WiMAX et de s\'en déconnecter."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"Gestion Bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Permet à une application de configurer le téléphone Bluetooth local, d\'identifier des périphériques distants et de les associer au téléphone."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"Création de connexions Bluetooth"</string>
-    <string name="permdesc_bluetooth" msgid="762515380679392945">"Permet à une application d\'obtenir la configuration du téléphone Bluetooth local et de créer et accepter des connexions à des appareils associés."</string>
+    <string name="permdesc_bluetooth" msgid="762515380679392945">"Permet à une application d\'obtenir la configuration du téléphone Bluetooth local, de se connecter à des appareils associés et d\'accepter leur connexion."</string>
     <string name="permlab_nfc" msgid="4423351274757876953">"contrôler la communication en champ proche"</string>
-    <string name="permdesc_nfc" msgid="9171401851954407226">"Autorise une application à communiquer avec des tags, cartes et lecteurs prenant en charge la communication en champ proche (NFC)."</string>
+    <string name="permdesc_nfc" msgid="9171401851954407226">"Permet à une application de communiquer avec des tags, cartes et lecteurs prenant en charge la communication en champ proche (NFC)."</string>
     <string name="permlab_disableKeyguard" msgid="4977406164311535092">"Désactivation du verrouillage des touches"</string>
     <string name="permdesc_disableKeyguard" msgid="3189763479326302017">"Permet à une application de désactiver le verrouillage des touches et toute sécurité par mot de passe. Exemple : Votre téléphone désactive le verrouillage du clavier lorsque vous recevez un appel, puis le réactive lorsque vous raccrochez."</string>
     <string name="permlab_readSyncSettings" msgid="6201810008230503052">"Lecture des paramètres de synchronisation"</string>
@@ -421,8 +425,8 @@
     <string name="permdesc_readDictionary" msgid="1082972603576360690">"Permet à une application de lire tous les mots, noms et expressions que l\'utilisateur a pu enregistrer dans son dictionnaire personnel."</string>
     <string name="permlab_writeDictionary" msgid="6703109511836343341">"Enregistrement dans le dictionnaire défini par l\'utilisateur"</string>
     <string name="permdesc_writeDictionary" msgid="2241256206524082880">"Permet à une application d\'enregistrer de nouveaux mots dans le dictionnaire personnel de l\'utilisateur."</string>
-    <string name="permlab_sdcardWrite" product="nosdcard" msgid="85430876310764752">"modifier/supprimer le contenu de la mémoire de stockage USB"</string>
-    <string name="permlab_sdcardWrite" product="default" msgid="8079403759001777291">"Modifier/supprimer le contenu de la carte SD"</string>
+    <string name="permlab_sdcardWrite" product="nosdcard" msgid="85430876310764752">"modif./suppr. contenu mémoire USB"</string>
+    <string name="permlab_sdcardWrite" product="default" msgid="8079403759001777291">"modifier/supprimer le contenu de la carte SD"</string>
     <string name="permdesc_sdcardWrite" product="nosdcard" msgid="6594393334785738252">"Autorise une application à écrire sur la mémoire USB."</string>
     <string name="permdesc_sdcardWrite" product="default" msgid="6643963204976471878">"Autorise une application à écrire sur la carte SD."</string>
     <string name="permlab_cache_filesystem" msgid="5656487264819669824">"accéder au système de fichiers en cache"</string>
@@ -432,13 +436,13 @@
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Définir les règles du mot de passe"</string>
     <string name="policydesc_limitPassword" msgid="9083400080861728056">"Gérer le nombre et le type de caractères autorisés dans les mots de passe de déverrouillage de l\'écran"</string>
     <string name="policylab_watchLogin" msgid="914130646942199503">"Gérer les tentatives de déverrouillage de l\'écran"</string>
-    <string name="policydesc_watchLogin" msgid="7227578260165172673">"Gérer le nombre de mots de passe incorrects saisis lors du déverrouillage de l\'écran et verrouiller le téléphone ou effacer toutes ses données après un certain nombre de tentatives"</string>
+    <string name="policydesc_watchLogin" msgid="7227578260165172673">"Surveiller le nombre de mots de passe incorrects saisis lors du déverrouillage de l\'écran et verrouiller le téléphone ou effacer toutes ses données après un certain nombre de tentatives"</string>
     <string name="policylab_resetPassword" msgid="2620077191242688955">"Modifier le mot de passe de déverrouillage de l\'écran"</string>
     <string name="policydesc_resetPassword" msgid="5391240616981297361">"Modifier le mot de passe de déverrouillage de l\'écran"</string>
     <string name="policylab_forceLock" msgid="2274085384704248431">"Verrouiller l\'écran"</string>
     <string name="policydesc_forceLock" msgid="5696964126226028442">"Gérer le mode et les conditions de verrouillage de l\'écran"</string>
     <string name="policylab_wipeData" msgid="3910545446758639713">"Effacer toutes les données"</string>
-    <string name="policydesc_wipeData" msgid="7669895333814222586">"Effacer les données du téléphone sans avertissement, en restaurant les valeurs d\'usine"</string>
+    <string name="policydesc_wipeData" msgid="7669895333814222586">"Effacer les données du téléphone sans avertissement, en restaurant la configuration usine"</string>
   <string-array name="phoneTypes">
     <item msgid="8901098336658710359">"Domicile"</item>
     <item msgid="869923650527136615">"Mobile"</item>
@@ -541,11 +545,11 @@
     <string name="keyguard_password_enter_pin_code" msgid="3731488827218876115">"Saisissez le code PIN"</string>
     <string name="keyguard_password_enter_password_code" msgid="9138158344813213754">"Saisissez le mot de passe pour procéder au déverrouillage."</string>
     <string name="keyguard_password_wrong_pin_code" msgid="1295984114338107718">"Le code PIN est incorrect !"</string>
-    <string name="keyguard_label_text" msgid="861796461028298424">"Pour débloquer le clavier, appuyez sur \"Menu\" puis sur 0."</string>
+    <string name="keyguard_label_text" msgid="861796461028298424">"Pour déverrouiller le clavier, appuyez sur \"Menu\" puis sur 0."</string>
     <string name="emergency_call_dialog_number_for_display" msgid="696192103195090970">"Numéro d\'urgence"</string>
     <string name="lockscreen_carrier_default" msgid="8812714795156374435">"(Aucun service)"</string>
     <string name="lockscreen_screen_locked" msgid="7288443074806832904">"Écran verrouillé"</string>
-    <string name="lockscreen_instructions_when_pattern_enabled" msgid="46154051614126049">"Appuyez sur \"Menu\" pour débloquer le téléphone ou appeler un numéro d\'urgence"</string>
+    <string name="lockscreen_instructions_when_pattern_enabled" msgid="46154051614126049">"Appuyez sur \"Menu\" pour déverrouiller le téléphone ou appeler un numéro d\'urgence"</string>
     <string name="lockscreen_instructions_when_pattern_disabled" msgid="686260028797158364">"Appuyez sur \"Menu\" pour déverrouiller le téléphone."</string>
     <string name="lockscreen_pattern_instructions" msgid="7478703254964810302">"Dessinez un schéma pour déverrouiller le téléphone"</string>
     <string name="lockscreen_emergency_call" msgid="5347633784401285225">"Appel d\'urgence"</string>
@@ -566,7 +570,7 @@
     <string name="lockscreen_sim_locked_message" msgid="8066660129206001039">"La carte SIM est verrouillée."</string>
     <string name="lockscreen_sim_unlock_progress_dialog_message" msgid="595323214052881264">"Déblocage de la carte SIM..."</string>
     <string name="lockscreen_too_many_failed_attempts_dialog_message" msgid="3514742106066877476">"Vous avez mal reproduit le schéma de déverrouillage <xliff:g id="NUMBER_0">%d</xliff:g> fois. "\n\n"Veuillez réessayer dans <xliff:g id="NUMBER_1">%d</xliff:g> secondes."</string>
-    <string name="lockscreen_failed_attempts_almost_glogin" msgid="3351013842320127827">"Vous avez mal saisi le schéma de déverrouillage <xliff:g id="NUMBER_0">%d</xliff:g> fois. Au bout de <xliff:g id="NUMBER_1">%d</xliff:g> tentatives supplémentaires, vous devrez débloquer votre téléphone à l\'aide de votre identifiant Google."\n\n"Merci de réessayer dans <xliff:g id="NUMBER_2">%d</xliff:g> secondes."</string>
+    <string name="lockscreen_failed_attempts_almost_glogin" msgid="3351013842320127827">"Vous avez mal saisi le schéma de déverrouillage <xliff:g id="NUMBER_0">%d</xliff:g> fois. Au bout de <xliff:g id="NUMBER_1">%d</xliff:g> tentatives supplémentaires, vous devrez déverrouiller votre téléphone à l\'aide de votre identifiant Google."\n\n"Merci de réessayer dans <xliff:g id="NUMBER_2">%d</xliff:g> secondes."</string>
     <string name="lockscreen_too_many_failed_attempts_countdown" msgid="6251480343394389665">"Réessayez dans <xliff:g id="NUMBER">%d</xliff:g> secondes."</string>
     <string name="lockscreen_forgot_pattern_button_text" msgid="2626999449610695930">"Schéma oublié ?"</string>
     <string name="lockscreen_glogin_forgot_pattern" msgid="2588521501166032747">"Déverrouillage du compte"</string>
@@ -577,7 +581,7 @@
     <string name="lockscreen_glogin_submit_button" msgid="7130893694795786300">"Se connecter"</string>
     <string name="lockscreen_glogin_invalid_input" msgid="1364051473347485908">"Nom d\'utilisateur ou mot de passe incorrect."</string>
     <string name="lockscreen_glogin_checking_password" msgid="6758890536332363322">"Vérification..."</string>
-    <string name="lockscreen_unlock_label" msgid="737440483220667054">"Débloquer"</string>
+    <string name="lockscreen_unlock_label" msgid="737440483220667054">"Déverrouiller"</string>
     <string name="lockscreen_sound_on_label" msgid="9068877576513425970">"Son activé"</string>
     <string name="lockscreen_sound_off_label" msgid="996822825154319026">"Son désactivé"</string>
     <string name="password_keyboard_label_symbol_key" msgid="992280756256536042">"?123"</string>
@@ -597,7 +601,7 @@
     <string name="permlab_readHistoryBookmarks" msgid="1284843728203412135">"lire l\'historique et les favoris du navigateur"</string>
     <string name="permdesc_readHistoryBookmarks" msgid="4981489815467617191">"Autorise l\'application à lire toutes les URL auxquelles le navigateur a accédé et tous ses favoris."</string>
     <string name="permlab_writeHistoryBookmarks" msgid="9009434109836280374">"écrire dans l\'historique et les favoris du navigateur"</string>
-    <string name="permdesc_writeHistoryBookmarks" msgid="945571990357114950">"Autorise une application à modifier l\'historique du navigateur ou les favoris enregistrés sur votre téléphone. Des applications malveillantes peuvent utiliser cette fonction pour effacer ou modifier les données de votre navigateur."</string>
+    <string name="permdesc_writeHistoryBookmarks" msgid="945571990357114950">"Permet à une application de modifier l\'historique du navigateur ou les favoris enregistrés sur votre téléphone. Des applications malveillantes peuvent exploiter cette fonction pour effacer ou modifier les données de votre navigateur."</string>
     <string name="permlab_setAlarm" msgid="5924401328803615165">"régler le réveil"</string>
     <string name="permdesc_setAlarm" msgid="5966966598149875082">"Permet à l\'application de définir une alarme dans un utilitaire faisant office de réveil. Certains réveils risquent ne pas prendre en charge cette fonctionnalité."</string>
     <string name="permlab_writeGeolocationPermissions" msgid="4715212655598275532">"Modifier les autorisations de géolocalisation du navigateur"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Utiliser cette application par défaut pour cette action"</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Effacer les paramètres par défaut dans les Paramètres de page d\'accueil &gt; Applications &gt; Gérer les applications."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Sélectionner une action"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Sélectionnez une application pour le périphérique USB"</string>
     <string name="noApplications" msgid="1691104391758345586">"Aucune application ne peut effectuer cette action."</string>
     <string name="aerr_title" msgid="653922989522758100">"Désolé !"</string>
     <string name="aerr_application" msgid="4683614104336409186">"Fermeture soudaine de l\'application <xliff:g id="APPLICATION">%1$s</xliff:g> (du processus <xliff:g id="PROCESS">%2$s</xliff:g>). Merci de réessayer."</string>
@@ -828,22 +833,22 @@
     <string name="ext_media_checking_notification_message" msgid="8287319882926737053">"Recherche d\'erreurs"</string>
     <string name="ext_media_nofs_notification_title" product="nosdcard" msgid="7788040745686229307">"Mémoire de stockage USB vide"</string>
     <string name="ext_media_nofs_notification_title" product="default" msgid="780477838241212997">"Carte SD vide"</string>
-    <string name="ext_media_nofs_notification_message" product="nosdcard" msgid="8623130522556087311">"Le stockage USB est vide ou son système de fichiers n\'est pas pris en charge."</string>
+    <string name="ext_media_nofs_notification_message" product="nosdcard" msgid="8623130522556087311">"La mémoire de stockage USB est vide ou son système de fichiers n\'est pas pris en charge."</string>
     <string name="ext_media_nofs_notification_message" product="default" msgid="3817704088027829380">"La carte SD est vide ou son système de fichiers n\'est pas pris en charge."</string>
-    <string name="ext_media_unmountable_notification_title" product="nosdcard" msgid="2090046769532713563">"Stockage USB endommagé"</string>
+    <string name="ext_media_unmountable_notification_title" product="nosdcard" msgid="2090046769532713563">"Mémoire de stockage USB endommagée"</string>
     <string name="ext_media_unmountable_notification_title" product="default" msgid="6410723906019100189">"Carte SD endommagée"</string>
     <string name="ext_media_unmountable_notification_message" product="nosdcard" msgid="529021299294450667">"La mémoire de stockage USB est endommagée. Un reformatage est peut-être nécessaire."</string>
     <string name="ext_media_unmountable_notification_message" product="default" msgid="6902531775948238989">"La carte SD est endommagée. Vous devrez peut-être la reformater."</string>
     <string name="ext_media_badremoval_notification_title" product="nosdcard" msgid="1661683031330951073">"Mémoire USB retirée inopinément"</string>
     <string name="ext_media_badremoval_notification_title" product="default" msgid="6872152882604407837">"Carte SD retirée inopinément"</string>
     <string name="ext_media_badremoval_notification_message" product="nosdcard" msgid="4329848819865594241">"Désinstaller la mémoire de stockage USB avant de la retirer pour éviter toute perte de données."</string>
-    <string name="ext_media_badremoval_notification_message" product="default" msgid="7260183293747448241">"Désactiver la carte SD avant de la retirer pour éviter toute perte de données."</string>
-    <string name="ext_media_safe_unmount_notification_title" product="nosdcard" msgid="3967973893270360230">"Retirez la mémoire USB en toute sécurité."</string>
+    <string name="ext_media_badremoval_notification_message" product="default" msgid="7260183293747448241">"Désinstaller la carte SD avant de la retirer pour éviter toute perte de données."</string>
+    <string name="ext_media_safe_unmount_notification_title" product="nosdcard" msgid="3967973893270360230">"Vous pouvez retirer la mémoire USB."</string>
     <string name="ext_media_safe_unmount_notification_title" product="default" msgid="6729801130790616200">"La carte SD peut être retirée en toute sécurité"</string>
-    <string name="ext_media_safe_unmount_notification_message" product="nosdcard" msgid="6142195361606493530">"La mémoire de stockage USB peut être retirée en toute sécurité."</string>
+    <string name="ext_media_safe_unmount_notification_message" product="nosdcard" msgid="6142195361606493530">"Vous pouvez retirer la mémoire de stockage USB en toute sécurité."</string>
     <string name="ext_media_safe_unmount_notification_message" product="default" msgid="568841278138377604">"Vous pouvez retirer la carte SD en toute sécurité."</string>
     <string name="ext_media_nomedia_notification_title" product="nosdcard" msgid="4486377230140227651">"Mémoire de stockage USB retirée"</string>
-    <string name="ext_media_nomedia_notification_title" product="default" msgid="8902518030404381318">"Carte SD manquante"</string>
+    <string name="ext_media_nomedia_notification_title" product="default" msgid="8902518030404381318">"Carte SD retirée"</string>
     <string name="ext_media_nomedia_notification_message" product="nosdcard" msgid="6921126162580574143">"Mémoire de stockage USB retirée. Insérez un nouveau support."</string>
     <string name="ext_media_nomedia_notification_message" product="default" msgid="3870120652983659641">"La carte SD a été retirée. Insérez-en une autre."</string>
     <string name="activity_list_empty" msgid="4168820609403385789">"Aucune activité correspondante trouvée"</string>
@@ -893,7 +898,7 @@
     <string name="throttled_notification_message" msgid="4712369856601275146">"Touchez pour en savoir plus sur l\'utilisation des données mobiles"</string>
     <string name="progress_unmounting" product="nosdcard" msgid="535863554318797377">"Désinstallation de la mémoire de stockage USB..."</string>
     <string name="progress_unmounting" product="default" msgid="5556813978958789471">"Désinstallation de la carte SD..."</string>
-    <string name="progress_erasing" product="nosdcard" msgid="4183664626203056915">"Effacement de la  mémoire de stockage USB..."</string>
+    <string name="progress_erasing" product="nosdcard" msgid="4183664626203056915">"Effacement de la mémoire de stockage USB..."</string>
     <string name="progress_erasing" product="default" msgid="2115214724367534095">"Effacement de la carte SD..."</string>
     <string name="format_error" product="nosdcard" msgid="4320339096529911637">"Impossible d\'effacer la mémoire de stockage USB"</string>
     <string name="format_error" product="default" msgid="1343380371925238343">"Impossible d\'effacer la carte SD"</string>
diff --git a/core/res/res/values-hr/strings.xml b/core/res/res/values-hr/strings.xml
index fbf149b..91cc3ed 100644
--- a/core/res/res/values-hr/strings.xml
+++ b/core/res/res/values-hr/strings.xml
@@ -183,6 +183,8 @@
     <string name="permdesc_receiveSms" msgid="6298292335965966117">"Aplikaciji omogućuje primanje i obradu SMS poruka. Zlonamjerne aplikacije mogu pratiti vaše poruke ili ih izbrisati prije nego što ih vi vidite."</string>
     <string name="permlab_receiveMms" msgid="8894700916188083287">"primanje MMS-a"</string>
     <string name="permdesc_receiveMms" msgid="4563346832000174373">"Aplikaciji omogućuje primanje i obradu MMS poruka. Zlonamjerne aplikacije mogu pratiti vaše poruke ili ih izbrisati prije nego što ih vi vidite."</string>
+    <string name="permlab_receiveEmergencyBroadcast" msgid="1803477660846288089">"primanje hitnih odašiljanja"</string>
+    <string name="permdesc_receiveEmergencyBroadcast" msgid="7118393393716546131">"Omogućuje aplikaciji primanje i obradu poruka hitnih odašiljanja. Ta je dozvola dostupna samo aplikacijama sustava."</string>
     <string name="permlab_sendSms" msgid="5600830612147671529">"slanje SMS poruka"</string>
     <string name="permdesc_sendSms" msgid="1946540351763502120">"Aplikaciji omogućuje slanje SMS poruka. Zlonamjerne aplikacije mogu stvarati troškove slanjem poruka bez vaše potvrde."</string>
     <string name="permlab_readSms" msgid="4085333708122372256">"čitanje SMS-a ili MMS-a"</string>
@@ -335,8 +337,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Aplikaciji omogućuje nadzor nad vibracijom."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"nadzor bljeskalice"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Aplikaciji omogućuje nadzor nad bljeskalicom."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"pristupi USB uređajima"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Omogućuje aplikaciji pristup USB uređajima."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"upravljanje postavkama i dozvolama za USB uređaje"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Aplikaciji omogućuje upravljanje postavkama i dozvolama za USB uređaje."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"testiranje hardvera"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Aplikacijama omogućuje nadzor nad raznim vanjskim jedinicama u svrhu hardverskog testiranja."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"izravno pozivanje telefonskog broja"</string>
@@ -399,6 +401,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Aplikacije omogućuju povezivanje i prekidanje veze s Wi-Fi pristupnim točkama te promjene u konfiguriranim Wi-Fi mrežama."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"omogući višenamjenski Wi-Fi prijem"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Aplikaciji omogućuje primanje paketa koji nisu izravno upućeni na vaš uređaj. To može biti korisno za otkrivanje obližnjih usluge. Koristi više energije od višenamjenskog načina rada."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"prikaz stanja WiMAX mreže"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Aplikaciji omogućuje prikaz informacija o stanju WiMAX mreže."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"promjena stanja WiMAX mreže"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Omogućuje aplikaciji povezivanje i prekid veze s WiMAX mrežom."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"bluetooth administracija"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Aplikaciji omogućuje konfiguraciju lokalnog Bluetooth telefona i otkrivanje i sparivanje s udaljenim uređajima."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"stvaranje Bluetooth veza"</string>
@@ -733,6 +739,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Koristi se kao zadana postavka za ovu lokaciju."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Izbrišite zadane postavke u izborniku Početne postavke &gt; Aplikacije &gt; Upravljanje aplikacijama."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Odaberite radnju"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Odaberite aplikaciju za USB uređaj"</string>
     <string name="noApplications" msgid="1691104391758345586">"Tu radnju ne može izvesti nijedna aplikacija."</string>
     <string name="aerr_title" msgid="653922989522758100">"Žao nam je."</string>
     <string name="aerr_application" msgid="4683614104336409186">"Aplikacija <xliff:g id="APPLICATION">%1$s</xliff:g> (postupak <xliff:g id="PROCESS">%2$s</xliff:g>) neočekivano je zaustavljen. Pokušajte ponovo."</string>
@@ -891,7 +898,7 @@
     <string name="throttle_warning_notification_message" msgid="2609734763845705708">"Dotaknite da biste saznali više o upotrebi mobilnih podataka"</string>
     <string name="throttled_notification_title" msgid="6269541897729781332">"Prekoračeno je ograničenje za podatke na mobilnom uređaju"</string>
     <string name="throttled_notification_message" msgid="4712369856601275146">"Dotaknite da biste saznali više o upotrebi mobilnih podataka"</string>
-    <string name="progress_unmounting" product="nosdcard" msgid="535863554318797377">"Isključivanje memorije USB..."</string>
+    <string name="progress_unmounting" product="nosdcard" msgid="535863554318797377">"Isključivanje USB memorije..."</string>
     <string name="progress_unmounting" product="default" msgid="5556813978958789471">"Isključivanje SD kartice..."</string>
     <string name="progress_erasing" product="nosdcard" msgid="4183664626203056915">"Brisanje memorije USB..."</string>
     <string name="progress_erasing" product="default" msgid="2115214724367534095">"Brisanje SD kartice..."</string>
diff --git a/core/res/res/values-hu/strings.xml b/core/res/res/values-hu/strings.xml
index 33fe6d3..da96ada 100644
--- a/core/res/res/values-hu/strings.xml
+++ b/core/res/res/values-hu/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Lehetővé teszi az alkalmazás számára a rezgés vezérlését."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"vaku vezérlése"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Lehetővé teszi az alkalmazás számára a vaku vezérlését."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"USB-eszközök elérése"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Lehetővé teszi az alkalmazások számára az USB-eszközök elérését."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"USB-eszközök preferenciáinak és engedélyeinek kezelése"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Lehetővé teszi, hogy az alkalmazás kezelje az USB-eszközök preferenciáit és engedélyeit."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"hardver tesztelése"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Lehetővé teszi az alkalmazás számára különböző perifériák vezérlését hardvertesztelés céljából."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"telefonszámok közvetlen hívása"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Lehetővé teszi egy alkalmazás számára Wi-Fi hozzáférési pontok használatát, valamint módosítások végrehajtását a konfigurált Wi-Fi hálózatokban."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"Wi-Fi multicast vétel engedélyezése"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Lehetővé teszi egy alkalmazás számára, hogy nem közvetlenül az eszköznek küldött csomagokat is fogadjon. Ez a közeli szolgáltatások felderítésében nyújthat segítséget. Több energiát fogyaszt, mint a nem multicast mód."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"WiMAX-állapot megtekintése"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Lehetővé teszi az alkalmazás számára a WiMAX állapotinformációk megtekintését."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"WiMAX-állapot módosítása"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Lehetővé teszi, hogy egy alkalmazás csatlakozzon a WiMAX hálózathoz, illetve megszüntesse a kapcsolatot a hálózattal."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"bluetooth felügyelet"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Lehetővé teszi egy alkalmazás számára a helyi Bluetooth telefon konfigurálását, valamint a távoli eszközök felderítését és párosítását."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"Bluetooth kapcsolatok létrehozása"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Ez legyen az alapértelmezett program ehhez a művelethez."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Az alapértelmezés törlése a Főoldal beállításai &gt; Alkalmazások &gt; Alkalmazások kezelése menüben lehetséges."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Válasszon műveletet"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Válasszon egy alkalmazást az USB-eszköz számára"</string>
     <string name="noApplications" msgid="1691104391758345586">"Egyik alkalmazás sem tudja végrehajtani ezt a műveletet."</string>
     <string name="aerr_title" msgid="653922989522758100">"Sajnáljuk!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"A(z) <xliff:g id="APPLICATION">%1$s</xliff:g> alkalmazás <xliff:g id="PROCESS">%2$s</xliff:g> folyamata váratlanul leállt. Kérjük, próbálja újra."</string>
diff --git a/core/res/res/values-in/strings.xml b/core/res/res/values-in/strings.xml
index cefc140..052ccb5 100644
--- a/core/res/res/values-in/strings.xml
+++ b/core/res/res/values-in/strings.xml
@@ -128,7 +128,7 @@
     <string name="low_memory" msgid="6632412458436461203">"Penyimpanan di ponsel penuh! Hapus sebagian berkas untuk mendapatkan ruang."</string>
     <string name="me" msgid="6545696007631404292">"Saya"</string>
     <string name="power_dialog" msgid="1319919075463988638">"Opsi telepon"</string>
-    <string name="silent_mode" msgid="7167703389802618663">"Mode senyap"</string>
+    <string name="silent_mode" msgid="7167703389802618663">"Modus senyap"</string>
     <string name="turn_on_radio" msgid="3912793092339962371">"Hidupkan nirkabel"</string>
     <string name="turn_off_radio" msgid="8198784949987062346">"Matikan nirkabel"</string>
     <string name="screen_lock" msgid="799094655496098153">"Kunci layar"</string>
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Mengizinkan aplikasi mengontrol penggetar."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"mengontrol lampu senter"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Mengizinkan aplikasi mengontrol lampu senter."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"akses perangkat USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Mengizinkan aplikasi untuk perangkat USB."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"kelola preferensi dan izin untuk perangkat USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Membiarkan aplikasi mengelola preferensi dan izin untuk perangkat USB."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"uji perangkat keras"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Mengizinkan aplikasi mengontrol berbagai perangkat periferal untuk tujuan menguji perangkat keras."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"panggil nomor telepon secara langsung"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Mengizinkan aplikasi tersambung dan diputus dari titik akses Wi-Fi, dan melakukan perubahan pada jaringan Wi-Fi yang dikonfigurasi."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"Izinkan penerimaan Wi-Fi Multicast"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Mengizinkan aplikasi menerima paket yang tidak langsung dialamatkan ke perangkat Anda. Ini dapat bermanfaat ketika mencari perangkat yang ditawarkan di dekat Anda. Aplikasi ini menggunakan lebih banyak daya ketimbang mode selain multicast."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"lihat status WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Mengizinkan aplikasi melihat informasi tentang status WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"Ganti status WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Mengizinkan aplikasi menyambung ke dan memutus dari jaringan WiMAX."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"Administrasi bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Mengizinkan aplikasi mengonfigurasi ponsel Bluetooth lokal, dan menemukan dan menyandingkan perangkat jarak jauh."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"buat sambungan Bluetooth"</string>
@@ -605,7 +609,7 @@
     <string name="save_password_message" msgid="767344687139195790">"Apakah Anda ingin peramban menyimpan sandi ini?"</string>
     <string name="save_password_notnow" msgid="6389675316706699758">"Tidak sekarang"</string>
     <string name="save_password_remember" msgid="6491879678996749466">"Ingat"</string>
-    <string name="save_password_never" msgid="8274330296785855105">"Tidak pernah"</string>
+    <string name="save_password_never" msgid="8274330296785855105">"Jangan"</string>
     <string name="open_permission_deny" msgid="5661861460947222274">"Anda tidak memiliki izin untuk membuka laman ini."</string>
     <string name="text_copied" msgid="4985729524670131385">"Teks disalin ke clipboard."</string>
     <string name="more_item_label" msgid="4650918923083320495">"Lainnya"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Gunakan secara bawaan untuk tindakan ini."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Bersihkan bawaan pada Setelan Beranda &gt; Aplikasi &gt; Kelola aplikasi."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Pilih tindakan"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Pilih sebuah aplikasi untuk perangkat USB"</string>
     <string name="noApplications" msgid="1691104391758345586">"Tidak ada aplikasi dapat melakukan tindakan ini."</string>
     <string name="aerr_title" msgid="653922989522758100">"Maaf!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"<xliff:g id="APPLICATION">%1$s</xliff:g> aplikasi (<xliff:g id="PROCESS">%2$s</xliff:g> proses) berhenti tiba-tiba. Harap coba lagi."</string>
diff --git a/core/res/res/values-it/strings.xml b/core/res/res/values-it/strings.xml
index 8608b5b..90c2ab7 100644
--- a/core/res/res/values-it/strings.xml
+++ b/core/res/res/values-it/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Consente all\'applicazione di controllare la vibrazione."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"controllo flash"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Consente all\'applicazione di controllare il flash."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"accesso a dispositivi USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Consente all\'applicazione di accedere ai dispositivi USB"</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"gestione preferenze e autorizzazioni per dispositivi USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Consente all\'applicazione di gestire le preferenze e le autorizzazioni relative ai dispositivi USB."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"esecuzione test hardware"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Consente all\'applicazione di controllare varie periferiche per il test dell\'hardware."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"chiamata diretta n. telefono"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Consente a un\'applicazione di connettersi/disconnettersi da punti di accesso Wi-Fi e di apportare modifiche alle reti Wi-Fi configurate."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"consenti ricezione multicast Wi-Fi"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Consente a un\'applicazione di ricevere pacchetti non direttamente indirizzati al tuo dispositivo. Può essere utile durante la ricerca di servizi offerti nelle vicinanze. Consuma di più rispetto alla modalità non multicast."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"visualizzazione stato WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Consente a un\'applicazione di visualizzare le informazioni relative allo stato della rete WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"modifica stato WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Consente a un\'applicazione di connettersi/disconnettersi dalla rete WiMAX."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"gestione Bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Consente a un\'applicazione di configurare il telefono Bluetooth locale e di rilevare e abbinare dispositivi remoti."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"creazione connessioni Bluetooth"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Usa come predefinita per questa azione."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Cancella predefinita in Home &gt; Impostazioni &gt; Applicazioni &gt; Gestisci applicazioni."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Seleziona un\'azione"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Seleziona un\'applicazione per il dispositivo USB"</string>
     <string name="noApplications" msgid="1691104391758345586">"Nessuna applicazione è in grado di svolgere questa azione."</string>
     <string name="aerr_title" msgid="653922989522758100">"Spiacenti."</string>
     <string name="aerr_application" msgid="4683614104336409186">"Interruzione imprevista dell\'applicazione <xliff:g id="APPLICATION">%1$s</xliff:g> (processo <xliff:g id="PROCESS">%2$s</xliff:g>). Riprova."</string>
@@ -872,7 +877,7 @@
     <string name="permission_request_notification_with_subtitle" msgid="4325409589686688000">"Autorizzazione richiesta"\n"per l\'account <xliff:g id="ACCOUNT">%s</xliff:g>"</string>
     <string name="input_method_binding_label" msgid="1283557179944992649">"Metodo inserimento"</string>
     <string name="sync_binding_label" msgid="3687969138375092423">"Sinc"</string>
-    <string name="accessibility_binding_label" msgid="4148120742096474641">"Accesso facilitato"</string>
+    <string name="accessibility_binding_label" msgid="4148120742096474641">"Accessibilità"</string>
     <string name="wallpaper_binding_label" msgid="1240087844304687662">"Sfondo"</string>
     <string name="chooser_wallpaper" msgid="7873476199295190279">"Cambia sfondo"</string>
     <string name="pptp_vpn_description" msgid="2688045385181439401">"Protocollo di tunneling Point-to-Point"</string>
diff --git a/core/res/res/values-iw/strings.xml b/core/res/res/values-iw/strings.xml
index 454a624..1d48f6e 100644
--- a/core/res/res/values-iw/strings.xml
+++ b/core/res/res/values-iw/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"מאפשר ליישום לשלוט ברטט."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"שליטה בפנס"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"מאפשר ליישום לשלוט בפנס."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"גישה להתקני USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"מאפשר ליישום גישה להתקני USB."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"נהל העדפות ואישורים עבור התקני USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"מאפשר ליישום לנהל העדפות ואישורים עבור התקני USB."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"בדוק חומרה"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"מאפשר ליישום לשלוט בציוד היקפי מסוגים שונים לצורך בדיקת חומרה."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"התקשר ישירות למספרי טלפון"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"מאפשר ליישום להתחבר ולהתנתק מנקודות גישה של Wi-Fi, ולבצע שינויים ברשתות Wi-Fi מוגדרות."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"אפשר קבלת שידורים מרובים ב-Wi-Fi"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"מאפשר ליישום לקבל חפיסות שלא ממוענות ישירות למכשיר שלך. יכולת זו שימושית בעת גילוי שירותים המוצעים בקרבת מקום. היא משתמשת במתח סוללה רב יותר לעומת מצב שאינו ריבוי שידורים."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"הצג את מצב WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"מאפשר ליישום להציג את המידע על המצב של WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"שנה את מצב WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"מאפשר ליישום להתחבר ולהתנתק מרשת WiMAX."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"ניהול Bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"מאפשר ליישום להגדיר את טלפון Bluetooth המקומי, ולגלות מכשירים מרוחקים ולבצע התאמה איתם."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"צור חיבורי Bluetooth"</string>
@@ -440,7 +444,7 @@
     <string name="policylab_wipeData" msgid="3910545446758639713">"מחק את כל הנתונים"</string>
     <string name="policydesc_wipeData" msgid="7669895333814222586">"מחק את נתוני הטלפון ללא אזהרה, על ידי ביצוע איפוס נתוני יצרן"</string>
   <string-array name="phoneTypes">
-    <item msgid="8901098336658710359">"דף הבית"</item>
+    <item msgid="8901098336658710359">"בית"</item>
     <item msgid="869923650527136615">"נייד"</item>
     <item msgid="7897544654242874543">"עבודה"</item>
     <item msgid="1103601433382158155">"פקס בעבודה"</item>
@@ -450,19 +454,19 @@
     <item msgid="9192514806975898961">"מותאם אישית"</item>
   </string-array>
   <string-array name="emailAddressTypes">
-    <item msgid="8073994352956129127">"דף הבית"</item>
+    <item msgid="8073994352956129127">"בית"</item>
     <item msgid="7084237356602625604">"עבודה"</item>
     <item msgid="1112044410659011023">"אחר"</item>
     <item msgid="2374913952870110618">"מותאם אישית"</item>
   </string-array>
   <string-array name="postalAddressTypes">
-    <item msgid="6880257626740047286">"דף הבית"</item>
+    <item msgid="6880257626740047286">"בית"</item>
     <item msgid="5629153956045109251">"עבודה"</item>
     <item msgid="4966604264500343469">"אחר"</item>
     <item msgid="4932682847595299369">"מותאם אישית"</item>
   </string-array>
   <string-array name="imAddressTypes">
-    <item msgid="1738585194601476694">"דף הבית"</item>
+    <item msgid="1738585194601476694">"בית"</item>
     <item msgid="1359644565647383708">"עבודה"</item>
     <item msgid="7868549401053615677">"אחר"</item>
     <item msgid="3145118944639869809">"מותאם אישית"</item>
@@ -483,7 +487,7 @@
     <item msgid="1648797903785279353">"Jabber"</item>
   </string-array>
     <string name="phoneTypeCustom" msgid="1644738059053355820">"מותאם אישית"</string>
-    <string name="phoneTypeHome" msgid="2570923463033985887">"דף הבית"</string>
+    <string name="phoneTypeHome" msgid="2570923463033985887">"בית"</string>
     <string name="phoneTypeMobile" msgid="6501463557754751037">"נייד"</string>
     <string name="phoneTypeWork" msgid="8863939667059911633">"עבודה"</string>
     <string name="phoneTypeFaxWork" msgid="3517792160008890912">"פקס בעבודה"</string>
@@ -507,16 +511,16 @@
     <string name="eventTypeAnniversary" msgid="3876779744518284000">"יום השנה"</string>
     <string name="eventTypeOther" msgid="5834288791948564594">"אירוע"</string>
     <string name="emailTypeCustom" msgid="8525960257804213846">"מותאם אישית"</string>
-    <string name="emailTypeHome" msgid="449227236140433919">"דף הבית"</string>
+    <string name="emailTypeHome" msgid="449227236140433919">"בית"</string>
     <string name="emailTypeWork" msgid="3548058059601149973">"עבודה"</string>
     <string name="emailTypeOther" msgid="2923008695272639549">"אחר"</string>
     <string name="emailTypeMobile" msgid="119919005321166205">"סלולרי"</string>
     <string name="postalTypeCustom" msgid="8903206903060479902">"מותאם אישית"</string>
-    <string name="postalTypeHome" msgid="8165756977184483097">"דף הבית"</string>
+    <string name="postalTypeHome" msgid="8165756977184483097">"בית"</string>
     <string name="postalTypeWork" msgid="5268172772387694495">"עבודה"</string>
     <string name="postalTypeOther" msgid="2726111966623584341">"אחר"</string>
     <string name="imTypeCustom" msgid="2074028755527826046">"מותאם אישית"</string>
-    <string name="imTypeHome" msgid="6241181032954263892">"דף הבית"</string>
+    <string name="imTypeHome" msgid="6241181032954263892">"בית"</string>
     <string name="imTypeWork" msgid="1371489290242433090">"עבודה"</string>
     <string name="imTypeOther" msgid="5377007495735915478">"אחר"</string>
     <string name="imProtocolCustom" msgid="6919453836618749992">"מותאם אישית"</string>
@@ -533,7 +537,7 @@
     <string name="orgTypeOther" msgid="3951781131570124082">"אחר"</string>
     <string name="orgTypeCustom" msgid="225523415372088322">"מותאם אישית"</string>
     <string name="sipAddressTypeCustom" msgid="2473580593111590945">"מותאם אישית"</string>
-    <string name="sipAddressTypeHome" msgid="6093598181069359295">"דף הבית"</string>
+    <string name="sipAddressTypeHome" msgid="6093598181069359295">"בית"</string>
     <string name="sipAddressTypeWork" msgid="6920725730797099047">"עבודה"</string>
     <string name="sipAddressTypeOther" msgid="4408436162950119849">"אחר"</string>
     <string name="contact_status_update_attribution" msgid="5112589886094402795">"דרך <xliff:g id="SOURCE">%1$s</xliff:g>"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"השתמש כברירת מחדל עבור פעולה זו."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"נקה את ברירת המחדל ב\'הגדרות דף הבית\' &gt; \'יישומים\' &gt; \'נהל יישומים\'."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"בחר פעולה"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"בחר יישום עבור התקן ה-USB"</string>
     <string name="noApplications" msgid="1691104391758345586">"אין יישומים שיכולים לבצע פעולה זו."</string>
     <string name="aerr_title" msgid="653922989522758100">"מצטערים!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"היישום <xliff:g id="APPLICATION">%1$s</xliff:g> (תהליך <xliff:g id="PROCESS">%2$s</xliff:g>) הופסק באופן לא צפוי. נסה שוב."</string>
diff --git a/core/res/res/values-ja/strings.xml b/core/res/res/values-ja/strings.xml
index 48c73cc..0e26ce2 100644
--- a/core/res/res/values-ja/strings.xml
+++ b/core/res/res/values-ja/strings.xml
@@ -270,7 +270,7 @@
     <string name="permlab_readLogs" msgid="6615778543198967614">"機密ログデータの読み取り"</string>
     <string name="permdesc_readLogs" msgid="8896449437464867766">"システムの各種ログファイルの読み取りをアプリケーションに許可します。許可すると端末の使用状況に関する全般的な情報が読み取られます。この情報には個人情報や機密情報が含まれる場合があります。"</string>
     <string name="permlab_diagnostic" msgid="8076743953908000342">"diagが所有するリソースの読み書き"</string>
-    <string name="permdesc_diagnostic" msgid="3121238373951637049">"diagグループが所有するリソース(例:/dev内のファイル)への読み書きをアプリケーションに許可します。システムの安定性とセキュリティに影響する恐れがあります。メーカー/オペレーターによるハードウェア固有の診断以外には使用しないでください。"</string>
+    <string name="permdesc_diagnostic" msgid="3121238373951637049">"diagグループが所有するリソース(例:/dev内のファイル)への読み書きをアプリケーションに許可します。システムの安定性とセキュリティに影響する恐れがあります。メーカー/通信事業者によるハードウェア固有の診断以外には使用しないでください。"</string>
     <string name="permlab_changeComponentState" msgid="79425198834329406">"アプリケーションのコンポーネントを有効/無効にする"</string>
     <string name="permdesc_changeComponentState" msgid="4569107043246700630">"別アプリケーションのコンポーネントの有効/無効を変更することをアプリケーションに許可します。これにより悪意のあるアプリケーションが、携帯電話の重要な機能を無効にする恐れがあります。アプリケーションコンポーネントが利用できない、整合性が取れない、または不安定な状態になる恐れがあるので、許可には注意が必要です。"</string>
     <string name="permlab_setPreferredApplications" msgid="3393305202145172005">"優先アプリケーションの設定"</string>
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"バイブレーションの制御をアプリケーションに許可します。"</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"ライトのコントロール"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"ライトの制御をアプリケーションに許可します。"</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"USBデバイスへのアクセス"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"USBデバイスへのアクセスをアプリケーションに許可します。"</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"USBデバイスの設定と許可の管理"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"USBデバイスの設定と許可の管理をアプリケーションに許可します。"</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"ハードウェアのテスト"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"ハードウェアのテストのためにさまざまな周辺機器を制御することをアプリケーションに許可します。"</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"電話番号発信"</string>
@@ -352,13 +352,13 @@
     <string name="permlab_bindGadget" msgid="776905339015863471">"ウィジェットの選択"</string>
     <string name="permdesc_bindGadget" msgid="2098697834497452046">"どのアプリケーションがどのウィジェットを使用できるかシステムに指定することをこのアプリケーションに許可します。これにより、アプリケーション間で個人データにアクセスできるようになります。通常のアプリケーションでは使用しません。"</string>
     <string name="permlab_modifyPhoneState" msgid="8423923777659292228">"端末ステータスの変更"</string>
-    <string name="permdesc_modifyPhoneState" msgid="3302284561346956587">"端末の電話機能のコントロールをアプリケーションに許可します。アプリケーションは、ネットワークの切り替え、携帯電話の無線通信のオン/オフなどを通知せずに行うことができます。"</string>
+    <string name="permdesc_modifyPhoneState" msgid="3302284561346956587">"端末の電話機能のコントロールをアプリケーションに許可します。アプリケーションは、ネットワークの切り替え、携帯電話の無線通信のON/OFFなどを通知せずに行うことができます。"</string>
     <string name="permlab_readPhoneState" msgid="2326172951448691631">"携帯のステータスとIDの読み取り"</string>
     <string name="permdesc_readPhoneState" msgid="188877305147626781">"端末の電話機能へのアクセスをアプリケーションに許可します。この権限が許可されたアプリケーションでは、この携帯の電話番号やシリアル番号、通話中かどうか、通話相手の電話番号などを特定できます。"</string>
     <string name="permlab_wakeLock" msgid="573480187941496130">"端末のスリープを無効にする"</string>
     <string name="permdesc_wakeLock" msgid="7584036471227467099">"端末のスリープを無効にすることをアプリケーションに許可します。"</string>
     <string name="permlab_devicePower" msgid="4928622470980943206">"電源のON/OFF"</string>
-    <string name="permdesc_devicePower" msgid="4577331933252444818">"携帯電話の電源のオン/オフをアプリケーションに許可します。"</string>
+    <string name="permdesc_devicePower" msgid="4577331933252444818">"携帯電話の電源のON/OFFをアプリケーションに許可します。"</string>
     <string name="permlab_factoryTest" msgid="3715225492696416187">"出荷時試験モードでの実行"</string>
     <string name="permdesc_factoryTest" msgid="8136644990319244802">"携帯電話のハードウェアへのアクセスを完全に許可して、低レベルのメーカーテストとして実行します。メーカーのテストモードで携帯電話を使用するときのみ利用できます。"</string>
     <string name="permlab_setWallpaper" msgid="6627192333373465143">"壁紙の設定"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Wi-Fiアクセスポイントへの接続や接続の切断、設定されたWi-Fiネットワークの変更をアプリケーションに許可します。"</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"Wi-Fiマルチキャストの受信を許可する"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"端末を直接の宛先とはしていないパケットの受信をアプリケーションに許可します。近隣で提供中のサービスを検出したい場合に便利です。マルチキャスト以外のモードよりも電力を消費します。"</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"WiMAX状態の表示"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"WiMAX状態に関する情報の表示をアプリケーションに許可します。"</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"WiMAX状態の変更"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"WiMAXネットワークへの接続と接続解除をアプリケーションに許可します。"</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"Bluetoothの管理"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"このBluetooth端末の設定、およびリモート端末を検出してペアに設定することをアプリケーションに許可します。"</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"Bluetooth接続の作成"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"常にこの操作で使用する"</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"ホームの[設定]&gt;[アプリケーション]&gt;[アプリケーションの管理]でデフォルト設定をクリアします。"</string>
     <string name="chooseActivity" msgid="1009246475582238425">"操作の選択"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"USBデバイス用アプリケーションを選択"</string>
     <string name="noApplications" msgid="1691104391758345586">"この操作を実行できるアプリケーションはありません。"</string>
     <string name="aerr_title" msgid="653922989522758100">"エラー"</string>
     <string name="aerr_application" msgid="4683614104336409186">"<xliff:g id="APPLICATION">%1$s</xliff:g>(<xliff:g id="PROCESS">%2$s</xliff:g>)が予期せず停止しました。やり直してください。"</string>
diff --git a/core/res/res/values-ko/strings.xml b/core/res/res/values-ko/strings.xml
index 179dabe..a81e73b 100644
--- a/core/res/res/values-ko/strings.xml
+++ b/core/res/res/values-ko/strings.xml
@@ -177,7 +177,7 @@
     <string name="permdesc_statusBarService" msgid="4097605867643520920">"애플리케이션이 상태 표시줄이 되도록 허용합니다."</string>
     <string name="permlab_expandStatusBar" msgid="1148198785937489264">"상태 표시줄 확장/축소"</string>
     <string name="permdesc_expandStatusBar" msgid="7088604400110768665">"애플리케이션이 상태 표시줄을 확장하거나 축소할 수 있도록 합니다."</string>
-    <string name="permlab_processOutgoingCalls" msgid="1136262550878335980">"발신전화 가로채기"</string>
+    <string name="permlab_processOutgoingCalls" msgid="1136262550878335980">"발신전화 차단"</string>
     <string name="permdesc_processOutgoingCalls" msgid="2228988201852654461">"애플리케이션이 발신전화를 처리하고 전화를 걸 번호를 변경할 수 있도록 합니다. 이 경우 악성 애플리케이션이 발신전화를 모니터링하거나, 다른 방향으로 돌리거나, 중단시킬 수 있습니다."</string>
     <string name="permlab_receiveSms" msgid="2697628268086208535">"SMS 수신"</string>
     <string name="permdesc_receiveSms" msgid="6298292335965966117">"애플리케이션이 SMS 메시지를 받고 처리할 수 있도록 합니다. 이 경우 악성 애플리케이션이 메시지를 모니터링하거나 사용자가 보기 전에 삭제할 수 있습니다."</string>
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"애플리케이션이 진동을 제어할 수 있도록 합니다."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"카메라 플래시 제어"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"애플리케이션이 카메라 플래시를 제어할 수 있도록 합니다."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"USB 장치 액세스"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"애플리케이션이 USB 장치에 액세스하도록 허용합니다."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"USB 기기에 대한 환경설정 및 권한 관리"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"애플리케이션이 USB 기기에 대한 환경설정 및 권한을 관리하도록 허용합니다."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"하드웨어 테스트"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"애플리케이션이 하드웨어를 테스트할 목적으로 다양한 주변장치를 제어할 수 있도록 합니다."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"전화번호 자동 연결"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"애플리케이션이 Wi-Fi 액세스포인트에 연결하거나 연결을 끊고, 구성된 Wi-Fi 네트워크를 변경할 수 있도록 합니다."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"Wi-Fi 멀티캐스트 수신 허용"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"애플리케이션이 휴대기기로 직접 주소가 지정되지 않은 패킷을 받을 수 있도록 합니다. 이 기능은 가까운 곳에서 제공되는 서비스를 검색할 때 유용하며 비멀티캐스트 모드보다 전원을 더 많이 소비합니다."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"WiMAX 상태 보기"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"애플리케이션이 WiMAX의 상태에 대한 정보를 볼 수 있도록 합니다."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"WiMAX 상태 변경"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"애플리케이션이 WiMAX 네트워크에 연결하거나 연결을 끊을 수 있도록 합니다."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"Bluetooth 관리"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"애플리케이션이 로컬 Bluetooth 휴대전화를 구성한 다음 원격 장치를 검색하여 페어링할 수 있도록 합니다."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"Bluetooth 연결 만들기"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"이 작업에 대해 기본값으로 사용"</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"홈 설정 &gt; 애플리케이션 &gt; 애플리케이션 관리에서 기본값을 지웁니다."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"작업 선택"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"USB 기기에 대한 애플리케이션 선택"</string>
     <string name="noApplications" msgid="1691104391758345586">"작업을 수행할 수 있는 애플리케이션이 없습니다."</string>
     <string name="aerr_title" msgid="653922989522758100">"죄송합니다."</string>
     <string name="aerr_application" msgid="4683614104336409186">"<xliff:g id="APPLICATION">%1$s</xliff:g> 애플리케이션(<xliff:g id="PROCESS">%2$s</xliff:g> 프로세스)이 예상치 않게 중지되었습니다. 다시 시도해 주세요."</string>
@@ -863,7 +868,7 @@
     <string name="create_contact_using" msgid="4947405226788104538">"전화번호부에"\n"<xliff:g id="NUMBER">%s</xliff:g> 추가"</string>
     <string name="accessibility_compound_button_selected" msgid="5612776946036285686">"선택함"</string>
     <string name="accessibility_compound_button_unselected" msgid="8864512895673924091">"선택 안함"</string>
-    <string name="grant_credentials_permission_message_header" msgid="6824538733852821001">"현재 이후로 하나 이상의 다음 애플리케이션이 계정에 대한 액세스 권한을 요청합니다."</string>
+    <string name="grant_credentials_permission_message_header" msgid="6824538733852821001">"다음 애플리케이션에서 계정 액세스 요청이 들어왔습니다."</string>
     <string name="grant_credentials_permission_message_footer" msgid="3125211343379376561">"요청을 허용하시겠습니까?"</string>
     <string name="grant_permissions_header_text" msgid="2722567482180797717">"액세스 요청"</string>
     <string name="allow" msgid="7225948811296386551">"허용"</string>
diff --git a/core/res/res/values-lt/strings.xml b/core/res/res/values-lt/strings.xml
index 07a1e72..656338a 100644
--- a/core/res/res/values-lt/strings.xml
+++ b/core/res/res/values-lt/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Leidžia programai valdyti vibratorių."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"valdyti šviesos signalą"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Leidžia programai valdyti šviesos signalą."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"pasiekti USB įrenginius"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Leidžiama programai pasiekti USB įrenginius."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"valdyti USB įrenginių nuostatas ir leidimus"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Leidžiama programai valdyti USB įrenginių nuostatas ir leidimus."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"bandyti aparatinę įrangą"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Leidžia programai valdyti įvairius išorinius įrenginius aparatinės įrangos bandymo tikslais."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"skambinti tiesiogiai telefono numeriais"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Leidžia programai prisijungti ir atsijungti nuo „Wi-Fi“ prieigos taškų ir keisti konfigūruotus „Wi-Fi“ tinklus."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"leisti „Wi-Fi“ daugiaadresio perdavimo priėmimą"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Leidžia programai gauti paketus, tiesiogiai neadresuotus jūsų įrenginiui. Tai naudinga atradus šalia siūlomas paslaugas. Tai naudoja daugiau energijos nei ne daugiaadresio perdavimo režimas."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"žiūrėti „WiMAX“ būseną"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Leidžiama programai matyti informaciją apie „WiMAX“ būseną."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"keisti „WiMAX“ būseną"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Leidžiama programai prisijungti prie „WiMAX“ tinklo ir nuo jo atsijungti."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"„bluetooth“ administravimas"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Leidžia programai konfigūruoti vietinį „Bluetooth“ telefoną ir atrasti bei susieti su nuotoliniais įrenginiais."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"kurti „Bluetooth“ ryšius"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Šiam veiksmui tai naudoti pagal numatytuosius nustatymus."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Išvalykite numatytuosius nustatymus apsilankę „Pagrindiniai nustatymai“ &gt; „Programos“ &gt; „Valdyti programas“."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"pasirinkti veiksmą"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Pasirinkti programą USB įrenginiui"</string>
     <string name="noApplications" msgid="1691104391758345586">"Šio veiksmo negali atlikti jokios programos."</string>
     <string name="aerr_title" msgid="653922989522758100">"Apgailestaujame!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"Programa <xliff:g id="APPLICATION">%1$s</xliff:g> (<xliff:g id="PROCESS">%2$s</xliff:g> procesas) netikėtai sustojo. Bandykite dar kartą."</string>
diff --git a/core/res/res/values-lv/strings.xml b/core/res/res/values-lv/strings.xml
index 59c93393..6462b05 100644
--- a/core/res/res/values-lv/strings.xml
+++ b/core/res/res/values-lv/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Ļauj lietojumprogrammai kontrolēt vibrozvanu."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"kontrolēt uzliesmojumu"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Ļauj lietojumprogrammai kontrolēt uzliesmojumu."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"piekļuve USB ierīcēm"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Ļauj lietojumprogrammai piekļūt USB ierīcēm."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"USB ierīču preferenču un atļauju pārvaldība"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Ļauj lietojumprogrammai pārvaldīt preferences un atļaujas saistībā ar USB ierīcēm."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"pārbaudīt aparatūru"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Ļauj lietojumprogrammai kontrolēt dažādas perifērijas ierīces aparatūras pārbaudīšanas nolūkos."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"tieši zvanīt uz tālruņa numuriem"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Ļauj lietojumprogrammai izveidot savienojumu ar Wi-Fi piekļuves punktiem un atvienot to, kā arī veikt izmaiņas konfigurētajos Wi-Fi tīklos."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"atļaut Wi-Fi multiraides uztveršanu"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Ļauj lietojumprogrammai saņemt paketes, kas nav tieši adresētas ierīcei. Tas var būt noderīgi, atklājot pakalpojumus, kas tiek piedāvāti tuvākajā apkārtnē. Tas izmanto vairāk jaudas nekā režīmā, kas nav multiraides režīms."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"WiMAX statusa skatīšana"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Ļauj lietojumprogrammai skatīt informāciju par WiMAX statusu."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"WiMAX statusa mainīšana"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Ļauj lietojumprogrammai izveidot un pārtraukt savienojumu ar WiMAX tīklu."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"Bluetooth administrēšana"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Ļauj lietojumprogrammai konfigurēt vietējo Bluetooth tālruni un atklāt attālās ierīces, un izveidot pāri ar tām."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"izveidot Bluetooth savienojumus"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Pēc noklusējuma izmantot šai darbībai."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Notīriet noklusējumu šeit: Sākuma iestatījumi &gt; Lietojumprogrammas &gt; Lietojumprogrammu pārvaldība."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Atlasiet darbību"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Atlasīt lietojumprogrammu USB ierīcei"</string>
     <string name="noApplications" msgid="1691104391758345586">"Šo darbību nevar veikt neviena lietojumprogramma."</string>
     <string name="aerr_title" msgid="653922989522758100">"Atvainojiet!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"Lietojumprogrammas <xliff:g id="APPLICATION">%1$s</xliff:g> (process <xliff:g id="PROCESS">%2$s</xliff:g>) darbība neparedzēti tika apturēta. Lūdzu, mēģiniet vēlreiz."</string>
diff --git a/core/res/res/values-nb/strings.xml b/core/res/res/values-nb/strings.xml
index 6424c68..35a7606 100644
--- a/core/res/res/values-nb/strings.xml
+++ b/core/res/res/values-nb/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Lar applikasjonen kontrollere vibratoren."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"kontrollere lommelykten"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Lar applikasjonen kontrollere lommelykten."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"tilgang til USB-enheter"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Tillater programmet å få tilgang til USB-enheter."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"administrere innstillinger og tillatelser for USB-enheter"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Tillater at programmet administrerer innstillinger og tillatelser for USB-enheter."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"teste maskinvare"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Lar applikasjonen styre diverse enheter med det formål å teste maskinvaren."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"ringe telefonnummer direkte"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Lar applikasjonen koble til og fra trådløse aksesspunkt, og å gjøre endringer i konfigurerte trådløse nettverk."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"tillat multicast for trådløse nettverk"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Lar applikasjonen motta pakker som ikke er adressert til enheten selv. Dette kan være nyttig ved leting etter nærliggende tjenester, men bruker mer strøm enn ikke-multicast-modus."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"vis WiMAX-status"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Dette gjør det mulig for en app å vise informasjon om WiMAX-statusen."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"endre WiMAX-status"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Gjør at en app kan koble til og fra WiMAX-nettverk."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"Bluetooth-administrasjon"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Lar applikasjonen konfigurere den lokale Bluetooth-telefonen, og å oppdage og pare med andre enheter."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"opprette Bluetooth-tilkoblinger"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Bruk som standardvalg."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Fjern standardvalg i Innstillinger &gt; Applikasjoner &gt; Installerte applikasjoner."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Velg en aktivitet"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Velg et program for USB-enheten"</string>
     <string name="noApplications" msgid="1691104391758345586">"Ingen applikasjoner kan gjøre dette."</string>
     <string name="aerr_title" msgid="653922989522758100">"Beklager!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"Applikasjonen <xliff:g id="APPLICATION">%1$s</xliff:g> (prosess <xliff:g id="PROCESS">%2$s</xliff:g>) stoppet uventet. Prøv igjen."</string>
@@ -834,11 +839,11 @@
     <string name="ext_media_unmountable_notification_title" product="default" msgid="6410723906019100189">"Skadet minnekort"</string>
     <string name="ext_media_unmountable_notification_message" product="nosdcard" msgid="529021299294450667">"USB-lagring er skadet. Det kan være nødvendig å formatere enheten på nytt."</string>
     <string name="ext_media_unmountable_notification_message" product="default" msgid="6902531775948238989">"Minnekortet er skadet. Du må kanskje formatere det."</string>
-    <string name="ext_media_badremoval_notification_title" product="nosdcard" msgid="1661683031330951073">"USB-lagring fjernet uventet"</string>
+    <string name="ext_media_badremoval_notification_title" product="nosdcard" msgid="1661683031330951073">"USB-enhet fjernet uventet"</string>
     <string name="ext_media_badremoval_notification_title" product="default" msgid="6872152882604407837">"Minnekortet ble tatt ut uventet"</string>
-    <string name="ext_media_badremoval_notification_message" product="nosdcard" msgid="4329848819865594241">"Koble fra USB-lagring før enheten tas ut av maskinen for å unngå tap av data."</string>
+    <string name="ext_media_badremoval_notification_message" product="nosdcard" msgid="4329848819865594241">"Koble fra USB-enheten før du tar den ut for å unngå tap av data."</string>
     <string name="ext_media_badremoval_notification_message" product="default" msgid="7260183293747448241">"Avmonter minnekortet før det tas ut, for å unngå datatap."</string>
-    <string name="ext_media_safe_unmount_notification_title" product="nosdcard" msgid="3967973893270360230">"USB-lagring kan trygt fjernes"</string>
+    <string name="ext_media_safe_unmount_notification_title" product="nosdcard" msgid="3967973893270360230">"USB-enheten kan trygt fjernes"</string>
     <string name="ext_media_safe_unmount_notification_title" product="default" msgid="6729801130790616200">"Trygt å ta ut minnekort"</string>
     <string name="ext_media_safe_unmount_notification_message" product="nosdcard" msgid="6142195361606493530">"Det er trygt å ta ut enheten for USB-lagring."</string>
     <string name="ext_media_safe_unmount_notification_message" product="default" msgid="568841278138377604">"Det er trygt å ta ut minnekortet."</string>
diff --git a/core/res/res/values-nl/strings.xml b/core/res/res/values-nl/strings.xml
index 9c3478d..0a51eae 100644
--- a/core/res/res/values-nl/strings.xml
+++ b/core/res/res/values-nl/strings.xml
@@ -172,75 +172,75 @@
     <string name="permgroupdesc_storage" product="nosdcard" msgid="7442318502446874999">"Toegang krijgen tot USB-opslag."</string>
     <string name="permgroupdesc_storage" product="default" msgid="9203302214915355774">"Toegang tot de SD-kaart."</string>
     <string name="permlab_statusBar" msgid="7417192629601890791">"statusbalk uitschakelen of wijzigen"</string>
-    <string name="permdesc_statusBar" msgid="1365473595331989732">"Hiermee kan een toepassing de statusbalk uitschakelen of systeempictogrammen toevoegen en verwijderen."</string>
+    <string name="permdesc_statusBar" msgid="1365473595331989732">"Hiermee kan een app de statusbalk uitschakelen of systeempictogrammen toevoegen en verwijderen."</string>
     <string name="permlab_statusBarService" msgid="7247281911387931485">"statusbalk"</string>
-    <string name="permdesc_statusBarService" msgid="4097605867643520920">"Hiermee kan de toepassing de statusbalk zijn."</string>
+    <string name="permdesc_statusBarService" msgid="4097605867643520920">"Hiermee kan de app de statusbalk zijn."</string>
     <string name="permlab_expandStatusBar" msgid="1148198785937489264">"statusbalk uitvouwen/samenvouwen"</string>
-    <string name="permdesc_expandStatusBar" msgid="7088604400110768665">"Hiermee kan de toepassing de statusbalk uitvouwen of samenvouwen."</string>
+    <string name="permdesc_expandStatusBar" msgid="7088604400110768665">"Hiermee kan de app de statusbalk uitvouwen of samenvouwen."</string>
     <string name="permlab_processOutgoingCalls" msgid="1136262550878335980">"uitgaande oproepen onderscheppen"</string>
-    <string name="permdesc_processOutgoingCalls" msgid="2228988201852654461">"Hiermee kan een toepassing uitgaande oproepen verwerken en het nummer wijzigen dat wordt gebeld. Schadelijke toepassingen kunnen uitgaande oproepen bijhouden, omleiden of tegenhouden."</string>
+    <string name="permdesc_processOutgoingCalls" msgid="2228988201852654461">"Hiermee kan een app uitgaande oproepen verwerken en het nummer wijzigen dat wordt gebeld. Schadelijke apps kunnen uitgaande oproepen bijhouden, omleiden of tegenhouden."</string>
     <string name="permlab_receiveSms" msgid="2697628268086208535">"SMS ontvangen"</string>
-    <string name="permdesc_receiveSms" msgid="6298292335965966117">"Hiermee kan een toepassing SMS-berichten ontvangen en verwerken. Schadelijke toepassingen kunnen uw berichten bijhouden of deze verwijderen zonder dat u ze te zien krijgt."</string>
+    <string name="permdesc_receiveSms" msgid="6298292335965966117">"Hiermee kan een app SMS-berichten ontvangen en verwerken. Schadelijke apps kunnen uw berichten bijhouden of deze verwijderen zonder dat u ze te zien krijgt."</string>
     <string name="permlab_receiveMms" msgid="8894700916188083287">"MMS ontvangen"</string>
-    <string name="permdesc_receiveMms" msgid="4563346832000174373">"Hiermee kan een toepassing MMS-berichten ontvangen en verwerken. Schadelijke toepassingen kunnen uw berichten bijhouden of deze verwijderen zonder dat u ze te zien krijgt."</string>
+    <string name="permdesc_receiveMms" msgid="4563346832000174373">"Hiermee kan een app MMS-berichten ontvangen en verwerken. Schadelijke apps kunnen uw berichten bijhouden of deze verwijderen zonder dat u ze te zien krijgt."</string>
     <string name="permlab_sendSms" msgid="5600830612147671529">"SMS-berichten verzenden"</string>
-    <string name="permdesc_sendSms" msgid="1946540351763502120">"Hiermee kan de toepassing SMS-berichten verzenden. Schadelijke toepassingen kunnen u geld kosten door berichten te verzenden zonder uw toestemming."</string>
+    <string name="permdesc_sendSms" msgid="1946540351763502120">"Hiermee kan de app SMS-berichten verzenden. Schadelijke apps kunnen u geld kosten door berichten te verzenden zonder uw toestemming."</string>
     <string name="permlab_readSms" msgid="4085333708122372256">"SMS of MMS lezen"</string>
-    <string name="permdesc_readSms" msgid="3002170087197294591">"Hiermee kan een toepassing de op uw telefoon of SIM-kaart opgeslagen SMS-berichten lezen. Schadelijke toepassingen kunnen uw vertrouwelijke berichten mogelijk lezen."</string>
+    <string name="permdesc_readSms" msgid="3002170087197294591">"Hiermee kan een app de op uw telefoon of SIM-kaart opgeslagen SMS-berichten lezen. Schadelijke apps kunnen uw vertrouwelijke berichten mogelijk lezen."</string>
     <string name="permlab_writeSms" msgid="6881122575154940744">"SMS of MMS bewerken"</string>
-    <string name="permdesc_writeSms" msgid="6299398896177548095">"Hiermee kan een toepassing naar de op uw telefoon of SIM-kaart opgeslagen SMS-berichten schrijven. Schadelijke toepassingen kunnen uw berichten mogelijk verwijderen."</string>
+    <string name="permdesc_writeSms" msgid="6299398896177548095">"Hiermee kan een app naar de op uw telefoon of SIM-kaart opgeslagen SMS-berichten schrijven. Schadelijke apps kunnen uw berichten mogelijk verwijderen."</string>
     <string name="permlab_receiveWapPush" msgid="8258226427716551388">"WAP ontvangen"</string>
-    <string name="permdesc_receiveWapPush" msgid="5979623826128082171">"Hiermee kan een toepassing WAP-berichten ontvangen en verwerken. Schadelijke toepassingen kunnen uw berichten bijhouden of deze verwijderen zonder dat u ze te zien krijgt."</string>
+    <string name="permdesc_receiveWapPush" msgid="5979623826128082171">"Hiermee kan een app WAP-berichten ontvangen en verwerken. Schadelijke apps kunnen uw berichten bijhouden of deze verwijderen zonder dat u ze te zien krijgt."</string>
     <string name="permlab_getTasks" msgid="5005277531132573353">"actieve toepassingen ophalen"</string>
-    <string name="permdesc_getTasks" msgid="7048711358713443341">"Hiermee kan een toepassing informatie over huidige en recent uitgevoerde taken ophalen. Schadelijke toepassingen kunnen op deze manier mogelijk privé-informatie over andere toepassingen achterhalen."</string>
+    <string name="permdesc_getTasks" msgid="7048711358713443341">"Hiermee kan een app informatie over huidige en recent uitgevoerde taken ophalen. Schadelijke apps kunnen op deze manier mogelijk privé-informatie over andere apps achterhalen."</string>
     <string name="permlab_reorderTasks" msgid="5669588525059921549">"actieve toepassingen opnieuw indelen"</string>
-    <string name="permdesc_reorderTasks" msgid="126252774270522835">"Hiermee kan een toepassing taken naar de voor- en achtergrond verplaatsen. Schadelijke toepassingen kunnen zichzelf op de voorgrond plaatsen zonder dat u hier iets aan kunt doen."</string>
+    <string name="permdesc_reorderTasks" msgid="126252774270522835">"Hiermee kan een app taken naar de voor- en achtergrond verplaatsen. Schadelijke apps kunnen zichzelf op de voorgrond plaatsen zonder dat u hier iets aan kunt doen."</string>
     <string name="permlab_setDebugApp" msgid="4339730312925176742">"foutopsporing in toepassingen inschakelen"</string>
-    <string name="permdesc_setDebugApp" msgid="5584310661711990702">"Hiermee kan een toepassing de foutopsporing voor een andere toepassing inschakelen. Schadelijke toepassingen kunnen dit gebruiken om andere toepassingen af te sluiten."</string>
+    <string name="permdesc_setDebugApp" msgid="5584310661711990702">"Hiermee kan een app de foutopsporing voor een andere app inschakelen. Schadelijke apps kunnen dit gebruiken om andere apps af te sluiten."</string>
     <string name="permlab_changeConfiguration" msgid="8214475779521218295">"uw UI-instellingen wijzigen"</string>
-    <string name="permdesc_changeConfiguration" msgid="3465121501528064399">"Hiermee kan een toepassing de huidige configuratie, zoals de landinstelling of de algemene lettergrootte, wijzigen."</string>
+    <string name="permdesc_changeConfiguration" msgid="3465121501528064399">"Hiermee kan een app de huidige configuratie, zoals de landinstelling of de algemene lettergrootte, wijzigen."</string>
     <string name="permlab_enableCarMode" msgid="5684504058192921098">"automodus inschakelen"</string>
-    <string name="permdesc_enableCarMode" msgid="5673461159384850628">"Staat een toepassing toe de automodus in te schakelen."</string>
+    <string name="permdesc_enableCarMode" msgid="5673461159384850628">"Staat een app toe de automodus in te schakelen."</string>
     <string name="permlab_killBackgroundProcesses" msgid="8373714752793061963">"processen op de achtergrond beëindigen"</string>
-    <string name="permdesc_killBackgroundProcesses" msgid="2908829602869383753">"Staat een toepassing toe processen op de achtergrond te beëindigen, zelfs als er voldoende geheugen beschikbaar is."</string>
+    <string name="permdesc_killBackgroundProcesses" msgid="2908829602869383753">"Staat een app toe processen op de achtergrond te beëindigen, zelfs als er voldoende geheugen beschikbaar is."</string>
     <string name="permlab_forceStopPackages" msgid="1447830113260156236">"andere toepassingen gedwongen stoppen"</string>
-    <string name="permdesc_forceStopPackages" msgid="7263036616161367402">"Staat een toepassing toe andere toepassingen te stoppen."</string>
-    <string name="permlab_forceBack" msgid="1804196839880393631">"toepassing nu sluiten"</string>
-    <string name="permdesc_forceBack" msgid="6534109744159919013">"Hiermee kan een toepassing elke willekeurige activiteit die op de voorgrond wordt uitgevoerd, sluiten en naar de achtergrond verplaatsen. Nooit vereist voor normale toepassingen."</string>
+    <string name="permdesc_forceStopPackages" msgid="7263036616161367402">"Staat een app toe andere apps te stoppen."</string>
+    <string name="permlab_forceBack" msgid="1804196839880393631">"app nu sluiten"</string>
+    <string name="permdesc_forceBack" msgid="6534109744159919013">"Hiermee kan een app elke willekeurige activiteit die op de voorgrond wordt uitgevoerd, sluiten en naar de achtergrond verplaatsen. Nooit vereist voor normale apps."</string>
     <string name="permlab_dump" msgid="1681799862438954752">"interne systeemstatus ophalen"</string>
-    <string name="permdesc_dump" msgid="2198776174276275220">"Hiermee kan een toepassing de interne status van het systeem ophalen. Schadelijke toepassingen kunnen privé- of veiligheidsgegevens ophalen die ze normaal niet nodig hebben."</string>
+    <string name="permdesc_dump" msgid="2198776174276275220">"Hiermee kan een app de interne status van het systeem ophalen. Schadelijke apps kunnen privé- of veiligheidsgegevens ophalen die ze normaal niet nodig hebben."</string>
     <string name="permlab_shutdown" msgid="7185747824038909016">"gedeeltelijke uitschakeling"</string>
     <string name="permdesc_shutdown" msgid="7046500838746291775">"Hiermee wordt activiteitenbeheer uitgeschakeld. Er wordt geen volledige uitschakeling uitgevoerd."</string>
     <string name="permlab_stopAppSwitches" msgid="4138608610717425573">"schakelen tussen toepassingen voorkomen"</string>
-    <string name="permdesc_stopAppSwitches" msgid="3857886086919033794">"Hiermee wordt voorkomen dat de gebruiker overschakelt naar een andere toepassing."</string>
+    <string name="permdesc_stopAppSwitches" msgid="3857886086919033794">"Hiermee wordt voorkomen dat de gebruiker overschakelt naar een andere app."</string>
     <string name="permlab_runSetActivityWatcher" msgid="7811586187574696296">"alle startende toepassingen bijhouden en beheren"</string>
-    <string name="permdesc_runSetActivityWatcher" msgid="3228701938345388092">"Hiermee kan een toepassing de manier waarop het systeem activiteiten start, bijhouden en beheren. Schadelijke toepassingen kunnen het systeem volledig in gevaar brengen. Deze machtiging is alleen voor ontwikkeling vereist, nooit voor normaal telefoongebruik."</string>
+    <string name="permdesc_runSetActivityWatcher" msgid="3228701938345388092">"Hiermee kan een app de manier waarop het systeem activiteiten start, bijhouden en beheren. Schadelijke apps kunnen het systeem volledig in gevaar brengen. Deze machtiging is alleen voor ontwikkeling vereist, nooit voor normaal telefoongebruik."</string>
     <string name="permlab_broadcastPackageRemoved" msgid="2576333434893532475">"melding verzenden dat pakket is verwijderd"</string>
-    <string name="permdesc_broadcastPackageRemoved" msgid="3453286591439891260">"Hiermee kan een toepassing een melding verzenden dat een toepassingspakket is verwijderd. Schadelijke toepassingen kunnen hiervan gebruik maken om alle andere actieve toepassingen af te sluiten."</string>
+    <string name="permdesc_broadcastPackageRemoved" msgid="3453286591439891260">"Hiermee kan een app een melding verzenden dat een applicatiepakket (APK) is verwijderd. Schadelijke apps kunnen hiervan gebruik maken om alle andere actieve apps af te sluiten."</string>
     <string name="permlab_broadcastSmsReceived" msgid="5689095009030336593">"melding over ontvangen SMS-bericht verzenden"</string>
-    <string name="permdesc_broadcastSmsReceived" msgid="9122419277306740155">"Hiermee kan een toepassing een melding verzenden dat een SMS-bericht is ontvangen. Schadelijke toepassingen kunnen hiervan gebruik maken om inkomende SMS-berichten te vervalsen."</string>
+    <string name="permdesc_broadcastSmsReceived" msgid="9122419277306740155">"Hiermee kan een app een melding verzenden dat een SMS-bericht is ontvangen. Schadelijke apps kunnen hiervan gebruik maken om inkomende SMS-berichten te vervalsen."</string>
     <string name="permlab_broadcastWapPush" msgid="3145347413028582371">"melding over ontvangen WAP-PUSH-bericht verzenden"</string>
-    <string name="permdesc_broadcastWapPush" msgid="3955303669461378091">"Hiermee kan een toepassing een melding verzenden dat een WAP PUSH-bericht is ontvangen. Schadelijke toepassingen kunnen hiervan gebruik maken om een valse MMS-ontvangst te melden of de inhoud van willekeurige webpagina\'s door schadelijke varianten te vervangen."</string>
+    <string name="permdesc_broadcastWapPush" msgid="3955303669461378091">"Hiermee kan een app een melding verzenden dat een WAP PUSH-bericht is ontvangen. Schadelijke apps kunnen hiervan gebruik maken om een valse MMS-ontvangst te melden of de inhoud van willekeurige webpagina\'s door schadelijke varianten te vervangen."</string>
     <string name="permlab_setProcessLimit" msgid="2451873664363662666">"aantal actieve processen beperken"</string>
-    <string name="permdesc_setProcessLimit" msgid="7824786028557379539">"Hiermee kan een toepassing het maximum aantal processen bepalen dat wordt uitgevoerd. Nooit vereist voor normale toepassingen."</string>
+    <string name="permdesc_setProcessLimit" msgid="7824786028557379539">"Hiermee kan een app het maximum aantal processen bepalen dat wordt uitgevoerd. Nooit vereist voor normale apps."</string>
     <string name="permlab_setAlwaysFinish" msgid="5342837862439543783">"alle achtergrondtoepassingen sluiten"</string>
-    <string name="permdesc_setAlwaysFinish" msgid="8773936403987091620">"Hiermee kan een toepassing bepalen of activiteiten altijd worden afgesloten zodra deze naar de achtergrond gaan. Nooit nodig voor normale toepassingen."</string>
+    <string name="permdesc_setAlwaysFinish" msgid="8773936403987091620">"Hiermee kan een app bepalen of activiteiten altijd worden afgesloten zodra deze naar de achtergrond gaan. Nooit nodig voor normale apps."</string>
     <string name="permlab_batteryStats" msgid="7863923071360031652">"accustatistieken aanpassen"</string>
     <string name="permdesc_batteryStats" msgid="5847319823772230560">"Hiermee kunnen verzamelde accustatistieken worden gewijzigd. Niet voor gebruik door normale toepassingen."</string>
     <string name="permlab_backup" msgid="470013022865453920">"systeemback-up en -herstel beheren"</string>
-    <string name="permdesc_backup" msgid="4837493065154256525">"Hiermee kan de toepassing het mechanisme voor systeemback-up en -herstel beheren. Niet voor gebruik door normale toepassingen."</string>
+    <string name="permdesc_backup" msgid="4837493065154256525">"Hiermee kan de app het mechanisme voor systeemback-up en -herstel beheren. Niet voor gebruik door normale apps."</string>
     <string name="permlab_internalSystemWindow" msgid="2148563628140193231">"niet-geautoriseerde vensters weergeven"</string>
     <string name="permdesc_internalSystemWindow" msgid="5895082268284998469">"Hiermee kunnen vensters worden gemaakt die door de interne systeemgebruikersinterface worden gebruikt. Niet voor gebruik door normale toepassingen."</string>
     <string name="permlab_systemAlertWindow" msgid="3372321942941168324">"waarschuwingen op systeemniveau weergeven"</string>
-    <string name="permdesc_systemAlertWindow" msgid="5109622689323490558">"Hiermee kan een toepassing systeemwaarschuwingen weergeven. Schadelijke toepassingen kunnen op deze manier het hele scherm van de telefoon overnemen."</string>
+    <string name="permdesc_systemAlertWindow" msgid="5109622689323490558">"Hiermee kan een app systeemwaarschuwingen weergeven. Schadelijke apps kunnen op deze manier het hele scherm van de telefoon overnemen."</string>
     <string name="permlab_setAnimationScale" msgid="2805103241153907174">"algemene animatiesnelheid wijzigen"</string>
-    <string name="permdesc_setAnimationScale" msgid="7181522138912391988">"Hiermee kan een toepassing op elk gewenst moment de algemene animatiesnelheid wijzigen (snellere of tragere animaties)."</string>
+    <string name="permdesc_setAnimationScale" msgid="7181522138912391988">"Hiermee kan een app op elk gewenst moment de algemene animatiesnelheid wijzigen (snellere of tragere animaties)."</string>
     <string name="permlab_manageAppTokens" msgid="17124341698093865">"toepassingstokens beheren"</string>
     <string name="permdesc_manageAppTokens" msgid="977127907524195988">"Hiermee kunnen toepassingen hun eigen tokens maken en beheren, waarbij de normale Z-volgorde wordt overgeslagen. Nooit nodig voor normale toepassingen."</string>
     <string name="permlab_injectEvents" msgid="1378746584023586600">"drukken op toetsen en bedieningselementen"</string>
-    <string name="permdesc_injectEvents" msgid="3946098050410874715">"Hiermee kan een toepassing zijn eigen invoergebeurtenissen (toetsaanslagen, enzovoort) aan andere toepassingen doorgeven. Schadelijke toepassingen kunnen dit gebruiken om de telefoon over te nemen."</string>
+    <string name="permdesc_injectEvents" msgid="3946098050410874715">"Hiermee kan een app zijn de invoergebeurtenissen (toetsaanslagen, enzovoort) aan andere apps doorgeven. Schadelijke apps kunnen dit gebruiken om de telefoon over te nemen."</string>
     <string name="permlab_readInputState" msgid="469428900041249234">"uw invoer en acties vastleggen"</string>
-    <string name="permdesc_readInputState" msgid="5132879321450325445">"Hiermee kan een toepassing uw toetsaanslagen registreren, zelfs tijdens de interactie met een andere toepassing (zoals de invoer van een wachtwoord). Nooit vereist voor normale toepassingen."</string>
+    <string name="permdesc_readInputState" msgid="5132879321450325445">"Hiermee kan een app uw toetsaanslagen registreren, zelfs tijdens de interactie met een andere app (zoals de invoer van een wachtwoord). Nooit vereist voor normale apps."</string>
     <string name="permlab_bindInputMethod" msgid="3360064620230515776">"verbinden aan een invoermethode"</string>
     <string name="permdesc_bindInputMethod" msgid="3734838321027317228">"Hiermee staat u de houder toe zich te verbinden met de hoofdinterface van een invoermethode. Nooit vereist voor normale toepassingen."</string>
     <string name="permlab_bindWallpaper" msgid="8716400279937856462">"verbinden met een achtergrond"</string>
@@ -248,51 +248,51 @@
     <string name="permlab_bindDeviceAdmin" msgid="8704986163711455010">"interactie met apparaatbeheer"</string>
     <string name="permdesc_bindDeviceAdmin" msgid="8714424333082216979">"Staat de houder toe intenties te verzenden naar een apparaatbeheerder. Nooit vereist voor normale toepassingen."</string>
     <string name="permlab_setOrientation" msgid="3365947717163866844">"schermstand wijzigen"</string>
-    <string name="permdesc_setOrientation" msgid="6335814461615851863">"Hiermee kan een toepassing op elk gewenst moment de oriëntatie van het scherm wijzigen. Nooit vereist voor normale toepassingen."</string>
+    <string name="permdesc_setOrientation" msgid="6335814461615851863">"Hiermee kan een app op elk gewenst moment de oriëntatie van het scherm wijzigen. Nooit vereist voor normale apps."</string>
     <string name="permlab_signalPersistentProcesses" msgid="4255467255488653854">"Linux-signalen verzenden naar toepassingen"</string>
-    <string name="permdesc_signalPersistentProcesses" msgid="3565530463215015289">"Hiermee kan de toepassing ervoor zorgen dat het geleverde signaal wordt verzonden naar alle persistente processen."</string>
-    <string name="permlab_persistentActivity" msgid="8659652042401085862">"toepassing altijd laten uitvoeren"</string>
-    <string name="permdesc_persistentActivity" msgid="5037199778265006008">"Hiermee kan een toepassing delen van zichzelf persistent maken, zodat het systeem dat deel niet voor andere toepassingen kan gebruiken."</string>
+    <string name="permdesc_signalPersistentProcesses" msgid="3565530463215015289">"Hiermee kan de app ervoor zorgen dat het geleverde signaal wordt verzonden naar alle persistente processen."</string>
+    <string name="permlab_persistentActivity" msgid="8659652042401085862">"app altijd laten uitvoeren"</string>
+    <string name="permdesc_persistentActivity" msgid="5037199778265006008">"Hiermee kan een app delen van zichzelf persistent maken, zodat het systeem dat deel niet voor andere apps kan gebruiken."</string>
     <string name="permlab_deletePackages" msgid="3343439331576348805">"toepassingen verwijderen"</string>
-    <string name="permdesc_deletePackages" msgid="3634943677518723314">"Hiermee kan een toepassing Android-pakketten verwijderen. Schadelijke toepassingen kunnen dit gebruiken om belangrijke toepassingen te verwijderen."</string>
+    <string name="permdesc_deletePackages" msgid="3634943677518723314">"Hiermee kan een app Android-pakketten verwijderen. Schadelijke apps kunnen dit gebruiken om belangrijke apps te verwijderen."</string>
     <string name="permlab_clearAppUserData" msgid="2192134353540277878">"gegevens van andere toepassingen verwijderen"</string>
-    <string name="permdesc_clearAppUserData" msgid="7546345080434325456">"Hiermee kan een toepassing gebruikersgegevens wissen."</string>
+    <string name="permdesc_clearAppUserData" msgid="7546345080434325456">"Hiermee kan een app gebruikersgegevens wissen."</string>
     <string name="permlab_deleteCacheFiles" msgid="1518556602634276725">"caches van andere toepassingen verwijderen"</string>
-    <string name="permdesc_deleteCacheFiles" msgid="2283074077168165971">"Hiermee kan een toepassing cachebestanden verwijderen."</string>
-    <string name="permlab_getPackageSize" msgid="4799785352306641460">"opslagruimte van toepassing bepalen"</string>
-    <string name="permdesc_getPackageSize" msgid="5557253039670753437">"Hiermee kan een toepassing de bijbehorende code, gegevens en cachegrootten ophalen."</string>
+    <string name="permdesc_deleteCacheFiles" msgid="2283074077168165971">"Hiermee kan een app cachebestanden verwijderen."</string>
+    <string name="permlab_getPackageSize" msgid="4799785352306641460">"opslagruimte van app bepalen"</string>
+    <string name="permdesc_getPackageSize" msgid="5557253039670753437">"Hiermee kan een app de bijbehorende code, gegevens en cachegrootten ophalen."</string>
     <string name="permlab_installPackages" msgid="335800214119051089">"toepassingen rechtstreeks installeren"</string>
-    <string name="permdesc_installPackages" msgid="526669220850066132">"Hiermee kan een toepassing nieuwe of bijgewerkte Android-pakketten installeren. Schadelijke toepassingen kunnen hiervan gebruik maken om nieuwe toepassingen met willekeurig krachtige machtigingen toe te voegen."</string>
-    <string name="permlab_clearAppCache" msgid="4747698311163766540">"alle cachegegevens van toepassing verwijderen"</string>
-    <string name="permdesc_clearAppCache" msgid="7740465694193671402">"Hiermee kan een toepassing opslagruimte op de telefoon vrij maken door bestanden te verwijderen uit de cachemap van de toepassing. De toegang is doorgaans beperkt tot het systeemproces."</string>
+    <string name="permdesc_installPackages" msgid="526669220850066132">"Hiermee kan een app nieuwe of bijgewerkte Android-pakketten installeren. Schadelijke apps kunnen hiervan gebruik maken om nieuwe apps met willekeurig krachtige machtigingen toe te voegen."</string>
+    <string name="permlab_clearAppCache" msgid="4747698311163766540">"alle cachegegevens van app verwijderen"</string>
+    <string name="permdesc_clearAppCache" msgid="7740465694193671402">"Hiermee kan een app opslagruimte op de telefoon vrij maken door bestanden te verwijderen uit de cachemap van de app. De toegang is doorgaans beperkt tot het systeemproces."</string>
     <string name="permlab_movePackage" msgid="728454979946503926">"Toepassingsbronnen verplaatsen"</string>
-    <string name="permdesc_movePackage" msgid="6323049291923925277">"Een toepassing toestaan toepassingsbronnen te verplaatsen van interne naar externe media en omgekeerd."</string>
+    <string name="permdesc_movePackage" msgid="6323049291923925277">"Een app toestaan app-bronnen te verplaatsen van interne naar externe media en omgekeerd."</string>
     <string name="permlab_readLogs" msgid="6615778543198967614">"gevoelige logbestandsgegevens lezen"</string>
-    <string name="permdesc_readLogs" msgid="8896449437464867766">"Hiermee kan een toepassing de verschillende logbestanden van het systeem lezen. De toepassing kan op deze manier algemene informatie achterhalen over uw telefoongebruik, mogelijk inclusief persoonlijke of privé-informatie."</string>
+    <string name="permdesc_readLogs" msgid="8896449437464867766">"Hiermee kan een app de verschillende logbestanden van het systeem lezen. De app kan op deze manier algemene informatie achterhalen over uw telefoongebruik, mogelijk inclusief persoonlijke of privé-informatie."</string>
     <string name="permlab_diagnostic" msgid="8076743953908000342">"lezen/schrijven naar bronnen van diag"</string>
-    <string name="permdesc_diagnostic" msgid="3121238373951637049">"Hiermee kan een toepassing lezen en schrijven naar elke bron die hoort bij de diagnostische groep, zoals bestanden in /dev. Hierdoor kan de systeemstabiliteit en -veiligheid worden beïnvloed. Dit mag ALLEEN worden gebruikt voor hardwarespecifieke diagnostiek door de fabrikant of operator."</string>
+    <string name="permdesc_diagnostic" msgid="3121238373951637049">"Hiermee kan een app lezen en schrijven naar elke bron die hoort bij de diagnostische groep, zoals bestanden in /dev. Hierdoor kan de systeemstabiliteit en -veiligheid worden beïnvloed. Dit mag ALLEEN worden gebruikt voor hardwarespecifieke diagnostiek door de fabrikant of operator."</string>
     <string name="permlab_changeComponentState" msgid="79425198834329406">"toepassingscomponenten in- of uitschakelen"</string>
-    <string name="permdesc_changeComponentState" msgid="4569107043246700630">"Hiermee kan een toepassing bepalen of een component van een andere toepassing is ingeschakeld. Schadelijke toepassingen kunnen hiervan gebruik maken om belangrijke telefoonfuncties uit te schakelen. Een machtiging moet zorgvuldig worden overwogen, aangezien toepassingscomponenten onbruikbaar, inconsistent of instabiel kunnen worden."</string>
+    <string name="permdesc_changeComponentState" msgid="4569107043246700630">"Hiermee kan een app bepalen of een component van een andere app is ingeschakeld. Schadelijke apps kunnen hiervan gebruik maken om belangrijke telefoonfuncties uit te schakelen. Een machtiging moet zorgvuldig worden overwogen, aangezien app-componenten onbruikbaar, inconsistent of instabiel kunnen worden."</string>
     <string name="permlab_setPreferredApplications" msgid="3393305202145172005">"voorkeurstoepassingen instellen"</string>
-    <string name="permdesc_setPreferredApplications" msgid="760008293501937546">"Hiermee kan een toepassing uw voorkeurstoepassingen wijzigen. Schadelijke toepassingen kunnen op deze manier de actieve toepassingen zonder uw medeweten wijzigen en uw bestaande toepassingen doorzoeken om privégegevens van u te verzamelen."</string>
+    <string name="permdesc_setPreferredApplications" msgid="760008293501937546">"Hiermee kan een app uw voorkeurs-apps wijzigen. Schadelijke apps kunnen op deze manier de actieve apps zonder uw medeweten wijzigen en uw bestaande apps doorzoeken om privégegevens van u te verzamelen."</string>
     <string name="permlab_writeSettings" msgid="1365523497395143704">"algemene systeeminstellingen wijzigen"</string>
-    <string name="permdesc_writeSettings" msgid="838789419871034696">"Hiermee kan een toepassing de systeeminstellingen wijzigen. Schadelijke toepassingen kunnen hiermee uw systeemconfiguratie beschadigen."</string>
+    <string name="permdesc_writeSettings" msgid="838789419871034696">"Hiermee kan een app de systeeminstellingen wijzigen. Schadelijke apps kunnen hiermee uw systeemconfiguratie beschadigen."</string>
     <string name="permlab_writeSecureSettings" msgid="204676251876718288">"beveiligde systeeminstellingen wijzigen"</string>
-    <string name="permdesc_writeSecureSettings" msgid="5497873143539034724">"Hiermee kan een toepassing beveiligde systeeminstellingen wijzigen. Niet voor gebruik door normale toepassingen."</string>
+    <string name="permdesc_writeSecureSettings" msgid="5497873143539034724">"Hiermee kan een app beveiligde systeeminstellingen wijzigen. Niet voor gebruik door normale apps."</string>
     <string name="permlab_writeGservices" msgid="2149426664226152185">"de Google-serviceskaart wijzigen"</string>
-    <string name="permdesc_writeGservices" msgid="6602362746516676175">"Hiermee kan een toepassing de Google-serviceskaart wijzigen. Niet voor gebruik door normale toepassingen."</string>
+    <string name="permdesc_writeGservices" msgid="6602362746516676175">"Hiermee kan een app de Google-serviceskaart wijzigen. Niet voor gebruik door normale apps."</string>
     <string name="permlab_receiveBootCompleted" msgid="7776779842866993377">"automatisch starten bij opstarten"</string>
-    <string name="permdesc_receiveBootCompleted" msgid="698336728415008796">"Hiermee kan een toepassing zichzelf starten zodra het systeem klaar is met opstarten. Hierdoor kan het langer duren voordat de telefoon is opgestart en kan de toepassing de telefoonprocessen vertragen door altijd actief te zijn."</string>
+    <string name="permdesc_receiveBootCompleted" msgid="698336728415008796">"Hiermee kan een app zichzelf starten zodra het systeem klaar is met opstarten. Hierdoor kan het langer duren voordat de telefoon is opgestart en kan de app de telefoonprocessen vertragen door altijd actief te zijn."</string>
     <string name="permlab_broadcastSticky" msgid="7919126372606881614">"sticky broadcast verzenden"</string>
-    <string name="permdesc_broadcastSticky" msgid="1920045289234052219">"Hiermee kan een toepassing sticky broadcasts verzenden die achterblijven als de broadcast eindigt. Schadelijke toepassingen kunnen hiermee de telefoon traag of instabiel maken door ervoor te zorgen dat er te veel geheugenruimte wordt gebruikt."</string>
+    <string name="permdesc_broadcastSticky" msgid="1920045289234052219">"Hiermee kan een app sticky broadcasts verzenden die achterblijven als de broadcast eindigt. Schadelijke apps kunnen hiermee de telefoon traag of instabiel maken door ervoor te zorgen dat er te veel geheugenruimte wordt gebruikt."</string>
     <string name="permlab_readContacts" msgid="6219652189510218240">"contactgegevens lezen"</string>
-    <string name="permdesc_readContacts" msgid="3371591512896545975">"Hiermee kan een toepassing alle contactgegevens (adresgegevens) zien die op uw telefoon zijn opgeslagen. Schadelijke toepassingen kunnen hiervan gebruik maken om uw gegevens te verzenden naar andere personen."</string>
+    <string name="permdesc_readContacts" msgid="3371591512896545975">"Hiermee kan een app alle contactgegevens (adresgegevens) zien die op uw telefoon zijn opgeslagen. Schadelijke apps kunnen hiervan gebruik maken om uw gegevens te verzenden naar andere personen."</string>
     <string name="permlab_writeContacts" msgid="644616215860933284">"contactgegevens schrijven"</string>
-    <string name="permdesc_writeContacts" msgid="3924383579108183601">"Hiermee kan een toepassing de op uw telefoon opgeslagen contactgegevens (adresgegevens) wijzigen. Schadelijke toepassingen kunnen hiermee uw contactgegevens verwijderen of wijzigen."</string>
+    <string name="permdesc_writeContacts" msgid="3924383579108183601">"Hiermee kan een app de op uw telefoon opgeslagen contactgegevens (adresgegevens) wijzigen. Schadelijke apps kunnen hiermee uw contactgegevens verwijderen of wijzigen."</string>
     <string name="permlab_readCalendar" msgid="6898987798303840534">"agendagebeurtenissen lezen"</string>
-    <string name="permdesc_readCalendar" msgid="5533029139652095734">"Hiermee kan een toepassing alle agendagebeurtenissen lezen die zijn opgeslagen op uw telefoon. Schadelijke toepassingen kunnen hiervan gebruik maken om uw agendagebeurtenissen te verzenden naar andere personen."</string>
+    <string name="permdesc_readCalendar" msgid="5533029139652095734">"Hiermee kan een app alle agendagebeurtenissen lezen die zijn opgeslagen op uw telefoon. Schadelijke apps kunnen hiervan gebruik maken om uw agendagebeurtenissen te verzenden naar andere personen."</string>
     <string name="permlab_writeCalendar" msgid="3894879352594904361">"agendagebeurtenissen toevoegen of aanpassen en e-mail verzenden naar gasten"</string>
-    <string name="permdesc_writeCalendar" msgid="2988871373544154221">"Een toepassing toestaan gebeurtenissen aan uw agenda toe te voegen of te wijzigen, wat inhoudt dat er e-mails kunnen worden verzonden naar gasten. Schadelijke toepassingen kunnen dit gebruiken om uw agendagebeurtenissen te wissen of aan te passen of om e-mail naar gasten te verzenden."</string>
+    <string name="permdesc_writeCalendar" msgid="2988871373544154221">"Een app toestaan gebeurtenissen aan uw agenda toe te voegen of te wijzigen, wat inhoudt dat er e-mails kunnen worden verzonden naar gasten. Schadelijke apps kunnen dit gebruiken om uw agendagebeurtenissen te wissen of aan te passen of om e-mail naar gasten te verzenden."</string>
     <string name="permlab_accessMockLocation" msgid="8688334974036823330">"neplocatiebronnen voor test"</string>
     <string name="permdesc_accessMockLocation" msgid="7648286063459727252">"Neplocatiebronnen voor testdoeleinden maken. Schadelijke toepassingen kunnen dit gebruiken om de locatie en/of status te overschrijven die door de echte locatiebronnen wordt aangegeven, zoals GPS of netwerkaanbieders."</string>
     <string name="permlab_accessLocationExtraCommands" msgid="2836308076720553837">"toegang tot extra opdrachten van locatieaanbieder"</string>
@@ -304,131 +304,135 @@
     <string name="permlab_accessCoarseLocation" msgid="4642255009181975828">"globale (netwerkgebaseerde) locatie"</string>
     <string name="permdesc_accessCoarseLocation" msgid="8235655958070862293">"Toegang tot globale locatiebronnen, zoals de mobiele netwerkdatabase om een globale telefoonlocatie te bepalen, indien beschikbaar. Schadelijke toepassingen kunnen hiervan gebruik maken om bij benadering te bepalen waar u zich bevindt."</string>
     <string name="permlab_accessSurfaceFlinger" msgid="2363969641792388947">"toegang tot SurfaceFlinger"</string>
-    <string name="permdesc_accessSurfaceFlinger" msgid="6805241830020733025">"Hiermee kan een toepassing SurfaceFlinger-functies op laag niveau gebruiken."</string>
+    <string name="permdesc_accessSurfaceFlinger" msgid="6805241830020733025">"Hiermee kan een app SurfaceFlinger-functies op laag niveau gebruiken."</string>
     <string name="permlab_readFrameBuffer" msgid="6690504248178498136">"framebuffer lezen"</string>
-    <string name="permdesc_readFrameBuffer" msgid="7530020370469942528">"Hiermee kan een toepassing de inhoud van de framebuffer lezen."</string>
+    <string name="permdesc_readFrameBuffer" msgid="7530020370469942528">"Hiermee kan een app de inhoud van de framebuffer lezen."</string>
     <string name="permlab_modifyAudioSettings" msgid="6095859937069146086">"uw audio-instellingen wijzigen"</string>
-    <string name="permdesc_modifyAudioSettings" msgid="5793461287365991922">"Hiermee kan een toepassing de algemene audio-instellingen, zoals volume en omleiding, wijzigen."</string>
+    <string name="permdesc_modifyAudioSettings" msgid="5793461287365991922">"Hiermee kan een app de algemene audio-instellingen, zoals volume en omleiding, wijzigen."</string>
     <string name="permlab_recordAudio" msgid="3876049771427466323">"audio opnemen"</string>
-    <string name="permdesc_recordAudio" msgid="6493228261176552356">"Hiermee krijgt de toepassing toegang tot het audio-opnamepad."</string>
+    <string name="permdesc_recordAudio" msgid="6493228261176552356">"Hiermee krijgt de app toegang tot het audio-opnamepad."</string>
     <string name="permlab_camera" msgid="3616391919559751192">"foto\'s en video\'s maken"</string>
-    <string name="permdesc_camera" msgid="6004878235852154239">"Hiermee kan een toepassing foto\'s en video\'s maken met de camera. De toepassing kan op deze manier op elk gewenste moment beelden verzamelen van wat de camera ziet."</string>
+    <string name="permdesc_camera" msgid="6004878235852154239">"Hiermee kan een app foto\'s en video\'s maken met de camera. De app kan op deze manier op elk gewenste moment beelden verzamelen van wat de camera ziet."</string>
     <string name="permlab_brick" msgid="8337817093326370537">"telefoon permanent uitschakelen"</string>
-    <string name="permdesc_brick" msgid="5569526552607599221">"Hiermee kan de toepassing de telefoon permanent uitschakelen. Dit is erg gevaarlijk."</string>
+    <string name="permdesc_brick" msgid="5569526552607599221">"Hiermee kan de app de telefoon permanent uitschakelen. Dit is erg gevaarlijk."</string>
     <string name="permlab_reboot" msgid="2898560872462638242">"telefoon nu opnieuw opstarten"</string>
-    <string name="permdesc_reboot" msgid="7914933292815491782">"Hiermee kan de toepassing de telefoon nu opnieuw opstarten."</string>
+    <string name="permdesc_reboot" msgid="7914933292815491782">"Hiermee kan de app de telefoon nu opnieuw opstarten."</string>
     <string name="permlab_mount_unmount_filesystems" msgid="1761023272170956541">"bestandssystemen koppelen en ontkoppelen"</string>
-    <string name="permdesc_mount_unmount_filesystems" msgid="6253263792535859767">"Hiermee kan de toepassing bestandssystemen koppelen en ontkoppelen voor verwisselbare opslagruimte."</string>
+    <string name="permdesc_mount_unmount_filesystems" msgid="6253263792535859767">"Hiermee kan de app bestandssystemen koppelen en ontkoppelen voor verwisselbare opslagruimte."</string>
     <string name="permlab_mount_format_filesystems" msgid="5523285143576718981">"externe opslag formatteren"</string>
-    <string name="permdesc_mount_format_filesystems" msgid="574060044906047386">"Hiermee kan de toepassing de externe opslag formatteren."</string>
+    <string name="permdesc_mount_format_filesystems" msgid="574060044906047386">"Hiermee kan de app de externe opslag formatteren."</string>
     <string name="permlab_asec_access" msgid="3411338632002193846">"informatie over de interne opslag verkrijgen"</string>
-    <string name="permdesc_asec_access" msgid="8820326551687285439">"Hiermee kan de toepassing informatie over de interne opslag verkrijgen."</string>
+    <string name="permdesc_asec_access" msgid="8820326551687285439">"Hiermee kan de app informatie over de interne opslag verkrijgen."</string>
     <string name="permlab_asec_create" msgid="6414757234789336327">"interne opslag maken"</string>
-    <string name="permdesc_asec_create" msgid="2621346764995731250">"Hiermee kan de toepassing interne opslag maken."</string>
+    <string name="permdesc_asec_create" msgid="2621346764995731250">"Hiermee kan de app interne opslag maken."</string>
     <string name="permlab_asec_destroy" msgid="526928328301618022">"interne opslag vernietigen"</string>
-    <string name="permdesc_asec_destroy" msgid="2746706889208066256">"Hiermee kan de toepassing de interne opslag vernietigen."</string>
+    <string name="permdesc_asec_destroy" msgid="2746706889208066256">"Hiermee kan de app de interne opslag vernietigen."</string>
     <string name="permlab_asec_mount_unmount" msgid="2456287623689029744">"interne opslag koppelen/ontkoppelen"</string>
-    <string name="permdesc_asec_mount_unmount" msgid="5934375590189368200">"Hiermee kan de toepassing de interne opslag koppelen/ontkoppelen."</string>
+    <string name="permdesc_asec_mount_unmount" msgid="5934375590189368200">"Hiermee kan de app de interne opslag koppelen/ontkoppelen."</string>
     <string name="permlab_asec_rename" msgid="7496633954080472417">"naam van interne opslag wijzigen"</string>
-    <string name="permdesc_asec_rename" msgid="2152829985238876790">"Hiermee kan de toepassing de naam van de interne opslag wijzigen."</string>
+    <string name="permdesc_asec_rename" msgid="2152829985238876790">"Hiermee kan de app de naam van de interne opslag wijzigen."</string>
     <string name="permlab_vibrate" msgid="7768356019980849603">"trilstand beheren"</string>
-    <string name="permdesc_vibrate" msgid="2886677177257789187">"Hiermee kan de toepassing de trilstand beheren."</string>
+    <string name="permdesc_vibrate" msgid="2886677177257789187">"Hiermee kan de app de trilstand beheren."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"zaklamp bedienen"</string>
-    <string name="permdesc_flashlight" msgid="6433045942283802309">"Hiermee kan de toepassing de zaklamp bedienen."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"toegang krijgen tot USB-apparaten"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Hiermee kan de toepassing toegang krijgen tot USB-apparaten."</string>
+    <string name="permdesc_flashlight" msgid="6433045942283802309">"Hiermee kan de app de zaklamp bedienen."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"voorkeuren en rechten voor USB-apparaten beheren"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Hiermee kan de app voorkeuren en rechten voor USB-apparaten beheren."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"hardware testen"</string>
-    <string name="permdesc_hardware_test" msgid="3668894686500081699">"Hiermee kan de toepassing verschillende randapparaten beheren om de hardware te testen."</string>
+    <string name="permdesc_hardware_test" msgid="3668894686500081699">"Hiermee kan de app verschillende randapparaten beheren om de hardware te testen."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"telefoonnummers rechtstreeks bellen"</string>
-    <string name="permdesc_callPhone" msgid="3369867353692722456">"Hiermee kan de toepassing telefoonnummers bellen zonder uw tussenkomst. Door schadelijke toepassingen kunnen onverwachte oproepen op uw telefoonrekening verschijnen. De toepassing kan hiermee geen alarmnummers bellen."</string>
+    <string name="permdesc_callPhone" msgid="3369867353692722456">"Hiermee kan de app telefoonnummers bellen zonder uw tussenkomst. Door schadelijke apps kunnen onverwachte oproepen op uw telefoonrekening verschijnen. De app kan hiermee geen alarmnummers bellen."</string>
     <string name="permlab_callPrivileged" msgid="4198349211108497879">"alle telefoonnummers rechtstreeks bellen"</string>
-    <string name="permdesc_callPrivileged" msgid="244405067160028452">"Hiermee kan een toepassing elk telefoonnummer, inclusief alarmnummers, bellen zonder uw tussenkomst. Schadelijke toepassingen kunnen onnodige en illegale oproepen uitvoeren naar alarmdiensten."</string>
+    <string name="permdesc_callPrivileged" msgid="244405067160028452">"Hiermee kan een app elk telefoonnummer, inclusief alarmnummers, bellen zonder uw tussenkomst. Schadelijke apps kunnen onnodige en illegale oproepen uitvoeren naar alarmdiensten."</string>
     <string name="permlab_performCdmaProvisioning" msgid="5604848095315421425">"meteen starten met CDMA-telefooninstelling"</string>
-    <string name="permdesc_performCdmaProvisioning" msgid="6457447676108355905">"Hiermee kan de toepassing starten met CDMA-provisioning. Schadelijke applicaties kunnen de CDMA-provisioning onnodig starten"</string>
+    <string name="permdesc_performCdmaProvisioning" msgid="6457447676108355905">"Hiermee kan de app starten met CDMA-provisioning. Schadelijke apps kunnen de CDMA-provisioning onnodig starten"</string>
     <string name="permlab_locationUpdates" msgid="7785408253364335740">"meldingen over locatie-updates beheren"</string>
     <string name="permdesc_locationUpdates" msgid="2300018303720930256">"Hiermee kunnen updatemeldingen voor locaties van de radio worden ingeschakeld/uitgeschakeld. Niet voor gebruik door normale toepassingen."</string>
     <string name="permlab_checkinProperties" msgid="7855259461268734914">"toegang tot checkin-eigenschappen"</string>
     <string name="permdesc_checkinProperties" msgid="7150307006141883832">"Hiermee wordt lees-/schrijftoegang gegeven tot eigenschappen die door de checkin-service zijn geüpload. Niet voor gebruik door normale toepassingen."</string>
     <string name="permlab_bindGadget" msgid="776905339015863471">"widgets kiezen"</string>
-    <string name="permdesc_bindGadget" msgid="2098697834497452046">"Hiermee kan een toepassing het systeem melden welke widgets door welke toepassing kunnen worden gebruikt. Met deze toestemming kunnen toepassingen andere toepassingen toegang geven tot persoonlijke gegevens. Niet voor gebruik door normale toepassingen."</string>
+    <string name="permdesc_bindGadget" msgid="2098697834497452046">"Hiermee kan een app het systeem melden welke widgets door welke app kunnen worden gebruikt. Met deze toestemming kunnen apps andere apps toegang geven tot persoonlijke gegevens. Niet voor gebruik door normale apps."</string>
     <string name="permlab_modifyPhoneState" msgid="8423923777659292228">"telefoonstatus wijzigen"</string>
-    <string name="permdesc_modifyPhoneState" msgid="3302284561346956587">"Hiermee kan de toepassing de telefoonfuncties van het apparaat beheren. Een toepassing met deze machtiging kan schakelen tussen netwerken, de radio van de telefoon in- of uitschakelen en dergelijke zonder dat u hiervan op de hoogte wordt gesteld."</string>
+    <string name="permdesc_modifyPhoneState" msgid="3302284561346956587">"Hiermee kan de app de telefoonfuncties van het apparaat beheren. Een app met deze machtiging kan schakelen tussen netwerken, de radio van de telefoon in- of uitschakelen en dergelijke zonder dat u hiervan op de hoogte wordt gesteld."</string>
     <string name="permlab_readPhoneState" msgid="2326172951448691631">"telefoonstatus en -identiteit lezen"</string>
-    <string name="permdesc_readPhoneState" msgid="188877305147626781">"Hiermee krijgt de toepassing toegang tot de telefoonfuncties van het apparaat. Een toepassing met de betreffende machtiging kan het telefoonnummer en serienummer van deze telefoon achterhalen, bepalen of een oproep actief is, het gekozen nummer achterhalen en dergelijke."</string>
+    <string name="permdesc_readPhoneState" msgid="188877305147626781">"Hiermee krijgt de app toegang tot de telefoonfuncties van het apparaat. Een app met de betreffende machtiging kan het telefoonnummer en serienummer van deze telefoon achterhalen, bepalen of een oproep actief is, het gekozen nummer achterhalen en dergelijke."</string>
     <string name="permlab_wakeLock" msgid="573480187941496130">"voorkomen dat telefoon overschakelt naar slaapmodus"</string>
-    <string name="permdesc_wakeLock" msgid="7584036471227467099">"Hiermee kan een toepassing voorkomen dat de telefoon overschakelt naar de slaapmodus."</string>
+    <string name="permdesc_wakeLock" msgid="7584036471227467099">"Hiermee kan een app voorkomen dat de telefoon overschakelt naar de slaapmodus."</string>
     <string name="permlab_devicePower" msgid="4928622470980943206">"telefoon in- of uitschakelen"</string>
-    <string name="permdesc_devicePower" msgid="4577331933252444818">"Hiermee kan de toepassing de telefoon in- of uitschakelen."</string>
+    <string name="permdesc_devicePower" msgid="4577331933252444818">"Hiermee kan de app de telefoon in- of uitschakelen."</string>
     <string name="permlab_factoryTest" msgid="3715225492696416187">"uitvoeren in fabriekstestmodus"</string>
     <string name="permdesc_factoryTest" msgid="8136644990319244802">"Uitvoeren als fabrikanttest op laag niveau, waardoor toegang wordt gegeven tot de hardware van de telefoon. Alleen beschikbaar als een telefoon zich in de fabrikanttestmodus bevindt."</string>
     <string name="permlab_setWallpaper" msgid="6627192333373465143">"achtergrond instellen"</string>
-    <string name="permdesc_setWallpaper" msgid="6417041752170585837">"Hiermee kan de toepassing de systeemachtergrond instellen."</string>
+    <string name="permdesc_setWallpaper" msgid="6417041752170585837">"Hiermee kan de app de systeemachtergrond instellen."</string>
     <string name="permlab_setWallpaperHints" msgid="3600721069353106851">"grootte achtergrond instellen"</string>
-    <string name="permdesc_setWallpaperHints" msgid="6019479164008079626">"Hiermee kan de toepassing de grootte van de achtergrond instellen."</string>
+    <string name="permdesc_setWallpaperHints" msgid="6019479164008079626">"Hiermee kan de app de grootte van de achtergrond instellen."</string>
     <string name="permlab_masterClear" msgid="2315750423139697397">"systeem terugzetten op fabrieksinstellingen"</string>
-    <string name="permdesc_masterClear" msgid="5033465107545174514">"Hiermee kan een toepassing het systeem terugzetten op de fabrieksinstellingen, waarbij alle gegevens, configuraties en geïnstalleerde toepassingen worden verwijderd."</string>
+    <string name="permdesc_masterClear" msgid="5033465107545174514">"Hiermee kan een app het systeem terugzetten op de fabrieksinstellingen, waarbij alle gegevens, configuraties en geïnstalleerde apps worden verwijderd."</string>
     <string name="permlab_setTime" msgid="2021614829591775646">"tijd instellen"</string>
-    <string name="permdesc_setTime" msgid="667294309287080045">"Staat een toepassing toe de kloktijd van de telefoon te wijzigen."</string>
+    <string name="permdesc_setTime" msgid="667294309287080045">"Staat een app toe de kloktijd van de telefoon te wijzigen."</string>
     <string name="permlab_setTimeZone" msgid="2945079801013077340">"tijdzone instellen"</string>
-    <string name="permdesc_setTimeZone" msgid="1902540227418179364">"Hiermee kan een toepassing de tijdzone van de telefoon wijzigen."</string>
+    <string name="permdesc_setTimeZone" msgid="1902540227418179364">"Hiermee kan een app de tijdzone van de telefoon wijzigen."</string>
     <string name="permlab_accountManagerService" msgid="4829262349691386986">"fungeren als de AccountManagerService"</string>
-    <string name="permdesc_accountManagerService" msgid="6056903274106394752">"Hiermee kan een toepassing aanroepen plaatsen naar AccountAuthenticators"</string>
+    <string name="permdesc_accountManagerService" msgid="6056903274106394752">"Hiermee kan een app aanroepen plaatsen naar AccountAuthenticators"</string>
     <string name="permlab_getAccounts" msgid="4549918644233460103">"bekende accounts zoeken"</string>
-    <string name="permdesc_getAccounts" msgid="6839262446413155394">"Hiermee kan een toepassing de lijst met accounts van een telefoon ophalen."</string>
+    <string name="permdesc_getAccounts" msgid="6839262446413155394">"Hiermee kan een app de lijst met accounts van een telefoon ophalen."</string>
     <string name="permlab_authenticateAccounts" msgid="3940505577982882450">"fungeren als verificatie-instantie voor het account"</string>
-    <string name="permdesc_authenticateAccounts" msgid="4006839406474208874">"Hiermee kan een toepassing de mogelijkheden voor verificatie-instanties voor het account van de AccountManager gebruiken, waaronder het maken van accounts en het ophalen en instellen van de bijbehorende wachtwoorden."</string>
+    <string name="permdesc_authenticateAccounts" msgid="4006839406474208874">"Hiermee kan een app de mogelijkheden voor verificatie-instanties voor het account van de AccountManager gebruiken, waaronder het maken van accounts en het ophalen en instellen van de bijbehorende wachtwoorden."</string>
     <string name="permlab_manageAccounts" msgid="4440380488312204365">"de lijst met accounts beheren"</string>
-    <string name="permdesc_manageAccounts" msgid="8804114016661104517">"Hiermee kan een toepassing bewerkingen uitvoeren, zoals het toevoegen en verwijderen van accounts en het verwijderen van de bijbehorende wachtwoorden."</string>
+    <string name="permdesc_manageAccounts" msgid="8804114016661104517">"Hiermee kan een app bewerkingen uitvoeren, zoals het toevoegen en verwijderen van accounts en het verwijderen van de bijbehorende wachtwoorden."</string>
     <string name="permlab_useCredentials" msgid="6401886092818819856">"de verificatiegegevens van een account gebruiken"</string>
-    <string name="permdesc_useCredentials" msgid="7416570544619546974">"Hiermee kan een toepassing verificatietokens aanvragen."</string>
+    <string name="permdesc_useCredentials" msgid="7416570544619546974">"Hiermee kan een app verificatietokens aanvragen."</string>
     <string name="permlab_accessNetworkState" msgid="6865575199464405769">"netwerkstatus bekijken"</string>
-    <string name="permdesc_accessNetworkState" msgid="558721128707712766">"Hiermee kan een toepassing de status van alle netwerken bekijken."</string>
+    <string name="permdesc_accessNetworkState" msgid="558721128707712766">"Hiermee kan een app de status van alle netwerken bekijken."</string>
     <string name="permlab_createNetworkSockets" msgid="9121633680349549585">"volledige internettoegang"</string>
-    <string name="permdesc_createNetworkSockets" msgid="4593339106921772192">"Hiermee kan een toepassing netwerksockets maken."</string>
+    <string name="permdesc_createNetworkSockets" msgid="4593339106921772192">"Hiermee kan een app netwerksockets maken."</string>
     <string name="permlab_writeApnSettings" msgid="7823599210086622545">"instellingen voor toegangspuntnaam schrijven"</string>
-    <string name="permdesc_writeApnSettings" msgid="7443433457842966680">"Hiermee kan een toepassing de APN-instellingen, zoals proxy en poort, van elke APN wijzigen."</string>
+    <string name="permdesc_writeApnSettings" msgid="7443433457842966680">"Hiermee kan een app de APN-instellingen, zoals proxy en poort, van elke APN wijzigen."</string>
     <string name="permlab_changeNetworkState" msgid="958884291454327309">"netwerkverbinding wijzigen"</string>
-    <string name="permdesc_changeNetworkState" msgid="4199958910396387075">"Staat een toepassing toe de status van de netwerkverbinding te wijzigen."</string>
+    <string name="permdesc_changeNetworkState" msgid="4199958910396387075">"Staat een app toe de status van de netwerkverbinding te wijzigen."</string>
     <string name="permlab_changeTetherState" msgid="2702121155761140799">"Getetherde verbinding wijzigen"</string>
-    <string name="permdesc_changeTetherState" msgid="8905815579146349568">"Staat een toepassing toe de status van de getetherde netwerkverbinding te wijzigen."</string>
+    <string name="permdesc_changeTetherState" msgid="8905815579146349568">"Staat een app toe de status van de getetherde netwerkverbinding te wijzigen."</string>
     <string name="permlab_changeBackgroundDataSetting" msgid="1400666012671648741">"instelling voor gebruik van achtergrondgegevens van gegevens wijzigen"</string>
-    <string name="permdesc_changeBackgroundDataSetting" msgid="1001482853266638864">"Hiermee kan een toepassing de instelling voor gebruik van achtergrondgegevens wijzigen."</string>
+    <string name="permdesc_changeBackgroundDataSetting" msgid="1001482853266638864">"Hiermee kan een app de instelling voor gebruik van achtergrondgegevens wijzigen."</string>
     <string name="permlab_accessWifiState" msgid="8100926650211034400">"Wi-Fi-status bekijken"</string>
-    <string name="permdesc_accessWifiState" msgid="485796529139236346">"Hiermee kan een toepassing informatie over de Wi-Fi-status bekijken."</string>
+    <string name="permdesc_accessWifiState" msgid="485796529139236346">"Hiermee kan een app informatie over de Wi-Fi-status bekijken."</string>
     <string name="permlab_changeWifiState" msgid="7280632711057112137">"Wi-Fi-status wijzigen"</string>
-    <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Hiermee kan een toepassing zich koppelen aan en loskoppelen van Wi-Fi toegangspunten en wijzigingen aanbrengen in geconfigureerde Wi-Fi-netwerken."</string>
+    <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Hiermee kan een app zich koppelen aan en loskoppelen van Wi-Fi toegangspunten en wijzigingen aanbrengen in geconfigureerde Wi-Fi-netwerken."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"Wi-Fi Multicast-ontvangst toestaan"</string>
-    <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Hiermee kan een toepassing pakketten ontvangen die niet rechtstreeks zijn geadresseerd aan uw apparaat. Dit kan handig zijn wanneer services in de buurt worden ontdekt. Dit verbruikt meer energie dan de niet-multicastmodus."</string>
+    <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Hiermee kan een app pakketten ontvangen die niet rechtstreeks zijn geadresseerd aan uw apparaat. Dit kan handig zijn wanneer services in de buurt worden ontdekt. Dit verbruikt meer energie dan de niet-multicastmodus."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"WiMAX-status bekijken"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Hiermee kan een app informatie over de WiMAX-status bekijken."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"WiMAX-status wijzigen"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Hiermee kan een app verbinding maken met een WiMAX-netwerk en deze verbreken."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"bluetooth-beheer"</string>
-    <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Hiermee kan een toepassing de lokale Bluetooth-telefoon configureren en externe apparaten zoeken en aansluiten."</string>
+    <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Hiermee kan een app de lokale Bluetooth-telefoon configureren en externe apparaten zoeken en aansluiten."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"Bluetooth-verbindingen maken"</string>
-    <string name="permdesc_bluetooth" msgid="762515380679392945">"Hiermee kan een toepassing de configuratie van een lokale Bluetooth-telefoon bekijken en verbindingen met gekoppelde apparaten maken en accepteren."</string>
+    <string name="permdesc_bluetooth" msgid="762515380679392945">"Hiermee kan een app de configuratie van een lokale Bluetooth-telefoon bekijken en verbindingen met gekoppelde apparaten maken en accepteren."</string>
     <string name="permlab_nfc" msgid="4423351274757876953">"Near Field Communication regelen"</string>
-    <string name="permdesc_nfc" msgid="9171401851954407226">"Hiermee kan een toepassing communiceren met NFC-tags (Near Field Communication), kaarten en lezers."</string>
+    <string name="permdesc_nfc" msgid="9171401851954407226">"Hiermee kan een app communiceren met NFC-tags (Near Field Communication), kaarten en lezers."</string>
     <string name="permlab_disableKeyguard" msgid="4977406164311535092">"toetsvergrendeling uitschakelen"</string>
-    <string name="permdesc_disableKeyguard" msgid="3189763479326302017">"Hiermee kan een toepassing de toetsvergrendeling en bijbehorende wachtwoordbeveiliging uitschakelen. Een voorbeeld: de telefoon schakelt de toetsvergrendeling uit als er een oproep binnenkomt en schakelt de toetsvergrendeling weer in als de oproep is beëindigd."</string>
+    <string name="permdesc_disableKeyguard" msgid="3189763479326302017">"Hiermee kan een app de toetsvergrendeling en bijbehorende wachtwoordbeveiliging uitschakelen. Een voorbeeld: de telefoon schakelt de toetsvergrendeling uit wanneer een oproep binnenkomt en schakelt de toetsvergrendeling weer in zodra de oproep wordt beëindigd."</string>
     <string name="permlab_readSyncSettings" msgid="6201810008230503052">"synchronisatie-instellingen lezen"</string>
-    <string name="permdesc_readSyncSettings" msgid="5315925706353341823">"Hiermee kan een toepassing de synchronisatie-instellingen lezen, bijvoorbeeld of de synchronisatie van contacten is ingeschakeld."</string>
+    <string name="permdesc_readSyncSettings" msgid="5315925706353341823">"Hiermee kan een app de synchronisatie-instellingen lezen, bijvoorbeeld of de synchronisatie van contacten is ingeschakeld."</string>
     <string name="permlab_writeSyncSettings" msgid="6297138566442486462">"synchronisatie-instellingen schrijven"</string>
-    <string name="permdesc_writeSyncSettings" msgid="2498201614431360044">"Hiermee kan een toepassing uw synchronisatie-instellingen wijzigen, bijvoorbeeld of de synchronisatie van contacten is ingeschakeld."</string>
+    <string name="permdesc_writeSyncSettings" msgid="2498201614431360044">"Hiermee kan een app uw synchronisatie-instellingen wijzigen, bijvoorbeeld of de synchronisatie van contacten is ingeschakeld."</string>
     <string name="permlab_readSyncStats" msgid="7396577451360202448">"synchronisatiestatistieken lezen"</string>
-    <string name="permdesc_readSyncStats" msgid="7511448343374465000">"Hiermee kan een toepassing de synchronisatiestatistieken lezen, zoals de geschiedenis van uitgevoerde synchronisaties."</string>
+    <string name="permdesc_readSyncStats" msgid="7511448343374465000">"Hiermee kan een app de synchronisatiestatistieken lezen, zoals de geschiedenis van uitgevoerde synchronisaties."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"geabonneerde feeds lezen"</string>
-    <string name="permdesc_subscribedFeedsRead" msgid="3622200625634207660">"Hiermee kan een toepassing details over de huidige gesynchroniseerde feeds achterhalen."</string>
+    <string name="permdesc_subscribedFeedsRead" msgid="3622200625634207660">"Hiermee kan een app details over de huidige gesynchroniseerde feeds achterhalen."</string>
     <string name="permlab_subscribedFeedsWrite" msgid="9015246325408209296">"geabonneerde feeds schrijven"</string>
-    <string name="permdesc_subscribedFeedsWrite" msgid="8121607099326533878">"Hiermee kan een toepassing uw huidige gesynchroniseerde feeds wijzigen. Een schadelijke toepassing kan op deze manier uw gesynchroniseerde feeds wijzigen."</string>
+    <string name="permdesc_subscribedFeedsWrite" msgid="8121607099326533878">"Hiermee kan een app uw huidige gesynchroniseerde feeds wijzigen. Een schadelijke app kan op deze manier uw gesynchroniseerde feeds wijzigen."</string>
     <string name="permlab_readDictionary" msgid="432535716804748781">"door gebruiker gedefinieerd woordenboek lezen"</string>
-    <string name="permdesc_readDictionary" msgid="1082972603576360690">"Hiermee kan een toepassing privéwoorden, namen en woordcombinaties lezen die de gebruiker heeft opgeslagen in het gebruikerswoordenboek."</string>
+    <string name="permdesc_readDictionary" msgid="1082972603576360690">"Hiermee kan een app privéwoorden, namen en woordcombinaties lezen die de gebruiker heeft opgeslagen in het gebruikerswoordenboek."</string>
     <string name="permlab_writeDictionary" msgid="6703109511836343341">"schrijven naar door gebruiker gedefinieerd woordenboek"</string>
-    <string name="permdesc_writeDictionary" msgid="2241256206524082880">"Hiermee kan een toepassing nieuwe woorden schrijven naar het gebruikerswoordenboek."</string>
+    <string name="permdesc_writeDictionary" msgid="2241256206524082880">"Hiermee kan een app nieuwe woorden schrijven naar het gebruikerswoordenboek."</string>
     <string name="permlab_sdcardWrite" product="nosdcard" msgid="85430876310764752">"inhoud van USB-opslag aanpassen/verwijderen"</string>
     <string name="permlab_sdcardWrite" product="default" msgid="8079403759001777291">"inhoud op de SD-kaart aanpassen/verwijderen"</string>
-    <string name="permdesc_sdcardWrite" product="nosdcard" msgid="6594393334785738252">"Hiermee kan een toepassing schrijven naar de USB-opslag."</string>
-    <string name="permdesc_sdcardWrite" product="default" msgid="6643963204976471878">"Hiermee kan een toepassing schrijven naar de SD-kaart."</string>
+    <string name="permdesc_sdcardWrite" product="nosdcard" msgid="6594393334785738252">"Hiermee kan een app schrijven naar de USB-opslag."</string>
+    <string name="permdesc_sdcardWrite" product="default" msgid="6643963204976471878">"Hiermee kan een app schrijven naar de SD-kaart."</string>
     <string name="permlab_cache_filesystem" msgid="5656487264819669824">"het cachebestandssysteem openen"</string>
-    <string name="permdesc_cache_filesystem" msgid="1624734528435659906">"Staat een toepassing toe het cachebestandssysteem te lezen en te schrijven."</string>
+    <string name="permdesc_cache_filesystem" msgid="1624734528435659906">"Staat een app toe het cachebestandssysteem te lezen en te schrijven."</string>
     <string name="permlab_use_sip" msgid="5986952362795870502">"internetoproepen starten/ontvangen"</string>
-    <string name="permdesc_use_sip" msgid="6320376185606661843">"Hiermee kan een toepassing de SIP-service gebruiken om internetoproepen te starten/te ontvangen."</string>
+    <string name="permdesc_use_sip" msgid="6320376185606661843">"Hiermee kan een app de SIP-service gebruiken om internetoproepen te starten/te ontvangen."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Wachtwoordregels instellen"</string>
     <string name="policydesc_limitPassword" msgid="9083400080861728056">"De lengte en tekens beheren die zijn toegestaan in wachtwoorden voor schermontgrendeling"</string>
     <string name="policylab_watchLogin" msgid="914130646942199503">"Pogingen voor schermontgrendeling bijhouden"</string>
@@ -595,13 +599,13 @@
     <string name="save_password_label" msgid="6860261758665825069">"Bevestigen"</string>
     <string name="double_tap_toast" msgid="1068216937244567247">"Tip: tik tweemaal om in of uit te zoomen."</string>
     <string name="permlab_readHistoryBookmarks" msgid="1284843728203412135">"browsergeschiedenis en bladwijzers lezen"</string>
-    <string name="permdesc_readHistoryBookmarks" msgid="4981489815467617191">"Hiermee kan een toepassing de URL\'s lezen die u via de browser heeft bezocht, evenals alle bladwijzers van de browser."</string>
+    <string name="permdesc_readHistoryBookmarks" msgid="4981489815467617191">"Hiermee kan een app de URL\'s lezen die u via de browser heeft bezocht, evenals alle bladwijzers van de browser."</string>
     <string name="permlab_writeHistoryBookmarks" msgid="9009434109836280374">"browsergeschiedenis en bladwijzers schrijven"</string>
-    <string name="permdesc_writeHistoryBookmarks" msgid="945571990357114950">"Hiermee kan een toepassing de op uw telefoon opgeslagen browsergeschiedenis of bladwijzers wijzigen. Schadelijke toepassingen kunnen hiermee uw browsergegevens verwijderen of wijzigen."</string>
+    <string name="permdesc_writeHistoryBookmarks" msgid="945571990357114950">"Hiermee kan een app de op uw telefoon opgeslagen browsergeschiedenis of bladwijzers wijzigen. Schadelijke apps kunnen hiermee uw browsergegevens verwijderen of wijzigen."</string>
     <string name="permlab_setAlarm" msgid="5924401328803615165">"alarm instellen in wekker"</string>
-    <string name="permdesc_setAlarm" msgid="5966966598149875082">"Hiermee kan de toepassing een alarm instellen in een geïnstalleerde wekkertoepassing. Deze functie wordt door sommige wekkertoepassingen niet geïmplementeerd."</string>
+    <string name="permdesc_setAlarm" msgid="5966966598149875082">"Hiermee kan de app een alarm instellen in een geïnstalleerde wekker-app. Deze functie wordt door sommige wekker-apps niet geïmplementeerd."</string>
     <string name="permlab_writeGeolocationPermissions" msgid="4715212655598275532">"Geolocatierechten voor browser aanpassen"</string>
-    <string name="permdesc_writeGeolocationPermissions" msgid="4011908282980861679">"Staat een toepassing toe de geolocatierechten van de browser aan te passen. Schadelijke toepassingen kunnen dit gebruiken om locatiegegevens te verzenden naar willekeurige websites."</string>
+    <string name="permdesc_writeGeolocationPermissions" msgid="4011908282980861679">"Staat een app toe de geolocatierechten van de browser aan te passen. Schadelijke apps kunnen dit gebruiken om locatiegegevens te verzenden naar willekeurige websites."</string>
     <string name="save_password_message" msgid="767344687139195790">"Wilt u dat de browser dit wachtwoord onthoudt?"</string>
     <string name="save_password_notnow" msgid="6389675316706699758">"Niet nu"</string>
     <string name="save_password_remember" msgid="6491879678996749466">"Onthouden"</string>
@@ -733,31 +737,32 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Standaard gebruiken voor deze actie."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Wis standaardinstelling via startscherm: \'Instellingen\' &gt; \'Toepassingen\' &gt; \'Toepassingen beheren\'."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Een actie selecteren"</string>
-    <string name="noApplications" msgid="1691104391758345586">"Geen enkele toepassing kan deze actie uitvoeren."</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Selecteer een app voor het USB-apparaat"</string>
+    <string name="noApplications" msgid="1691104391758345586">"Geen enkele app kan deze actie uitvoeren."</string>
     <string name="aerr_title" msgid="653922989522758100">"Helaas!"</string>
-    <string name="aerr_application" msgid="4683614104336409186">"De toepassing <xliff:g id="APPLICATION">%1$s</xliff:g> (proces <xliff:g id="PROCESS">%2$s</xliff:g>) is onverwachts gestopt. Probeer het opnieuw."</string>
+    <string name="aerr_application" msgid="4683614104336409186">"De app <xliff:g id="APPLICATION">%1$s</xliff:g> (proces <xliff:g id="PROCESS">%2$s</xliff:g>) is onverwachts gestopt. Probeer het opnieuw."</string>
     <string name="aerr_process" msgid="1551785535966089511">"Het proces <xliff:g id="PROCESS">%1$s</xliff:g> is onverwachts gestopt. Probeer het opnieuw."</string>
     <string name="anr_title" msgid="3100070910664756057">"Helaas!"</string>
-    <string name="anr_activity_application" msgid="3538242413112507636">"Activiteit <xliff:g id="ACTIVITY">%1$s</xliff:g> (in toepassing <xliff:g id="APPLICATION">%2$s</xliff:g>) reageert niet."</string>
+    <string name="anr_activity_application" msgid="3538242413112507636">"Activiteit <xliff:g id="ACTIVITY">%1$s</xliff:g> (in app <xliff:g id="APPLICATION">%2$s</xliff:g>) reageert niet."</string>
     <string name="anr_activity_process" msgid="5420826626009561014">"Activiteit <xliff:g id="ACTIVITY">%1$s</xliff:g> (in proces <xliff:g id="PROCESS">%2$s</xliff:g>) reageert niet."</string>
-    <string name="anr_application_process" msgid="4185842666452210193">"Toepassing <xliff:g id="APPLICATION">%1$s</xliff:g> (in proces <xliff:g id="PROCESS">%2$s</xliff:g>) reageert niet."</string>
+    <string name="anr_application_process" msgid="4185842666452210193">"App <xliff:g id="APPLICATION">%1$s</xliff:g> (in proces <xliff:g id="PROCESS">%2$s</xliff:g>) reageert niet."</string>
     <string name="anr_process" msgid="1246866008169975783">"Proces <xliff:g id="PROCESS">%1$s</xliff:g> reageert niet."</string>
     <string name="force_close" msgid="3653416315450806396">"Nu sluiten"</string>
     <string name="report" msgid="4060218260984795706">"Rapport"</string>
     <string name="wait" msgid="7147118217226317732">"Wachten"</string>
-    <string name="launch_warning_title" msgid="8323761616052121936">"Toepassing omgeleid"</string>
+    <string name="launch_warning_title" msgid="8323761616052121936">"App omgeleid"</string>
     <string name="launch_warning_replace" msgid="6202498949970281412">"<xliff:g id="APP_NAME">%1$s</xliff:g> is nu actief."</string>
     <string name="launch_warning_original" msgid="188102023021668683">"<xliff:g id="APP_NAME">%1$s</xliff:g> was het eerst gestart."</string>
-    <string name="smv_application" msgid="295583804361236288">"De toepassing <xliff:g id="APPLICATION">%1$s</xliff:g> (proces <xliff:g id="PROCESS">%2$s</xliff:g>) heeft het zelf afgedwongen StrictMode-beleid geschonden."</string>
+    <string name="smv_application" msgid="295583804361236288">"De app <xliff:g id="APPLICATION">%1$s</xliff:g> (proces <xliff:g id="PROCESS">%2$s</xliff:g>) heeft het zelf afgedwongen StrictMode-beleid geschonden."</string>
     <string name="smv_process" msgid="5120397012047462446">"Het proces <xliff:g id="PROCESS">%1$s</xliff:g> heeft het zelf afgedwongen StrictMode-beleid geschonden."</string>
     <string name="heavy_weight_notification" msgid="9087063985776626166">"<xliff:g id="APP">%1$s</xliff:g> wordt uitgevoerd"</string>
-    <string name="heavy_weight_notification_detail" msgid="2423977499339403402">"Selecteren om over te schakelen naar toepassing"</string>
+    <string name="heavy_weight_notification_detail" msgid="2423977499339403402">"Selecteren om over te schakelen naar app"</string>
     <string name="heavy_weight_switcher_title" msgid="1135403633766694316">"Toepassingen wijzigen?"</string>
-    <string name="heavy_weight_switcher_text" msgid="4592075610079319667">"Er wordt al een andere toepassing uitgevoerd die moet worden gestopt voordat u een nieuwe toepassing kunt starten."</string>
+    <string name="heavy_weight_switcher_text" msgid="4592075610079319667">"Er wordt al een andere app uitgevoerd die moet worden gestopt voordat u een nieuwe app kunt starten."</string>
     <string name="old_app_action" msgid="493129172238566282">"Terug naar <xliff:g id="OLD_APP">%1$s</xliff:g>"</string>
-    <string name="old_app_description" msgid="942967900237208466">"De nieuwe toepassing niet starten."</string>
+    <string name="old_app_description" msgid="942967900237208466">"De nieuwe app niet starten."</string>
     <string name="new_app_action" msgid="5472756926945440706">"<xliff:g id="OLD_APP">%1$s</xliff:g> starten"</string>
-    <string name="new_app_description" msgid="6830398339826789493">"De oude toepassing stoppen zonder opslaan."</string>
+    <string name="new_app_description" msgid="6830398339826789493">"De oude app stoppen zonder opslaan."</string>
     <string name="sendText" msgid="5132506121645618310">"Selecteer een actie voor tekst"</string>
     <string name="volume_ringtone" msgid="6885421406845734650">"Belvolume"</string>
     <string name="volume_music" msgid="5421651157138628171">"Mediavolume"</string>
@@ -782,7 +787,7 @@
     <item quantity="other" msgid="7915895323644292768">"Open Wi-Fi-netwerken beschikbaar"</item>
   </plurals>
     <string name="select_character" msgid="3365550120617701745">"Teken invoegen"</string>
-    <string name="sms_control_default_app_name" msgid="7630529934366549163">"Onbekende toepassing"</string>
+    <string name="sms_control_default_app_name" msgid="7630529934366549163">"Onbekende app"</string>
     <string name="sms_control_title" msgid="7296612781128917719">"SMS-berichten verzenden"</string>
     <string name="sms_control_message" msgid="1289331457999236205">"Er wordt een groot aantal SMS-berichten verzonden. Selecteer \'OK\' om door te gaan of \'Annuleren\' om de verzending te stoppen."</string>
     <string name="sms_control_yes" msgid="2532062172402615953">"OK"</string>
diff --git a/core/res/res/values-pl/strings.xml b/core/res/res/values-pl/strings.xml
index de72e8c..a70bcbf 100644
--- a/core/res/res/values-pl/strings.xml
+++ b/core/res/res/values-pl/strings.xml
@@ -50,7 +50,7 @@
     <string name="needPuk2" msgid="4526033371987193070">"Wprowadź kod PUK2, aby odblokować kartę SIM."</string>
     <string name="ClipMmi" msgid="6952821216480289285">"Identyfikator rozmówcy przy połączeniach przychodzących"</string>
     <string name="ClirMmi" msgid="7784673673446833091">"Identyfikator rozmówcy przy połączeniach wychodzących"</string>
-    <string name="CfMmi" msgid="5123218989141573515">"Przekierowania połączeń"</string>
+    <string name="CfMmi" msgid="5123218989141573515">"Przekazywanie połączeń"</string>
     <string name="CwMmi" msgid="9129678056795016867">"Połączenia oczekujące"</string>
     <string name="BaMmi" msgid="455193067926770581">"Blokada dzwonienia"</string>
     <string name="PwdMmi" msgid="7043715687905254199">"Zmiana hasła"</string>
@@ -241,8 +241,8 @@
     <string name="permdesc_injectEvents" msgid="3946098050410874715">"Pozwala aplikacjom na dostarczanie własnych zdarzeń wprowadzania danych (naciśnięcie klawisza itp.) do innych aplikacji. Szkodliwe aplikacje mogą to wykorzystać do przejęcia kontroli nad telefonem."</string>
     <string name="permlab_readInputState" msgid="469428900041249234">"zapamiętywanie wpisywanych znaków oraz wykonywanych czynności"</string>
     <string name="permdesc_readInputState" msgid="5132879321450325445">"Pozwala aplikacjom na śledzenie naciskanych klawiszy, nawet podczas pracy z innym programem (na przykład podczas wpisywania hasła). Nigdy nie powinno być potrzebne normalnym aplikacjom."</string>
-    <string name="permlab_bindInputMethod" msgid="3360064620230515776">"tworzenie powiązania z metodą wejściową"</string>
-    <string name="permdesc_bindInputMethod" msgid="3734838321027317228">"Pozwala na tworzenie powiązania z interfejsem najwyższego poziomu metody wejściowej. To uprawnienie nie powinno być nigdy wymagane przez zwykłe aplikacje."</string>
+    <string name="permlab_bindInputMethod" msgid="3360064620230515776">"powiązanie ze sposobem wprowadzania tekstu"</string>
+    <string name="permdesc_bindInputMethod" msgid="3734838321027317228">"Pozwala na powiązanie wybranego sposobu wprowadzania tekstu z interfejsem najwyższego poziomu. To uprawnienie nie powinno być nigdy wymagane przez zwykłe aplikacje."</string>
     <string name="permlab_bindWallpaper" msgid="8716400279937856462">"powiązanie z tapetą"</string>
     <string name="permdesc_bindWallpaper" msgid="5287754520361915347">"Umożliwia posiadaczowi powiązać interfejs najwyższego poziomu dla tapety. Nie powinno być nigdy potrzebne w przypadku zwykłych aplikacji."</string>
     <string name="permlab_bindDeviceAdmin" msgid="8704986163711455010">"interakcja z administratorem urządzenia"</string>
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Pozwala aplikacjom na kontrolowanie wibracji."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"kontrolowanie latarki"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Pozwala aplikacji kontrolować latarkę."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"dostęp do urządzeń USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Zezwala aplikacji na dostęp do urządzeń USB."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"zarządzanie ustawieniami i uprawnieniami urządzeń USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Umożliwia aplikacji zarządzanie ustawieniami i uprawnieniami urządzeń USB."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"testowanie sprzętu"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Pozwala aplikacji na kontrolowanie różnych urządzeń peryferyjnych w celu testowania sprzętu."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"bezpośrednie wybieranie numerów telefonów"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Pozwala aplikacji na łączenie i rozłączanie z punktami dostępowymi Wi-Fi oraz na dokonywanie zmian skonfigurowanych sieci Wi-Fi."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"zezwolenie na odbiór grupowych połączeń Wi-Fi"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Umożliwia aplikacji odbieranie pakietów nieskierowanych bezpośrednio do Twojego urządzenia. Może to być przydatne przy wykrywaniu usług oferowanych w okolicy. Powoduje większe zapotrzebowanie na energię niż w trybie innym niż grupowy."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"wyświetlanie stanu WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Zezwala aplikacji na dostęp do informacji o stanie połączenia WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"zmiana stanu WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Zezwala aplikacji na łączenie się i rozłączanie z siecią WiMAX."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"administrowanie Bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Pozwala aplikacji na konfigurowanie lokalnego telefonu Bluetooth, wyszukiwanie urządzeń zdalnych i łączenie się z nimi."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"tworzenie połączeń Bluetooth"</string>
@@ -717,7 +721,7 @@
     <string name="copy" msgid="2681946229533511987">"Kopiuj"</string>
     <string name="paste" msgid="5629880836805036433">"Wklej"</string>
     <string name="copyUrl" msgid="2538211579596067402">"Kopiuj adres URL"</string>
-    <string name="inputMethod" msgid="1653630062304567879">"Metoda wprowadzania"</string>
+    <string name="inputMethod" msgid="1653630062304567879">"Sposób wprowadzania tekstu"</string>
     <string name="addToDictionary" msgid="8793624991686948709">"Dodaj termin „<xliff:g id="WORD">%s</xliff:g>” do słownika"</string>
     <string name="editTextMenuTitle" msgid="1672989176958581452">"Edytuj tekst"</string>
     <string name="low_internal_storage_view_title" msgid="1399732408701697546">"Mało miejsca"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Używaj domyślnie dla tej czynności."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Wyczyść domyślne w: Ustawienia strony głównej &gt; Aplikacje &gt; Zarządzaj aplikacjami."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Wybierz czynność"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Wybierz aplikację dla urządzenia USB"</string>
     <string name="noApplications" msgid="1691104391758345586">"Żadna z aplikacji nie może wykonać tej czynności."</string>
     <string name="aerr_title" msgid="653922989522758100">"Przepraszamy!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"Aplikacja <xliff:g id="APPLICATION">%1$s</xliff:g> (proces <xliff:g id="PROCESS">%2$s</xliff:g>) została niespodziewanie zatrzymana. Spróbuj ponownie."</string>
@@ -819,7 +824,7 @@
     <string name="extmedia_format_button_format" msgid="4131064560127478695">"Formatuj"</string>
     <string name="adb_active_notification_title" msgid="6729044778949189918">"Podłączono moduł debugowania USB"</string>
     <string name="adb_active_notification_message" msgid="8470296818270110396">"Wybierz, aby wyłączyć debugowanie USB."</string>
-    <string name="select_input_method" msgid="6865512749462072765">"Wybierz metodę wprowadzania"</string>
+    <string name="select_input_method" msgid="6865512749462072765">"Wybierz sposób wprowadzania tekstu"</string>
     <string name="fast_scroll_alphabet" msgid="5433275485499039199">" AĄBCĆDEĘFGHIJKLŁMNŃOÓPQRSŚTUVWXYZŹŻ"</string>
     <string name="fast_scroll_numeric_alphabet" msgid="4030170524595123610">" 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"</string>
     <string name="candidates_style" msgid="4333913089637062257"><u>"kandydaci"</u></string>
@@ -870,7 +875,7 @@
     <string name="deny" msgid="2081879885755434506">"Odmów"</string>
     <string name="permission_request_notification_title" msgid="5390555465778213840">"Żądane pozwolenie"</string>
     <string name="permission_request_notification_with_subtitle" msgid="4325409589686688000">"Prośba o pozwolenie"\n"dotyczące konta <xliff:g id="ACCOUNT">%s</xliff:g>"</string>
-    <string name="input_method_binding_label" msgid="1283557179944992649">"Metoda wprowadzania"</string>
+    <string name="input_method_binding_label" msgid="1283557179944992649">"Sposób wprowadzania tekstu"</string>
     <string name="sync_binding_label" msgid="3687969138375092423">"Synchronizacja"</string>
     <string name="accessibility_binding_label" msgid="4148120742096474641">"Ułatwienia dostępu"</string>
     <string name="wallpaper_binding_label" msgid="1240087844304687662">"Tapeta"</string>
diff --git a/core/res/res/values-pt-rPT/strings.xml b/core/res/res/values-pt-rPT/strings.xml
index 3a8759a..e272223 100644
--- a/core/res/res/values-pt-rPT/strings.xml
+++ b/core/res/res/values-pt-rPT/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Permite à aplicação controlar o vibrador."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"controlar lanterna"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Permite à aplicação controlar a lanterna."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"aceder a dispositivos USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Permite à aplicação aceder a dispositivos USB."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"gerir preferências e permissões para dispositivos USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Permite à aplicação gerir as preferências e permissões para dispositivos USB."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"testar hardware"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Permite à aplicação controlar vários periféricos para fins de teste de hardware."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"marcar números de telefone directamente"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Permite a uma aplicação ligar e desligar de pontos de acesso de Wi-Fi, bem como efectuar alterações a redes Wi-Fi configuradas."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"permitir recepção Multicast Wi-Fi"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Permite que uma aplicação receba pacotes não enviados directamente para o dispositivo. Esta opção pode ser útil para descobrir serviços oferecidos na vizinhança. Utiliza mais energia do que o modo não multicast."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"ver estado do WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Permite a uma aplicação ver as informações acerca do estado do Wi-Fi."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"alterar estado do WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Permite a uma aplicação ligar-se e desligar-se da rede WiMAX."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"administração de Bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Permite a uma aplicação configurar o telefone Bluetooth local, bem como descobrir e emparelhar com dispositivos remotos."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"criar ligações Bluetooth"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Utilizar por predefinição para esta acção."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Limpar predefinição em Definições iniciais &gt; Aplicações &gt; Gerir aplicações."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Seleccionar uma acção"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Selecione uma aplicação para o dispositivo USB"</string>
     <string name="noApplications" msgid="1691104391758345586">"Nenhuma aplicação pode efectuar esta acção."</string>
     <string name="aerr_title" msgid="653922989522758100">"Lamentamos."</string>
     <string name="aerr_application" msgid="4683614104336409186">"A aplicação <xliff:g id="APPLICATION">%1$s</xliff:g> (processo <xliff:g id="PROCESS">%2$s</xliff:g>) parou de forma inesperada. Tente novamente."</string>
diff --git a/core/res/res/values-pt/strings.xml b/core/res/res/values-pt/strings.xml
index 5926941..726a64e 100644
--- a/core/res/res/values-pt/strings.xml
+++ b/core/res/res/values-pt/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Permite que o aplicativo controle o vibrador."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"controlar lanterna"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Permite que o aplicativo controle a lanterna."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"acessar dispositivos USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Permitir que o aplicativo acesse dispositivos USB."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"gerenciar preferências e permissões de aplicativos USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Permite que o aplicativo gerencie as preferências e as permissões de aplicativos USB."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"testar hardware"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Permite que o aplicativo controle diversos periféricos para teste do hardware."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"chamar diretamente os números de telefone"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Permite que um aplicativo se conecte e desconecte dos pontos de acesso Wi-Fi e faça alterações nas redes Wi-Fi configuradas."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"permitir recebimento de multicast Wi-Fi"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Permite que um aplicativo receba pacotes não endereçados diretamente para o seu aparelho. Isso pode ser útil ao detectar os serviços oferecidos nas proximidades. Ele consome mais energia do que o modo não-multicast."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"visualizar estado do WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Permite que um aplicativo veja as informações sobre o estado do WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"alterar estado do WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Permite que um aplicativo seja conectado e desconectado à uma rede WiMAX."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"administração de Bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Permite que um aplicativo configure o telefone Bluetooth local, descubra e pareie com dispositivos remotos."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"criar conexões Bluetooth"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Usar como padrão para esta ação."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Limpar o padrão em Configurações da página inicial &gt; Aplicativos &gt; Gerenciar aplicativos."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Selecionar uma ação"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Selecione um aplicativo para o dispositivo USB"</string>
     <string name="noApplications" msgid="1691104391758345586">"Nenhum aplicativo pode realizar esta ação."</string>
     <string name="aerr_title" msgid="653922989522758100">"Desculpe!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"O aplicativo <xliff:g id="APPLICATION">%1$s</xliff:g> (processo <xliff:g id="PROCESS">%2$s</xliff:g>) parou inesperadamente. Tente novamente."</string>
diff --git a/core/res/res/values-rm/strings.xml b/core/res/res/values-rm/strings.xml
index de4b04b..090661b5 100644
--- a/core/res/res/values-rm/strings.xml
+++ b/core/res/res/values-rm/strings.xml
@@ -336,8 +336,10 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Permetta a l\'applicaziun da controllar la vibraziun."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"controllar la glischina"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Permetta a l\'applicaziun da controllar la glischina."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"acceder ad apparats USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Permetta a l\'applicaziun dad acceder als apparats periferics USB."</string>
+    <!-- no translation found for permlab_manageUsb (1113453430645402723) -->
+    <skip />
+    <!-- no translation found for permdesc_manageUsb (6148489202092166164) -->
+    <skip />
     <string name="permlab_hardware_test" msgid="4148290860400659146">"testar la hardware"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Permetta ad ina applicaziun da controllar differents apparats periferics per motivs da test da hardware."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"telefonar directamain a numers da telefon"</string>
@@ -400,6 +402,14 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"\"Permetta ad ina applicaziun da stabilir ina connexiun a puncts d\'access WLAN, da sa deconnectar da quels e da modifitgar ils parameters da raits WLAN configuradas.\""</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"permetter la recepziun da multicast WLAN"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Permetta ad ina applicaziun da retschaiver pachets da datas che n\'èn betg adressads directamain a Voss apparat. Quai po esser nizzaivel per tschertgar servetschs che vegnan mess a disposiziun en il conturn. Consumescha dapli energia ch\'il modus betg-multicast."</string>
+    <!-- no translation found for permlab_accessWimaxState (2800410363171809280) -->
+    <skip />
+    <!-- no translation found for permdesc_accessWimaxState (8298035866227524023) -->
+    <skip />
+    <!-- no translation found for permlab_changeWimaxState (340465839241528618) -->
+    <skip />
+    <!-- no translation found for permdesc_changeWimaxState (474918005058989421) -->
+    <skip />
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"administraziun bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"\"Permetta ad ina applicaziun da configurar il telefon bluetooth local, dad identifitgar apparats periferics a distanza e d\'als associar cun il telefon.\""</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"stabilir connexiuns bluetooth"</string>
@@ -745,6 +755,8 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Utilisar questa applicaziun sco standard per questa acziun."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Stizzar ils parameters da standard en Parameters da la pagina da partenza &gt; Applicaziuns &gt; Administrar las applicaziuns."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Tscherner ina acziun"</string>
+    <!-- no translation found for chooseUsbActivity (7892597146032121735) -->
+    <skip />
     <string name="noApplications" msgid="1691104391758345586">"Nagina applicaziun po exequir questa acziun."</string>
     <string name="aerr_title" msgid="653922989522758100">"Perstgisai!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"L\'applicaziun <xliff:g id="APPLICATION">%1$s</xliff:g> (process <xliff:g id="PROCESS">%2$s</xliff:g>) è vegnida serrada nunspetgadamain. Empruvai anc ina giada."</string>
diff --git a/core/res/res/values-ro/strings.xml b/core/res/res/values-ro/strings.xml
index c58e2fb..7b50b2e 100644
--- a/core/res/res/values-ro/strings.xml
+++ b/core/res/res/values-ro/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Permite aplicaţiei să controleze mecanismul de vibrare."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"control lanternă"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Permite aplicaţiei să controleze lanterna."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"accesare dispozitive USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Permite aplicaţiei să acceseze dispozitive USB."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"gestionaţi preferinţele şi permisiunile pentru dispozitivele USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Permite aplicaţiei să gestioneze preferinţele şi permisiunile pentru dispozitivele USB."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"testare hardware"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Permite aplicaţiei să controleze diverse periferice în scopul testării componentelor hardware."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"apelare directă numere de telefon"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Permite unei aplicaţii să se conecteze la şi să se deconecteze de la punctele de acces Wi-Fi, precum şi să efectueze modificări în reţelele Wi-Fi configurate."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"permitere recepţionare difuzare multiplă Wi-Fi"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Permite unei aplicaţii să primească pachete care nu sunt direct adresate dispozitivului dvs. Această permisiune poate fi utilă la descoperirea serviciilor oferite în apropiere. Consumă mai multă energie decât modul fără difuzare multiplă."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"vizualizaţi starea WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Permite unei aplicaţii să vizualizeze informaţiile despre starea WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"schimbaţi starea WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Permite unei aplicaţii să se conecteze şi să se deconecteze de la reţeaua WiMAX."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"administrare bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Permite unei aplicaţii să configureze telefonul Bluetooth local, să descopere şi să se asocieze cu dispozitive la distanţă."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"creare conexiuni Bluetooth"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Se utilizează în mod prestabilit pentru această acţiune."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Ştergeţi setările prestabilite din Setări pagină de pornire &gt; Aplicaţii &gt; Gestionare aplicaţii."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Selectaţi o acţiune"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Selectaţi o aplicaţie pentru dispozitivul USB"</string>
     <string name="noApplications" msgid="1691104391758345586">"Această acţiune nu poate fi efectuată de nicio aplicaţie."</string>
     <string name="aerr_title" msgid="653922989522758100">"Ne pare rău!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"Aplicaţia <xliff:g id="APPLICATION">%1$s</xliff:g> (procesul <xliff:g id="PROCESS">%2$s</xliff:g>) s-a oprit în mod neaşteptat. Încercaţi din nou."</string>
diff --git a/core/res/res/values-ru/strings.xml b/core/res/res/values-ru/strings.xml
index dc095c5..447c856 100644
--- a/core/res/res/values-ru/strings.xml
+++ b/core/res/res/values-ru/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Позволяет приложению управлять виброзвонком."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"управлять вспышкой"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Позволяет приложению управлять вспышкой."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"доступ к USB-устройствам"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Позволяет приложению получать доступ к USB-устройствам."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"управлять настройками и разрешениями для USB-устройств"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Приложение может управлять настройками и разрешениями для USB-устройств."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"проверять аппаратное обеспечение"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Позволяет приложению управлять различными периферийными устройствами для проверки аппаратного обеспечения."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"посылать прямые вызовы на номера телефонов"</string>
@@ -379,7 +379,7 @@
     <string name="permdesc_authenticateAccounts" msgid="4006839406474208874">"Разрешает приложению использовать возможности аутентификации диспетчера аккаунта, в том числе создавать аккаунты, получать и устанавливать пароли для них."</string>
     <string name="permlab_manageAccounts" msgid="4440380488312204365">"управление списком аккаунтов"</string>
     <string name="permdesc_manageAccounts" msgid="8804114016661104517">"Разрешает приложению добавлять и удалять аккаунты и стирать их пароли."</string>
-    <string name="permlab_useCredentials" msgid="6401886092818819856">"использование регистрационных данных аккаунта для аутентификации"</string>
+    <string name="permlab_useCredentials" msgid="6401886092818819856">"использование учетных данных аккаунта для аутентификации"</string>
     <string name="permdesc_useCredentials" msgid="7416570544619546974">"Разрешает приложению запрашивать маркеры аутентификации."</string>
     <string name="permlab_accessNetworkState" msgid="6865575199464405769">"просматривать состояние сети"</string>
     <string name="permdesc_accessNetworkState" msgid="558721128707712766">"Позволяет приложению просматривать состояние всех сетей."</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Позволяет приложению подключаться к точкам доступа Wi-Fi и отключаться от них, а также вносить изменения в конфигурацию сетей Wi-Fi."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"разрешить принимать многоадресный сигнал Wi-Fi"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Разрешает приложению получать пакеты, не адресованные напрямую вашему устройству. Это может быть полезно при поиске находящихся рядом служб. Расход заряда батареи при этом выше, чем при одноадресной передаче."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"получать сведения о состоянии WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Позволяет приложению получать сведения о состоянии WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"изменять состояние WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Позволяет приложению подключаться к сети WiMAX и отключаться от нее."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"управление Bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Позволяет приложению настраивать локальный телефон Bluetooth, обнаруживать и выполнять сопряжение удаленных устройств."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"создавать подключения Bluetooth"</string>
@@ -421,7 +425,7 @@
     <string name="permdesc_readDictionary" msgid="1082972603576360690">"Позволяет приложению считывать любые слова, имена и фразы личного пользования, которые могут храниться в пользовательском словаре."</string>
     <string name="permlab_writeDictionary" msgid="6703109511836343341">"записывать в словарь пользователя"</string>
     <string name="permdesc_writeDictionary" msgid="2241256206524082880">"Позволяет приложению записывать новые слова в словарь пользователя."</string>
-    <string name="permlab_sdcardWrite" product="nosdcard" msgid="85430876310764752">"изменять и удалять содержимое USB-накопителя"</string>
+    <string name="permlab_sdcardWrite" product="nosdcard" msgid="85430876310764752">"изм./удал. содерж. накопителя"</string>
     <string name="permlab_sdcardWrite" product="default" msgid="8079403759001777291">"изменять/удалять содержимое SD-карты"</string>
     <string name="permdesc_sdcardWrite" product="nosdcard" msgid="6594393334785738252">"Разрешает приложению запись на USB-накопитель."</string>
     <string name="permdesc_sdcardWrite" product="default" msgid="6643963204976471878">"Разрешает приложению запись на SD-карту"</string>
@@ -547,13 +551,13 @@
     <string name="lockscreen_screen_locked" msgid="7288443074806832904">"Экран заблокирован."</string>
     <string name="lockscreen_instructions_when_pattern_enabled" msgid="46154051614126049">"Нажмите \"Меню\", чтобы разблокировать экран или вызвать службу экстренной помощи."</string>
     <string name="lockscreen_instructions_when_pattern_disabled" msgid="686260028797158364">"Для разблокировки нажмите \"Меню\"."</string>
-    <string name="lockscreen_pattern_instructions" msgid="7478703254964810302">"Для разблокировки введите графический ключ"</string>
+    <string name="lockscreen_pattern_instructions" msgid="7478703254964810302">"Введите графический ключ"</string>
     <string name="lockscreen_emergency_call" msgid="5347633784401285225">"Экстренный вызов"</string>
     <string name="lockscreen_return_to_call" msgid="5244259785500040021">"Вернуться к вызову"</string>
     <string name="lockscreen_pattern_correct" msgid="9039008650362261237">"Правильно!"</string>
     <string name="lockscreen_pattern_wrong" msgid="4817583279053112312">"Повторите попытку"</string>
     <string name="lockscreen_plugged_in" msgid="613343852842944435">"Идет зарядка (<xliff:g id="NUMBER">%d</xliff:g><xliff:g id="PERCENT">%%</xliff:g>)"</string>
-    <string name="lockscreen_charged" msgid="4938930459620989972">"Заряжена."</string>
+    <string name="lockscreen_charged" msgid="4938930459620989972">"Батарея заряжена"</string>
     <string name="lockscreen_battery_short" msgid="3617549178603354656">"<xliff:g id="NUMBER">%d</xliff:g><xliff:g id="PERCENT">%%</xliff:g>"</string>
     <string name="lockscreen_low_battery" msgid="1482873981919249740">"Подключите зарядное устройство."</string>
     <string name="lockscreen_missing_sim_message_short" msgid="7381499217732227295">"Нет SIM-карты."</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"По умолчанию для этого действия"</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Удалить настройки по умолчанию: главный экран &gt; \"Настройки\" &gt; \"Приложения\" &gt; \"Управление приложениями\"."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Выберите действие"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Выбор приложения для USB-устройства"</string>
     <string name="noApplications" msgid="1691104391758345586">"Это действие не может выполнять ни одно приложение."</string>
     <string name="aerr_title" msgid="653922989522758100">"Ошибка приложения!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"Произошла неожиданная остановка приложения <xliff:g id="APPLICATION">%1$s</xliff:g> (процесс <xliff:g id="PROCESS">%2$s</xliff:g>). Повторите попытку."</string>
@@ -743,7 +748,7 @@
     <string name="anr_application_process" msgid="4185842666452210193">"Приложение <xliff:g id="APPLICATION">%1$s</xliff:g> (в процессе <xliff:g id="PROCESS">%2$s</xliff:g>) не отвечает."</string>
     <string name="anr_process" msgid="1246866008169975783">"Процесс <xliff:g id="PROCESS">%1$s</xliff:g> не отвечает."</string>
     <string name="force_close" msgid="3653416315450806396">"Закрыть"</string>
-    <string name="report" msgid="4060218260984795706">"Отчет"</string>
+    <string name="report" msgid="4060218260984795706">"Отзыв"</string>
     <string name="wait" msgid="7147118217226317732">"Подождать"</string>
     <string name="launch_warning_title" msgid="8323761616052121936">"Приложение перенаправлено"</string>
     <string name="launch_warning_replace" msgid="6202498949970281412">"Приложение <xliff:g id="APP_NAME">%1$s</xliff:g> выполняется."</string>
@@ -834,7 +839,7 @@
     <string name="ext_media_unmountable_notification_title" product="default" msgid="6410723906019100189">"Поврежденная карта SD"</string>
     <string name="ext_media_unmountable_notification_message" product="nosdcard" msgid="529021299294450667">"USB-накопитель поврежден. Попробуйте отформатировать его."</string>
     <string name="ext_media_unmountable_notification_message" product="default" msgid="6902531775948238989">"SD-карта повреждена. Попробуйте отформатировать ее."</string>
-    <string name="ext_media_badremoval_notification_title" product="nosdcard" msgid="1661683031330951073">"USB-накопитель неожиданно отключен"</string>
+    <string name="ext_media_badremoval_notification_title" product="nosdcard" msgid="1661683031330951073">"Накопитель неожиданно отключен"</string>
     <string name="ext_media_badremoval_notification_title" product="default" msgid="6872152882604407837">"Карта SD неожиданно извлечена"</string>
     <string name="ext_media_badremoval_notification_message" product="nosdcard" msgid="4329848819865594241">"Перед извлечением USB-накопителя отключите его во избежание потери данных."</string>
     <string name="ext_media_badremoval_notification_message" product="default" msgid="7260183293747448241">"Перед извлечением карты SD отключите ее во избежание потери данных."</string>
@@ -874,17 +879,17 @@
     <string name="sync_binding_label" msgid="3687969138375092423">"Синхр."</string>
     <string name="accessibility_binding_label" msgid="4148120742096474641">"Спец. возможности"</string>
     <string name="wallpaper_binding_label" msgid="1240087844304687662">"Фоновый рисунок"</string>
-    <string name="chooser_wallpaper" msgid="7873476199295190279">"Изменить фоновый рисунок"</string>
+    <string name="chooser_wallpaper" msgid="7873476199295190279">"Сменить обои"</string>
     <string name="pptp_vpn_description" msgid="2688045385181439401">"Протокол PPTP"</string>
     <string name="l2tp_vpn_description" msgid="3750692169378923304">"Протокол L2TP"</string>
-    <string name="l2tp_ipsec_psk_vpn_description" msgid="3945043564008303239">"L2TP/IPSec VPN (на основе предв. общ. ключа)"</string>
-    <string name="l2tp_ipsec_crt_vpn_description" msgid="5382714073103653577">"L2TP/IPSec VPN (на основе сертификата)"</string>
+    <string name="l2tp_ipsec_psk_vpn_description" msgid="3945043564008303239">"L2TP/IPSec VPN с использованием общего ключа"</string>
+    <string name="l2tp_ipsec_crt_vpn_description" msgid="5382714073103653577">"L2TP/IPSec VPN с использованием сертификатов"</string>
     <string name="upload_file" msgid="2897957172366730416">"Выбрать файл"</string>
     <string name="reset" msgid="2448168080964209908">"Сбросить"</string>
     <string name="submit" msgid="1602335572089911941">"Отправить"</string>
     <string name="description_star" msgid="2654319874908576133">"избранное"</string>
-    <string name="car_mode_disable_notification_title" msgid="3164768212003864316">"Режим громкой связи включен"</string>
-    <string name="car_mode_disable_notification_message" msgid="668663626721675614">"Выберите для выхода из режима громкой связи."</string>
+    <string name="car_mode_disable_notification_title" msgid="3164768212003864316">"Включен режим \"Штурман\""</string>
+    <string name="car_mode_disable_notification_message" msgid="668663626721675614">"Чтобы закрыть приложение, нажмите здесь."</string>
     <string name="tethered_notification_title" msgid="3146694234398202601">"USB-модем или точка доступа Wi-Fi активны"</string>
     <string name="tethered_notification_message" msgid="3067108323903048927">"Нажмите для настройки"</string>
     <string name="throttle_warning_notification_title" msgid="4890894267454867276">"Активная передача данных"</string>
diff --git a/core/res/res/values-sk/strings.xml b/core/res/res/values-sk/strings.xml
index d72c026..a783f0b 100644
--- a/core/res/res/values-sk/strings.xml
+++ b/core/res/res/values-sk/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Umožňuje aplikácii ovládať vibrácie."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"ovládanie kontrolky"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Umožňuje aplikácii ovládať kontrolku."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"prístup k zariadeniam USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Umožní aplikácii prístup k zariadeniam USB."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"spravovať predvoľby a povolenia zariadení USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Povolí aplikácii spravovať predvoľby a povolenia zariadení USB."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"testovanie hardvéru"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Umožňuje aplikácii ovládať rôzne periférie na účely testovania hardvéru."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"priame volanie na telefónne čísla"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Umožňuje aplikácii pripojiť sa k prístupovým bodom Wi-Fi alebo sa od nich odpojiť a uskutočňovať zmeny nakonfigurovaných sietí Wi-Fi."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"Povoliť príjem viacsmerového vysielania Wi-Fi"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Umožňuje aplikácii prijímať pakety, ktoré neboli adresované priamo vášmu zariadeniu. Pomocou tejto možnosti môžete objaviť služby ponúkané vo vašej blízkosti. Spotreba energie je vyššia ako v režime bez viacsmerového vysielania."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"zobraziť stav WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Umožňuje aplikácii zobraziť informácie o stave siete WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"zmeniť stav WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Umožňuje aplikácii pripojiť sa a odpojiť zo siete WiMAX."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"správa rozhrania Bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Umožňuje aplikácii konfigurovať miestny telefón s rozhraním Bluetooth a vyhľadávať a párovať vzdialené zariadenia."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"vytvorenie pripojenia Bluetooth"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Použiť ako predvolené nastavenie pre túto akciu."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Vymazanie predvolených hodnôt v časti Nastavenia plochy &gt; Aplikácie &gt; Správa aplikácií."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Vyberte akciu"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Vyberte aplikáciu pre zariadenia USB"</string>
     <string name="noApplications" msgid="1691104391758345586">"Túto akciu nemôžu vykonávať žiadne aplikácie."</string>
     <string name="aerr_title" msgid="653922989522758100">"Je nám ľúto!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"Aplikácia <xliff:g id="APPLICATION">%1$s</xliff:g> (proces <xliff:g id="PROCESS">%2$s</xliff:g>) bola neočakávane zastavená. Skúste to znova."</string>
diff --git a/core/res/res/values-sl/strings.xml b/core/res/res/values-sl/strings.xml
index 5799fa4..53e155b 100644
--- a/core/res/res/values-sl/strings.xml
+++ b/core/res/res/values-sl/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Programu dovoljuje nadzor vibriranja."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"nadzor svetilke"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Programu dovoljuje nadzor svetilke."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"dostop do naprav USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Programu omogoča dostop do naprav USB."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"upravljanje nastavitev in dovoljenj za naprave USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Omogoči programu upravljanje nastavitev in dovoljenj za naprave USB."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"preskušanje strojne opreme"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Programu dovoljuje nadzor različnih zunanjih naprav za preskušanje strojne opreme."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"neposredno klicanje telefonskih številk"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Programu dovoljuje vzpostavljanje povezave z dostopnimi točkami brezžičnega omrežja in prekinitev povezave z njimi ter spreminjanje konfiguriranih brezžičnih omrežij."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"dovoljevanje sprejema večvrstnega brezžičnega oddajanja"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Programu dovoljuje prejemanje paketov, ki niso naslovljeni neposredno na vašo napravo. To je lahko uporabno, ko odkrivate storitve, ki so dane na voljo v bližini. Poraba je večja od načina delovanja brez večvrstnega oddajanja."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"prikaz stanja omrežja WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Programu omogoča prikaz podatkov o stanju omrežja WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"sprememba stanja omrežja WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Programu omogoča povezovanje v omrežje WiMAX in prekinitev povezave."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"skrbništvo storitve Bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Programu dovoljuje konfiguriranje lokalnega telefona s tehnologijo Bluetooth ter odkrivanje oddaljenih naprav in povezovanje z njimi."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"ustvarjanje povezav Bluetooth"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Privzeta uporaba za to dejanje."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Počistite privzete nastavitve v razdelku Osnovne nastavitve &gt; Programi &gt; Upravljanje programov."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Izberite dejanje"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Izberite program za napravo USB"</string>
     <string name="noApplications" msgid="1691104391758345586">"Tega dejanja ne more izvesti noben program."</string>
     <string name="aerr_title" msgid="653922989522758100">"Oprostite."</string>
     <string name="aerr_application" msgid="4683614104336409186">"Program <xliff:g id="APPLICATION">%1$s</xliff:g> (postopek <xliff:g id="PROCESS">%2$s</xliff:g>) se je nepričakovano ustavil. Poskusite znova."</string>
diff --git a/core/res/res/values-sr/strings.xml b/core/res/res/values-sr/strings.xml
index c21fa1b..767744e 100644
--- a/core/res/res/values-sr/strings.xml
+++ b/core/res/res/values-sr/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Омогућава да апликација контролише вибрације."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"контрола осветљења"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Омогућава да апликација контролише осветљење."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"приступ USB уређајима"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Омогућава апликацији приступ USB уређајима."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"управљање подешавањима и дозволама за USB уређаје"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Омогућава да апликација управља подешавањима и дозволама за USB уређаје."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"тестирање хардвера"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Омогућава да апликација контролише разноврсне периферне уређаје у сврхе тестирања хардвера."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"директно позивање бројева телефона"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Омогућава да се апликација повезује са Wi-Fi приступним тачкама и да прекине везу са њима, као и да уноси промене у конфигурисане Wi-Fi мреже."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"омогућавање пријема вишесмерног Wi-Fi саобраћаја"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Омогућава да апликација прима пакете који нису директно намењени вашем уређају. То може бити корисно при откривању услуга које се нуде у вашој близини. Користи више напајања од режима једносмерног саобраћаја."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"прикажи WiMAX статуса"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Омогућава апликацији преглед информација о WiMAX статусу."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"промени WiMAX статуса"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Омогућава апликацији повезивање и прекид везе са WiMAX мрежом."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"администрирање преко bluetooth-а"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Омогућава да апликација конфигурише локални Bluetooth телефон, као и да открије удаљене уређаје и упари се са њима."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"креирање Bluetooth веза"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Подразумевано користи за ову радњу."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Обришите подразумевана подешавања у оквиру ставки Подешавања почетне странице &gt; Апликације &gt; Управљање апликацијама."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Избор радње"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Избор апликације за USB уређај"</string>
     <string name="noApplications" msgid="1691104391758345586">"Ниједна апликација не може да изврши ову радњу."</string>
     <string name="aerr_title" msgid="653922989522758100">"Жао нам је!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"Апликација <xliff:g id="APPLICATION">%1$s</xliff:g> (процес <xliff:g id="PROCESS">%2$s</xliff:g>) је неочекивано заустављена. Покушајте поново."</string>
diff --git a/core/res/res/values-sv/strings.xml b/core/res/res/values-sv/strings.xml
index 78fe64b..1731567 100644
--- a/core/res/res/values-sv/strings.xml
+++ b/core/res/res/values-sv/strings.xml
@@ -136,7 +136,7 @@
     <string name="shutdown_progress" msgid="2281079257329981203">"Avslutar…"</string>
     <string name="shutdown_confirm" msgid="649792175242821353">"Din telefon stängs av."</string>
     <string name="recent_tasks_title" msgid="3691764623638127888">"Senaste"</string>
-    <string name="no_recent_tasks" msgid="279702952298056674">"Inga nya program."</string>
+    <string name="no_recent_tasks" msgid="279702952298056674">"Inga nya appar."</string>
     <string name="global_actions" msgid="2406416831541615258">"Telefonalternativ"</string>
     <string name="global_action_lock" msgid="2844945191792119712">"Skärmlås"</string>
     <string name="global_action_power_off" msgid="4471879440839879722">"Stäng av"</string>
@@ -191,11 +191,11 @@
     <string name="permdesc_writeSms" msgid="6299398896177548095">"Tillåter att program skriver till SMS-meddelanden som lagrats på din telefon eller SIM-kort. Skadliga program kan radera dina meddelanden."</string>
     <string name="permlab_receiveWapPush" msgid="8258226427716551388">"ta emot WAP"</string>
     <string name="permdesc_receiveWapPush" msgid="5979623826128082171">"Tillåter att program tar emot och bearbetar WAP-meddelanden. Skadliga program kan övervaka dina meddelanden eller ta bort dem utan att visa dem för dig."</string>
-    <string name="permlab_getTasks" msgid="5005277531132573353">"hämta program som körs"</string>
+    <string name="permlab_getTasks" msgid="5005277531132573353">"hämta appar som körs"</string>
     <string name="permdesc_getTasks" msgid="7048711358713443341">"Tillåter att program hämtar information om uppgifter som körs och har körts. Skadliga program kan upptäcka privat information om andra program."</string>
-    <string name="permlab_reorderTasks" msgid="5669588525059921549">"byt ordning på program som körs"</string>
+    <string name="permlab_reorderTasks" msgid="5669588525059921549">"byt ordning på appar som körs"</string>
     <string name="permdesc_reorderTasks" msgid="126252774270522835">"Tillåter att ett program flyttar uppgifter till förgrunden eller bakgrunden. Skadliga program kan tvinga sig till förgrunden utan att du kan styra det."</string>
-    <string name="permlab_setDebugApp" msgid="4339730312925176742">"aktivera felsökning av program"</string>
+    <string name="permlab_setDebugApp" msgid="4339730312925176742">"aktivera felsökning av appar"</string>
     <string name="permdesc_setDebugApp" msgid="5584310661711990702">"Tillåter att ett program aktiverar felsökning för ett annat program. Skadliga program kan använda detta för att avsluta andra program."</string>
     <string name="permlab_changeConfiguration" msgid="8214475779521218295">"ändra dina gränssnittsinställningar"</string>
     <string name="permdesc_changeConfiguration" msgid="3465121501528064399">"Tillåter att ett program ändrar den aktuella konfigurationen, till exempel språk eller övergripande teckenformat."</string>
@@ -203,17 +203,17 @@
     <string name="permdesc_enableCarMode" msgid="5673461159384850628">"Tillåter att ett program aktiverar trafikläge."</string>
     <string name="permlab_killBackgroundProcesses" msgid="8373714752793061963">"avbryt bakgrundsprocesser"</string>
     <string name="permdesc_killBackgroundProcesses" msgid="2908829602869383753">"Tillåter att ett program avslutar bakgrundsprocesser för andra program även om det inte finns för lite ledigt minne."</string>
-    <string name="permlab_forceStopPackages" msgid="1447830113260156236">"framtvinga avslutning av andra program"</string>
+    <string name="permlab_forceStopPackages" msgid="1447830113260156236">"framtvinga avslutning av andra appar"</string>
     <string name="permdesc_forceStopPackages" msgid="7263036616161367402">"Tillåter att ett program framtvingar avslutning av andra program."</string>
-    <string name="permlab_forceBack" msgid="1804196839880393631">"tvinga program att avsluta"</string>
+    <string name="permlab_forceBack" msgid="1804196839880393631">"tvinga appar att avsluta"</string>
     <string name="permdesc_forceBack" msgid="6534109744159919013">"Tillåter att ett program tvingar en aktivitet som finns i förgrunden att avsluta och gå tillbaka. Behövs inte för vanliga program."</string>
     <string name="permlab_dump" msgid="1681799862438954752">"hämta systemets interna status"</string>
     <string name="permdesc_dump" msgid="2198776174276275220">"Tillåter att ett program hämtar systemets interna status. Skadliga program kan hämta privat och skyddad information som de normalt aldrig ska behöva."</string>
     <string name="permlab_shutdown" msgid="7185747824038909016">"avsluta delvis"</string>
     <string name="permdesc_shutdown" msgid="7046500838746291775">"Sätter aktivitetshanteraren i avstängningsläge. Utför inte en fullständig avstängning."</string>
     <string name="permlab_stopAppSwitches" msgid="4138608610717425573">"förhindrar programbyten"</string>
-    <string name="permdesc_stopAppSwitches" msgid="3857886086919033794">"Hindrar att användaren byter till ett annat program."</string>
-    <string name="permlab_runSetActivityWatcher" msgid="7811586187574696296">"övervaka och styra alla program som öppnas"</string>
+    <string name="permdesc_stopAppSwitches" msgid="3857886086919033794">"Hindrar att användaren byter till en annan app."</string>
+    <string name="permlab_runSetActivityWatcher" msgid="7811586187574696296">"övervaka och styra alla appar som öppnas"</string>
     <string name="permdesc_runSetActivityWatcher" msgid="3228701938345388092">"Tillåter att ett program övervakar och styr hur systemet startar aktiviteter. Skadliga program kan bryta systemet helt. Den här behörigheten behövs bara för programmering, aldrig för vanlig telefonanvändning."</string>
     <string name="permlab_broadcastPackageRemoved" msgid="2576333434893532475">"skicka meddelande om borttaget paket"</string>
     <string name="permdesc_broadcastPackageRemoved" msgid="3453286591439891260">"Tillåter att ett program skickar ett meddelande om att ett programpaket har tagits bort. Skadliga program kan använda detta för att avsluta alla andra program som körs."</string>
@@ -244,16 +244,16 @@
     <string name="permlab_bindInputMethod" msgid="3360064620230515776">"binda till en metod för indata"</string>
     <string name="permdesc_bindInputMethod" msgid="3734838321027317228">"Innehavaren tillåts att binda till den översta nivåns gränssnitt för en inmatningsmetod. Ska inte behövas för vanliga program."</string>
     <string name="permlab_bindWallpaper" msgid="8716400279937856462">"binda till en bakgrund"</string>
-    <string name="permdesc_bindWallpaper" msgid="5287754520361915347">"Innehavaren tillåts att binda till den översta nivåns gränssnitt för en bakgrund. Ska inte behövas för vanliga program."</string>
+    <string name="permdesc_bindWallpaper" msgid="5287754520361915347">"Innehavaren tillåts att binda till den översta nivåns gränssnitt för en bakgrund. Ska inte behövas för vanliga appar."</string>
     <string name="permlab_bindDeviceAdmin" msgid="8704986163711455010">"arbeta med en enhetsadministratör"</string>
     <string name="permdesc_bindDeviceAdmin" msgid="8714424333082216979">"Tillåter att innehavaren skickar avsikter till en enhetsadministratör. Vanliga program behöver aldrig göra detta."</string>
     <string name="permlab_setOrientation" msgid="3365947717163866844">"ändra bildskärmens rikting"</string>
     <string name="permdesc_setOrientation" msgid="6335814461615851863">"Tillåter att ett program när som helst ändrar skärmens rotering. Behövs inte för vanliga program."</string>
-    <string name="permlab_signalPersistentProcesses" msgid="4255467255488653854">"skicka Linux-signaler till program"</string>
+    <string name="permlab_signalPersistentProcesses" msgid="4255467255488653854">"skicka Linux-signaler till appar"</string>
     <string name="permdesc_signalPersistentProcesses" msgid="3565530463215015289">"Tillåter att programmet begär att den angivna signalen skickas till alla beständiga processer."</string>
     <string name="permlab_persistentActivity" msgid="8659652042401085862">"se till att programmet alltid körs"</string>
     <string name="permdesc_persistentActivity" msgid="5037199778265006008">"Tillåter att ett program gör vissa delar beständiga så att systemet inte kan använda det för andra program."</string>
-    <string name="permlab_deletePackages" msgid="3343439331576348805">"ta bort program"</string>
+    <string name="permlab_deletePackages" msgid="3343439331576348805">"ta bort appar"</string>
     <string name="permdesc_deletePackages" msgid="3634943677518723314">"Tillåter att ett program tar bort Android-paket. Skadliga program kan använda detta för att ta bort viktiga program."</string>
     <string name="permlab_clearAppUserData" msgid="2192134353540277878">"ta bort de andra programmens uppgifter"</string>
     <string name="permdesc_clearAppUserData" msgid="7546345080434325456">"Tillåter att ett program tar bort användardata."</string>
@@ -261,9 +261,9 @@
     <string name="permdesc_deleteCacheFiles" msgid="2283074077168165971">"Tillåter att ett program raderar cachefiler."</string>
     <string name="permlab_getPackageSize" msgid="4799785352306641460">"mäta telefonens lagringsutrymme"</string>
     <string name="permdesc_getPackageSize" msgid="5557253039670753437">"Tillåter att ett program hämtar kod, data och cachestorlekar"</string>
-    <string name="permlab_installPackages" msgid="335800214119051089">"installera program direkt"</string>
+    <string name="permlab_installPackages" msgid="335800214119051089">"installera appar direkt"</string>
     <string name="permdesc_installPackages" msgid="526669220850066132">"Tillåter att ett program installerar nya eller uppdaterade Android-paket. Skadliga program kan använda detta för att lägga till nya program med godtyckliga och starka behörigheter."</string>
-    <string name="permlab_clearAppCache" msgid="4747698311163766540">"ta bort cacheinformation för alla program"</string>
+    <string name="permlab_clearAppCache" msgid="4747698311163766540">"ta bort cacheinformation för alla appar"</string>
     <string name="permdesc_clearAppCache" msgid="7740465694193671402">"Tillåter att ett program frigör lagringsutrymme i telefonen genom att ta bort filer i programmets katalog för cachelagring. Åtkomst är mycket begränsad, vanligtvis till systemprocesser."</string>
     <string name="permlab_movePackage" msgid="728454979946503926">"Flytta programresurser"</string>
     <string name="permdesc_movePackage" msgid="6323049291923925277">"Tillåter att ett program flyttar programresurser från interna till externa medier och tvärt om."</string>
@@ -273,7 +273,7 @@
     <string name="permdesc_diagnostic" msgid="3121238373951637049">"Tillåter att ett program läser och skriver till en resurs som ägs av diag-gruppen; till exempel filer i /dev. Detta kan eventuellt påverka systemets stabilitet och säkerhet. Detta bör ENDAST används av tillverkaren eller operatören för maskinvaruspecifik diagnostik."</string>
     <string name="permlab_changeComponentState" msgid="79425198834329406">"aktivera eller inaktivera programkomponenter"</string>
     <string name="permdesc_changeComponentState" msgid="4569107043246700630">"Tillåter att ett program ändrar inställningen för om en komponent i ett annat program har aktiverats eller inte. Skadliga program kan använda detta för att inaktivera viktiga telefonfunktioner. Var försiktig med behörigheten, eftersom programkomponenter kan bli oanvändbara, inkonsekventa eller ostabila."</string>
-    <string name="permlab_setPreferredApplications" msgid="3393305202145172005">"ange önskade program"</string>
+    <string name="permlab_setPreferredApplications" msgid="3393305202145172005">"ange önskade appar"</string>
     <string name="permdesc_setPreferredApplications" msgid="760008293501937546">"Tillåter att ett program ändrar dina önskade program. Skadliga program kan utan varning ändra de program som körs och förfalska dina befintliga program så att de samlar privata data från dig."</string>
     <string name="permlab_writeSettings" msgid="1365523497395143704">"ändra globala systeminställningar"</string>
     <string name="permdesc_writeSettings" msgid="838789419871034696">"Tillåter att ett program ändrar systemets inställningar. Skadliga program kan skada systemets konfiguration."</string>
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Tillåter att programmet styr vibratorn."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"styra lampa"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Tillåter att programmet styr lampan."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"åtkomst till USB-enheter"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Tillåter att programmet använder USB-enheter."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"hantera inställningar och behörighet för USB-enheter"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Tillåter att programmet hanterar inställningar och behörigheter för USB-enheter."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"testa maskinvara"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Tillåter att ett program styr kringutrustning i syfte att testa maskinvara."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"ringa telefonnummer direkt"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Tillåter att ett program ansluter till och kopplar från Wi-Fi-åtkomstpunkter och gör ändringar i konfigurerade Wi-Fi-nätverk."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"tillåt Wi-Fi multicast-mottagning"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Tillåter att ett program tar emot paket som inte är adresserade direkt till din enhet. Detta är användbart om du vill upptäcka tillgängliga tjänster i närheten. Det drar mer batteri än om telefonen inte är i multicast-läge."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"visa WiMAX-status"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Gör att en app kan visa information om WiMAX-status."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"ändra WiMAX-status"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Gör att en app kan anslutas till och kopplas ifrån WiMAX-nätverk."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"administrera bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Tillåter att ett program konfigurerar den lokala Bluetooth-telefonen samt upptäcker och parkopplar den med fjärranslutna enheter."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"skapa Bluetooth-anslutningar"</string>
@@ -733,7 +737,8 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Använd som standard för denna åtgärd."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Rensa standardinställning i Startinställningar &gt; Appar &gt; Hantera appar."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Välj en åtgärd"</string>
-    <string name="noApplications" msgid="1691104391758345586">"Inga program kan utföra den här åtgärden."</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Välj ett program för USB-enheten"</string>
+    <string name="noApplications" msgid="1691104391758345586">"Inga appar kan utföra den här åtgärden."</string>
     <string name="aerr_title" msgid="653922989522758100">"Tyvärr!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"Processen <xliff:g id="PROCESS">%2$s</xliff:g> för programmet <xliff:g id="APPLICATION">%1$s</xliff:g> stoppades oväntat. Försök igen."</string>
     <string name="aerr_process" msgid="1551785535966089511">"Processen <xliff:g id="PROCESS">%1$s</xliff:g> avslutades oväntat. Försök igen."</string>
@@ -742,7 +747,7 @@
     <string name="anr_activity_process" msgid="5420826626009561014">"Aktiviteten <xliff:g id="ACTIVITY">%1$s</xliff:g> (i processen <xliff:g id="PROCESS">%2$s</xliff:g>) svarar inte."</string>
     <string name="anr_application_process" msgid="4185842666452210193">"Programmet <xliff:g id="APPLICATION">%1$s</xliff:g> (i processen <xliff:g id="PROCESS">%2$s</xliff:g>) svarar inte."</string>
     <string name="anr_process" msgid="1246866008169975783">"Processen <xliff:g id="PROCESS">%1$s</xliff:g> svarar inte."</string>
-    <string name="force_close" msgid="3653416315450806396">"Tvinga fram en stängning"</string>
+    <string name="force_close" msgid="3653416315450806396">"Tvinga stängning"</string>
     <string name="report" msgid="4060218260984795706">"Rapportera"</string>
     <string name="wait" msgid="7147118217226317732">"Vänta"</string>
     <string name="launch_warning_title" msgid="8323761616052121936">"Programmet omdirigerades"</string>
@@ -752,8 +757,8 @@
     <string name="smv_process" msgid="5120397012047462446">"Processen <xliff:g id="PROCESS">%1$s</xliff:g> har brutit mot sin egen StrictMode-policy."</string>
     <string name="heavy_weight_notification" msgid="9087063985776626166">"<xliff:g id="APP">%1$s</xliff:g> körs"</string>
     <string name="heavy_weight_notification_detail" msgid="2423977499339403402">"Välj om du vill växla till programmet"</string>
-    <string name="heavy_weight_switcher_title" msgid="1135403633766694316">"Vill du byta program?"</string>
-    <string name="heavy_weight_switcher_text" msgid="4592075610079319667">"Ett annat program som körs måste avslutas innan du kan starta ett nytt."</string>
+    <string name="heavy_weight_switcher_title" msgid="1135403633766694316">"Vill du byta app?"</string>
+    <string name="heavy_weight_switcher_text" msgid="4592075610079319667">"En annan app som körs måste avslutas innan du kan starta en ny."</string>
     <string name="old_app_action" msgid="493129172238566282">"Gå tillbaka till <xliff:g id="OLD_APP">%1$s</xliff:g>"</string>
     <string name="old_app_description" msgid="942967900237208466">"Starta inte det nya programmet."</string>
     <string name="new_app_action" msgid="5472756926945440706">"Starta <xliff:g id="OLD_APP">%1$s</xliff:g>"</string>
@@ -782,7 +787,7 @@
     <item quantity="other" msgid="7915895323644292768">"Öppna Wi-Fi-nätverk är tillgängliga"</item>
   </plurals>
     <string name="select_character" msgid="3365550120617701745">"Infoga tecken"</string>
-    <string name="sms_control_default_app_name" msgid="7630529934366549163">"Okänt program"</string>
+    <string name="sms_control_default_app_name" msgid="7630529934366549163">"Okänd app"</string>
     <string name="sms_control_title" msgid="7296612781128917719">"Skickar SMS"</string>
     <string name="sms_control_message" msgid="1289331457999236205">"Flera SMS-meddelanden skickas. Tryck på OK om du vill fortsätta eller på Avbryt om du vill avsluta sändningen."</string>
     <string name="sms_control_yes" msgid="2532062172402615953">"OK"</string>
@@ -809,7 +814,7 @@
     <string name="usb_storage_stop_button_mount" msgid="7060218034900696029">"Inaktivera USB-lagring"</string>
     <string name="usb_storage_stop_error_message" msgid="143881914840412108">"Ett problem uppstod när USB-lagringsplatsen skulle inaktiveras. Kontrollera att USB-värden har demonterats och försök igen."</string>
     <string name="dlg_confirm_kill_storage_users_title" msgid="963039033470478697">"Aktivera USB-lagring"</string>
-    <string name="dlg_confirm_kill_storage_users_text" msgid="3202838234780505886">"Om du aktiverar USB-lagring avbryts några av de program som körs och de kanske inte blir tillgängliga igen förrän du inaktiverar USB-lagring."</string>
+    <string name="dlg_confirm_kill_storage_users_text" msgid="3202838234780505886">"Om du aktiverar USB-lagring avbryts några av de appar som körs och de kanske inte blir tillgängliga igen förrän du inaktiverar USB-lagring."</string>
     <string name="dlg_error_title" msgid="8048999973837339174">"USB-åtgärd misslyckades"</string>
     <string name="dlg_ok" msgid="7376953167039865701">"OK"</string>
     <string name="extmedia_format_title" product="nosdcard" msgid="7980995592595097841">"Formatera USB-enhet"</string>
@@ -849,8 +854,8 @@
     <string name="activity_list_empty" msgid="4168820609403385789">"Inga matchande aktiviteter hittades"</string>
     <string name="permlab_pkgUsageStats" msgid="8787352074326748892">"uppdatera statistik över användning av komponenter"</string>
     <string name="permdesc_pkgUsageStats" msgid="891553695716752835">"Tillåter att samlad komponentstatistik ändras. Används inte av vanliga program."</string>
-    <string name="permlab_copyProtectedData" msgid="1660908117394854464">"Tillåter att innehåll kopieras genom att standardbehållartjänsten startas. Vanliga program behöver aldrig göra detta."</string>
-    <string name="permdesc_copyProtectedData" msgid="537780957633976401">"Tillåter att innehåll kopieras genom att standardbehållartjänsten startas. Vanliga program behöver aldrig göra detta."</string>
+    <string name="permlab_copyProtectedData" msgid="1660908117394854464">"Tillåter att innehåll kopieras genom att standardbehållartjänsten startas. Vanliga appar behöver aldrig göra detta."</string>
+    <string name="permdesc_copyProtectedData" msgid="537780957633976401">"Tillåter att innehåll kopieras genom att standardbehållartjänsten startas. Vanliga appar behöver aldrig göra detta."</string>
     <string name="tutorial_double_tap_to_zoom_message_short" msgid="1311810005957319690">"Peka två gånger för zoomkontroll"</string>
     <string name="gadget_host_error_inflating" msgid="2613287218853846830">"Fel när widgeten expanderades"</string>
     <string name="ime_action_go" msgid="8320845651737369027">"Kör"</string>
@@ -863,7 +868,7 @@
     <string name="create_contact_using" msgid="4947405226788104538">"Skapa kontakt"\n"med <xliff:g id="NUMBER">%s</xliff:g>"</string>
     <string name="accessibility_compound_button_selected" msgid="5612776946036285686">"markerad"</string>
     <string name="accessibility_compound_button_unselected" msgid="8864512895673924091">"inte markerad"</string>
-    <string name="grant_credentials_permission_message_header" msgid="6824538733852821001">"Följande program begär behörighet till konto, både nu och i framtiden."</string>
+    <string name="grant_credentials_permission_message_header" msgid="6824538733852821001">"Följande appar begär behörighet till konto, både nu och i framtiden."</string>
     <string name="grant_credentials_permission_message_footer" msgid="3125211343379376561">"Vill du tillåta den här begäran?"</string>
     <string name="grant_permissions_header_text" msgid="2722567482180797717">"Begäran om åtkomst"</string>
     <string name="allow" msgid="7225948811296386551">"Tillåt"</string>
diff --git a/core/res/res/values-th/strings.xml b/core/res/res/values-th/strings.xml
index e618941..3dad236 100644
--- a/core/res/res/values-th/strings.xml
+++ b/core/res/res/values-th/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"อนุญาตให้แอปพลิเคชันควบคุมการสั่นเตือน"</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"ควบคุมไฟฉาย"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"อนุญาตให้แอปพลิเคชันควบคุมไฟฉาย"</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"เข้าถึงอุปกรณ์ USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"อนุญาตให้แอปพลิเคชันเข้าถึงอุปกรณ์ USB"</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"จัดการค่ากำหนดและการอนุญาตสำหรับอุปกรณ์ USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"อนุญาตให้แอปพลิเคชันจัดการค่ากำหนดและการอนุญาตสำหรับอุปกรณ์ USB"</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"ทดสอบฮาร์ดแวร์"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"อนุญาตให้แอปพลิเคชันควบคุมอุปกรณ์ต่อพ่วงหลายอย่างเพื่อการทดสอบฮาร์ดแวร์"</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"โทรติดต่อหมายเลขโทรศัพท์โดยตรง"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"อนุญาตให้แอปพลิเคชันเชื่อมต่อและตัดการเชื่อมต่อจากจุดเข้าใช้งาน Wi-Fi และเปลี่ยนแปลงเครือข่าย Wi-Fi ที่กำหนดค่าไว้"</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"อนุญาตให้รับมัลติแคสต์ผ่าน Wi-Fi"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"อนุญาตให้แอปพลิเคชันรับแพ็คเก็ตที่ไม่ได้ส่งถึงอุปกรณ์ของคุณโดยตรง วิธีนี้อาจเป็นประโยชน์เมื่อพบบริการที่นำเสนออยู่ใกล้ๆ แต่จะใช้พลังงานมากกว่าโหมดที่ไม่ใช่มัลติแคสต์"</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"ดูสถานะของ WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"อนุญาตให้แอปพลิเคชันดูข้อมูลเกี่ยวกับสถานะของ WiMAX"</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"เปลี่ยนสถานะของ WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"อนุญาตให้แอปพลิเคชันเชื่อมต่อและยกเลิกการเชื่อมต่อกับเครือข่าย WiMAX"</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"การใช้บลูทูธ"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"อนุญาตให้แอปพลิเคชันกำหนดค่าโทรศัพท์บลูทูธในพื้นที่ ตลอดจนค้นหาและจับคู่กับอุปกรณ์ที่อยู่ระยะไกล"</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"สร้างการเชื่อมต่อบลูทูธ"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"ใช้ค่าเริ่มต้นสำหรับการทำงานนี้"</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"ล้างข้อมูลค่าเริ่มต้นในการตั้งค่าหน้าแรก &gt; แอปพลิเคชัน &gt; จัดการแอปพลิเคชัน"</string>
     <string name="chooseActivity" msgid="1009246475582238425">"เลือกการทำงาน"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"เลือกแอปพลิเคชันสำหรับอุปกรณ์ USB"</string>
     <string name="noApplications" msgid="1691104391758345586">"ไม่มีแอปพลิเคชันใดทำงานนี้ได้"</string>
     <string name="aerr_title" msgid="653922989522758100">"ขออภัย!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"แอปพลิเคชัน <xliff:g id="APPLICATION">%1$s</xliff:g> (กระบวนการ <xliff:g id="PROCESS">%2$s</xliff:g> หยุดทำงานโดยไม่คาดหมาย โปรดลองอีกครั้ง"</string>
diff --git a/core/res/res/values-tl/strings.xml b/core/res/res/values-tl/strings.xml
index fd4ede5..762464c 100644
--- a/core/res/res/values-tl/strings.xml
+++ b/core/res/res/values-tl/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Pinapayagan ang application na kontrolin ang vibrator."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"kontrolin ang flashlight"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Pinapayagan ang application na kontrolin ang flashlight."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"i-access ang mga USB device"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Pinapayagan ang application na i-access ang mga USB device."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"pamahalaan ang mga kagustuhan at pahintulot para sa mga USB device"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Pinapayagan ang application na pamahalaan ang mga kagustuhan at pahintulot para sa mga USB device."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"subukan ang hardware"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Pinapayagan ang application na kontrolin ang iba\'t ibang peripheral para sa layunin ng pagsubok ng hardware."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"direktang tawagan ang mga numero ng telepono"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Pinapayagan ang isang application na kumonekta sa at i-disconnect mula sa mga Wi-Fi access point, at magsagawa ng mga pagbabago sa mga na-configure na Wi-Fi network."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"payagan ang pagtanggap ng Wi-Fi Multicast"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Pinapayagan ang isang application na tumanggap ng mga packet na hindi direktang nakatugon sa iyong device. Magiging kapaki-pakinabang ito kapag tumutuklas ng mga serbisyong inaalok sa malapit. Gumagamit ito ng higit pang baterya kaysa sa non-multicast mode."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"tingnan ang katayuan ng WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Pinapayagan ang application na tingnan ang impormasyon tungkol sa katayuan ng WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"baguhin ang katayuan ng WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Pinapayagan ang isang application na makakonekta sa at maalis sa pagkakakonekta mula sa network ng WiMAX."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"pangangasiwa ng bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Pinapayagan ang isang application na i-configure ang lokal na Bluetooth na telepono, at upang tumuklas at mapareha sa mga remote na device."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"lumikha ng mga koneksyon ng Bluetooth"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Gamitin bilang default para sa pagkilos na ito."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"I-clear ang default sa Mga Setting ng Home &gt; Mga Application &gt; Pamahalaan ang mga application."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Pumili ng pagkilos"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Pumili ng application para sa USB device"</string>
     <string name="noApplications" msgid="1691104391758345586">"Walang mga application ang makakapagsagawa ng pagkilos na ito."</string>
     <string name="aerr_title" msgid="653922989522758100">"Paumanhin!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"Hindi inaasahang humito ang <xliff:g id="APPLICATION">%1$s</xliff:g> (proseso <xliff:g id="PROCESS">%2$s</xliff:g>) ng application. Pakisubukang muli."</string>
diff --git a/core/res/res/values-tr/strings.xml b/core/res/res/values-tr/strings.xml
index 0174024..e41112b 100644
--- a/core/res/res/values-tr/strings.xml
+++ b/core/res/res/values-tr/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Uygulamanın titreşimi denetlemesine izin verir."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"flaşı denetle"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Uygulamaların flaş ışığını denetlemesine izin verir."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"USB cihazlarına erişme"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Uygulamaların USB cihazlarına erişimine izin verir"</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"USB cihazları için tercihleri ve izinleri yönet"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Uygulamanın USB cihazları için tercihleri ve izinleri yönetmesine izin verir."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"donanımı test et"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Uygulamanın donanım testi için çeşitli çevre birimlerini denetlemesine izin verir."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"telefon numaralarına doğrudan çağrı yap"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Uygulamaların kablosuz erişim noktalarına bağlanıp bunlarla bağlantısını kesmesine ve yapılandırılmış kablosuz ağlarda değişiklikler yapmasına izin verir."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"Kablosuz Çoklu Yayın alımına izin ver"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Bir uygulamaya doğrudan cihazınıza yönlendirilmemiş paketleri alma izni verir. Yakın yerlerde sunulan hizmetlerin keşfedilmesi sırasında faydalı olabilir. Birden fazla noktaya yayın yapmayan moda göre daha fazla güç harcar."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"WiMAX durumunu görüntüle"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Uygulamanın, WiMAX\'ın durumuyla ilgili bilgileri görüntülemesine izin verir."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"WiMAX durumunu değiştir"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Uygulamanın, WiMAX ağına bağlanmasına veya bağlantısını kesmesine izin verir."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"bluetooth yönetimi"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Uygulamaların yerel Bluetooth telefonunu yapılandırmasına ve uzak cihazları keşfedip bunlar ile eşleşmesine izin verir."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"Bluetooth bağlantıları oluştur"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Varsayılan olarak bu işlem için kullan."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Giriş Ayarları &gt; Uygulamalar &gt; Uygulamaları yönet\'te varsayılanı temizleyin."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"İşlem seç"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"USB cihazı için bir uygulama seçin"</string>
     <string name="noApplications" msgid="1691104391758345586">"Hiçbir uygulama bu işlemi yapamaz."</string>
     <string name="aerr_title" msgid="653922989522758100">"Üzgünüz!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"<xliff:g id="APPLICATION">%1$s</xliff:g> uygulaması (<xliff:g id="PROCESS">%2$s</xliff:g> işlemi) beklenmedik biçimde durdu. Lütfen yeniden deneyin."</string>
@@ -743,7 +748,7 @@
     <string name="anr_application_process" msgid="4185842666452210193">"<xliff:g id="APPLICATION">%1$s</xliff:g> uygulaması (<xliff:g id="PROCESS">%2$s</xliff:g> işleminde) yanıt vermiyor."</string>
     <string name="anr_process" msgid="1246866008169975783">"<xliff:g id="PROCESS">%1$s</xliff:g> işlemi yanıt vermiyor."</string>
     <string name="force_close" msgid="3653416315450806396">"Kapanmaya zorla"</string>
-    <string name="report" msgid="4060218260984795706">"Rapor"</string>
+    <string name="report" msgid="4060218260984795706">"Bildir"</string>
     <string name="wait" msgid="7147118217226317732">"Bekle"</string>
     <string name="launch_warning_title" msgid="8323761616052121936">"Uygulama yönlendirildi"</string>
     <string name="launch_warning_replace" msgid="6202498949970281412">"<xliff:g id="APP_NAME">%1$s</xliff:g> şimdi çalışıyor."</string>
@@ -812,7 +817,7 @@
     <string name="dlg_confirm_kill_storage_users_text" msgid="3202838234780505886">"USB depolama birimini açarsanız, kullanmakta olduğunuz bazı uygulamalar durur ve USB depolama birimi kapatılıncaya kadar kullanılamayabilir."</string>
     <string name="dlg_error_title" msgid="8048999973837339174">"USB işlemi başarısız oldu"</string>
     <string name="dlg_ok" msgid="7376953167039865701">"Tamam"</string>
-    <string name="extmedia_format_title" product="nosdcard" msgid="7980995592595097841">"USB dep br biçimlndr"</string>
+    <string name="extmedia_format_title" product="nosdcard" msgid="7980995592595097841">"USB\'yi biçimlendir"</string>
     <string name="extmedia_format_title" product="default" msgid="8663247929551095854">"SD kartı biçimlendir"</string>
     <string name="extmedia_format_message" product="nosdcard" msgid="8296908079722897772">"USB depolama birimi biçimlendirilsin mi? Depolama biriminde saklanan tüm dosyalar silinir. İşlem geri alınamaz!"</string>
     <string name="extmedia_format_message" product="default" msgid="3621369962433523619">"SD kartı biçimlendirmek istediğinizden emin misiniz? Kartınızdaki tüm veriler yok olacak."</string>
diff --git a/core/res/res/values-uk/strings.xml b/core/res/res/values-uk/strings.xml
index 6a7a12a..cf295ab 100644
--- a/core/res/res/values-uk/strings.xml
+++ b/core/res/res/values-uk/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Дозволяє програмі контролювати вібросигнал."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"контр. блим. світло"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Дозволяє програмі контролювати світловий сигнал."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"отр.дост.до прист.USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Дозволяє програмі отрим. доступ до пристр. USB."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"керувати налаштуваннями та дозволами для пристроїв USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Дозволяє програмі керувати налаштуваннями та дозволами для пристроїв USB."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"тест-ти обладн."</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Дозволяє програмі контрол. різні периферійні пристрої для тестування апаратного забезпечення."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"прямо набирати номери тел."</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Дозволяє програмі підключатися та відключатися від точок доступу Wi-Fi, а також вносити зміни до налаштованих Wi-Fi мереж."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"дозвол. отримання багатоадр. Wi-Fi"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Дозволяє програмі отрим. пакети, які не адрес. безпосер. вашому пристрою. Це може бути корисно під час виявл. пропонованих служб неподалік. Викор. більше потужності, ніж не багатоадресний реж."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"переглядати стан WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Дозволяє програмі переглядати інформацію про стан WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"змінювати стан WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Дозволяє програмі підключатися та відключатися від мережі WiMAX."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"адміністрування bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Дозволяє програмі налашт. локальний телефон із Bluetooth і знаходити та створ. пару з віддаленими пристроями."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"створюв. підключення Bluetooth"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Використ. за умовч. для цієї дії."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Очист. налашт. за умовч. у Дом. налашт. &gt; Програми &gt; Керув. програмами."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Виберіть дію"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Виберіть програму для пристрою USB"</string>
     <string name="noApplications" msgid="1691104391758345586">"Жодна програма не може виконати цю дію."</string>
     <string name="aerr_title" msgid="653922989522758100">"Помилка!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"Програма <xliff:g id="APPLICATION">%1$s</xliff:g> (процес <xliff:g id="PROCESS">%2$s</xliff:g>) несподівано зупинилася. Спробуйте ще."</string>
diff --git a/core/res/res/values-vi/strings.xml b/core/res/res/values-vi/strings.xml
index 28ad8b1..ed660f0 100644
--- a/core/res/res/values-vi/strings.xml
+++ b/core/res/res/values-vi/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"Cho phép ứng dụng kiểm soát bộ rung."</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"kiểm soát đèn nháy"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"Cho phép ứng dụng kiểm soát đèn nháy."</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"truy cập bộ nhớ USB"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"Cho phép ứng dụng truy cập thiết bị USB."</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"quản lý các tùy chọn và quyền dành cho thiết bị USB"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"Cho phép ứng dụng quản lý các tùy chọn và quyền dành cho thiết bị USB."</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"kiểm tra phần cứng"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"Cho phép ứng dụng kiểm soát các thiết bị ngoại vi khác nhau nhằm mục đích kiểm tra phần cứng."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"gọi trực tiếp số điện thoại"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"Cho phép ứng dụng kết nối và ngắt kết nối khỏi điểm truy cập Wi-Fi cũng như thực hiện các thay đổi đối với mạng Wi-Fi đã được định cấu hình."</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"cho phép thu tín hiệu Wi-Fi Đa hướng"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"Cho phép ứng dụng nhận các gói không được gửi trực tiếp đến thiết bị của bạn. Quyền này có thể hữu ích khi phát hiện các dịch vụ được cung cấp gần đó. Thiết bị của bạn sử dụng nhiều năng lượng hơn chế độ không phát đa hướng."</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"xem trạng thái WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"Cho phép ứng dụng xem thông tin về trạng thái của WiMAX."</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"thay đổi trạng thái WiMAX"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"Cho phép ứng dụng kết nối và ngắt kết nối khỏi mạng WiMAX."</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"quản trị bluetooth"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"Cho phép ứng dụng định cấu hình điện thoại Bluetooth nội hạt cũng như phát hiện và ghép nối với các thiết bị từ xa."</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"tạo kết nối Bluetooth"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"Sử dụng theo mặc định đối với tác vụ này."</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"Xoá mặc định trong Cài đặt Màn hình trang chủ &gt; Ứng dụng&gt; Quản lý ứng dụng."</string>
     <string name="chooseActivity" msgid="1009246475582238425">"Chọn tác vụ"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"Chọn ứng dụng cho thiết bị USB"</string>
     <string name="noApplications" msgid="1691104391758345586">"Không ứng dụng nào có thể thực hiện tác vụ này."</string>
     <string name="aerr_title" msgid="653922989522758100">"Rất tiếc!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"Ứng dụng <xliff:g id="APPLICATION">%1$s</xliff:g> (quá trình <xliff:g id="PROCESS">%2$s</xliff:g>) đã dừng đột ngột. Vui lòng thử lại."</string>
diff --git a/core/res/res/values-zh-rCN/strings.xml b/core/res/res/values-zh-rCN/strings.xml
index 6832787..432fe4b 100644
--- a/core/res/res/values-zh-rCN/strings.xml
+++ b/core/res/res/values-zh-rCN/strings.xml
@@ -335,8 +335,8 @@
     <string name="permdesc_vibrate" msgid="2886677177257789187">"允许应用程序控制振动器。"</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"控制闪光灯"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"允许应用程序控制闪光灯。"</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"访问 USB 设备"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"允许应用程序访问 USB 设备。"</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"管理 USB 设备的偏好设置和权限"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"允许应用程序管理 USB 设备的偏好设置和权限。"</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"测试硬件"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"允许应用程序控制各外围设备以进行硬件测试。"</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"直接拨打电话号码"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"允许应用程序连接到 Wi-Fi 接入点以及与 Wi-Fi 接入点断开连接,并对配置的 Wi-Fi 网络进行更改。"</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"允许接收 Wi-Fi 多播"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"允许应用程序接收并非直接向您的设备发送的数据包。这样在查找附近提供的服务时很有用。这种操作所耗电量大于非多播模式。"</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"查看 WiMAX 状态"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"允许应用程序查看有关 WiMAX 状态的信息。"</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"更改 WiMAX 状态"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"允许应用程序连接到 WiMAX 网络以及从 WiMAX 网络断开连接。"</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"蓝牙管理"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"允许应用程序配置本地蓝牙手机,以及发现远程设备并与其配对。"</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"创建蓝牙连接"</string>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"默认使用此方式发送。"</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"通过主屏幕上的“设置”&gt;“应用程序”&gt;“管理应用程序”清除默认设置。"</string>
     <string name="chooseActivity" msgid="1009246475582238425">"选择一项操作"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"选择适用于 USB 设备的应用程序"</string>
     <string name="noApplications" msgid="1691104391758345586">"没有应用程序可执行此操作。"</string>
     <string name="aerr_title" msgid="653922989522758100">"很抱歉!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"应用程序 <xliff:g id="APPLICATION">%1$s</xliff:g>(进程:<xliff:g id="PROCESS">%2$s</xliff:g>)意外停止,请重试。"</string>
diff --git a/core/res/res/values-zh-rTW/strings.xml b/core/res/res/values-zh-rTW/strings.xml
index 2810fdd..a5827c4 100644
--- a/core/res/res/values-zh-rTW/strings.xml
+++ b/core/res/res/values-zh-rTW/strings.xml
@@ -68,7 +68,7 @@
     <string name="serviceNotProvisioned" msgid="8614830180508686666">"無法提供此服務。"</string>
     <string name="CLIRPermanent" msgid="5460892159398802465">"本機號碼顯示設定無法變更。"</string>
     <string name="RestrictedChangedTitle" msgid="5592189398956187498">"受限存取已變更"</string>
-    <string name="RestrictedOnData" msgid="8653794784690065540">"已封鎖資料傳輸服務。"</string>
+    <string name="RestrictedOnData" msgid="8653794784690065540">"已封鎖數據傳輸服務。"</string>
     <string name="RestrictedOnEmergency" msgid="6581163779072833665">"已封鎖緊急服務。"</string>
     <string name="RestrictedOnNormal" msgid="4953867011389750673">"已封鎖語音服務。"</string>
     <string name="RestrictedOnAllVoice" msgid="1459318899842232234">"已封鎖所有語音服務。"</string>
@@ -226,9 +226,9 @@
     <string name="permlab_setAlwaysFinish" msgid="5342837862439543783">"關閉所有背景程式"</string>
     <string name="permdesc_setAlwaysFinish" msgid="8773936403987091620">"允許應用程式控制哪些活動在被移到背景執行時,儘速結束。一般應用程式不需要此功能。"</string>
     <string name="permlab_batteryStats" msgid="7863923071360031652">"編輯電池狀態"</string>
-    <string name="permdesc_batteryStats" msgid="5847319823772230560">"允許修改電池狀態。一般應用程式不會使用此功能。"</string>
+    <string name="permdesc_batteryStats" msgid="5847319823772230560">"允修改收集到的電池用量統計資料。一般應用程式不應使用這項功能。"</string>
     <string name="permlab_backup" msgid="470013022865453920">"控制系統備份與還原"</string>
-    <string name="permdesc_backup" msgid="4837493065154256525">"允許應用程式控制系統備份與還原機制 (不建議一般應用程式使用)。"</string>
+    <string name="permdesc_backup" msgid="4837493065154256525">"允許應用程式控制系統的備份與還原機制。一般應用程式不應使用這項功能。"</string>
     <string name="permlab_internalSystemWindow" msgid="2148563628140193231">"顯示未授權視窗"</string>
     <string name="permdesc_internalSystemWindow" msgid="5895082268284998469">"允許內部系統使用介面建立視窗。一般應用程式不會使用此功能。"</string>
     <string name="permlab_systemAlertWindow" msgid="3372321942941168324">"顯示系統警示"</string>
@@ -248,11 +248,11 @@
     <string name="permlab_bindDeviceAdmin" msgid="8704986163711455010">"與裝置管理員互動"</string>
     <string name="permdesc_bindDeviceAdmin" msgid="8714424333082216979">"允許應用程式將調用請求 (intent) 傳送至裝置管理員;一般應用程式不需使用此選項。"</string>
     <string name="permlab_setOrientation" msgid="3365947717163866844">"變更螢幕顯示方向"</string>
-    <string name="permdesc_setOrientation" msgid="6335814461615851863">"允許應用程式隨時變更螢幕顯示方向。一般應用程式不需要此功能。"</string>
+    <string name="permdesc_setOrientation" msgid="6335814461615851863">"允許應用程式可隨時變更螢幕旋轉方向。一般應用不應使用這項功能。"</string>
     <string name="permlab_signalPersistentProcesses" msgid="4255467255488653854">"傳送 Linux 訊號到應用程式"</string>
     <string name="permdesc_signalPersistentProcesses" msgid="3565530463215015289">"允許應用程式要求將支援的訊號傳送到所有持續的程序。"</string>
     <string name="permlab_persistentActivity" msgid="8659652042401085862">"設定應用程式持續執行"</string>
-    <string name="permdesc_persistentActivity" msgid="5037199778265006008">"允許應用程式持續執行,避免系統將它應用到其他程式。"</string>
+    <string name="permdesc_persistentActivity" msgid="5037199778265006008">"允許應用程式部分持續執行,避免系統將它用於其他應用程式。"</string>
     <string name="permlab_deletePackages" msgid="3343439331576348805">"刪除應用程式"</string>
     <string name="permdesc_deletePackages" msgid="3634943677518723314">"允許應用程式刪除 Android 程式。請注意:惡意程式可能利用此功能刪除重要應用程式。"</string>
     <string name="permlab_clearAppUserData" msgid="2192134353540277878">"刪除其他應用程式資料"</string>
@@ -310,7 +310,7 @@
     <string name="permlab_modifyAudioSettings" msgid="6095859937069146086">"變更音訊設定"</string>
     <string name="permdesc_modifyAudioSettings" msgid="5793461287365991922">"允許應用程式編輯全域音訊設定,例如音量與路由。"</string>
     <string name="permlab_recordAudio" msgid="3876049771427466323">"錄製音訊"</string>
-    <string name="permdesc_recordAudio" msgid="6493228261176552356">"允許應用程式存取音訊錄製路徑。"</string>
+    <string name="permdesc_recordAudio" msgid="6493228261176552356">"允許應用程式存取錄音檔路徑。"</string>
     <string name="permlab_camera" msgid="3616391919559751192">"拍照和拍攝影片"</string>
     <string name="permdesc_camera" msgid="6004878235852154239">"允許應用程式使用相機拍照和錄影,此功能可讓應用程式隨時透過相機收集圖片。"</string>
     <string name="permlab_brick" msgid="8337817093326370537">"永久停用電話"</string>
@@ -321,34 +321,34 @@
     <string name="permdesc_mount_unmount_filesystems" msgid="6253263792535859767">"允許應用程式掛載/卸載抽取式儲存設備的檔案系統。"</string>
     <string name="permlab_mount_format_filesystems" msgid="5523285143576718981">"將外接式儲存裝置格式化"</string>
     <string name="permdesc_mount_format_filesystems" msgid="574060044906047386">"允許應用程式將可移除式儲存裝置格式化。"</string>
-    <string name="permlab_asec_access" msgid="3411338632002193846">"取得內存空間的資訊"</string>
-    <string name="permdesc_asec_access" msgid="8820326551687285439">"允許應用程式取得內存空間的資訊。"</string>
-    <string name="permlab_asec_create" msgid="6414757234789336327">"建立內存空間"</string>
-    <string name="permdesc_asec_create" msgid="2621346764995731250">"允許應用程式建立內存空間。"</string>
-    <string name="permlab_asec_destroy" msgid="526928328301618022">"銷毀內存空間"</string>
-    <string name="permdesc_asec_destroy" msgid="2746706889208066256">"允許應用程式銷毀內存空間。"</string>
-    <string name="permlab_asec_mount_unmount" msgid="2456287623689029744">"掛接/卸載內存空間"</string>
-    <string name="permdesc_asec_mount_unmount" msgid="5934375590189368200">"允許應用程式掛接/卸載內存空間。"</string>
-    <string name="permlab_asec_rename" msgid="7496633954080472417">"重新命名內存空間"</string>
-    <string name="permdesc_asec_rename" msgid="2152829985238876790">"允許應用程式重新命名內存空間。"</string>
+    <string name="permlab_asec_access" msgid="3411338632002193846">"取得內部儲存空間的資訊"</string>
+    <string name="permdesc_asec_access" msgid="8820326551687285439">"允許應用程式取得內部儲存空間的資訊。"</string>
+    <string name="permlab_asec_create" msgid="6414757234789336327">"建立內部儲存空間"</string>
+    <string name="permdesc_asec_create" msgid="2621346764995731250">"允許應用程式建立內部儲存空間。"</string>
+    <string name="permlab_asec_destroy" msgid="526928328301618022">"銷毀內部儲存空間"</string>
+    <string name="permdesc_asec_destroy" msgid="2746706889208066256">"允許應用程式銷毀內部儲存空間。"</string>
+    <string name="permlab_asec_mount_unmount" msgid="2456287623689029744">"掛接/卸載內部儲存空間"</string>
+    <string name="permdesc_asec_mount_unmount" msgid="5934375590189368200">"允許應用程式掛接/卸載內部儲存空間。"</string>
+    <string name="permlab_asec_rename" msgid="7496633954080472417">"重新命名內部儲存空間"</string>
+    <string name="permdesc_asec_rename" msgid="2152829985238876790">"允許應用程式重新命名內部儲存空間。"</string>
     <string name="permlab_vibrate" msgid="7768356019980849603">"控制震動"</string>
     <string name="permdesc_vibrate" msgid="2886677177257789187">"允許應用程式控制震動。"</string>
     <string name="permlab_flashlight" msgid="2155920810121984215">"控制閃光燈"</string>
     <string name="permdesc_flashlight" msgid="6433045942283802309">"允許應用程式控制閃光燈。"</string>
-    <string name="permlab_accessUsb" msgid="7362327818655760496">"存取 USB 裝置"</string>
-    <string name="permdesc_accessUsb" msgid="2414271762914049292">"允許應用程式存取 USB 裝置。"</string>
+    <string name="permlab_manageUsb" msgid="1113453430645402723">"管理 USB 裝置的偏好設定和權限"</string>
+    <string name="permdesc_manageUsb" msgid="6148489202092166164">"允許應用程式管理 USB 裝置的偏好設定和權限。"</string>
     <string name="permlab_hardware_test" msgid="4148290860400659146">"測試硬體"</string>
     <string name="permdesc_hardware_test" msgid="3668894686500081699">"允許應用程式控制各種週邊設備,以供測試用。"</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"直接撥打電話號碼"</string>
     <string name="permdesc_callPhone" msgid="3369867353692722456">"允許應用程式自行撥打電話。請注意:惡意程式可能任意撥打電話,造成預期外的支出。但此選項並不允許應用程式撥打緊急電話號碼。"</string>
     <string name="permlab_callPrivileged" msgid="4198349211108497879">"直接撥打任何電話號碼"</string>
-    <string name="permdesc_callPrivileged" msgid="244405067160028452">"允許應用程式自行撥打任何電話號碼,包括緊急電話號碼。請注意:惡意程式可能利用此功能濫用緊急服務,撥打不必要或違法的電話。"</string>
+    <string name="permdesc_callPrivileged" msgid="244405067160028452">"允許應用程式自行撥打任何電話號碼,包括緊急電話號碼。請注意:惡意應用程式可能會利用此權限,向緊急服務撥打騷擾甚至非法電話。"</string>
     <string name="permlab_performCdmaProvisioning" msgid="5604848095315421425">"直接起始 CDMA 手機設定程序"</string>
     <string name="permdesc_performCdmaProvisioning" msgid="6457447676108355905">"允許應用程式啟動 CDMA 服務 (惡意應用程式可能會在非必要的情況下啟動 CDMA 服務)。"</string>
     <string name="permlab_locationUpdates" msgid="7785408253364335740">"控制位置更新通知"</string>
-    <string name="permdesc_locationUpdates" msgid="2300018303720930256">"允許啟用/停用無線通訊位置更新通知。一般應用程式不會使用此功能。"</string>
+    <string name="permdesc_locationUpdates" msgid="2300018303720930256">"允許從廣播中啟用/停用位置資訊更新通知。一般應用程式不應使用這項功能。"</string>
     <string name="permlab_checkinProperties" msgid="7855259461268734914">"存取登機選項"</string>
-    <string name="permdesc_checkinProperties" msgid="7150307006141883832">"允許讀寫登機服務上傳的資料。一般應用程式不會使用此功能。"</string>
+    <string name="permdesc_checkinProperties" msgid="7150307006141883832">"允許讀取/寫入由登錄服務所更新的屬性存取權。一般應用程式不應使用這項功能。"</string>
     <string name="permlab_bindGadget" msgid="776905339015863471">"選擇小工具"</string>
     <string name="permdesc_bindGadget" msgid="2098697834497452046">"允許應用程式告知系統哪個應用程式可以使用哪些小工具。開啟此權限後,應用程式會讓其他程式使用個人資料,但一般應用程式不適合使用此功能。"</string>
     <string name="permlab_modifyPhoneState" msgid="8423923777659292228">"修改手機狀態"</string>
@@ -389,8 +389,8 @@
     <string name="permdesc_writeApnSettings" msgid="7443433457842966680">"允許應用程式修改 APN 設定,例如:Proxy 及 APN 的連接埠。"</string>
     <string name="permlab_changeNetworkState" msgid="958884291454327309">"變更網路連線"</string>
     <string name="permdesc_changeNetworkState" msgid="4199958910396387075">"允許應用程式變更網路連線狀態。"</string>
-    <string name="permlab_changeTetherState" msgid="2702121155761140799">"變更數據連線"</string>
-    <string name="permdesc_changeTetherState" msgid="8905815579146349568">"允許應用程式變更數據網路連線狀態。"</string>
+    <string name="permlab_changeTetherState" msgid="2702121155761140799">"變更網路共用設定"</string>
+    <string name="permdesc_changeTetherState" msgid="8905815579146349568">"允許應用程式變更已共用網路的連線狀態。"</string>
     <string name="permlab_changeBackgroundDataSetting" msgid="1400666012671648741">"變更背景資料使用設定"</string>
     <string name="permdesc_changeBackgroundDataSetting" msgid="1001482853266638864">"允許應用程式變更背景資料使用設定。"</string>
     <string name="permlab_accessWifiState" msgid="8100926650211034400">"檢視 Wi-Fi 狀態"</string>
@@ -399,6 +399,10 @@
     <string name="permdesc_changeWifiState" msgid="2950383153656873267">"允許應用程式與 Wi-Fi 存取點連線或中斷連線,並可變更 Wi-Fi 網路設定。"</string>
     <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"允許接收 Wi-Fi 多點傳播封包"</string>
     <string name="permdesc_changeWifiMulticastState" msgid="8199464507656067553">"允許應用程式接收並非指定傳送給您裝置的封包,這在您發現附近有服務可使用時很有用,但消耗的電力比非多點傳播模式還要多。"</string>
+    <string name="permlab_accessWimaxState" msgid="2800410363171809280">"查看 WiMAX 狀態"</string>
+    <string name="permdesc_accessWimaxState" msgid="8298035866227524023">"允許應用程式查看 WiMAX 連線狀態相關資訊。"</string>
+    <string name="permlab_changeWimaxState" msgid="340465839241528618">"變更 WiMAX 狀態"</string>
+    <string name="permdesc_changeWimaxState" msgid="474918005058989421">"允許應用程式建立或中斷 WiMAX 網路連線。"</string>
     <string name="permlab_bluetoothAdmin" msgid="1092209628459341292">"藍牙管理"</string>
     <string name="permdesc_bluetoothAdmin" msgid="7256289774667054555">"允許應用程式設定本機藍牙電話,以及偵測與配對其他遠端裝置。"</string>
     <string name="permlab_bluetooth" msgid="8361038707857018732">"建立藍牙連線"</string>
@@ -618,15 +622,15 @@
     <string name="beforeOneMonthDurationPast" msgid="909134546836499826">"1 個月前"</string>
   <plurals name="num_seconds_ago">
     <item quantity="one" msgid="4869870056547896011">"1 秒以前"</item>
-    <item quantity="other" msgid="3903706804349556379">"<xliff:g id="COUNT">%d</xliff:g> 秒以前"</item>
+    <item quantity="other" msgid="3903706804349556379">"<xliff:g id="COUNT">%d</xliff:g> 秒前"</item>
   </plurals>
   <plurals name="num_minutes_ago">
     <item quantity="one" msgid="3306787433088810191">"1 分鐘以前"</item>
-    <item quantity="other" msgid="2176942008915455116">"<xliff:g id="COUNT">%d</xliff:g> 分鐘以前"</item>
+    <item quantity="other" msgid="2176942008915455116">"<xliff:g id="COUNT">%d</xliff:g> 分鐘前"</item>
   </plurals>
   <plurals name="num_hours_ago">
     <item quantity="one" msgid="9150797944610821849">"1 小時以前"</item>
-    <item quantity="other" msgid="2467273239587587569">"<xliff:g id="COUNT">%d</xliff:g> 小時以前"</item>
+    <item quantity="other" msgid="2467273239587587569">"<xliff:g id="COUNT">%d</xliff:g> 小時前"</item>
   </plurals>
   <plurals name="last_num_days">
     <item quantity="other" msgid="3069992808164318268">"最近 <xliff:g id="COUNT">%d</xliff:g> 天"</item>
@@ -635,7 +639,7 @@
     <string name="older" msgid="5211975022815554840">"較舊"</string>
   <plurals name="num_days_ago">
     <item quantity="one" msgid="861358534398115820">"昨天"</item>
-    <item quantity="other" msgid="2479586466153314633">"<xliff:g id="COUNT">%d</xliff:g> 天以前"</item>
+    <item quantity="other" msgid="2479586466153314633">"<xliff:g id="COUNT">%d</xliff:g> 天前"</item>
   </plurals>
   <plurals name="in_num_seconds">
     <item quantity="one" msgid="2729745560954905102">"1 秒內"</item>
@@ -663,11 +667,11 @@
   </plurals>
   <plurals name="abbrev_num_hours_ago">
     <item quantity="one" msgid="4796212039724722116">"1 小時以前"</item>
-    <item quantity="other" msgid="6889970745748538901">"<xliff:g id="COUNT">%d</xliff:g> 小時以前"</item>
+    <item quantity="other" msgid="6889970745748538901">"<xliff:g id="COUNT">%d</xliff:g> 小時前"</item>
   </plurals>
   <plurals name="abbrev_num_days_ago">
     <item quantity="one" msgid="8463161711492680309">"昨天"</item>
-    <item quantity="other" msgid="3453342639616481191">"<xliff:g id="COUNT">%d</xliff:g> 天以前"</item>
+    <item quantity="other" msgid="3453342639616481191">"<xliff:g id="COUNT">%d</xliff:g> 天前"</item>
   </plurals>
   <plurals name="abbrev_in_num_seconds">
     <item quantity="one" msgid="5842225370795066299">"1 秒內"</item>
@@ -733,6 +737,7 @@
     <string name="alwaysUse" msgid="4583018368000610438">"以此為本操作預設值。"</string>
     <string name="clearDefaultHintMsg" msgid="4815455344600932173">"清除首頁設定 (應用程式) 管理應用程式的預設值。"</string>
     <string name="chooseActivity" msgid="1009246475582238425">"選取一項操作"</string>
+    <string name="chooseUsbActivity" msgid="7892597146032121735">"選取要以 USB 裝置存取的應用程式"</string>
     <string name="noApplications" msgid="1691104391758345586">"沒有應用程式可執行此項操作。"</string>
     <string name="aerr_title" msgid="653922989522758100">"很抱歉!"</string>
     <string name="aerr_application" msgid="4683614104336409186">"<xliff:g id="APPLICATION">%1$s</xliff:g> 應用程式 (程序:<xliff:g id="PROCESS">%2$s</xliff:g>) 異常終止。請再試一次。"</string>
@@ -833,14 +838,14 @@
     <string name="ext_media_unmountable_notification_title" product="nosdcard" msgid="2090046769532713563">"USB 儲存裝置已毀損"</string>
     <string name="ext_media_unmountable_notification_title" product="default" msgid="6410723906019100189">"SD 卡已損壞"</string>
     <string name="ext_media_unmountable_notification_message" product="nosdcard" msgid="529021299294450667">"USB 儲存裝置已損壞,您可能必須重新格式化。"</string>
-    <string name="ext_media_unmountable_notification_message" product="default" msgid="6902531775948238989">"SD 卡已毀損,您可能必須予以重新格式化。"</string>
-    <string name="ext_media_badremoval_notification_title" product="nosdcard" msgid="1661683031330951073">"USB 儲存裝置已意外移除"</string>
+    <string name="ext_media_unmountable_notification_message" product="default" msgid="6902531775948238989">"SD 卡已毀損,您可能必須重新格式化。"</string>
+    <string name="ext_media_badremoval_notification_title" product="nosdcard" msgid="1661683031330951073">"USB 儲存裝置未正常移除"</string>
     <string name="ext_media_badremoval_notification_title" product="default" msgid="6872152882604407837">"SD 卡未正常移除"</string>
     <string name="ext_media_badremoval_notification_message" product="nosdcard" msgid="4329848819865594241">"請先卸載 USB 儲存裝置,再將其移除,以免資料遺失。"</string>
     <string name="ext_media_badremoval_notification_message" product="default" msgid="7260183293747448241">"請先卸載 SD 卡,再將其移除,以免資料遺失。"</string>
     <string name="ext_media_safe_unmount_notification_title" product="nosdcard" msgid="3967973893270360230">"USB 儲存裝置已可安全移除"</string>
     <string name="ext_media_safe_unmount_notification_title" product="default" msgid="6729801130790616200">"可安全移除 SD 卡"</string>
-    <string name="ext_media_safe_unmount_notification_message" product="nosdcard" msgid="6142195361606493530">"您可安全移除 USB 儲存裝置了。"</string>
+    <string name="ext_media_safe_unmount_notification_message" product="nosdcard" msgid="6142195361606493530">"您現在可以安全地移除 USB 儲存裝置。"</string>
     <string name="ext_media_safe_unmount_notification_message" product="default" msgid="568841278138377604">"您現在可以安全地移除 SD 卡。"</string>
     <string name="ext_media_nomedia_notification_title" product="nosdcard" msgid="4486377230140227651">"USB 儲存裝置已移除"</string>
     <string name="ext_media_nomedia_notification_title" product="default" msgid="8902518030404381318">"已移除 SD 卡"</string>
@@ -885,7 +890,7 @@
     <string name="description_star" msgid="2654319874908576133">"我的最愛"</string>
     <string name="car_mode_disable_notification_title" msgid="3164768212003864316">"已啟用車用模式"</string>
     <string name="car_mode_disable_notification_message" msgid="668663626721675614">"選取結束車用模式。"</string>
-    <string name="tethered_notification_title" msgid="3146694234398202601">"數據連線或無線基地台已啟用"</string>
+    <string name="tethered_notification_title" msgid="3146694234398202601">"網路共用或無線基地台已啟用"</string>
     <string name="tethered_notification_message" msgid="3067108323903048927">"輕觸以設定"</string>
     <string name="throttle_warning_notification_title" msgid="4890894267454867276">"高行動資料用量"</string>
     <string name="throttle_warning_notification_message" msgid="2609734763845705708">"輕觸即可瞭解更多有關行動資料用量的詳細資訊"</string>
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
old mode 100644
new mode 100755
index 355e681..abc27e2
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -125,6 +125,7 @@
 
     <!-- Regex array of allowable upstream ifaces for tethering - for example if you want
          tethering on a new interface called "foo2" add <item>"foo\\d"</item> to the array -->
+    <!-- Interfaces will be prioritized according to the order listed -->
     <string-array translatable="false" name="config_tether_upstream_regexs">
     </string-array>
 
@@ -399,4 +400,94 @@
     <!-- Do not translate. Defines the slots is Two Digit Number for dialing normally not USSD -->
     <string-array name="config_twoDigitNumberPattern">
     </string-array>
+
+    <!-- The VoiceMail default value is displayed to my own number if it is true -->
+    <bool name="config_telephony_use_own_number_for_voicemail">false</bool>
+
+    <!-- If this value is true, Sms encoded as octet is decoded by utf8 decoder.
+         If false, decoded by Latin decoder. -->
+    <bool name="config_sms_utf8_support">false</bool>
+
+    <!-- If this value is true, The mms content-disposition field is supported correctly.
+         If false, Content-disposition fragments are ignored -->
+    <bool name="config_mms_content_disposition_support">true</bool>
+
+    <!-- If this value is true, the carrier supports sms delivery reports.
+         If false, sms delivery reports are not supported and the preference
+         option to enable/disable delivery reports is removed in the Messaging app. -->
+    <bool name="config_sms_delivery_reports_support">true</bool>
+
+    <!-- If this value is true, the carrier supports mms delivery reports.
+         If false, mms delivery reports are not supported and the preference
+         option to enable/disable delivery reports is removed in the Messaging app. -->
+    <bool name="config_mms_delivery_reports_support">true</bool>
+
+    <!-- If this value is true, the carrier supports mms read reports.
+         If false, mms read reports are not supported and the preference
+         option to enable/disable read reports is removed in the Messaging app. -->
+    <bool name="config_mms_read_reports_support">true</bool>
+
+    <!-- National Language Identifier codes for the following two config items.
+         (from 3GPP TS 23.038 V9.1.1 Table 6.2.1.2.4.1):
+          0  - reserved
+          1  - Turkish
+          2  - Spanish (single shift table only)
+          3  - Portuguese
+          4  - Bengali
+          5  - Gujarati
+          6  - Hindi
+          7  - Kannada
+          8  - Malayalam
+          9  - Oriya
+         10  - Punjabi
+         11  - Tamil
+         12  - Telugu
+         13  - Urdu
+         14+ - reserved -->
+
+    <!-- National language single shift tables to enable for SMS encoding.
+         Decoding is always enabled. 3GPP TS 23.038 states that this feature
+         should not be enabled until a formal request is issued by the relevant
+         national regulatory body. Array elements are codes from the table above.
+         Example 1: devices sold in Turkey must include table 1 to conform with
+           By-Law Number 27230. (http://www.btk.gov.tr/eng/pdf/2009/BY-LAW_SMS.pdf)
+         Example 2: devices sold in India should include tables 4 through 13
+           to enable use of the new Release 9 tables for Indic languages. -->
+    <integer-array name="config_sms_enabled_single_shift_tables"></integer-array>
+
+    <!-- National language locking shift tables to enable for SMS encoding.
+         Decoding is always enabled. 3GPP TS 23.038 states that this feature
+         should not be enabled until a formal request is issued by the relevant
+         national regulatory body. Array elements are codes from the table above.
+         Example 1: devices sold in Turkey must include table 1 after the
+           Turkish Telecommunication Authority requires locking shift encoding
+           to be enabled (est. July 2012). (http://www.btk.gov.tr/eng/pdf/2009/BY-LAW_SMS.pdf)
+           See also: http://www.mobitech.com.tr/tr/ersanozturkblog_en/index.php?entry=entry090223-160014
+         Example 2: devices sold in India should include tables 4 through 13
+         to enable use of the new Release 9 tables for Indic languages. -->
+    <integer-array name="config_sms_enabled_locking_shift_tables"></integer-array>
+
+    <!-- Set and Unsets WiMAX -->
+    <bool name="config_wimaxEnabled">false</bool>
+    <!-- Location of the wimax framwork jar location -->
+    <string name="config_wimaxServiceJarLocation"></string>
+    <!-- Location of the wimax native library locaiton -->
+    <string name="config_wimaxNativeLibLocation"></string>
+    <!-- Name of the wimax manager class -->
+    <string name="config_wimaxManagerClassname"></string>
+    <!-- Name of the wimax service class -->
+    <string name="config_wimaxServiceClassname"></string>
+    <!-- Name of the wimax state tracker clas -->
+    <string name="config_wimaxStateTrackerClassname"></string>
+
+    <!-- Set to true if the RSSI should always display CDMA signal strength
+         even on EVDO -->
+    <bool name="config_alwaysUseCdmaRssi">false</bool>
+
+    <!-- If this value is true, duplicate Source/Destination port fields
+         in WDP header of some carriers OMADM wap push are supported.
+         ex: MSGTYPE-TotalSegments-CurrentSegment
+             -SourcePortDestPort-SourcePortDestPort-OMADM PDU
+         If false, not supported. -->
+    <bool name="config_duplicate_port_omadm_wappush">false</bool>
 </resources>
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index e331f8d..9a88ab3 100755
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -427,6 +427,13 @@
       your messages or delete them without showing them to you.</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_receiveEmergencyBroadcast">receive emergency broadcasts</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_receiveEmergencyBroadcast">Allows application to receive
+      and process emergency broadcast messages. This permission is only available
+      to system applications.</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_sendSms">send SMS messages</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_sendSms">Allows application to send SMS
@@ -927,9 +934,9 @@
         the flashlight.</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_accessUsb">access USB devices</string>
+    <string name="permlab_manageUsb">manage preferences and permissions for USB devices</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_accessUsb">Allows the application to access USB devices.</string>
+    <string name="permdesc_manageUsb">Allows the application to manage preferences and permissions for USB devices.</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_hardware_test">test hardware</string>
@@ -1139,6 +1146,18 @@
       than the non-multicast mode.</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_accessWimaxState">view WiMAX 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_accessWimaxState">Allows an application to view
+      the information about the state of WiMAX.</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_changeWimaxState">change WiMAX 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_changeWimaxState">Allows an application to connect
+      to and disconnect from WiMAX network.</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_bluetoothAdmin">bluetooth administration</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_bluetoothAdmin">Allows an application to configure
@@ -1926,6 +1945,8 @@
     <string name="clearDefaultHintMsg">Clear default in Home Settings &gt; Applications &gt; Manage applications.</string>
     <!-- Default title for the activity chooser, when one is not given. Android allows multiple activities to perform an action.  for example, there may be many ringtone pickers installed.  A dialog is shown to the user allowing him to pick which activity should be used.  This is the title. -->
     <string name="chooseActivity">Select an action</string>
+    <!-- title for the USB activity chooser. -->
+    <string name="chooseUsbActivity">Select an application for the USB device</string>
     <!-- Text to display when there are no activities found to display in the
          activity chooser. See the "Select an action" title. -->
     <string name="noApplications">No applications can perform this action.</string>
diff --git a/core/tests/ConnectivityManagerTest/Android.mk b/core/tests/ConnectivityManagerTest/Android.mk
index a1546fa..56011f7 100644
--- a/core/tests/ConnectivityManagerTest/Android.mk
+++ b/core/tests/ConnectivityManagerTest/Android.mk
@@ -25,6 +25,6 @@
 
 LOCAL_PACKAGE_NAME := ConnectivityManagerTest
 
-#LOCAL_INSTRUMENTATION_FOR := connectivitymanagertest
+LOCAL_CERTIFICATE := platform
 
 include $(BUILD_PACKAGE)
diff --git a/core/tests/ConnectivityManagerTest/AndroidManifest.xml b/core/tests/ConnectivityManagerTest/AndroidManifest.xml
index b116bea..05f8b39 100644
--- a/core/tests/ConnectivityManagerTest/AndroidManifest.xml
+++ b/core/tests/ConnectivityManagerTest/AndroidManifest.xml
@@ -16,7 +16,8 @@
 
 <!-- package name must be unique so suffix with "tests" so package loader doesn't ignore us -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.android.connectivitymanagertest">
+  package="com.android.connectivitymanagertest"
+  android:sharedUserId="com.android.uid.test">
 
     <!-- We add an application tag here just so that we can indicate that
          this package needs to link against the android.test library,
@@ -67,5 +68,9 @@
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
     <uses-permission android:name="android.permission.WRITE_SETTINGS" />
+    <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
     <uses-permission android:name="android.permission.WAKE_LOCK" />
+    <uses-permission android:name="android.permission.DEVICE_POWER" />
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+
 </manifest>
diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerStressTestRunner.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerStressTestRunner.java
index 47f208a..5b76e39 100644
--- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerStressTestRunner.java
+++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerStressTestRunner.java
@@ -19,8 +19,8 @@
 import android.os.Bundle;
 import android.test.InstrumentationTestRunner;
 import android.test.InstrumentationTestSuite;
-import android.util.Log;
 import com.android.connectivitymanagertest.stress.WifiApStress;
+import com.android.connectivitymanagertest.stress.WifiStressTest;
 
 import junit.framework.TestSuite;
 
@@ -34,10 +34,18 @@
  */
 
 public class ConnectivityManagerStressTestRunner extends InstrumentationTestRunner {
+    public int mSoftapIterations = 100;
+    public int mScanIterations = 100;
+    public int mReconnectIterations = 100;
+    public int mSleepTime = 30 * 1000;  // default sleep time is 30 seconds
+    public String mReconnectSsid = "securenetdhcp";
+    public String mReconnectPassword = "androidwifi";
+
     @Override
     public TestSuite getAllTests() {
         TestSuite suite = new InstrumentationTestSuite(this);
         suite.addTestSuite(WifiApStress.class);
+        suite.addTestSuite(WifiStressTest.class);
         return suite;
     }
 
@@ -49,14 +57,46 @@
     @Override
     public void onCreate(Bundle icicle) {
         super.onCreate(icicle);
-        String stressValue = (String) icicle.get("stressnum");
-        if (stressValue != null) {
-            int iteration = Integer.parseInt(stressValue);
+        String valueStr = (String) icicle.get("softap_iterations");
+        if (valueStr != null) {
+            int iteration = Integer.parseInt(valueStr);
             if (iteration > 0) {
-                numStress = iteration;
+                mSoftapIterations = iteration;
+            }
+        }
+
+        String scanIterationStr = (String) icicle.get("scan_iterations");
+        if (scanIterationStr != null) {
+            int scanIteration = Integer.parseInt(scanIterationStr);
+            if (scanIteration > 0) {
+                mScanIterations = scanIteration;
+            }
+        }
+
+        String ssidStr= (String) icicle.get("reconnect_ssid");
+        if (ssidStr != null) {
+            mReconnectSsid = ssidStr;
+        }
+
+        String passwordStr = (String) icicle.get("reconnect_password");
+        if (passwordStr != null) {
+            mReconnectPassword = passwordStr;
+        }
+
+        String reconnectStr = (String) icicle.get("reconnect_iterations");
+        if (reconnectStr != null) {
+            int iteration = Integer.parseInt(reconnectStr);
+            if (iteration > 0) {
+                mReconnectIterations = iteration;
+            }
+        }
+
+        String sleepTimeStr = (String) icicle.get("sleep_time");
+        if (sleepTimeStr != null) {
+            int sleepTime = Integer.parseInt(sleepTimeStr);
+            if (sleepTime > 0) {
+                mSleepTime = 1000 * sleepTime;
             }
         }
     }
-
-    public int numStress = 100;
 }
diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestActivity.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestActivity.java
index 0807706..7aa0afd 100644
--- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestActivity.java
+++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestActivity.java
@@ -24,11 +24,17 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.os.Bundle;
+import android.os.IPowerManager;
+import android.os.PowerManager;
+import android.os.ServiceManager;
+import android.os.SystemClock;
 import android.provider.Settings;
 import android.util.Log;
 import android.view.KeyEvent;
 
+import java.io.IOException;
 import java.io.InputStream;
+import java.net.UnknownHostException;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
@@ -54,7 +60,7 @@
 
     public static final String LOG_TAG = "ConnectivityManagerTestActivity";
     public static final int WAIT_FOR_SCAN_RESULT = 10 * 1000; //10 seconds
-    public static final int WIFI_SCAN_TIMEOUT = 20 * 1000;
+    public static final int WIFI_SCAN_TIMEOUT = 50 * 1000;
     public static final int SHORT_TIMEOUT = 5 * 1000;
     public static final long LONG_TIMEOUT = 50 * 1000;
     public static final int SUCCESS = 0;  // for Wifi tethering state change
@@ -64,6 +70,7 @@
     public ConnectivityReceiver mConnectivityReceiver = null;
     public WifiReceiver mWifiReceiver = null;
     private AccessPointParserHelper mParseHelper = null;
+    public boolean scanResultAvailable = false;
     /*
      * Track network connectivity information
      */
@@ -79,7 +86,7 @@
     public int mWifiState;
     public NetworkInfo mWifiNetworkInfo;
     public String mBssid;
-    public String mPowerSsid = "GoogleGuest"; //Default power SSID
+    public String mPowerSsid = "opennet"; //Default power SSID
     private Context mContext;
 
     /*
@@ -104,7 +111,7 @@
     private class ConnectivityReceiver extends BroadcastReceiver {
         @Override
         public void onReceive(Context context, Intent intent) {
-            Log.v(LOG_TAG, "ConnectivityReceiver: onReceive() is called with " + intent);
+            log("ConnectivityReceiver: onReceive() is called with " + intent);
             String action = intent.getAction();
             if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                 Log.v("ConnectivityReceiver", "onReceive() called with " + intent);
@@ -129,9 +136,9 @@
             mReason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
             mIsFailOver = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
 
-            Log.v(LOG_TAG, "mNetworkInfo: " + mNetworkInfo.toString());
+            log("mNetworkInfo: " + mNetworkInfo.toString());
             if (mOtherNetworkInfo != null) {
-                Log.v(LOG_TAG, "mOtherNetworkInfo: " + mOtherNetworkInfo.toString());
+                log("mOtherNetworkInfo: " + mOtherNetworkInfo.toString());
             }
             recordNetworkState(mNetworkInfo.getType(), mNetworkInfo.getState());
             if (mOtherNetworkInfo != null) {
@@ -151,7 +158,7 @@
             } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                 mWifiNetworkInfo =
                     (NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
-                Log.v(LOG_TAG, "mWifiNetworkInfo: " + mWifiNetworkInfo.toString());
+                log("mWifiNetworkInfo: " + mWifiNetworkInfo.toString());
                 if (mWifiNetworkInfo.getState() == State.CONNECTED) {
                     mBssid = intent.getStringExtra(WifiManager.EXTRA_BSSID);
                 }
@@ -159,7 +166,7 @@
             } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                 mWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
                                                 WifiManager.WIFI_STATE_UNKNOWN);
-                Log.v(LOG_TAG, "mWifiState: " + mWifiState);
+                log("mWifiState: " + mWifiState);
                 notifyWifiState();
             } else if (action.equals(WifiManager.WIFI_AP_STATE_CHANGED_ACTION)) {
                 notifyWifiAPState();
@@ -180,12 +187,13 @@
 
     public ConnectivityManagerTestActivity() {
         mState = State.UNKNOWN;
+        scanResultAvailable = false;
     }
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-        Log.v(LOG_TAG, "onCreate, inst=" + Integer.toHexString(hashCode()));
+        log("onCreate, inst=" + Integer.toHexString(hashCode()));
 
         // Create a simple layout
         LinearLayout contentView = new LinearLayout(this);
@@ -216,7 +224,7 @@
         initializeNetworkStates();
 
         if (mWifiManager.isWifiEnabled()) {
-            Log.v(LOG_TAG, "Clear Wifi before we start the test.");
+            log("Clear Wifi before we start the test.");
             removeConfiguredNetworksAndDisableWifi();
         }
         mWifiRegexs = mCM.getTetherableWifiRegexs();
@@ -240,9 +248,9 @@
     private void printNetConfig(String[] configuration) {
         for (int i = 0; i < configuration.length; i++) {
             if (i == 0) {
-                Log.v(LOG_TAG, "SSID: " + configuration[0]);
+                log("SSID: " + configuration[0]);
             } else {
-                Log.v(LOG_TAG, "      " + configuration[i]);
+                log("      " + configuration[i]);
             }
         }
     }
@@ -251,14 +259,14 @@
     public void initializeNetworkStates() {
         for (int networkType = NUM_NETWORK_TYPES - 1; networkType >=0; networkType--) {
             connectivityState[networkType] =  new NetworkState();
-            Log.v(LOG_TAG, "Initialize network state for " + networkType + ": " +
+            log("Initialize network state for " + networkType + ": " +
                     connectivityState[networkType].toString());
         }
     }
 
     // deposit a network state
     public void recordNetworkState(int networkType, State networkState) {
-        Log.v(LOG_TAG, "record network state for network " +  networkType +
+        log("record network state for network " +  networkType +
                 ", state is " + networkState);
         connectivityState[networkType].recordState(networkState);
     }
@@ -272,40 +280,41 @@
 
     // Validate the states recorded
     public boolean validateNetworkStates(int networkType) {
-        Log.v(LOG_TAG, "validate network state for " + networkType + ": ");
+        log("validate network state for " + networkType + ": ");
         return connectivityState[networkType].validateStateTransition();
     }
 
     // return result from network state validation
     public String getTransitionFailureReason(int networkType) {
-        Log.v(LOG_TAG, "get network state transition failure reason for " + networkType + ": " +
+        log("get network state transition failure reason for " + networkType + ": " +
                 connectivityState[networkType].toString());
         return connectivityState[networkType].getReason();
     }
 
     private void notifyNetworkConnectivityChange() {
         synchronized(connectivityObject) {
-            Log.v(LOG_TAG, "notify network connectivity changed");
+            log("notify network connectivity changed");
             connectivityObject.notifyAll();
         }
     }
     private void notifyScanResult() {
         synchronized (this) {
-            Log.v(LOG_TAG, "notify that scan results are available");
+            log("notify that scan results are available");
+            scanResultAvailable = true;
             this.notify();
         }
     }
 
     private void notifyWifiState() {
         synchronized (wifiObject) {
-            Log.v(LOG_TAG, "notify wifi state changed");
+            log("notify wifi state changed");
             wifiObject.notify();
         }
     }
 
     private void notifyWifiAPState() {
         synchronized (this) {
-            Log.v(LOG_TAG, "notify wifi AP state changed");
+            log("notify wifi AP state changed");
             this.notify();
         }
     }
@@ -319,7 +328,7 @@
             for (Object obj: tethered) {
                 String str = (String)obj;
                 for (String tethRex: mWifiRegexs) {
-                    Log.v(LOG_TAG, "str: " + str +"tethRex: " + tethRex);
+                    log("str: " + str +"tethRex: " + tethRex);
                     if (str.matches(tethRex)) {
                         wifiTethered = true;
                     }
@@ -329,7 +338,7 @@
             for (Object obj: errored) {
                 String str = (String)obj;
                 for (String tethRex: mWifiRegexs) {
-                    Log.v(LOG_TAG, "error: str: " + str +"tethRex: " + tethRex);
+                    log("error: str: " + str +"tethRex: " + tethRex);
                     if (str.matches(tethRex)) {
                         wifiErrored = true;
                     }
@@ -341,7 +350,7 @@
             } else if (wifiErrored) {
                 mWifiTetherResult = FAILURE;   // wifi tethering failed
             }
-            Log.v(LOG_TAG, "mWifiTetherResult: " + mWifiTetherResult);
+            log("mWifiTetherResult: " + mWifiTetherResult);
             this.notify();
         }
     }
@@ -357,12 +366,12 @@
                     return false;
                 } else {
                     // the broadcast has been sent out. the state has been changed.
-                    Log.v(LOG_TAG, "networktype: " + networkType + " state: " +
+                    log("networktype: " + networkType + " state: " +
                             mCM.getNetworkInfo(networkType));
                     return true;
                 }
             }
-            Log.v(LOG_TAG, "Wait for the connectivity state for network: " + networkType +
+            log("Wait for the connectivity state for network: " + networkType +
                     " to be " + expectedState.toString());
             synchronized (connectivityObject) {
                 try {
@@ -372,7 +381,7 @@
                 }
                 if ((mNetworkInfo.getType() != networkType) ||
                     (mNetworkInfo.getState() != expectedState)) {
-                    Log.v(LOG_TAG, "network state for " + mNetworkInfo.getType() +
+                    log("network state for " + mNetworkInfo.getType() +
                             "is: " + mNetworkInfo.getState());
                     continue;
                 }
@@ -393,7 +402,7 @@
                     return true;
                 }
             }
-            Log.v(LOG_TAG, "Wait for wifi state to be: " + expectedState);
+            log("Wait for wifi state to be: " + expectedState);
             synchronized (wifiObject) {
                 try {
                     wifiObject.wait(SHORT_TIMEOUT);
@@ -401,7 +410,7 @@
                     e.printStackTrace();
                 }
                 if (mWifiState != expectedState) {
-                    Log.v(LOG_TAG, "Wifi state is: " + mWifiState);
+                    log("Wifi state is: " + mWifiState);
                     continue;
                 }
                 return true;
@@ -421,7 +430,7 @@
                     return true;
                 }
             }
-            Log.v(LOG_TAG, "Wait for wifi AP state to be: " + expectedState);
+            log("Wait for wifi AP state to be: " + expectedState);
             synchronized (wifiObject) {
                 try {
                     wifiObject.wait(SHORT_TIMEOUT);
@@ -429,7 +438,7 @@
                     e.printStackTrace();
                 }
                 if (mWifiManager.getWifiApState() != expectedState) {
-                    Log.v(LOG_TAG, "Wifi state is: " + mWifiManager.getWifiApState());
+                    log("Wifi state is: " + mWifiManager.getWifiApState());
                     continue;
                 }
                 return true;
@@ -449,7 +458,7 @@
             if ((System.currentTimeMillis() - startTime) > timeout) {
                 return mWifiTetherResult;
             }
-            Log.v(LOG_TAG, "Wait for wifi tethering result.");
+            log("Wait for wifi tethering result.");
             synchronized (this) {
                 try {
                     this.wait(SHORT_TIMEOUT);
@@ -479,6 +488,64 @@
         return mWifiManager.setWifiEnabled(true);
     }
 
+    // Turn screen off
+    public void turnScreenOff() {
+        log("Turn screen off");
+        PowerManager pm =
+            (PowerManager) getSystemService(Context.POWER_SERVICE);
+        pm.goToSleep(SystemClock.uptimeMillis() + 100);
+    }
+
+    // Turn screen on
+    public void turnScreenOn() {
+        log("Turn screen on");
+        IPowerManager mPowerManagerService = IPowerManager.Stub.asInterface(
+                ServiceManager.getService("power"));;
+        try {
+            mPowerManagerService.userActivityWithForce(SystemClock.uptimeMillis(), false, true);
+        } catch (Exception e) {
+            log(e.toString());
+        }
+    }
+
+    /**
+     * @param pingServerList a list of servers that can be used for ping test, can be null
+     * @return true if the ping test is successful, false otherwise.
+     */
+    public boolean pingTest(String[] pingServerList) {
+        boolean result = false;
+        String[] hostList = {"www.google.com", "www.yahoo.com",
+                "www.bing.com", "www.facebook.com", "www.ask.com"};
+        if (pingServerList != null) {
+            hostList = pingServerList;
+        }
+        try {
+            // assume the chance that all servers are down is very small
+            for (int i = 0; i < hostList.length; i++ ) {
+                String host = hostList[i];
+                log("Start ping test, ping " + host);
+                Process p = Runtime.getRuntime().exec("ping -c 10 -w 100 " + host);
+                int status = p.waitFor();
+                if (status == 0) {
+                    // if any of the ping test is successful, return true
+                    result = true;
+                    break;
+                } else {
+                    result = false;
+                    log("ping " + host + " failed.");
+                }
+            }
+        } catch (UnknownHostException e) {
+            log("Ping test Fail: Unknown Host");
+        } catch (IOException e) {
+            log("Ping test Fail:  IOException");
+        } catch (InterruptedException e) {
+            log("Ping test Fail: InterruptedException");
+        }
+        log("return");
+        return result;
+    }
+
     /**
      * Associate the device to given SSID
      * If the device is already associated with a WiFi, disconnect and forget it,
@@ -503,13 +570,13 @@
 
         //If Wifi is not enabled, enable it
         if (!mWifiManager.isWifiEnabled()) {
-            Log.v(LOG_TAG, "Wifi is not enabled, enable it");
+            log("Wifi is not enabled, enable it");
             mWifiManager.setWifiEnabled(true);
         }
 
         List<ScanResult> netList = mWifiManager.getScanResults();
         if (netList == null) {
-            Log.v(LOG_TAG, "scan results are null");
+            log("scan results are null");
             // if no scan results are available, start active scan
             mWifiManager.startScanActive();
             mScanResultIsAvailable = false;
@@ -540,7 +607,7 @@
         for (int i = 0; i < netList.size(); i++) {
             ScanResult sr= netList.get(i);
             if (sr.SSID.equals(ssid)) {
-                Log.v(LOG_TAG, "found " + ssid + " in the scan result list");
+                log("found " + ssid + " in the scan result list");
                 int networkId = mWifiManager.addNetwork(config);
                 // Connect to network by disabling others.
                 mWifiManager.enableNetwork(networkId, true);
@@ -552,7 +619,7 @@
 
         List<WifiConfiguration> netConfList = mWifiManager.getConfiguredNetworks();
         if (netConfList.size() <= 0) {
-            Log.v(LOG_TAG, ssid + " is not available");
+            log(ssid + " is not available");
             return false;
         }
         return true;
@@ -575,7 +642,7 @@
             // remove other saved networks
             List<WifiConfiguration> netConfList = mWifiManager.getConfiguredNetworks();
             if (netConfList != null) {
-                Log.v(LOG_TAG, "remove configured network ids");
+                log("remove configured network ids");
                 for (int i = 0; i < netConfList.size(); i++) {
                     WifiConfiguration conf = new WifiConfiguration();
                     conf = netConfList.get(i);
@@ -640,7 +707,7 @@
         if (mWifiReceiver != null) {
             unregisterReceiver(mWifiReceiver);
         }
-        Log.v(LOG_TAG, "onDestroy, inst=" + Integer.toHexString(hashCode()));
+        log("onDestroy, inst=" + Integer.toHexString(hashCode()));
     }
 
     @Override
@@ -682,5 +749,8 @@
         }
         return super.onKeyDown(keyCode, event);
     }
-}
 
+    private void log(String message) {
+        Log.v(LOG_TAG, message);
+    }
+}
diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiApStress.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiApStress.java
index cc53ddc..8717a12 100644
--- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiApStress.java
+++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiApStress.java
@@ -19,25 +19,33 @@
 
 import com.android.connectivitymanagertest.ConnectivityManagerStressTestRunner;
 import com.android.connectivitymanagertest.ConnectivityManagerTestActivity;
-import com.android.connectivitymanagertest.ConnectivityManagerTestRunner;
 
 import android.net.wifi.WifiConfiguration;
 import android.net.wifi.WifiConfiguration.KeyMgmt;
 import android.net.wifi.WifiConfiguration.AuthAlgorithm;
+import android.net.wifi.WifiManager;
+import android.os.Environment;
 import android.test.ActivityInstrumentationTestCase2;
 import android.test.suitebuilder.annotation.LargeTest;
 import android.util.Log;
 
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileWriter;
+
 /**
  * Stress the wifi driver as access point.
  */
 public class WifiApStress
     extends ActivityInstrumentationTestCase2<ConnectivityManagerTestActivity> {
     private final static String TAG = "WifiApStress";
-    private ConnectivityManagerTestActivity mAct;
     private static String NETWORK_ID = "AndroidAPTest";
     private static String PASSWD = "androidwifi";
-    private int max_num;
+    private final static String OUTPUT_FILE = "WifiStressTestOutput.txt";
+    private ConnectivityManagerTestActivity mAct;
+    private int iterations;
+    private BufferedWriter mOutputWriter = null;
+    private int mLastIteration = 0;
 
     public WifiApStress() {
         super(ConnectivityManagerTestActivity.class);
@@ -47,11 +55,20 @@
     public void setUp() throws Exception {
         super.setUp();
         mAct = getActivity();
-        max_num = ((ConnectivityManagerStressTestRunner)getInstrumentation()).numStress;
+        ConnectivityManagerStressTestRunner mRunner =
+            (ConnectivityManagerStressTestRunner)getInstrumentation();
+        iterations = mRunner.mSoftapIterations;
+        mAct.turnScreenOn();
     }
 
     @Override
     public void tearDown() throws Exception {
+        // write the total number of iterations into output file
+        mOutputWriter = new BufferedWriter(new FileWriter(new File(
+                Environment.getExternalStorageDirectory(), OUTPUT_FILE)));
+        mOutputWriter.write(String.format("iteration %d out of %d\n", mLastIteration, iterations));
+        mOutputWriter.flush();
+        mOutputWriter.close();
         super.tearDown();
     }
 
@@ -67,22 +84,38 @@
         if (mAct.mWifiManager.isWifiEnabled()) {
             mAct.disableWifi();
         }
-        for (int i = 0; i < max_num; i++) {
+        int i;
+        for (i = 0; i < iterations; i++) {
             Log.v(TAG, "iteration: " + i);
+            mLastIteration = i;
             // enable Wifi tethering
             assertTrue(mAct.mWifiManager.setWifiApEnabled(config, true));
             // Wait for wifi ap state to be ENABLED
-            assertTrue(mAct.waitForWifiAPState(mAct.mWifiManager.WIFI_AP_STATE_ENABLED,
-                    mAct.LONG_TIMEOUT));
+            assertTrue(mAct.waitForWifiAPState(WifiManager.WIFI_AP_STATE_ENABLED,
+                    ConnectivityManagerTestActivity.LONG_TIMEOUT));
             // Wait for wifi tethering result
-            assertEquals(mAct.SUCCESS, mAct.waitForTetherStateChange(2*mAct.SHORT_TIMEOUT));
+            assertEquals(ConnectivityManagerTestActivity.SUCCESS,
+                    mAct.waitForTetherStateChange(2*ConnectivityManagerTestActivity.SHORT_TIMEOUT));
             // Allow the wifi tethering to be enabled for 10 seconds
             try {
                 Thread.sleep(2 * ConnectivityManagerTestActivity.SHORT_TIMEOUT);
             } catch (Exception e) {
                 fail("thread in sleep is interrupted");
             }
+            assertTrue("no uplink data connection after Wi-Fi tethering", mAct.pingTest(null));
+            // Disable soft AP
             assertTrue(mAct.mWifiManager.setWifiApEnabled(config, false));
+            // Wait for 30 seconds until Wi-Fi tethering is stopped
+            try {
+                Thread.sleep(30 * 1000);
+                Log.v(TAG, "wait for Wi-Fi tethering to be disabled.");
+            } catch (Exception e) {
+                fail("thread in sleep is interrupted");
+            }
+            assertFalse("Wi-Fi AP disable failed", mAct.mWifiManager.isWifiApEnabled());
+        }
+        if (i == iterations) {
+            mLastIteration = iterations;
         }
     }
 
diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiStressTest.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiStressTest.java
new file mode 100644
index 0000000..9adccc7
--- /dev/null
+++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiStressTest.java
@@ -0,0 +1,285 @@
+/*
+ * Copyright (C) 2010, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.connectivitymanagertest.stress;
+
+import com.android.connectivitymanagertest.ConnectivityManagerStressTestRunner;
+import com.android.connectivitymanagertest.ConnectivityManagerTestActivity;
+
+import android.content.Context;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo.State;
+import android.net.wifi.ScanResult;
+import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiConfiguration.KeyMgmt;
+import android.net.wifi.WifiManager;
+import android.os.Environment;
+import android.os.PowerManager;
+import android.provider.Settings;
+import android.test.ActivityInstrumentationTestCase2;
+import android.test.suitebuilder.annotation.LargeTest;
+
+import android.util.Log;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.List;
+
+/**
+ * Stress Wi-Fi connection, scanning and reconnection after sleep.
+ *
+ * To run this stress test suite, type
+ * adb shell am instrument -e class com.android.connectivitymanagertest.stress.WifiStressTest
+ *                  -w com.android.connectivitymanagertest/.ConnectivityManagerStressTestRunner
+ */
+public class WifiStressTest
+    extends ActivityInstrumentationTestCase2<ConnectivityManagerTestActivity> {
+    private final static String TAG = "WifiStressTest";
+
+    /**
+     * Wi-Fi idle time for default sleep policy
+     */
+    private final static long WIFI_IDLE_MS = 60 * 1000;
+
+    /**
+     * The delay for Wi-Fi to get into idle, after screen off + WIFI_IDEL_MS + WIFI_IDLE_DELAY
+     * the Wi-Fi should be in idle mode and device should be in cellular mode.
+     */
+    private final static long WIFI_IDLE_DELAY = 3 * 1000;
+
+    private final static String OUTPUT_FILE = "WifiStressTestOutput.txt";
+    private ConnectivityManagerTestActivity mAct;
+    private int mReconnectIterations;
+    private int mWifiSleepTime;
+    private int mScanIterations;
+    private String mSsid;
+    private String mPassword;
+    private ConnectivityManagerStressTestRunner mRunner;
+    private BufferedWriter mOutputWriter = null;
+
+    public WifiStressTest() {
+        super(ConnectivityManagerTestActivity.class);
+    }
+
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        mAct = getActivity();
+        mRunner = (ConnectivityManagerStressTestRunner) getInstrumentation();
+        mReconnectIterations = mRunner.mReconnectIterations;
+        mSsid = mRunner.mReconnectSsid;
+        mPassword = mRunner.mReconnectPassword;
+        mScanIterations = mRunner.mScanIterations;
+        mWifiSleepTime = mRunner.mSleepTime;
+        mOutputWriter = new BufferedWriter(new FileWriter(new File(
+                Environment.getExternalStorageDirectory(), OUTPUT_FILE), true));
+        if (!mAct.mWifiManager.isWifiEnabled()) {
+            if (!mAct.enableWifi()) {
+                tearDown();
+                fail("enable wifi failed.");
+            }
+            sleep(ConnectivityManagerTestActivity.SHORT_TIMEOUT,
+                    "Interruped while waiting for wifi on");
+        }
+    }
+
+    @Override
+    public void tearDown() throws Exception {
+        log("tearDown()");
+        if (mOutputWriter != null) {
+            mOutputWriter.close();
+        }
+        super.tearDown();
+    }
+
+    private void writeOutput(String s) {
+        log("write message: " + s);
+        if (mOutputWriter == null) {
+            log("no writer attached to file " + OUTPUT_FILE);
+            return;
+        }
+        try {
+            mOutputWriter.write(s + "\n");
+            mOutputWriter.flush();
+        } catch (IOException e) {
+            log("failed to write output.");
+        }
+    }
+
+    public void log(String message) {
+        Log.v(TAG, message);
+    }
+
+    private void sleep(long sometime, String errorMsg) {
+        try {
+            Thread.sleep(sometime);
+        } catch (InterruptedException e) {
+            fail(errorMsg);
+        }
+    }
+
+    /**
+     *  Stress Wifi Scanning
+     *  TODO: test the scanning quality for each frequency band
+     */
+    @LargeTest
+    public void testWifiScanning() {
+        int scanTimeSum = 0;
+        int i;
+        int ssidAppearInScanResultsCount = 0; // count times of given ssid appear in scan results.
+        for (i = 0; i < mScanIterations; i++) {
+            log("testWifiScanning: iteration: " + i);
+            int averageScanTime = 0;
+            if (i > 0) {
+                averageScanTime = scanTimeSum/i;
+            }
+            writeOutput(String.format("iteration %d out of %d",
+                    i, mScanIterations));
+            writeOutput(String.format("average scanning time is %d", averageScanTime));
+            writeOutput(String.format("ssid appear %d out of %d scan iterations",
+                    ssidAppearInScanResultsCount, i));
+            long startTime = System.currentTimeMillis();
+            mAct.scanResultAvailable = false;
+            assertTrue("start scan failed", mAct.mWifiManager.startScanActive());
+            while (true) {
+                if ((System.currentTimeMillis() - startTime) >
+                ConnectivityManagerTestActivity.WIFI_SCAN_TIMEOUT) {
+                    fail("Wifi scanning takes more than " +
+                            ConnectivityManagerTestActivity.WIFI_SCAN_TIMEOUT + " ms");
+                }
+                synchronized(mAct) {
+                    try {
+                        mAct.wait(ConnectivityManagerTestActivity.WAIT_FOR_SCAN_RESULT);
+                    } catch (InterruptedException e) {
+                        e.printStackTrace();
+                    }
+                    if (mAct.scanResultAvailable) {
+                        long scanTime = (System.currentTimeMillis() - startTime);
+                        scanTimeSum += scanTime;
+                        break;
+                    }
+                }
+            }
+            if ((mAct.mWifiManager.getScanResults() == null) ||
+                    (mAct.mWifiManager.getScanResults().size() <= 0)) {
+                fail("Scan results are empty ");
+            }
+
+            List<ScanResult> netList = mAct.mWifiManager.getScanResults();
+            if (netList != null) {
+                log("size of scan result list: " + netList.size());
+                for (int s = 0; s < netList.size(); s++) {
+                    ScanResult sr= netList.get(s);
+                    log(String.format("scan result for %s is: %s", sr.SSID, sr.toString()));
+                    log(String.format("signal level for %s is %d ", sr.SSID, sr.level));
+                    if (sr.SSID.equals(mSsid)) {
+                        ssidAppearInScanResultsCount += 1;
+                        log("Number of times " + mSsid + " appear in the scan list: " +
+                                ssidAppearInScanResultsCount);
+                        break;
+                    }
+                }
+            }
+        }
+        if (i == mScanIterations) {
+            writeOutput(String.format("iteration %d out of %d",
+                    i, mScanIterations));
+            writeOutput(String.format("average scanning time is %d", scanTimeSum/mScanIterations));
+            writeOutput(String.format("ssid appear %d out of %d scan iterations",
+                    ssidAppearInScanResultsCount, mScanIterations));
+        }
+    }
+
+    // Stress Wifi reconnection to secure net after sleep
+    @LargeTest
+    public void testWifiReconnectionAfterSleep() {
+        int value = Settings.System.getInt(mRunner.getContext().getContentResolver(),
+                Settings.System.WIFI_SLEEP_POLICY, -1);
+        if (value < 0) {
+            Settings.System.putInt(mRunner.getContext().getContentResolver(),
+                    Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
+            log("set wifi sleep policy to default value");
+        }
+        Settings.Secure.putLong(mRunner.getContext().getContentResolver(),
+                Settings.Secure.WIFI_IDLE_MS, WIFI_IDLE_MS);
+
+        // Connect to a Wi-Fi network
+        WifiConfiguration config = new WifiConfiguration();
+        config.SSID = mSsid;
+        config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
+        if (mPassword.matches("[0-9A-Fa-f]{64}")) {
+            config.preSharedKey = mPassword;
+        } else {
+            config.preSharedKey = '"' + mPassword + '"';
+        }
+        assertTrue("Failed to connect to Wi-Fi network: " + mSsid,
+                mAct.connectToWifiWithConfiguration(config));
+        assertTrue(mAct.waitForWifiState(WifiManager.WIFI_STATE_ENABLED,
+                ConnectivityManagerTestActivity.SHORT_TIMEOUT));
+        assertTrue(mAct.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
+                ConnectivityManagerTestActivity.LONG_TIMEOUT));
+        // Run ping test to verify the data connection
+        assertTrue("Wi-Fi is connected, but no data connection.", mAct.pingTest(null));
+
+        int i;
+        for (i = 0; i < mReconnectIterations; i++) {
+            // 1. Put device into sleep mode
+            // 2. Wait for the device to sleep for sometime, verify wi-fi is off and mobile is on.
+            // 3. Maintain the sleep mode for some time,
+            // 4. Verify the Wi-Fi is still off, and data is on
+            // 5. Wake up the device, verify Wi-Fi is enabled and connected.
+            writeOutput(String.format("iteration %d out of %d",
+                    i, mReconnectIterations));
+            log("iteration: " + i);
+            mAct.turnScreenOff();
+            PowerManager pm =
+                (PowerManager)mRunner.getContext().getSystemService(Context.POWER_SERVICE);
+            assertFalse(pm.isScreenOn());
+            sleep(WIFI_IDLE_MS, "Interruped while wait for wifi to be idle");
+            assertTrue("Wait for Wi-Fi to idle timeout",
+                    mAct.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.DISCONNECTED,
+                    6 * ConnectivityManagerTestActivity.SHORT_TIMEOUT));
+            // use long timeout as the pppd startup may take several retries.
+            assertTrue("Wait for cellular connection timeout",
+                    mAct.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.CONNECTED,
+                    ConnectivityManagerTestActivity.LONG_TIMEOUT));
+            sleep(mWifiSleepTime + WIFI_IDLE_DELAY, "Interrupted while device is in sleep mode");
+            // Verify the wi-fi is still off and data connection is on
+            assertEquals("Wi-Fi is reconnected", State.DISCONNECTED,
+                    mAct.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState());
+
+            assertEquals("Cellular connection is down", State.CONNECTED,
+                         mAct.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState());
+            assertTrue("Mobile is connected, but no data connection.", mAct.pingTest(null));
+
+            // Turn screen on again
+            mAct.turnScreenOn();
+            assertTrue("Wait for Wi-Fi enable timeout after wake up",
+                    mAct.waitForWifiState(WifiManager.WIFI_STATE_ENABLED,
+                    ConnectivityManagerTestActivity.SHORT_TIMEOUT));
+            assertTrue("Wait for Wi-Fi connection timeout after wake up",
+                    mAct.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
+                    ConnectivityManagerTestActivity.LONG_TIMEOUT));
+            assertTrue("Reconnect to Wi-Fi network, but no data connection.", mAct.pingTest(null));
+        }
+        if (i == mReconnectIterations) {
+            writeOutput(String.format("iteration %d out of %d",
+                    i, mReconnectIterations));
+        }
+    }
+}
diff --git a/core/tests/coretests/AndroidManifest.xml b/core/tests/coretests/AndroidManifest.xml
index 487a00d..27b334e 100644
--- a/core/tests/coretests/AndroidManifest.xml
+++ b/core/tests/coretests/AndroidManifest.xml
@@ -96,6 +96,12 @@
 
     <application android:theme="@style/Theme">
         <uses-library android:name="android.test.runner" />
+        <activity android:name="android.view.ViewAttachTestActivity" android:label="View Attach Test">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
+            </intent-filter>
+        </activity>
         <activity android:name="StubTestBrowserActivity" android:label="Stubbed Test Browser">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN"/>
@@ -411,6 +417,13 @@
             </intent-filter>
         </activity>
 
+        <activity android:name="android.widget.scroll.arrowscroll.MultiPageTextWithPadding" android:label="arrowscrollMultiPageTextWithPadding">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
+            </intent-filter>
+        </activity>
+
         <activity android:name="android.view.Include" android:label="IncludeTag">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
diff --git a/core/tests/coretests/res/layout/attach_view_test.xml b/core/tests/coretests/res/layout/attach_view_test.xml
new file mode 100644
index 0000000..42841cb
--- /dev/null
+++ b/core/tests/coretests/res/layout/attach_view_test.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:orientation="vertical"
+    android:layout_width="fill_parent"
+    android:layout_height="fill_parent">
+    <android.view.ViewAttachView
+    android:id="@+id/view_attach_view"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:keepScreenOn="true"/>
+</LinearLayout>
diff --git a/core/tests/coretests/src/android/bluetooth/BluetoothTestUtils.java b/core/tests/coretests/src/android/bluetooth/BluetoothTestUtils.java
index f40d857..4ab9f7b 100644
--- a/core/tests/coretests/src/android/bluetooth/BluetoothTestUtils.java
+++ b/core/tests/coretests/src/android/bluetooth/BluetoothTestUtils.java
@@ -613,8 +613,7 @@
             return;
         }
 
-        // TODO: put assertTrue() around cancelDiscovery() once it starts returning true.
-        adapter.cancelDiscovery();
+        assertTrue(adapter.cancelDiscovery());
 
         long s = System.currentTimeMillis();
         while (System.currentTimeMillis() - s < CANCEL_DISCOVERY_TIMEOUT) {
diff --git a/core/tests/coretests/src/android/text/TextUtilsTest.java b/core/tests/coretests/src/android/text/TextUtilsTest.java
index 79d57f1..63dd0cc 100644
--- a/core/tests/coretests/src/android/text/TextUtilsTest.java
+++ b/core/tests/coretests/src/android/text/TextUtilsTest.java
@@ -17,6 +17,7 @@
 package android.text;
 
 import android.graphics.Paint;
+import android.os.Parcel;
 import android.test.suitebuilder.annotation.LargeTest;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.text.Spannable;
@@ -352,6 +353,51 @@
         assertFalse(TextUtils.delimitedStringContains("network,mock,gpsx", ',', "gps"));
     }
 
+    @SmallTest
+    public void testCharSequenceCreator() {
+        Parcel p = Parcel.obtain();
+        TextUtils.writeToParcel(null, p, 0);
+        CharSequence text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(p);
+        assertNull("null CharSequence should generate null from parcel", text);
+        p = Parcel.obtain();
+        TextUtils.writeToParcel("test", p, 0);
+        text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(p);
+        assertEquals("conversion to/from parcel failed", "test", text);
+    }
+
+    @SmallTest
+    public void testCharSequenceCreatorNull() {
+        Parcel p;
+        CharSequence text;
+        p = Parcel.obtain();
+        TextUtils.writeToParcel(null, p, 0);
+        p.setDataPosition(0);
+        text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(p);
+        assertNull("null CharSequence should generate null from parcel", text);
+    }
+
+    @SmallTest
+    public void testCharSequenceCreatorSpannable() {
+        Parcel p;
+        CharSequence text;
+        p = Parcel.obtain();
+        TextUtils.writeToParcel(new SpannableString("test"), p, 0);
+        p.setDataPosition(0);
+        text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(p);
+        assertEquals("conversion to/from parcel failed", "test", text.toString());
+    }
+
+    @SmallTest
+    public void testCharSequenceCreatorString() {
+        Parcel p;
+        CharSequence text;
+        p = Parcel.obtain();
+        TextUtils.writeToParcel("test", p, 0);
+        p.setDataPosition(0);
+        text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(p);
+        assertEquals("conversion to/from parcel failed", "test", text.toString());
+    }
+
     /**
      * CharSequence wrapper for testing the cases where text is copied into
      * a char array instead of working from a String or a Spanned.
diff --git a/core/tests/coretests/src/android/util/ScrollViewScenario.java b/core/tests/coretests/src/android/util/ScrollViewScenario.java
index 83afe06..db3d9d0 100644
--- a/core/tests/coretests/src/android/util/ScrollViewScenario.java
+++ b/core/tests/coretests/src/android/util/ScrollViewScenario.java
@@ -61,6 +61,7 @@
 
     /**
      * Partially implement ViewFactory given a height ratio.
+     * A negative height ratio means that WRAP_CONTENT will be used as height
      */
     private static abstract class ViewFactoryBase implements ViewFactory {
 
@@ -87,6 +88,9 @@
 
         List<ViewFactory> mViewFactories = Lists.newArrayList();
 
+        int mTopPadding = 0;
+        int mBottomPadding = 0;
+
         /**
          * Add a text view.
          * @param text The text of the text view.
@@ -186,6 +190,13 @@
             });
             return this;
         }
+
+        public Params addPaddingToScrollView(int topPadding, int bottomPadding) {
+            mTopPadding = topPadding;
+            mBottomPadding = bottomPadding;
+
+            return this;
+        }
     }
 
     /**
@@ -239,13 +250,17 @@
 
         // create views specified by params
         for (ViewFactory viewFactory : params.mViewFactories) {
+            int height = ViewGroup.LayoutParams.WRAP_CONTENT;
+            if (viewFactory.getHeightRatio() >= 0) {
+                height = (int) (viewFactory.getHeightRatio() * screenHeight);
+            }
             final LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
-                    ViewGroup.LayoutParams.MATCH_PARENT,
-                    (int) (viewFactory.getHeightRatio() * screenHeight));
+                    ViewGroup.LayoutParams.MATCH_PARENT, height);
             mLinearLayout.addView(viewFactory.create(this), lp);
         }
 
         mScrollView = createScrollView();
+        mScrollView.setPadding(0, params.mTopPadding, 0, params.mBottomPadding);
         mScrollView.addView(mLinearLayout, new ViewGroup.LayoutParams(
                 ViewGroup.LayoutParams.MATCH_PARENT,
                 ViewGroup.LayoutParams.MATCH_PARENT));
diff --git a/core/tests/coretests/src/android/view/ViewAttachTest.java b/core/tests/coretests/src/android/view/ViewAttachTest.java
new file mode 100644
index 0000000..cff66e4
--- /dev/null
+++ b/core/tests/coretests/src/android/view/ViewAttachTest.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.view;
+
+import android.content.pm.ActivityInfo;
+import android.os.SystemClock;
+import android.test.ActivityInstrumentationTestCase2;
+
+public class ViewAttachTest extends
+        ActivityInstrumentationTestCase2<ViewAttachTestActivity> {
+
+    public ViewAttachTest() {
+        super(ViewAttachTestActivity.class);
+    }
+
+    /**
+     * Make sure that onAttachedToWindow and onDetachedToWindow is called in the
+     * correct order The ViewAttachTestActivity contains a view that will throw
+     * an RuntimeException if onDetachedToWindow and onAttachedToWindow is
+     * called in the wrong order.
+     *
+     * 1. Initiate the activity 2. Perform a series of orientation changes to
+     * the activity (this will force the View hierarchy to be rebuild,
+     * generating onAttachedToWindow and onDetachedToWindow)
+     *
+     * Expected result: No RuntimeException is thrown from the TestView in
+     * ViewFlipperTestActivity.
+     *
+     * @throws Throwable
+     */
+    public void testAttached() throws Throwable {
+        final ViewAttachTestActivity activity = getActivity();
+        for (int i = 0; i < 20; i++) {
+            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
+            SystemClock.sleep(250);
+            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
+            SystemClock.sleep(250);
+        }
+    }
+}
diff --git a/core/tests/coretests/src/android/view/ViewAttachTestActivity.java b/core/tests/coretests/src/android/view/ViewAttachTestActivity.java
new file mode 100644
index 0000000..59e25ae
--- /dev/null
+++ b/core/tests/coretests/src/android/view/ViewAttachTestActivity.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.view;
+
+import com.android.frameworks.coretests.R;
+
+import android.app.Activity;
+import android.os.Bundle;
+
+public class ViewAttachTestActivity extends Activity {
+    public static final String TAG = "OnAttachedTest";
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.attach_view_test);
+    }
+}
diff --git a/core/tests/coretests/src/android/view/ViewAttachView.java b/core/tests/coretests/src/android/view/ViewAttachView.java
new file mode 100644
index 0000000..5af2d8f
--- /dev/null
+++ b/core/tests/coretests/src/android/view/ViewAttachView.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.view;
+
+import android.content.Context;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.os.SystemClock;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.view.View;
+
+/**
+ * A View that will throw a RuntimeException if onAttachedToWindow and
+ * onDetachedFromWindow is called in the wrong order for ViewAttachTest
+ */
+public class ViewAttachView extends View {
+    public static final String TAG = "OnAttachedTest";
+    private boolean attached;
+
+    public ViewAttachView(Context context, AttributeSet attrs, int defStyle) {
+        super(context, attrs, defStyle);
+        init(attrs, defStyle);
+    }
+
+    public ViewAttachView(Context context, AttributeSet attrs) {
+        super(context, attrs);
+        init(attrs, 0);
+    }
+
+    public ViewAttachView(Context context) {
+        super(context);
+        init(null, 0);
+    }
+
+    private void init(AttributeSet attrs, int defStyle) {
+        SystemClock.sleep(2000);
+    }
+
+    @Override
+    protected void onAttachedToWindow() {
+        Log.d(TAG, "onAttachedToWindow");
+        super.onAttachedToWindow();
+        if (attached) {
+            throw new RuntimeException("OnAttachedToWindow called more than once in a row");
+        }
+        attached = true;
+    }
+
+    @Override
+    protected void onDetachedFromWindow() {
+        Log.d(TAG, "onDetachedFromWindow");
+        super.onDetachedFromWindow();
+        if (!attached) {
+            throw new RuntimeException(
+                    "onDetachedFromWindowcalled without prior call to OnAttachedToWindow");
+        }
+        attached = false;
+    }
+
+    @Override
+    protected void onDraw(Canvas canvas) {
+        super.onDraw(canvas);
+        canvas.drawColor(Color.BLUE);
+    }
+}
diff --git a/core/tests/coretests/src/android/widget/scroll/arrowscroll/MultiPageTextWithPadding.java b/core/tests/coretests/src/android/widget/scroll/arrowscroll/MultiPageTextWithPadding.java
new file mode 100644
index 0000000..7d5a8d8
--- /dev/null
+++ b/core/tests/coretests/src/android/widget/scroll/arrowscroll/MultiPageTextWithPadding.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.widget.scroll.arrowscroll;
+
+import android.util.ScrollViewScenario;
+
+/**
+ * One TextView with a text covering several pages. Padding is added
+ * above and below the ScrollView.
+ */
+public class MultiPageTextWithPadding extends ScrollViewScenario {
+
+    @Override
+    protected void init(Params params) {
+
+        String text = "This is a long text.";
+        String longText = "First text.";
+        for (int i = 0; i < 300; i++) {
+            longText = longText + " " + text;
+        }
+        longText = longText + " Last text.";
+        params.addTextView(longText, -1.0f).addPaddingToScrollView(50, 50);
+    }
+}
diff --git a/core/tests/coretests/src/android/widget/scroll/arrowscroll/MultiPageTextWithPaddingTest.java b/core/tests/coretests/src/android/widget/scroll/arrowscroll/MultiPageTextWithPaddingTest.java
new file mode 100644
index 0000000..ddde48f
--- /dev/null
+++ b/core/tests/coretests/src/android/widget/scroll/arrowscroll/MultiPageTextWithPaddingTest.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2011 Sony Ericsson Mobile Communications AB.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.widget.scroll.arrowscroll;
+
+import android.widget.scroll.arrowscroll.MultiPageTextWithPadding;
+import android.test.ActivityInstrumentationTestCase;
+import android.test.suitebuilder.annotation.LargeTest;
+import android.test.suitebuilder.annotation.MediumTest;
+import android.view.KeyEvent;
+import android.widget.TextView;
+import android.widget.ScrollView;
+
+public class MultiPageTextWithPaddingTest extends
+        ActivityInstrumentationTestCase<MultiPageTextWithPadding> {
+
+    private ScrollView mScrollView;
+
+    private TextView mTextView;
+
+    public MultiPageTextWithPaddingTest() {
+        super("com.android.frameworks.coretests", MultiPageTextWithPadding.class);
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+
+        mScrollView = getActivity().getScrollView();
+        mTextView = getActivity().getContentChildAt(0);
+    }
+
+    @MediumTest
+    public void testPreconditions() {
+        assertTrue("text should not fit on screen",
+                   mTextView.getHeight() > mScrollView.getHeight());
+    }
+
+    @LargeTest
+    public void testScrollDownToBottom() throws Exception {
+        // Calculate the number of arrow scrolls needed to reach the bottom
+        int scrollsNeeded = (int)Math.ceil(Math.max(0.0f,
+                (mTextView.getHeight() - mScrollView.getHeight()))
+                / mScrollView.getMaxScrollAmount());
+        for (int i = 0; i < scrollsNeeded; i++) {
+            sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
+        }
+
+        assertEquals(
+                "should be fully scrolled to bottom",
+                getActivity().getLinearLayout().getHeight()
+                        - (mScrollView.getHeight() - mScrollView.getPaddingTop() - mScrollView
+                                .getPaddingBottom()), mScrollView.getScrollY());
+    }
+}
diff --git a/data/etc/android.hardware.usb.accessory.xml b/data/etc/android.hardware.usb.accessory.xml
new file mode 100644
index 0000000..80a0904
--- /dev/null
+++ b/data/etc/android.hardware.usb.accessory.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2011 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<!-- This is the standard feature indicating that the device supports USB accessories. -->
+<permissions>
+    <feature name="android.hardware.usb.accessory" />
+    <library name="com.android.future.usb.accessory"
+            file="/system/framework/com.android.future.usb.accessory.jar" />
+</permissions>
diff --git a/data/fonts/DroidSans-Bold.ttf b/data/fonts/DroidSans-Bold.ttf
index 7ac04b6..d065b64 100644
--- a/data/fonts/DroidSans-Bold.ttf
+++ b/data/fonts/DroidSans-Bold.ttf
Binary files differ
diff --git a/data/fonts/DroidSans.ttf b/data/fonts/DroidSans.ttf
index 767c63a..ad1efca8 100644
--- a/data/fonts/DroidSans.ttf
+++ b/data/fonts/DroidSans.ttf
Binary files differ
diff --git a/data/fonts/DroidSansArabic.ttf b/data/fonts/DroidSansArabic.ttf
index 660e2a9..bdefaac 100644
--- a/data/fonts/DroidSansArabic.ttf
+++ b/data/fonts/DroidSansArabic.ttf
Binary files differ
diff --git a/data/fonts/DroidSansFallback.ttf b/data/fonts/DroidSansFallback.ttf
index 206621f..ba9d76f 100644
--- a/data/fonts/DroidSansFallback.ttf
+++ b/data/fonts/DroidSansFallback.ttf
Binary files differ
diff --git a/data/fonts/DroidSansMono.ttf b/data/fonts/DroidSansMono.ttf
index 6e79dad..a007071 100644
--- a/data/fonts/DroidSansMono.ttf
+++ b/data/fonts/DroidSansMono.ttf
Binary files differ
diff --git a/data/fonts/DroidSerif-Bold.ttf b/data/fonts/DroidSerif-Bold.ttf
index 85d6c6b..838d255 100644
--- a/data/fonts/DroidSerif-Bold.ttf
+++ b/data/fonts/DroidSerif-Bold.ttf
Binary files differ
diff --git a/data/fonts/DroidSerif-BoldItalic.ttf b/data/fonts/DroidSerif-BoldItalic.ttf
index 9d8e798..0b1601f 100644
--- a/data/fonts/DroidSerif-BoldItalic.ttf
+++ b/data/fonts/DroidSerif-BoldItalic.ttf
Binary files differ
diff --git a/data/fonts/DroidSerif-Italic.ttf b/data/fonts/DroidSerif-Italic.ttf
index 6acc86d..2972809 100644
--- a/data/fonts/DroidSerif-Italic.ttf
+++ b/data/fonts/DroidSerif-Italic.ttf
Binary files differ
diff --git a/data/fonts/DroidSerif-Regular.ttf b/data/fonts/DroidSerif-Regular.ttf
index 8c1c2c4..5b4fe81 100644
--- a/data/fonts/DroidSerif-Regular.ttf
+++ b/data/fonts/DroidSerif-Regular.ttf
Binary files differ
diff --git a/data/fonts/MTLc3m.ttf b/data/fonts/MTLc3m.ttf
index 3cc5c96..86bdcc7 100644
--- a/data/fonts/MTLc3m.ttf
+++ b/data/fonts/MTLc3m.ttf
Binary files differ
diff --git a/data/fonts/MTLmr3m.ttf b/data/fonts/MTLmr3m.ttf
index 05b9093..76fe737 100644
--- a/data/fonts/MTLmr3m.ttf
+++ b/data/fonts/MTLmr3m.ttf
Binary files differ
diff --git a/docs/html/guide/developing/tools/traceview.jd b/docs/html/guide/developing/tools/traceview.jd
index 95ae823..b681bba 100644
--- a/docs/html/guide/developing/tools/traceview.jd
+++ b/docs/html/guide/developing/tools/traceview.jd
@@ -120,7 +120,7 @@
     the first row show the extent (entry to exit) of all the calls to the selected
     method. The method in this case is LoadListener.nativeFinished() and it was
     selected in the profile view. </p>
-<p><img src="/images/traceview_timeline.png" alt="Traceview timeline panel" width="893" height="284"></p>
+<p><img src="{@docRoot}images/traceview_timeline.png" alt="Traceview timeline panel" width="893" height="284"></p>
 <a name="profilepanel"></a>
 <h3>Profile Panel</h3>
 <p>The image below shows the profile pane. The profile pane shows a
@@ -137,7 +137,7 @@
     view, we can see that there were 14 calls to LoadListener.nativeFinished(); looking
     at the timeline panel shows that one of those calls took an unusually
     long time.</p>
-<p><img src="/images/traceview_profile.png" alt="Traceview profile panel." width="892" height="630"></p>
+<p><img src="{@docRoot}images/traceview_profile.png" alt="Traceview profile panel." width="892" height="630"></p>
 
 <a name="format"></a>
 <h2>Traceview File Format</h2>
diff --git a/docs/html/guide/market/billing/billing_integrate.jd b/docs/html/guide/market/billing/billing_integrate.jd
index 0f081a5..6e40f32 100755
--- a/docs/html/guide/market/billing/billing_integrate.jd
+++ b/docs/html/guide/market/billing/billing_integrate.jd
@@ -223,7 +223,7 @@
 <pre>
 try {
   boolean bindResult = mContext.bindService(
-    new Intent(IMarketBillingService.class.getName()), this, Context.BIND_AUTO_CREATE);
+    new Intent("com.android.vending.billing.MarketBillingService.BIND"), this, Context.BIND_AUTO_CREATE);
   if (bindResult) {
     Log.i(TAG, "Service bind successful.");
   } else {
diff --git a/docs/html/guide/topics/nfc/index.jd b/docs/html/guide/topics/nfc/index.jd
index 3992099..c4917b4 100644
--- a/docs/html/guide/topics/nfc/index.jd
+++ b/docs/html/guide/topics/nfc/index.jd
@@ -31,29 +31,33 @@
     </div>
   </div>
 
-  <p>Near Field Communication (NFC) is a set of short-range wireless technologies, similar to RFID.
-  It typically requires a distance of 4 cm or less and operates at 13.56mhz and at rates ranging
-  from 106 kbit/s to 848 kbit/s. NFC communication always involves an initiator and a target. The
-  initiator actively generates an RF field that can power a passive target. This enables NFC
-  targets to take very simple form factors such as tags, stickers or cards that do not require
-  power. NFC peer-to-peer communication is also possible, where both devices are powered.</p>
-
-  <p>Compared to other wireless technologies such as Bluetooth or WiFi, NFC provides much lower
-  bandwidth and range, but provides low-cost, un-powered targets and do not require discovery or
-  pairing. Users interact with NFC tags with just a tap. Targets can range in complexity. Simple
-  tags just offer read and write capabilities, sometimes with one-time programmable areas to make
-  the card read-only. More complex tags offer math operations, and have cryptographic hardware to
-  authenticate access to a sector. The most sophisticated tags contain operating environments,
-  allowing complex interactions with applets that are running on the tag.</p>
-
-  <p>An Android device with NFC hardware typically acts as an initiator. This mode is also known as
-  NFC reader/writer. The device actively looks for NFC tags and starts activities to handle them in
-  this mode. In Android 2.3.3, devices also have some limited peer-to-peer support.</p>
+  <p>Near Field Communication (NFC) is a set of short-range wireless technologies, typically
+  requiring a distance of 4cm or less. NFC operates at 13.56mhz, and at rates ranging
+  from 106 kbit/s to 848 kbit/s. NFC communication always involves an initiator and a target.
+  The initiator actively generates an RF field that can power a passive target. This
+  enables NFC targets to take very simple form factors such as tags, stickers or cards that do
+  not require power. NFC peer-to-peer communication is also possible, where both devices
+  are powered.
+  <p>
+  Compared to other wireless technologies such as Bluetooth or WiFi, NFC provides much lower
+  bandwidth and range, but enables low-cost, un-powered targets
+  and does not require discovery or pairing. Interactions can be initiated with just a tap.
+  <p>
+  An Android device with NFC hardware will typically act as an initiator when the screen is
+  on. This mode is also known as NFC reader/writer. It will actively look for NFC tags and start
+  activities to handle them. Android 2.3.3 also has some limited P2P support.
+  <p>
+  Tags can range in complexity, simple tags just offer read/write semantics, sometimes
+  with one-time-programmable areas to make the card read-only. More complex tags offer
+  math operations, and have cryptographic hardware to authenticate access to a sector.
+  The most sophisticated tags contain operating environments, allowing
+  complex interactions with code executing on the tag.
 
   <h2 id="api">API Overview</h2>
 
-  <p>The {@link android.nfc} package contain the high-level classes to interact with the local
-  device's NFC adapter, to represent discovered tags, and to use the NDEF data format.</p>
+  <p>The {@link android.nfc} package contains the high-level classes to interact
+  with the local device's NFC adapter, to represent discovered tags, and to use
+  the NDEF data format.
 
   <table>
     <tr>
@@ -65,44 +69,52 @@
     <tr>
       <td>{@link android.nfc.NfcManager}</td>
 
-      <td>A high level manager class that enumerates the NFC adapters on this Android device. Since
-      most Android devices only have one NFC adapter, you can just use the static helper {@link
-      android.nfc.NfcAdapter#getDefaultAdapter()} for most situations.</td>
+
+      <td>A high level manager class that enumerates the NFC adapters on this Android device.
+      Since most Android devices only have one NFC adapter, you can just use the static helper
+      {@link android.nfc.NfcAdapter#getDefaultAdapter(Context)} for most situations.</td>
     </tr>
 
     <tr>
       <td>{@link android.nfc.NfcAdapter}</td>
 
-      <td>Represents the local NFC adapter and defines the Intents that are used in the tag
-      dispatch system. It provides methods to register for foreground tag dispatching and
-      foreground NDEF pushing. Foreground NDEF push is the only peer-to-peer support that is
-      currently provided in Android.</td>
+      <td>Represents the local NFC adapter. Defines the intent's used to request
+      tag dispatch to your activity, and provides methods to register for foreground
+      tag dispatch and foreground NDEF push. Foreground NDEF push is the only
+      peer-to-peer support that is currently provided in Android.</td>
     </tr>
 
     <tr>
       <td>{@link android.nfc.NdefMessage} and {@link android.nfc.NdefRecord}</td>
 
-      <td>NDEF is an NFC Forum defined data structure, designed to efficiently store data on NFC
-      tags, such as Text, URLs, and other MIME types. An {@link android.nfc.NdefMessage} acts as a
+      <td>NDEF is an NFC Forum defined data structure, designed to efficiently
+      store data on NFC tags, such as text, URL's, and other MIME types. A
+      {@link android.nfc.NdefMessage} acts as a
       container for the data that you want to transmit or read. One {@link android.nfc.NdefMessage}
-      object contains zero or more {@link android.nfc.NdefRecord}s. Each NDEF Record has a type
-      such as Text, URL, Smart Poster, or any MIME type. The type of the first NDEF Record in the
-      NDEF message is used to dispatch a tag to an Activity.</td>
+      object contains zero or more {@link android.nfc.NdefRecord}s. Each NDEF record
+      has a type such as text, URL, smart poster, or any MIME data. The type of the
+      first NDEF record in the NDEF message is used to dispatch a tag to an activity
+      on Android.</td>
     </tr>
 
     <tr>
       <td>{@link android.nfc.Tag}</td>
 
-      <td>Represents a passive NFC target. These can come in many form factors such as a tag, card,
-      FOB, or an even more complex device doing card emulation. When a tag is discovered, a {@link
-      android.nfc.Tag} object is created and wrapped inside an Intent. The dispatch system sends
-      the Intent to a compatible Activity <code>startActivity()</code>. You can use the {@link
+      <td>Represents a passive NFC target. These can come in many form factors such as
+      a tag, card, key fob, or even a phone doing card emulation. When a tag is
+      discovered, a {@link android.nfc.Tag} object is created and wrapped inside an
+      Intent. The NFC dispatch system sends the intent to a compatible actvitiy
+      using <code>startActivity()</code>. You can use the {@link
       android.nfc.Tag#getTechList getTechList()} method to determine the technologies supported by
       this tag and create the corresponding {@link android.nfc.tech.TagTechnology} object with one
       of classes provided by {@link android.nfc.tech}.</td>
     </tr>
   </table>
 
+  <p>The {@link android.nfc.tech} package contains classes to query properties
+  and perform I/O operations on a tag. The classes are divided to represent different
+  NFC technologies that can be available on a tag.
+
   <p>The {@link android.nfc.tech} package contains classes to query properties and perform I/O
   operations on a tag. The classes are divided to represent different NFC technologies that can be
   available on a Tag:</p>
@@ -117,7 +129,7 @@
     <tr>
       <td>{@link android.nfc.tech.TagTechnology}</td>
 
-      <td>The interface that all Tag Technology classes must implement.</td>
+      <td>The interface that all tag technology classes must implement.</td>
     </tr>
 
     <tr>
@@ -153,8 +165,8 @@
     <tr>
       <td>{@link android.nfc.tech.Ndef}</td>
 
-      <td>Provides access to NDEF data and operations on NFC Tags that have been formatted as
-      NDEF.</td>
+      <td>Provides access to NDEF data and operations on NFC tags that have been formatted as NDEF.
+      </td>
     </tr>
 
     <tr>
@@ -166,15 +178,15 @@
     <tr>
       <td>{@link android.nfc.tech.MifareClassic}</td>
 
-      <td>Provides access to MIFARE Classic properties and I/O operations. Not all Android devices
-      provide implementations for this class.</td>
+      <td>Provides access to MIFARE Classic properties and I/O operations, if this
+      Android device supports MIFARE.</td>
     </tr>
 
     <tr>
       <td>{@link android.nfc.tech.MifareUltralight}</td>
 
-      <td>Provides access to MIFARE Ultralight properties and I/O operations. Not all Android
-      devices provide implementations for this class.</td>
+      <td>Provides access to MIFARE Ultralight properties and I/O operations, if this
+      Android device supports MIFARE.</td>
     </tr>
   </table>
 
@@ -191,12 +203,13 @@
     </li>
 
     <li>The minimum SDK version that your application can support. API level 9 only supports
-    limited tag dispatching with {@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED}, and only
-    gives access to NDEF messages via the {@link android.nfc.NfcAdapter#EXTRA_NDEF_MESSAGES} extra.
-    No other tag properties or I/O operations are accessible. API level 10 adds comprehensive
-    reader/writer support, so you probably want to use this for more functionality.
-      <pre class="pretty-print">
-&lt;uses-sdk android:minSdkVersion="9|10"/&gt;
+    limited tag dispatch via {@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED},
+    and only gives access to NDEF messages via the {@link android.nfc.NfcAdapter#EXTRA_NDEF_MESSAGES}
+    extra. No other tag properties or I/O operations are accessible. You probably want
+    to use API level 10 which includes comprehensive reader/writer support.
+
+<pre class="pretty-print">
+&lt;uses-sdk android:minSdkVersion="10"/&gt;
 </pre>
     </li>
 
diff --git a/docs/html/sdk/index.jd b/docs/html/sdk/index.jd
index bfcd14e..551361f7 100644
--- a/docs/html/sdk/index.jd
+++ b/docs/html/sdk/index.jd
@@ -3,7 +3,7 @@
 
 sdk.win_installer=installer_r09-windows.exe
 sdk.win_installer_bytes=32828818
-sdk.win_installer_checksum=a0185701ac0d635a4fbf8169ac949a3c5b3d31e0 
+sdk.win_installer_checksum=ef92e643731f820360e036eb11658656
 
 sdk.win_download=android-sdk_r09-windows.zip
 sdk.win_bytes=32779808
diff --git a/graphics/java/android/graphics/Bitmap.java b/graphics/java/android/graphics/Bitmap.java
index dd83c3b..a9ac1d3 100644
--- a/graphics/java/android/graphics/Bitmap.java
+++ b/graphics/java/android/graphics/Bitmap.java
@@ -546,7 +546,8 @@
      */
     public enum CompressFormat {
         JPEG    (0),
-        PNG     (1);
+        PNG     (1),
+        WEBP    (2);
 
         CompressFormat(int nativeInt) {
             this.nativeInt = nativeInt;
diff --git a/graphics/java/android/graphics/Movie.java b/graphics/java/android/graphics/Movie.java
index 95e9946..4a33453 100644
--- a/graphics/java/android/graphics/Movie.java
+++ b/graphics/java/android/graphics/Movie.java
@@ -46,6 +46,8 @@
     public static native Movie decodeByteArray(byte[] data, int offset,
                                                int length);
 
+    private static native void nativeDestructor(int nativeMovie);
+
     public static Movie decodeFile(String pathName) {
         InputStream is;
         try {
@@ -57,6 +59,15 @@
         return decodeTempStream(is);
     }
 
+    @Override
+    protected void finalize() throws Throwable {
+        try {
+            nativeDestructor(mNativeMovie);
+        } finally {
+            super.finalize();
+        }
+    }
+
     private static Movie decodeTempStream(InputStream is) {
         Movie moov = null;
         try {
diff --git a/graphics/java/android/graphics/drawable/BitmapDrawable.java b/graphics/java/android/graphics/drawable/BitmapDrawable.java
index 0b8465e..501374b 100644
--- a/graphics/java/android/graphics/drawable/BitmapDrawable.java
+++ b/graphics/java/android/graphics/drawable/BitmapDrawable.java
@@ -474,10 +474,8 @@
         mBitmapState = state;
         if (res != null) {
             mTargetDensity = res.getDisplayMetrics().densityDpi;
-        } else if (state != null) {
-            mTargetDensity = state.mTargetDensity;
         } else {
-            mTargetDensity = DisplayMetrics.DENSITY_DEFAULT;
+            mTargetDensity = state.mTargetDensity;
         }
         setBitmap(state.mBitmap);
     }
diff --git a/include/gui/SurfaceTexture.h b/include/gui/SurfaceTexture.h
index 255afdd..946afb9 100644
--- a/include/gui/SurfaceTexture.h
+++ b/include/gui/SurfaceTexture.h
@@ -22,12 +22,14 @@
 struct SurfaceTexture {
     struct FrameAvailableListener : public virtual RefBase {};
 
-    SurfaceTexture(GLuint) {}
+    SurfaceTexture(GLuint, bool allowSynchronousMode = true) {}
     void updateTexImage() {}
     void decStrong(android::sp<android::SurfaceTexture>* const) {}
     void incStrong(android::sp<android::SurfaceTexture>* const) {}
     void getTransformMatrix(float mtx[16]) {}
     void setFrameAvailableListener(const sp<FrameAvailableListener>&) {}
+    void setSynchronousMode(bool) {}
+    GLenum getCurrentTextureTarget() const { return 0; }
 };
 
 static sp<SurfaceTexture> SurfaceTexture_getSurfaceTexture(JNIEnv* env, jobject thiz)
diff --git a/include/media/EffectApi.h b/include/media/EffectApi.h
index b97c22e..6e6660c 100644
--- a/include/media/EffectApi.h
+++ b/include/media/EffectApi.h
@@ -602,9 +602,9 @@
 
 // Audio mode
 enum audio_mode_e {
-    AUDIO_MODE_NORMAL,      // device idle
-    AUDIO_MODE_RINGTONE,    // device ringing
-    AUDIO_MODE_IN_CALL      // audio call connected (VoIP or telephony)
+    AUDIO_EFFECT_MODE_NORMAL,   // device idle
+    AUDIO_EFFECT_MODE_RINGTONE, // device ringing
+    AUDIO_EFFECT_MODE_IN_CALL   // audio call connected (VoIP or telephony)
 };
 
 // Values for "accessMode" field of buffer_config_t:
diff --git a/include/ui/GraphicBuffer.h b/include/ui/GraphicBuffer.h
index 0be26a7..1da9729 100644
--- a/include/ui/GraphicBuffer.h
+++ b/include/ui/GraphicBuffer.h
@@ -74,6 +74,8 @@
 
     GraphicBuffer();
 
+    GraphicBuffer(android_native_buffer_t*, bool);
+
     // creates w * h buffer
     GraphicBuffer(uint32_t w, uint32_t h, PixelFormat format, uint32_t usage);
 
diff --git a/include/ui/android_native_buffer.h b/include/ui/android_native_buffer.h
index a472824..85a1638 100644
--- a/include/ui/android_native_buffer.h
+++ b/include/ui/android_native_buffer.h
@@ -63,6 +63,7 @@
     void* reserved_proc[8];
 } android_native_buffer_t;
 
+#define ANativeWindowBuffer android_native_buffer_t
 
 /*****************************************************************************/
 
diff --git a/include/utils/RefBase.h b/include/utils/RefBase.h
index 9c64ac0..0af7e6a 100644
--- a/include/utils/RefBase.h
+++ b/include/utils/RefBase.h
@@ -31,13 +31,10 @@
 
 // ---------------------------------------------------------------------------
 
-#define COMPARE(_op_)                                           \
+#define COMPARE_WEAK(_op_)                                      \
 inline bool operator _op_ (const sp<T>& o) const {              \
     return m_ptr _op_ o.m_ptr;                                  \
 }                                                               \
-inline bool operator _op_ (const wp<T>& o) const {              \
-    return m_ptr _op_ o.m_ptr;                                  \
-}                                                               \
 inline bool operator _op_ (const T* o) const {                  \
     return m_ptr _op_ o;                                        \
 }                                                               \
@@ -46,12 +43,18 @@
     return m_ptr _op_ o.m_ptr;                                  \
 }                                                               \
 template<typename U>                                            \
-inline bool operator _op_ (const wp<U>& o) const {              \
+inline bool operator _op_ (const U* o) const {                  \
+    return m_ptr _op_ o;                                        \
+}
+
+#define COMPARE(_op_)                                           \
+COMPARE_WEAK(_op_)                                              \
+inline bool operator _op_ (const wp<T>& o) const {              \
     return m_ptr _op_ o.m_ptr;                                  \
 }                                                               \
 template<typename U>                                            \
-inline bool operator _op_ (const U* o) const {                  \
-    return m_ptr _op_ o;                                        \
+inline bool operator _op_ (const wp<U>& o) const {              \
+    return m_ptr _op_ o.m_ptr;                                  \
 }
 
 // ---------------------------------------------------------------------------
@@ -109,10 +112,24 @@
         getWeakRefs()->trackMe(enable, retain); 
     }
 
+    // used to override the RefBase destruction.
+    class Destroyer {
+        friend class RefBase;
+        friend class weakref_type;
+    public:
+        virtual ~Destroyer();
+    private:
+        virtual void destroy(RefBase const* base) = 0;
+    };
+
+    // Make sure to never acquire a strong reference from this function. The
+    // same restrictions than for destructors apply.
+    void setDestroyer(Destroyer* destroyer);
+
 protected:
                             RefBase();
     virtual                 ~RefBase();
-    
+
     //! Flags for extendObjectLifetime()
     enum {
         OBJECT_LIFETIME_WEAK    = 0x0001,
@@ -274,13 +291,43 @@
     inline  T* unsafe_get() const { return m_ptr; }
 
     // Operators
-        
-    COMPARE(==)
-    COMPARE(!=)
-    COMPARE(>)
-    COMPARE(<)
-    COMPARE(<=)
-    COMPARE(>=)
+
+    COMPARE_WEAK(==)
+    COMPARE_WEAK(!=)
+    COMPARE_WEAK(>)
+    COMPARE_WEAK(<)
+    COMPARE_WEAK(<=)
+    COMPARE_WEAK(>=)
+
+    inline bool operator == (const wp<T>& o) const {
+        return (m_ptr == o.m_ptr) && (m_refs == o.m_refs);
+    }
+    template<typename U>
+    inline bool operator == (const wp<U>& o) const {
+        return m_ptr == o.m_ptr;
+    }
+
+    inline bool operator > (const wp<T>& o) const {
+        return (m_ptr == o.m_ptr) ? (m_refs > o.m_refs) : (m_ptr > o.m_ptr);
+    }
+    template<typename U>
+    inline bool operator > (const wp<U>& o) const {
+        return (m_ptr == o.m_ptr) ? (m_refs > o.m_refs) : (m_ptr > o.m_ptr);
+    }
+
+    inline bool operator < (const wp<T>& o) const {
+        return (m_ptr == o.m_ptr) ? (m_refs < o.m_refs) : (m_ptr < o.m_ptr);
+    }
+    template<typename U>
+    inline bool operator < (const wp<U>& o) const {
+        return (m_ptr == o.m_ptr) ? (m_refs < o.m_refs) : (m_ptr < o.m_ptr);
+    }
+                         inline bool operator != (const wp<T>& o) const { return m_refs != o.m_refs; }
+    template<typename U> inline bool operator != (const wp<U>& o) const { return !operator == (o); }
+                         inline bool operator <= (const wp<T>& o) const { return !operator > (o); }
+    template<typename U> inline bool operator <= (const wp<U>& o) const { return !operator > (o); }
+                         inline bool operator >= (const wp<T>& o) const { return !operator < (o); }
+    template<typename U> inline bool operator >= (const wp<U>& o) const { return !operator < (o); }
 
 private:
     template<typename Y> friend class sp;
@@ -294,6 +341,7 @@
 TextOutput& operator<<(TextOutput& to, const wp<T>& val);
 
 #undef COMPARE
+#undef COMPARE_WEAK
 
 // ---------------------------------------------------------------------------
 // No user serviceable parts below here.
diff --git a/libs/ui/GraphicBuffer.cpp b/libs/ui/GraphicBuffer.cpp
index 3671954..d9efeab 100644
--- a/libs/ui/GraphicBuffer.cpp
+++ b/libs/ui/GraphicBuffer.cpp
@@ -49,6 +49,19 @@
     handle = NULL;
 }
 
+GraphicBuffer::GraphicBuffer(android_native_buffer_t*, bool)
+    : BASE(), mOwner(ownData), mBufferMapper(GraphicBufferMapper::get()),
+      mInitCheck(NO_ERROR), mIndex(-1)
+{
+    width  = 
+    height = 
+    stride = 
+    format = 
+    usage  = 0;
+    transform = 0;
+    handle = NULL;
+}
+
 GraphicBuffer::GraphicBuffer(uint32_t w, uint32_t h, 
         PixelFormat reqFormat, uint32_t reqUsage)
     : BASE(), mOwner(ownData), mBufferMapper(GraphicBufferMapper::get()),
diff --git a/libs/ui/GraphicBufferAllocator.cpp b/libs/ui/GraphicBufferAllocator.cpp
index 9847a5f..fa46ab7 100644
--- a/libs/ui/GraphicBufferAllocator.cpp
+++ b/libs/ui/GraphicBufferAllocator.cpp
@@ -63,7 +63,7 @@
     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 (%4u) x %4u | %8X | 0x%08x\n",
+        snprintf(buffer, SIZE, "%10p: %7.2f KiB | %4u (%4u) x %4u | %2d | 0x%08x\n",
             list.keyAt(i), rec.size/1024.0f, 
             rec.w, rec.s, rec.h, rec.format, rec.usage);
         result.append(buffer);
diff --git a/libs/ui/InputDispatcher.cpp b/libs/ui/InputDispatcher.cpp
index 421ad663..c0872e5 100644
--- a/libs/ui/InputDispatcher.cpp
+++ b/libs/ui/InputDispatcher.cpp
@@ -37,7 +37,9 @@
 // Log debug messages about the app switch latency optimization.
 #define DEBUG_APP_SWITCH 0
 
+#include <android/input.h>
 #include <cutils/log.h>
+#include <ui/Input.h>
 #include <ui/InputDispatcher.h>
 #include <ui/PowerManager.h>
 
@@ -592,10 +594,6 @@
     // mKeyRepeatState.lastKeyEntry in addition to the one we return.
     entry->refCount += 1;
 
-    if (entry->repeatCount == 1) {
-        entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
-    }
-
     mKeyRepeatState.nextRepeatTime = currentTime + keyRepeatDelay;
     return entry;
 }
@@ -645,6 +643,12 @@
             resetKeyRepeatLocked();
         }
 
+        if (entry->repeatCount == 1) {
+            entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
+        } else {
+            entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
+        }
+
         entry->dispatchInProgress = true;
         resetTargetsLocked();
 
@@ -2092,6 +2096,26 @@
         return;
     }
 
+    /* According to http://source.android.com/porting/keymaps_keyboard_input.html
+     * Key definitions: Key definitions follow the syntax key SCANCODE KEYCODE [FLAGS...],
+     * where SCANCODE is a number, KEYCODE is defined in your specific keylayout file
+     * (android.keylayout.xxx), and potential FLAGS are defined as follows:
+     *     SHIFT: While pressed, the shift key modifier is set
+     *     ALT: While pressed, the alt key modifier is set
+     *     CAPS: While pressed, the caps lock key modifier is set
+     *     Since KeyEvent.java doesn't check if Cap lock is ON and we don't have a
+     *     modifer state for cap lock, we will not support it.
+     */
+    if (policyFlags & POLICY_FLAG_ALT) {
+        metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
+    }
+    if (policyFlags & POLICY_FLAG_ALT_GR) {
+        metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
+    }
+    if (policyFlags & POLICY_FLAG_SHIFT) {
+        metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
+    }
+
     policyFlags |= POLICY_FLAG_TRUSTED;
     mPolicy->interceptKeyBeforeQueueing(eventTime, deviceId, action, /*byref*/ flags,
             keyCode, scanCode, /*byref*/ policyFlags);
diff --git a/libs/ui/InputReader.cpp b/libs/ui/InputReader.cpp
index 34e44e4..336d489 100644
--- a/libs/ui/InputReader.cpp
+++ b/libs/ui/InputReader.cpp
@@ -547,9 +547,9 @@
             for (size_t i = 0; i < numDevices; i++) {
                 InputDevice* device = mDevices.valueAt(i);
                 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
-                    result = (device->*getStateFunc)(sourceMask, code);
-                    if (result >= AKEY_STATE_DOWN) {
-                        return result;
+                    int32_t state = (device->*getStateFunc)(sourceMask, code);
+                    if (state > result) {
+                        result = state;
                     }
                 }
             }
@@ -737,9 +737,9 @@
     for (size_t i = 0; i < numMappers; i++) {
         InputMapper* mapper = mMappers[i];
         if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
-            result = (mapper->*getStateFunc)(sourceMask, code);
-            if (result >= AKEY_STATE_DOWN) {
-                return result;
+            int32_t state = (mapper->*getStateFunc)(sourceMask, code);
+            if (state > result) {
+                result = state;
             }
         }
     }
diff --git a/libs/usb/Android.mk b/libs/usb/Android.mk
new file mode 100644
index 0000000..129828f
--- /dev/null
+++ b/libs/usb/Android.mk
@@ -0,0 +1,27 @@
+#
+# Copyright (C) 2011 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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_MODULE_TAGS := optional
+
+LOCAL_MODULE:= com.android.future.usb.accessory
+
+include $(BUILD_JAVA_LIBRARY)
diff --git a/libs/usb/src/com/android/future/usb/UsbAccessory.java b/libs/usb/src/com/android/future/usb/UsbAccessory.java
new file mode 100644
index 0000000..0f965d7
--- /dev/null
+++ b/libs/usb/src/com/android/future/usb/UsbAccessory.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.future.usb;
+
+/**
+ * A class representing a USB accessory.
+ */
+public class UsbAccessory {
+
+    private final String mManufacturer;
+    private final String mModel;
+    private final String mDescription;
+    private final String mVersion;
+    private final String mUri;
+    private final String mSerial;
+
+    /* package */ UsbAccessory(android.hardware.usb.UsbAccessory accessory) {
+        mManufacturer = accessory.getManufacturer();
+        mModel = accessory.getModel();
+        mDescription = accessory.getDescription();
+        mVersion = accessory.getVersion();
+        mUri = accessory.getUri();
+        mSerial = accessory.getSerial();
+    }
+
+    /**
+     * Returns the manufacturer of the accessory.
+     *
+     * @return the accessory manufacturer
+     */
+    public String getManufacturer() {
+        return mManufacturer;
+    }
+
+    /**
+     * Returns the model name of the accessory.
+     *
+     * @return the accessory model
+     */
+    public String getModel() {
+        return mModel;
+    }
+
+    /**
+     * Returns a user visible description of the accessory.
+     *
+     * @return the accessory description
+     */
+    public String getDescription() {
+        return mDescription;
+    }
+
+    /**
+     * Returns the version of the accessory.
+     *
+     * @return the accessory version
+     */
+    public String getVersion() {
+        return mVersion;
+    }
+
+    /**
+     * Returns the URI for the accessory.
+     * This is an optional URI that might show information about the accessory
+     * or provide the option to download an application for the accessory
+     *
+     * @return the accessory URI
+     */
+    public String getUri() {
+        return mUri;
+    }
+
+    /**
+     * Returns the unique serial number for the accessory.
+     * This is an optional serial number that can be used to differentiate
+     * between individual accessories of the same model and manufacturer
+     *
+     * @return the unique serial number
+     */
+    public String getSerial() {
+        return mSerial;
+    }
+
+    private static boolean compare(String s1, String s2) {
+        if (s1 == null) return (s2 == null);
+        return s1.equals(s2);
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (obj instanceof UsbAccessory) {
+            UsbAccessory accessory = (UsbAccessory)obj;
+            return (compare(mManufacturer, accessory.getManufacturer()) &&
+                    compare(mModel, accessory.getModel()) &&
+                    compare(mDescription, accessory.getDescription()) &&
+                    compare(mVersion, accessory.getVersion()) &&
+                    compare(mUri, accessory.getUri()) &&
+                    compare(mSerial, accessory.getSerial()));
+        }
+        return false;
+    }
+
+    @Override
+    public int hashCode() {
+        return ((mManufacturer == null ? 0 : mManufacturer.hashCode()) ^
+                (mModel == null ? 0 : mModel.hashCode()) ^
+                (mDescription == null ? 0 : mDescription.hashCode()) ^
+                (mVersion == null ? 0 : mVersion.hashCode()) ^
+                (mUri == null ? 0 : mUri.hashCode()) ^
+                (mSerial == null ? 0 : mSerial.hashCode()));
+    }
+
+    @Override
+    public String toString() {
+        return "UsbAccessory[mManufacturer=" + mManufacturer +
+                            ", mModel=" + mModel +
+                            ", mDescription=" + mDescription +
+                            ", mVersion=" + mVersion +
+                            ", mUri=" + mUri +
+                            ", mSerial=" + mSerial + "]";
+    }
+}
diff --git a/libs/usb/src/com/android/future/usb/UsbManager.java b/libs/usb/src/com/android/future/usb/UsbManager.java
new file mode 100644
index 0000000..91d8e8a
--- /dev/null
+++ b/libs/usb/src/com/android/future/usb/UsbManager.java
@@ -0,0 +1,186 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.future.usb;
+
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.hardware.usb.IUsbManager;
+import android.os.IBinder;
+import android.os.ParcelFileDescriptor;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.util.Log;
+
+/**
+ * This is a wrapper class for the USB Manager to support USB accessories.
+ *
+ * <p>You can obtain an instance of this class by calling {@link #getInstance}
+ *
+ */
+public class UsbManager {
+    private static final String TAG = "UsbManager";
+
+   /**
+     * Broadcast Action:  A broadcast for USB accessory attached event.
+     *
+     * This intent is sent when a USB accessory is attached.
+     * Call {@link #getAccessory(android.content.Intent)} to retrieve the
+     * {@link com.google.android.usb.UsbAccessory} for the attached accessory.
+     */
+    public static final String ACTION_USB_ACCESSORY_ATTACHED =
+            "android.hardware.usb.action.USB_ACCESSORY_ATTACHED";
+
+   /**
+     * Broadcast Action:  A broadcast for USB accessory detached event.
+     *
+     * This intent is sent when a USB accessory is detached.
+     * Call {@link #getAccessory(android.content.Intent)} to retrieve the
+     * {@link com.google.android.usb.UsbAccessory} for the attached accessory that was detached.
+     */
+    public static final String ACTION_USB_ACCESSORY_DETACHED =
+            "android.hardware.usb.action.USB_ACCESSORY_DETACHED";
+
+    /**
+     * Name of extra added to the {@link android.app.PendingIntent}
+     * passed into {#requestPermission} or {#requestPermission}
+     * containing a boolean value indicating whether the user granted permission or not.
+     */
+    public static final String EXTRA_PERMISSION_GRANTED = "permission";
+
+    private final Context mContext;
+    private final IUsbManager mService;
+
+    private UsbManager(Context context, IUsbManager service) {
+        mContext = context;
+        mService = service;
+    }
+
+    /**
+     * Returns a new instance of this class.
+     *
+     * @param context the caller's {@link android.content.Context}
+     * @return UsbManager instance.
+     */
+    public static UsbManager getInstance(Context context) {
+        IBinder b = ServiceManager.getService(Context.USB_SERVICE);
+        return new UsbManager(context, IUsbManager.Stub.asInterface(b));
+    }
+
+    /**
+     * Returns the {@link com.google.android.usb.UsbAccessory} for
+     * a {@link #ACTION_USB_ACCESSORY_ATTACHED} or {@link #ACTION_USB_ACCESSORY_ATTACHED}
+     * broadcast Intent. This can also be used to retrieve the accessory from the result
+     * of a call to {#requestPermission}.
+     *
+     * @return UsbAccessory for the intent.
+     */
+    public static UsbAccessory getAccessory(Intent intent) {
+        android.hardware.usb.UsbAccessory accessory =
+            intent.getParcelableExtra(android.hardware.usb.UsbManager.EXTRA_ACCESSORY);
+        if (accessory == null) {
+            return null;
+        } else {
+            return new UsbAccessory(accessory);
+        }
+    }
+
+    /**
+     * Returns a list of currently attached USB accessories.
+     * (in the current implementation there can be at most one)
+     *
+     * @return list of USB accessories, or null if none are attached.
+     */
+    public UsbAccessory[] getAccessoryList() {
+        try {
+            android.hardware.usb.UsbAccessory accessory = mService.getCurrentAccessory();
+            if (accessory == null) {
+                return null;
+            } else {
+                return new UsbAccessory[] { new UsbAccessory(accessory) };
+            }
+        } catch (RemoteException e) {
+            Log.e(TAG, "RemoteException in getAccessoryList" , e);
+            return null;
+        }
+    }
+
+    /**
+     * Opens a file descriptor for reading and writing data to the USB accessory.
+     *
+     * @param accessory the USB accessory to open
+     * @return file descriptor, or null if the accessor could not be opened.
+     */
+    public ParcelFileDescriptor openAccessory(UsbAccessory accessory) {
+        try {
+            return mService.openAccessory(new android.hardware.usb.UsbAccessory(
+                    accessory.getManufacturer(),accessory.getModel(),
+                    accessory.getDescription(), accessory.getVersion(),
+                    accessory.getUri(), accessory.getSerial()));
+        } catch (RemoteException e) {
+            Log.e(TAG, "RemoteException in openAccessory" , e);
+            return null;
+        }
+    }
+
+    /**
+     * Returns true if the caller has permission to access the accessory.
+     * Permission might have been granted temporarily via
+     * {@link #requestPermission} or
+     * by the user choosing the caller as the default application for the accessory.
+     *
+     * @param accessory to check permissions for
+     * @return true if caller has permission
+     */
+    public boolean hasPermission(UsbAccessory accessory) {
+        try {
+            return mService.hasAccessoryPermission(new android.hardware.usb.UsbAccessory(
+                    accessory.getManufacturer(),accessory.getModel(),
+                    accessory.getDescription(), accessory.getVersion(),
+                    accessory.getUri(), accessory.getSerial()));
+        } catch (RemoteException e) {
+            Log.e(TAG, "RemoteException in hasPermission", e);
+            return false;
+        }
+    }
+
+    /**
+     * Requests temporary permission for the given package to access the accessory.
+     * This may result in a system dialog being displayed to the user
+     * if permission had not already been granted.
+     * Success or failure is returned via the {@link android.app.PendingIntent} pi.
+     * The boolean extra {@link #EXTRA_PERMISSION_GRANTED} will be attached to the
+     * PendingIntent to indicate success or failure.
+     * If successful, this grants the caller permission to access the device only
+     * until the device is disconnected.
+     *
+     * @param accessory to request permissions for
+     * @param pi PendingIntent for returning result
+     */
+    public void requestPermission(UsbAccessory accessory, PendingIntent pi) {
+        try {
+            mService.requestAccessoryPermission(new android.hardware.usb.UsbAccessory(
+                    accessory.getManufacturer(),accessory.getModel(),
+                    accessory.getDescription(), accessory.getVersion(),
+                    accessory.getUri(), accessory.getSerial()),
+                    mContext.getPackageName(), pi);
+        } catch (RemoteException e) {
+            Log.e(TAG, "RemoteException in requestPermission", e);
+        }
+    }
+}
diff --git a/libs/usb/tests/AccessoryChat/Android.mk b/libs/usb/tests/AccessoryChat/Android.mk
new file mode 100644
index 0000000..77b8424
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/Android.mk
@@ -0,0 +1,31 @@
+#
+# Copyright (C) 2011 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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_MODULE_TAGS := tests
+
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
+
+LOCAL_PACKAGE_NAME := AccessoryChat
+
+LOCAL_JAVA_LIBRARIES := com.android.future.usb.accessory
+
+# Force an old SDK version to make sure we aren't using newer UsbManager APIs
+LOCAL_SDK_VERSION := 8
+
+include $(BUILD_PACKAGE)
diff --git a/libs/usb/tests/AccessoryChat/AndroidManifest.xml b/libs/usb/tests/AccessoryChat/AndroidManifest.xml
new file mode 100644
index 0000000..802b715
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/AndroidManifest.xml
@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2011 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.accessorychat">
+
+    <application android:label="Accessory Chat">
+        <uses-library android:name="com.android.future.usb.accessory" />
+
+        <activity android:name="AccessoryChat" android:label="Accessory Chat">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.DEFAULT" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+
+            <intent-filter>
+                <action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
+            </intent-filter>
+
+            <meta-data android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"
+                android:resource="@xml/accessory_filter" />
+        </activity>
+    </application>
+    <uses-sdk android:minSdkVersion="10" />
+</manifest>
diff --git a/libs/usb/tests/AccessoryChat/README.txt b/libs/usb/tests/AccessoryChat/README.txt
new file mode 100644
index 0000000..d2ce11e
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/README.txt
@@ -0,0 +1,10 @@
+This is a test app for the USB accessory APIs.  It consists of two parts:
+
+AccessoryChat - A Java app with a chat-like UI that sends and receives strings
+                via the UsbAccessory class.
+
+accessorychat - A C command-line program that communicates with AccessoryChat.
+                This program behaves as if it were a USB accessory.
+                It builds both for the host (Linux PC) and as an android
+                command line program, which will work if run as root on an
+                android device with USB host support
diff --git a/libs/usb/tests/AccessoryChat/accessorychat/Android.mk b/libs/usb/tests/AccessoryChat/accessorychat/Android.mk
new file mode 100644
index 0000000..5a7b30e
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/accessorychat/Android.mk
@@ -0,0 +1,21 @@
+LOCAL_PATH:= $(call my-dir)
+
+# Build for Linux (desktop) host
+ifeq ($(HOST_OS),linux)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := accessorychat.c usbhost.c
+
+LOCAL_MODULE := accessorychat
+
+LOCAL_C_INCLUDES += bionic/libc/kernel/common
+LOCAL_STATIC_LIBRARIES := libcutils
+LOCAL_LDLIBS += -lpthread
+LOCAL_CFLAGS := -g -O0
+
+include $(BUILD_HOST_EXECUTABLE)
+
+endif
diff --git a/libs/usb/tests/AccessoryChat/accessorychat/accessorychat.c b/libs/usb/tests/AccessoryChat/accessorychat/accessorychat.c
new file mode 100644
index 0000000..85b52dd
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/accessorychat/accessorychat.c
@@ -0,0 +1,196 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <unistd.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <pthread.h>
+#include <time.h>
+
+#include <usbhost/usbhost.h>
+#include <linux/usb/f_accessory.h>
+
+struct usb_device *sDevice = NULL;
+
+static void* read_thread(void* arg) {
+    int endpoint = (int)arg;
+    int ret = 0;
+
+    while (sDevice && ret >= 0) {
+        char    buffer[16384];
+
+        ret = usb_device_bulk_transfer(sDevice, endpoint, buffer, sizeof(buffer), 1000);
+        if (ret < 0 && errno == ETIMEDOUT)
+            ret = 0;
+        if (ret > 0) {
+            fwrite(buffer, 1, ret, stdout);
+            printf("\n");
+            fflush(stdout);
+        }
+    }
+
+    return NULL;
+}
+
+static void* write_thread(void* arg) {
+    int endpoint = (int)arg;
+    int ret = 0;
+
+    while (ret >= 0) {
+        char    buffer[16384];
+        char *line = fgets(buffer, sizeof(buffer), stdin);
+        if (!line || !sDevice)
+            break;
+        ret = usb_device_bulk_transfer(sDevice, endpoint, line, strlen(line), 1000);
+    }
+
+    return NULL;
+}
+
+static void milli_sleep(int millis) {
+    struct timespec tm;
+
+    tm.tv_sec = 0;
+    tm.tv_nsec = millis * 1000000;
+    nanosleep(&tm, NULL);
+}
+
+static void send_string(struct usb_device *device, int index, const char* string) {
+    int ret = usb_device_control_transfer(device, USB_DIR_OUT | USB_TYPE_VENDOR,
+            ACCESSORY_SEND_STRING, 0, index, (void *)string, strlen(string) + 1, 0);
+
+    // some devices can't handle back-to-back requests, so delay a bit
+    milli_sleep(10);
+}
+
+static int usb_device_added(const char *devname, void* client_data) {
+    struct usb_descriptor_header* desc;
+    struct usb_descriptor_iter iter;
+    uint16_t vendorId, productId;
+    int ret;
+    pthread_t th;
+
+    struct usb_device *device = usb_device_open(devname);
+    if (!device) {
+        fprintf(stderr, "usb_device_open failed\n");
+        return 0;
+    }
+
+    vendorId = usb_device_get_vendor_id(device);
+    productId = usb_device_get_product_id(device);
+
+    if (vendorId == 0x18D1 || vendorId == 0x22B8) {
+        if (!sDevice && (productId == 0x2D00 || productId == 0x2D01)) {
+            struct usb_descriptor_header* desc;
+            struct usb_descriptor_iter iter;
+            struct usb_interface_descriptor *intf = NULL;
+            struct usb_endpoint_descriptor *ep1 = NULL;
+            struct usb_endpoint_descriptor *ep2 = NULL;
+
+            printf("Found android device in accessory mode\n");
+            sDevice = device;
+
+            usb_descriptor_iter_init(device, &iter);
+            while ((desc = usb_descriptor_iter_next(&iter)) != NULL && (!intf || !ep1 || !ep2)) {
+                if (desc->bDescriptorType == USB_DT_INTERFACE) {
+                    intf = (struct usb_interface_descriptor *)desc;
+                } else if (desc->bDescriptorType == USB_DT_ENDPOINT) {
+                    if (ep1)
+                        ep2 = (struct usb_endpoint_descriptor *)desc;
+                    else
+                        ep1 = (struct usb_endpoint_descriptor *)desc;
+                }
+            }
+
+            if (!intf) {
+                fprintf(stderr, "interface not found\n");
+                exit(1);
+            }
+            if (!ep1 || !ep2) {
+                fprintf(stderr, "endpoints not found\n");
+                exit(1);
+            }
+
+            if (usb_device_claim_interface(device, intf->bInterfaceNumber)) {
+                fprintf(stderr, "usb_device_claim_interface failed errno: %d\n", errno);
+                exit(1);
+            }
+
+            if ((ep1->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN) {
+                pthread_create(&th, NULL, read_thread, (void *)ep1->bEndpointAddress);
+                pthread_create(&th, NULL, write_thread, (void *)ep2->bEndpointAddress);
+            } else {
+                pthread_create(&th, NULL, read_thread, (void *)ep2->bEndpointAddress);
+                pthread_create(&th, NULL, write_thread, (void *)ep1->bEndpointAddress);
+            }
+        } else {
+            printf("Found possible android device - attempting to switch to accessory mode\n");
+
+            uint16_t protocol;
+            ret = usb_device_control_transfer(device, USB_DIR_IN | USB_TYPE_VENDOR,
+                    ACCESSORY_GET_PROTOCOL, 0, 0, &protocol, sizeof(protocol), 0);
+            if (ret == 2)
+                printf("device supports protocol version %d\n", protocol);
+            else
+                fprintf(stderr, "failed to read protocol version\n");
+
+            send_string(device, ACCESSORY_STRING_MANUFACTURER, "Google, Inc.");
+            send_string(device, ACCESSORY_STRING_MODEL, "AccessoryChat");
+            send_string(device, ACCESSORY_STRING_DESCRIPTION, "Accessory Chat");
+            send_string(device, ACCESSORY_STRING_VERSION, "1.0");
+            send_string(device, ACCESSORY_STRING_URI, "http://www.android.com");
+            send_string(device, ACCESSORY_STRING_SERIAL, "1234567890");
+
+            ret = usb_device_control_transfer(device, USB_DIR_OUT | USB_TYPE_VENDOR,
+                    ACCESSORY_START, 0, 0, 0, 0, 0);
+            return 0;
+        }
+    }
+
+    if (device != sDevice)
+        usb_device_close(device);
+
+    return 0;
+}
+
+static int usb_device_removed(const char *devname, void* client_data) {
+    if (sDevice && !strcmp(usb_device_get_name(sDevice), devname)) {
+        usb_device_close(sDevice);
+        sDevice = NULL;
+        // exit when we are disconnected
+        return 1;
+    }
+    return 0;
+}
+
+
+int main(int argc, char* argv[]) {
+    struct usb_host_context* context = usb_host_init();
+    if (!context) {
+        fprintf(stderr, "usb_host_init failed");
+        return 1;
+    }
+
+    // this will never return so it is safe to pass thiz directly
+    usb_host_run(context, usb_device_added, usb_device_removed, NULL, NULL);
+    return 0;
+}
diff --git a/libs/usb/tests/AccessoryChat/accessorychat/usbhost.c b/libs/usb/tests/AccessoryChat/accessorychat/usbhost.c
new file mode 100644
index 0000000..f5a7c3f
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/accessorychat/usbhost.c
@@ -0,0 +1,574 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// #define DEBUG 1
+#if DEBUG
+
+#ifdef USE_LIBLOG
+#define LOG_TAG "usbhost"
+#include "utils/Log.h"
+#define D LOGD
+#else
+#define D printf
+#endif
+
+#else
+#define D(...)
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <string.h>
+
+#include <sys/ioctl.h>
+#include <sys/types.h>
+#include <sys/time.h>
+#include <sys/inotify.h>
+#include <dirent.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <ctype.h>
+#include <pthread.h>
+
+#include <linux/usbdevice_fs.h>
+#include <asm/byteorder.h>
+
+#include "usbhost/usbhost.h"
+
+#define USB_FS_DIR "/dev/bus/usb"
+#define USB_FS_ID_SCANNER   "/dev/bus/usb/%d/%d"
+#define USB_FS_ID_FORMAT    "/dev/bus/usb/%03d/%03d"
+
+
+struct usb_host_context {
+    int fd;
+};
+
+struct usb_device {
+    char dev_name[64];
+    unsigned char desc[4096];
+    int desc_length;
+    int fd;
+    int writeable;
+};
+
+static inline int badname(const char *name)
+{
+    while(*name) {
+        if(!isdigit(*name++)) return 1;
+    }
+    return 0;
+}
+
+/* returns true if one of the callbacks indicates we are done */
+static int find_existing_devices(usb_device_added_cb added_cb,
+                                  usb_device_removed_cb removed_cb,
+                                  void *client_data)
+{
+    char busname[32], devname[32];
+    DIR *busdir , *devdir ;
+    struct dirent *de;
+    int done = 0;
+
+    busdir = opendir(USB_FS_DIR);
+    if(busdir == 0) return 1;
+
+    while ((de = readdir(busdir)) != 0 && !done) {
+        if(badname(de->d_name)) continue;
+
+        snprintf(busname, sizeof busname, "%s/%s", USB_FS_DIR, de->d_name);
+        devdir = opendir(busname);
+        if(devdir == 0) continue;
+
+        while ((de = readdir(devdir)) && !done) {
+            if(badname(de->d_name)) continue;
+
+            snprintf(devname, sizeof devname, "%s/%s", busname, de->d_name);
+            done = added_cb(devname, client_data);
+        } // end of devdir while
+        closedir(devdir);
+    } //end of busdir while
+    closedir(busdir);
+
+    return done;
+}
+
+struct usb_host_context *usb_host_init()
+{
+    struct usb_host_context *context = calloc(1, sizeof(struct usb_host_context));
+    if (!context) {
+        fprintf(stderr, "out of memory in usb_host_context\n");
+        return NULL;
+    }
+    context->fd = inotify_init();
+    if (context->fd < 0) {
+        fprintf(stderr, "inotify_init failed\n");
+        free(context);
+        return NULL;
+    }
+    return context;
+}
+
+void usb_host_cleanup(struct usb_host_context *context)
+{
+    close(context->fd);
+    free(context);
+}
+
+void usb_host_run(struct usb_host_context *context,
+                  usb_device_added_cb added_cb,
+                  usb_device_removed_cb removed_cb,
+                  usb_discovery_done_cb discovery_done_cb,
+                  void *client_data)
+{
+    struct inotify_event* event;
+    char event_buf[512];
+    char path[100];
+    int i, ret, done = 0;
+    int wd, wds[10];
+    int wd_count = sizeof(wds) / sizeof(wds[0]);
+
+    D("Created device discovery thread\n");
+
+    /* watch for files added and deleted within USB_FS_DIR */
+    memset(wds, 0, sizeof(wds));
+    /* watch the root for new subdirectories */
+    wds[0] = inotify_add_watch(context->fd, USB_FS_DIR, IN_CREATE | IN_DELETE);
+    if (wds[0] < 0) {
+        fprintf(stderr, "inotify_add_watch failed\n");
+        if (discovery_done_cb)
+            discovery_done_cb(client_data);
+        return;
+    }
+
+    /* watch existing subdirectories of USB_FS_DIR */
+    for (i = 1; i < wd_count; i++) {
+        snprintf(path, sizeof(path), "%s/%03d", USB_FS_DIR, i);
+        ret = inotify_add_watch(context->fd, path, IN_CREATE | IN_DELETE);
+        if (ret > 0)
+            wds[i] = ret;
+    }
+
+    /* check for existing devices first, after we have inotify set up */
+    done = find_existing_devices(added_cb, removed_cb, client_data);
+    if (discovery_done_cb)
+        done |= discovery_done_cb(client_data);
+
+    while (!done) {
+        ret = read(context->fd, event_buf, sizeof(event_buf));
+        if (ret >= (int)sizeof(struct inotify_event)) {
+            event = (struct inotify_event *)event_buf;
+            wd = event->wd;
+            if (wd == wds[0]) {
+                i = atoi(event->name);
+                snprintf(path, sizeof(path), "%s/%s", USB_FS_DIR, event->name);
+                D("new subdirectory %s: index: %d\n", path, i);
+                if (i > 0 && i < wd_count) {
+                ret = inotify_add_watch(context->fd, path, IN_CREATE | IN_DELETE);
+                if (ret > 0)
+                    wds[i] = ret;
+                }
+            } else {
+                for (i = 1; i < wd_count && !done; i++) {
+                    if (wd == wds[i]) {
+                        snprintf(path, sizeof(path), "%s/%03d/%s", USB_FS_DIR, i, event->name);
+                        if (event->mask == IN_CREATE) {
+                            D("new device %s\n", path);
+                            done = added_cb(path, client_data);
+                        } else if (event->mask == IN_DELETE) {
+                            D("gone device %s\n", path);
+                            done = removed_cb(path, client_data);
+                        }
+                    }
+                }
+            }
+        }
+    }
+}
+
+struct usb_device *usb_device_open(const char *dev_name)
+{
+    int fd, did_retry = 0, writeable = 1;
+
+    D("usb_device_open %s\n", dev_name);
+
+retry:
+    fd = open(dev_name, O_RDWR);
+    if (fd < 0) {
+        /* if we fail, see if have read-only access */
+        fd = open(dev_name, O_RDONLY);
+        D("usb_device_open open returned %d errno %d\n", fd, errno);
+        if (fd < 0 && (errno == EACCES || errno == ENOENT) && !did_retry) {
+            /* work around race condition between inotify and permissions management */
+            sleep(1);
+            did_retry = 1;
+            goto retry;
+        }
+
+        if (fd < 0)
+            return NULL;
+        writeable = 0;
+        D("[ usb open read-only %s fd = %d]\n", dev_name, fd);
+    }
+
+    struct usb_device* result = usb_device_new(dev_name, fd);
+    if (result)
+        result->writeable = writeable;
+    return result;
+}
+
+void usb_device_close(struct usb_device *device)
+{
+    close(device->fd);
+    free(device);
+}
+
+struct usb_device *usb_device_new(const char *dev_name, int fd)
+{
+    struct usb_device *device = calloc(1, sizeof(struct usb_device));
+    int length;
+
+    D("usb_device_new %s fd: %d\n", dev_name, fd);
+
+    if (lseek(fd, 0, SEEK_SET) != 0)
+        goto failed;
+    length = read(fd, device->desc, sizeof(device->desc));
+    D("usb_device_new read returned %d errno %d\n", length, errno);
+    if (length < 0)
+        goto failed;
+
+    strncpy(device->dev_name, dev_name, sizeof(device->dev_name) - 1);
+    device->fd = fd;
+    device->desc_length = length;
+    // assume we are writeable, since usb_device_get_fd will only return writeable fds
+    device->writeable = 1;
+    return device;
+
+failed:
+    close(fd);
+    free(device);
+    return NULL;
+}
+
+static int usb_device_reopen_writeable(struct usb_device *device)
+{
+    if (device->writeable)
+        return 1;
+
+    int fd = open(device->dev_name, O_RDWR);
+    if (fd >= 0) {
+        close(device->fd);
+        device->fd = fd;
+        device->writeable = 1;
+        return 1;
+    }
+    D("usb_device_reopen_writeable failed errno %d\n", errno);
+    return 0;
+}
+
+int usb_device_get_fd(struct usb_device *device)
+{
+    if (!usb_device_reopen_writeable(device))
+        return -1;
+    return device->fd;
+}
+
+const char* usb_device_get_name(struct usb_device *device)
+{
+    return device->dev_name;
+}
+
+int usb_device_get_unique_id(struct usb_device *device)
+{
+    int bus = 0, dev = 0;
+    sscanf(device->dev_name, USB_FS_ID_SCANNER, &bus, &dev);
+    return bus * 1000 + dev;
+}
+
+int usb_device_get_unique_id_from_name(const char* name)
+{
+    int bus = 0, dev = 0;
+    sscanf(name, USB_FS_ID_SCANNER, &bus, &dev);
+    return bus * 1000 + dev;
+}
+
+char* usb_device_get_name_from_unique_id(int id)
+{
+    int bus = id / 1000;
+    int dev = id % 1000;
+    char* result = (char *)calloc(1, strlen(USB_FS_ID_FORMAT));
+    snprintf(result, strlen(USB_FS_ID_FORMAT) - 1, USB_FS_ID_FORMAT, bus, dev);
+    return result;
+}
+
+uint16_t usb_device_get_vendor_id(struct usb_device *device)
+{
+    struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc;
+    return __le16_to_cpu(desc->idVendor);
+}
+
+uint16_t usb_device_get_product_id(struct usb_device *device)
+{
+    struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc;
+    return __le16_to_cpu(desc->idProduct);
+}
+
+const struct usb_device_descriptor* usb_device_get_device_descriptor(struct usb_device *device)
+{
+    return (struct usb_device_descriptor*)device->desc;
+}
+
+char* usb_device_get_string(struct usb_device *device, int id)
+{
+    char string[256];
+    __u16 buffer[128];
+    __u16 languages[128];
+    int i, result;
+    int languageCount = 0;
+
+    string[0] = 0;
+    memset(languages, 0, sizeof(languages));
+
+    // read list of supported languages
+    result = usb_device_control_transfer(device,
+            USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
+            (USB_DT_STRING << 8) | 0, 0, languages, sizeof(languages), 0);
+    if (result > 0)
+        languageCount = (result - 2) / 2;
+
+    for (i = 1; i <= languageCount; i++) {
+        memset(buffer, 0, sizeof(buffer));
+
+        result = usb_device_control_transfer(device,
+                USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
+                (USB_DT_STRING << 8) | id, languages[i], buffer, sizeof(buffer), 0);
+        if (result > 0) {
+            int i;
+            // skip first word, and copy the rest to the string, changing shorts to bytes.
+            result /= 2;
+            for (i = 1; i < result; i++)
+                string[i - 1] = buffer[i];
+            string[i - 1] = 0;
+            return strdup(string);
+        }
+    }
+
+    return NULL;
+}
+
+char* usb_device_get_manufacturer_name(struct usb_device *device)
+{
+    struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
+
+    if (desc->iManufacturer)
+        return usb_device_get_string(device, desc->iManufacturer);
+    else
+        return NULL;
+}
+
+char* usb_device_get_product_name(struct usb_device *device)
+{
+    struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
+
+    if (desc->iProduct)
+        return usb_device_get_string(device, desc->iProduct);
+    else
+        return NULL;
+}
+
+char* usb_device_get_serial(struct usb_device *device)
+{
+    struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
+
+    if (desc->iSerialNumber)
+        return usb_device_get_string(device, desc->iSerialNumber);
+    else
+        return NULL;
+}
+
+int usb_device_is_writeable(struct usb_device *device)
+{
+    return device->writeable;
+}
+
+void usb_descriptor_iter_init(struct usb_device *device, struct usb_descriptor_iter *iter)
+{
+    iter->config = device->desc;
+    iter->config_end = device->desc + device->desc_length;
+    iter->curr_desc = device->desc;
+}
+
+struct usb_descriptor_header *usb_descriptor_iter_next(struct usb_descriptor_iter *iter)
+{
+    struct usb_descriptor_header* next;
+    if (iter->curr_desc >= iter->config_end)
+        return NULL;
+    next = (struct usb_descriptor_header*)iter->curr_desc;
+    iter->curr_desc += next->bLength;
+    return next;
+}
+
+int usb_device_claim_interface(struct usb_device *device, unsigned int interface)
+{
+    return ioctl(device->fd, USBDEVFS_CLAIMINTERFACE, &interface);
+}
+
+int usb_device_release_interface(struct usb_device *device, unsigned int interface)
+{
+    return ioctl(device->fd, USBDEVFS_RELEASEINTERFACE, &interface);
+}
+
+int usb_device_connect_kernel_driver(struct usb_device *device,
+        unsigned int interface, int connect)
+{
+    struct usbdevfs_ioctl ctl;
+
+    ctl.ifno = interface;
+    ctl.ioctl_code = (connect ? USBDEVFS_CONNECT : USBDEVFS_DISCONNECT);
+    ctl.data = NULL;
+    return ioctl(device->fd, USBDEVFS_IOCTL, &ctl);
+}
+
+int usb_device_control_transfer(struct usb_device *device,
+                            int requestType,
+                            int request,
+                            int value,
+                            int index,
+                            void* buffer,
+                            int length,
+                            unsigned int timeout)
+{
+    struct usbdevfs_ctrltransfer  ctrl;
+
+    // this usually requires read/write permission
+    if (!usb_device_reopen_writeable(device))
+        return -1;
+
+    memset(&ctrl, 0, sizeof(ctrl));
+    ctrl.bRequestType = requestType;
+    ctrl.bRequest = request;
+    ctrl.wValue = value;
+    ctrl.wIndex = index;
+    ctrl.wLength = length;
+    ctrl.data = buffer;
+    ctrl.timeout = timeout;
+    return ioctl(device->fd, USBDEVFS_CONTROL, &ctrl);
+}
+
+int usb_device_bulk_transfer(struct usb_device *device,
+                            int endpoint,
+                            void* buffer,
+                            int length,
+                            unsigned int timeout)
+{
+    struct usbdevfs_bulktransfer  ctrl;
+
+    memset(&ctrl, 0, sizeof(ctrl));
+    ctrl.ep = endpoint;
+    ctrl.len = length;
+    ctrl.data = buffer;
+    ctrl.timeout = timeout;
+    return ioctl(device->fd, USBDEVFS_BULK, &ctrl);
+}
+
+struct usb_request *usb_request_new(struct usb_device *dev,
+        const struct usb_endpoint_descriptor *ep_desc)
+{
+    struct usbdevfs_urb *urb = calloc(1, sizeof(struct usbdevfs_urb));
+    if (!urb)
+        return NULL;
+
+    if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK)
+        urb->type = USBDEVFS_URB_TYPE_BULK;
+    else if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT)
+        urb->type = USBDEVFS_URB_TYPE_INTERRUPT;
+    else {
+        D("Unsupported endpoint type %d", ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK);
+        free(urb);
+        return NULL;
+    }
+    urb->endpoint = ep_desc->bEndpointAddress;
+
+    struct usb_request *req = calloc(1, sizeof(struct usb_request));
+    if (!req) {
+        free(urb);
+        return NULL;
+    }
+
+    req->dev = dev;
+    req->max_packet_size = __le16_to_cpu(ep_desc->wMaxPacketSize);
+    req->private_data = urb;
+    req->endpoint = urb->endpoint;
+    urb->usercontext = req;
+
+    return req;
+}
+
+void usb_request_free(struct usb_request *req)
+{
+    free(req->private_data);
+    free(req);
+}
+
+int usb_request_queue(struct usb_request *req)
+{
+    struct usbdevfs_urb *urb = (struct usbdevfs_urb*)req->private_data;
+    int res;
+
+    urb->status = -1;
+    urb->buffer = req->buffer;
+    urb->buffer_length = req->buffer_length;
+
+    do {
+        res = ioctl(req->dev->fd, USBDEVFS_SUBMITURB, urb);
+    } while((res < 0) && (errno == EINTR));
+
+    return res;
+}
+
+struct usb_request *usb_request_wait(struct usb_device *dev)
+{
+    struct usbdevfs_urb *urb = NULL;
+    struct usb_request *req = NULL;
+    int res;
+
+    while (1) {
+        int res = ioctl(dev->fd, USBDEVFS_REAPURB, &urb);
+        D("USBDEVFS_REAPURB returned %d\n", res);
+        if (res < 0) {
+            if(errno == EINTR) {
+                continue;
+            }
+            D("[ reap urb - error ]\n");
+            return NULL;
+        } else {
+            D("[ urb @%p status = %d, actual = %d ]\n",
+                urb, urb->status, urb->actual_length);
+            req = (struct usb_request*)urb->usercontext;
+            req->actual_length = urb->actual_length;
+        }
+        break;
+    }
+    return req;
+}
+
+int usb_request_cancel(struct usb_request *req)
+{
+    struct usbdevfs_urb *urb = ((struct usbdevfs_urb*)req->private_data);
+    return ioctl(req->dev->fd, USBDEVFS_DISCARDURB, &urb);
+}
+
diff --git a/libs/usb/tests/AccessoryChat/accessorychat/usbhost/usbhost.h b/libs/usb/tests/AccessoryChat/accessorychat/usbhost/usbhost.h
new file mode 100644
index 0000000..9a6b59c
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/accessorychat/usbhost/usbhost.h
@@ -0,0 +1,219 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __USB_HOST_H
+#define __USB_HOST_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+
+#include <linux/version.h>
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20)
+#include <linux/usb/ch9.h>
+#else
+#include <linux/usb_ch9.h>
+#endif
+
+struct usb_host_context;
+struct usb_endpoint_descriptor;
+
+struct usb_descriptor_iter {
+    unsigned char*  config;
+    unsigned char*  config_end;
+    unsigned char*  curr_desc;
+};
+
+struct usb_request
+{
+    struct usb_device *dev;
+    void* buffer;
+    int buffer_length;
+    int actual_length;
+    int max_packet_size;
+    void *private_data; /* struct usbdevfs_urb* */
+    int endpoint;
+    void *client_data;  /* free for use by client */
+};
+
+/* Callback for notification when new USB devices are attached.
+ * Return true to exit from usb_host_run.
+ */
+typedef int (* usb_device_added_cb)(const char *dev_name, void *client_data);
+
+/* Callback for notification when USB devices are removed.
+ * Return true to exit from usb_host_run.
+ */
+typedef int (* usb_device_removed_cb)(const char *dev_name, void *client_data);
+
+/* Callback indicating that initial device discovery is done.
+ * Return true to exit from usb_host_run.
+ */
+typedef int (* usb_discovery_done_cb)(void *client_data);
+
+/* Call this to initialize the USB host library. */
+struct usb_host_context *usb_host_init(void);
+
+/* Call this to cleanup the USB host library. */
+void usb_host_cleanup(struct usb_host_context *context);
+
+/* Call this to monitor the USB bus for new and removed devices.
+ * This is intended to be called from a dedicated thread,
+ * as it will not return until one of the callbacks returns true.
+ * added_cb will be called immediately for each existing USB device,
+ * and subsequently each time a new device is added.
+ * removed_cb is called when USB devices are removed from the bus.
+ * discovery_done_cb is called after the initial discovery of already
+ * connected devices is complete.
+ */
+void usb_host_run(struct usb_host_context *context,
+                  usb_device_added_cb added_cb,
+                  usb_device_removed_cb removed_cb,
+                  usb_discovery_done_cb discovery_done_cb,
+                  void *client_data);
+
+/* Creates a usb_device object for a USB device */
+struct usb_device *usb_device_open(const char *dev_name);
+
+/* Releases all resources associated with the USB device */
+void usb_device_close(struct usb_device *device);
+
+/* Creates a usb_device object for already open USB device */
+struct usb_device *usb_device_new(const char *dev_name, int fd);
+
+/* Returns the file descriptor for the usb_device */
+int usb_device_get_fd(struct usb_device *device);
+
+/* Returns the name for the USB device, which is the same as
+ * the dev_name passed to usb_device_open()
+ */
+const char* usb_device_get_name(struct usb_device *device);
+
+/* Returns a unique ID for the device.
+ *Currently this is generated from the dev_name path.
+ */
+int usb_device_get_unique_id(struct usb_device *device);
+
+/* Returns a unique ID for the device name.
+ * Currently this is generated from the device path.
+ */
+int usb_device_get_unique_id_from_name(const char* name);
+
+/* Returns the device name for the unique ID.
+ * Call free() to deallocate the returned string */
+char* usb_device_get_name_from_unique_id(int id);
+
+/* Returns the USB vendor ID from the device descriptor for the USB device */
+uint16_t usb_device_get_vendor_id(struct usb_device *device);
+
+/* Returns the USB product ID from the device descriptor for the USB device */
+uint16_t usb_device_get_product_id(struct usb_device *device);
+
+const struct usb_device_descriptor* usb_device_get_device_descriptor(struct usb_device *device);
+
+/* Returns a USB descriptor string for the given string ID.
+ * Used to implement usb_device_get_manufacturer_name,
+ * usb_device_get_product_name and usb_device_get_serial.
+ * Call free() to free the result when you are done with it.
+ */
+char* usb_device_get_string(struct usb_device *device, int id);
+
+/* Returns the manufacturer name for the USB device.
+ * Call free() to free the result when you are done with it.
+ */
+char* usb_device_get_manufacturer_name(struct usb_device *device);
+
+/* Returns the product name for the USB device.
+ * Call free() to free the result when you are done with it.
+ */
+char* usb_device_get_product_name(struct usb_device *device);
+
+/* Returns the USB serial number for the USB device.
+ * Call free() to free the result when you are done with it.
+ */
+char* usb_device_get_serial(struct usb_device *device);
+
+/* Returns true if we have write access to the USB device,
+ * and false if we only have access to the USB device configuration.
+ */
+int usb_device_is_writeable(struct usb_device *device);
+
+/* Initializes a usb_descriptor_iter, which can be used to iterate through all
+ * the USB descriptors for a USB device.
+ */
+void usb_descriptor_iter_init(struct usb_device *device, struct usb_descriptor_iter *iter);
+
+/* Returns the next USB descriptor for a device, or NULL if we have reached the
+ * end of the list.
+ */
+struct usb_descriptor_header *usb_descriptor_iter_next(struct usb_descriptor_iter *iter);
+
+/* Claims the specified interface of a USB device */
+int usb_device_claim_interface(struct usb_device *device, unsigned int interface);
+
+/* Releases the specified interface of a USB device */
+int usb_device_release_interface(struct usb_device *device, unsigned int interface);
+
+/* Requests the kernel to connect or disconnect its driver for the specified interface.
+ * This can be used to ask the kernel to disconnect its driver for a device
+ * so usb_device_claim_interface can claim it instead.
+ */
+int usb_device_connect_kernel_driver(struct usb_device *device,
+        unsigned int interface, int connect);
+
+/* Sends a control message to the specified device on endpoint zero */
+int usb_device_control_transfer(struct usb_device *device,
+                            int requestType,
+                            int request,
+                            int value,
+                            int index,
+                            void* buffer,
+                            int length,
+                            unsigned int timeout);
+
+/* Reads or writes on a bulk endpoint.
+ * Returns number of bytes transferred, or negative value for error.
+ */
+int usb_device_bulk_transfer(struct usb_device *device,
+                            int endpoint,
+                            void* buffer,
+                            int length,
+                            unsigned int timeout);
+
+/* Creates a new usb_request. */
+struct usb_request *usb_request_new(struct usb_device *dev,
+        const struct usb_endpoint_descriptor *ep_desc);
+
+/* Releases all resources associated with the request */
+void usb_request_free(struct usb_request *req);
+
+/* Submits a read or write request on the specified device */
+int usb_request_queue(struct usb_request *req);
+
+ /* Waits for the results of a previous usb_request_queue operation.
+  * Returns a usb_request, or NULL for error.
+  */
+struct usb_request *usb_request_wait(struct usb_device *dev);
+
+/* Cancels a pending usb_request_queue() operation. */
+int usb_request_cancel(struct usb_request *req);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* __USB_HOST_H */
diff --git a/libs/usb/tests/AccessoryChat/res/layout/accessory_chat.xml b/libs/usb/tests/AccessoryChat/res/layout/accessory_chat.xml
new file mode 100644
index 0000000..596ecbf
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/res/layout/accessory_chat.xml
@@ -0,0 +1,47 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2011 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT 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="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="vertical"
+    >
+
+    <ScrollView android:id="@+id/scroll"
+        android:layout_width="match_parent"
+        android:layout_height="0px"
+        android:layout_weight="1"
+        >
+        <TextView android:id="@+id/log"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_marginTop="25dp"
+            android:textSize="12sp"
+            android:textColor="#ffffffff"
+            />
+    </ScrollView>
+
+    <EditText android:id="@+id/message"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:capitalize="sentences"
+        android:autoText="true"
+        android:singleLine="true"
+        />
+
+</LinearLayout>
+
+
diff --git a/libs/usb/tests/AccessoryChat/res/xml/accessory_filter.xml b/libs/usb/tests/AccessoryChat/res/xml/accessory_filter.xml
new file mode 100644
index 0000000..588946f
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/res/xml/accessory_filter.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2011 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<resources>
+    <usb-accessory manufacturer="Google, Inc." model="AccessoryChat" type="Sample Program" version="1.0" />
+</resources>
diff --git a/libs/usb/tests/AccessoryChat/src/com/android/accessorychat/AccessoryChat.java b/libs/usb/tests/AccessoryChat/src/com/android/accessorychat/AccessoryChat.java
new file mode 100644
index 0000000..c3f4fa3
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/src/com/android/accessorychat/AccessoryChat.java
@@ -0,0 +1,199 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.accessorychat;
+
+import android.app.Activity;
+import android.app.PendingIntent;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.os.ParcelFileDescriptor;
+import android.view.KeyEvent;
+import android.view.View;
+import android.view.inputmethod.EditorInfo;
+import android.util.Log;
+import android.widget.EditText;
+import android.widget.TextView;
+
+import com.android.future.usb.UsbAccessory;
+import com.android.future.usb.UsbManager;
+
+import java.io.FileDescriptor;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+public class AccessoryChat extends Activity implements Runnable, TextView.OnEditorActionListener {
+
+    private static final String TAG = "AccessoryChat";
+
+    private static final String ACTION_USB_PERMISSION =
+            "com.android.accessorychat.action.USB_PERMISSION";
+
+    private TextView mLog;
+    private EditText mEditText;
+    private ParcelFileDescriptor mFileDescriptor;
+    private FileInputStream mInputStream;
+    private FileOutputStream mOutputStream;
+    private UsbManager mUsbManager;
+    private PendingIntent mPermissionIntent;
+    private boolean mPermissionRequestPending;
+
+    private static final int MESSAGE_LOG = 1;
+
+   private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            if (ACTION_USB_PERMISSION.equals(intent.getAction())) {
+                synchronized (this) {
+                    UsbAccessory accessory = UsbManager.getAccessory(intent);
+                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
+                        openAccessory(accessory);
+                    } else {
+                        Log.d(TAG, "permission denied for accessory " + accessory);
+                    }
+                    mPermissionRequestPending = false;
+                }
+            }
+        }
+    };
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        mUsbManager = UsbManager.getInstance(this);
+        mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
+        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
+        registerReceiver(mUsbReceiver, filter);
+
+        setContentView(R.layout.accessory_chat);
+        mLog = (TextView)findViewById(R.id.log);
+        mEditText = (EditText)findViewById(R.id.message);
+        mEditText.setOnEditorActionListener(this);
+    }
+
+    @Override
+    public void onResume() {
+        super.onResume();
+
+        Intent intent = getIntent();
+        Log.d(TAG, "intent: " + intent);
+        UsbAccessory[] accessories = mUsbManager.getAccessoryList();
+        UsbAccessory accessory = (accessories == null ? null : accessories[0]);
+        if (accessory != null) {
+            if (mUsbManager.hasPermission(accessory)) {
+                openAccessory(accessory);
+            } else {
+                synchronized (mUsbReceiver) {
+                    if (!mPermissionRequestPending) {
+                        mUsbManager.requestPermission(accessory, mPermissionIntent);
+                        mPermissionRequestPending = true;
+                    }
+                }
+            }
+         } else {
+            Log.d(TAG, "mAccessory is null");
+        }
+    }
+
+    @Override
+    public void onPause() {
+        super.onPause();
+        if (mFileDescriptor != null) {
+            try {
+                mFileDescriptor.close();
+            } catch (IOException e) {
+            } finally {
+                mFileDescriptor = null;
+            }
+        }
+    }
+
+    @Override
+    public void onDestroy() {
+        unregisterReceiver(mUsbReceiver);
+       super.onDestroy();
+    }
+
+    private void openAccessory(UsbAccessory accessory) {
+        Log.d(TAG, "openAccessory: " + accessory);
+        mFileDescriptor = mUsbManager.openAccessory(accessory);
+        if (mFileDescriptor != null) {
+            FileDescriptor fd = mFileDescriptor.getFileDescriptor();
+            mInputStream = new FileInputStream(fd);
+            mOutputStream = new FileOutputStream(fd);
+            Thread thread = new Thread(null, this, "AccessoryChat");
+            thread.start();
+            Log.d(TAG, "openAccessory succeeded");
+        } else {
+            Log.d(TAG, "openAccessory fail");
+        }
+    }
+
+    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
+        if (actionId == EditorInfo.IME_ACTION_DONE && mOutputStream != null) {
+            try {
+                mOutputStream.write(v.getText().toString().getBytes());
+            } catch (IOException e) {
+                Log.e(TAG, "write failed", e);
+            }
+            v.setText("");
+            return true;
+        }
+        Log.d(TAG, "onEditorAction " + actionId + " event: " + event);
+        return false;
+    }
+
+    public void run() {
+        int ret = 0;
+        byte[] buffer = new byte[16384];
+        while (ret >= 0) {
+            try {
+                ret = mInputStream.read(buffer);
+            } catch (IOException e) {
+                break;
+            }
+
+            if (ret > 0) {
+                Message m = Message.obtain(mHandler, MESSAGE_LOG);
+                String text = new String(buffer, 0, ret);
+                Log.d(TAG, "chat: " + text);
+                m.obj = text;
+                mHandler.sendMessage(m);
+            }
+        }
+        Log.d(TAG, "thread out");
+    }
+
+   Handler mHandler = new Handler() {
+        @Override
+        public void handleMessage(Message msg) {
+            switch (msg.what) {
+                case MESSAGE_LOG:
+                    mLog.setText(mLog.getText() + "\n" + (String)msg.obj);
+                    break;
+             }
+        }
+    };
+}
+
+
diff --git a/libs/utils/AssetManager.cpp b/libs/utils/AssetManager.cpp
index 13004cd..0b4d1ac 100644
--- a/libs/utils/AssetManager.cpp
+++ b/libs/utils/AssetManager.cpp
@@ -680,6 +680,9 @@
                 delete ass;
             }
         }
+        if (idmap != NULL) {
+            delete idmap;
+        }
     }
 
     if (required && !rt) LOGW("Unable to find resources file resources.arsc");
diff --git a/libs/utils/RefBase.cpp b/libs/utils/RefBase.cpp
index 0bd1af4..545da7d 100644
--- a/libs/utils/RefBase.cpp
+++ b/libs/utils/RefBase.cpp
@@ -48,6 +48,11 @@
 
 // ---------------------------------------------------------------------------
 
+RefBase::Destroyer::~Destroyer() {
+}
+
+// ---------------------------------------------------------------------------
+
 class RefBase::weakref_impl : public RefBase::weakref_type
 {
 public:
@@ -55,7 +60,7 @@
     volatile int32_t    mWeak;
     RefBase* const      mBase;
     volatile int32_t    mFlags;
-
+    Destroyer*          mDestroyer;
 
 #if !DEBUG_REFS
 
@@ -64,6 +69,7 @@
         , mWeak(0)
         , mBase(base)
         , mFlags(0)
+        , mDestroyer(0)
     {
     }
 
@@ -310,7 +316,11 @@
     if (c == 1) {
         const_cast<RefBase*>(this)->onLastStrongRef(id);
         if ((refs->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK) {
-            delete this;
+            if (refs->mDestroyer) {
+                refs->mDestroyer->destroy(this);
+            } else {
+                delete this;
+            }
         }
     }
     refs->removeWeakRef(id);
@@ -345,7 +355,9 @@
     return mRefs->mStrong;
 }
 
-
+void RefBase::setDestroyer(RefBase::Destroyer* destroyer) {
+    mRefs->mDestroyer = destroyer;
+}
 
 RefBase* RefBase::weakref_type::refBase() const
 {
@@ -369,16 +381,28 @@
     if (c != 1) return;
     
     if ((impl->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK) {
-        if (impl->mStrong == INITIAL_STRONG_VALUE)
-            delete impl->mBase;
-        else {
-//            LOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
+        if (impl->mStrong == INITIAL_STRONG_VALUE) {
+            if (impl->mBase) {
+                if (impl->mDestroyer) {
+                    impl->mDestroyer->destroy(impl->mBase);
+                } else {
+                    delete impl->mBase;
+                }
+            }
+        } else {
+            // LOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
             delete impl;
         }
     } else {
         impl->mBase->onLastWeakRef(id);
         if ((impl->mFlags&OBJECT_LIFETIME_FOREVER) != OBJECT_LIFETIME_FOREVER) {
-            delete impl->mBase;
+            if (impl->mBase) {
+                if (impl->mDestroyer) {
+                    impl->mDestroyer->destroy(impl->mBase);
+                } else {
+                    delete impl->mBase;
+                }
+            }
         }
     }
 }
@@ -480,7 +504,7 @@
 
 void RefBase::weakref_type::trackMe(bool enable, bool retain)
 {
-    static_cast<const weakref_impl*>(this)->trackMe(enable, retain);
+    static_cast<weakref_impl*>(this)->trackMe(enable, retain);
 }
 
 RefBase::weakref_type* RefBase::createWeak(const void* id) const
@@ -502,10 +526,10 @@
 
 RefBase::~RefBase()
 {
-//    LOGV("Destroying RefBase %p (refs %p)\n", this, mRefs);
-    if (mRefs->mWeak == 0) {
-//        LOGV("Freeing refs %p of old RefBase %p\n", mRefs, this);
-        delete mRefs;
+    if ((mRefs->mFlags & OBJECT_LIFETIME_WEAK) == OBJECT_LIFETIME_WEAK) {
+        if (mRefs->mWeak == 0) {
+            delete mRefs;
+        }
     }
 }
 
diff --git a/libs/utils/ResourceTypes.cpp b/libs/utils/ResourceTypes.cpp
index 57aaf24..fc5a3ab 100644
--- a/libs/utils/ResourceTypes.cpp
+++ b/libs/utils/ResourceTypes.cpp
@@ -4200,7 +4200,8 @@
                 | (0x0000ffff & (entryIndex));
             resource_name resName;
             if (!this->getResourceName(resID, &resName)) {
-                return UNKNOWN_ERROR;
+                LOGW("idmap: resource 0x%08x has spec but lacks values, skipping\n", resID);
+                continue;
             }
 
             const String16 overlayType(resName.type, resName.typeLen);
diff --git a/location/java/com/android/internal/location/GpsNetInitiatedHandler.java b/location/java/com/android/internal/location/GpsNetInitiatedHandler.java
index ffc3346..29dec63 100755
--- a/location/java/com/android/internal/location/GpsNetInitiatedHandler.java
+++ b/location/java/com/android/internal/location/GpsNetInitiatedHandler.java
@@ -205,7 +205,7 @@
             mNiNotification.defaults &= ~Notification.DEFAULT_SOUND;
         }        
 
-        mNiNotification.flags = Notification.FLAG_ONGOING_EVENT;
+        mNiNotification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_AUTO_CANCEL;
         mNiNotification.tickerText = getNotifTicker(notif, mContext);
 
         // if not to popup dialog immediately, pending intent will open the dialog
diff --git a/media/java/android/media/ExifInterface.java b/media/java/android/media/ExifInterface.java
index 74488c5..a08f388 100644
--- a/media/java/android/media/ExifInterface.java
+++ b/media/java/android/media/ExifInterface.java
@@ -293,12 +293,16 @@
         String lngRef = mAttributes.get(ExifInterface.TAG_GPS_LONGITUDE_REF);
 
         if (latValue != null && latRef != null && lngValue != null && lngRef != null) {
-            output[0] = convertRationalLatLonToFloat(latValue, latRef);
-            output[1] = convertRationalLatLonToFloat(lngValue, lngRef);
-            return true;
-        } else {
-            return false;
+            try {
+                output[0] = convertRationalLatLonToFloat(latValue, latRef);
+                output[1] = convertRationalLatLonToFloat(lngValue, lngRef);
+                return true;
+            } catch (IllegalArgumentException e) {
+                // if values are not parseable
+            }
         }
+
+        return false;
     }
 
     /**
@@ -367,12 +371,12 @@
 
             String [] pair;
             pair = parts[0].split("/");
-            int degrees = (int) (Float.parseFloat(pair[0].trim())
-                    / Float.parseFloat(pair[1].trim()));
+            double degrees = Double.parseDouble(pair[0].trim())
+                    / Double.parseDouble(pair[1].trim());
 
             pair = parts[1].split("/");
-            int minutes = (int) ((Float.parseFloat(pair[0].trim())
-                    / Float.parseFloat(pair[1].trim())));
+            double minutes = Double.parseDouble(pair[0].trim())
+                    / Double.parseDouble(pair[1].trim());
 
             pair = parts[2].split("/");
             double seconds = Double.parseDouble(pair[0].trim())
@@ -383,10 +387,12 @@
                 return (float) -result;
             }
             return (float) result;
-        } catch (RuntimeException ex) {
-            // if for whatever reason we can't parse the lat long then return
-            // null
-            return 0f;
+        } catch (NumberFormatException e) {
+            // Some of the nubmers are not valid
+            throw new IllegalArgumentException();
+        } catch (ArrayIndexOutOfBoundsException e) {
+            // Some of the rational does not follow the correct format
+            throw new IllegalArgumentException();
         }
     }
 
diff --git a/media/libstagefright/AudioSource.cpp b/media/libstagefright/AudioSource.cpp
index 29f16d8..a84365f 100644
--- a/media/libstagefright/AudioSource.cpp
+++ b/media/libstagefright/AudioSource.cpp
@@ -287,9 +287,10 @@
         }
 
         ssize_t n = mRecord->read(buffer->data(), buffer->size());
-        if (n < 0) {
+        if (n <= 0) {
+            LOGE("Read from AudioRecord returns: %ld", n);
             buffer->release();
-            return (status_t)n;
+            return UNKNOWN_ERROR;
         }
 
         int64_t recordDurationUs = (1000000LL * n >> 1) / sampleRate;
diff --git a/media/libstagefright/AwesomePlayer.cpp b/media/libstagefright/AwesomePlayer.cpp
index 6dc61c7..e7aec35 100644
--- a/media/libstagefright/AwesomePlayer.cpp
+++ b/media/libstagefright/AwesomePlayer.cpp
@@ -1165,7 +1165,7 @@
     }
 
     if (mAudioPlayer != NULL) {
-        LOGV("seeking audio to %lld us (%.2f secs).", timeUs, timeUs / 1E6);
+        LOGV("seeking audio to %lld us (%.2f secs).", videoTimeUs, videoTimeUs / 1E6);
 
         // If we don't have a video time, seek audio to the originally
         // requested seek time instead.
diff --git a/media/libstagefright/HTTPStream.cpp b/media/libstagefright/HTTPStream.cpp
index 7194614..42664b2 100644
--- a/media/libstagefright/HTTPStream.cpp
+++ b/media/libstagefright/HTTPStream.cpp
@@ -124,6 +124,83 @@
     return result;
 }
 
+// Apparently under our linux closing a socket descriptor from one thread
+// will not unblock a pending send/recv on that socket on another thread.
+static ssize_t MySendReceive(
+        int s, void *data, size_t size, int flags, bool sendData) {
+    ssize_t result = 0;
+
+    if (s < 0) {
+        return -1;
+    }
+    while (size > 0) {
+        fd_set rs, ws, es;
+        FD_ZERO(&rs);
+        FD_ZERO(&ws);
+        FD_ZERO(&es);
+        FD_SET(s, sendData ? &ws : &rs);
+        FD_SET(s, &es);
+
+        struct timeval tv;
+        tv.tv_sec = 0;
+        tv.tv_usec = 100000ll;
+
+        int nfds = ::select(
+                s + 1,
+                sendData ? NULL : &rs,
+                sendData ? &ws : NULL,
+                &es,
+                &tv);
+
+        if (nfds < 0) {
+            if (errno == EINTR) {
+                continue;
+            }
+
+            result = -errno;
+            break;
+        } else if (nfds == 0) {
+            // timeout
+
+            continue;
+        }
+
+        CHECK_EQ(nfds, 1);
+
+        ssize_t nbytes =
+            sendData ? send(s, data, size, flags) : recv(s, data, size, flags);
+
+        if (nbytes < 0) {
+            if (errno == EINTR) {
+                continue;
+            }
+
+            result = -errno;
+            break;
+        } else if (nbytes == 0) {
+            result = 0;
+            break;
+        }
+
+        data = (uint8_t *)data + nbytes;
+        size -= nbytes;
+
+        result = nbytes;
+        break;
+    }
+
+    return result;
+}
+
+static ssize_t MySend(int s, const void *data, size_t size, int flags) {
+    return MySendReceive(
+            s, const_cast<void *>(data), size, flags, true /* sendData */);
+}
+
+static ssize_t MyReceive(int s, void *data, size_t size, int flags) {
+    return MySendReceive(s, data, size, flags, false /* sendData */);
+}
+
 status_t HTTPStream::connect(const char *server, int port) {
     Mutex::Autolock autoLock(mLock);
 
@@ -133,40 +210,58 @@
         return ERROR_ALREADY_CONNECTED;
     }
 
-    struct hostent *ent = gethostbyname(server);
-    if (ent == NULL) {
+    if (port < 0 || port > (int) USHRT_MAX) {
+        return UNKNOWN_ERROR;
+    }
+
+    char service[sizeof("65536")];
+    sprintf(service, "%d", port);
+    struct addrinfo hints, *ai;
+    memset(&hints, 0, sizeof(hints));
+    hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV;
+    hints.ai_socktype = SOCK_STREAM;
+
+    int ret = getaddrinfo(server, service, &hints, &ai);
+    if (ret) {
         return ERROR_UNKNOWN_HOST;
     }
 
     CHECK_EQ(mSocket, -1);
-    mSocket = socket(AF_INET, SOCK_STREAM, 0);
-
-    if (mSocket < 0) {
-        return UNKNOWN_ERROR;
-    }
-
-    setReceiveTimeout(30);  // Time out reads after 30 secs by default
 
     mState = CONNECTING;
+    status_t res = -1;
+    struct addrinfo *tmp;
+    for (tmp = ai; tmp; tmp = tmp->ai_next) {
+        mSocket = socket(tmp->ai_family, tmp->ai_socktype, tmp->ai_protocol);
+        if (mSocket < 0) {
+            continue;
+        }
 
-    int s = mSocket;
+        setReceiveTimeout(30);  // Time out reads after 30 secs by default.
 
-    mLock.unlock();
+        int s = mSocket;
 
-    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));
+        mLock.unlock();
 
-    status_t res = MyConnect(s, (const struct sockaddr *)&addr, sizeof(addr));
+        res = MyConnect(s, tmp->ai_addr, tmp->ai_addrlen);
 
-    mLock.lock();
+        mLock.lock();
 
-    if (mState != CONNECTING) {
-        return UNKNOWN_ERROR;
+        if (mState != CONNECTING) {
+            close(s);
+            freeaddrinfo(ai);
+            return UNKNOWN_ERROR;
+        }
+
+        if (res == OK) {
+            break;
+        }
+
+        close(s);
     }
 
+    freeaddrinfo(ai);
+
     if (res != OK) {
         close(mSocket);
         mSocket = -1;
@@ -202,16 +297,12 @@
     }
 
     while (size > 0) {
-        ssize_t n = ::send(mSocket, data, size, 0);
+        ssize_t n = MySend(mSocket, data, size, 0);
 
         if (n < 0) {
-            if (errno == EINTR) {
-                continue;
-            }
-
             disconnect();
 
-            return ERROR_IO;
+            return n;
         } else if (n == 0) {
             disconnect();
 
@@ -247,12 +338,8 @@
 
     for (;;) {
         char c;
-        ssize_t n = recv(mSocket, &c, 1, 0);
+        ssize_t n = MyReceive(mSocket, &c, 1, 0);
         if (n < 0) {
-            if (errno == EINTR) {
-                continue;
-            }
-
             disconnect();
 
             return ERROR_IO;
@@ -365,14 +452,10 @@
 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);
+        ssize_t n = MyReceive(mSocket, (char *)data + total, size - total, 0);
 
         if (n < 0) {
-            if (errno == EINTR) {
-                continue;
-            }
-
-            LOGE("recv failed, errno = %d (%s)", errno, strerror(errno));
+            LOGE("recv failed, errno = %d (%s)", (int)n, strerror(-n));
 
             disconnect();
             return (ssize_t)ERROR_IO;
diff --git a/media/libstagefright/MP3Extractor.cpp b/media/libstagefright/MP3Extractor.cpp
index b15c720..ed14a4b 100644
--- a/media/libstagefright/MP3Extractor.cpp
+++ b/media/libstagefright/MP3Extractor.cpp
@@ -37,10 +37,10 @@
 namespace android {
 
 // Everything must match except for
-// protection, bitrate, padding, private bits, mode extension,
+// protection, bitrate, padding, private bits, mode, mode extension,
 // copyright bit, original bit and emphasis.
 // Yes ... there are things that must indeed match...
-static const uint32_t kMask = 0xfffe0cc0;
+static const uint32_t kMask = 0xfffe0c00;
 
 static bool get_mp3_frame_size(
         uint32_t header, size_t *frame_size,
@@ -344,22 +344,55 @@
 
     off_t pos = *inout_pos;
     bool valid = false;
+
+    const size_t kMaxReadBytes = 1024;
+    const off_t kMaxBytesChecked = 128 * 1024;
+    uint8_t buf[kMaxReadBytes];
+    ssize_t bytesToRead = kMaxReadBytes;
+    ssize_t totalBytesRead = 0;
+    ssize_t remainingBytes = 0;
+    bool reachEOS = false;
+    uint8_t *tmp = buf;
+
     do {
-        if (pos >= *inout_pos + 128 * 1024) {
+        if (pos >= *inout_pos + kMaxBytesChecked) {
             // Don't scan forever.
             LOGV("giving up at offset %ld", pos);
             break;
         }
 
-        uint8_t tmp[4];
-        if (source->readAt(pos, tmp, 4) != 4) {
-            break;
+        if (remainingBytes < 4) {
+            if (reachEOS) {
+                break;
+            } else {
+                memcpy(buf, tmp, remainingBytes);
+                bytesToRead = kMaxReadBytes - remainingBytes;
+
+                /*
+                 * The next read position should start from the end of
+                 * the last buffer, and thus should include the remaining
+                 * bytes in the buffer.
+                 */
+                totalBytesRead = source->readAt(pos + remainingBytes,
+                                                buf + remainingBytes,
+                                                bytesToRead);
+                if (totalBytesRead <= 0) {
+                    break;
+                }
+                reachEOS = (totalBytesRead != bytesToRead);
+                totalBytesRead += remainingBytes;
+                remainingBytes = totalBytesRead;
+                tmp = buf;
+                continue;
+            }
         }
 
         uint32_t header = U32_AT(tmp);
 
         if (match_header != 0 && (header & kMask) != (match_header & kMask)) {
             ++pos;
+            ++tmp;
+            --remainingBytes;
             continue;
         }
 
@@ -368,6 +401,8 @@
         if (!get_mp3_frame_size(header, &frame_size,
                                &sample_rate, &num_channels, &bitrate)) {
             ++pos;
+            ++tmp;
+            --remainingBytes;
             continue;
         }
 
@@ -417,6 +452,8 @@
         }
 
         ++pos;
+        ++tmp;
+        --remainingBytes;
     } while (!valid);
 
     return valid;
diff --git a/media/libstagefright/NuCachedSource2.cpp b/media/libstagefright/NuCachedSource2.cpp
index 5b0168b..3a37bf3 100644
--- a/media/libstagefright/NuCachedSource2.cpp
+++ b/media/libstagefright/NuCachedSource2.cpp
@@ -326,24 +326,31 @@
     mCondition.signal();
 }
 
-void NuCachedSource2::restartPrefetcherIfNecessary_l() {
+void NuCachedSource2::restartPrefetcherIfNecessary_l(bool force) {
     static const size_t kGrayArea = 256 * 1024;
 
     if (mFetching || mFinalStatus != OK) {
         return;
     }
 
-    if (mCacheOffset + mCache->totalSize() - mLastAccessPos
-            >= kLowWaterThreshold) {
-        return;
-    }
+    size_t maxBytes;
 
-    size_t maxBytes = mLastAccessPos - mCacheOffset;
-    if (maxBytes < kGrayArea) {
-        return;
-    }
+    if (!force) {
+        if (mCacheOffset + mCache->totalSize() - mLastAccessPos
+                >= kLowWaterThreshold) {
+            return;
+        }
 
-    maxBytes -= kGrayArea;
+        maxBytes = mLastAccessPos - mCacheOffset;
+        if (maxBytes < kGrayArea) {
+            return;
+        }
+
+        maxBytes -= kGrayArea;
+    } else {
+        // Empty it all out.
+        maxBytes = mLastAccessPos - mCacheOffset;
+    }
 
     size_t actualBytes = mCache->releaseFromStart(maxBytes);
     mCacheOffset += actualBytes;
@@ -415,10 +422,17 @@
 }
 
 ssize_t NuCachedSource2::readInternal(off_t offset, void *data, size_t size) {
+    CHECK(size <= kHighWaterThreshold);
+
     LOGV("readInternal offset %ld size %d", offset, size);
 
     Mutex::Autolock autoLock(mLock);
 
+    if (!mFetching) {
+        mLastAccessPos = offset;
+        restartPrefetcherIfNecessary_l(true /* force */);
+    }
+
     if (offset < mCacheOffset
             || offset >= (off_t)(mCacheOffset + mCache->totalSize())) {
         static const off_t kPadding = 32768;
diff --git a/media/libstagefright/NuHTTPDataSource.cpp b/media/libstagefright/NuHTTPDataSource.cpp
index 04cca47..af247d5 100644
--- a/media/libstagefright/NuHTTPDataSource.cpp
+++ b/media/libstagefright/NuHTTPDataSource.cpp
@@ -1,3 +1,19 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 //#define LOG_NDEBUG 0
 #define LOG_TAG "NuHTTPDataSource"
 #include <utils/Log.h>
diff --git a/media/libstagefright/codecs/aacenc/Android.mk b/media/libstagefright/codecs/aacenc/Android.mk
index cda4f9d..3782853 100644
--- a/media/libstagefright/codecs/aacenc/Android.mk
+++ b/media/libstagefright/codecs/aacenc/Android.mk
@@ -59,7 +59,7 @@
 
 LOCAL_ARM_MODE := arm
 
-LOCAL_STATIC_LIBRARIES := 
+LOCAL_STATIC_LIBRARIES :=
 
 LOCAL_SHARED_LIBRARIES :=
 
diff --git a/media/libstagefright/codecs/aacenc/SampleCode/AAC_E_SAMPLES.c b/media/libstagefright/codecs/aacenc/SampleCode/AAC_E_SAMPLES.c
index 64d012d..c7b2616 100644
--- a/media/libstagefright/codecs/aacenc/SampleCode/AAC_E_SAMPLES.c
+++ b/media/libstagefright/codecs/aacenc/SampleCode/AAC_E_SAMPLES.c
@@ -1,283 +1,283 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		AAC_E_SAMPLES.h

-

-	Content:	sample code for AAC encoder

-

-*******************************************************************************/

-

-#include		<dlfcn.h>

-#include		<stdio.h>

-#include		<stdlib.h>

-#include		<string.h>

-#include		<time.h>

-#include		"voAAC.h"

-#include		"cmnMemory.h"

-

-#define  VO_AAC_E_OUTPUT	  1

-#define READ_SIZE	(1024*8)	

-unsigned char outBuf[1024*8];

-unsigned char inBuf[READ_SIZE];

-

-const char* HelpString = 

-"VisualOn AAC encoder Usage:\n"

-"voAACEncTest -if <inputfile.pcm> -of <outputfile.aac> -sr <samplerate> -ch <channel> -br <bitrate> -adts <adts> \n"

-"-if input file name \n"

-"-of output file name \n"

-"-sr input pcm samplerate, default 44100 \n"

-"-ch input pcm channel, default 2 channel \n"

-"-br encoded aac bitrate, default 64000 * (samplerate/100)*channel/441(480)\n"

-"-adts add or no adts header, default add adts header\n"

-"For example: \n"

-"./voAACEncTest -if raw.pcm -of raw.aac -sr 44100 -ch 2 -br 128000\n";

-

-static int parsecmdline(int argc, char **argv,char  **input_filename, char  **output_filename, AACENC_PARAM *param)

-{

-	// notice that:

-	// bitRate/nChannels > 8000

-	// bitRate/nChannels < 160000 

-	// bitRate/nChannels < sampleRate*6

-	param->adtsUsed = 1;

-	param->bitRate = 0;

-	param->nChannels = 2;

-	param->sampleRate = 44100;

-

-	if(argc < 5 || argc > 13)

-	{

-		return -1;

-	}

-

-	argc--;

-	argv++;

-	while (argc > 0)

-	{

-		if (!strcmp(*argv, "-if"))

-		{

-			argv++;

-			argc--;

-			*input_filename = *argv; 

-		}

-		else if (!strcmp(*argv, "-of"))

-		{

-			argv++;

-			argc--;

-			*output_filename = *argv;

-		}

-		else if (!strcmp(*argv, "-sr"))

-		{

-			argv++;

-			argc--;

-			param->sampleRate = atoi(*argv);

-		}

-		else if (!strcmp(*argv, "-ch"))

-		{

-			argv++;

-			argc--;

-			param->nChannels = atoi(*argv);

-		}

-		else if (!strcmp(*argv, "-br"))

-		{

-			argv++;

-			argc--;

-			param->bitRate = atoi(*argv);

-		}

-		else if(!strcmp(*argv, "-adts"))

-		{

-			argv++;

-			argc--;

-			param->adtsUsed = atoi(*argv);

-		}

-		else

-		{

-			return -1;

-		}

-

-		argv++;

-		argc--;

-	}

-

-	if(param->bitRate == 0)

-	{

-		int scale = 441;

-		if(param->sampleRate%8000 == 0)

-			scale = 480;

-		param->bitRate = 640*param->nChannels*param->sampleRate/scale;

-	}

-

-	return 0;

-}

-

-int ReadFile2Buf(FILE* infile,unsigned char* dest,int readSize)

-{

-	int readBytes = 0;

-	readBytes = fread(dest, 1, readSize, infile);

-	return readBytes;

-}

-

-typedef int (VO_API * VOGETAUDIODECAPI) (VO_AUDIO_CODECAPI * pDecHandle);

-

-int main(int argc, char **argv)

-{

-	FILE						*infile, *outfile;

-	int							t1, t2;

-	VO_AUDIO_CODECAPI			AudioAPI;

-	VO_MEM_OPERATOR				moper;

-	VO_CODEC_INIT_USERDATA		useData;

-	VO_HANDLE					hCodec;

-	VO_CODECBUFFER				inData;

-	VO_CODECBUFFER				outData;

-	VO_AUDIO_OUTPUTINFO			outInfo;

-    int							firstWrite = 1;

-	int							eofFile = 0;

-	int							*info=(int*)inBuf;

-	int							bytesLeft, nRead;

-	int							EncoderdFrame = 0;

-	int							total = 0;

-	int							isOutput = 1;

-	int							returnCode;

-	AACENC_PARAM				aacpara;

-	void						*handle;

-	void						*pfunc;

-	VOGETAUDIODECAPI			pGetAPI;

-	const char					*infileName = NULL;

-    const char					*outfileName = NULL;

-

-	returnCode = parsecmdline(argc,argv, &infileName, &outfileName, &aacpara);

-	if(returnCode)

-	{

-		printf("%s", HelpString);

-		return 0;

-	}

-

-	/* open input file */

-	infile = fopen(infileName, "rb");

-	if (!infile) {

-		printf("Open input file fail...");

-		return -1;

-	}

-

-	/* open output file */

-	if(isOutput)

-	{

-		outfile = fopen(outfileName, "wb"); 

-		if (!outfile) {

-			printf("Open output file fail...");

-			return -1;

-		}

-	}

-	// set memory operators;

-	moper.Alloc = cmnMemAlloc;

-	moper.Copy = cmnMemCopy;

-	moper.Free = cmnMemFree;

-	moper.Set = cmnMemSet;

-	moper.Check = cmnMemCheck;

-	useData.memflag = VO_IMF_USERMEMOPERATOR;

-	useData.memData = (VO_PTR)(&moper);

-	// open encoder dll;

-	handle = dlopen("/data/local/tmp/libvoAACEncv7.so", RTLD_NOW);

-	if(handle == 0)

-	{

-		printf("open dll error......");

-		return -1;

-	}

-	// Get API;

-	pfunc = dlsym(handle, "voGetAACEncAPI");	

-	if(pfunc == 0)

-	{

-		printf("open function error......");

-		return -1;

-	}

-	pGetAPI = (VOGETAUDIODECAPI)pfunc;

-	returnCode  = pGetAPI(&AudioAPI);

-	if(returnCode)

-		return -1;

-

-

-//#######################################   Init Encoding Section   #########################################

-	returnCode = AudioAPI.Init(&hCodec, VO_AUDIO_CodingAAC, &useData);

-	if(returnCode < 0)

-	{

-		printf("#### VOI_Error2:fail to initialize the Encoderr###\n");

-		return -1;

-	}

-

-	returnCode = AudioAPI.SetParam(hCodec, VO_PID_AAC_ENCPARAM, &aacpara);	

-	

-	inData.Buffer = inBuf;

-	bytesLeft = ReadFile2Buf(infile,inData.Buffer,READ_SIZE);

-

-//#######################################    Encoding Section   #########################################

-	

-	do {

-

-		inData.Length    = bytesLeft;

-		outData.Buffer   = outBuf;

-		outData.Length = 1024*8;

-

-		t1 = clock();

-		

-		returnCode = AudioAPI.SetInputData(hCodec,&inData);

-		

-		do {

-			outData.Buffer   = outBuf;

-			outData.Length = 1024*8;

-

-			returnCode = AudioAPI.GetOutputData(hCodec,&outData, &outInfo);

-

-			if(returnCode == 0)

-				EncoderdFrame++;

-			if(returnCode == VO_ERR_LICENSE_ERROR)

-				break;

-

-#if VO_AAC_E_OUTPUT

-			if (isOutput && returnCode == 0)

-			{

-				fwrite(outData.Buffer, 1, outData.Length, outfile);

-			}

-#endif

-		} while(returnCode != (VO_ERR_INPUT_BUFFER_SMALL));

-

-		if(returnCode == VO_ERR_LICENSE_ERROR)

-			break;

-

-		t2 = clock();

-		total += t2 - t1;

-

-		if (!eofFile) {

-			nRead = ReadFile2Buf(infile, inBuf,READ_SIZE);

-			bytesLeft = nRead;

-			inData.Buffer = inBuf;

-			if (feof(infile))

-				eofFile = 1;

-		}

-

-	} while (!eofFile && returnCode);

-

-

-//################################################  End Encoding Section  #######################################################

-	returnCode = AudioAPI.Uninit(hCodec);

-

-	fclose(infile);

-	if (outfile)

-    {

-        fclose(outfile);

-    }

-	dlclose(handle);

-	return 0;

-}

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		AAC_E_SAMPLES.h
+
+	Content:	sample code for AAC encoder
+
+*******************************************************************************/
+
+#include		<dlfcn.h>
+#include		<stdio.h>
+#include		<stdlib.h>
+#include		<string.h>
+#include		<time.h>
+#include		"voAAC.h"
+#include		"cmnMemory.h"
+
+#define  VO_AAC_E_OUTPUT	  1
+#define READ_SIZE	(1024*8)
+unsigned char outBuf[1024*8];
+unsigned char inBuf[READ_SIZE];
+
+const char* HelpString =
+"VisualOn AAC encoder Usage:\n"
+"voAACEncTest -if <inputfile.pcm> -of <outputfile.aac> -sr <samplerate> -ch <channel> -br <bitrate> -adts <adts> \n"
+"-if input file name \n"
+"-of output file name \n"
+"-sr input pcm samplerate, default 44100 \n"
+"-ch input pcm channel, default 2 channel \n"
+"-br encoded aac bitrate, default 64000 * (samplerate/100)*channel/441(480)\n"
+"-adts add or no adts header, default add adts header\n"
+"For example: \n"
+"./voAACEncTest -if raw.pcm -of raw.aac -sr 44100 -ch 2 -br 128000\n";
+
+static int parsecmdline(int argc, char **argv,char  **input_filename, char  **output_filename, AACENC_PARAM *param)
+{
+	// notice that:
+	// bitRate/nChannels > 8000
+	// bitRate/nChannels < 160000
+	// bitRate/nChannels < sampleRate*6
+	param->adtsUsed = 1;
+	param->bitRate = 0;
+	param->nChannels = 2;
+	param->sampleRate = 44100;
+
+	if(argc < 5 || argc > 13)
+	{
+		return -1;
+	}
+
+	argc--;
+	argv++;
+	while (argc > 0)
+	{
+		if (!strcmp(*argv, "-if"))
+		{
+			argv++;
+			argc--;
+			*input_filename = *argv;
+		}
+		else if (!strcmp(*argv, "-of"))
+		{
+			argv++;
+			argc--;
+			*output_filename = *argv;
+		}
+		else if (!strcmp(*argv, "-sr"))
+		{
+			argv++;
+			argc--;
+			param->sampleRate = atoi(*argv);
+		}
+		else if (!strcmp(*argv, "-ch"))
+		{
+			argv++;
+			argc--;
+			param->nChannels = atoi(*argv);
+		}
+		else if (!strcmp(*argv, "-br"))
+		{
+			argv++;
+			argc--;
+			param->bitRate = atoi(*argv);
+		}
+		else if(!strcmp(*argv, "-adts"))
+		{
+			argv++;
+			argc--;
+			param->adtsUsed = atoi(*argv);
+		}
+		else
+		{
+			return -1;
+		}
+
+		argv++;
+		argc--;
+	}
+
+	if(param->bitRate == 0)
+	{
+		int scale = 441;
+		if(param->sampleRate%8000 == 0)
+			scale = 480;
+		param->bitRate = 640*param->nChannels*param->sampleRate/scale;
+	}
+
+	return 0;
+}
+
+int ReadFile2Buf(FILE* infile,unsigned char* dest,int readSize)
+{
+	int readBytes = 0;
+	readBytes = fread(dest, 1, readSize, infile);
+	return readBytes;
+}
+
+typedef int (VO_API * VOGETAUDIODECAPI) (VO_AUDIO_CODECAPI * pDecHandle);
+
+int main(int argc, char **argv)
+{
+	FILE						*infile, *outfile;
+	int							t1, t2;
+	VO_AUDIO_CODECAPI			AudioAPI;
+	VO_MEM_OPERATOR				moper;
+	VO_CODEC_INIT_USERDATA		useData;
+	VO_HANDLE					hCodec;
+	VO_CODECBUFFER				inData;
+	VO_CODECBUFFER				outData;
+	VO_AUDIO_OUTPUTINFO			outInfo;
+    int							firstWrite = 1;
+	int							eofFile = 0;
+	int							*info=(int*)inBuf;
+	int							bytesLeft, nRead;
+	int							EncoderdFrame = 0;
+	int							total = 0;
+	int							isOutput = 1;
+	int							returnCode;
+	AACENC_PARAM				aacpara;
+	void						*handle;
+	void						*pfunc;
+	VOGETAUDIODECAPI			pGetAPI;
+	const char					*infileName = NULL;
+    const char					*outfileName = NULL;
+
+	returnCode = parsecmdline(argc,argv, &infileName, &outfileName, &aacpara);
+	if(returnCode)
+	{
+		printf("%s", HelpString);
+		return 0;
+	}
+
+	/* open input file */
+	infile = fopen(infileName, "rb");
+	if (!infile) {
+		printf("Open input file fail...");
+		return -1;
+	}
+
+	/* open output file */
+	if(isOutput)
+	{
+		outfile = fopen(outfileName, "wb");
+		if (!outfile) {
+			printf("Open output file fail...");
+			return -1;
+		}
+	}
+	// set memory operators;
+	moper.Alloc = cmnMemAlloc;
+	moper.Copy = cmnMemCopy;
+	moper.Free = cmnMemFree;
+	moper.Set = cmnMemSet;
+	moper.Check = cmnMemCheck;
+	useData.memflag = VO_IMF_USERMEMOPERATOR;
+	useData.memData = (VO_PTR)(&moper);
+	// open encoder dll;
+	handle = dlopen("/data/local/tmp/libvoAACEncv7.so", RTLD_NOW);
+	if(handle == 0)
+	{
+		printf("open dll error......");
+		return -1;
+	}
+	// Get API;
+	pfunc = dlsym(handle, "voGetAACEncAPI");
+	if(pfunc == 0)
+	{
+		printf("open function error......");
+		return -1;
+	}
+	pGetAPI = (VOGETAUDIODECAPI)pfunc;
+	returnCode  = pGetAPI(&AudioAPI);
+	if(returnCode)
+		return -1;
+
+
+//#######################################   Init Encoding Section   #########################################
+	returnCode = AudioAPI.Init(&hCodec, VO_AUDIO_CodingAAC, &useData);
+	if(returnCode < 0)
+	{
+		printf("#### VOI_Error2:fail to initialize the Encoderr###\n");
+		return -1;
+	}
+
+	returnCode = AudioAPI.SetParam(hCodec, VO_PID_AAC_ENCPARAM, &aacpara);
+
+	inData.Buffer = inBuf;
+	bytesLeft = ReadFile2Buf(infile,inData.Buffer,READ_SIZE);
+
+//#######################################    Encoding Section   #########################################
+
+	do {
+
+		inData.Length    = bytesLeft;
+		outData.Buffer   = outBuf;
+		outData.Length = 1024*8;
+
+		t1 = clock();
+
+		returnCode = AudioAPI.SetInputData(hCodec,&inData);
+
+		do {
+			outData.Buffer   = outBuf;
+			outData.Length = 1024*8;
+
+			returnCode = AudioAPI.GetOutputData(hCodec,&outData, &outInfo);
+
+			if(returnCode == 0)
+				EncoderdFrame++;
+			if(returnCode == VO_ERR_LICENSE_ERROR)
+				break;
+
+#if VO_AAC_E_OUTPUT
+			if (isOutput && returnCode == 0)
+			{
+				fwrite(outData.Buffer, 1, outData.Length, outfile);
+			}
+#endif
+		} while(returnCode != (VO_ERR_INPUT_BUFFER_SMALL));
+
+		if(returnCode == VO_ERR_LICENSE_ERROR)
+			break;
+
+		t2 = clock();
+		total += t2 - t1;
+
+		if (!eofFile) {
+			nRead = ReadFile2Buf(infile, inBuf,READ_SIZE);
+			bytesLeft = nRead;
+			inData.Buffer = inBuf;
+			if (feof(infile))
+				eofFile = 1;
+		}
+
+	} while (!eofFile && returnCode);
+
+
+//################################################  End Encoding Section  #######################################################
+	returnCode = AudioAPI.Uninit(hCodec);
+
+	fclose(infile);
+	if (outfile)
+    {
+        fclose(outfile);
+    }
+	dlclose(handle);
+	return 0;
+}
+
+
diff --git a/media/libstagefright/codecs/aacenc/SampleCode/Android.mk b/media/libstagefright/codecs/aacenc/SampleCode/Android.mk
index 52c9c07..9f168cb 100644
--- a/media/libstagefright/codecs/aacenc/SampleCode/Android.mk
+++ b/media/libstagefright/codecs/aacenc/SampleCode/Android.mk
@@ -2,15 +2,15 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES := 	AAC_E_SAMPLES.c
-	
+
 LOCAL_SRC_FILES += 	\
-	../../../Common/cmnMemory.c 
+	../../../Common/cmnMemory.c
 
 LOCAL_MODULE := TestvoAACEnc
 
 LOCAL_ARM_MODE := arm
 
-LOCAL_STATIC_LIBRARIES := 
+LOCAL_STATIC_LIBRARIES :=
 
 LOCAL_SHARED_LIBRARIES := libvoAACEnc
 
@@ -20,5 +20,5 @@
 	$(LOCAL_PATH)/../../../Include \
 
 LOCAL_CFLAGS := $(VO_CFLAGS)
-	
+
 include $(BUILD_EXECUTABLE)
diff --git a/media/libstagefright/codecs/aacenc/SampleCode/eclair/Makefile b/media/libstagefright/codecs/aacenc/SampleCode/eclair/Makefile
index 22c5dc1..c6ec42f 100644
--- a/media/libstagefright/codecs/aacenc/SampleCode/eclair/Makefile
+++ b/media/libstagefright/codecs/aacenc/SampleCode/eclair/Makefile
@@ -1,55 +1,55 @@
-#/*

-#** Copyright 2003-2010, VisualOn, Inc.

-#**

-#** Licensed under the Apache License, Version 2.0 (the "License");

-#** you may not use this file except in compliance with the License.

-#** You may obtain a copy of the License at

-#**

-#**     http://www.apache.org/licenses/LICENSE-2.0

-#**

-#** Unless required by applicable law or agreed to in writing, software

-#** distributed under the License is distributed on an "AS IS" BASIS,

-#** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-#** See the License for the specific language governing permissions and

-#** limitations under the License.

-#*/

-

-# target6

-# available: pc, v4(armv4), v5(armv5), v5x(armv5 xscale), v6(armv6), v7(cortex-a8 neon)

-VOTT:= v7

-

-

-# module type

-# please specify the type of your module: lib or exe

-VOMT:= exe

-

-

-# module macros

-# please append the additional macro definitions here for your module if necessary. 

-# e.g. -DVISUALON, macro VISUALON defined for your module 

-VOMM:= #ARMV5E

-

-

-

-# please specify the name of your module

-VOTARGET:= voAACEncTestv7

-

-

-# please modify here to be sure to see the g1.mk

-include ../../../../Tools/eclair.mk 

-

-# dependent libraries.

-VODEPLIBS:=-ldl

-

-# module source

-# please modify here to be sure to see the ms.mk which specifies all source info of your module

-include ../ms.mk

-

-

-# please specify where is the voRelease on your PC, relative path is suggested

-VORELDIR:=../../../../../Release/

-

-

-# please modify here to be sure to see the doit.mk

-include ../../../../Tools/doit.mk 

-

+#/*
+#** Copyright 2003-2010, VisualOn, Inc.
+#**
+#** Licensed under the Apache License, Version 2.0 (the "License");
+#** you may not use this file except in compliance with the License.
+#** You may obtain a copy of the License at
+#**
+#**     http://www.apache.org/licenses/LICENSE-2.0
+#**
+#** Unless required by applicable law or agreed to in writing, software
+#** distributed under the License is distributed on an "AS IS" BASIS,
+#** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#** See the License for the specific language governing permissions and
+#** limitations under the License.
+#*/
+
+# target6
+# available: pc, v4(armv4), v5(armv5), v5x(armv5 xscale), v6(armv6), v7(cortex-a8 neon)
+VOTT:= v7
+
+
+# module type
+# please specify the type of your module: lib or exe
+VOMT:= exe
+
+
+# module macros
+# please append the additional macro definitions here for your module if necessary.
+# e.g. -DVISUALON, macro VISUALON defined for your module
+VOMM:= #ARMV5E
+
+
+
+# please specify the name of your module
+VOTARGET:= voAACEncTestv7
+
+
+# please modify here to be sure to see the g1.mk
+include ../../../../Tools/eclair.mk
+
+# dependent libraries.
+VODEPLIBS:=-ldl
+
+# module source
+# please modify here to be sure to see the ms.mk which specifies all source info of your module
+include ../ms.mk
+
+
+# please specify where is the voRelease on your PC, relative path is suggested
+VORELDIR:=../../../../../Release/
+
+
+# please modify here to be sure to see the doit.mk
+include ../../../../Tools/doit.mk
+
diff --git a/media/libstagefright/codecs/aacenc/SampleCode/ms.mk b/media/libstagefright/codecs/aacenc/SampleCode/ms.mk
index 771a569..b6255e8 100644
--- a/media/libstagefright/codecs/aacenc/SampleCode/ms.mk
+++ b/media/libstagefright/codecs/aacenc/SampleCode/ms.mk
@@ -1,23 +1,23 @@
-#/*

-#** Copyright 2003-2010, VisualOn, Inc.

-#**

-#** Licensed under the Apache License, Version 2.0 (the "License");

-#** you may not use this file except in compliance with the License.

-#** You may obtain a copy of the License at

-#**

-#**     http://www.apache.org/licenses/LICENSE-2.0

-#**

-#** Unless required by applicable law or agreed to in writing, software

-#** distributed under the License is distributed on an "AS IS" BASIS,

-#** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-#** See the License for the specific language governing permissions and

-#** limitations under the License.

-#*/

-

-# please list all objects needed by your target here

-OBJS:=AAC_E_SAMPLES.o	cmnMemory.o

-			

-# please list all directories that all source files relative with your module(.h .c .cpp) locate 

-VOSRCDIR:=../ ../../../../include  ../../../../Common

-					

-				

+#/*
+#** Copyright 2003-2010, VisualOn, Inc.
+#**
+#** Licensed under the Apache License, Version 2.0 (the "License");
+#** you may not use this file except in compliance with the License.
+#** You may obtain a copy of the License at
+#**
+#**     http://www.apache.org/licenses/LICENSE-2.0
+#**
+#** Unless required by applicable law or agreed to in writing, software
+#** distributed under the License is distributed on an "AS IS" BASIS,
+#** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#** See the License for the specific language governing permissions and
+#** limitations under the License.
+#*/
+
+# please list all objects needed by your target here
+OBJS:=AAC_E_SAMPLES.o	cmnMemory.o
+
+# please list all directories that all source files relative with your module(.h .c .cpp) locate
+VOSRCDIR:=../ ../../../../include  ../../../../Common
+
+
diff --git a/media/libstagefright/codecs/aacenc/Tools/doit.mk b/media/libstagefright/codecs/aacenc/Tools/doit.mk
index dea0b0a..4924341 100644
--- a/media/libstagefright/codecs/aacenc/Tools/doit.mk
+++ b/media/libstagefright/codecs/aacenc/Tools/doit.mk
@@ -28,10 +28,10 @@
 TARGET=$(VOTARGET)
 endif
 
-CFLAGS=$(VOCFLAGS) $(addprefix -I, $(VOSRCDIR)) 
-CPPFLAGS=$(VOCPPFLAGS) $(addprefix -I, $(VOSRCDIR)) 
+CFLAGS=$(VOCFLAGS) $(addprefix -I, $(VOSRCDIR))
+CPPFLAGS=$(VOCPPFLAGS) $(addprefix -I, $(VOSRCDIR))
 ifneq ($(VOTT), pc)
-ASFLAGS=$(VOASFLAGS) $(addprefix -I, $(VOSRCDIR)) 
+ASFLAGS=$(VOASFLAGS) $(addprefix -I, $(VOSRCDIR))
 endif
 
 LDFLAGS:=$(VOLDFLAGS)
@@ -90,7 +90,7 @@
 endif
 
 $(LIB_DYNAMIC):$(OBJS)
-	$(GG) $(LDFLAGS) -o $@ $(OBJDIR)/*.o -Wl,--whole-archive $(VOSTCLIBS) -Wl,--no-whole-archive $(VOTLDEPS) 
+	$(GG) $(LDFLAGS) -o $@ $(OBJDIR)/*.o -Wl,--whole-archive $(VOSTCLIBS) -Wl,--no-whole-archive $(VOTLDEPS)
 ifneq ($(VODBG), yes)
 		$(STRIP) $@
 endif
diff --git a/media/libstagefright/codecs/aacenc/Tools/eclair.mk b/media/libstagefright/codecs/aacenc/Tools/eclair.mk
index 1688361..41dd9c1 100644
--- a/media/libstagefright/codecs/aacenc/Tools/eclair.mk
+++ b/media/libstagefright/codecs/aacenc/Tools/eclair.mk
@@ -14,10 +14,10 @@
 # ** limitations under the License.
 # */
 
-# special macro definitions for building 
-VOPREDEF=-DLINUX -D_LINUX 
+# special macro definitions for building
+VOPREDEF=-DLINUX -D_LINUX
 
-VOPRJ ?= 
+VOPRJ ?=
 VONJ ?= eclair
 VOTT ?= v6
 # control the version to release out
@@ -80,19 +80,19 @@
 	-I$(TCROOTPATH)/bionic/libthread_db/include \
 	-I$(TCROOTPATH)/bionic/libm/arm \
 	-I$(TCROOTPATH)/bionic/libm \
-	-I$(TCROOTPATH)/frameworks/base/include/android_runtime 
+	-I$(TCROOTPATH)/frameworks/base/include/android_runtime
 	#-I$(TCROOTPATH)/out/target/product/$(VOTP)/obj/SHARED_LIBRARIES/libm_intermediates
 
 CCTCFLAGS:=-msoft-float -mthumb-interwork -fno-exceptions -ffunction-sections -funwind-tables -fstack-protector -fno-short-enums -fmessage-length=0 -finline-functions -finline-limit=600 -fno-inline-functions-called-once -fgcse-after-reload -frerun-cse-after-loop -frename-registers -fstrict-aliasing -funswitch-loops
-#-fwide-exec-charset=charset=UTF-32 
+#-fwide-exec-charset=charset=UTF-32
 
 # for target exe
-TELDFLAGS:=-nostdlib -Bdynamic -Wl,-T,$(TCROOTPATH)/build/core/armelf.x -Wl,-dynamic-linker,/system/bin/linker -Wl,--gc-sections -Wl,-z,nocopyreloc -Wl,--no-undefined -Wl,-rpath-link=$(CCTLIB) -L$(CCTLIB) 
+TELDFLAGS:=-nostdlib -Bdynamic -Wl,-T,$(TCROOTPATH)/build/core/armelf.x -Wl,-dynamic-linker,/system/bin/linker -Wl,--gc-sections -Wl,-z,nocopyreloc -Wl,--no-undefined -Wl,-rpath-link=$(CCTLIB) -L$(CCTLIB)
 
 VOTEDEPS:=$(CCTLIB)/crtbegin_dynamic.o $(CCTLIB)/crtend_android.o $(TCPATH)/lib/gcc/arm-eabi/$(GCCVER)/interwork/libgcc.a -lc -lm
 
 # for target lib
-TLLDFLAGS:=-nostdlib -Wl,-T,$(TCROOTPATH)/build/core/armelf.xsc -Wl,--gc-sections -Wl,-shared,-Bsymbolic -L$(CCTLIB) -Wl,--no-whole-archive -Wl,--no-undefined $(TCPATH)/lib/gcc/arm-eabi/$(GCCVER)/interwork/libgcc.a 
+TLLDFLAGS:=-nostdlib -Wl,-T,$(TCROOTPATH)/build/core/armelf.xsc -Wl,--gc-sections -Wl,-shared,-Bsymbolic -L$(CCTLIB) -Wl,--no-whole-archive -Wl,--no-undefined $(TCPATH)/lib/gcc/arm-eabi/$(GCCVER)/interwork/libgcc.a
 
 VOTLDEPS:=-lm -lc
 
@@ -113,7 +113,7 @@
 endif
 
 ifeq ($(VOTT), v6)
-#VOCFLAGS:=-march=armv6 -mtune=arm1136jf-s 
+#VOCFLAGS:=-march=armv6 -mtune=arm1136jf-s
 #VOASFLAGS:=-march=armv6
 VOCFLAGS:=-march=armv6j -mtune=arm1136jf-s -mfpu=vfp -mfloat-abi=softfp -mapcs -mtpcs-leaf-frame -mlong-calls
 VOASFLAGS:=-march=armv6j -mcpu=arm1136jf-s -mfpu=arm1136jf-s -mfloat-abi=softfp -mapcs-float -mapcs-reentrant
@@ -133,7 +133,7 @@
 #global compiling options for ARM target
 ifneq ($(VOTT), pc)
 VOASFLAGS+=--strip-local-absolute -R
-endif 
+endif
 
 
 ifeq ($(VODBG), yes)
@@ -167,6 +167,6 @@
 #VOLDFLAGS:=
 endif
 
-# where to place object files 
+# where to place object files
 OBJDIR=obj
 
diff --git a/media/libstagefright/codecs/aacenc/basic_op/basic_op.h b/media/libstagefright/codecs/aacenc/basic_op/basic_op.h
index 5457f33..ef3c31b 100644
--- a/media/libstagefright/codecs/aacenc/basic_op/basic_op.h
+++ b/media/libstagefright/codecs/aacenc/basic_op/basic_op.h
@@ -1,27 +1,27 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		basicop2.h

-

-	Content:	Constants , Globals and Basic arithmetic operators.

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		basicop2.h
+
+	Content:	Constants , Globals and Basic arithmetic operators.
+
 *******************************************************************************/
 
 #ifndef __BASIC_OP_H
-#define __BASIC_OP_H

+#define __BASIC_OP_H
 
 #include "typedef.h"
 
@@ -30,1137 +30,1137 @@
 
 #define MAX_16 (Word16)0x7fff
 #define MIN_16 (Word16)0x8000
-#define ABS(a)	((a) >= 0) ? (a) : (-(a))

-

-/* Short abs,           1   */

-#define abs_s(x)       ((Word16)(((x) != MIN_16) ? (((x) >= 0) ? (x) : (-(x))) : MAX_16))

-

-/* 16 bit var1 -> MSB,     2 */

-#define L_deposit_h(x) (((Word32)(x)) << 16)

-

-

-/* 16 bit var1 -> LSB,     2 */

-#define L_deposit_l(x) ((Word32)(x))

-

-

-/* Long abs,              3  */

-#define L_abs(x) (((x) != MIN_32) ? (((x) >= 0) ? (x) : (-(x))) : MAX_32)

-

-

-/* Short negate,        1   */

-#define negate(var1) ((Word16)(((var1) == MIN_16) ? MAX_16 : (-(var1))))

-

-

-/* Long negate,     2 */

-#define L_negate(L_var1) (((L_var1) == (MIN_32)) ? (MAX_32) : (-(L_var1)))

-

-

-#define MULHIGH(A,B) (int)(((Word64)(A)*(Word64)(B)) >> 32)

-#define fixmul(a, b) (int)((((Word64)(a)*(Word64)(b)) >> 32) << 1)

-

-

-#if  (SATRUATE_IS_INLINE)

-__inline Word16 saturate(Word32 L_var1);

-#else

-Word16 saturate(Word32 L_var1);

-#endif

-

-/* Short shift left,    1   */

-#if (SHL_IS_INLINE)

-__inline Word16 shl (Word16 var1, Word16 var2);

-#else

-Word16 shl (Word16 var1, Word16 var2);

-#endif

-

-/* Short shift right,   1   */

-#if (SHR_IS_INLINE)

-__inline Word16 shr (Word16 var1, Word16 var2);

-#else

-Word16 shr (Word16 var1, Word16 var2);

-#endif

-

-#if (L_MULT_IS_INLINE)

-__inline Word32 L_mult(Word16 var1, Word16 var2);

-#else

-Word32 L_mult(Word16 var1, Word16 var2);

-#endif

-

-/* Msu,  1  */

-#if (L_MSU_IS_INLINE)

-__inline Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2);

-#else

-Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2);

-#endif

-    

-/* Long sub,        2 */

-#if (L_SUB_IS_INLINE)

-__inline Word32 L_sub(Word32 L_var1, Word32 L_var2);

-#else

-Word32 L_sub(Word32 L_var1, Word32 L_var2);

-#endif

-

-/* Long shift left, 2 */

-#if (L_SHL_IS_INLINE)

-__inline Word32 L_shl (Word32 L_var1, Word16 var2);

-#else

-Word32 L_shl (Word32 L_var1, Word16 var2);

-#endif

-

-/* Long shift right, 2*/

-#if (L_SHR_IS_INLINE)

-__inline Word32 L_shr (Word32 L_var1, Word16 var2);

-#else

-Word32 L_shr (Word32 L_var1, Word16 var2);

-#endif

-

-/* Short add,           1   */

-#if (ADD_IS_INLINE)

-__inline Word16 add (Word16 var1, Word16 var2);

-#else

-Word16 add (Word16 var1, Word16 var2);

-#endif

-    

-/* Short sub,           1   */

-#if (SUB_IS_INLINE)

-__inline Word16 sub(Word16 var1, Word16 var2);

-#else

-Word16 sub(Word16 var1, Word16 var2);

-#endif

-

-/* Short division,       18  */

-#if (DIV_S_IS_INLINE)

-__inline Word16 div_s (Word16 var1, Word16 var2);

-#else

-Word16 div_s (Word16 var1, Word16 var2);

-#endif

-

-/* Short mult,          1   */

-#if (MULT_IS_INLINE)

-__inline Word16 mult (Word16 var1, Word16 var2);

-#else

-Word16 mult (Word16 var1, Word16 var2);

-#endif

-

-/* Short norm,           15  */

-#if (NORM_S_IS_INLINE)

-__inline Word16 norm_s (Word16 var1);

-#else

-Word16 norm_s (Word16 var1);

-#endif

-

-/* Long norm,            30  */

-#if (NORM_L_IS_INLINE)

-__inline Word16 norm_l (Word32 L_var1);

-#else

-Word16 norm_l (Word32 L_var1);

-#endif

-

-/* Round,               1   */

-#if (ROUND_IS_INLINE)

-__inline Word16 round16(Word32 L_var1);

-#else

-Word16 round16(Word32 L_var1);

-#endif

-

-/* Mac,  1  */

-#if (L_MAC_IS_INLINE)

-__inline Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2);

-#else

-Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2);

-#endif

-

-#if (L_ADD_IS_INLINE)

-__inline Word32 L_add (Word32 L_var1, Word32 L_var2);

-#else

-Word32 L_add (Word32 L_var1, Word32 L_var2);

-#endif

-

-/* Extract high,        1   */

-#if (EXTRACT_H_IS_INLINE)

-__inline Word16 extract_h (Word32 L_var1);

-#else

-Word16 extract_h (Word32 L_var1);

-#endif

-

-/* Extract low,         1   */

-#if (EXTRACT_L_IS_INLINE)

-__inline Word16 extract_l(Word32 L_var1);

-#else

-Word16 extract_l(Word32 L_var1);

-#endif

-

-/* Mult with round, 2 */

-#if (MULT_R_IS_INLINE)

-__inline Word16 mult_r(Word16 var1, Word16 var2);

-#else

-Word16 mult_r(Word16 var1, Word16 var2);

-#endif

-

-/* Shift right with round, 2           */

-#if (SHR_R_IS_INLINE)

-__inline Word16 shr_r (Word16 var1, Word16 var2);

-#else

-Word16 shr_r (Word16 var1, Word16 var2);

-#endif

-

-/* Mac with rounding,2 */

-#if (MAC_R_IS_INLINE)

-__inline Word16 mac_r (Word32 L_var3, Word16 var1, Word16 var2);

-#else

-Word16 mac_r (Word32 L_var3, Word16 var1, Word16 var2);

-#endif

-

-/* Msu with rounding,2 */

-#if (MSU_R_IS_INLINE)

-__inline Word16 msu_r (Word32 L_var3, Word16 var1, Word16 var2);

-#else

-Word16 msu_r (Word32 L_var3, Word16 var1, Word16 var2);

-#endif

-

-/* Long shift right with round,  3             */

-#if (L_SHR_R_IS_INLINE)

-__inline Word32 L_shr_r (Word32 L_var1, Word16 var2);

-#else

-Word32 L_shr_r (Word32 L_var1, Word16 var2);

-#endif

-

-#if ARMV4_INASM

-__inline Word32 ASM_L_shr(Word32 L_var1, Word16 var2)

-{

-	Word32 result; 

-	asm volatile( 

-		"MOV %[result], %[L_var1], ASR %[var2] \n" 

-		:[result]"=r"(result)

-		:[L_var1]"r"(L_var1), [var2]"r"(var2)

-		); 

-	return result;	

-}

- 

-__inline Word32 ASM_L_shl(Word32 L_var1, Word16 var2)

-{

-	Word32 result; 

-	asm volatile( 

-		"MOV	r2, %[L_var1] \n"

-		"MOV	r3, #0x7fffffff\n"

-		"MOV	%[result], %[L_var1], ASL %[var2] \n" 

-		"TEQ	r2, %[result], ASR %[var2]\n"

-		"EORNE  %[result],r3,r2,ASR#31\n"

-		:[result]"+r"(result)

-		:[L_var1]"r"(L_var1), [var2]"r"(var2)

-		:"r2", "r3"

-		); 

-	return result;	

-}

-

-__inline Word32 ASM_shr(Word32 L_var1, Word16 var2)

-{

-	Word32 result; 

-	asm volatile( 

-		"CMP	%[var2], #15\n"

-		"MOVGE  %[var2], #15\n"

-		"MOV	%[result], %[L_var1], ASR %[var2]\n"

-		:[result]"=r"(result)

-		:[L_var1]"r"(L_var1), [var2]"r"(var2) 

-		); 

-	return result;	

-} 

-

-__inline Word32 ASM_shl(Word32 L_var1, Word16 var2)

-{

-	Word32 result; 

-	asm volatile( 

-		"CMP	%[var2], #16\n"

-		"MOVGE  %[var2], #16\n"

-		"MOV    %[result], %[L_var1], ASL %[var2]\n"

-		"MOV    r3, #1\n"

-        "MOV    r2, %[result], ASR #15\n"

-        "RSB    r3,r3,r3,LSL #15 \n"

-        "TEQ    r2, %[result], ASR #31 \n"

-        "EORNE  %[result], r3, %[result],ASR #31"

-		:[result]"+r"(result)

-		:[L_var1]"r"(L_var1), [var2]"r"(var2)

-		:"r2", "r3"

-		); 

-	return result;	

-} 

-#endif

-

-/*___________________________________________________________________________

- |                                                                           |

- |   definitions for inline basic arithmetic operators                       |

- |___________________________________________________________________________|

-*/

-#if (SATRUATE_IS_INLINE)

-__inline Word16 saturate(Word32 L_var1)

-{

-#if ARMV5TE_SAT

-	Word16 result;

-	asm volatile (

-		"MOV	%[result], %[L_var1]\n"

-		"MOV	r3, #1\n"

-		"MOV	r2,%[L_var1],ASR#15\n"

-		"RSB	r3, r3, r3, LSL #15\n"

-		"TEQ	r2,%[L_var1],ASR#31\n"	

-		"EORNE	%[result],r3,%[L_var1],ASR#31\n"

-		:[result]"+r"(result)

-		:[L_var1]"r"(L_var1)

-		:"r2", "r3"			

-	);

-

-	return result;

-#else

-    Word16 var_out;

-    

-    //var_out = (L_var1 > (Word32)0X00007fffL) ? (MAX_16) : ((L_var1 < (Word32)0xffff8000L) ? (MIN_16) : ((Word16)L_var1));

-

-    if (L_var1 > 0X00007fffL)

-    {

-        var_out = MAX_16;

-    }

-    else if (L_var1 < (Word32) 0xffff8000L)

-    {

-        var_out = MIN_16;

-    }

-    else

-    {

-        var_out = extract_l(L_var1);

-    }

-

-    return (var_out);

-#endif

-}

-#endif

-

-/* Short shift left,    1   */

-#if (SHL_IS_INLINE)

-__inline Word16 shl (Word16 var1, Word16 var2)

-{

-#if ARMV5TE_SHL

-	if(var2>=0)

-	{

-		return ASM_shl( var1, var2);

-	}

-	else

-	{

-		return ASM_shr( var1, -var2);

-	}

-#else

-    Word16 var_out;

-    Word32 result;

-

-    if (var2 < 0)

-    {

-        var_out = shr (var1, (Word16)-var2);

-    }

-    else

-    {

-        result = (Word32) var1 *((Word32) 1 << var2);

-

-        if ((var2 > 15 && var1 != 0) || (result != (Word32) ((Word16) result)))

-        {

-            var_out = (Word16)((var1 > 0) ? MAX_16 : MIN_16);

-        }

-        else

-        {

-            var_out = extract_l(result);

-        }

-    }

-    return (var_out);

-#endif

-}

-#endif

-

-/* Short shift right,   1   */

-#if (SHR_IS_INLINE)

-__inline Word16 shr (Word16 var1, Word16 var2)

-{

-#if ARMV5TE_SHR

-	if(var2>=0)

-	{

-		return  ASM_shr( var1, var2);

-	}

-	else

-	{

-		return  ASM_shl( var1, -var2);

-	}

-#else

-    Word16 var_out;

-

-    if (var2 < 0)

-    {

-        var_out = shl (var1, (Word16)-var2);

-    }

-    else

-    {

-        if (var2 >= 15)

-        {

-            var_out = (Word16)((var1 < 0) ? -1 : 0);

-        }

-        else

-        {

-            if (var1 < 0)

-            {

-                var_out = (Word16)(~((~var1) >> var2));

-            }

-            else

-            {

-                var_out = (Word16)(var1 >> var2);

-            }

-        }

-    }

-

-    return (var_out);

-#endif

-}

-#endif

-

-

-#if (L_MULT_IS_INLINE)

-__inline Word32 L_mult(Word16 var1, Word16 var2)

-{

-#if ARMV5TE_L_MULT

-	Word32 result; 

-	asm volatile( 

-		"SMULBB %[result], %[var1], %[var2] \n" 

-		"QADD %[result], %[result], %[result] \n" 

-		:[result]"+r"(result)

-		:[var1]"r"(var1), [var2]"r"(var2)

-		); 

-	return result;

-#else

-    Word32 L_var_out;

-

-    L_var_out = (Word32) var1 *(Word32) var2;

-

-    if (L_var_out != (Word32) 0x40000000L)

-    {

-        L_var_out <<= 1;

-    }

-    else

-    {

-        L_var_out = MAX_32;

-    }

-    return (L_var_out);

-#endif

-}

-#endif

-

-#if (L_MSU_IS_INLINE)

-__inline Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2)

-{

-#if ARMV5TE_L_MSU

-	Word32 result; 

-	asm volatile( 

-		"SMULBB %[result], %[var1], %[var2] \n" 

-		"QADD %[result], %[result], %[result] \n"

-		"QSUB %[result], %[L_var3], %[result]\n"

-		:[result]"+r"(result)

-		:[L_var3]"r"(L_var3), [var1]"r"(var1), [var2]"r"(var2)

-		); 

-	return result;

-#else

-    Word32 L_var_out;

-    Word32 L_product;

-

-    L_product = L_mult(var1, var2);

-    L_var_out = L_sub(L_var3, L_product);

-    return (L_var_out);

-#endif

-}

-#endif

-

-#if (L_SUB_IS_INLINE)

-__inline Word32 L_sub(Word32 L_var1, Word32 L_var2)

-{

-#if ARMV5TE_L_SUB

-	Word32 result; 

-	asm volatile( 

-		"QSUB %[result], %[L_var1], %[L_var2]\n"

-		:[result]"+r"(result)

-		:[L_var1]"r"(L_var1), [L_var2]"r"(L_var2)

-		); 

-	return result;

-#else

-    Word32 L_var_out;

-

-    L_var_out = L_var1 - L_var2;

-

-    if (((L_var1 ^ L_var2) & MIN_32) != 0)

-    {

-        if ((L_var_out ^ L_var1) & MIN_32)

-        {

-            L_var_out = (L_var1 < 0L) ? MIN_32 : MAX_32;

-        }

-    }

-

-    return (L_var_out);

-#endif

-}

-#endif

-

-#if (L_SHL_IS_INLINE)

-__inline Word32 L_shl(Word32 L_var1, Word16 var2)

-{

-#if ARMV5TE_L_SHL

-    if(var2>=0)

-    {

-        return  ASM_L_shl( L_var1, var2);

-    }

-    else

-    {

-        return  ASM_L_shr( L_var1, -var2);

-    }

-#else

-    Word32 L_var_out = 0L;

-

-    if (var2 <= 0)

-    {

-        L_var1 = L_shr(L_var1, (Word16)-var2);

-    }

-    else

-    {

-        for (; var2 > 0; var2--)

-        {

-            if (L_var1 > (Word32) 0X3fffffffL)

-            {

-                return MAX_32;

-            }

-            else

-            {

-                if (L_var1 < (Word32) 0xc0000000L)

-                {

-                    return MIN_32;

-                }

-            }

-            L_var1 <<= 1;

-            L_var_out = L_var1;

-        }

-    }

-    return (L_var1);

-#endif

-}

-#endif

-

-#if (L_SHR_IS_INLINE)

-__inline Word32 L_shr (Word32 L_var1, Word16 var2)

-{

-#if ARMV5TE_L_SHR

-	if(var2>=0)

-	{

-		return ASM_L_shr( L_var1, var2);

-	}

-	else

-	{

-		return ASM_L_shl( L_var1, -var2);

-	}

-#else

-    Word32 L_var_out;

-

-    if (var2 < 0)

-    {

-        L_var_out = L_shl (L_var1, (Word16)-var2);

-    }

-    else

-    {

-        if (var2 >= 31)

-        {

-            L_var_out = (L_var1 < 0L) ? -1 : 0;

-        }

-        else

-        {

-            if (L_var1 < 0)

-            {

-                L_var_out = ~((~L_var1) >> var2);

-            }

-            else

-            {

-                L_var_out = L_var1 >> var2;

-            }

-        }

-    }

-    return (L_var_out);

-#endif

-}

-#endif

-

-/* Short add,           1   */

-#if (ADD_IS_INLINE)

-__inline Word16 add (Word16 var1, Word16 var2)

-{

-#if ARMV5TE_ADD

-	Word32 result; 

-	asm volatile( 

-		"ADD  %[result], %[var1], %[var2] \n" 

-		"MOV  r3, #0x1\n"

-		"MOV  r2, %[result], ASR #15\n"

-		"RSB  r3, r3, r3, LSL, #15\n"

-		"TEQ  r2, %[result], ASR #31\n"

-		"EORNE %[result], r3, %[result], ASR #31"

-		:[result]"+r"(result)

-		:[var1]"r"(var1), [var2]"r"(var2)

-		:"r2", "r3"

-		); 

-	return result;

-#else

-    Word16 var_out;

-    Word32 L_sum;

-

-    L_sum = (Word32) var1 + var2;

-    var_out = saturate(L_sum);

-

-    return (var_out);

-#endif

-}

-#endif

-

-/* Short sub,           1   */

-#if (SUB_IS_INLINE)

-__inline Word16 sub(Word16 var1, Word16 var2)

-{

-#if ARMV5TE_SUB

-	Word32 result; 

-	asm volatile( 

-		"MOV   r3, #1\n"

-		"SUB   %[result], %[var1], %[var2] \n"		

-		"RSB   r3,r3,r3,LSL#15\n"

-		"MOV   r2, %[var1], ASR #15 \n" 

-		"TEQ   r2, %[var1], ASR #31 \n"

-		"EORNE %[result], r3, %[result], ASR #31 \n"

-		:[result]"+r"(result)

-		:[var1]"r"(var1), [var2]"r"(var2)

-		:"r2", "r3"

-		); 

-	return result;

-#else

-    Word16 var_out;

-    Word32 L_diff;

-

-    L_diff = (Word32) var1 - var2;

-    var_out = saturate(L_diff);

-   

-    return (var_out);

-#endif

-}

-#endif

-

-/* Short division,       18  */

-#if (DIV_S_IS_INLINE)

-__inline Word16 div_s (Word16 var1, Word16 var2)

-{

-    Word16 var_out = 0;

-    Word16 iteration;

-    Word32 L_num;

-    Word32 L_denom;

-

-    var_out = MAX_16;

-    if (var1!= var2)//var1!= var2

-    {

-    	var_out = 0;

-    	L_num = (Word32) var1;

-    

-    	L_denom = (Word32) var2;

-    	

-		//return (L_num<<15)/var2;

-

-    	for (iteration = 0; iteration < 15; iteration++)

-    	{

-    		var_out <<= 1;

-    		L_num <<= 1;

-    		

-    		if (L_num >= L_denom)

-    		{

-    			L_num -= L_denom;

-    			var_out++;

-    		}

-    	}

-    }

-    return (var_out);

-}

-#endif

-

-/* Short mult,          1   */

-#if (MULT_IS_INLINE)

-__inline Word16 mult (Word16 var1, Word16 var2)

-{

-#if ARMV5TE_MULT

-	Word32 result; 

-	asm volatile( 

-		"SMULBB r2, %[var1], %[var2] \n"

-		"MOV	r3, #1\n"

-		"MOV	%[result], r2, ASR #15\n"

-		"RSB	r3, r3, r3, LSL #15\n"

-		"MOV	r2, %[result], ASR #15\n"

-		"TEQ	r2, %[result], ASR #31\n"

-		"EORNE  %[result], r3, %[result], ASR #31 \n"

-		:[result]"+r"(result)

-		:[var1]"r"(var1), [var2]"r"(var2)

-		:"r2", "r3"

-		); 

-	return result;

-#else

-    Word16 var_out;

-    Word32 L_product;

-

-    L_product = (Word32) var1 *(Word32) var2;

-    L_product = (L_product & (Word32) 0xffff8000L) >> 15;

-    if (L_product & (Word32) 0x00010000L)

-        L_product = L_product | (Word32) 0xffff0000L;

-    var_out = saturate(L_product);

-

-    return (var_out);

-#endif

-}

-#endif

-

-

-/* Short norm,           15  */

-#if (NORM_S_IS_INLINE)

-__inline Word16 norm_s (Word16 var1)

-{

-#if ARMV5TE_NORM_S

-	Word16 result; 

-	asm volatile( 

-		"MOV   r2,%[var1] \n"

-		"CMP   r2, #0\n"

-		"RSBLT %[var1], %[var1], #0 \n"

-		"CLZNE %[result], %[var1]\n"

-		"SUBNE %[result], %[result], #17\n"

-		"MOVEQ %[result], #0\n"

-		"CMP   r2, #-1\n"

-		"MOVEQ %[result], #15\n" 

-		:[result]"+r"(result)

-		:[var1]"r"(var1)

-		:"r2"

-		); 

-	return result;

-#else

-    Word16 var_out;

-

-    if (var1 == 0)

-    {

-        var_out = 0;

-    }

-    else

-    {

-        if (var1 == -1)

-        {

-            var_out = 15;

-        }

-        else

-        {

-            if (var1 < 0)

-            {

-                var1 = (Word16)~var1;

-            }

-            for (var_out = 0; var1 < 0x4000; var_out++)

-            {

-                var1 <<= 1;

-            }

-        }

-    }

-    return (var_out);

-#endif

-}

-#endif

-

-/* Long norm,            30  */

-#if (NORM_L_IS_INLINE)

-__inline Word16 norm_l (Word32 L_var1)

-{

-#if ARMV5TE_NORM_L

-	Word16 result; 

-	asm volatile( 

-		"CMP    %[L_var1], #0\n"

-		"CLZNE  %[result], %[L_var1]\n"

-		"SUBNE  %[result], %[result], #1\n" 

-		"MOVEQ  %[result], #0\n"

-		:[result]"+r"(result)

-		:[L_var1]"r"(L_var1)

-		); 

-	return result;

-#else

-    //Word16 var_out;

-

-    //if (L_var1 == 0)

-    //{

-    //    var_out = 0;

-    //}

-    //else

-    //{

-    //    if (L_var1 == (Word32) 0xffffffffL)

-    //    {

-    //        var_out = 31;

-    //    }

-    //    else

-    //    {

-    //        if (L_var1 < 0)

-    //        {

-    //            L_var1 = ~L_var1;

-    //        }

-    //        for (var_out = 0; L_var1 < (Word32) 0x40000000L; var_out++)

-    //        {

-    //            L_var1 <<= 1;

-    //        }

-    //    }

-    //}

-    //return (var_out);

-  Word16 a16;

-  Word16 r = 0 ;       

-

-   

-  if ( L_var1 < 0 ) {

-    L_var1 = ~L_var1; 

-  }

-

-  if (0 == (L_var1 & 0x7fff8000)) {

-    a16 = extract_l(L_var1);

-    r += 16;

-       

-    if (0 == (a16 & 0x7f80)) {

-      r += 8;

-         

-      if (0 == (a16 & 0x0078)) {

-        r += 4;

-           

-        if (0 == (a16 & 0x0006)) {

-          r += 2;

-             

-          if (0 == (a16 & 0x0001)) {

-            r += 1;

-          }

-        }

-        else {

-             

-          if (0 == (a16 & 0x0004)) {

-            r += 1;

-          }

-        }

-      }

-      else {

-           

-        if (0 == (a16 & 0x0060)) {

-          r += 2;

-             

-          if (0 == (a16 & 0x0010)) {

-            r += 1;

-          }

-        }

-        else {

-             

-          if (0 == (a16 & 0x0040)) {

-            r += 1;

-          }

-        }

-      }

-    } 

-    else { 

-         

-      if (0 == (a16 & 0x7800)) {

-        r += 4;

-           

-        if (0 == (a16 & 0x0600)) {

-          r += 2;

-             

-          if (0 == (a16 & 0x0100)) {

-            r += 1;

-          }

-        }

-        else {

-             

-          if (0 == (a16 & 0x0400)) {

-            r += 1;

-          }

-        }

-      }

-      else {

-           

-        if (0 == (a16 & 0x6000)) {

-          r += 2;

-             

-          if (0 == (a16 & 0x1000)) {

-            r += 1;

-          }

-        }

-        else {

-             

-          if (0 == (a16 & 0x4000)) {

-            r += 1;

-          }

-        }

-      }

-    }

-  }

-  else {

-    a16 = extract_h(L_var1);

-       

-    if (0 == (a16 & 0x7f80)) {

-      r += 8;

-         

-      if (0 == (a16 & 0x0078)) {

-        r += 4 ;

-           

-        if (0 == (a16 & 0x0006)) {

-          r += 2;

-             

-          if (0 == (a16 & 0x0001)) {

-            r += 1;

-          }

-        }

-        else {

-             

-          if (0 == (a16 & 0x0004)) {

-            r += 1;

-          }

-        }

-      }

-      else {

-           

-        if (0 == (a16 & 0x0060)) {

-          r += 2;

-             

-          if (0 == (a16 & 0x0010)) {

-            r += 1;

-          }

-        }

-        else {

-             

-          if (0 == (a16 & 0x0040)) {

-            r += 1;

-          }

-        }

-      }

-    }

-    else {

-         

-      if (0 == (a16 & 0x7800)) {

-        r += 4;

-           

-        if (0 == (a16 & 0x0600)) {

-          r += 2;

-             

-          if (0 == (a16 & 0x0100)) {

-            r += 1;

-          }

-        }

-        else {

-             

-          if (0 == (a16 & 0x0400)) {

-            r += 1;

-          }

-        }

-      }

-      else {

-           

-        if (0 == (a16 & 0x6000)) {

-          r += 2;

-             

-          if (0 == (a16 & 0x1000)) {

-            r += 1;

-          }

-        }

-        else {

-             

-          if (0 == (a16 & 0x4000)) {

-            return 1;

-          }

-        }

-      }

-    }

-  }

-  

-  return r ;

-#endif

-}

-#endif

-

-/* Round,               1   */

-#if (ROUND_IS_INLINE)

-__inline Word16 round16(Word32 L_var1)

-{

-#if ARMV5TE_ROUND

-	Word16 result; 

-	asm volatile( 

-		"MOV   r1,#0x00008000\n"

-		"QADD  %[result], %[L_var1], r1\n"

-		"MOV   %[result], %[result], ASR #16 \n" 

-		:[result]"+r"(result)

-		:[L_var1]"r"(L_var1)

-		:"r1"

-		); 

-	return result;

-#else   

-    Word16 var_out;

-    Word32 L_rounded;

-

-    L_rounded = L_add (L_var1, (Word32) 0x00008000L);

-    var_out = extract_h (L_rounded);

-    return (var_out);

-#endif

-}

-#endif

-

-/* Mac,  1  */

-#if (L_MAC_IS_INLINE)

-__inline Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2)

-{

-#if ARMV5TE_L_MAC

-	Word32 result; 

-	asm volatile( 

-		"SMULBB %[result], %[var1], %[var2]\n"

-		"QADD	%[result], %[result], %[result]\n"

-		"QADD   %[result], %[result], %[L_var3]\n"

-		:[result]"+r"(result)

-		: [L_var3]"r"(L_var3), [var1]"r"(var1), [var2]"r"(var2)

-		); 

-	return result;

-#else

-    Word32 L_var_out;

-    Word32 L_product;

-

-    L_product = L_mult(var1, var2);

-    L_var_out = L_add (L_var3, L_product);

-    return (L_var_out);

-#endif

-}

-#endif

-

-#if (L_ADD_IS_INLINE)

-__inline Word32 L_add (Word32 L_var1, Word32 L_var2)

-{

-#if ARMV5TE_L_ADD

-	Word32 result; 

-	asm volatile( 

-		"QADD %[result], %[L_var1], %[L_var2]\n"

-		:[result]"+r"(result)

-		:[L_var1]"r"(L_var1), [L_var2]"r"(L_var2)

-		); 

-	return result;

-#else

-    Word32 L_var_out;

-

-    L_var_out = L_var1 + L_var2;

-    if (((L_var1 ^ L_var2) & MIN_32) == 0)

-    {

-        if ((L_var_out ^ L_var1) & MIN_32)

-        {

-            L_var_out = (L_var1 < 0) ? MIN_32 : MAX_32;

-        }

-    }

-    return (L_var_out);

-#endif

-}

-#endif

-

-

-

-#if (MULT_R_IS_INLINE)

-__inline Word16 mult_r (Word16 var1, Word16 var2)

-{

-    Word16 var_out;

-    Word32 L_product_arr;

-

-    L_product_arr = (Word32)var1 *(Word32)var2;       /* product */

-    L_product_arr += (Word32)0x00004000L;      /* round */

-    L_product_arr >>= 15;       /* shift */

-

-    var_out = saturate(L_product_arr);

-

-    return (var_out);

-}

-#endif

-

-#if (SHR_R_IS_INLINE)

-__inline Word16 shr_r (Word16 var1, Word16 var2)

-{

-    Word16 var_out;

-

-    if (var2 > 15)

-    {

-        var_out = 0;

-    }

-    else

-    {

-        var_out = shr(var1, var2);

-

-        if (var2 > 0)

-        {

-            if ((var1 & ((Word16) 1 << (var2 - 1))) != 0)

-            {

-                var_out++;

-            }

-        }

-    }

-

-    return (var_out);

-}

-#endif

-

-#if (MAC_R_IS_INLINE)

-__inline Word16 mac_r (Word32 L_var3, Word16 var1, Word16 var2)

-{

-    Word16 var_out;

-

-    L_var3 = L_mac (L_var3, var1, var2);

-    var_out = (Word16)((L_var3 + 0x8000L) >> 16);

-

-    return (var_out);

-}

-#endif

-

-#if (MSU_R_IS_INLINE)

-__inline Word16 msu_r (Word32 L_var3, Word16 var1, Word16 var2)

-{

-    Word16 var_out;

-

-    L_var3 = L_msu (L_var3, var1, var2);

-    var_out = (Word16)((L_var3 + 0x8000L) >> 16);

-    

-    return (var_out);

-}

-#endif

-

-#if (L_SHR_R_IS_INLINE)

-__inline Word32 L_shr_r (Word32 L_var1, Word16 var2)

-{

-    Word32 L_var_out;

-

-    if (var2 > 31)

-    {

-        L_var_out = 0;

-    }

-    else

-    {

-        L_var_out = L_shr(L_var1, var2);

-

-        if (var2 > 0)

-        {

-            if ((L_var1 & ((Word32) 1 << (var2 - 1))) != 0)

-            {

-                L_var_out++;

-            }

-        }

-    }

-

-    return (L_var_out);

-}

-#endif

-

-#if (EXTRACT_H_IS_INLINE)

-__inline Word16 extract_h (Word32 L_var1)

-{

-    Word16 var_out;

-

-    var_out = (Word16) (L_var1 >> 16);

-

-    return (var_out);

-}

-#endif

-

-#if (EXTRACT_L_IS_INLINE)

-__inline Word16 extract_l(Word32 L_var1)

-{

-	return (Word16) L_var1;

-}

-#endif

-

+#define ABS(a)	((a) >= 0) ? (a) : (-(a))
+
+/* Short abs,           1   */
+#define abs_s(x)       ((Word16)(((x) != MIN_16) ? (((x) >= 0) ? (x) : (-(x))) : MAX_16))
+
+/* 16 bit var1 -> MSB,     2 */
+#define L_deposit_h(x) (((Word32)(x)) << 16)
+
+
+/* 16 bit var1 -> LSB,     2 */
+#define L_deposit_l(x) ((Word32)(x))
+
+
+/* Long abs,              3  */
+#define L_abs(x) (((x) != MIN_32) ? (((x) >= 0) ? (x) : (-(x))) : MAX_32)
+
+
+/* Short negate,        1   */
+#define negate(var1) ((Word16)(((var1) == MIN_16) ? MAX_16 : (-(var1))))
+
+
+/* Long negate,     2 */
+#define L_negate(L_var1) (((L_var1) == (MIN_32)) ? (MAX_32) : (-(L_var1)))
+
+
+#define MULHIGH(A,B) (int)(((Word64)(A)*(Word64)(B)) >> 32)
+#define fixmul(a, b) (int)((((Word64)(a)*(Word64)(b)) >> 32) << 1)
+
+
+#if  (SATRUATE_IS_INLINE)
+__inline Word16 saturate(Word32 L_var1);
+#else
+Word16 saturate(Word32 L_var1);
+#endif
+
+/* Short shift left,    1   */
+#if (SHL_IS_INLINE)
+__inline Word16 shl (Word16 var1, Word16 var2);
+#else
+Word16 shl (Word16 var1, Word16 var2);
+#endif
+
+/* Short shift right,   1   */
+#if (SHR_IS_INLINE)
+__inline Word16 shr (Word16 var1, Word16 var2);
+#else
+Word16 shr (Word16 var1, Word16 var2);
+#endif
+
+#if (L_MULT_IS_INLINE)
+__inline Word32 L_mult(Word16 var1, Word16 var2);
+#else
+Word32 L_mult(Word16 var1, Word16 var2);
+#endif
+
+/* Msu,  1  */
+#if (L_MSU_IS_INLINE)
+__inline Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2);
+#else
+Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2);
+#endif
+
+/* Long sub,        2 */
+#if (L_SUB_IS_INLINE)
+__inline Word32 L_sub(Word32 L_var1, Word32 L_var2);
+#else
+Word32 L_sub(Word32 L_var1, Word32 L_var2);
+#endif
+
+/* Long shift left, 2 */
+#if (L_SHL_IS_INLINE)
+__inline Word32 L_shl (Word32 L_var1, Word16 var2);
+#else
+Word32 L_shl (Word32 L_var1, Word16 var2);
+#endif
+
+/* Long shift right, 2*/
+#if (L_SHR_IS_INLINE)
+__inline Word32 L_shr (Word32 L_var1, Word16 var2);
+#else
+Word32 L_shr (Word32 L_var1, Word16 var2);
+#endif
+
+/* Short add,           1   */
+#if (ADD_IS_INLINE)
+__inline Word16 add (Word16 var1, Word16 var2);
+#else
+Word16 add (Word16 var1, Word16 var2);
+#endif
+
+/* Short sub,           1   */
+#if (SUB_IS_INLINE)
+__inline Word16 sub(Word16 var1, Word16 var2);
+#else
+Word16 sub(Word16 var1, Word16 var2);
+#endif
+
+/* Short division,       18  */
+#if (DIV_S_IS_INLINE)
+__inline Word16 div_s (Word16 var1, Word16 var2);
+#else
+Word16 div_s (Word16 var1, Word16 var2);
+#endif
+
+/* Short mult,          1   */
+#if (MULT_IS_INLINE)
+__inline Word16 mult (Word16 var1, Word16 var2);
+#else
+Word16 mult (Word16 var1, Word16 var2);
+#endif
+
+/* Short norm,           15  */
+#if (NORM_S_IS_INLINE)
+__inline Word16 norm_s (Word16 var1);
+#else
+Word16 norm_s (Word16 var1);
+#endif
+
+/* Long norm,            30  */
+#if (NORM_L_IS_INLINE)
+__inline Word16 norm_l (Word32 L_var1);
+#else
+Word16 norm_l (Word32 L_var1);
+#endif
+
+/* Round,               1   */
+#if (ROUND_IS_INLINE)
+__inline Word16 round16(Word32 L_var1);
+#else
+Word16 round16(Word32 L_var1);
+#endif
+
+/* Mac,  1  */
+#if (L_MAC_IS_INLINE)
+__inline Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2);
+#else
+Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2);
+#endif
+
+#if (L_ADD_IS_INLINE)
+__inline Word32 L_add (Word32 L_var1, Word32 L_var2);
+#else
+Word32 L_add (Word32 L_var1, Word32 L_var2);
+#endif
+
+/* Extract high,        1   */
+#if (EXTRACT_H_IS_INLINE)
+__inline Word16 extract_h (Word32 L_var1);
+#else
+Word16 extract_h (Word32 L_var1);
+#endif
+
+/* Extract low,         1   */
+#if (EXTRACT_L_IS_INLINE)
+__inline Word16 extract_l(Word32 L_var1);
+#else
+Word16 extract_l(Word32 L_var1);
+#endif
+
+/* Mult with round, 2 */
+#if (MULT_R_IS_INLINE)
+__inline Word16 mult_r(Word16 var1, Word16 var2);
+#else
+Word16 mult_r(Word16 var1, Word16 var2);
+#endif
+
+/* Shift right with round, 2           */
+#if (SHR_R_IS_INLINE)
+__inline Word16 shr_r (Word16 var1, Word16 var2);
+#else
+Word16 shr_r (Word16 var1, Word16 var2);
+#endif
+
+/* Mac with rounding,2 */
+#if (MAC_R_IS_INLINE)
+__inline Word16 mac_r (Word32 L_var3, Word16 var1, Word16 var2);
+#else
+Word16 mac_r (Word32 L_var3, Word16 var1, Word16 var2);
+#endif
+
+/* Msu with rounding,2 */
+#if (MSU_R_IS_INLINE)
+__inline Word16 msu_r (Word32 L_var3, Word16 var1, Word16 var2);
+#else
+Word16 msu_r (Word32 L_var3, Word16 var1, Word16 var2);
+#endif
+
+/* Long shift right with round,  3             */
+#if (L_SHR_R_IS_INLINE)
+__inline Word32 L_shr_r (Word32 L_var1, Word16 var2);
+#else
+Word32 L_shr_r (Word32 L_var1, Word16 var2);
+#endif
+
+#if ARMV4_INASM
+__inline Word32 ASM_L_shr(Word32 L_var1, Word16 var2)
+{
+	Word32 result;
+	asm volatile(
+		"MOV %[result], %[L_var1], ASR %[var2] \n"
+		:[result]"=r"(result)
+		:[L_var1]"r"(L_var1), [var2]"r"(var2)
+		);
+	return result;
+}
+
+__inline Word32 ASM_L_shl(Word32 L_var1, Word16 var2)
+{
+	Word32 result;
+	asm volatile(
+		"MOV	r2, %[L_var1] \n"
+		"MOV	r3, #0x7fffffff\n"
+		"MOV	%[result], %[L_var1], ASL %[var2] \n"
+		"TEQ	r2, %[result], ASR %[var2]\n"
+		"EORNE  %[result],r3,r2,ASR#31\n"
+		:[result]"+r"(result)
+		:[L_var1]"r"(L_var1), [var2]"r"(var2)
+		:"r2", "r3"
+		);
+	return result;
+}
+
+__inline Word32 ASM_shr(Word32 L_var1, Word16 var2)
+{
+	Word32 result;
+	asm volatile(
+		"CMP	%[var2], #15\n"
+		"MOVGE  %[var2], #15\n"
+		"MOV	%[result], %[L_var1], ASR %[var2]\n"
+		:[result]"=r"(result)
+		:[L_var1]"r"(L_var1), [var2]"r"(var2)
+		);
+	return result;
+}
+
+__inline Word32 ASM_shl(Word32 L_var1, Word16 var2)
+{
+	Word32 result;
+	asm volatile(
+		"CMP	%[var2], #16\n"
+		"MOVGE  %[var2], #16\n"
+		"MOV    %[result], %[L_var1], ASL %[var2]\n"
+		"MOV    r3, #1\n"
+        "MOV    r2, %[result], ASR #15\n"
+        "RSB    r3,r3,r3,LSL #15 \n"
+        "TEQ    r2, %[result], ASR #31 \n"
+        "EORNE  %[result], r3, %[result],ASR #31"
+		:[result]"+r"(result)
+		:[L_var1]"r"(L_var1), [var2]"r"(var2)
+		:"r2", "r3"
+		);
+	return result;
+}
+#endif
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   definitions for inline basic arithmetic operators                       |
+ |___________________________________________________________________________|
+*/
+#if (SATRUATE_IS_INLINE)
+__inline Word16 saturate(Word32 L_var1)
+{
+#if ARMV5TE_SAT
+	Word16 result;
+	asm volatile (
+		"MOV	%[result], %[L_var1]\n"
+		"MOV	r3, #1\n"
+		"MOV	r2,%[L_var1],ASR#15\n"
+		"RSB	r3, r3, r3, LSL #15\n"
+		"TEQ	r2,%[L_var1],ASR#31\n"
+		"EORNE	%[result],r3,%[L_var1],ASR#31\n"
+		:[result]"+r"(result)
+		:[L_var1]"r"(L_var1)
+		:"r2", "r3"
+	);
+
+	return result;
+#else
+    Word16 var_out;
+
+    //var_out = (L_var1 > (Word32)0X00007fffL) ? (MAX_16) : ((L_var1 < (Word32)0xffff8000L) ? (MIN_16) : ((Word16)L_var1));
+
+    if (L_var1 > 0X00007fffL)
+    {
+        var_out = MAX_16;
+    }
+    else if (L_var1 < (Word32) 0xffff8000L)
+    {
+        var_out = MIN_16;
+    }
+    else
+    {
+        var_out = extract_l(L_var1);
+    }
+
+    return (var_out);
+#endif
+}
+#endif
+
+/* Short shift left,    1   */
+#if (SHL_IS_INLINE)
+__inline Word16 shl (Word16 var1, Word16 var2)
+{
+#if ARMV5TE_SHL
+	if(var2>=0)
+	{
+		return ASM_shl( var1, var2);
+	}
+	else
+	{
+		return ASM_shr( var1, -var2);
+	}
+#else
+    Word16 var_out;
+    Word32 result;
+
+    if (var2 < 0)
+    {
+        var_out = shr (var1, (Word16)-var2);
+    }
+    else
+    {
+        result = (Word32) var1 *((Word32) 1 << var2);
+
+        if ((var2 > 15 && var1 != 0) || (result != (Word32) ((Word16) result)))
+        {
+            var_out = (Word16)((var1 > 0) ? MAX_16 : MIN_16);
+        }
+        else
+        {
+            var_out = extract_l(result);
+        }
+    }
+    return (var_out);
+#endif
+}
+#endif
+
+/* Short shift right,   1   */
+#if (SHR_IS_INLINE)
+__inline Word16 shr (Word16 var1, Word16 var2)
+{
+#if ARMV5TE_SHR
+	if(var2>=0)
+	{
+		return  ASM_shr( var1, var2);
+	}
+	else
+	{
+		return  ASM_shl( var1, -var2);
+	}
+#else
+    Word16 var_out;
+
+    if (var2 < 0)
+    {
+        var_out = shl (var1, (Word16)-var2);
+    }
+    else
+    {
+        if (var2 >= 15)
+        {
+            var_out = (Word16)((var1 < 0) ? -1 : 0);
+        }
+        else
+        {
+            if (var1 < 0)
+            {
+                var_out = (Word16)(~((~var1) >> var2));
+            }
+            else
+            {
+                var_out = (Word16)(var1 >> var2);
+            }
+        }
+    }
+
+    return (var_out);
+#endif
+}
+#endif
+
+
+#if (L_MULT_IS_INLINE)
+__inline Word32 L_mult(Word16 var1, Word16 var2)
+{
+#if ARMV5TE_L_MULT
+	Word32 result;
+	asm volatile(
+		"SMULBB %[result], %[var1], %[var2] \n"
+		"QADD %[result], %[result], %[result] \n"
+		:[result]"+r"(result)
+		:[var1]"r"(var1), [var2]"r"(var2)
+		);
+	return result;
+#else
+    Word32 L_var_out;
+
+    L_var_out = (Word32) var1 *(Word32) var2;
+
+    if (L_var_out != (Word32) 0x40000000L)
+    {
+        L_var_out <<= 1;
+    }
+    else
+    {
+        L_var_out = MAX_32;
+    }
+    return (L_var_out);
+#endif
+}
+#endif
+
+#if (L_MSU_IS_INLINE)
+__inline Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2)
+{
+#if ARMV5TE_L_MSU
+	Word32 result;
+	asm volatile(
+		"SMULBB %[result], %[var1], %[var2] \n"
+		"QADD %[result], %[result], %[result] \n"
+		"QSUB %[result], %[L_var3], %[result]\n"
+		:[result]"+r"(result)
+		:[L_var3]"r"(L_var3), [var1]"r"(var1), [var2]"r"(var2)
+		);
+	return result;
+#else
+    Word32 L_var_out;
+    Word32 L_product;
+
+    L_product = L_mult(var1, var2);
+    L_var_out = L_sub(L_var3, L_product);
+    return (L_var_out);
+#endif
+}
+#endif
+
+#if (L_SUB_IS_INLINE)
+__inline Word32 L_sub(Word32 L_var1, Word32 L_var2)
+{
+#if ARMV5TE_L_SUB
+	Word32 result;
+	asm volatile(
+		"QSUB %[result], %[L_var1], %[L_var2]\n"
+		:[result]"+r"(result)
+		:[L_var1]"r"(L_var1), [L_var2]"r"(L_var2)
+		);
+	return result;
+#else
+    Word32 L_var_out;
+
+    L_var_out = L_var1 - L_var2;
+
+    if (((L_var1 ^ L_var2) & MIN_32) != 0)
+    {
+        if ((L_var_out ^ L_var1) & MIN_32)
+        {
+            L_var_out = (L_var1 < 0L) ? MIN_32 : MAX_32;
+        }
+    }
+
+    return (L_var_out);
+#endif
+}
+#endif
+
+#if (L_SHL_IS_INLINE)
+__inline Word32 L_shl(Word32 L_var1, Word16 var2)
+{
+#if ARMV5TE_L_SHL
+    if(var2>=0)
+    {
+        return  ASM_L_shl( L_var1, var2);
+    }
+    else
+    {
+        return  ASM_L_shr( L_var1, -var2);
+    }
+#else
+    Word32 L_var_out = 0L;
+
+    if (var2 <= 0)
+    {
+        L_var1 = L_shr(L_var1, (Word16)-var2);
+    }
+    else
+    {
+        for (; var2 > 0; var2--)
+        {
+            if (L_var1 > (Word32) 0X3fffffffL)
+            {
+                return MAX_32;
+            }
+            else
+            {
+                if (L_var1 < (Word32) 0xc0000000L)
+                {
+                    return MIN_32;
+                }
+            }
+            L_var1 <<= 1;
+            L_var_out = L_var1;
+        }
+    }
+    return (L_var1);
+#endif
+}
+#endif
+
+#if (L_SHR_IS_INLINE)
+__inline Word32 L_shr (Word32 L_var1, Word16 var2)
+{
+#if ARMV5TE_L_SHR
+	if(var2>=0)
+	{
+		return ASM_L_shr( L_var1, var2);
+	}
+	else
+	{
+		return ASM_L_shl( L_var1, -var2);
+	}
+#else
+    Word32 L_var_out;
+
+    if (var2 < 0)
+    {
+        L_var_out = L_shl (L_var1, (Word16)-var2);
+    }
+    else
+    {
+        if (var2 >= 31)
+        {
+            L_var_out = (L_var1 < 0L) ? -1 : 0;
+        }
+        else
+        {
+            if (L_var1 < 0)
+            {
+                L_var_out = ~((~L_var1) >> var2);
+            }
+            else
+            {
+                L_var_out = L_var1 >> var2;
+            }
+        }
+    }
+    return (L_var_out);
+#endif
+}
+#endif
+
+/* Short add,           1   */
+#if (ADD_IS_INLINE)
+__inline Word16 add (Word16 var1, Word16 var2)
+{
+#if ARMV5TE_ADD
+	Word32 result;
+	asm volatile(
+		"ADD  %[result], %[var1], %[var2] \n"
+		"MOV  r3, #0x1\n"
+		"MOV  r2, %[result], ASR #15\n"
+		"RSB  r3, r3, r3, LSL, #15\n"
+		"TEQ  r2, %[result], ASR #31\n"
+		"EORNE %[result], r3, %[result], ASR #31"
+		:[result]"+r"(result)
+		:[var1]"r"(var1), [var2]"r"(var2)
+		:"r2", "r3"
+		);
+	return result;
+#else
+    Word16 var_out;
+    Word32 L_sum;
+
+    L_sum = (Word32) var1 + var2;
+    var_out = saturate(L_sum);
+
+    return (var_out);
+#endif
+}
+#endif
+
+/* Short sub,           1   */
+#if (SUB_IS_INLINE)
+__inline Word16 sub(Word16 var1, Word16 var2)
+{
+#if ARMV5TE_SUB
+	Word32 result;
+	asm volatile(
+		"MOV   r3, #1\n"
+		"SUB   %[result], %[var1], %[var2] \n"
+		"RSB   r3,r3,r3,LSL#15\n"
+		"MOV   r2, %[var1], ASR #15 \n"
+		"TEQ   r2, %[var1], ASR #31 \n"
+		"EORNE %[result], r3, %[result], ASR #31 \n"
+		:[result]"+r"(result)
+		:[var1]"r"(var1), [var2]"r"(var2)
+		:"r2", "r3"
+		);
+	return result;
+#else
+    Word16 var_out;
+    Word32 L_diff;
+
+    L_diff = (Word32) var1 - var2;
+    var_out = saturate(L_diff);
+
+    return (var_out);
+#endif
+}
+#endif
+
+/* Short division,       18  */
+#if (DIV_S_IS_INLINE)
+__inline Word16 div_s (Word16 var1, Word16 var2)
+{
+    Word16 var_out = 0;
+    Word16 iteration;
+    Word32 L_num;
+    Word32 L_denom;
+
+    var_out = MAX_16;
+    if (var1!= var2)//var1!= var2
+    {
+    	var_out = 0;
+    	L_num = (Word32) var1;
+
+    	L_denom = (Word32) var2;
+
+		//return (L_num<<15)/var2;
+
+    	for (iteration = 0; iteration < 15; iteration++)
+    	{
+    		var_out <<= 1;
+    		L_num <<= 1;
+
+    		if (L_num >= L_denom)
+    		{
+    			L_num -= L_denom;
+    			var_out++;
+    		}
+    	}
+    }
+    return (var_out);
+}
+#endif
+
+/* Short mult,          1   */
+#if (MULT_IS_INLINE)
+__inline Word16 mult (Word16 var1, Word16 var2)
+{
+#if ARMV5TE_MULT
+	Word32 result;
+	asm volatile(
+		"SMULBB r2, %[var1], %[var2] \n"
+		"MOV	r3, #1\n"
+		"MOV	%[result], r2, ASR #15\n"
+		"RSB	r3, r3, r3, LSL #15\n"
+		"MOV	r2, %[result], ASR #15\n"
+		"TEQ	r2, %[result], ASR #31\n"
+		"EORNE  %[result], r3, %[result], ASR #31 \n"
+		:[result]"+r"(result)
+		:[var1]"r"(var1), [var2]"r"(var2)
+		:"r2", "r3"
+		);
+	return result;
+#else
+    Word16 var_out;
+    Word32 L_product;
+
+    L_product = (Word32) var1 *(Word32) var2;
+    L_product = (L_product & (Word32) 0xffff8000L) >> 15;
+    if (L_product & (Word32) 0x00010000L)
+        L_product = L_product | (Word32) 0xffff0000L;
+    var_out = saturate(L_product);
+
+    return (var_out);
+#endif
+}
+#endif
+
+
+/* Short norm,           15  */
+#if (NORM_S_IS_INLINE)
+__inline Word16 norm_s (Word16 var1)
+{
+#if ARMV5TE_NORM_S
+	Word16 result;
+	asm volatile(
+		"MOV   r2,%[var1] \n"
+		"CMP   r2, #0\n"
+		"RSBLT %[var1], %[var1], #0 \n"
+		"CLZNE %[result], %[var1]\n"
+		"SUBNE %[result], %[result], #17\n"
+		"MOVEQ %[result], #0\n"
+		"CMP   r2, #-1\n"
+		"MOVEQ %[result], #15\n"
+		:[result]"+r"(result)
+		:[var1]"r"(var1)
+		:"r2"
+		);
+	return result;
+#else
+    Word16 var_out;
+
+    if (var1 == 0)
+    {
+        var_out = 0;
+    }
+    else
+    {
+        if (var1 == -1)
+        {
+            var_out = 15;
+        }
+        else
+        {
+            if (var1 < 0)
+            {
+                var1 = (Word16)~var1;
+            }
+            for (var_out = 0; var1 < 0x4000; var_out++)
+            {
+                var1 <<= 1;
+            }
+        }
+    }
+    return (var_out);
+#endif
+}
+#endif
+
+/* Long norm,            30  */
+#if (NORM_L_IS_INLINE)
+__inline Word16 norm_l (Word32 L_var1)
+{
+#if ARMV5TE_NORM_L
+	Word16 result;
+	asm volatile(
+		"CMP    %[L_var1], #0\n"
+		"CLZNE  %[result], %[L_var1]\n"
+		"SUBNE  %[result], %[result], #1\n"
+		"MOVEQ  %[result], #0\n"
+		:[result]"+r"(result)
+		:[L_var1]"r"(L_var1)
+		);
+	return result;
+#else
+    //Word16 var_out;
+
+    //if (L_var1 == 0)
+    //{
+    //    var_out = 0;
+    //}
+    //else
+    //{
+    //    if (L_var1 == (Word32) 0xffffffffL)
+    //    {
+    //        var_out = 31;
+    //    }
+    //    else
+    //    {
+    //        if (L_var1 < 0)
+    //        {
+    //            L_var1 = ~L_var1;
+    //        }
+    //        for (var_out = 0; L_var1 < (Word32) 0x40000000L; var_out++)
+    //        {
+    //            L_var1 <<= 1;
+    //        }
+    //    }
+    //}
+    //return (var_out);
+  Word16 a16;
+  Word16 r = 0 ;
+
+
+  if ( L_var1 < 0 ) {
+    L_var1 = ~L_var1;
+  }
+
+  if (0 == (L_var1 & 0x7fff8000)) {
+    a16 = extract_l(L_var1);
+    r += 16;
+
+    if (0 == (a16 & 0x7f80)) {
+      r += 8;
+
+      if (0 == (a16 & 0x0078)) {
+        r += 4;
+
+        if (0 == (a16 & 0x0006)) {
+          r += 2;
+
+          if (0 == (a16 & 0x0001)) {
+            r += 1;
+          }
+        }
+        else {
+
+          if (0 == (a16 & 0x0004)) {
+            r += 1;
+          }
+        }
+      }
+      else {
+
+        if (0 == (a16 & 0x0060)) {
+          r += 2;
+
+          if (0 == (a16 & 0x0010)) {
+            r += 1;
+          }
+        }
+        else {
+
+          if (0 == (a16 & 0x0040)) {
+            r += 1;
+          }
+        }
+      }
+    }
+    else {
+
+      if (0 == (a16 & 0x7800)) {
+        r += 4;
+
+        if (0 == (a16 & 0x0600)) {
+          r += 2;
+
+          if (0 == (a16 & 0x0100)) {
+            r += 1;
+          }
+        }
+        else {
+
+          if (0 == (a16 & 0x0400)) {
+            r += 1;
+          }
+        }
+      }
+      else {
+
+        if (0 == (a16 & 0x6000)) {
+          r += 2;
+
+          if (0 == (a16 & 0x1000)) {
+            r += 1;
+          }
+        }
+        else {
+
+          if (0 == (a16 & 0x4000)) {
+            r += 1;
+          }
+        }
+      }
+    }
+  }
+  else {
+    a16 = extract_h(L_var1);
+
+    if (0 == (a16 & 0x7f80)) {
+      r += 8;
+
+      if (0 == (a16 & 0x0078)) {
+        r += 4 ;
+
+        if (0 == (a16 & 0x0006)) {
+          r += 2;
+
+          if (0 == (a16 & 0x0001)) {
+            r += 1;
+          }
+        }
+        else {
+
+          if (0 == (a16 & 0x0004)) {
+            r += 1;
+          }
+        }
+      }
+      else {
+
+        if (0 == (a16 & 0x0060)) {
+          r += 2;
+
+          if (0 == (a16 & 0x0010)) {
+            r += 1;
+          }
+        }
+        else {
+
+          if (0 == (a16 & 0x0040)) {
+            r += 1;
+          }
+        }
+      }
+    }
+    else {
+
+      if (0 == (a16 & 0x7800)) {
+        r += 4;
+
+        if (0 == (a16 & 0x0600)) {
+          r += 2;
+
+          if (0 == (a16 & 0x0100)) {
+            r += 1;
+          }
+        }
+        else {
+
+          if (0 == (a16 & 0x0400)) {
+            r += 1;
+          }
+        }
+      }
+      else {
+
+        if (0 == (a16 & 0x6000)) {
+          r += 2;
+
+          if (0 == (a16 & 0x1000)) {
+            r += 1;
+          }
+        }
+        else {
+
+          if (0 == (a16 & 0x4000)) {
+            return 1;
+          }
+        }
+      }
+    }
+  }
+
+  return r ;
+#endif
+}
+#endif
+
+/* Round,               1   */
+#if (ROUND_IS_INLINE)
+__inline Word16 round16(Word32 L_var1)
+{
+#if ARMV5TE_ROUND
+	Word16 result;
+	asm volatile(
+		"MOV   r1,#0x00008000\n"
+		"QADD  %[result], %[L_var1], r1\n"
+		"MOV   %[result], %[result], ASR #16 \n"
+		:[result]"+r"(result)
+		:[L_var1]"r"(L_var1)
+		:"r1"
+		);
+	return result;
+#else
+    Word16 var_out;
+    Word32 L_rounded;
+
+    L_rounded = L_add (L_var1, (Word32) 0x00008000L);
+    var_out = extract_h (L_rounded);
+    return (var_out);
+#endif
+}
+#endif
+
+/* Mac,  1  */
+#if (L_MAC_IS_INLINE)
+__inline Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2)
+{
+#if ARMV5TE_L_MAC
+	Word32 result;
+	asm volatile(
+		"SMULBB %[result], %[var1], %[var2]\n"
+		"QADD	%[result], %[result], %[result]\n"
+		"QADD   %[result], %[result], %[L_var3]\n"
+		:[result]"+r"(result)
+		: [L_var3]"r"(L_var3), [var1]"r"(var1), [var2]"r"(var2)
+		);
+	return result;
+#else
+    Word32 L_var_out;
+    Word32 L_product;
+
+    L_product = L_mult(var1, var2);
+    L_var_out = L_add (L_var3, L_product);
+    return (L_var_out);
+#endif
+}
+#endif
+
+#if (L_ADD_IS_INLINE)
+__inline Word32 L_add (Word32 L_var1, Word32 L_var2)
+{
+#if ARMV5TE_L_ADD
+	Word32 result;
+	asm volatile(
+		"QADD %[result], %[L_var1], %[L_var2]\n"
+		:[result]"+r"(result)
+		:[L_var1]"r"(L_var1), [L_var2]"r"(L_var2)
+		);
+	return result;
+#else
+    Word32 L_var_out;
+
+    L_var_out = L_var1 + L_var2;
+    if (((L_var1 ^ L_var2) & MIN_32) == 0)
+    {
+        if ((L_var_out ^ L_var1) & MIN_32)
+        {
+            L_var_out = (L_var1 < 0) ? MIN_32 : MAX_32;
+        }
+    }
+    return (L_var_out);
+#endif
+}
+#endif
+
+
+
+#if (MULT_R_IS_INLINE)
+__inline Word16 mult_r (Word16 var1, Word16 var2)
+{
+    Word16 var_out;
+    Word32 L_product_arr;
+
+    L_product_arr = (Word32)var1 *(Word32)var2;       /* product */
+    L_product_arr += (Word32)0x00004000L;      /* round */
+    L_product_arr >>= 15;       /* shift */
+
+    var_out = saturate(L_product_arr);
+
+    return (var_out);
+}
+#endif
+
+#if (SHR_R_IS_INLINE)
+__inline Word16 shr_r (Word16 var1, Word16 var2)
+{
+    Word16 var_out;
+
+    if (var2 > 15)
+    {
+        var_out = 0;
+    }
+    else
+    {
+        var_out = shr(var1, var2);
+
+        if (var2 > 0)
+        {
+            if ((var1 & ((Word16) 1 << (var2 - 1))) != 0)
+            {
+                var_out++;
+            }
+        }
+    }
+
+    return (var_out);
+}
+#endif
+
+#if (MAC_R_IS_INLINE)
+__inline Word16 mac_r (Word32 L_var3, Word16 var1, Word16 var2)
+{
+    Word16 var_out;
+
+    L_var3 = L_mac (L_var3, var1, var2);
+    var_out = (Word16)((L_var3 + 0x8000L) >> 16);
+
+    return (var_out);
+}
+#endif
+
+#if (MSU_R_IS_INLINE)
+__inline Word16 msu_r (Word32 L_var3, Word16 var1, Word16 var2)
+{
+    Word16 var_out;
+
+    L_var3 = L_msu (L_var3, var1, var2);
+    var_out = (Word16)((L_var3 + 0x8000L) >> 16);
+
+    return (var_out);
+}
+#endif
+
+#if (L_SHR_R_IS_INLINE)
+__inline Word32 L_shr_r (Word32 L_var1, Word16 var2)
+{
+    Word32 L_var_out;
+
+    if (var2 > 31)
+    {
+        L_var_out = 0;
+    }
+    else
+    {
+        L_var_out = L_shr(L_var1, var2);
+
+        if (var2 > 0)
+        {
+            if ((L_var1 & ((Word32) 1 << (var2 - 1))) != 0)
+            {
+                L_var_out++;
+            }
+        }
+    }
+
+    return (L_var_out);
+}
+#endif
+
+#if (EXTRACT_H_IS_INLINE)
+__inline Word16 extract_h (Word32 L_var1)
+{
+    Word16 var_out;
+
+    var_out = (Word16) (L_var1 >> 16);
+
+    return (var_out);
+}
+#endif
+
+#if (EXTRACT_L_IS_INLINE)
+__inline Word16 extract_l(Word32 L_var1)
+{
+	return (Word16) L_var1;
+}
+#endif
+
 #endif
diff --git a/media/libstagefright/codecs/aacenc/basic_op/basicop2.c b/media/libstagefright/codecs/aacenc/basic_op/basicop2.c
index a0d5dba..d43bbd9 100644
--- a/media/libstagefright/codecs/aacenc/basic_op/basicop2.c
+++ b/media/libstagefright/codecs/aacenc/basic_op/basicop2.c
@@ -1,1624 +1,1624 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		basicop2.c

-

-	Content:	Basic arithmetic operators. 

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		basicop2.c
+
+	Content:	Basic arithmetic operators.
+
 *******************************************************************************/
 
 #include "typedef.h"
-#include "basic_op.h"

-

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Functions                                                               |

- |___________________________________________________________________________|

-*/

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : saturate                                                |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |    Limit the 32 bit input to the range of a 16 bit word.                  |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    L_var1                                                                 |

- |             32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.                 |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    var_out                                                                |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |

- |___________________________________________________________________________|

-*/

-

-#if (!SATRUATE_IS_INLINE)

-Word16 saturate(Word32 L_var1)

-{

-    Word16 var_out;

-

-    if (L_var1 > 0X00007fffL)

-    {

-        var_out = MAX_16;

-    }

-    else if (L_var1 < (Word32) 0xffff8000L)

-    {

-        var_out = MIN_16;

-    }

-    else

-    {

-        var_out = extract_l(L_var1);

-    }

-

-    return (var_out);

-}

-#endif

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : add                                                     |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |    Performs the addition (var1+var2) with overflow control and saturation;|

- |    the 16 bit result is set at +32767 when overflow occurs or at -32768   |

- |    when underflow occurs.                                                 |

- |                                                                           |

- |   Complexity weight : 1                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    var1                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |    var2                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    var_out                                                                |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |

- |___________________________________________________________________________|

-*/

-

-#if (!ADD_IS_INLINE)

-Word16 add (Word16 var1, Word16 var2)

-{

-    Word16 var_out;

-    Word32 L_sum;

-

-    L_sum = (Word32)var1 + (Word32)var2;

-    var_out = saturate(L_sum);

-

-    return (var_out);

-}

-#endif

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : sub                                                     |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |    Performs the subtraction (var1+var2) with overflow control and satu-   |

- |    ration; the 16 bit result is set at +32767 when overflow occurs or at  |

- |    -32768 when underflow occurs.                                          |

- |                                                                           |

- |   Complexity weight : 1                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    var1                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |    var2                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    var_out                                                                |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |

- |___________________________________________________________________________|

-*/

-#if (!SUB_IS_INLINE)

-Word16 sub(Word16 var1, Word16 var2)

-{

-    Word16 var_out;

-    Word32 L_diff;

-

-    L_diff = (Word32) var1 - var2;

-    var_out = saturate(L_diff);

-

-    return (var_out);

-}

-#endif

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : abs_s                                                   |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |    Absolute value of var1; abs_s(-32768) = 32767.                         |

- |                                                                           |

- |   Complexity weight : 1                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    var1                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    var_out                                                                |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0x0000 0000 <= var_out <= 0x0000 7fff.                |

- |___________________________________________________________________________|

-*/

-//Word16 abs_s (Word16 var1)

-//{

-//    Word16 var_out;

-//

-//    if (var1 == MIN_16)

-//    {

-//        var_out = MAX_16;

-//    }

-//    else

-//    {

-//        if (var1 < 0)

-//        {

-//            var_out = (Word16)-var1;

-//        }

-//        else

-//        {

-//            var_out = var1;

-//        }

-//    }

-//

-//    return (var_out);

-//}

-

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : shl                                                     |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Arithmetically shift the 16 bit input var1 left var2 positions.Zero fill|

- |   the var2 LSB of the result. If var2 is negative, arithmetically shift   |

- |   var1 right by -var2 with sign extension. Saturate the result in case of |

- |   underflows or overflows.                                                |

- |                                                                           |

- |   Complexity weight : 1                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    var1                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |    var2                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    var_out                                                                |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |

- |___________________________________________________________________________|

-*/

-

-#if (!SHL_IS_INLINE)

-Word16 shl (Word16 var1, Word16 var2)

-{

-    Word16 var_out;

-    Word32 result;

-

-    if (var2 < 0)

-    {

-        if (var2 < -16)

-            var2 = -16;

-        var_out = shr (var1, (Word16)-var2);

-    }

-    else

-    {

-        result = (Word32) var1 *((Word32) 1 << var2);

-

-        if ((var2 > 15 && var1 != 0) || (result != (Word32) ((Word16) result)))

-        {

-            //Overflow = 1;

-            var_out = (Word16)((var1 > 0) ? MAX_16 : MIN_16);

-        }

-        else

-        {

-            var_out = extract_l(result);

-        }

-    }

-

-    return (var_out);

-}

-#endif

-// end

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : shr                                                     |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Arithmetically shift the 16 bit input var1 right var2 positions with    |

- |   sign extension. If var2 is negative, arithmetically shift var1 left by  |

- |   -var2 with sign extension. Saturate the result in case of underflows or |

- |   overflows.                                                              |

- |                                                                           |

- |   Complexity weight : 1                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    var1                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |    var2                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    var_out                                                                |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |

- |___________________________________________________________________________|

-*/

-

-#if (!SHR_IS_INLINE)

-Word16 shr (Word16 var1, Word16 var2)

-{

-    Word16 var_out;

-

-    if (var2 < 0)

-    {

-        if (var2 < -16)

-            var2 = -16;

-        var_out = shl (var1, (Word16)-var2);

-    }

-    else

-    {

-        if (var2 >= 15)

-        {

-            var_out = (Word16)((var1 < 0) ? -1 : 0);

-        }

-        else

-        {

-            if (var1 < 0)

-            {

-                var_out = (Word16)(~((~var1) >> var2));

-            }

-            else

-            {

-                var_out = (Word16)(var1 >> var2);

-            }

-        }

-    }

-

-    return (var_out);

-}

-#endif

-

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : mult                                                    |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |    Performs the multiplication of var1 by var2 and gives a 16 bit result  |

- |    which is scaled i.e.:                                                  |

- |             mult(var1,var2) = extract_l(L_shr((var1 times var2),15)) and  |

- |             mult(-32768,-32768) = 32767.                                  |

- |                                                                           |

- |   Complexity weight : 1                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    var1                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |    var2                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    var_out                                                                |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |

- |___________________________________________________________________________|

-*/

-#if (!MULT_IS_INLINE)

-Word16 mult (Word16 var1, Word16 var2)

-{

-    Word16 var_out;

-    Word32 L_product;

-

-    L_product = (Word32) var1 *(Word32) var2;

-

-    L_product = (L_product & (Word32) 0xffff8000L) >> 15;

-

-    if (L_product & (Word32) 0x00010000L)

-        L_product = L_product | (Word32) 0xffff0000L;

-

-    var_out = saturate(L_product);

-

-    return (var_out);

-}

-#endif

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : L_mult                                                  |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   L_mult is the 32 bit result of the multiplication of var1 times var2    |

- |   with one shift left i.e.:                                               |

- |        L_mult(var1,var2) = L_shl((var1 times var2),1) and                 |

- |        L_mult(-32768,-32768) = 2147483647.                                |

- |                                                                           |

- |   Complexity weight : 1                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    var1                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |    var2                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    L_var_out                                                              |

- |             32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |

- |___________________________________________________________________________|

-*/

-

-#if (!L_MULT_IS_INLINE)

-Word32 L_mult(Word16 var1, Word16 var2)

-{

-    Word32 L_var_out;

-

-    L_var_out = (Word32) var1 *(Word32) var2;

-

-    if (L_var_out != (Word32) 0x40000000L)

-    {

-        L_var_out <<= 1;

-    }

-    else

-    {

-        L_var_out = MAX_32;

-    }

-        

-    return (L_var_out);

-}

-#endif

-// end

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : negate                                                  |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Negate var1 with saturation, saturate in the case where input is -32768:|

- |                negate(var1) = sub(0,var1).                                |

- |                                                                           |

- |   Complexity weight : 1                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    var1                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    var_out                                                                |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |

- |___________________________________________________________________________|

-*/

-//Word16 negate (Word16 var1)

-//{

-//    Word16 var_out;

-//

-//    var_out = (Word16)((var1 == MIN_16) ? MAX_16 : -var1);

-//

-//    return (var_out);

-//}

-

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : extract_h                                               |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Return the 16 MSB of L_var1.                                            |

- |                                                                           |

- |   Complexity weight : 1                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    L_var1                                                                 |

- |             32 bit long signed integer (Word32 ) whose value falls in the |

- |             range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.                 |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    var_out                                                                |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |

- |___________________________________________________________________________|

-*/

-#if (!EXTRACT_H_IS_INLINE)

-Word16 extract_h (Word32 L_var1)

-{

-    Word16 var_out;

-

-    var_out = (Word16) (L_var1 >> 16);

-

-    return (var_out);

-}

-#endif

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : extract_l                                               |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Return the 16 LSB of L_var1.                                            |

- |                                                                           |

- |   Complexity weight : 1                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    L_var1                                                                 |

- |             32 bit long signed integer (Word32 ) whose value falls in the |

- |             range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.                 |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    var_out                                                                |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |

- |___________________________________________________________________________|

-*/

-#if (!EXTRACT_L_IS_INLINE)

-Word16 extract_l(Word32 L_var1)

-{

-    Word16 var_out;

-

-    var_out = (Word16) L_var1;

-

-    return (var_out);

-}

-#endif

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : round                                                   |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Round the lower 16 bits of the 32 bit input number into the MS 16 bits  |

- |   with saturation. Shift the resulting bits right by 16 and return the 16 |

- |   bit number:                                                             |

- |               round(L_var1) = extract_h(L_add(L_var1,32768))              |

- |                                                                           |

- |   Complexity weight : 1                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    L_var1                                                                 |

- |             32 bit long signed integer (Word32 ) whose value falls in the |

- |             range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.                 |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    var_out                                                                |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |

- |___________________________________________________________________________|

-*/

-

-#if (!ROUND_IS_INLINE)

-Word16 round16(Word32 L_var1)

-{

-    Word16 var_out;

-    Word32 L_rounded;

-

-    L_rounded = L_add (L_var1, (Word32) 0x00008000L);

-    var_out = extract_h (L_rounded);

-

-    return (var_out);

-}

-#endif

-// end

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : L_mac                                                   |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Multiply var1 by var2 and shift the result left by 1. Add the 32 bit    |

- |   result to L_var3 with saturation, return a 32 bit result:               |

- |        L_mac(L_var3,var1,var2) = L_add(L_var3,L_mult(var1,var2)).         |

- |                                                                           |

- |   Complexity weight : 1                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    L_var3   32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |

- |                                                                           |

- |    var1                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |    var2                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    L_var_out                                                              |

- |             32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |

- |___________________________________________________________________________|

-*/

-#if (!L_MSU_IS_INLINE)

-Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2)

-{

-    Word32 L_var_out;

-    Word32 L_product;

-

-    L_product = L_mult(var1, var2);

-    L_var_out = L_add (L_var3, L_product);

-

-    return (L_var_out);

-}

-#endif

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : L_msu                                                   |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Multiply var1 by var2 and shift the result left by 1. Subtract the 32   |

- |   bit result to L_var3 with saturation, return a 32 bit result:           |

- |        L_msu(L_var3,var1,var2) = L_sub(L_var3,L_mult(var1,var2)).         |

- |                                                                           |

- |   Complexity weight : 1                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    L_var3   32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |

- |                                                                           |

- |    var1                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |    var2                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    L_var_out                                                              |

- |             32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |

- |___________________________________________________________________________|

-*/

-

-#if (!L_MSU_IS_INLINE)

-Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2)

-{

-    Word32 L_var_out;

-    Word32 L_product;

-

-    L_product = L_mult(var1, var2);

-    L_var_out = L_sub (L_var3, L_product);

-

-    return (L_var_out);

-}

-#endif

-

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : L_add                                                   |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   32 bits addition of the two 32 bits variables (L_var1+L_var2) with      |

- |   overflow control and saturation; the result is set at +2147483647 when  |

- |   overflow occurs or at -2147483648 when underflow occurs.                |

- |                                                                           |

- |   Complexity weight : 2                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    L_var1   32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |

- |                                                                           |

- |    L_var2   32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    L_var_out                                                              |

- |             32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |

- |___________________________________________________________________________|

-*/

-#if (!L_ADD_IS_INLINE)

-Word32 L_add (Word32 L_var1, Word32 L_var2)

-{

-    Word32 L_var_out;

-

-    L_var_out = L_var1 + L_var2;

-

-    if (((L_var1 ^ L_var2) & MIN_32) == 0)

-    {

-        if ((L_var_out ^ L_var1) & MIN_32)

-        {

-            L_var_out = (L_var1 < 0) ? MIN_32 : MAX_32;

-            //Overflow = 1;

-        }

-    }

-

-    return (L_var_out);

-}

-#endif

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : L_sub                                                   |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   32 bits subtraction of the two 32 bits variables (L_var1-L_var2) with   |

- |   overflow control and saturation; the result is set at +2147483647 when  |

- |   overflow occurs or at -2147483648 when underflow occurs.                |

- |                                                                           |

- |   Complexity weight : 2                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    L_var1   32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |

- |                                                                           |

- |    L_var2   32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    L_var_out                                                              |

- |             32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |

- |___________________________________________________________________________|

-*/

-#if (!L_SUB_IS_INLINE)

-Word32 L_sub(Word32 L_var1, Word32 L_var2)

-{

-    Word32 L_var_out;

-

-    L_var_out = L_var1 - L_var2;

-

-    if (((L_var1 ^ L_var2) & MIN_32) != 0)

-    {

-        if ((L_var_out ^ L_var1) & MIN_32)

-        {

-            L_var_out = (L_var1 < 0L) ? MIN_32 : MAX_32;

-            //Overflow = 1;

-        }

-    }

-

-    return (L_var_out);

-}

-#endif

-

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : L_negate                                                |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Negate the 32 bit variable L_var1 with saturation; saturate in the case |

- |   where input is -2147483648 (0x8000 0000).                               |

- |                                                                           |

- |   Complexity weight : 2                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    L_var1   32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    L_var_out                                                              |

- |             32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |

- |___________________________________________________________________________|

-*/

-//Word32 L_negate (Word32 L_var1)

-//{

-//    Word32 L_var_out;

-//

-//    L_var_out = (L_var1 == MIN_32) ? MAX_32 : -L_var1;

-//

-//    return (L_var_out);

-//}

-

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : mult_r                                                  |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Same as mult with rounding, i.e.:                                       |

- |     mult_r(var1,var2) = extract_l(L_shr(((var1 * var2) + 16384),15)) and  |

- |     mult_r(-32768,-32768) = 32767.                                        |

- |                                                                           |

- |   Complexity weight : 2                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    var1                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |    var2                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    var_out                                                                |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |

- |___________________________________________________________________________|

-*/

-#if (!MULT_R_IS_INLINE)

-Word16 mult_r (Word16 var1, Word16 var2)

-{

-    Word16 var_out;

-    Word32 L_product_arr;

-

-    L_product_arr = (Word32) var1 *(Word32) var2;       /* product */

-    L_product_arr += (Word32) 0x00004000L;      /* round */

-    L_product_arr &= (Word32) 0xffff8000L;

-    L_product_arr >>= 15;       /* shift */

-

-    if (L_product_arr & (Word32) 0x00010000L)   /* sign extend when necessary */

-    {

-        L_product_arr |= (Word32) 0xffff0000L;

-    }

-    var_out = saturate(L_product_arr);

-

-    return (var_out);

-}

-#endif

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : L_shl                                                   |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Arithmetically shift the 32 bit input L_var1 left var2 positions. Zero  |

- |   fill the var2 LSB of the result. If var2 is negative, arithmetically    |

- |   shift L_var1 right by -var2 with sign extension. Saturate the result in |

- |   case of underflows or overflows.                                        |

- |                                                                           |

- |   Complexity weight : 2                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    L_var1   32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |

- |                                                                           |

- |    var2                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    L_var_out                                                              |

- |             32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |

- |___________________________________________________________________________|

-*/

-

-#if (!L_SHL_IS_INLINE)

-Word32 L_shl (Word32 L_var1, Word16 var2)

-{

-    Word32 L_var_out = 0L;

-

-    if (var2 <= 0)

-    {

-        L_var1 = L_shr(L_var1, (Word16)-var2);

-    }

-    else

-    {

-        for (; var2 > 0; var2--)

-        {

-            if (L_var1 > (Word32) 0X3fffffffL)

-            {

-                return MAX_32;

-            }

-            else

-            {

-                if (L_var1 < (Word32) 0xc0000000L)

-                {

-                    return MIN_32;

-                }

-            }

-            L_var1 <<= 1;

-        }

-    }

-    return (L_var1);

-}

-#endif

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : L_shr                                                   |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Arithmetically shift the 32 bit input L_var1 right var2 positions with  |

- |   sign extension. If var2 is negative, arithmetically shift L_var1 left   |

- |   by -var2 and zero fill the -var2 LSB of the result. Saturate the result |

- |   in case of underflows or overflows.                                     |

- |                                                                           |

- |   Complexity weight : 2                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    L_var1   32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |

- |                                                                           |

- |    var2                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    L_var_out                                                              |

- |             32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |

- |___________________________________________________________________________|

-*/

-

-#if (!L_SHR_IS_INLINE)

-Word32 L_shr (Word32 L_var1, Word16 var2)

-{

-    Word32 L_var_out;

-

-    if (var2 < 0)

-    {

-        L_var_out = L_shl (L_var1, (Word16)-var2);

-    }

-    else

-    {

-        if (var2 >= 31)

-        {

-            L_var_out = (L_var1 < 0L) ? -1 : 0;

-        }

-        else

-        {

-            if (L_var1 < 0)

-            {

-                L_var_out = ~((~L_var1) >> var2);

-            }

-            else

-            {

-                L_var_out = L_var1 >> var2;

-            }

-        }

-    }

-    return (L_var_out);

-}

-#endif

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : shr_r                                                   |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Same as shr(var1,var2) but with rounding. Saturate the result in case of|

- |   underflows or overflows :                                               |

- |    - If var2 is greater than zero :                                       |

- |          if (sub(shl(shr(var1,var2),1),shr(var1,sub(var2,1))))            |

- |          is equal to zero                                                 |

- |                     then                                                  |

- |                     shr_r(var1,var2) = shr(var1,var2)                     |

- |                     else                                                  |

- |                     shr_r(var1,var2) = add(shr(var1,var2),1)              |

- |    - If var2 is less than or equal to zero :                              |

- |                     shr_r(var1,var2) = shr(var1,var2).                    |

- |                                                                           |

- |   Complexity weight : 2                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    var1                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |    var2                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    var_out                                                                |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |

- |___________________________________________________________________________|

-*/

-#if (!SHR_R_IS_INLINE)

-Word16 shr_r (Word16 var1, Word16 var2)

-{

-    Word16 var_out;

-

-    if (var2 > 15)

-    {

-        var_out = 0;

-    }

-    else

-    {

-        var_out = shr (var1, var2);

-

-        if (var2 > 0)

-        {

-            if ((var1 & ((Word16) 1 << (var2 - 1))) != 0)

-            {

-                var_out++;

-            }

-        }

-    }

-

-    return (var_out);

-}

-#endif

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : mac_r                                                   |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Multiply var1 by var2 and shift the result left by 1. Add the 32 bit    |

- |   result to L_var3 with saturation. Round the LS 16 bits of the result    |

- |   into the MS 16 bits with saturation and shift the result right by 16.   |

- |   Return a 16 bit result.                                                 |

- |            mac_r(L_var3,var1,var2) = round(L_mac(L_var3,var1,var2))       |

- |                                                                           |

- |   Complexity weight : 2                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    L_var3   32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |

- |                                                                           |

- |    var1                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |    var2                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    var_out                                                                |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0x0000 8000 <= L_var_out <= 0x0000 7fff.              |

- |___________________________________________________________________________|

-*/

-#if (!MAC_R_IS_INLINE)

-Word16 mac_r (Word32 L_var3, Word16 var1, Word16 var2)

-{

-    Word16 var_out;

-

-    L_var3 = L_mac (L_var3, var1, var2);

-    L_var3 = L_add (L_var3, (Word32) 0x00008000L);

-    var_out = extract_h (L_var3);

-

-    return (var_out);

-}

-#endif

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : msu_r                                                   |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Multiply var1 by var2 and shift the result left by 1. Subtract the 32   |

- |   bit result to L_var3 with saturation. Round the LS 16 bits of the res-  |

- |   ult into the MS 16 bits with saturation and shift the result right by   |

- |   16. Return a 16 bit result.                                             |

- |            msu_r(L_var3,var1,var2) = round(L_msu(L_var3,var1,var2))       |

- |                                                                           |

- |   Complexity weight : 2                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    L_var3   32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |

- |                                                                           |

- |    var1                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |    var2                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    var_out                                                                |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0x0000 8000 <= L_var_out <= 0x0000 7fff.              |

- |___________________________________________________________________________|

-*/

-#if (!MSU_R_IS_INLINE)

-Word16 msu_r (Word32 L_var3, Word16 var1, Word16 var2)

-{

-    Word16 var_out;

-

-    L_var3 = L_msu (L_var3, var1, var2);

-    L_var3 = L_add (L_var3, (Word32) 0x00008000L);

-    var_out = extract_h (L_var3);

-

-    return (var_out);

-}

-#endif

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : L_deposit_h                                             |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Deposit the 16 bit var1 into the 16 MS bits of the 32 bit output. The   |

- |   16 LS bits of the output are zeroed.                                    |

- |                                                                           |

- |   Complexity weight : 2                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    var1                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    L_var_out                                                              |

- |             32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= var_out <= 0x7fff 0000.                |

- |___________________________________________________________________________|

-*/

-//Word32 L_deposit_h (Word16 var1)

-//{

-//    Word32 L_var_out;

-//

-//    L_var_out = (Word32) var1 << 16;

-//

-//    return (L_var_out);

-//}

-

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : L_deposit_l                                             |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Deposit the 16 bit var1 into the 16 LS bits of the 32 bit output. The   |

- |   16 MS bits of the output are sign extended.                             |

- |                                                                           |

- |   Complexity weight : 2                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    var1                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    L_var_out                                                              |

- |             32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0xFFFF 8000 <= var_out <= 0x0000 7fff.                |

- |___________________________________________________________________________|

-*/

-//Word32 L_deposit_l (Word16 var1)

-//{

-//    Word32 L_var_out;

-//

-//    L_var_out = (Word32) var1;

-//

-//    return (L_var_out);

-//}

-

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : L_shr_r                                                 |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Same as L_shr(L_var1,var2) but with rounding. Saturate the result in    |

- |   case of underflows or overflows :                                       |

- |    - If var2 is greater than zero :                                       |

- |          if (L_sub(L_shl(L_shr(L_var1,var2),1),L_shr(L_var1,sub(var2,1))))|

- |          is equal to zero                                                 |

- |                     then                                                  |

- |                     L_shr_r(L_var1,var2) = L_shr(L_var1,var2)             |

- |                     else                                                  |

- |                     L_shr_r(L_var1,var2) = L_add(L_shr(L_var1,var2),1)    |

- |    - If var2 is less than or equal to zero :                              |

- |                     L_shr_r(L_var1,var2) = L_shr(L_var1,var2).            |

- |                                                                           |

- |   Complexity weight : 3                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    L_var1                                                                 |

- |             32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= var1 <= 0x7fff ffff.                   |

- |                                                                           |

- |    var2                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    L_var_out                                                              |

- |             32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= var_out <= 0x7fff ffff.                |

- |___________________________________________________________________________|

-*/

-#if (!L_SHR_R_IS_INLINE)

-Word32 L_shr_r (Word32 L_var1, Word16 var2)

-{

-    Word32 L_var_out;

-

-    if (var2 > 31)

-    {

-        L_var_out = 0;

-    }

-    else

-    {

-        L_var_out = L_shr (L_var1, var2);

-

-        if (var2 > 0)

-        {

-            if ((L_var1 & ((Word32) 1 << (var2 - 1))) != 0)

-            {

-                L_var_out++;

-            }

-        }

-    }

-

-    return (L_var_out);

-}

-#endif

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : L_abs                                                   |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |    Absolute value of L_var1; Saturate in case where the input is          |

- |                                                               -214783648  |

- |                                                                           |

- |   Complexity weight : 3                                                   |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    L_var1                                                                 |

- |             32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= var1 <= 0x7fff ffff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    L_var_out                                                              |

- |             32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x0000 0000 <= var_out <= 0x7fff ffff.                |

- |___________________________________________________________________________|

-*/

-//Word32 L_abs (Word32 L_var1)

-//{

-//    Word32 L_var_out;

-//

-//    if (L_var1 == MIN_32)

-//    {

-//        L_var_out = MAX_32;

-//    }

-//    else

-//    {

-//        if (L_var1 < 0)

-//        {

-//            L_var_out = -L_var1;

-//        }

-//        else

-//        {

-//            L_var_out = L_var1;

-//        }

-//    }

-//

-//    return (L_var_out);

-//}

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : norm_s                                                  |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Produces the number of left shift needed to normalize the 16 bit varia- |

- |   ble var1 for positive values on the interval with minimum of 16384 and  |

- |   maximum of 32767, and for negative values on the interval with minimum  |

- |   of -32768 and maximum of -16384; in order to normalize the result, the  |

- |   following operation must be done :                                      |

- |                    norm_var1 = shl(var1,norm_s(var1)).                    |

- |                                                                           |

- |   Complexity weight : 15                                                  |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    var1                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    var_out                                                                |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0x0000 0000 <= var_out <= 0x0000 000f.                |

- |___________________________________________________________________________|

-*/

-

-#if (!NORM_S_IS_INLINE)

-Word16 norm_s (Word16 var1)

-{

-    Word16 var_out;

-

-    if (var1 == 0)

-    {

-        var_out = 0;

-    }

-    else

-    {

-        if (var1 == -1)

-        {

-            var_out = 15;

-        }

-        else

-        {

-            if (var1 < 0)

-            {

-                var1 = (Word16)~var1;

-            }

-            for (var_out = 0; var1 < 0x4000; var_out++)

-            {

-                var1 <<= 1;

-            }

-        }

-    }

-

-    return (var_out);

-}

-#endif

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : div_s                                                   |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Produces a result which is the fractional integer division of var1  by  |

- |   var2; var1 and var2 must be positive and var2 must be greater or equal  |

- |   to var1; the result is positive (leading bit equal to 0) and truncated  |

- |   to 16 bits.                                                             |

- |   If var1 = var2 then div(var1,var2) = 32767.                             |

- |                                                                           |

- |   Complexity weight : 18                                                  |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    var1                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0x0000 0000 <= var1 <= var2 and var2 != 0.            |

- |                                                                           |

- |    var2                                                                   |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : var1 <= var2 <= 0x0000 7fff and var2 != 0.            |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    var_out                                                                |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0x0000 0000 <= var_out <= 0x0000 7fff.                |

- |             It's a Q15 value (point between b15 and b14).                 |

- |___________________________________________________________________________|

-*/

-

-#if (!DIV_S_IS_INLINE)

-Word16 div_s (Word16 var1, Word16 var2)

-{

-    Word16 var_out = 0;

-    Word16 iteration;

-    Word32 L_num;

-    Word32 L_denom;

-

-    if (var1 == 0)

-    {

-        var_out = 0;

-    }

-    else

-    {

-        if (var1 == var2)

-        {

-            var_out = MAX_16;

-        }

-        else

-        {

-            L_num = L_deposit_l (var1);

-            L_denom = L_deposit_l (var2);

-

-            for (iteration = 0; iteration < 15; iteration++)

-            {

-                var_out <<= 1;

-                L_num <<= 1;

-

-                if (L_num >= L_denom)

-                {

-                    L_num = L_sub(L_num, L_denom);

-                    var_out = add (var_out, 1);

-                }

-            }

-        }

-    }

-

-    return (var_out);

-}

-#endif

-

-/*___________________________________________________________________________

- |                                                                           |

- |   Function Name : norm_l                                                  |

- |                                                                           |

- |   Purpose :                                                               |

- |                                                                           |

- |   Produces the number of left shifts needed to normalize the 32 bit varia-|

- |   ble L_var1 for positive values on the interval with minimum of          |

- |   1073741824 and maximum of 2147483647, and for negative values on the in-|

- |   terval with minimum of -2147483648 and maximum of -1073741824; in order |

- |   to normalize the result, the following operation must be done :         |

- |                   norm_L_var1 = L_shl(L_var1,norm_l(L_var1)).             |

- |                                                                           |

- |   Complexity weight : 30                                                  |

- |                                                                           |

- |   Inputs :                                                                |

- |                                                                           |

- |    L_var1                                                                 |

- |             32 bit long signed integer (Word32) whose value falls in the  |

- |             range : 0x8000 0000 <= var1 <= 0x7fff ffff.                   |

- |                                                                           |

- |   Outputs :                                                               |

- |                                                                           |

- |    none                                                                   |

- |                                                                           |

- |   Return Value :                                                          |

- |                                                                           |

- |    var_out                                                                |

- |             16 bit short signed integer (Word16) whose value falls in the |

- |             range : 0x0000 0000 <= var_out <= 0x0000 001f.                |

- |___________________________________________________________________________|

-*/

-

-#if (!NORM_L_IS_INLINE)

-Word16 norm_l (Word32 L_var1)

-{

-    Word16 var_out;

-

-    if (L_var1 == 0)

-    {

-        var_out = 0;

-    }

-    else

-    {

-        if (L_var1 == (Word32) 0xffffffffL)

-        {

-            var_out = 31;

-        }

-        else

-        {

-            if (L_var1 < 0)

-            {

-                L_var1 = ~L_var1;

-            }

-            for (var_out = 0; L_var1 < (Word32) 0x40000000L; var_out++)

-            {

-                L_var1 <<= 1;

-            }

-        }

-    }

-

-    return (var_out);

-}

-#endif

+#include "basic_op.h"
+
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Functions                                                               |
+ |___________________________________________________________________________|
+*/
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : saturate                                                |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |    Limit the 32 bit input to the range of a 16 bit word.                  |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    L_var1                                                                 |
+ |             32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.                 |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    var_out                                                                |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
+ |___________________________________________________________________________|
+*/
+
+#if (!SATRUATE_IS_INLINE)
+Word16 saturate(Word32 L_var1)
+{
+    Word16 var_out;
+
+    if (L_var1 > 0X00007fffL)
+    {
+        var_out = MAX_16;
+    }
+    else if (L_var1 < (Word32) 0xffff8000L)
+    {
+        var_out = MIN_16;
+    }
+    else
+    {
+        var_out = extract_l(L_var1);
+    }
+
+    return (var_out);
+}
+#endif
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : add                                                     |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |    Performs the addition (var1+var2) with overflow control and saturation;|
+ |    the 16 bit result is set at +32767 when overflow occurs or at -32768   |
+ |    when underflow occurs.                                                 |
+ |                                                                           |
+ |   Complexity weight : 1                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    var1                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |    var2                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    var_out                                                                |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
+ |___________________________________________________________________________|
+*/
+
+#if (!ADD_IS_INLINE)
+Word16 add (Word16 var1, Word16 var2)
+{
+    Word16 var_out;
+    Word32 L_sum;
+
+    L_sum = (Word32)var1 + (Word32)var2;
+    var_out = saturate(L_sum);
+
+    return (var_out);
+}
+#endif
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : sub                                                     |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |    Performs the subtraction (var1+var2) with overflow control and satu-   |
+ |    ration; the 16 bit result is set at +32767 when overflow occurs or at  |
+ |    -32768 when underflow occurs.                                          |
+ |                                                                           |
+ |   Complexity weight : 1                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    var1                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |    var2                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    var_out                                                                |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
+ |___________________________________________________________________________|
+*/
+#if (!SUB_IS_INLINE)
+Word16 sub(Word16 var1, Word16 var2)
+{
+    Word16 var_out;
+    Word32 L_diff;
+
+    L_diff = (Word32) var1 - var2;
+    var_out = saturate(L_diff);
+
+    return (var_out);
+}
+#endif
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : abs_s                                                   |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |    Absolute value of var1; abs_s(-32768) = 32767.                         |
+ |                                                                           |
+ |   Complexity weight : 1                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    var1                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    var_out                                                                |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0x0000 0000 <= var_out <= 0x0000 7fff.                |
+ |___________________________________________________________________________|
+*/
+//Word16 abs_s (Word16 var1)
+//{
+//    Word16 var_out;
+//
+//    if (var1 == MIN_16)
+//    {
+//        var_out = MAX_16;
+//    }
+//    else
+//    {
+//        if (var1 < 0)
+//        {
+//            var_out = (Word16)-var1;
+//        }
+//        else
+//        {
+//            var_out = var1;
+//        }
+//    }
+//
+//    return (var_out);
+//}
+
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : shl                                                     |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Arithmetically shift the 16 bit input var1 left var2 positions.Zero fill|
+ |   the var2 LSB of the result. If var2 is negative, arithmetically shift   |
+ |   var1 right by -var2 with sign extension. Saturate the result in case of |
+ |   underflows or overflows.                                                |
+ |                                                                           |
+ |   Complexity weight : 1                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    var1                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |    var2                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    var_out                                                                |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
+ |___________________________________________________________________________|
+*/
+
+#if (!SHL_IS_INLINE)
+Word16 shl (Word16 var1, Word16 var2)
+{
+    Word16 var_out;
+    Word32 result;
+
+    if (var2 < 0)
+    {
+        if (var2 < -16)
+            var2 = -16;
+        var_out = shr (var1, (Word16)-var2);
+    }
+    else
+    {
+        result = (Word32) var1 *((Word32) 1 << var2);
+
+        if ((var2 > 15 && var1 != 0) || (result != (Word32) ((Word16) result)))
+        {
+            //Overflow = 1;
+            var_out = (Word16)((var1 > 0) ? MAX_16 : MIN_16);
+        }
+        else
+        {
+            var_out = extract_l(result);
+        }
+    }
+
+    return (var_out);
+}
+#endif
+// end
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : shr                                                     |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Arithmetically shift the 16 bit input var1 right var2 positions with    |
+ |   sign extension. If var2 is negative, arithmetically shift var1 left by  |
+ |   -var2 with sign extension. Saturate the result in case of underflows or |
+ |   overflows.                                                              |
+ |                                                                           |
+ |   Complexity weight : 1                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    var1                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |    var2                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    var_out                                                                |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
+ |___________________________________________________________________________|
+*/
+
+#if (!SHR_IS_INLINE)
+Word16 shr (Word16 var1, Word16 var2)
+{
+    Word16 var_out;
+
+    if (var2 < 0)
+    {
+        if (var2 < -16)
+            var2 = -16;
+        var_out = shl (var1, (Word16)-var2);
+    }
+    else
+    {
+        if (var2 >= 15)
+        {
+            var_out = (Word16)((var1 < 0) ? -1 : 0);
+        }
+        else
+        {
+            if (var1 < 0)
+            {
+                var_out = (Word16)(~((~var1) >> var2));
+            }
+            else
+            {
+                var_out = (Word16)(var1 >> var2);
+            }
+        }
+    }
+
+    return (var_out);
+}
+#endif
+
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : mult                                                    |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |    Performs the multiplication of var1 by var2 and gives a 16 bit result  |
+ |    which is scaled i.e.:                                                  |
+ |             mult(var1,var2) = extract_l(L_shr((var1 times var2),15)) and  |
+ |             mult(-32768,-32768) = 32767.                                  |
+ |                                                                           |
+ |   Complexity weight : 1                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    var1                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |    var2                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    var_out                                                                |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
+ |___________________________________________________________________________|
+*/
+#if (!MULT_IS_INLINE)
+Word16 mult (Word16 var1, Word16 var2)
+{
+    Word16 var_out;
+    Word32 L_product;
+
+    L_product = (Word32) var1 *(Word32) var2;
+
+    L_product = (L_product & (Word32) 0xffff8000L) >> 15;
+
+    if (L_product & (Word32) 0x00010000L)
+        L_product = L_product | (Word32) 0xffff0000L;
+
+    var_out = saturate(L_product);
+
+    return (var_out);
+}
+#endif
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : L_mult                                                  |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   L_mult is the 32 bit result of the multiplication of var1 times var2    |
+ |   with one shift left i.e.:                                               |
+ |        L_mult(var1,var2) = L_shl((var1 times var2),1) and                 |
+ |        L_mult(-32768,-32768) = 2147483647.                                |
+ |                                                                           |
+ |   Complexity weight : 1                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    var1                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |    var2                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    L_var_out                                                              |
+ |             32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
+ |___________________________________________________________________________|
+*/
+
+#if (!L_MULT_IS_INLINE)
+Word32 L_mult(Word16 var1, Word16 var2)
+{
+    Word32 L_var_out;
+
+    L_var_out = (Word32) var1 *(Word32) var2;
+
+    if (L_var_out != (Word32) 0x40000000L)
+    {
+        L_var_out <<= 1;
+    }
+    else
+    {
+        L_var_out = MAX_32;
+    }
+
+    return (L_var_out);
+}
+#endif
+// end
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : negate                                                  |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Negate var1 with saturation, saturate in the case where input is -32768:|
+ |                negate(var1) = sub(0,var1).                                |
+ |                                                                           |
+ |   Complexity weight : 1                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    var1                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    var_out                                                                |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
+ |___________________________________________________________________________|
+*/
+//Word16 negate (Word16 var1)
+//{
+//    Word16 var_out;
+//
+//    var_out = (Word16)((var1 == MIN_16) ? MAX_16 : -var1);
+//
+//    return (var_out);
+//}
+
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : extract_h                                               |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Return the 16 MSB of L_var1.                                            |
+ |                                                                           |
+ |   Complexity weight : 1                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    L_var1                                                                 |
+ |             32 bit long signed integer (Word32 ) whose value falls in the |
+ |             range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.                 |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    var_out                                                                |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
+ |___________________________________________________________________________|
+*/
+#if (!EXTRACT_H_IS_INLINE)
+Word16 extract_h (Word32 L_var1)
+{
+    Word16 var_out;
+
+    var_out = (Word16) (L_var1 >> 16);
+
+    return (var_out);
+}
+#endif
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : extract_l                                               |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Return the 16 LSB of L_var1.                                            |
+ |                                                                           |
+ |   Complexity weight : 1                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    L_var1                                                                 |
+ |             32 bit long signed integer (Word32 ) whose value falls in the |
+ |             range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.                 |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    var_out                                                                |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
+ |___________________________________________________________________________|
+*/
+#if (!EXTRACT_L_IS_INLINE)
+Word16 extract_l(Word32 L_var1)
+{
+    Word16 var_out;
+
+    var_out = (Word16) L_var1;
+
+    return (var_out);
+}
+#endif
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : round                                                   |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Round the lower 16 bits of the 32 bit input number into the MS 16 bits  |
+ |   with saturation. Shift the resulting bits right by 16 and return the 16 |
+ |   bit number:                                                             |
+ |               round(L_var1) = extract_h(L_add(L_var1,32768))              |
+ |                                                                           |
+ |   Complexity weight : 1                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    L_var1                                                                 |
+ |             32 bit long signed integer (Word32 ) whose value falls in the |
+ |             range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.                 |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    var_out                                                                |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
+ |___________________________________________________________________________|
+*/
+
+#if (!ROUND_IS_INLINE)
+Word16 round16(Word32 L_var1)
+{
+    Word16 var_out;
+    Word32 L_rounded;
+
+    L_rounded = L_add (L_var1, (Word32) 0x00008000L);
+    var_out = extract_h (L_rounded);
+
+    return (var_out);
+}
+#endif
+// end
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : L_mac                                                   |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Multiply var1 by var2 and shift the result left by 1. Add the 32 bit    |
+ |   result to L_var3 with saturation, return a 32 bit result:               |
+ |        L_mac(L_var3,var1,var2) = L_add(L_var3,L_mult(var1,var2)).         |
+ |                                                                           |
+ |   Complexity weight : 1                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    L_var3   32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
+ |                                                                           |
+ |    var1                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |    var2                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    L_var_out                                                              |
+ |             32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
+ |___________________________________________________________________________|
+*/
+#if (!L_MSU_IS_INLINE)
+Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2)
+{
+    Word32 L_var_out;
+    Word32 L_product;
+
+    L_product = L_mult(var1, var2);
+    L_var_out = L_add (L_var3, L_product);
+
+    return (L_var_out);
+}
+#endif
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : L_msu                                                   |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Multiply var1 by var2 and shift the result left by 1. Subtract the 32   |
+ |   bit result to L_var3 with saturation, return a 32 bit result:           |
+ |        L_msu(L_var3,var1,var2) = L_sub(L_var3,L_mult(var1,var2)).         |
+ |                                                                           |
+ |   Complexity weight : 1                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    L_var3   32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
+ |                                                                           |
+ |    var1                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |    var2                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    L_var_out                                                              |
+ |             32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
+ |___________________________________________________________________________|
+*/
+
+#if (!L_MSU_IS_INLINE)
+Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2)
+{
+    Word32 L_var_out;
+    Word32 L_product;
+
+    L_product = L_mult(var1, var2);
+    L_var_out = L_sub (L_var3, L_product);
+
+    return (L_var_out);
+}
+#endif
+
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : L_add                                                   |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   32 bits addition of the two 32 bits variables (L_var1+L_var2) with      |
+ |   overflow control and saturation; the result is set at +2147483647 when  |
+ |   overflow occurs or at -2147483648 when underflow occurs.                |
+ |                                                                           |
+ |   Complexity weight : 2                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    L_var1   32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
+ |                                                                           |
+ |    L_var2   32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    L_var_out                                                              |
+ |             32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
+ |___________________________________________________________________________|
+*/
+#if (!L_ADD_IS_INLINE)
+Word32 L_add (Word32 L_var1, Word32 L_var2)
+{
+    Word32 L_var_out;
+
+    L_var_out = L_var1 + L_var2;
+
+    if (((L_var1 ^ L_var2) & MIN_32) == 0)
+    {
+        if ((L_var_out ^ L_var1) & MIN_32)
+        {
+            L_var_out = (L_var1 < 0) ? MIN_32 : MAX_32;
+            //Overflow = 1;
+        }
+    }
+
+    return (L_var_out);
+}
+#endif
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : L_sub                                                   |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   32 bits subtraction of the two 32 bits variables (L_var1-L_var2) with   |
+ |   overflow control and saturation; the result is set at +2147483647 when  |
+ |   overflow occurs or at -2147483648 when underflow occurs.                |
+ |                                                                           |
+ |   Complexity weight : 2                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    L_var1   32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
+ |                                                                           |
+ |    L_var2   32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    L_var_out                                                              |
+ |             32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
+ |___________________________________________________________________________|
+*/
+#if (!L_SUB_IS_INLINE)
+Word32 L_sub(Word32 L_var1, Word32 L_var2)
+{
+    Word32 L_var_out;
+
+    L_var_out = L_var1 - L_var2;
+
+    if (((L_var1 ^ L_var2) & MIN_32) != 0)
+    {
+        if ((L_var_out ^ L_var1) & MIN_32)
+        {
+            L_var_out = (L_var1 < 0L) ? MIN_32 : MAX_32;
+            //Overflow = 1;
+        }
+    }
+
+    return (L_var_out);
+}
+#endif
+
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : L_negate                                                |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Negate the 32 bit variable L_var1 with saturation; saturate in the case |
+ |   where input is -2147483648 (0x8000 0000).                               |
+ |                                                                           |
+ |   Complexity weight : 2                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    L_var1   32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    L_var_out                                                              |
+ |             32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
+ |___________________________________________________________________________|
+*/
+//Word32 L_negate (Word32 L_var1)
+//{
+//    Word32 L_var_out;
+//
+//    L_var_out = (L_var1 == MIN_32) ? MAX_32 : -L_var1;
+//
+//    return (L_var_out);
+//}
+
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : mult_r                                                  |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Same as mult with rounding, i.e.:                                       |
+ |     mult_r(var1,var2) = extract_l(L_shr(((var1 * var2) + 16384),15)) and  |
+ |     mult_r(-32768,-32768) = 32767.                                        |
+ |                                                                           |
+ |   Complexity weight : 2                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    var1                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |    var2                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    var_out                                                                |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
+ |___________________________________________________________________________|
+*/
+#if (!MULT_R_IS_INLINE)
+Word16 mult_r (Word16 var1, Word16 var2)
+{
+    Word16 var_out;
+    Word32 L_product_arr;
+
+    L_product_arr = (Word32) var1 *(Word32) var2;       /* product */
+    L_product_arr += (Word32) 0x00004000L;      /* round */
+    L_product_arr &= (Word32) 0xffff8000L;
+    L_product_arr >>= 15;       /* shift */
+
+    if (L_product_arr & (Word32) 0x00010000L)   /* sign extend when necessary */
+    {
+        L_product_arr |= (Word32) 0xffff0000L;
+    }
+    var_out = saturate(L_product_arr);
+
+    return (var_out);
+}
+#endif
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : L_shl                                                   |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Arithmetically shift the 32 bit input L_var1 left var2 positions. Zero  |
+ |   fill the var2 LSB of the result. If var2 is negative, arithmetically    |
+ |   shift L_var1 right by -var2 with sign extension. Saturate the result in |
+ |   case of underflows or overflows.                                        |
+ |                                                                           |
+ |   Complexity weight : 2                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    L_var1   32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
+ |                                                                           |
+ |    var2                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    L_var_out                                                              |
+ |             32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
+ |___________________________________________________________________________|
+*/
+
+#if (!L_SHL_IS_INLINE)
+Word32 L_shl (Word32 L_var1, Word16 var2)
+{
+    Word32 L_var_out = 0L;
+
+    if (var2 <= 0)
+    {
+        L_var1 = L_shr(L_var1, (Word16)-var2);
+    }
+    else
+    {
+        for (; var2 > 0; var2--)
+        {
+            if (L_var1 > (Word32) 0X3fffffffL)
+            {
+                return MAX_32;
+            }
+            else
+            {
+                if (L_var1 < (Word32) 0xc0000000L)
+                {
+                    return MIN_32;
+                }
+            }
+            L_var1 <<= 1;
+        }
+    }
+    return (L_var1);
+}
+#endif
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : L_shr                                                   |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Arithmetically shift the 32 bit input L_var1 right var2 positions with  |
+ |   sign extension. If var2 is negative, arithmetically shift L_var1 left   |
+ |   by -var2 and zero fill the -var2 LSB of the result. Saturate the result |
+ |   in case of underflows or overflows.                                     |
+ |                                                                           |
+ |   Complexity weight : 2                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    L_var1   32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
+ |                                                                           |
+ |    var2                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    L_var_out                                                              |
+ |             32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
+ |___________________________________________________________________________|
+*/
+
+#if (!L_SHR_IS_INLINE)
+Word32 L_shr (Word32 L_var1, Word16 var2)
+{
+    Word32 L_var_out;
+
+    if (var2 < 0)
+    {
+        L_var_out = L_shl (L_var1, (Word16)-var2);
+    }
+    else
+    {
+        if (var2 >= 31)
+        {
+            L_var_out = (L_var1 < 0L) ? -1 : 0;
+        }
+        else
+        {
+            if (L_var1 < 0)
+            {
+                L_var_out = ~((~L_var1) >> var2);
+            }
+            else
+            {
+                L_var_out = L_var1 >> var2;
+            }
+        }
+    }
+    return (L_var_out);
+}
+#endif
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : shr_r                                                   |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Same as shr(var1,var2) but with rounding. Saturate the result in case of|
+ |   underflows or overflows :                                               |
+ |    - If var2 is greater than zero :                                       |
+ |          if (sub(shl(shr(var1,var2),1),shr(var1,sub(var2,1))))            |
+ |          is equal to zero                                                 |
+ |                     then                                                  |
+ |                     shr_r(var1,var2) = shr(var1,var2)                     |
+ |                     else                                                  |
+ |                     shr_r(var1,var2) = add(shr(var1,var2),1)              |
+ |    - If var2 is less than or equal to zero :                              |
+ |                     shr_r(var1,var2) = shr(var1,var2).                    |
+ |                                                                           |
+ |   Complexity weight : 2                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    var1                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |    var2                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    var_out                                                                |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
+ |___________________________________________________________________________|
+*/
+#if (!SHR_R_IS_INLINE)
+Word16 shr_r (Word16 var1, Word16 var2)
+{
+    Word16 var_out;
+
+    if (var2 > 15)
+    {
+        var_out = 0;
+    }
+    else
+    {
+        var_out = shr (var1, var2);
+
+        if (var2 > 0)
+        {
+            if ((var1 & ((Word16) 1 << (var2 - 1))) != 0)
+            {
+                var_out++;
+            }
+        }
+    }
+
+    return (var_out);
+}
+#endif
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : mac_r                                                   |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Multiply var1 by var2 and shift the result left by 1. Add the 32 bit    |
+ |   result to L_var3 with saturation. Round the LS 16 bits of the result    |
+ |   into the MS 16 bits with saturation and shift the result right by 16.   |
+ |   Return a 16 bit result.                                                 |
+ |            mac_r(L_var3,var1,var2) = round(L_mac(L_var3,var1,var2))       |
+ |                                                                           |
+ |   Complexity weight : 2                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    L_var3   32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
+ |                                                                           |
+ |    var1                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |    var2                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    var_out                                                                |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0x0000 8000 <= L_var_out <= 0x0000 7fff.              |
+ |___________________________________________________________________________|
+*/
+#if (!MAC_R_IS_INLINE)
+Word16 mac_r (Word32 L_var3, Word16 var1, Word16 var2)
+{
+    Word16 var_out;
+
+    L_var3 = L_mac (L_var3, var1, var2);
+    L_var3 = L_add (L_var3, (Word32) 0x00008000L);
+    var_out = extract_h (L_var3);
+
+    return (var_out);
+}
+#endif
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : msu_r                                                   |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Multiply var1 by var2 and shift the result left by 1. Subtract the 32   |
+ |   bit result to L_var3 with saturation. Round the LS 16 bits of the res-  |
+ |   ult into the MS 16 bits with saturation and shift the result right by   |
+ |   16. Return a 16 bit result.                                             |
+ |            msu_r(L_var3,var1,var2) = round(L_msu(L_var3,var1,var2))       |
+ |                                                                           |
+ |   Complexity weight : 2                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    L_var3   32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
+ |                                                                           |
+ |    var1                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |    var2                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    var_out                                                                |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0x0000 8000 <= L_var_out <= 0x0000 7fff.              |
+ |___________________________________________________________________________|
+*/
+#if (!MSU_R_IS_INLINE)
+Word16 msu_r (Word32 L_var3, Word16 var1, Word16 var2)
+{
+    Word16 var_out;
+
+    L_var3 = L_msu (L_var3, var1, var2);
+    L_var3 = L_add (L_var3, (Word32) 0x00008000L);
+    var_out = extract_h (L_var3);
+
+    return (var_out);
+}
+#endif
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : L_deposit_h                                             |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Deposit the 16 bit var1 into the 16 MS bits of the 32 bit output. The   |
+ |   16 LS bits of the output are zeroed.                                    |
+ |                                                                           |
+ |   Complexity weight : 2                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    var1                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    L_var_out                                                              |
+ |             32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= var_out <= 0x7fff 0000.                |
+ |___________________________________________________________________________|
+*/
+//Word32 L_deposit_h (Word16 var1)
+//{
+//    Word32 L_var_out;
+//
+//    L_var_out = (Word32) var1 << 16;
+//
+//    return (L_var_out);
+//}
+
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : L_deposit_l                                             |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Deposit the 16 bit var1 into the 16 LS bits of the 32 bit output. The   |
+ |   16 MS bits of the output are sign extended.                             |
+ |                                                                           |
+ |   Complexity weight : 2                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    var1                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    L_var_out                                                              |
+ |             32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0xFFFF 8000 <= var_out <= 0x0000 7fff.                |
+ |___________________________________________________________________________|
+*/
+//Word32 L_deposit_l (Word16 var1)
+//{
+//    Word32 L_var_out;
+//
+//    L_var_out = (Word32) var1;
+//
+//    return (L_var_out);
+//}
+
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : L_shr_r                                                 |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Same as L_shr(L_var1,var2) but with rounding. Saturate the result in    |
+ |   case of underflows or overflows :                                       |
+ |    - If var2 is greater than zero :                                       |
+ |          if (L_sub(L_shl(L_shr(L_var1,var2),1),L_shr(L_var1,sub(var2,1))))|
+ |          is equal to zero                                                 |
+ |                     then                                                  |
+ |                     L_shr_r(L_var1,var2) = L_shr(L_var1,var2)             |
+ |                     else                                                  |
+ |                     L_shr_r(L_var1,var2) = L_add(L_shr(L_var1,var2),1)    |
+ |    - If var2 is less than or equal to zero :                              |
+ |                     L_shr_r(L_var1,var2) = L_shr(L_var1,var2).            |
+ |                                                                           |
+ |   Complexity weight : 3                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    L_var1                                                                 |
+ |             32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= var1 <= 0x7fff ffff.                   |
+ |                                                                           |
+ |    var2                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    L_var_out                                                              |
+ |             32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= var_out <= 0x7fff ffff.                |
+ |___________________________________________________________________________|
+*/
+#if (!L_SHR_R_IS_INLINE)
+Word32 L_shr_r (Word32 L_var1, Word16 var2)
+{
+    Word32 L_var_out;
+
+    if (var2 > 31)
+    {
+        L_var_out = 0;
+    }
+    else
+    {
+        L_var_out = L_shr (L_var1, var2);
+
+        if (var2 > 0)
+        {
+            if ((L_var1 & ((Word32) 1 << (var2 - 1))) != 0)
+            {
+                L_var_out++;
+            }
+        }
+    }
+
+    return (L_var_out);
+}
+#endif
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : L_abs                                                   |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |    Absolute value of L_var1; Saturate in case where the input is          |
+ |                                                               -214783648  |
+ |                                                                           |
+ |   Complexity weight : 3                                                   |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    L_var1                                                                 |
+ |             32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= var1 <= 0x7fff ffff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    L_var_out                                                              |
+ |             32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x0000 0000 <= var_out <= 0x7fff ffff.                |
+ |___________________________________________________________________________|
+*/
+//Word32 L_abs (Word32 L_var1)
+//{
+//    Word32 L_var_out;
+//
+//    if (L_var1 == MIN_32)
+//    {
+//        L_var_out = MAX_32;
+//    }
+//    else
+//    {
+//        if (L_var1 < 0)
+//        {
+//            L_var_out = -L_var1;
+//        }
+//        else
+//        {
+//            L_var_out = L_var1;
+//        }
+//    }
+//
+//    return (L_var_out);
+//}
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : norm_s                                                  |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Produces the number of left shift needed to normalize the 16 bit varia- |
+ |   ble var1 for positive values on the interval with minimum of 16384 and  |
+ |   maximum of 32767, and for negative values on the interval with minimum  |
+ |   of -32768 and maximum of -16384; in order to normalize the result, the  |
+ |   following operation must be done :                                      |
+ |                    norm_var1 = shl(var1,norm_s(var1)).                    |
+ |                                                                           |
+ |   Complexity weight : 15                                                  |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    var1                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    var_out                                                                |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0x0000 0000 <= var_out <= 0x0000 000f.                |
+ |___________________________________________________________________________|
+*/
+
+#if (!NORM_S_IS_INLINE)
+Word16 norm_s (Word16 var1)
+{
+    Word16 var_out;
+
+    if (var1 == 0)
+    {
+        var_out = 0;
+    }
+    else
+    {
+        if (var1 == -1)
+        {
+            var_out = 15;
+        }
+        else
+        {
+            if (var1 < 0)
+            {
+                var1 = (Word16)~var1;
+            }
+            for (var_out = 0; var1 < 0x4000; var_out++)
+            {
+                var1 <<= 1;
+            }
+        }
+    }
+
+    return (var_out);
+}
+#endif
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : div_s                                                   |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Produces a result which is the fractional integer division of var1  by  |
+ |   var2; var1 and var2 must be positive and var2 must be greater or equal  |
+ |   to var1; the result is positive (leading bit equal to 0) and truncated  |
+ |   to 16 bits.                                                             |
+ |   If var1 = var2 then div(var1,var2) = 32767.                             |
+ |                                                                           |
+ |   Complexity weight : 18                                                  |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    var1                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0x0000 0000 <= var1 <= var2 and var2 != 0.            |
+ |                                                                           |
+ |    var2                                                                   |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : var1 <= var2 <= 0x0000 7fff and var2 != 0.            |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    var_out                                                                |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0x0000 0000 <= var_out <= 0x0000 7fff.                |
+ |             It's a Q15 value (point between b15 and b14).                 |
+ |___________________________________________________________________________|
+*/
+
+#if (!DIV_S_IS_INLINE)
+Word16 div_s (Word16 var1, Word16 var2)
+{
+    Word16 var_out = 0;
+    Word16 iteration;
+    Word32 L_num;
+    Word32 L_denom;
+
+    if (var1 == 0)
+    {
+        var_out = 0;
+    }
+    else
+    {
+        if (var1 == var2)
+        {
+            var_out = MAX_16;
+        }
+        else
+        {
+            L_num = L_deposit_l (var1);
+            L_denom = L_deposit_l (var2);
+
+            for (iteration = 0; iteration < 15; iteration++)
+            {
+                var_out <<= 1;
+                L_num <<= 1;
+
+                if (L_num >= L_denom)
+                {
+                    L_num = L_sub(L_num, L_denom);
+                    var_out = add (var_out, 1);
+                }
+            }
+        }
+    }
+
+    return (var_out);
+}
+#endif
+
+/*___________________________________________________________________________
+ |                                                                           |
+ |   Function Name : norm_l                                                  |
+ |                                                                           |
+ |   Purpose :                                                               |
+ |                                                                           |
+ |   Produces the number of left shifts needed to normalize the 32 bit varia-|
+ |   ble L_var1 for positive values on the interval with minimum of          |
+ |   1073741824 and maximum of 2147483647, and for negative values on the in-|
+ |   terval with minimum of -2147483648 and maximum of -1073741824; in order |
+ |   to normalize the result, the following operation must be done :         |
+ |                   norm_L_var1 = L_shl(L_var1,norm_l(L_var1)).             |
+ |                                                                           |
+ |   Complexity weight : 30                                                  |
+ |                                                                           |
+ |   Inputs :                                                                |
+ |                                                                           |
+ |    L_var1                                                                 |
+ |             32 bit long signed integer (Word32) whose value falls in the  |
+ |             range : 0x8000 0000 <= var1 <= 0x7fff ffff.                   |
+ |                                                                           |
+ |   Outputs :                                                               |
+ |                                                                           |
+ |    none                                                                   |
+ |                                                                           |
+ |   Return Value :                                                          |
+ |                                                                           |
+ |    var_out                                                                |
+ |             16 bit short signed integer (Word16) whose value falls in the |
+ |             range : 0x0000 0000 <= var_out <= 0x0000 001f.                |
+ |___________________________________________________________________________|
+*/
+
+#if (!NORM_L_IS_INLINE)
+Word16 norm_l (Word32 L_var1)
+{
+    Word16 var_out;
+
+    if (L_var1 == 0)
+    {
+        var_out = 0;
+    }
+    else
+    {
+        if (L_var1 == (Word32) 0xffffffffL)
+        {
+            var_out = 31;
+        }
+        else
+        {
+            if (L_var1 < 0)
+            {
+                L_var1 = ~L_var1;
+            }
+            for (var_out = 0; L_var1 < (Word32) 0x40000000L; var_out++)
+            {
+                L_var1 <<= 1;
+            }
+        }
+    }
+
+    return (var_out);
+}
+#endif
 
diff --git a/media/libstagefright/codecs/aacenc/basic_op/oper_32b.c b/media/libstagefright/codecs/aacenc/basic_op/oper_32b.c
index 906a9df..e48af9d 100644
--- a/media/libstagefright/codecs/aacenc/basic_op/oper_32b.c
+++ b/media/libstagefright/codecs/aacenc/basic_op/oper_32b.c
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		oper_32b.c

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		oper_32b.c
+
 	Content:	  This file contains operations in double precision.
- 

+
 *******************************************************************************/
 
 #include "typedef.h"
@@ -198,164 +198,164 @@
 
     return (L_32);
 }
-

-/*!

- 

-  \brief  calculates the log dualis times 4 of argument 

-          iLog4(x) = (Word32)(4 * log(value)/log(2.0))

-

-  \return ilog4 value

- 

-*/

-Word16 iLog4(Word32 value)

-{

-  Word16 iLog4;

-

-  if(value != 0){

-    Word32 tmp;

-    Word16 tmp16;

-    iLog4 = norm_l(value);

-    tmp = (value << iLog4);

-    tmp16 = round16(tmp);

-    tmp = L_mult(tmp16, tmp16);

-    tmp16 = round16(tmp);

-    tmp = L_mult(tmp16, tmp16);

-    tmp16 = round16(tmp);

-

-    iLog4 = (-(iLog4 << 2) - norm_s(tmp16)) - 1;

-  }

-  else {

-    iLog4 = -128; /* -(INT_BITS*4); */                                          

-  }

-

-  return iLog4;

-}

-

-#define step(shift) \

-    if ((0x40000000l >> shift) + root <= value)       \

-    {                                                 \

-        value -= (0x40000000l >> shift) + root;       \

-        root = (root >> 1) | (0x40000000l >> shift);  \

-    } else {                                          \

-        root = root >> 1;                             \

-    }

-

-Word32 rsqrt(Word32 value,     /*!< Operand to square root (0.0 ... 1) */

-             Word32 accuracy)  /*!< Number of valid bits that will be calculated */

-{

-    Word32 root = 0;

-	Word32 scale;

-

-	if(value < 0)

-		return 0;

-

-	scale = norm_l(value);

-	if(scale & 1) scale--;

-

-	value <<= scale;

-

-	step( 0); step( 2); step( 4); step( 6);

-    step( 8); step(10); step(12); step(14);

-    step(16); step(18); step(20); step(22);

-    step(24); step(26); step(28); step(30);

-

-    scale >>= 1;

-	if (root < value)

-        ++root;

-

-	root >>= scale;

-    return root* 46334;

-}

-

-static const Word32 pow2Table[POW2_TABLE_SIZE] = {

-0x7fffffff, 0x7fa765ad, 0x7f4f08ae, 0x7ef6e8da, 

-0x7e9f0606, 0x7e476009, 0x7deff6b6, 0x7d98c9e6, 

-0x7d41d96e, 0x7ceb2523, 0x7c94acde, 0x7c3e7073, 

-0x7be86fb9, 0x7b92aa88, 0x7b3d20b6, 0x7ae7d21a, 

-0x7a92be8b, 0x7a3de5df, 0x79e947ef, 0x7994e492, 

-0x7940bb9e, 0x78ecccec, 0x78991854, 0x78459dac, 

-0x77f25cce, 0x779f5591, 0x774c87cc, 0x76f9f359, 

-0x76a7980f, 0x765575c8, 0x76038c5b, 0x75b1dba2, 

-0x75606374, 0x750f23ab, 0x74be1c20, 0x746d4cac, 

-0x741cb528, 0x73cc556d, 0x737c2d55, 0x732c3cba, 

-0x72dc8374, 0x728d015d, 0x723db650, 0x71eea226, 

-0x719fc4b9, 0x71511de4, 0x7102ad80, 0x70b47368, 

-0x70666f76, 0x7018a185, 0x6fcb096f, 0x6f7da710, 

-0x6f307a41, 0x6ee382de, 0x6e96c0c3, 0x6e4a33c9, 

-0x6dfddbcc, 0x6db1b8a8, 0x6d65ca38, 0x6d1a1057, 

-0x6cce8ae1, 0x6c8339b2, 0x6c381ca6, 0x6bed3398, 

-0x6ba27e66, 0x6b57fce9, 0x6b0daeff, 0x6ac39485, 

-0x6a79ad56, 0x6a2ff94f, 0x69e6784d, 0x699d2a2c, 

-0x69540ec9, 0x690b2601, 0x68c26fb1, 0x6879ebb6, 

-0x683199ed, 0x67e97a34, 0x67a18c68, 0x6759d065, 

-0x6712460b, 0x66caed35, 0x6683c5c3, 0x663ccf92, 

-0x65f60a80, 0x65af766a, 0x6569132f, 0x6522e0ad, 

-0x64dcdec3, 0x64970d4f, 0x64516c2e, 0x640bfb41, 

-0x63c6ba64, 0x6381a978, 0x633cc85b, 0x62f816eb, 

-0x62b39509, 0x626f4292, 0x622b1f66, 0x61e72b65, 

-0x61a3666d, 0x615fd05f, 0x611c6919, 0x60d9307b, 

-0x60962665, 0x60534ab7, 0x60109d51, 0x5fce1e12, 

-0x5f8bccdb, 0x5f49a98c, 0x5f07b405, 0x5ec5ec26, 

-0x5e8451d0, 0x5e42e4e3, 0x5e01a540, 0x5dc092c7, 

-0x5d7fad59, 0x5d3ef4d7, 0x5cfe6923, 0x5cbe0a1c, 

-0x5c7dd7a4, 0x5c3dd19c, 0x5bfdf7e5, 0x5bbe4a61, 

-0x5b7ec8f2, 0x5b3f7377, 0x5b0049d4, 0x5ac14bea, 

-0x5a82799a, 0x5a43d2c6, 0x5a055751, 0x59c7071c, 

-0x5988e209, 0x594ae7fb, 0x590d18d3, 0x58cf7474, 

-0x5891fac1, 0x5854ab9b, 0x581786e6, 0x57da8c83, 

-0x579dbc57, 0x57611642, 0x57249a29, 0x56e847ef, 

-0x56ac1f75, 0x567020a0, 0x56344b52, 0x55f89f70, 

-0x55bd1cdb, 0x5581c378, 0x55469329, 0x550b8bd4, 

-0x54d0ad5b, 0x5495f7a1, 0x545b6a8b, 0x542105fd, 

-0x53e6c9db, 0x53acb607, 0x5372ca68, 0x533906e0, 

-0x52ff6b55, 0x52c5f7aa, 0x528cabc3, 0x52538786, 

-0x521a8ad7, 0x51e1b59a, 0x51a907b4, 0x5170810b, 

-0x51382182, 0x50ffe8fe, 0x50c7d765, 0x508fec9c, 

-0x50582888, 0x50208b0e, 0x4fe91413, 0x4fb1c37c, 

-0x4f7a9930, 0x4f439514, 0x4f0cb70c, 0x4ed5ff00, 

-0x4e9f6cd4, 0x4e69006e, 0x4e32b9b4, 0x4dfc988c, 

-0x4dc69cdd, 0x4d90c68b, 0x4d5b157e, 0x4d25899c, 

-0x4cf022ca, 0x4cbae0ef, 0x4c85c3f1, 0x4c50cbb8, 

-0x4c1bf829, 0x4be7492b, 0x4bb2bea5, 0x4b7e587d, 

-0x4b4a169c, 0x4b15f8e6, 0x4ae1ff43, 0x4aae299b, 

-0x4a7a77d5, 0x4a46e9d6, 0x4a137f88, 0x49e038d0, 

-0x49ad1598, 0x497a15c4, 0x4947393f, 0x49147fee, 

-0x48e1e9ba, 0x48af768a, 0x487d2646, 0x484af8d6, 

-0x4818ee22, 0x47e70611, 0x47b5408c, 0x47839d7b, 

-0x47521cc6, 0x4720be55, 0x46ef8210, 0x46be67e0, 

-0x468d6fae, 0x465c9961, 0x462be4e2, 0x45fb521a, 

-0x45cae0f2, 0x459a9152, 0x456a6323, 0x453a564d, 

-0x450a6abb, 0x44daa054, 0x44aaf702, 0x447b6ead, 

-0x444c0740, 0x441cc0a3, 0x43ed9ac0, 0x43be9580, 

-0x438fb0cb, 0x4360ec8d, 0x433248ae, 0x4303c517, 

-0x42d561b4, 0x42a71e6c, 0x4278fb2b, 0x424af7da, 

-0x421d1462, 0x41ef50ae, 0x41c1aca8, 0x41942839, 

-0x4166c34c, 0x41397dcc, 0x410c57a2, 0x40df50b8, 

-0x40b268fa, 0x4085a051, 0x4058f6a8, 0x402c6be9 

-};

-

-/*!

- 

-  \brief calculates 2 ^ (x/y) for x<=0, y > 0, x <= 32768 * y 

-  

-  avoids integer division

-  

-  \return 

-*/

-Word32 pow2_xy(Word32 x, Word32 y)

-{

-  Word32 iPart;

-  Word32 fPart;

-  Word32 res;

-  Word32 tmp, tmp2;

-  Word32 shift, shift2;

-

-  tmp2 = -x;

-  iPart = tmp2 / y;

-  fPart = tmp2 - iPart*y;

-  iPart = min(iPart,INT_BITS-1);

-

-  res = pow2Table[(POW2_TABLE_SIZE*fPart)/y] >> iPart; 

- 

-  return(res);

+
+/*!
+
+  \brief  calculates the log dualis times 4 of argument
+          iLog4(x) = (Word32)(4 * log(value)/log(2.0))
+
+  \return ilog4 value
+
+*/
+Word16 iLog4(Word32 value)
+{
+  Word16 iLog4;
+
+  if(value != 0){
+    Word32 tmp;
+    Word16 tmp16;
+    iLog4 = norm_l(value);
+    tmp = (value << iLog4);
+    tmp16 = round16(tmp);
+    tmp = L_mult(tmp16, tmp16);
+    tmp16 = round16(tmp);
+    tmp = L_mult(tmp16, tmp16);
+    tmp16 = round16(tmp);
+
+    iLog4 = (-(iLog4 << 2) - norm_s(tmp16)) - 1;
+  }
+  else {
+    iLog4 = -128; /* -(INT_BITS*4); */
+  }
+
+  return iLog4;
+}
+
+#define step(shift) \
+    if ((0x40000000l >> shift) + root <= value)       \
+    {                                                 \
+        value -= (0x40000000l >> shift) + root;       \
+        root = (root >> 1) | (0x40000000l >> shift);  \
+    } else {                                          \
+        root = root >> 1;                             \
+    }
+
+Word32 rsqrt(Word32 value,     /*!< Operand to square root (0.0 ... 1) */
+             Word32 accuracy)  /*!< Number of valid bits that will be calculated */
+{
+    Word32 root = 0;
+	Word32 scale;
+
+	if(value < 0)
+		return 0;
+
+	scale = norm_l(value);
+	if(scale & 1) scale--;
+
+	value <<= scale;
+
+	step( 0); step( 2); step( 4); step( 6);
+    step( 8); step(10); step(12); step(14);
+    step(16); step(18); step(20); step(22);
+    step(24); step(26); step(28); step(30);
+
+    scale >>= 1;
+	if (root < value)
+        ++root;
+
+	root >>= scale;
+    return root* 46334;
+}
+
+static const Word32 pow2Table[POW2_TABLE_SIZE] = {
+0x7fffffff, 0x7fa765ad, 0x7f4f08ae, 0x7ef6e8da,
+0x7e9f0606, 0x7e476009, 0x7deff6b6, 0x7d98c9e6,
+0x7d41d96e, 0x7ceb2523, 0x7c94acde, 0x7c3e7073,
+0x7be86fb9, 0x7b92aa88, 0x7b3d20b6, 0x7ae7d21a,
+0x7a92be8b, 0x7a3de5df, 0x79e947ef, 0x7994e492,
+0x7940bb9e, 0x78ecccec, 0x78991854, 0x78459dac,
+0x77f25cce, 0x779f5591, 0x774c87cc, 0x76f9f359,
+0x76a7980f, 0x765575c8, 0x76038c5b, 0x75b1dba2,
+0x75606374, 0x750f23ab, 0x74be1c20, 0x746d4cac,
+0x741cb528, 0x73cc556d, 0x737c2d55, 0x732c3cba,
+0x72dc8374, 0x728d015d, 0x723db650, 0x71eea226,
+0x719fc4b9, 0x71511de4, 0x7102ad80, 0x70b47368,
+0x70666f76, 0x7018a185, 0x6fcb096f, 0x6f7da710,
+0x6f307a41, 0x6ee382de, 0x6e96c0c3, 0x6e4a33c9,
+0x6dfddbcc, 0x6db1b8a8, 0x6d65ca38, 0x6d1a1057,
+0x6cce8ae1, 0x6c8339b2, 0x6c381ca6, 0x6bed3398,
+0x6ba27e66, 0x6b57fce9, 0x6b0daeff, 0x6ac39485,
+0x6a79ad56, 0x6a2ff94f, 0x69e6784d, 0x699d2a2c,
+0x69540ec9, 0x690b2601, 0x68c26fb1, 0x6879ebb6,
+0x683199ed, 0x67e97a34, 0x67a18c68, 0x6759d065,
+0x6712460b, 0x66caed35, 0x6683c5c3, 0x663ccf92,
+0x65f60a80, 0x65af766a, 0x6569132f, 0x6522e0ad,
+0x64dcdec3, 0x64970d4f, 0x64516c2e, 0x640bfb41,
+0x63c6ba64, 0x6381a978, 0x633cc85b, 0x62f816eb,
+0x62b39509, 0x626f4292, 0x622b1f66, 0x61e72b65,
+0x61a3666d, 0x615fd05f, 0x611c6919, 0x60d9307b,
+0x60962665, 0x60534ab7, 0x60109d51, 0x5fce1e12,
+0x5f8bccdb, 0x5f49a98c, 0x5f07b405, 0x5ec5ec26,
+0x5e8451d0, 0x5e42e4e3, 0x5e01a540, 0x5dc092c7,
+0x5d7fad59, 0x5d3ef4d7, 0x5cfe6923, 0x5cbe0a1c,
+0x5c7dd7a4, 0x5c3dd19c, 0x5bfdf7e5, 0x5bbe4a61,
+0x5b7ec8f2, 0x5b3f7377, 0x5b0049d4, 0x5ac14bea,
+0x5a82799a, 0x5a43d2c6, 0x5a055751, 0x59c7071c,
+0x5988e209, 0x594ae7fb, 0x590d18d3, 0x58cf7474,
+0x5891fac1, 0x5854ab9b, 0x581786e6, 0x57da8c83,
+0x579dbc57, 0x57611642, 0x57249a29, 0x56e847ef,
+0x56ac1f75, 0x567020a0, 0x56344b52, 0x55f89f70,
+0x55bd1cdb, 0x5581c378, 0x55469329, 0x550b8bd4,
+0x54d0ad5b, 0x5495f7a1, 0x545b6a8b, 0x542105fd,
+0x53e6c9db, 0x53acb607, 0x5372ca68, 0x533906e0,
+0x52ff6b55, 0x52c5f7aa, 0x528cabc3, 0x52538786,
+0x521a8ad7, 0x51e1b59a, 0x51a907b4, 0x5170810b,
+0x51382182, 0x50ffe8fe, 0x50c7d765, 0x508fec9c,
+0x50582888, 0x50208b0e, 0x4fe91413, 0x4fb1c37c,
+0x4f7a9930, 0x4f439514, 0x4f0cb70c, 0x4ed5ff00,
+0x4e9f6cd4, 0x4e69006e, 0x4e32b9b4, 0x4dfc988c,
+0x4dc69cdd, 0x4d90c68b, 0x4d5b157e, 0x4d25899c,
+0x4cf022ca, 0x4cbae0ef, 0x4c85c3f1, 0x4c50cbb8,
+0x4c1bf829, 0x4be7492b, 0x4bb2bea5, 0x4b7e587d,
+0x4b4a169c, 0x4b15f8e6, 0x4ae1ff43, 0x4aae299b,
+0x4a7a77d5, 0x4a46e9d6, 0x4a137f88, 0x49e038d0,
+0x49ad1598, 0x497a15c4, 0x4947393f, 0x49147fee,
+0x48e1e9ba, 0x48af768a, 0x487d2646, 0x484af8d6,
+0x4818ee22, 0x47e70611, 0x47b5408c, 0x47839d7b,
+0x47521cc6, 0x4720be55, 0x46ef8210, 0x46be67e0,
+0x468d6fae, 0x465c9961, 0x462be4e2, 0x45fb521a,
+0x45cae0f2, 0x459a9152, 0x456a6323, 0x453a564d,
+0x450a6abb, 0x44daa054, 0x44aaf702, 0x447b6ead,
+0x444c0740, 0x441cc0a3, 0x43ed9ac0, 0x43be9580,
+0x438fb0cb, 0x4360ec8d, 0x433248ae, 0x4303c517,
+0x42d561b4, 0x42a71e6c, 0x4278fb2b, 0x424af7da,
+0x421d1462, 0x41ef50ae, 0x41c1aca8, 0x41942839,
+0x4166c34c, 0x41397dcc, 0x410c57a2, 0x40df50b8,
+0x40b268fa, 0x4085a051, 0x4058f6a8, 0x402c6be9
+};
+
+/*!
+
+  \brief calculates 2 ^ (x/y) for x<=0, y > 0, x <= 32768 * y
+
+  avoids integer division
+
+  \return
+*/
+Word32 pow2_xy(Word32 x, Word32 y)
+{
+  Word32 iPart;
+  Word32 fPart;
+  Word32 res;
+  Word32 tmp, tmp2;
+  Word32 shift, shift2;
+
+  tmp2 = -x;
+  iPart = tmp2 / y;
+  fPart = tmp2 - iPart*y;
+  iPart = min(iPart,INT_BITS-1);
+
+  res = pow2Table[(POW2_TABLE_SIZE*fPart)/y] >> iPart;
+
+  return(res);
 }
\ No newline at end of file
diff --git a/media/libstagefright/codecs/aacenc/basic_op/oper_32b.h b/media/libstagefright/codecs/aacenc/basic_op/oper_32b.h
index 4119bc3..9ebd1c2 100644
--- a/media/libstagefright/codecs/aacenc/basic_op/oper_32b.h
+++ b/media/libstagefright/codecs/aacenc/basic_op/oper_32b.h
@@ -1,86 +1,86 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		oper_32b.h

-

-	Content:	Double precision operations

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		oper_32b.h
+
+	Content:	Double precision operations
+
 *******************************************************************************/
 
 #ifndef __OPER_32b_H
 #define __OPER_32b_H
-

-#include "typedef.h"

+
+#include "typedef.h"
 
 #ifdef __cplusplus
 extern "C" {
 #endif
-

-#define POW2_TABLE_BITS 8

-#define POW2_TABLE_SIZE (1<<POW2_TABLE_BITS)

+
+#define POW2_TABLE_BITS 8
+#define POW2_TABLE_SIZE (1<<POW2_TABLE_BITS)
 
 void L_Extract (Word32 L_32, Word16 *hi, Word16 *lo);
 Word32 L_Comp (Word16 hi, Word16 lo);
 Word32 Mpy_32 (Word16 hi1, Word16 lo1, Word16 hi2, Word16 lo2);
 Word32 Mpy_32_16 (Word16 hi, Word16 lo, Word16 n);
 Word32 Div_32 (Word32 L_num, Word32 denom);
-Word16 iLog4(Word32 value);

-Word32 rsqrt(Word32 value,  Word32 accuracy);

-Word32 pow2_xy(Word32 x, Word32 y);

-

-__inline Word32 L_mpy_ls(Word32 L_var2, Word16 var1)

-{

-    unsigned short swLow1;

-    Word16 swHigh1;

-    Word32 l_var_out;

-

-    swLow1 = (unsigned short)(L_var2);

-    swHigh1 = (Word16)(L_var2 >> 16);

-

-    l_var_out = (long)swLow1 * (long)var1 >> 15;

-    

-    l_var_out += swHigh1 * var1 << 1;

-    

-    return(l_var_out);

-}

-

-__inline Word32 L_mpy_wx(Word32 L_var2, Word16 var1)

-{

-#if ARMV5TE_L_MPY_LS

-	Word32 result; 

-	asm volatile( 

-		"SMULWB  %[result], %[L_var2], %[var1] \n" 

-		:[result]"+r"(result)

-		:[L_var2]"r"(L_var2), [var1]"r"(var1)

-		); 

-	return result;

-#else

-    unsigned short swLow1;

-    Word16 swHigh1;

-    Word32 l_var_out;

-

-    swLow1 = (unsigned short)(L_var2);

-    swHigh1 = (Word16)(L_var2 >> 16);

-

-    l_var_out = (long)swLow1 * (long)var1 >> 16;    

-    l_var_out += swHigh1 * var1;

-    

-    return(l_var_out);

-#endif

-}

+Word16 iLog4(Word32 value);
+Word32 rsqrt(Word32 value,  Word32 accuracy);
+Word32 pow2_xy(Word32 x, Word32 y);
+
+__inline Word32 L_mpy_ls(Word32 L_var2, Word16 var1)
+{
+    unsigned short swLow1;
+    Word16 swHigh1;
+    Word32 l_var_out;
+
+    swLow1 = (unsigned short)(L_var2);
+    swHigh1 = (Word16)(L_var2 >> 16);
+
+    l_var_out = (long)swLow1 * (long)var1 >> 15;
+
+    l_var_out += swHigh1 * var1 << 1;
+
+    return(l_var_out);
+}
+
+__inline Word32 L_mpy_wx(Word32 L_var2, Word16 var1)
+{
+#if ARMV5TE_L_MPY_LS
+	Word32 result;
+	asm volatile(
+		"SMULWB  %[result], %[L_var2], %[var1] \n"
+		:[result]"+r"(result)
+		:[L_var2]"r"(L_var2), [var1]"r"(var1)
+		);
+	return result;
+#else
+    unsigned short swLow1;
+    Word16 swHigh1;
+    Word32 l_var_out;
+
+    swLow1 = (unsigned short)(L_var2);
+    swHigh1 = (Word16)(L_var2 >> 16);
+
+    l_var_out = (long)swLow1 * (long)var1 >> 16;
+    l_var_out += swHigh1 * var1;
+
+    return(l_var_out);
+#endif
+}
 
 #ifdef __cplusplus
 }
diff --git a/media/libstagefright/codecs/aacenc/basic_op/typedef.h b/media/libstagefright/codecs/aacenc/basic_op/typedef.h
index d3a626a..b1f8225 100644
--- a/media/libstagefright/codecs/aacenc/basic_op/typedef.h
+++ b/media/libstagefright/codecs/aacenc/basic_op/typedef.h
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		typedef.h

-

-	Content:	type defined for defferent paltform

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		typedef.h
+
+	Content:	type defined for defferent paltform
+
 *******************************************************************************/
 
 #ifndef typedef_h
@@ -30,7 +30,7 @@
 /*
  * this is the original code from the ETSI file typedef.h
  */
-   
+
 #if defined(__BORLANDC__) || defined(__WATCOMC__) || defined(_MSC_VER) || defined(__ZTC__)
 typedef signed char Word8;
 typedef short Word16;
@@ -54,7 +54,7 @@
 
 /*
  * use (improved) type definition file typdefs.h and add a "Flag" type
- */

+ */
 #include "typedefs.h"
 typedef int Flag;
 
diff --git a/media/libstagefright/codecs/aacenc/basic_op/typedefs.h b/media/libstagefright/codecs/aacenc/basic_op/typedefs.h
index 7d16fca..c924e2c 100644
--- a/media/libstagefright/codecs/aacenc/basic_op/typedefs.h
+++ b/media/libstagefright/codecs/aacenc/basic_op/typedefs.h
@@ -1,61 +1,61 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		typedefs.h

-

-	Content:	type defined or const defined

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		typedefs.h
+
+	Content:	type defined or const defined
+
 *******************************************************************************/
 
 #ifndef typedefs_h
 #define typedefs_h "$Id $"
 
-#ifndef CHAR_BIT

-#define CHAR_BIT      8         /* number of bits in a char */

-#endif

-

-#ifndef VOAAC_SHRT_MAX

-#define VOAAC_SHRT_MAX    (32767)        /* maximum (signed) short value */

-#endif

+#ifndef CHAR_BIT
+#define CHAR_BIT      8         /* number of bits in a char */
+#endif
 
-#ifndef VOAAC_SHRT_MIN

-#define VOAAC_SHRT_MIN    (-32768)        /* minimum (signed) short value */

-#endif

+#ifndef VOAAC_SHRT_MAX
+#define VOAAC_SHRT_MAX    (32767)        /* maximum (signed) short value */
+#endif
 
-/* Define NULL pointer value */

-#ifndef NULL

-#ifdef __cplusplus

-#define NULL    0

-#else

-#define NULL    ((void *)0)

-#endif

+#ifndef VOAAC_SHRT_MIN
+#define VOAAC_SHRT_MIN    (-32768)        /* minimum (signed) short value */
+#endif
+
+/* Define NULL pointer value */
+#ifndef NULL
+#ifdef __cplusplus
+#define NULL    0
+#else
+#define NULL    ((void *)0)
+#endif
 #endif
 
 #ifndef assert
 #define assert(_Expression)     ((void)0)
 #endif
-

-#ifdef LINUX

-#define __inline static __inline__

-#endif

+
+#ifdef LINUX
+#define __inline static __inline__
+#endif
 
 #define INT_BITS   32
 /*
 ********************************************************************************
-*                         DEFINITION OF CONSTANTS 
+*                         DEFINITION OF CONSTANTS
 ********************************************************************************
 */
 /*
@@ -80,100 +80,100 @@
 typedef long Word32;
 typedef unsigned long UWord32;
 
-

-

+
+
 #ifdef LINUX
 typedef long long Word64;
 typedef unsigned long long UWord64;
 #else
-typedef __int64 Word64;

+typedef __int64 Word64;
 typedef unsigned __int64 UWord64;
 #endif
 
-#ifndef min

-#define min(a,b) ( a < b ? a : b)

-#endif

-

-#ifndef max

-#define max(a,b) ( a > b ? a : b)

-#endif

-

-#ifdef ARM_INASM

-#ifdef ARMV5_INASM

-#define ARMV5E_INASM	1

-#endif

-#define ARMV4_INASM		1

-#endif

-
-#if ARMV4_INASM

-	#define ARMV5TE_SAT           1

-    #define ARMV5TE_ADD           1

-    #define ARMV5TE_SUB           1

-	#define ARMV5TE_SHL           1

-    #define ARMV5TE_SHR           1

-	#define ARMV5TE_L_SHL         1

-    #define ARMV5TE_L_SHR         1

-#endif//ARMV4

-#if ARMV5E_INASM

-    #define ARMV5TE_L_ADD         1

-    #define ARMV5TE_L_SUB         1

-    #define ARMV5TE_L_MULT        1

-    #define ARMV5TE_L_MAC         1

-    #define ARMV5TE_L_MSU         1

-   

-    

-    #define ARMV5TE_DIV_S         1

-    #define ARMV5TE_ROUND         1

-    #define ARMV5TE_MULT          1

-    

-    #define ARMV5TE_NORM_S        1

-    #define ARMV5TE_NORM_L        1

-	#define ARMV5TE_L_MPY_LS	  1

+#ifndef min
+#define min(a,b) ( a < b ? a : b)
 #endif
-

-//basic operation functions optimization flags

-#define SATRUATE_IS_INLINE              1   //define saturate as inline function

-#define SHL_IS_INLINE                   1  //define shl as inline function

-#define SHR_IS_INLINE                   1   //define shr as inline function

-#define L_MULT_IS_INLINE                1   //define L_mult as inline function

-#define L_MSU_IS_INLINE                 1   //define L_msu as inline function

-#define L_SUB_IS_INLINE                 1   //define L_sub as inline function

-#define L_SHL_IS_INLINE                 1   //define L_shl as inline function

-#define L_SHR_IS_INLINE                 1   //define L_shr as inline function

-#define ADD_IS_INLINE                   1   //define add as inline function //add, inline is the best

-#define SUB_IS_INLINE                   1   //define sub as inline function //sub, inline is the best

-#define DIV_S_IS_INLINE                 1   //define div_s as inline function

-#define MULT_IS_INLINE                  1   //define mult as inline function

-#define NORM_S_IS_INLINE                1   //define norm_s as inline function

-#define NORM_L_IS_INLINE                1   //define norm_l as inline function

-#define ROUND_IS_INLINE                 1   //define round as inline function

-#define L_MAC_IS_INLINE                 1   //define L_mac as inline function

-#define L_ADD_IS_INLINE                 1   //define L_add as inline function

-#define EXTRACT_H_IS_INLINE             1   //define extract_h as inline function 

-#define EXTRACT_L_IS_INLINE             1   //define extract_l as inline function        //???

-#define MULT_R_IS_INLINE                1   //define mult_r as inline function

-#define SHR_R_IS_INLINE                 1   //define shr_r as inline function

-#define MAC_R_IS_INLINE                 1   //define mac_r as inline function

-#define MSU_R_IS_INLINE                 1   //define msu_r as inline function

-#define L_SHR_R_IS_INLINE               1   //define L_shr_r as inline function

-

-#define PREFIX				voAACEnc

-#define LINK0(x, y, z)		LINK1(x,y,z)

-#define LINK1(x,y,z)		x##y##z

-#define ADD_PREFIX(func)	LINK0(PREFIX, _, func)

-

-#define  L_Extract		ADD_PREFIX(L_Extract)

-#define  L_Comp			ADD_PREFIX(L_Comp)

-#define  Mpy_32			ADD_PREFIX(Mpy_32)

-#define  Mpy_32_16		ADD_PREFIX(Mpy_32_16)

-#define  Div_32			ADD_PREFIX(Div_32)

-#define  iLog4			ADD_PREFIX(iLog4)

-#define  rsqrt			ADD_PREFIX(rsqrt)

-#define  pow2_xy		ADD_PREFIX(pow2_xy)

-#define  L_mpy_ls		ADD_PREFIX(L_mpy_ls)

-#define  L_mpy_wx		ADD_PREFIX(L_mpy_wx)

-

-#define mem_malloc		ADD_PREFIX(mem_malloc)

-#define mem_free		ADD_PREFIX(mem_free)

-

+
+#ifndef max
+#define max(a,b) ( a > b ? a : b)
+#endif
+
+#ifdef ARM_INASM
+#ifdef ARMV5_INASM
+#define ARMV5E_INASM	1
+#endif
+#define ARMV4_INASM		1
+#endif
+
+#if ARMV4_INASM
+	#define ARMV5TE_SAT           1
+    #define ARMV5TE_ADD           1
+    #define ARMV5TE_SUB           1
+	#define ARMV5TE_SHL           1
+    #define ARMV5TE_SHR           1
+	#define ARMV5TE_L_SHL         1
+    #define ARMV5TE_L_SHR         1
+#endif//ARMV4
+#if ARMV5E_INASM
+    #define ARMV5TE_L_ADD         1
+    #define ARMV5TE_L_SUB         1
+    #define ARMV5TE_L_MULT        1
+    #define ARMV5TE_L_MAC         1
+    #define ARMV5TE_L_MSU         1
+
+
+    #define ARMV5TE_DIV_S         1
+    #define ARMV5TE_ROUND         1
+    #define ARMV5TE_MULT          1
+
+    #define ARMV5TE_NORM_S        1
+    #define ARMV5TE_NORM_L        1
+	#define ARMV5TE_L_MPY_LS	  1
+#endif
+
+//basic operation functions optimization flags
+#define SATRUATE_IS_INLINE              1   //define saturate as inline function
+#define SHL_IS_INLINE                   1  //define shl as inline function
+#define SHR_IS_INLINE                   1   //define shr as inline function
+#define L_MULT_IS_INLINE                1   //define L_mult as inline function
+#define L_MSU_IS_INLINE                 1   //define L_msu as inline function
+#define L_SUB_IS_INLINE                 1   //define L_sub as inline function
+#define L_SHL_IS_INLINE                 1   //define L_shl as inline function
+#define L_SHR_IS_INLINE                 1   //define L_shr as inline function
+#define ADD_IS_INLINE                   1   //define add as inline function //add, inline is the best
+#define SUB_IS_INLINE                   1   //define sub as inline function //sub, inline is the best
+#define DIV_S_IS_INLINE                 1   //define div_s as inline function
+#define MULT_IS_INLINE                  1   //define mult as inline function
+#define NORM_S_IS_INLINE                1   //define norm_s as inline function
+#define NORM_L_IS_INLINE                1   //define norm_l as inline function
+#define ROUND_IS_INLINE                 1   //define round as inline function
+#define L_MAC_IS_INLINE                 1   //define L_mac as inline function
+#define L_ADD_IS_INLINE                 1   //define L_add as inline function
+#define EXTRACT_H_IS_INLINE             1   //define extract_h as inline function
+#define EXTRACT_L_IS_INLINE             1   //define extract_l as inline function        //???
+#define MULT_R_IS_INLINE                1   //define mult_r as inline function
+#define SHR_R_IS_INLINE                 1   //define shr_r as inline function
+#define MAC_R_IS_INLINE                 1   //define mac_r as inline function
+#define MSU_R_IS_INLINE                 1   //define msu_r as inline function
+#define L_SHR_R_IS_INLINE               1   //define L_shr_r as inline function
+
+#define PREFIX				voAACEnc
+#define LINK0(x, y, z)		LINK1(x,y,z)
+#define LINK1(x,y,z)		x##y##z
+#define ADD_PREFIX(func)	LINK0(PREFIX, _, func)
+
+#define  L_Extract		ADD_PREFIX(L_Extract)
+#define  L_Comp			ADD_PREFIX(L_Comp)
+#define  Mpy_32			ADD_PREFIX(Mpy_32)
+#define  Mpy_32_16		ADD_PREFIX(Mpy_32_16)
+#define  Div_32			ADD_PREFIX(Div_32)
+#define  iLog4			ADD_PREFIX(iLog4)
+#define  rsqrt			ADD_PREFIX(rsqrt)
+#define  pow2_xy		ADD_PREFIX(pow2_xy)
+#define  L_mpy_ls		ADD_PREFIX(L_mpy_ls)
+#define  L_mpy_wx		ADD_PREFIX(L_mpy_wx)
+
+#define mem_malloc		ADD_PREFIX(mem_malloc)
+#define mem_free		ADD_PREFIX(mem_free)
+
 #endif
diff --git a/media/libstagefright/codecs/aacenc/build/eclair/ARMV5E/Makefile b/media/libstagefright/codecs/aacenc/build/eclair/ARMV5E/Makefile
index b4f63af..79be7da 100644
--- a/media/libstagefright/codecs/aacenc/build/eclair/ARMV5E/Makefile
+++ b/media/libstagefright/codecs/aacenc/build/eclair/ARMV5E/Makefile
@@ -1,55 +1,55 @@
-#/*

-#** Copyright 2003-2010, VisualOn, Inc.

-#**

-#** Licensed under the Apache License, Version 2.0 (the "License");

-#** you may not use this file except in compliance with the License.

-#** You may obtain a copy of the License at

-#**

-#**     http://www.apache.org/licenses/LICENSE-2.0

-#**

-#** Unless required by applicable law or agreed to in writing, software

-#** distributed under the License is distributed on an "AS IS" BASIS,

-#** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-#** See the License for the specific language governing permissions and

-#** limitations under the License.

-#*/

-

-# target6

-# available: pc, v4(armv4), v5(armv5), v5x(armv5 xscale), v6(armv6), v7(cortex-a8 neon)

-VOTT:= v5

-

-

-# module type

-# please specify the type of your module: lib or exe

-VOMT:= lib

-

-

-# module macros

-# please append the additional macro definitions here for your module if necessary. 

-# e.g. -DVISUALON, macro VISUALON defined for your module 

-VOMM:= -DARMV5E -DARM_INASM -DARMV5_INASM 

-

-

-

-# please specify the name of your module

-VOTARGET:=libvoAACEncv5

-

-

-# please modify here to be sure to see the g1.mk

-include ../../../../../Tools/eclair.mk 

-

-# dependent libraries.

-VODEPLIBS:=#-ldl -lstdc++ 

-

-# module source

-# please modify here to be sure to see the ms.mk which specifies all source info of your module

-include ../../ms.mk

-

-

-# please specify where is the voRelease on your PC, relative path is suggested

-VORELDIR:=../../../../../../Release

-

-

-# please modify here to be sure to see the doit.mk

-include ../../../../../Tools/doit.mk 

-

+#/*
+#** Copyright 2003-2010, VisualOn, Inc.
+#**
+#** Licensed under the Apache License, Version 2.0 (the "License");
+#** you may not use this file except in compliance with the License.
+#** You may obtain a copy of the License at
+#**
+#**     http://www.apache.org/licenses/LICENSE-2.0
+#**
+#** Unless required by applicable law or agreed to in writing, software
+#** distributed under the License is distributed on an "AS IS" BASIS,
+#** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#** See the License for the specific language governing permissions and
+#** limitations under the License.
+#*/
+
+# target6
+# available: pc, v4(armv4), v5(armv5), v5x(armv5 xscale), v6(armv6), v7(cortex-a8 neon)
+VOTT:= v5
+
+
+# module type
+# please specify the type of your module: lib or exe
+VOMT:= lib
+
+
+# module macros
+# please append the additional macro definitions here for your module if necessary.
+# e.g. -DVISUALON, macro VISUALON defined for your module
+VOMM:= -DARMV5E -DARM_INASM -DARMV5_INASM
+
+
+
+# please specify the name of your module
+VOTARGET:=libvoAACEncv5
+
+
+# please modify here to be sure to see the g1.mk
+include ../../../../../Tools/eclair.mk
+
+# dependent libraries.
+VODEPLIBS:=#-ldl -lstdc++
+
+# module source
+# please modify here to be sure to see the ms.mk which specifies all source info of your module
+include ../../ms.mk
+
+
+# please specify where is the voRelease on your PC, relative path is suggested
+VORELDIR:=../../../../../../Release
+
+
+# please modify here to be sure to see the doit.mk
+include ../../../../../Tools/doit.mk
+
diff --git a/media/libstagefright/codecs/aacenc/build/eclair/ARMV7/Makefile b/media/libstagefright/codecs/aacenc/build/eclair/ARMV7/Makefile
index cdce2c1..a72c850 100644
--- a/media/libstagefright/codecs/aacenc/build/eclair/ARMV7/Makefile
+++ b/media/libstagefright/codecs/aacenc/build/eclair/ARMV7/Makefile
@@ -1,55 +1,55 @@
-#/*

-#** Copyright 2003-2010, VisualOn, Inc.

-#**

-#** Licensed under the Apache License, Version 2.0 (the "License");

-#** you may not use this file except in compliance with the License.

-#** You may obtain a copy of the License at

-#**

-#**     http://www.apache.org/licenses/LICENSE-2.0

-#**

-#** Unless required by applicable law or agreed to in writing, software

-#** distributed under the License is distributed on an "AS IS" BASIS,

-#** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-#** See the License for the specific language governing permissions and

-#** limitations under the License.

-#*/

-

-# target6

-# available: pc, v4(armv4), v5(armv5), v5x(armv5 xscale), v6(armv6), v7(cortex-a8 neon)

-VOTT:= v7

-

-

-# module type

-# please specify the type of your module: lib or exe

-VOMT:= lib

-

-

-# module macros

-# please append the additional macro definitions here for your module if necessary. 

-# e.g. -DVISUALON, macro VISUALON defined for your module 

-VOMM:= -DARMV5E -DARMV7Neon -DARM_INASM -DARMV5_INASM 

-

-

-

-# please specify the name of your module

-VOTARGET:=libvoAACEncv7

-

-

-# please modify here to be sure to see the g1.mk

-include ../../../../../Tools/eclair.mk 

-

-# dependent libraries.

-VODEPLIBS:=#-ldl -lstdc++ 

-

-# module source

-# please modify here to be sure to see the ms.mk which specifies all source info of your module

-include ../../ms.mk

-

-

-# please specify where is the voRelease on your PC, relative path is suggested

-VORELDIR:=../../../../../../Release

-

-

-# please modify here to be sure to see the doit.mk

-include ../../../../../Tools/doit.mk  

-

+#/*
+#** Copyright 2003-2010, VisualOn, Inc.
+#**
+#** Licensed under the Apache License, Version 2.0 (the "License");
+#** you may not use this file except in compliance with the License.
+#** You may obtain a copy of the License at
+#**
+#**     http://www.apache.org/licenses/LICENSE-2.0
+#**
+#** Unless required by applicable law or agreed to in writing, software
+#** distributed under the License is distributed on an "AS IS" BASIS,
+#** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#** See the License for the specific language governing permissions and
+#** limitations under the License.
+#*/
+
+# target6
+# available: pc, v4(armv4), v5(armv5), v5x(armv5 xscale), v6(armv6), v7(cortex-a8 neon)
+VOTT:= v7
+
+
+# module type
+# please specify the type of your module: lib or exe
+VOMT:= lib
+
+
+# module macros
+# please append the additional macro definitions here for your module if necessary.
+# e.g. -DVISUALON, macro VISUALON defined for your module
+VOMM:= -DARMV5E -DARMV7Neon -DARM_INASM -DARMV5_INASM
+
+
+
+# please specify the name of your module
+VOTARGET:=libvoAACEncv7
+
+
+# please modify here to be sure to see the g1.mk
+include ../../../../../Tools/eclair.mk
+
+# dependent libraries.
+VODEPLIBS:=#-ldl -lstdc++
+
+# module source
+# please modify here to be sure to see the ms.mk which specifies all source info of your module
+include ../../ms.mk
+
+
+# please specify where is the voRelease on your PC, relative path is suggested
+VORELDIR:=../../../../../../Release
+
+
+# please modify here to be sure to see the doit.mk
+include ../../../../../Tools/doit.mk
+
diff --git a/media/libstagefright/codecs/aacenc/build/eclair/makefile b/media/libstagefright/codecs/aacenc/build/eclair/makefile
index 6bb3c13..5824d17 100644
--- a/media/libstagefright/codecs/aacenc/build/eclair/makefile
+++ b/media/libstagefright/codecs/aacenc/build/eclair/makefile
@@ -16,7 +16,7 @@
 
 # Just acting as Father Makefile of Modules
 # please keep the name 'makefile' unchanged
- 
+
 # Module Subdirs
 VOMSD:=$(dir $(shell find . -name 'Makefile'))
 
diff --git a/media/libstagefright/codecs/aacenc/build/ms.mk b/media/libstagefright/codecs/aacenc/build/ms.mk
index b67efbc..85adba1 100644
--- a/media/libstagefright/codecs/aacenc/build/ms.mk
+++ b/media/libstagefright/codecs/aacenc/build/ms.mk
@@ -1,42 +1,42 @@
-#/*

-#** Copyright 2003-2010, VisualOn, Inc.

-#**

-#** Licensed under the Apache License, Version 2.0 (the "License");

-#** you may not use this file except in compliance with the License.

-#** You may obtain a copy of the License at

-#**

-#**     http://www.apache.org/licenses/LICENSE-2.0

-#**

-#** Unless required by applicable law or agreed to in writing, software

-#** distributed under the License is distributed on an "AS IS" BASIS,

-#** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-#** See the License for the specific language governing permissions and

-#** limitations under the License.

-#*/

-

-

-# please list all objects needed by your target here

-OBJS:=basicop2.o oper_32b.o aac_rom.o aacenc.o aacenc_core.o adj_thr.o \

-			band_nrg.o bit_cnt.o bitbuffer.o bitenc.o block_switch.o channel_map.o \

-			dyn_bits.o grp_data.o interface.o line_pe.o memalign.o ms_stereo.o \

-			pre_echo_control.o psy_configuration.o psy_main.o qc_main.o quantize.o sf_estim.o \

-			spreading.o stat_bits.o tns.o transform.o

-			

-# please list all directories that all source files relative with your module(.h .c .cpp) locate 

-VOSRCDIR:=../../../src \

-					../../../inc \

-					../../../basic_op\

-					../../../../../Include 

-					

-ifeq ($(VOTT), v5)

-OBJS+= AutoCorrelation_v5.o band_nrg_v5.o CalcWindowEnergy_v5.o \

-				PrePostMDCT_v5.o R4R8First_v5.o Radix4FFT_v5.o

-VOSRCDIR+= ../../../src/asm/ARMV5E/

-endif	

-

-ifeq ($(VOTT), v7)

-OBJS+= AutoCorrelation_v5.o band_nrg_v5.o CalcWindowEnergy_v5.o \

-			 PrePostMDCT_v7.o R4R8First_v7.o Radix4FFT_v7.o

-VOSRCDIR+= ../../../src/asm/ARMV5E/

-VOSRCDIR+= ../../../src/asm/ARMV7/

-endif		
\ No newline at end of file
+#/*
+#** Copyright 2003-2010, VisualOn, Inc.
+#**
+#** Licensed under the Apache License, Version 2.0 (the "License");
+#** you may not use this file except in compliance with the License.
+#** You may obtain a copy of the License at
+#**
+#**     http://www.apache.org/licenses/LICENSE-2.0
+#**
+#** Unless required by applicable law or agreed to in writing, software
+#** distributed under the License is distributed on an "AS IS" BASIS,
+#** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#** See the License for the specific language governing permissions and
+#** limitations under the License.
+#*/
+
+
+# please list all objects needed by your target here
+OBJS:=basicop2.o oper_32b.o aac_rom.o aacenc.o aacenc_core.o adj_thr.o \
+			band_nrg.o bit_cnt.o bitbuffer.o bitenc.o block_switch.o channel_map.o \
+			dyn_bits.o grp_data.o interface.o line_pe.o memalign.o ms_stereo.o \
+			pre_echo_control.o psy_configuration.o psy_main.o qc_main.o quantize.o sf_estim.o \
+			spreading.o stat_bits.o tns.o transform.o
+
+# please list all directories that all source files relative with your module(.h .c .cpp) locate
+VOSRCDIR:=../../../src \
+					../../../inc \
+					../../../basic_op\
+					../../../../../Include
+
+ifeq ($(VOTT), v5)
+OBJS+= AutoCorrelation_v5.o band_nrg_v5.o CalcWindowEnergy_v5.o \
+				PrePostMDCT_v5.o R4R8First_v5.o Radix4FFT_v5.o
+VOSRCDIR+= ../../../src/asm/ARMV5E/
+endif
+
+ifeq ($(VOTT), v7)
+OBJS+= AutoCorrelation_v5.o band_nrg_v5.o CalcWindowEnergy_v5.o \
+			 PrePostMDCT_v7.o R4R8First_v7.o Radix4FFT_v7.o
+VOSRCDIR+= ../../../src/asm/ARMV5E/
+VOSRCDIR+= ../../../src/asm/ARMV7/
+endif
diff --git a/media/libstagefright/codecs/aacenc/inc/aac_rom.h b/media/libstagefright/codecs/aacenc/inc/aac_rom.h
index b0429fc..8e206b7 100644
--- a/media/libstagefright/codecs/aacenc/inc/aac_rom.h
+++ b/media/libstagefright/codecs/aacenc/inc/aac_rom.h
@@ -1,28 +1,28 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		aac_rom.h

-

-	Content:	constant tables 

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		aac_rom.h
+
+	Content:	constant tables
+
 *******************************************************************************/
 
 #ifndef ROM_H
 #define ROM_H
-

+
 #include "config.h"
 #include "psy_const.h"
 #include "tns_param.h"
@@ -31,16 +31,16 @@
   mdct
 */
 extern const int ShortWindowSine[FRAME_LEN_SHORT/2];
-extern const int LongWindowKBD[FRAME_LEN_LONG/2];

-

-extern const unsigned char bitrevTab[17 + 129];

-extern const int cossintab[128 + 1024];

-

-#if defined (ARMV5E) && !defined (ARMV7Neon)

-extern const int twidTab64[(4*6 + 16*6)/2];

-extern const int twidTab512[(8*6 + 32*6 + 128*6)/2];

-#else

-extern const int twidTab64[4*6 + 16*6];

+extern const int LongWindowKBD[FRAME_LEN_LONG/2];
+
+extern const unsigned char bitrevTab[17 + 129];
+extern const int cossintab[128 + 1024];
+
+#if defined (ARMV5E) && !defined (ARMV7Neon)
+extern const int twidTab64[(4*6 + 16*6)/2];
+extern const int twidTab512[(8*6 + 32*6 + 128*6)/2];
+#else
+extern const int twidTab64[4*6 + 16*6];
 extern const int twidTab512[8*6 + 32*6 + 128*6];
 #endif
 
@@ -61,7 +61,7 @@
 extern const UWord8 specExpTableComb_enc[4][14];
 
 extern const Word16 quantBorders[4][4];
-//extern const Word16 quantRecon[3][4];

+//extern const Word16 quantRecon[3][4];
 extern const Word16 quantRecon[4][3];
 
 /*
@@ -92,26 +92,26 @@
 /*
   misc
 */
-extern const int sampRateTab[NUM_SAMPLE_RATES];

-extern const int BandwithCoefTab[8][NUM_SAMPLE_RATES];

-extern const int rates[8];

-extern const UWord8 sfBandTotalShort[NUM_SAMPLE_RATES];

-extern const UWord8 sfBandTotalLong[NUM_SAMPLE_RATES];

-extern const int sfBandTabShortOffset[NUM_SAMPLE_RATES];

-extern const short sfBandTabShort[76];

-extern const int sfBandTabLongOffset[NUM_SAMPLE_RATES];

-extern const short sfBandTabLong[325];

+extern const int sampRateTab[NUM_SAMPLE_RATES];
+extern const int BandwithCoefTab[8][NUM_SAMPLE_RATES];
+extern const int rates[8];
+extern const UWord8 sfBandTotalShort[NUM_SAMPLE_RATES];
+extern const UWord8 sfBandTotalLong[NUM_SAMPLE_RATES];
+extern const int sfBandTabShortOffset[NUM_SAMPLE_RATES];
+extern const short sfBandTabShort[76];
+extern const int sfBandTabLongOffset[NUM_SAMPLE_RATES];
+extern const short sfBandTabLong[325];
 
 extern const Word32 m_log2_table[INT_BITS];
 
 /*
   TNS
 */
-extern const Word32 tnsCoeff3[8];

-extern const Word32 tnsCoeff3Borders[8];

-extern const Word32 tnsCoeff4[16];

-extern const Word32 tnsCoeff4Borders[16];

-extern const Word32 invSBF[24];

-extern const Word16 sideInfoTabLong[MAX_SFB_LONG + 1];

+extern const Word32 tnsCoeff3[8];
+extern const Word32 tnsCoeff3Borders[8];
+extern const Word32 tnsCoeff4[16];
+extern const Word32 tnsCoeff4Borders[16];
+extern const Word32 invSBF[24];
+extern const Word16 sideInfoTabLong[MAX_SFB_LONG + 1];
 extern const Word16 sideInfoTabShort[MAX_SFB_SHORT + 1];
 #endif
diff --git a/media/libstagefright/codecs/aacenc/inc/aacenc_core.h b/media/libstagefright/codecs/aacenc/inc/aacenc_core.h
index faa1d20..1acdbbc 100644
--- a/media/libstagefright/codecs/aacenc/inc/aacenc_core.h
+++ b/media/libstagefright/codecs/aacenc/inc/aacenc_core.h
@@ -1,37 +1,37 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		aacenc_core.h

-

-	Content:	aac encoder interface functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		aacenc_core.h
+
+	Content:	aac encoder interface functions
+
 *******************************************************************************/
 
 #ifndef _aacenc_core_h_
 #define _aacenc_core_h_
 
-

+
 #include "typedef.h"
-#include "config.h"

-#include "bitenc.h"

-

-#include "psy_configuration.h"

-#include "psy_main.h"

-#include "qc_main.h"

-#include "psy_main.h"

+#include "config.h"
+#include "bitenc.h"
+
+#include "psy_configuration.h"
+#include "psy_main.h"
+#include "qc_main.h"
+#include "psy_main.h"
 /*-------------------------- defines --------------------------------------*/
 
 
@@ -41,42 +41,42 @@
   Word32   bitRate;               /* encoder bit rate in bits/sec */
   Word16   nChannelsIn;           /* number of channels on input (1,2) */
   Word16   nChannelsOut;          /* number of channels on output (1,2) */
-  Word16   bandWidth;             /* targeted audio bandwidth in Hz */

+  Word16   bandWidth;             /* targeted audio bandwidth in Hz */
   Word16   adtsUsed;			  /* whether write adts header */
 } AACENC_CONFIG;
-

-

-typedef struct {

-	

-  AACENC_CONFIG config;     /* Word16 size: 8 */

-

-  ELEMENT_INFO elInfo;      /* Word16 size: 4 */

-

-  QC_STATE qcKernel;        /* Word16 size: 6 + 5(PADDING) + 7(ELEMENT_BITS) + 54(ADJ_THR_STATE) = 72 */

-  QC_OUT   qcOut;           /* Word16 size: MAX_CHANNELS*920(QC_OUT_CHANNEL) + 5(QC_OUT_ELEMENT) + 7 = 932 / 1852 */

-

-  PSY_OUT    psyOut;        /* Word16 size: MAX_CHANNELS*186 + 2 = 188 / 374 */

-  PSY_KERNEL psyKernel;     /* Word16 size:  2587 / 4491 */

-

-  struct BITSTREAMENCODER_INIT bseInit; /* Word16 size: 6 */

-  struct BIT_BUF  bitStream;            /* Word16 size: 8 */

-  HANDLE_BIT_BUF  hBitStream;

-  int			  initOK;

-

-  short			*intbuf;

-  short			*encbuf;

-  short			*inbuf;

-  int			enclen;

-  int			inlen;

-  int			intlen;

-  int			uselength;

-

-  void			*hCheck;

-  VO_MEM_OPERATOR *voMemop;

-  VO_MEM_OPERATOR voMemoprator;

-

-}AAC_ENCODER; /* Word16 size: 3809 / 6851 */

-

+
+
+typedef struct {
+
+  AACENC_CONFIG config;     /* Word16 size: 8 */
+
+  ELEMENT_INFO elInfo;      /* Word16 size: 4 */
+
+  QC_STATE qcKernel;        /* Word16 size: 6 + 5(PADDING) + 7(ELEMENT_BITS) + 54(ADJ_THR_STATE) = 72 */
+  QC_OUT   qcOut;           /* Word16 size: MAX_CHANNELS*920(QC_OUT_CHANNEL) + 5(QC_OUT_ELEMENT) + 7 = 932 / 1852 */
+
+  PSY_OUT    psyOut;        /* Word16 size: MAX_CHANNELS*186 + 2 = 188 / 374 */
+  PSY_KERNEL psyKernel;     /* Word16 size:  2587 / 4491 */
+
+  struct BITSTREAMENCODER_INIT bseInit; /* Word16 size: 6 */
+  struct BIT_BUF  bitStream;            /* Word16 size: 8 */
+  HANDLE_BIT_BUF  hBitStream;
+  int			  initOK;
+
+  short			*intbuf;
+  short			*encbuf;
+  short			*inbuf;
+  int			enclen;
+  int			inlen;
+  int			intlen;
+  int			uselength;
+
+  void			*hCheck;
+  VO_MEM_OPERATOR *voMemop;
+  VO_MEM_OPERATOR voMemoprator;
+
+}AAC_ENCODER; /* Word16 size: 3809 / 6851 */
+
 /*-----------------------------------------------------------------------------
 
 functionname: AacInitDefaultConfig
diff --git a/media/libstagefright/codecs/aacenc/inc/adj_thr.h b/media/libstagefright/codecs/aacenc/inc/adj_thr.h
index 4057cbe..0f4bb5e 100644
--- a/media/libstagefright/codecs/aacenc/inc/adj_thr.h
+++ b/media/libstagefright/codecs/aacenc/inc/adj_thr.h
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		adj_thr.h

-

-	Content:	Threshold compensation function 

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		adj_thr.h
+
+	Content:	Threshold compensation function
+
 *******************************************************************************/
 
 #ifndef __ADJ_THR_H
@@ -44,7 +44,7 @@
                       PSY_OUT_ELEMENT *psyOutElement,
                       Word16 *chBitDistribution,
                       Word16 logSfbEnergy[MAX_CHANNELS][MAX_GROUPED_SFB],
-                      Word16 sfbNRelevantLines[MAX_CHANNELS][MAX_GROUPED_SFB],                      
+                      Word16 sfbNRelevantLines[MAX_CHANNELS][MAX_GROUPED_SFB],
                       QC_OUT_ELEMENT* qcOE,
 					  ELEMENT_BITS* elBits,
 					  const Word16 nChannels,
diff --git a/media/libstagefright/codecs/aacenc/inc/adj_thr_data.h b/media/libstagefright/codecs/aacenc/inc/adj_thr_data.h
index 25dd437..30132d8 100644
--- a/media/libstagefright/codecs/aacenc/inc/adj_thr_data.h
+++ b/media/libstagefright/codecs/aacenc/inc/adj_thr_data.h
@@ -1,29 +1,29 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		adj_thr_data.h

-

-	Content:	Threshold compensation parameter 

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		adj_thr_data.h
+
+	Content:	Threshold compensation parameter
+
 *******************************************************************************/
 
 #ifndef __ADJ_THR_DATA_H
 #define __ADJ_THR_DATA_H
 
-#include "typedef.h"

+#include "typedef.h"
 #include "psy_const.h"
 #include "line_pe.h"
 
diff --git a/media/libstagefright/codecs/aacenc/inc/band_nrg.h b/media/libstagefright/codecs/aacenc/inc/band_nrg.h
index 68509da..65453c0 100644
--- a/media/libstagefright/codecs/aacenc/inc/band_nrg.h
+++ b/media/libstagefright/codecs/aacenc/inc/band_nrg.h
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		band_nrg.h

-

-	Content:	Band/Line energy calculations functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		band_nrg.h
+
+	Content:	Band/Line energy calculations functions
+
 *******************************************************************************/
 
 
diff --git a/media/libstagefright/codecs/aacenc/inc/bit_cnt.h b/media/libstagefright/codecs/aacenc/inc/bit_cnt.h
index 808319e..266a219 100644
--- a/media/libstagefright/codecs/aacenc/inc/bit_cnt.h
+++ b/media/libstagefright/codecs/aacenc/inc/bit_cnt.h
@@ -1,29 +1,29 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		bit_cnt.h

-

-	Content:	Huffman Bitcounter & coder structure and functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		bit_cnt.h
+
+	Content:	Huffman Bitcounter & coder structure and functions
+
 *******************************************************************************/
 
 #ifndef __BITCOUNT_H
 #define __BITCOUNT_H
 
-#include "bitbuffer.h"

+#include "bitbuffer.h"
 #include "basic_op.h"
 #define INVALID_BITCOUNT (MAX_16/4)
 
diff --git a/media/libstagefright/codecs/aacenc/inc/bitbuffer.h b/media/libstagefright/codecs/aacenc/inc/bitbuffer.h
index cb850c9..e538064 100644
--- a/media/libstagefright/codecs/aacenc/inc/bitbuffer.h
+++ b/media/libstagefright/codecs/aacenc/inc/bitbuffer.h
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		bitbuffer.h

-

-	Content:	Bit Buffer Management structure and functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		bitbuffer.h
+
+	Content:	Bit Buffer Management structure and functions
+
 *******************************************************************************/
 
 #ifndef BITBUFFER_H
diff --git a/media/libstagefright/codecs/aacenc/inc/bitenc.h b/media/libstagefright/codecs/aacenc/inc/bitenc.h
index 1151057..6a58aeb 100644
--- a/media/libstagefright/codecs/aacenc/inc/bitenc.h
+++ b/media/libstagefright/codecs/aacenc/inc/bitenc.h
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		bitenc.h

-

-	Content:	Bitstream encoder structure and functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		bitenc.h
+
+	Content:	Bitstream encoder structure and functions
+
 *******************************************************************************/
 
 #ifndef _BITENC_H
@@ -26,7 +26,7 @@
 #include "qc_data.h"
 #include "tns.h"
 #include "channel_map.h"
-#include "interface.h"  
+#include "interface.h"
 
 struct BITSTREAMENCODER_INIT
 {
@@ -42,8 +42,8 @@
                        ELEMENT_INFO elInfo,
                        QC_OUT *qcOut,
                        PSY_OUT *psyOut,
-                       Word16 *globUsedBits,

-                       const UWord8 *ancBytes,

+                       Word16 *globUsedBits,
+                       const UWord8 *ancBytes,
 					   Word16 samplerate
                        );
 
diff --git a/media/libstagefright/codecs/aacenc/inc/block_switch.h b/media/libstagefright/codecs/aacenc/inc/block_switch.h
index 3e35819..a4d3e8fd 100644
--- a/media/libstagefright/codecs/aacenc/inc/block_switch.h
+++ b/media/libstagefright/codecs/aacenc/inc/block_switch.h
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		block_switch.h

-

-	Content:	Block switching structure and functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		block_switch.h
+
+	Content:	Block switching structure and functions
+
 *******************************************************************************/
 
 #ifndef _BLOCK_SWITCH_H
diff --git a/media/libstagefright/codecs/aacenc/inc/channel_map.h b/media/libstagefright/codecs/aacenc/inc/channel_map.h
index e3aa8dc..c361feb 100644
--- a/media/libstagefright/codecs/aacenc/inc/channel_map.h
+++ b/media/libstagefright/codecs/aacenc/inc/channel_map.h
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		channel_map.h

-

-	Content:	channel mapping functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		channel_map.h
+
+	Content:	channel mapping functions
+
 *******************************************************************************/
 
 #ifndef _CHANNEL_MAP_H
diff --git a/media/libstagefright/codecs/aacenc/inc/config.h b/media/libstagefright/codecs/aacenc/inc/config.h
index 6211c8f..3b29cef 100644
--- a/media/libstagefright/codecs/aacenc/inc/config.h
+++ b/media/libstagefright/codecs/aacenc/inc/config.h
@@ -1,36 +1,36 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		config.h

-

-	Content:	aac encoder parameter

-

-*******************************************************************************/

-

-#ifndef _AACENC_CONFIG_H_

-#define _AACENC_CONFIG_H_

-

-#define MAX_CHANNELS        2

-

-#define AACENC_BLOCKSIZE    1024   /*! encoder only takes BLOCKSIZE samples at a time */

-#define AACENC_TRANS_FAC    8      /*! encoder short long ratio */

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		config.h
+
+	Content:	aac encoder parameter
+
+*******************************************************************************/
+
+#ifndef _AACENC_CONFIG_H_
+#define _AACENC_CONFIG_H_
+
+#define MAX_CHANNELS        2
+
+#define AACENC_BLOCKSIZE    1024   /*! encoder only takes BLOCKSIZE samples at a time */
+#define AACENC_TRANS_FAC    8      /*! encoder short long ratio */
+
+
 #define MAXBITS_COEF		6144
-#define MINBITS_COEF		744

-

-

+#define MINBITS_COEF		744
+
+
 #endif
\ No newline at end of file
diff --git a/media/libstagefright/codecs/aacenc/inc/dyn_bits.h b/media/libstagefright/codecs/aacenc/inc/dyn_bits.h
index 0468fa2..d3a8a67 100644
--- a/media/libstagefright/codecs/aacenc/inc/dyn_bits.h
+++ b/media/libstagefright/codecs/aacenc/inc/dyn_bits.h
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		dyn_bits.h

-

-	Content:	Noiseless coder module structure and functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		dyn_bits.h
+
+	Content:	Noiseless coder module structure and functions
+
 *******************************************************************************/
 
 #ifndef __DYN_BITS_H
diff --git a/media/libstagefright/codecs/aacenc/inc/grp_data.h b/media/libstagefright/codecs/aacenc/inc/grp_data.h
index 9666577..4c1b2cb 100644
--- a/media/libstagefright/codecs/aacenc/inc/grp_data.h
+++ b/media/libstagefright/codecs/aacenc/inc/grp_data.h
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		grp_data.h

-

-	Content:	Short block grouping function

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		grp_data.h
+
+	Content:	Short block grouping function
+
 *******************************************************************************/
 
 #ifndef __GRP_DATA_H__
diff --git a/media/libstagefright/codecs/aacenc/inc/interface.h b/media/libstagefright/codecs/aacenc/inc/interface.h
index b84334a..a42e6a9 100644
--- a/media/libstagefright/codecs/aacenc/inc/interface.h
+++ b/media/libstagefright/codecs/aacenc/inc/interface.h
@@ -1,29 +1,29 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		interface.h

-

-	Content:	psychoaccoustic/quantizer structures and interface

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		interface.h
+
+	Content:	psychoaccoustic/quantizer structures and interface
+
 *******************************************************************************/
 
 #ifndef _INTERFACE_H
 #define _INTERFACE_H
 
-#include "config.h"

+#include "config.h"
 #include "psy_const.h"
 #include "psy_data.h"
 #include "typedefs.h"
@@ -55,11 +55,11 @@
   Word16  windowShape;
   Word16  groupingMask;
   Word16  sfbOffsets[MAX_GROUPED_SFB+1];
-  Word16  mdctScale; 
-  Word32 *sfbEnergy; 
+  Word16  mdctScale;
+  Word32 *sfbEnergy;
   Word32 *sfbSpreadedEnergy;
-  Word32 *sfbThreshold;       
-  Word32 *mdctSpectrum;        
+  Word32 *sfbThreshold;
+  Word32 *mdctSpectrum;
   Word32  sfbEnSumLR;
   Word32  sfbEnSumMS;
   Word32 sfbDist[MAX_GROUPED_SFB];
diff --git a/media/libstagefright/codecs/aacenc/inc/line_pe.h b/media/libstagefright/codecs/aacenc/inc/line_pe.h
index fed938b..116d5a8 100644
--- a/media/libstagefright/codecs/aacenc/inc/line_pe.h
+++ b/media/libstagefright/codecs/aacenc/inc/line_pe.h
@@ -1,31 +1,31 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		line_pe.h

-

-	Content:	Perceptual entropie module structure and functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		line_pe.h
+
+	Content:	Perceptual entropie module structure and functions
+
 *******************************************************************************/
 
 #ifndef __LINE_PE_H
 #define __LINE_PE_H
 
 
-#include "psy_const.h" 
-#include "interface.h" 
+#include "psy_const.h"
+#include "interface.h"
 
 
 typedef struct {
@@ -72,4 +72,4 @@
 
 
 
-#endif 
+#endif
diff --git a/media/libstagefright/codecs/aacenc/inc/memalign.h b/media/libstagefright/codecs/aacenc/inc/memalign.h
index 3b302a7..30bbf45 100644
--- a/media/libstagefright/codecs/aacenc/inc/memalign.h
+++ b/media/libstagefright/codecs/aacenc/inc/memalign.h
@@ -1,35 +1,35 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		memalign.h

-

-	Content:	Memory alloc alignments functions

-

-*******************************************************************************/

-

-#ifndef __VO_AACENC_MEM_ALIGN_H__

-#define __VO_AACENC_MEM_ALIGN_H__

-

-#include "voMem.h"

-#include "typedef.h"

-

-extern void *mem_malloc(VO_MEM_OPERATOR *pMemop, unsigned int size, unsigned char alignment, unsigned int CodecID);

-extern void mem_free(VO_MEM_OPERATOR *pMemop, void *mem_ptr, unsigned int CodecID);

-

-#endif	/* __VO_MEM_ALIGN_H__ */

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		memalign.h
+
+	Content:	Memory alloc alignments functions
+
+*******************************************************************************/
+
+#ifndef __VO_AACENC_MEM_ALIGN_H__
+#define __VO_AACENC_MEM_ALIGN_H__
+
+#include "voMem.h"
+#include "typedef.h"
+
+extern void *mem_malloc(VO_MEM_OPERATOR *pMemop, unsigned int size, unsigned char alignment, unsigned int CodecID);
+extern void mem_free(VO_MEM_OPERATOR *pMemop, void *mem_ptr, unsigned int CodecID);
+
+#endif	/* __VO_MEM_ALIGN_H__ */
+
+
+
diff --git a/media/libstagefright/codecs/aacenc/inc/ms_stereo.h b/media/libstagefright/codecs/aacenc/inc/ms_stereo.h
index 6d43dec8..3c03dea 100644
--- a/media/libstagefright/codecs/aacenc/inc/ms_stereo.h
+++ b/media/libstagefright/codecs/aacenc/inc/ms_stereo.h
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		ms_stereo.h

-

-	Content:	Declaration MS stereo processing structure and functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		ms_stereo.h
+
+	Content:	Declaration MS stereo processing structure and functions
+
 *******************************************************************************/
 
 #ifndef __MS_STEREO_H__
diff --git a/media/libstagefright/codecs/aacenc/inc/pre_echo_control.h b/media/libstagefright/codecs/aacenc/inc/pre_echo_control.h
index 35f36e8..e719ba7 100644
--- a/media/libstagefright/codecs/aacenc/inc/pre_echo_control.h
+++ b/media/libstagefright/codecs/aacenc/inc/pre_echo_control.h
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		pre_echo_control.h

-

-	Content:	Pre echo control functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		pre_echo_control.h
+
+	Content:	Pre echo control functions
+
 *******************************************************************************/
 
 #ifndef __PRE_ECHO_CONTROL_H
diff --git a/media/libstagefright/codecs/aacenc/inc/psy_configuration.h b/media/libstagefright/codecs/aacenc/inc/psy_configuration.h
index 53cf25b..9abfc99 100644
--- a/media/libstagefright/codecs/aacenc/inc/psy_configuration.h
+++ b/media/libstagefright/codecs/aacenc/inc/psy_configuration.h
@@ -1,28 +1,28 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		psy_configuration.h

-

-	Content:	Psychoaccoustic configuration structure and functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		psy_configuration.h
+
+	Content:	Psychoaccoustic configuration structure and functions
+
 *******************************************************************************/
 
 #ifndef _PSY_CONFIGURATION_H
 #define _PSY_CONFIGURATION_H
-

+
 #include "typedefs.h"
 #include "psy_const.h"
 #include "tns.h"
@@ -38,7 +38,7 @@
   Word16 maxAllowedIncreaseFactor;   /* preecho control */
   Word16 minRemainingThresholdFactor;
 
-  Word16 lowpassLine;

+  Word16 lowpassLine;
   Word16 sampRateIdx;
   Word32 clipEnergy;                 /* for level dependend tmn */
 
@@ -68,7 +68,7 @@
   Word16 maxAllowedIncreaseFactor;   /* preecho control */
   Word16 minRemainingThresholdFactor;
 
-  Word16 lowpassLine;

+  Word16 lowpassLine;
   Word16 sampRateIdx;
   Word32 clipEnergy;                 /* for level dependend tmn */
 
@@ -85,10 +85,10 @@
   TNS_CONFIG tnsConf;
 
 }PSY_CONFIGURATION_SHORT; /*Word16 size: 8 + 16 + 16 + 16 + 16 + 16 + 16 + 16 + 47 = 167 */
-

-

-/* Returns the sample rate index */

-Word32 GetSRIndex(Word32 sampleRate);

+
+
+/* Returns the sample rate index */
+Word32 GetSRIndex(Word32 sampleRate);
 
 
 Word16 InitPsyConfigurationLong(Word32 bitrate,
diff --git a/media/libstagefright/codecs/aacenc/inc/psy_const.h b/media/libstagefright/codecs/aacenc/inc/psy_const.h
index 5455ab1..19fb9b2 100644
--- a/media/libstagefright/codecs/aacenc/inc/psy_const.h
+++ b/media/libstagefright/codecs/aacenc/inc/psy_const.h
@@ -1,37 +1,37 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		psy_const.h

-

-	Content:	Global psychoacoustic constants structures

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		psy_const.h
+
+	Content:	Global psychoacoustic constants structures
+
 *******************************************************************************/
 
 #ifndef _PSYCONST_H
 #define _PSYCONST_H
 
-#include "config.h"

+#include "config.h"
 
 #define TRUE  1
 #define FALSE 0
 
 #define FRAME_LEN_LONG    AACENC_BLOCKSIZE
 #define TRANS_FAC         8
-#define FRAME_LEN_SHORT   (FRAME_LEN_LONG/TRANS_FAC)

-

+#define FRAME_LEN_SHORT   (FRAME_LEN_LONG/TRANS_FAC)
+
 
 
 /* Block types */
@@ -69,12 +69,12 @@
 
 #define BLOCK_SWITCHING_OFFSET		   (1*1024+3*128+64+128)
 #define BLOCK_SWITCHING_DATA_SIZE          FRAME_LEN_LONG
-										    
+
 #define TRANSFORM_OFFSET_LONG    0
 #define TRANSFORM_OFFSET_SHORT   448
 
 #define LOG_NORM_PCM          -15
-

+
 #define NUM_SAMPLE_RATES	12
 
 #endif /* _PSYCONST_H */
diff --git a/media/libstagefright/codecs/aacenc/inc/psy_data.h b/media/libstagefright/codecs/aacenc/inc/psy_data.h
index 1412d53..3ea6a84 100644
--- a/media/libstagefright/codecs/aacenc/inc/psy_data.h
+++ b/media/libstagefright/codecs/aacenc/inc/psy_data.h
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		psy_data.h

-

-	Content:	Psychoacoustic data and structures

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		psy_data.h
+
+	Content:	Psychoacoustic data and structures
+
 *******************************************************************************/
 
 #ifndef _PSY_DATA_H
diff --git a/media/libstagefright/codecs/aacenc/inc/psy_main.h b/media/libstagefright/codecs/aacenc/inc/psy_main.h
index ab0b8b1..2ccac60 100644
--- a/media/libstagefright/codecs/aacenc/inc/psy_main.h
+++ b/media/libstagefright/codecs/aacenc/inc/psy_main.h
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		psy_main.h

-

-	Content:	Psychoacoustic major function block

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		psy_main.h
+
+	Content:	Psychoacoustic major function block
+
 *******************************************************************************/
 
 #ifndef _PSYMAIN_H
@@ -35,7 +35,7 @@
   PSY_CONFIGURATION_SHORT psyConfShort;          /* Word16 size: 167 */
   PSY_DATA                psyData[MAX_CHANNELS]; /* Word16 size: MAX_CHANNELS*1669*/
   TNS_DATA                tnsData[MAX_CHANNELS]; /* Word16 size: MAX_CHANNELS*235 */
-  Word32*                 pScratchTns;

+  Word32*                 pScratchTns;
   Word16				  sampleRateIdx;
 }PSY_KERNEL; /* Word16 size: 2587 / 4491 */
 
@@ -54,9 +54,9 @@
                     Word16 bandwidth);
 
 
-Word16 psyMain(Word16                   nChannels,   /*!< total number of channels */              
+Word16 psyMain(Word16                   nChannels,   /*!< total number of channels */
                ELEMENT_INFO             *elemInfo,
-               Word16                   *timeSignal, /*!< interleaved time signal */ 
+               Word16                   *timeSignal, /*!< interleaved time signal */
                PSY_DATA                 psyData[MAX_CHANNELS],
                TNS_DATA                 tnsData[MAX_CHANNELS],
                PSY_CONFIGURATION_LONG*  psyConfLong,
diff --git a/media/libstagefright/codecs/aacenc/inc/qc_data.h b/media/libstagefright/codecs/aacenc/inc/qc_data.h
index 81d4051..109922df 100644
--- a/media/libstagefright/codecs/aacenc/inc/qc_data.h
+++ b/media/libstagefright/codecs/aacenc/inc/qc_data.h
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		qc_data.h

-

-	Content:	Quantizing & coding structures

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		qc_data.h
+
+	Content:	Quantizing & coding structures
+
 *******************************************************************************/
 
 #ifndef _QC_DATA_H
@@ -89,7 +89,7 @@
 
 typedef struct
 {
-  Word16		  adtsUsed;

+  Word16		  adtsUsed;
   Word16          staticBitsUsed; /* for verification purposes */
   Word16          dynBitsUsed;    /* for verification purposes */
   Word16          pe;
diff --git a/media/libstagefright/codecs/aacenc/inc/qc_main.h b/media/libstagefright/codecs/aacenc/inc/qc_main.h
index e1138b2..8f83973 100644
--- a/media/libstagefright/codecs/aacenc/inc/qc_main.h
+++ b/media/libstagefright/codecs/aacenc/inc/qc_main.h
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		qc_main.h

-

-	Content:	Quantizing & coding functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		qc_main.h
+
+	Content:	Quantizing & coding functions
+
 *******************************************************************************/
 
 #ifndef _QC_MAIN_H
@@ -35,7 +35,7 @@
 
 Word16 QCNew(QC_STATE *hQC, VO_MEM_OPERATOR *pMemOP);
 
-Word16 QCInit(QC_STATE *hQC, 
+Word16 QCInit(QC_STATE *hQC,
               struct QC_INIT *init);
 
 void QCDelete(QC_STATE *hQC, VO_MEM_OPERATOR *pMemOP);
diff --git a/media/libstagefright/codecs/aacenc/inc/quantize.h b/media/libstagefright/codecs/aacenc/inc/quantize.h
index 88a95e1..1cafef6 100644
--- a/media/libstagefright/codecs/aacenc/inc/quantize.h
+++ b/media/libstagefright/codecs/aacenc/inc/quantize.h
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		quantize.h

-

-	Content:	Quantization functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		quantize.h
+
+	Content:	Quantization functions
+
 *******************************************************************************/
 
 #ifndef _QUANTIZE_H_
@@ -28,7 +28,7 @@
 
 #define MAX_QUANT 8191
 
-void QuantizeSpectrum(Word16 sfbCnt, 
+void QuantizeSpectrum(Word16 sfbCnt,
                       Word16 maxSfbPerGroup,
                       Word16 sfbPerGroup,
                       Word16 *sfbOffset, Word32 *mdctSpectrum,
diff --git a/media/libstagefright/codecs/aacenc/inc/sf_estim.h b/media/libstagefright/codecs/aacenc/inc/sf_estim.h
index b25ec3c..9039f25 100644
--- a/media/libstagefright/codecs/aacenc/inc/sf_estim.h
+++ b/media/libstagefright/codecs/aacenc/inc/sf_estim.h
@@ -1,29 +1,29 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		sf_estim.h

-

-	Content:	Scale factor estimation functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		sf_estim.h
+
+	Content:	Scale factor estimation functions
+
 *******************************************************************************/
 
 #ifndef __SF_ESTIM_H__
 #define __SF_ESTIM_H__
 /*
-   Scale factor estimation 
+   Scale factor estimation
  */
 #include "psy_const.h"
 #include "interface.h"
diff --git a/media/libstagefright/codecs/aacenc/inc/spreading.h b/media/libstagefright/codecs/aacenc/inc/spreading.h
index 29cf63d..0c96fc7 100644
--- a/media/libstagefright/codecs/aacenc/inc/spreading.h
+++ b/media/libstagefright/codecs/aacenc/inc/spreading.h
@@ -1,29 +1,29 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		spreading.h

-

-	Content:	Spreading of energy functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		spreading.h
+
+	Content:	Spreading of energy functions
+
 *******************************************************************************/
 
 #ifndef _SPREADING_H
 #define _SPREADING_H
 #include "typedefs.h"
-

+
 
 void SpreadingMax(const Word16 pbCnt,
                   const Word16 *maskLowFactor,
diff --git a/media/libstagefright/codecs/aacenc/inc/stat_bits.h b/media/libstagefright/codecs/aacenc/inc/stat_bits.h
index 6e90b9c..9cddc1d 100644
--- a/media/libstagefright/codecs/aacenc/inc/stat_bits.h
+++ b/media/libstagefright/codecs/aacenc/inc/stat_bits.h
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		stat_bits.h

-

-	Content:	Static bit counter functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		stat_bits.h
+
+	Content:	Static bit counter functions
+
 *******************************************************************************/
 
 #ifndef __STAT_BITS_H
@@ -28,7 +28,7 @@
 
 Word16 countStaticBitdemand(PSY_OUT_CHANNEL psyOutChannel[MAX_CHANNELS],
                             PSY_OUT_ELEMENT *psyOutElement,
-                            Word16 nChannels, 

+                            Word16 nChannels,
 							Word16 adtsUsed);
 
 #endif /* __STAT_BITS_H */
diff --git a/media/libstagefright/codecs/aacenc/inc/tns.h b/media/libstagefright/codecs/aacenc/inc/tns.h
index 9ffcce9..40cfaee 100644
--- a/media/libstagefright/codecs/aacenc/inc/tns.h
+++ b/media/libstagefright/codecs/aacenc/inc/tns.h
@@ -1,28 +1,28 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		tns.h

-

-	Content:	TNS structures

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		tns.h
+
+	Content:	TNS structures
+
 *******************************************************************************/
 
 #ifndef _TNS_H
 #define _TNS_H
-

+
 #include "typedef.h"
 #include "psy_const.h"
 
diff --git a/media/libstagefright/codecs/aacenc/inc/tns_func.h b/media/libstagefright/codecs/aacenc/inc/tns_func.h
index 58b75b6..02df24d 100644
--- a/media/libstagefright/codecs/aacenc/inc/tns_func.h
+++ b/media/libstagefright/codecs/aacenc/inc/tns_func.h
@@ -1,30 +1,30 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		tns_func.h

-

-	Content:	TNS functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		tns_func.h
+
+	Content:	TNS functions
+
 *******************************************************************************/
 
 /*
    Temporal noise shaping
  */
 #ifndef _TNS_FUNC_H
-#define _TNS_FUNC_H

+#define _TNS_FUNC_H
 #include "typedef.h"
 #include "psy_configuration.h"
 
diff --git a/media/libstagefright/codecs/aacenc/inc/tns_param.h b/media/libstagefright/codecs/aacenc/inc/tns_param.h
index 26266ac..0aa33c3 100644
--- a/media/libstagefright/codecs/aacenc/inc/tns_param.h
+++ b/media/libstagefright/codecs/aacenc/inc/tns_param.h
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		tns_param.h

-

-	Content:	TNS parameters

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		tns_param.h
+
+	Content:	TNS parameters
+
 *******************************************************************************/
 
 /*
@@ -44,7 +44,7 @@
 }TNS_INFO_TAB;
 
 
-void GetTnsParam(TNS_CONFIG_TABULATED *tnsConfigTab, 
+void GetTnsParam(TNS_CONFIG_TABULATED *tnsConfigTab,
                  Word32 bitRate, Word16 channels, Word16 blockType);
 
 void GetTnsMaxBands(Word32 samplingRate, Word16 blockType, Word16* tnsMaxSfb);
diff --git a/media/libstagefright/codecs/aacenc/inc/transform.h b/media/libstagefright/codecs/aacenc/inc/transform.h
index 2666914..fbac7aa 100644
--- a/media/libstagefright/codecs/aacenc/inc/transform.h
+++ b/media/libstagefright/codecs/aacenc/inc/transform.h
@@ -1,30 +1,30 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		transform.h

-

-	Content:	MDCT Transform functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		transform.h
+
+	Content:	MDCT Transform functions
+
 *******************************************************************************/
 
 #ifndef  __TRANSFORM_H__
 #define __TRANSFORM_H__
 
 #include "typedef.h"
-                  
+
 void Transform_Real(Word16 *mdctDelayBuffer,
                     Word16 *timeSignal,
                     Word16 chIncrement,     /*! channel increment */
diff --git a/media/libstagefright/codecs/aacenc/src/aac_rom.c b/media/libstagefright/codecs/aacenc/src/aac_rom.c
index 2ce0352..08792e8 100644
--- a/media/libstagefright/codecs/aacenc/src/aac_rom.c
+++ b/media/libstagefright/codecs/aacenc/src/aac_rom.c
@@ -1,1045 +1,1045 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		aac_rom.c

-

-	Content:	constant tables

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		aac_rom.c
+
+	Content:	constant tables
+
 *******************************************************************************/
 
-#include "aac_rom.h"

-

-#if defined (ARMV5E) && !defined (ARMV7Neon)

-

-/* 

- *  Q30 for 128 and 1024 

- *

- * for (i = 0; i < num/4; i++) {

- *   angle = (i + 0.125) * M_PI / num;

- *   x = cos(angle) * (1 << 30);

- *   x = sin(angle) * (1 << 30);

- * 

- *   angle = (num/2 - 1 - i + 0.125) * M_PI / num;

- *   x = cos(angle) * (1 << 30);

- *   x = sin(angle) * (1 << 30);

- * }

- */

-const int cossintab[128 + 1024] = {

-	/* 128 */

-	0x3fffec43, 0x003243f1, 0x015fd4d2, 0x3ffc38d1, 0x3ff9c13a, 0x01c454f5, 0x02f1b755, 0x3feea776, 

-	0x3fe9b8a9, 0x03562038, 0x0483259d, 0x3fd73a4a, 0x3fcfd50b, 0x04e767c5, 0x0613e1c5, 0x3fb5f4ea, 

-	0x3fac1a5b, 0x0677edbb, 0x07a3adff, 0x3f8adc77, 0x3f7e8e1e, 0x08077457, 0x09324ca7, 0x3f55f796, 

-	0x3f473759, 0x0995bdfd, 0x0abf8043, 0x3f174e70, 0x3f061e95, 0x0b228d42, 0x0c4b0b94, 0x3eceeaad, 

-	0x3ebb4ddb, 0x0cada4f5, 0x0dd4b19a, 0x3e7cd778, 0x3e66d0b4, 0x0e36c82a, 0x0f5c35a3, 0x3e212179, 

-	0x3e08b42a, 0x0fbdba40, 0x10e15b4e, 0x3dbbd6d4, 0x3da106bd, 0x11423ef0, 0x1263e699, 0x3d4d0728, 

-	0x3d2fd86c, 0x12c41a4f, 0x13e39be9, 0x3cd4c38b, 0x3cb53aaa, 0x144310dd, 0x15604013, 0x3c531e88, 

-	0x3c314060, 0x15bee78c, 0x16d99864, 0x3bc82c1f, 0x3ba3fde7, 0x173763c9, 0x184f6aab, 0x3b3401bb, 

-	0x3b0d8909, 0x18ac4b87, 0x19c17d44, 0x3a96b636, 0x3a6df8f8, 0x1a1d6544, 0x1b2f971e, 0x39f061d2, 

-	0x39c5664f, 0x1b8a7815, 0x1c997fc4, 0x39411e33, 0x3913eb0e, 0x1cf34baf, 0x1dfeff67, 0x38890663, 

-	0x3859a292, 0x1e57a86d, 0x1f5fdee6, 0x37c836c2, 0x3796a996, 0x1fb7575c, 0x20bbe7d8, 0x36fecd0e, 

-	0x36cb1e2a, 0x21122240, 0x2212e492, 0x362ce855, 0x35f71fb1, 0x2267d3a0, 0x2364a02e, 0x3552a8f4, 

-	0x351acedd, 0x23b836ca, 0x24b0e699, 0x34703095, 0x34364da6, 0x250317df, 0x25f78497, 0x3385a222, 

-	0x3349bf48, 0x264843d9, 0x273847c8, 0x329321c7, 0x32554840, 0x27878893, 0x2872feb6, 0x3198d4ea, 

-	0x31590e3e, 0x28c0b4d2, 0x29a778db, 0x3096e223, 0x30553828, 0x29f3984c, 0x2ad586a3, 0x2f8d713a, 

-	0x2f49ee0f, 0x2b2003ac, 0x2bfcf97c, 0x2e7cab1c, 0x2e37592c, 0x2c45c8a0, 0x2d1da3d5, 0x2d64b9da, 

-	/* 1024 */

-	0x3fffffb1, 0x0006487f, 0x002bfb74, 0x3ffff0e3, 0x3fffe705, 0x00388c6e, 0x005e3f4c, 0x3fffba9b, 

-	0x3fffa6de, 0x006ad03b, 0x009082ea, 0x3fff5cd8, 0x3fff3f3c, 0x009d13c5, 0x00c2c62f, 0x3ffed79b, 

-	0x3ffeb021, 0x00cf56ef, 0x00f508fc, 0x3ffe2ae5, 0x3ffdf98c, 0x01019998, 0x01274b31, 0x3ffd56b5, 

-	0x3ffd1b7e, 0x0133dba3, 0x01598cb1, 0x3ffc5b0c, 0x3ffc15f7, 0x01661cf0, 0x018bcd5b, 0x3ffb37ec, 

-	0x3ffae8f9, 0x01985d60, 0x01be0d11, 0x3ff9ed53, 0x3ff99483, 0x01ca9cd4, 0x01f04bb4, 0x3ff87b44, 

-	0x3ff81896, 0x01fcdb2e, 0x02228924, 0x3ff6e1bf, 0x3ff67534, 0x022f184d, 0x0254c544, 0x3ff520c5, 

-	0x3ff4aa5d, 0x02615414, 0x0286fff3, 0x3ff33858, 0x3ff2b813, 0x02938e62, 0x02b93914, 0x3ff12878, 

-	0x3ff09e56, 0x02c5c71a, 0x02eb7086, 0x3feef126, 0x3fee5d28, 0x02f7fe1c, 0x031da62b, 0x3fec9265, 

-	0x3febf48b, 0x032a3349, 0x034fd9e5, 0x3fea0c35, 0x3fe96480, 0x035c6682, 0x03820b93, 0x3fe75e98, 

-	0x3fe6ad08, 0x038e97a9, 0x03b43b17, 0x3fe48990, 0x3fe3ce26, 0x03c0c69e, 0x03e66852, 0x3fe18d1f, 

-	0x3fe0c7da, 0x03f2f342, 0x04189326, 0x3fde6945, 0x3fdd9a27, 0x04251d77, 0x044abb73, 0x3fdb1e06, 

-	0x3fda450f, 0x0457451d, 0x047ce11a, 0x3fd7ab64, 0x3fd6c894, 0x04896a16, 0x04af03fc, 0x3fd4115f, 

-	0x3fd324b7, 0x04bb8c42, 0x04e123fa, 0x3fd04ffc, 0x3fcf597c, 0x04edab83, 0x051340f6, 0x3fcc673b, 

-	0x3fcb66e4, 0x051fc7b9, 0x05455ad1, 0x3fc8571f, 0x3fc74cf3, 0x0551e0c7, 0x0577716b, 0x3fc41fac, 

-	0x3fc30baa, 0x0583f68c, 0x05a984a6, 0x3fbfc0e3, 0x3fbea30c, 0x05b608eb, 0x05db9463, 0x3fbb3ac7, 

-	0x3fba131b, 0x05e817c3, 0x060da083, 0x3fb68d5b, 0x3fb55bdc, 0x061a22f7, 0x063fa8e7, 0x3fb1b8a2, 

-	0x3fb07d50, 0x064c2a67, 0x0671ad71, 0x3facbc9f, 0x3fab777b, 0x067e2df5, 0x06a3ae00, 0x3fa79954, 

-	0x3fa64a5f, 0x06b02d81, 0x06d5aa77, 0x3fa24ec6, 0x3fa0f600, 0x06e228ee, 0x0707a2b7, 0x3f9cdcf7, 

-	0x3f9b7a62, 0x0714201b, 0x073996a1, 0x3f9743eb, 0x3f95d787, 0x074612eb, 0x076b8616, 0x3f9183a5, 

-	0x3f900d72, 0x0778013d, 0x079d70f7, 0x3f8b9c28, 0x3f8a1c29, 0x07a9eaf5, 0x07cf5726, 0x3f858d79, 

-	0x3f8403ae, 0x07dbcff2, 0x08013883, 0x3f7f579b, 0x3f7dc405, 0x080db016, 0x083314f1, 0x3f78fa92, 

-	0x3f775d31, 0x083f8b43, 0x0864ec4f, 0x3f727661, 0x3f70cf38, 0x08716159, 0x0896be80, 0x3f6bcb0e, 

-	0x3f6a1a1c, 0x08a3323a, 0x08c88b65, 0x3f64f89b, 0x3f633de2, 0x08d4fdc6, 0x08fa52de, 0x3f5dff0e, 

-	0x3f5c3a8f, 0x0906c3e0, 0x092c14ce, 0x3f56de6a, 0x3f551026, 0x09388469, 0x095dd116, 0x3f4f96b4, 

-	0x3f4dbeac, 0x096a3f42, 0x098f8796, 0x3f4827f0, 0x3f464626, 0x099bf44c, 0x09c13831, 0x3f409223, 

-	0x3f3ea697, 0x09cda368, 0x09f2e2c7, 0x3f38d552, 0x3f36e006, 0x09ff4c78, 0x0a24873a, 0x3f30f181, 

-	0x3f2ef276, 0x0a30ef5e, 0x0a56256c, 0x3f28e6b6, 0x3f26ddec, 0x0a628bfa, 0x0a87bd3d, 0x3f20b4f5, 

-	0x3f1ea26e, 0x0a94222f, 0x0ab94e8f, 0x3f185c43, 0x3f164001, 0x0ac5b1dc, 0x0aead944, 0x3f0fdca5, 

-	0x3f0db6a9, 0x0af73ae5, 0x0b1c5d3d, 0x3f073621, 0x3f05066d, 0x0b28bd2a, 0x0b4dda5c, 0x3efe68bc, 

-	0x3efc2f50, 0x0b5a388d, 0x0b7f5081, 0x3ef5747b, 0x3ef3315a, 0x0b8bacf0, 0x0bb0bf8f, 0x3eec5965, 

-	0x3eea0c8e, 0x0bbd1a33, 0x0be22766, 0x3ee3177e, 0x3ee0c0f4, 0x0bee8038, 0x0c1387e9, 0x3ed9aecc, 

-	0x3ed74e91, 0x0c1fdee1, 0x0c44e0f9, 0x3ed01f55, 0x3ecdb56a, 0x0c513610, 0x0c763278, 0x3ec66920, 

-	0x3ec3f585, 0x0c8285a5, 0x0ca77c47, 0x3ebc8c31, 0x3eba0ee9, 0x0cb3cd84, 0x0cd8be47, 0x3eb2888f, 

-	0x3eb0019c, 0x0ce50d8c, 0x0d09f85b, 0x3ea85e41, 0x3ea5cda3, 0x0d1645a0, 0x0d3b2a64, 0x3e9e0d4c, 

-	0x3e9b7306, 0x0d4775a1, 0x0d6c5443, 0x3e9395b7, 0x3e90f1ca, 0x0d789d71, 0x0d9d75db, 0x3e88f788, 

-	0x3e8649f5, 0x0da9bcf2, 0x0dce8f0d, 0x3e7e32c6, 0x3e7b7b90, 0x0ddad406, 0x0dff9fba, 0x3e734778, 

-	0x3e70869f, 0x0e0be28e, 0x0e30a7c5, 0x3e6835a4, 0x3e656b2b, 0x0e3ce86b, 0x0e61a70f, 0x3e5cfd51, 

-	0x3e5a2939, 0x0e6de580, 0x0e929d7a, 0x3e519e86, 0x3e4ec0d1, 0x0e9ed9af, 0x0ec38ae8, 0x3e46194a, 

-	0x3e4331fa, 0x0ecfc4d9, 0x0ef46f3b, 0x3e3a6da4, 0x3e377cbb, 0x0f00a6df, 0x0f254a53, 0x3e2e9b9c, 

-	0x3e2ba11b, 0x0f317fa5, 0x0f561c15, 0x3e22a338, 0x3e1f9f21, 0x0f624f0c, 0x0f86e460, 0x3e168480, 

-	0x3e1376d5, 0x0f9314f5, 0x0fb7a317, 0x3e0a3f7b, 0x3e07283f, 0x0fc3d143, 0x0fe8581d, 0x3dfdd432, 

-	0x3dfab365, 0x0ff483d7, 0x10190352, 0x3df142ab, 0x3dee1851, 0x10252c94, 0x1049a49a, 0x3de48aef, 

-	0x3de15708, 0x1055cb5b, 0x107a3bd5, 0x3dd7ad05, 0x3dd46f94, 0x1086600e, 0x10aac8e6, 0x3dcaa8f5, 

-	0x3dc761fc, 0x10b6ea90, 0x10db4baf, 0x3dbd7ec7, 0x3dba2e48, 0x10e76ac3, 0x110bc413, 0x3db02e84, 

-	0x3dacd481, 0x1117e088, 0x113c31f3, 0x3da2b834, 0x3d9f54af, 0x11484bc2, 0x116c9531, 0x3d951bde, 

-	0x3d91aed9, 0x1178ac53, 0x119cedaf, 0x3d87598c, 0x3d83e309, 0x11a9021d, 0x11cd3b50, 0x3d797145, 

-	0x3d75f147, 0x11d94d02, 0x11fd7df6, 0x3d6b6313, 0x3d67d99b, 0x12098ce5, 0x122db583, 0x3d5d2efe, 

-	0x3d599c0e, 0x1239c1a7, 0x125de1da, 0x3d4ed50f, 0x3d4b38aa, 0x1269eb2b, 0x128e02dc, 0x3d40554e, 

-	0x3d3caf76, 0x129a0954, 0x12be186c, 0x3d31afc5, 0x3d2e007c, 0x12ca1c03, 0x12ee226c, 0x3d22e47c, 

-	0x3d1f2bc5, 0x12fa231b, 0x131e20c0, 0x3d13f37e, 0x3d10315a, 0x132a1e7e, 0x134e1348, 0x3d04dcd2, 

-	0x3d011145, 0x135a0e0e, 0x137df9e7, 0x3cf5a082, 0x3cf1cb8e, 0x1389f1af, 0x13add481, 0x3ce63e98, 

-	0x3ce2603f, 0x13b9c943, 0x13dda2f7, 0x3cd6b71e, 0x3cd2cf62, 0x13e994ab, 0x140d652c, 0x3cc70a1c, 

-	0x3cc318ff, 0x141953cb, 0x143d1b02, 0x3cb7379c, 0x3cb33d22, 0x14490685, 0x146cc45c, 0x3ca73fa9, 

-	0x3ca33bd3, 0x1478acbc, 0x149c611d, 0x3c97224c, 0x3c93151d, 0x14a84652, 0x14cbf127, 0x3c86df8e, 

-	0x3c82c909, 0x14d7d32a, 0x14fb745e, 0x3c76777b, 0x3c7257a2, 0x15075327, 0x152aeaa3, 0x3c65ea1c, 

-	0x3c61c0f1, 0x1536c62b, 0x155a53d9, 0x3c55377b, 0x3c510501, 0x15662c18, 0x1589afe3, 0x3c445fa2, 

-	0x3c4023dd, 0x159584d3, 0x15b8fea4, 0x3c33629d, 0x3c2f1d8e, 0x15c4d03e, 0x15e83fff, 0x3c224075, 

-	0x3c1df21f, 0x15f40e3a, 0x161773d6, 0x3c10f935, 0x3c0ca19b, 0x16233eac, 0x16469a0d, 0x3bff8ce8, 

-	0x3bfb2c0c, 0x16526176, 0x1675b286, 0x3bedfb99, 0x3be9917e, 0x1681767c, 0x16a4bd25, 0x3bdc4552, 

-	0x3bd7d1fa, 0x16b07d9f, 0x16d3b9cc, 0x3bca6a1d, 0x3bc5ed8d, 0x16df76c3, 0x1702a85e, 0x3bb86a08, 

-	0x3bb3e440, 0x170e61cc, 0x173188be, 0x3ba6451b, 0x3ba1b620, 0x173d3e9b, 0x17605ad0, 0x3b93fb63, 

-	0x3b8f6337, 0x176c0d15, 0x178f1e76, 0x3b818ceb, 0x3b7ceb90, 0x179acd1c, 0x17bdd394, 0x3b6ef9be, 

-	0x3b6a4f38, 0x17c97e93, 0x17ec7a0d, 0x3b5c41e8, 0x3b578e39, 0x17f8215e, 0x181b11c4, 0x3b496574, 

-	0x3b44a8a0, 0x1826b561, 0x18499a9d, 0x3b36646e, 0x3b319e77, 0x18553a7d, 0x1878147a, 0x3b233ee1, 

-	0x3b1e6fca, 0x1883b097, 0x18a67f3f, 0x3b0ff4d9, 0x3b0b1ca6, 0x18b21791, 0x18d4dad0, 0x3afc8663, 

-	0x3af7a516, 0x18e06f50, 0x1903270f, 0x3ae8f38b, 0x3ae40926, 0x190eb7b7, 0x193163e1, 0x3ad53c5b, 

-	0x3ad048e3, 0x193cf0a9, 0x195f9128, 0x3ac160e1, 0x3abc6458, 0x196b1a09, 0x198daec8, 0x3aad6129, 

-	0x3aa85b92, 0x199933bb, 0x19bbbca6, 0x3a993d3e, 0x3a942e9d, 0x19c73da3, 0x19e9baa3, 0x3a84f52f, 

-	0x3a7fdd86, 0x19f537a4, 0x1a17a8a5, 0x3a708906, 0x3a6b6859, 0x1a2321a2, 0x1a45868e, 0x3a5bf8d1, 

-	0x3a56cf23, 0x1a50fb81, 0x1a735442, 0x3a47449c, 0x3a4211f0, 0x1a7ec524, 0x1aa111a6, 0x3a326c74, 

-	0x3a2d30cd, 0x1aac7e6f, 0x1acebe9d, 0x3a1d7066, 0x3a182bc8, 0x1ada2746, 0x1afc5b0a, 0x3a08507f, 

-	0x3a0302ed, 0x1b07bf8c, 0x1b29e6d2, 0x39f30ccc, 0x39edb649, 0x1b354727, 0x1b5761d8, 0x39dda55a, 

-	0x39d845e9, 0x1b62bdf8, 0x1b84cc01, 0x39c81a36, 0x39c2b1da, 0x1b9023e5, 0x1bb22530, 0x39b26b6d, 

-	0x39acfa2b, 0x1bbd78d2, 0x1bdf6d4a, 0x399c990d, 0x39971ee7, 0x1beabca1, 0x1c0ca432, 0x3986a324, 

-	0x3981201e, 0x1c17ef39, 0x1c39c9cd, 0x397089bf, 0x396afddc, 0x1c45107c, 0x1c66ddfe, 0x395a4ceb, 

-	0x3954b82e, 0x1c72204f, 0x1c93e0ab, 0x3943ecb6, 0x393e4f23, 0x1c9f1e96, 0x1cc0d1b6, 0x392d692f, 

-	0x3927c2c9, 0x1ccc0b35, 0x1cedb106, 0x3916c262, 0x3911132d, 0x1cf8e611, 0x1d1a7e7d, 0x38fff85e, 

-	0x38fa405e, 0x1d25af0d, 0x1d473a00, 0x38e90b31, 0x38e34a69, 0x1d52660f, 0x1d73e374, 0x38d1fae9, 

-	0x38cc315d, 0x1d7f0afb, 0x1da07abc, 0x38bac795, 0x38b4f547, 0x1dab9db5, 0x1dccffbf, 0x38a37142, 

-	0x389d9637, 0x1dd81e21, 0x1df9725f, 0x388bf7ff, 0x3886143b, 0x1e048c24, 0x1e25d282, 0x38745bdb, 

-	0x386e6f60, 0x1e30e7a4, 0x1e52200c, 0x385c9ce3, 0x3856a7b6, 0x1e5d3084, 0x1e7e5ae2, 0x3844bb28, 

-	0x383ebd4c, 0x1e8966a8, 0x1eaa82e9, 0x382cb6b7, 0x3826b030, 0x1eb589f7, 0x1ed69805, 0x38148f9f, 

-	0x380e8071, 0x1ee19a54, 0x1f029a1c, 0x37fc45ef, 0x37f62e1d, 0x1f0d97a5, 0x1f2e8911, 0x37e3d9b7, 

-	0x37ddb945, 0x1f3981ce, 0x1f5a64cb, 0x37cb4b04, 0x37c521f6, 0x1f6558b5, 0x1f862d2d, 0x37b299e7, 

-	0x37ac6841, 0x1f911c3d, 0x1fb1e21d, 0x3799c66f, 0x37938c34, 0x1fbccc4d, 0x1fdd8381, 0x3780d0aa, 

-	0x377a8ddf, 0x1fe868c8, 0x2009113c, 0x3767b8a9, 0x37616d51, 0x2013f196, 0x20348b35, 0x374e7e7b, 

-	0x37482a9a, 0x203f6699, 0x205ff14f, 0x3735222f, 0x372ec5c9, 0x206ac7b8, 0x208b4372, 0x371ba3d4, 

-	0x37153eee, 0x209614d9, 0x20b68181, 0x3702037c, 0x36fb9618, 0x20c14ddf, 0x20e1ab63, 0x36e84135, 

-	0x36e1cb58, 0x20ec72b1, 0x210cc0fc, 0x36ce5d10, 0x36c7debd, 0x21178334, 0x2137c232, 0x36b4571b, 

-	0x36add058, 0x21427f4d, 0x2162aeea, 0x369a2f69, 0x3693a038, 0x216d66e2, 0x218d870b, 0x367fe608, 

-	0x36794e6e, 0x219839d8, 0x21b84a79, 0x36657b08, 0x365edb09, 0x21c2f815, 0x21e2f91a, 0x364aee7b, 

-	0x3644461b, 0x21eda17f, 0x220d92d4, 0x36304070, 0x36298fb4, 0x221835fb, 0x2238178d, 0x361570f8, 

-	0x360eb7e3, 0x2242b56f, 0x22628729, 0x35fa8023, 0x35f3beba, 0x226d1fc1, 0x228ce191, 0x35df6e03, 

-	0x35d8a449, 0x229774d7, 0x22b726a8, 0x35c43aa7, 0x35bd68a1, 0x22c1b496, 0x22e15655, 0x35a8e621, 

-	0x35a20bd3, 0x22ebdee5, 0x230b707e, 0x358d7081, 0x35868def, 0x2315f3a8, 0x23357509, 0x3571d9d9, 

-	0x356aef08, 0x233ff2c8, 0x235f63dc, 0x35562239, 0x354f2f2c, 0x2369dc29, 0x23893cdd, 0x353a49b2, 

-	0x35334e6f, 0x2393afb2, 0x23b2fff3, 0x351e5056, 0x35174ce0, 0x23bd6d48, 0x23dcad03, 0x35023636, 

-	0x34fb2a92, 0x23e714d3, 0x240643f4, 0x34e5fb63, 0x34dee795, 0x2410a639, 0x242fc4ad, 0x34c99fef, 

-	0x34c283fb, 0x243a215f, 0x24592f13, 0x34ad23eb, 0x34a5ffd5, 0x2463862c, 0x2482830d, 0x34908768, 

-	0x34895b36, 0x248cd487, 0x24abc082, 0x3473ca79, 0x346c962f, 0x24b60c57, 0x24d4e757, 0x3456ed2f, 

-	0x344fb0d1, 0x24df2d81, 0x24fdf775, 0x3439ef9c, 0x3432ab2e, 0x250837ed, 0x2526f0c1, 0x341cd1d2, 

-	0x34158559, 0x25312b81, 0x254fd323, 0x33ff93e2, 0x33f83f62, 0x255a0823, 0x25789e80, 0x33e235df, 

-	0x33dad95e, 0x2582cdbc, 0x25a152c0, 0x33c4b7db, 0x33bd535c, 0x25ab7c30, 0x25c9efca, 0x33a719e8, 

-	0x339fad70, 0x25d41369, 0x25f27584, 0x33895c18, 0x3381e7ac, 0x25fc934b, 0x261ae3d6, 0x336b7e7e, 

-	0x33640223, 0x2624fbbf, 0x26433aa7, 0x334d812d, 0x3345fce6, 0x264d4cac, 0x266b79dd, 0x332f6435, 

-	0x3327d808, 0x267585f8, 0x2693a161, 0x331127ab, 0x3309939c, 0x269da78b, 0x26bbb119, 0x32f2cba1, 

-	0x32eb2fb5, 0x26c5b14c, 0x26e3a8ec, 0x32d45029, 0x32ccac64, 0x26eda322, 0x270b88c2, 0x32b5b557, 

-	0x32ae09be, 0x27157cf5, 0x27335082, 0x3296fb3d, 0x328f47d5, 0x273d3eac, 0x275b0014, 0x327821ee, 

-	0x327066bc, 0x2764e82f, 0x27829760, 0x3259297d, 0x32516686, 0x278c7965, 0x27aa164c, 0x323a11fe, 

-	0x32324746, 0x27b3f235, 0x27d17cc1, 0x321adb83, 0x3213090f, 0x27db5288, 0x27f8caa5, 0x31fb8620, 

-	0x31f3abf5, 0x28029a45, 0x281fffe2, 0x31dc11e8, 0x31d4300b, 0x2829c954, 0x28471c5e, 0x31bc7eee, 

-	0x31b49564, 0x2850df9d, 0x286e2002, 0x319ccd46, 0x3194dc14, 0x2877dd07, 0x28950ab6, 0x317cfd04, 

-	0x3175042e, 0x289ec17a, 0x28bbdc61, 0x315d0e3b, 0x31550dc6, 0x28c58cdf, 0x28e294eb, 0x313d00ff, 

-	0x3134f8f1, 0x28ec3f1e, 0x2909343e, 0x311cd564, 0x3114c5c0, 0x2912d81f, 0x292fba40, 0x30fc8b7d, 

-	0x30f47449, 0x293957c9, 0x295626da, 0x30dc235e, 0x30d404a0, 0x295fbe06, 0x297c79f5, 0x30bb9d1c, 

-	0x30b376d8, 0x29860abd, 0x29a2b378, 0x309af8ca, 0x3092cb05, 0x29ac3dd7, 0x29c8d34d, 0x307a367c, 

-	0x3072013c, 0x29d2573c, 0x29eed95b, 0x30595648, 0x30511991, 0x29f856d5, 0x2a14c58b, 0x30385840, 

-	0x30301418, 0x2a1e3c8a, 0x2a3a97c7, 0x30173c7a, 0x300ef0e5, 0x2a440844, 0x2a604ff5, 0x2ff6030a, 

-	0x2fedb00d, 0x2a69b9ec, 0x2a85ee00, 0x2fd4ac04, 0x2fcc51a5, 0x2a8f516b, 0x2aab71d0, 0x2fb3377c, 

-	0x2faad5c1, 0x2ab4cea9, 0x2ad0db4e, 0x2f91a589, 0x2f893c75, 0x2ada318e, 0x2af62a63, 0x2f6ff63d, 

-	0x2f6785d7, 0x2aff7a05, 0x2b1b5ef8, 0x2f4e29af, 0x2f45b1fb, 0x2b24a7f6, 0x2b4078f5, 0x2f2c3ff2, 

-	0x2f23c0f6, 0x2b49bb4a, 0x2b657844, 0x2f0a391d, 0x2f01b2de, 0x2b6eb3ea, 0x2b8a5cce, 0x2ee81543, 

-	0x2edf87c6, 0x2b9391c0, 0x2baf267d, 0x2ec5d479, 0x2ebd3fc4, 0x2bb854b4, 0x2bd3d53a, 0x2ea376d6, 

-	0x2e9adaee, 0x2bdcfcb0, 0x2bf868ed, 0x2e80fc6e, 0x2e785958, 0x2c01899e, 0x2c1ce181, 0x2e5e6556, 

-	0x2e55bb17, 0x2c25fb66, 0x2c413edf, 0x2e3bb1a4, 0x2e330042, 0x2c4a51f3, 0x2c6580f1, 0x2e18e16d, 

-	0x2e1028ed, 0x2c6e8d2e, 0x2c89a79f, 0x2df5f4c7, 0x2ded352f, 0x2c92ad01, 0x2cadb2d5, 0x2dd2ebc7, 

-	0x2dca251c, 0x2cb6b155, 0x2cd1a27b, 0x2dafc683, 0x2da6f8ca, 0x2cda9a14, 0x2cf5767c, 0x2d8c8510, 

-	0x2d83b04f, 0x2cfe6728, 0x2d192ec1, 0x2d692784, 0x2d604bc0, 0x2d22187a, 0x2d3ccb34, 0x2d45adf6

-};

-

-

-const int twidTab512[(8*6 + 32*6 + 128*6)/2] = {

-	0x40000000, 0x40000000, 0x40000000, 0x3b20187d, 

-	0x3ec50c7c, 0x3536238e, 0x2d412d41, 0x3b20187d, 

-	0x187d3b20, 0x187d3b20, 0x3536238e, 0xf3843ec5, 

-	0x00004000, 0x2d412d41, 0xd2bf2d41, 0xe7833b20, 

-	0x238e3536, 0xc13b0c7c, 0xd2bf2d41, 0x187d3b20, 

-	0xc4e0e783, 0xc4e0187d, 0x0c7c3ec5, 0xdc72caca, 

-

-	0x40000000, 0x40000000, 0x40000000, 0x3fb10645, 

-	0x3fec0323, 0x3f4e0964, 0x3ec50c7c, 0x3fb10645, 

-	0x3d3e1294, 0x3d3e1294, 0x3f4e0964, 0x39da1b5d, 

-	0x3b20187d, 0x3ec50c7c, 0x3536238e, 0x38711e2b, 

-	0x3e140f8c, 0x2f6b2afa, 0x3536238e, 0x3d3e1294, 

-	0x28993179, 0x31792899, 0x3c42158f, 0x20e736e5, 

-	0x2d412d41, 0x3b20187d, 0x187d3b20, 0x28993179, 

-	0x39da1b5d, 0x0f8c3e14, 0x238e3536, 0x38711e2b, 

-	0x06453fb1, 0x1e2b3871, 0x36e520e7, 0xfcdd3fec, 

-	0x187d3b20, 0x3536238e, 0xf3843ec5, 0x12943d3e, 

-	0x3367261f, 0xea713c42, 0x0c7c3ec5, 0x31792899, 

-	0xe1d53871, 0x06453fb1, 0x2f6b2afa, 0xd9e13367, 

-	0x00004000, 0x2d412d41, 0xd2bf2d41, 0xf9bb3fb1, 

-	0x2afa2f6b, 0xcc99261f, 0xf3843ec5, 0x28993179, 

-	0xc78f1e2b, 0xed6c3d3e, 0x261f3367, 0xc3be158f, 

-	0xe7833b20, 0x238e3536, 0xc13b0c7c, 0xe1d53871, 

-	0x20e736e5, 0xc0140323, 0xdc723536, 0x1e2b3871, 

-	0xc04ff9bb, 0xd7673179, 0x1b5d39da, 0xc1ecf074, 

-	0xd2bf2d41, 0x187d3b20, 0xc4e0e783, 0xce872899, 

-	0x158f3c42, 0xc91bdf19, 0xcaca238e, 0x12943d3e, 

-	0xce87d767, 0xc78f1e2b, 0x0f8c3e14, 0xd506d095, 

-	0xc4e0187d, 0x0c7c3ec5, 0xdc72caca, 0xc2c21294, 

-	0x09643f4e, 0xe4a3c626, 0xc13b0c7c, 0x06453fb1, 

-	0xed6cc2c2, 0xc04f0645, 0x03233fec, 0xf69cc0b2, 

-

-	0x40000000, 0x40000000, 0x40000000, 0x3ffb0192, 

-	0x3ffe00c9, 0x3ff4025b, 0x3fec0323, 0x3ffb0192, 

-	0x3fd304b5, 0x3fd304b5, 0x3ff4025b, 0x3f9c070d, 

-	0x3fb10645, 0x3fec0323, 0x3f4e0964, 0x3f8407d5, 

-	0x3fe103ec, 0x3eeb0bb6, 0x3f4e0964, 0x3fd304b5, 

-	0x3e710e05, 0x3f0e0af1, 0x3fc3057d, 0x3de2104f, 

-	0x3ec50c7c, 0x3fb10645, 0x3d3e1294, 0x3e710e05, 

-	0x3f9c070d, 0x3c8414d1, 0x3e140f8c, 0x3f8407d5, 

-	0x3bb61708, 0x3dae1111, 0x3f6a089c, 0x3ad21937, 

-	0x3d3e1294, 0x3f4e0964, 0x39da1b5d, 0x3cc51413, 

-	0x3f2f0a2a, 0x38cf1d79, 0x3c42158f, 0x3f0e0af1, 

-	0x37af1f8b, 0x3bb61708, 0x3eeb0bb6, 0x367c2192, 

-	0x3b20187d, 0x3ec50c7c, 0x3536238e, 0x3a8219ef, 

-	0x3e9c0d41, 0x33de257d, 0x39da1b5d, 0x3e710e05, 

-	0x3274275f, 0x392a1cc6, 0x3e440ec9, 0x30f82934, 

-	0x38711e2b, 0x3e140f8c, 0x2f6b2afa, 0x37af1f8b, 

-	0x3de2104f, 0x2dce2cb2, 0x36e520e7, 0x3dae1111, 

-	0x2c212e5a, 0x3612223d, 0x3d7711d3, 0x2a652ff1, 

-	0x3536238e, 0x3d3e1294, 0x28993179, 0x345324da, 

-	0x3d021354, 0x26c032ee, 0x3367261f, 0x3cc51413, 

-	0x24da3453, 0x3274275f, 0x3c8414d1, 0x22e635a5, 

-	0x31792899, 0x3c42158f, 0x20e736e5, 0x307629cd, 

-	0x3bfd164c, 0x1edc3811, 0x2f6b2afa, 0x3bb61708, 

-	0x1cc6392a, 0x2e5a2c21, 0x3b6c17c3, 0x1aa63a2f, 

-	0x2d412d41, 0x3b20187d, 0x187d3b20, 0x2c212e5a, 

-	0x3ad21937, 0x164c3bfd, 0x2afa2f6b, 0x3a8219ef, 

-	0x14133cc5, 0x29cd3076, 0x3a2f1aa6, 0x11d33d77, 

-	0x28993179, 0x39da1b5d, 0x0f8c3e14, 0x275f3274, 

-	0x39831c12, 0x0d413e9c, 0x261f3367, 0x392a1cc6, 

-	0x0af13f0e, 0x24da3453, 0x38cf1d79, 0x089c3f6a, 

-	0x238e3536, 0x38711e2b, 0x06453fb1, 0x223d3612, 

-	0x38111edc, 0x03ec3fe1, 0x20e736e5, 0x37af1f8b, 

-	0x01923ffb, 0x1f8b37af, 0x374b2039, 0xff373ffe, 

-	0x1e2b3871, 0x36e520e7, 0xfcdd3fec, 0x1cc6392a, 

-	0x367c2192, 0xfa833fc3, 0x1b5d39da, 0x3612223d, 

-	0xf82b3f84, 0x19ef3a82, 0x35a522e6, 0xf5d63f2f, 

-	0x187d3b20, 0x3536238e, 0xf3843ec5, 0x17083bb6, 

-	0x34c62434, 0xf1373e44, 0x158f3c42, 0x345324da, 

-	0xeeef3dae, 0x14133cc5, 0x33de257d, 0xecac3d02, 

-	0x12943d3e, 0x3367261f, 0xea713c42, 0x11113dae, 

-	0x32ee26c0, 0xe83d3b6c, 0x0f8c3e14, 0x3274275f, 

-	0xe6113a82, 0x0e053e71, 0x31f727fd, 0xe3ee3983, 

-	0x0c7c3ec5, 0x31792899, 0xe1d53871, 0x0af13f0e, 

-	0x30f82934, 0xdfc7374b, 0x09643f4e, 0x307629cd, 

-	0xddc33612, 0x07d53f84, 0x2ff12a65, 0xdbcc34c6, 

-	0x06453fb1, 0x2f6b2afa, 0xd9e13367, 0x04b53fd3, 

-	0x2ee32b8e, 0xd80331f7, 0x03233fec, 0x2e5a2c21, 

-	0xd6333076, 0x01923ffb, 0x2dce2cb2, 0xd4722ee3, 

-	0x00004000, 0x2d412d41, 0xd2bf2d41, 0xfe6e3ffb, 

-	0x2cb22dce, 0xd11d2b8e, 0xfcdd3fec, 0x2c212e5a, 

-	0xcf8a29cd, 0xfb4b3fd3, 0x2b8e2ee3, 0xce0927fd, 

-	0xf9bb3fb1, 0x2afa2f6b, 0xcc99261f, 0xf82b3f84, 

-	0x2a652ff1, 0xcb3a2434, 0xf69c3f4e, 0x29cd3076, 

-	0xc9ee223d, 0xf50f3f0e, 0x293430f8, 0xc8b52039, 

-	0xf3843ec5, 0x28993179, 0xc78f1e2b, 0xf1fb3e71, 

-	0x27fd31f7, 0xc67d1c12, 0xf0743e14, 0x275f3274, 

-	0xc57e19ef, 0xeeef3dae, 0x26c032ee, 0xc49417c3, 

-	0xed6c3d3e, 0x261f3367, 0xc3be158f, 0xebed3cc5, 

-	0x257d33de, 0xc2fe1354, 0xea713c42, 0x24da3453, 

-	0xc2521111, 0xe8f83bb6, 0x243434c6, 0xc1bc0ec9, 

-	0xe7833b20, 0x238e3536, 0xc13b0c7c, 0xe6113a82, 

-	0x22e635a5, 0xc0d10a2a, 0xe4a339da, 0x223d3612, 

-	0xc07c07d5, 0xe33a392a, 0x2192367c, 0xc03d057d, 

-	0xe1d53871, 0x20e736e5, 0xc0140323, 0xe07537af, 

-	0x2039374b, 0xc00200c9, 0xdf1936e5, 0x1f8b37af, 

-	0xc005fe6e, 0xddc33612, 0x1edc3811, 0xc01ffc14, 

-	0xdc723536, 0x1e2b3871, 0xc04ff9bb, 0xdb263453, 

-	0x1d7938cf, 0xc096f764, 0xd9e13367, 0x1cc6392a, 

-	0xc0f2f50f, 0xd8a13274, 0x1c123983, 0xc164f2bf, 

-	0xd7673179, 0x1b5d39da, 0xc1ecf074, 0xd6333076, 

-	0x1aa63a2f, 0xc289ee2d, 0xd5062f6b, 0x19ef3a82, 

-	0xc33bebed, 0xd3df2e5a, 0x19373ad2, 0xc403e9b4, 

-	0xd2bf2d41, 0x187d3b20, 0xc4e0e783, 0xd1a62c21, 

-	0x17c33b6c, 0xc5d1e55a, 0xd0952afa, 0x17083bb6, 

-	0xc6d6e33a, 0xcf8a29cd, 0x164c3bfd, 0xc7efe124, 

-	0xce872899, 0x158f3c42, 0xc91bdf19, 0xcd8c275f, 

-	0x14d13c84, 0xca5bdd1a, 0xcc99261f, 0x14133cc5, 

-	0xcbaddb26, 0xcbad24da, 0x13543d02, 0xcd12d940, 

-	0xcaca238e, 0x12943d3e, 0xce87d767, 0xc9ee223d, 

-	0x11d33d77, 0xd00fd59b, 0xc91b20e7, 0x11113dae, 

-	0xd1a6d3df, 0xc8511f8b, 0x104f3de2, 0xd34ed232, 

-	0xc78f1e2b, 0x0f8c3e14, 0xd506d095, 0xc6d61cc6, 

-	0x0ec93e44, 0xd6cccf08, 0xc6261b5d, 0x0e053e71, 

-	0xd8a1cd8c, 0xc57e19ef, 0x0d413e9c, 0xda83cc22, 

-	0xc4e0187d, 0x0c7c3ec5, 0xdc72caca, 0xc44a1708, 

-	0x0bb63eeb, 0xde6ec984, 0xc3be158f, 0x0af13f0e, 

-	0xe075c851, 0xc33b1413, 0x0a2a3f2f, 0xe287c731, 

-	0xc2c21294, 0x09643f4e, 0xe4a3c626, 0xc2521111, 

-	0x089c3f6a, 0xe6c9c52e, 0xc1ec0f8c, 0x07d53f84, 

-	0xe8f8c44a, 0xc18f0e05, 0x070d3f9c, 0xeb2fc37c, 

-	0xc13b0c7c, 0x06453fb1, 0xed6cc2c2, 0xc0f20af1, 

-	0x057d3fc3, 0xefb1c21e, 0xc0b20964, 0x04b53fd3, 

-	0xf1fbc18f, 0xc07c07d5, 0x03ec3fe1, 0xf44ac115, 

-	0xc04f0645, 0x03233fec, 0xf69cc0b2, 0xc02d04b5, 

-	0x025b3ff4, 0xf8f3c064, 0xc0140323, 0x01923ffb, 

-	0xfb4bc02d, 0xc0050192, 0x00c93ffe, 0xfda5c00c	

-};

-

-const int twidTab64[(4*6 + 16*6)/2] = {

-	0x40000000, 0x40000000, 0x40000000, 0x2d412d41, 

-	0x3b20187d, 0x187d3b20, 0x00004000, 0x2d412d41, 

-	0xd2bf2d41, 0xd2bf2d41, 0x187d3b20, 0xc4e0e783, 

-

-	0x40000000, 0x40000000, 0x40000000, 0x3ec50c7c, 

-	0x3fb10645, 0x3d3e1294, 0x3b20187d, 0x3ec50c7c, 

-	0x3536238e, 0x3536238e, 0x3d3e1294, 0x28993179, 

-	0x2d412d41, 0x3b20187d, 0x187d3b20, 0x238e3536, 

-	0x38711e2b, 0x06453fb1, 0x187d3b20, 0x3536238e, 

-	0xf3843ec5, 0x0c7c3ec5, 0x31792899, 0xe1d53871, 

-	0x00004000, 0x2d412d41, 0xd2bf2d41, 0xf3843ec5, 

-	0x28993179, 0xc78f1e2b, 0xe7833b20, 0x238e3536, 

-	0xc13b0c7c, 0xdc723536, 0x1e2b3871, 0xc04ff9bb, 

-	0xd2bf2d41, 0x187d3b20, 0xc4e0e783, 0xcaca238e, 

-	0x12943d3e, 0xce87d767, 0xc4e0187d, 0x0c7c3ec5, 

-	0xdc72caca, 0xc13b0c7c, 0x06453fb1, 0xed6cc2c2 

-};

-

-#elif defined ARMV7Neon

-/* 

- *  Q29 for 128 and 1024 

- *

- * for (i = 0; i < num/4; i++) {

- *   angle = (i + 0.125) * M_PI / num;

- *   x = cos(angle) * (1 << 29);

- *   x = sin(angle) * (1 << 29);

- * 

- *   angle = (num/2 - 1 - i + 0.125) * M_PI / num;

- *   x = cos(angle) * (1 << 29);

- *   x = sin(angle) * (1 << 29);

- * }

- */

-const int cossintab[128 + 1024] = {

-	/* 128 */

-	0x1ffff621, 0x001921f9, 0x00afea69, 0x1ffe1c68, 0x1ffce09d, 0x00e22a7a, 0x0178dbaa, 0x1ff753bb, 
-	0x1ff4dc55, 0x01ab101c, 0x024192cf, 0x1feb9d25, 0x1fe7ea85, 0x0273b3e2, 0x0309f0e2, 0x1fdafa75, 
-	0x1fd60d2e, 0x033bf6dd, 0x03d1d700, 0x1fc56e3b, 0x1fbf470f, 0x0403ba2b, 0x04992653, 0x1faafbcb, 
-	0x1fa39bac, 0x04cadefe, 0x055fc022, 0x1f8ba738, 0x1f830f4a, 0x059146a1, 0x062585ca, 0x1f677557, 
-	0x1f5da6ed, 0x0656d27a, 0x06ea58cd, 0x1f3e6bbc, 0x1f33685a, 0x071b6415, 0x07ae1ad2, 0x1f1090bd, 
-	0x1f045a15, 0x07dedd20, 0x0870ada7, 0x1eddeb6a, 0x1ed0835f, 0x08a11f78, 0x0931f34d, 0x1ea68394, 
-	0x1e97ec36, 0x09620d27, 0x09f1cdf5, 0x1e6a61c5, 0x1e5a9d55, 0x0a21886e, 0x0ab02009, 0x1e298f44, 
-	0x1e18a030, 0x0adf73c6, 0x0b6ccc32, 0x1de4160f, 0x1dd1fef4, 0x0b9bb1e5, 0x0c27b555, 0x1d9a00de, 
-	0x1d86c484, 0x0c5625c3, 0x0ce0bea2, 0x1d4b5b1b, 0x1d36fc7c, 0x0d0eb2a2, 0x0d97cb8f, 0x1cf830e9, 
-	0x1ce2b328, 0x0dc53c0a, 0x0e4cbfe2, 0x1ca08f1a, 0x1c89f587, 0x0e79a5d7, 0x0eff7fb3, 0x1c448331, 
-	0x1c2cd149, 0x0f2bd437, 0x0fafef73, 0x1be41b61, 0x1bcb54cb, 0x0fdbabae, 0x105df3ec, 0x1b7f6687, 
-	0x1b658f15, 0x10891120, 0x11097249, 0x1b16742a, 0x1afb8fd9, 0x1133e9d0, 0x11b25017, 0x1aa9547a, 
-	0x1a8d676e, 0x11dc1b65, 0x1258734d, 0x1a38184a, 0x1a1b26d3, 0x12818bef, 0x12fbc24b, 0x19c2d111, 
-	0x19a4dfa4, 0x132421ec, 0x139c23e4, 0x194990e4, 0x192aa420, 0x13c3c44a, 0x14397f5b, 0x18cc6a75, 
-	0x18ac871f, 0x14605a69, 0x14d3bc6d, 0x184b7112, 0x182a9c14, 0x14f9cc26, 0x156ac352, 0x17c6b89d, 
-	0x17a4f708, 0x159001d6, 0x15fe7cbe, 0x173e558e, 0x171bac96, 0x1622e450, 0x168ed1eb, 0x16b25ced,

-	/* 1024 */

-	0x1fffffd9, 0x0003243f, 0x0015fdba, 0x1ffff872, 0x1ffff382, 0x001c4637, 0x002f1fa6, 0x1fffdd4d, 

-	0x1fffd36f, 0x0035681d, 0x00484175, 0x1fffae6c, 0x1fff9f9e, 0x004e89e3, 0x00616318, 0x1fff6bce, 

-	0x1fff5811, 0x0067ab77, 0x007a847e, 0x1fff1572, 0x1ffefcc6, 0x0080cccc, 0x0093a599, 0x1ffeab5b, 

-	0x1ffe8dbf, 0x0099edd2, 0x00acc658, 0x1ffe2d86, 0x1ffe0afc, 0x00b30e78, 0x00c5e6ad, 0x1ffd9bf6, 

-	0x1ffd747c, 0x00cc2eb0, 0x00df0688, 0x1ffcf6aa, 0x1ffcca41, 0x00e54e6a, 0x00f825da, 0x1ffc3da2, 

-	0x1ffc0c4b, 0x00fe6d97, 0x01114492, 0x1ffb70e0, 0x1ffb3a9a, 0x01178c27, 0x012a62a2, 0x1ffa9063, 

-	0x1ffa552e, 0x0130aa0a, 0x01437ffa, 0x1ff99c2c, 0x1ff95c09, 0x0149c731, 0x015c9c8a, 0x1ff8943c, 

-	0x1ff84f2b, 0x0162e38d, 0x0175b843, 0x1ff77893, 0x1ff72e94, 0x017bff0e, 0x018ed316, 0x1ff64932, 

-	0x1ff5fa46, 0x019519a5, 0x01a7ecf2, 0x1ff5061b, 0x1ff4b240, 0x01ae3341, 0x01c105c9, 0x1ff3af4c, 

-	0x1ff35684, 0x01c74bd5, 0x01da1d8c, 0x1ff244c8, 0x1ff1e713, 0x01e0634f, 0x01f33429, 0x1ff0c68f, 

-	0x1ff063ed, 0x01f979a1, 0x020c4993, 0x1fef34a3, 0x1feecd14, 0x02128ebb, 0x02255db9, 0x1fed8f03, 

-	0x1fed2287, 0x022ba28f, 0x023e708d, 0x1febd5b2, 0x1feb644a, 0x0244b50b, 0x025781fe, 0x1fea08b0, 

-	0x1fe9925c, 0x025dc621, 0x027091fd, 0x1fe827fe, 0x1fe7acbe, 0x0276d5c1, 0x0289a07b, 0x1fe6339d, 

-	0x1fe5b372, 0x028fe3dd, 0x02a2ad69, 0x1fe42b90, 0x1fe3a679, 0x02a8f063, 0x02bbb8b6, 0x1fe20fd6, 

-	0x1fe185d5, 0x02c1fb46, 0x02d4c253, 0x1fdfe071, 0x1fdf5186, 0x02db0475, 0x02edca32, 0x1fdd9d64, 

-	0x1fdd098e, 0x02f40be2, 0x0306d042, 0x1fdb46ae, 0x1fdaadee, 0x030d117c, 0x031fd474, 0x1fd8dc51, 

-	0x1fd83ea8, 0x03261534, 0x0338d6b8, 0x1fd65e4f, 0x1fd5bbbd, 0x033f16fb, 0x0351d700, 0x1fd3ccaa, 

-	0x1fd32530, 0x035816c1, 0x036ad53c, 0x1fd12763, 0x1fd07b00, 0x03711477, 0x0383d15c, 0x1fce6e7c, 

-	0x1fcdbd31, 0x038a100e, 0x039ccb51, 0x1fcba1f5, 0x1fcaebc3, 0x03a30975, 0x03b5c30b, 0x1fc8c1d2, 

-	0x1fc806b9, 0x03bc009f, 0x03ceb87c, 0x1fc5ce14, 0x1fc50e14, 0x03d4f57a, 0x03e7ab93, 0x1fc2c6bd, 

-	0x1fc201d7, 0x03ede7f9, 0x04009c42, 0x1fbfabcd, 0x1fbee202, 0x0406d80b, 0x04198a78, 0x1fbc7d49, 

-	0x1fbbae99, 0x041fc5a1, 0x04327628, 0x1fb93b31, 0x1fb8679c, 0x0438b0ac, 0x044b5f40, 0x1fb5e587, 

-	0x1fb50d0e, 0x0451991d, 0x046445b2, 0x1fb27c4e, 0x1fb19ef1, 0x046a7ee3, 0x047d296f, 0x1faeff87, 

-	0x1fae1d47, 0x048361f0, 0x04960a67, 0x1fab6f35, 0x1faa8813, 0x049c4235, 0x04aee88b, 0x1fa7cb5a, 

-	0x1fa6df56, 0x04b51fa1, 0x04c7c3cb, 0x1fa413f8, 0x1fa32313, 0x04cdfa26, 0x04e09c18, 0x1fa04912, 

-	0x1f9f534c, 0x04e6d1b4, 0x04f97163, 0x1f9c6aa9, 0x1f9b7003, 0x04ffa63c, 0x0512439d, 0x1f9878c1, 

-	0x1f97793b, 0x051877af, 0x052b12b6, 0x1f94735b, 0x1f936ef6, 0x053145fd, 0x0543de9e, 0x1f905a7a, 

-	0x1f8f5137, 0x054a1117, 0x055ca748, 0x1f8c2e21, 0x1f8b2000, 0x0562d8ee, 0x05756ca2, 0x1f87ee52, 

-	0x1f86db55, 0x057b9d73, 0x058e2e9f, 0x1f839b10, 0x1f828336, 0x05945e95, 0x05a6ed2e, 0x1f7f345e, 

-	0x1f7e17a8, 0x05ad1c47, 0x05bfa840, 0x1f7aba3e, 0x1f7998ad, 0x05c5d678, 0x05d85fc7, 0x1f762cb2, 

-	0x1f750647, 0x05de8d19, 0x05f113b3, 0x1f718bbf, 0x1f70607a, 0x05f7401c, 0x0609c3f5, 0x1f6cd766, 

-	0x1f6ba748, 0x060fef71, 0x0622707d, 0x1f680fab, 0x1f66dab5, 0x06289b08, 0x063b193c, 0x1f633490, 

-	0x1f61fac3, 0x064142d3, 0x0653be23, 0x1f5e4619, 0x1f5d0775, 0x0659e6c2, 0x066c5f24, 0x1f594448, 

-	0x1f5800ce, 0x067286c6, 0x0684fc2e, 0x1f542f21, 0x1f52e6d2, 0x068b22d0, 0x069d9532, 0x1f4f06a6, 

-	0x1f4db983, 0x06a3bad0, 0x06b62a22, 0x1f49cadc, 0x1f4878e5, 0x06bc4eb9, 0x06cebaee, 0x1f447bc4, 

-	0x1f4324fb, 0x06d4de79, 0x06e74786, 0x1f3f1963, 0x1f3dbdc8, 0x06ed6a03, 0x06ffcfdd, 0x1f39a3bc, 

-	0x1f384350, 0x0705f147, 0x071853e3, 0x1f341ad2, 0x1f32b595, 0x071e7436, 0x0730d388, 0x1f2e7ea9, 

-	0x1f2d149d, 0x0736f2c0, 0x07494ebd, 0x1f28cf43, 0x1f276069, 0x074f6cd7, 0x0761c574, 0x1f230ca5, 

-	0x1f2198fd, 0x0767e26c, 0x077a379d, 0x1f1d36d2, 0x1f1bbe5d, 0x07805370, 0x0792a52a, 0x1f174dce, 

-	0x1f15d08d, 0x0798bfd3, 0x07ab0e0a, 0x1f11519c, 0x1f0fcf91, 0x07b12786, 0x07c37230, 0x1f0b4240, 

-	0x1f09bb6b, 0x07c98a7a, 0x07dbd18c, 0x1f051fbe, 0x1f03941f, 0x07e1e8a1, 0x07f42c0e, 0x1efeea19, 

-	0x1efd59b3, 0x07fa41eb, 0x080c81a9, 0x1ef8a155, 0x1ef70c28, 0x0812964a, 0x0824d24d, 0x1ef24577, 

-	0x1ef0ab84, 0x082ae5ad, 0x083d1dea, 0x1eebd682, 0x1eea37ca, 0x08433007, 0x08556473, 0x1ee5547a, 

-	0x1ee3b0fe, 0x085b7548, 0x086da5d8, 0x1edebf64, 0x1edd1724, 0x0873b562, 0x0885e209, 0x1ed81742, 

-	0x1ed66a41, 0x088bf044, 0x089e18f9, 0x1ed15c1a, 0x1ecfaa57, 0x08a425e1, 0x08b64a98, 0x1eca8def, 

-	0x1ec8d76c, 0x08bc562a, 0x08ce76d8, 0x1ec3acc6, 0x1ec1f184, 0x08d4810f, 0x08e69da8, 0x1ebcb8a3, 

-	0x1ebaf8a3, 0x08eca681, 0x08febefb, 0x1eb5b18a, 0x1eb3eccd, 0x0904c673, 0x0916dac2, 0x1eae977f, 

-	0x1eacce07, 0x091ce0d4, 0x092ef0ed, 0x1ea76a87, 0x1ea59c55, 0x0934f596, 0x0947016e, 0x1ea02aa7, 

-	0x1e9e57bb, 0x094d04aa, 0x095f0c36, 0x1e98d7e2, 0x1e97003e, 0x09650e01, 0x09771136, 0x1e91723e, 

-	0x1e8f95e3, 0x097d118d, 0x098f1060, 0x1e89f9bf, 0x1e8818ad, 0x09950f3f, 0x09a709a4, 0x1e826e69, 

-	0x1e8088a2, 0x09ad0707, 0x09befcf4, 0x1e7ad041, 0x1e78e5c7, 0x09c4f8d8, 0x09d6ea40, 0x1e731f4c, 

-	0x1e71301f, 0x09dce4a1, 0x09eed17b, 0x1e6b5b8f, 0x1e6967b1, 0x09f4ca56, 0x0a06b296, 0x1e63850e, 

-	0x1e618c80, 0x0a0ca9e6, 0x0a1e8d81, 0x1e5b9bce, 0x1e599e91, 0x0a248343, 0x0a36622e, 0x1e539fd4, 

-	0x1e519dea, 0x0a3c565e, 0x0a4e308f, 0x1e4b9126, 0x1e498a8e, 0x0a542329, 0x0a65f894, 0x1e436fc7, 

-	0x1e416485, 0x0a6be995, 0x0a7dba2f, 0x1e3b3bbd, 0x1e392bd1, 0x0a83a993, 0x0a957551, 0x1e32f50e, 

-	0x1e30e079, 0x0a9b6315, 0x0aad29ec, 0x1e2a9bbd, 0x1e288281, 0x0ab3160c, 0x0ac4d7f1, 0x1e222fd1, 

-	0x1e2011ee, 0x0acac26a, 0x0adc7f52, 0x1e19b14f, 0x1e178ec7, 0x0ae2681f, 0x0af41fff, 0x1e11203b, 

-	0x1e0ef910, 0x0afa071d, 0x0b0bb9eb, 0x1e087c9b, 0x1e0650ce, 0x0b119f56, 0x0b234d07, 0x1dffc674, 

-	0x1dfd9606, 0x0b2930bb, 0x0b3ad943, 0x1df6fdcc, 0x1df4c8bf, 0x0b40bb3e, 0x0b525e92, 0x1dee22a9, 

-	0x1debe8fd, 0x0b583ecf, 0x0b69dce6, 0x1de5350f, 0x1de2f6c6, 0x0b6fbb62, 0x0b81542f, 0x1ddc3504, 

-	0x1dd9f220, 0x0b8730e6, 0x0b98c45f, 0x1dd3228e, 0x1dd0db10, 0x0b9e9f4d, 0x0bb02d68, 0x1dc9fdb2, 

-	0x1dc7b19b, 0x0bb6068a, 0x0bc78f3b, 0x1dc0c676, 0x1dbe75c8, 0x0bcd668e, 0x0bdee9ca, 0x1db77cdf, 

-	0x1db5279c, 0x0be4bf4a, 0x0bf63d07, 0x1dae20f4, 0x1dabc71d, 0x0bfc10af, 0x0c0d88e2, 0x1da4b2ba, 

-	0x1da25450, 0x0c135ab0, 0x0c24cd4e, 0x1d9b3237, 0x1d98cf3b, 0x0c2a9d3e, 0x0c3c0a3d, 0x1d919f70, 

-	0x1d8f37e5, 0x0c41d84b, 0x0c533fa0, 0x1d87fa6d, 0x1d858e53, 0x0c590bc9, 0x0c6a6d68, 0x1d7e4332, 

-	0x1d7bd28b, 0x0c7037a8, 0x0c819388, 0x1d7479c5, 0x1d720493, 0x0c875bdb, 0x0c98b1f0, 0x1d6a9e2e, 

-	0x1d682472, 0x0c9e7854, 0x0cafc894, 0x1d60b070, 0x1d5e322c, 0x0cb58d04, 0x0cc6d764, 0x1d56b094, 

-	0x1d542dc9, 0x0ccc99de, 0x0cddde53, 0x1d4c9e9f, 0x1d4a174f, 0x0ce39ed2, 0x0cf4dd52, 0x1d427a97, 

-	0x1d3feec3, 0x0cfa9bd2, 0x0d0bd452, 0x1d384483, 0x1d35b42d, 0x0d1190d1, 0x0d22c347, 0x1d2dfc68, 

-	0x1d2b6791, 0x0d287dc1, 0x0d39aa21, 0x1d23a24e, 0x1d2108f8, 0x0d3f6292, 0x0d5088d3, 0x1d19363a, 

-	0x1d169867, 0x0d563f38, 0x0d675f4e, 0x1d0eb833, 0x1d0c15e4, 0x0d6d13a3, 0x0d7e2d85, 0x1d04283f, 

-	0x1d018176, 0x0d83dfc6, 0x0d94f369, 0x1cf98666, 0x1cf6db24, 0x0d9aa393, 0x0dabb0ec, 0x1ceed2ad, 

-	0x1cec22f4, 0x0db15efc, 0x0dc26600, 0x1ce40d1b, 0x1ce158ed, 0x0dc811f3, 0x0dd91298, 0x1cd935b7, 

-	0x1cd67d15, 0x0ddebc69, 0x0defb6a5, 0x1cce4c87, 0x1ccb8f74, 0x0df55e51, 0x0e065219, 0x1cc35192, 

-	0x1cc0900f, 0x0e0bf79c, 0x0e1ce4e6, 0x1cb844df, 0x1cb57eee, 0x0e22883e, 0x0e336eff, 0x1cad2675, 

-	0x1caa5c17, 0x0e391027, 0x0e49f055, 0x1ca1f65b, 0x1c9f2792, 0x0e4f8f4b, 0x0e6068db, 0x1c96b497, 

-	0x1c93e165, 0x0e66059a, 0x0e76d883, 0x1c8b6131, 0x1c888997, 0x0e7c7308, 0x0e8d3f3e, 0x1c7ffc2f, 

-	0x1c7d202f, 0x0e92d787, 0x0ea39d00, 0x1c748599, 0x1c71a535, 0x0ea93308, 0x0eb9f1ba, 0x1c68fd75, 

-	0x1c6618ae, 0x0ebf857d, 0x0ed03d5e, 0x1c5d63ca, 0x1c5a7aa4, 0x0ed5ceda, 0x0ee67fdf, 0x1c51b8a1, 

-	0x1c4ecb1c, 0x0eec0f10, 0x0efcb92f, 0x1c45fc00, 0x1c430a1d, 0x0f024612, 0x0f12e941, 0x1c3a2ded, 

-	0x1c3737b0, 0x0f1873d2, 0x0f291006, 0x1c2e4e72, 0x1c2b53db, 0x0f2e9842, 0x0f3f2d71, 0x1c225d94, 

-	0x1c1f5ea6, 0x0f44b354, 0x0f554175, 0x1c165b5b, 0x1c135818, 0x0f5ac4fc, 0x0f6b4c03, 0x1c0a47cf, 

-	0x1c074038, 0x0f70cd2a, 0x0f814d0e, 0x1bfe22f8, 0x1bfb170f, 0x0f86cbd3, 0x0f974489, 0x1bf1ecdb, 

-	0x1beedca2, 0x0f9cc0e7, 0x0fad3265, 0x1be5a582, 0x1be290fb, 0x0fb2ac5a, 0x0fc31697, 0x1bd94cf4, 

-	0x1bd63421, 0x0fc88e1e, 0x0fd8f10f, 0x1bcce337, 0x1bc9c61a, 0x0fde6626, 0x0feec1c0, 0x1bc06855, 

-	0x1bbd46f0, 0x0ff43464, 0x1004889e, 0x1bb3dc55, 0x1bb0b6a9, 0x1009f8cb, 0x101a459a, 0x1ba73f3d, 

-	0x1ba4154d, 0x101fb34d, 0x102ff8a8, 0x1b9a9117, 0x1b9762e4, 0x103563dc, 0x1045a1b9, 0x1b8dd1ea, 

-	0x1b8a9f77, 0x104b0a6c, 0x105b40c1, 0x1b8101be, 0x1b7dcb0c, 0x1060a6ef, 0x1070d5b1, 0x1b74209b, 

-	0x1b70e5ac, 0x10763958, 0x1086607e, 0x1b672e88, 0x1b63ef5f, 0x108bc19a, 0x109be119, 0x1b5a2b8e, 

-	0x1b56e82c, 0x10a13fa6, 0x10b15775, 0x1b4d17b4, 0x1b49d01c, 0x10b6b371, 0x10c6c385, 0x1b3ff304, 

-	0x1b3ca737, 0x10cc1cec, 0x10dc253c, 0x1b32bd84, 0x1b2f6d85, 0x10e17c0b, 0x10f17c8d, 0x1b25773d, 

-	0x1b22230e, 0x10f6d0c0, 0x1106c96a, 0x1b182038, 0x1b14c7da, 0x110c1afe, 0x111c0bc6, 0x1b0ab87c, 

-	0x1b075bf1, 0x11215ab8, 0x11314395, 0x1afd4012, 0x1af9df5d, 0x11368fe1, 0x114670c8, 0x1aefb702, 

-	0x1aec5225, 0x114bba6b, 0x115b9354, 0x1ae21d54, 0x1adeb451, 0x1160da4b, 0x1170ab2a, 0x1ad47311, 

-	0x1ad105e9, 0x1175ef72, 0x1185b83f, 0x1ac6b841, 0x1ac346f8, 0x118af9d4, 0x119aba84, 0x1ab8ecec, 

-	0x1ab57784, 0x119ff964, 0x11afb1ee, 0x1aab111c, 0x1aa79796, 0x11b4ee14, 0x11c49e6f, 0x1a9d24d9, 

-	0x1a99a737, 0x11c9d7d9, 0x11d97ff9, 0x1a8f282b, 0x1a8ba670, 0x11deb6a4, 0x11ee5682, 0x1a811b1b, 

-	0x1a7d9549, 0x11f38a6a, 0x120321fa, 0x1a72fdb2, 0x1a6f73ca, 0x1208531c, 0x1217e256, 0x1a64cff8, 

-	0x1a6141fd, 0x121d10af, 0x122c9789, 0x1a5691f5, 0x1a52ffeb, 0x1231c316, 0x12414186, 0x1a4843b4, 

-	0x1a44ad9b, 0x12466a44, 0x1255e041, 0x1a39e53d, 0x1a364b17, 0x125b062b, 0x126a73ac, 0x1a2b7698, 

-	0x1a27d868, 0x126f96c1, 0x127efbbb, 0x1a1cf7ce, 0x1a195597, 0x12841bf6, 0x12937861, 0x1a0e68e9, 

-	0x1a0ac2ac, 0x129895c0, 0x12a7e991, 0x19ffc9f1, 0x19fc1fb1, 0x12ad0412, 0x12bc4f40, 0x19f11af0, 

-	0x19ed6caf, 0x12c166de, 0x12d0a960, 0x19e25bee, 0x19dea9ae, 0x12d5be18, 0x12e4f7e5, 0x19d38cf4, 

-	0x19cfd6b8, 0x12ea09b4, 0x12f93ac2, 0x19c4ae0c, 0x19c0f3d6, 0x12fe49a6, 0x130d71eb, 0x19b5bf3f, 

-	0x19b20111, 0x13127de0, 0x13219d53, 0x19a6c096, 0x19a2fe73, 0x1326a656, 0x1335bcef, 0x1997b21b, 

-	0x1993ec04, 0x133ac2fc, 0x1349d0b0, 0x198893d6, 0x1984c9ce, 0x134ed3c5, 0x135dd88c, 0x197965d0, 

-	0x197597da, 0x1362d8a6, 0x1371d476, 0x196a2815, 0x19665632, 0x1376d191, 0x1385c461, 0x195adaab, 

-	0x195704df, 0x138abe7b, 0x1399a841, 0x194b7d9e, 0x1947a3eb, 0x139e9f56, 0x13ad800a, 0x193c10f7, 

-	0x1938335e, 0x13b27417, 0x13c14bb0, 0x192c94bf, 0x1928b343, 0x13c63cb2, 0x13d50b26, 0x191d08ff, 

-	0x191923a3, 0x13d9f91b, 0x13e8be60, 0x190d6dc1, 0x19098488, 0x13eda944, 0x13fc6553, 0x18fdc310, 

-	0x18f9d5fa, 0x14014d23, 0x140ffff1, 0x18ee08f4, 0x18ea1805, 0x1414e4aa, 0x14238e2f, 0x18de3f77, 

-	0x18da4ab2, 0x14286fce, 0x14371001, 0x18ce66a3, 0x18ca6e0a, 0x143bee83, 0x144a855b, 0x18be7e82, 

-	0x18ba8217, 0x144f60bd, 0x145dee30, 0x18ae871e, 0x18aa86e3, 0x1462c670, 0x14714a76, 0x189e8080, 

-	0x189a7c78, 0x14761f8f, 0x14849a1f, 0x188e6ab2, 0x188a62e0, 0x14896c0f, 0x1497dd20, 0x187e45be, 

-	0x187a3a25, 0x149cabe4, 0x14ab136d, 0x186e11af, 0x186a0250, 0x14afdf03, 0x14be3cfa, 0x185dce8e, 

-	0x1859bb6c, 0x14c3055e, 0x14d159bc, 0x184d7c65, 0x18496583, 0x14d61eeb, 0x14e469a6, 0x183d1b3e, 

-	0x1839009e, 0x14e92b9e, 0x14f76cad, 0x182cab24, 0x18288cc8, 0x14fc2b6a, 0x150a62c6, 0x181c2c20, 

-	0x18180a0c, 0x150f1e45, 0x151d4be3, 0x180b9e3d, 0x18077873, 0x15220422, 0x153027fb, 0x17fb0185, 

-	0x17f6d807, 0x1534dcf6, 0x1542f700, 0x17ea5602, 0x17e628d3, 0x1547a8b5, 0x1555b8e8, 0x17d99bbe, 

-	0x17d56ae0, 0x155a6754, 0x15686da7, 0x17c8d2c4, 0x17c49e3b, 0x156d18c7, 0x157b1532, 0x17b7fb1f, 

-	0x17b3c2ec, 0x157fbd03, 0x158daf7c, 0x17a714d7, 0x17a2d8fe, 0x159253fb, 0x15a03c7a, 0x17961ff9, 

-	0x1791e07b, 0x15a4dda5, 0x15b2bc22, 0x17851c8e, 0x1780d96f, 0x15b759f5, 0x15c52e67, 0x17740aa1, 

-	0x176fc3e3, 0x15c9c8e0, 0x15d7933f, 0x1762ea3d, 0x175e9fe2, 0x15dc2a5a, 0x15e9ea9d, 0x1751bb6b, 

-	0x174d6d77, 0x15ee7e58, 0x15fc3477, 0x17407e37, 0x173c2cac, 0x1600c4cf, 0x160e70c1, 0x172f32ab, 

-	0x172add8c, 0x1612fdb3, 0x16209f70, 0x171dd8d2, 0x17198021, 0x162528fa, 0x1632c078, 0x170c70b7, 

-	0x17081477, 0x16374697, 0x1644d3d0, 0x16fafa64, 0x16f69a97, 0x16495680, 0x1656d96a, 0x16e975e4, 

-	0x16e5128e, 0x165b58aa, 0x1668d13e, 0x16d7e341, 0x16d37c65, 0x166d4d0a, 0x167abb3e, 0x16c64288, 

-	0x16c1d827, 0x167f3394, 0x168c9760, 0x16b493c2, 0x16b025e0, 0x16910c3d, 0x169e659a, 0x16a2d6fb

-};

-

-const int twidTab512[8*6 + 32*6 + 128*6] = {

-	0x20000000, 0x00000000, 0x1d906bcf, 0x0c3ef153, 0x16a09e66, 0x16a09e66, 0x0c3ef153, 0x1d906bcf, 
-	0x20000000, 0x00000000, 0x1f6297d0, 0x063e2e0f, 0x1d906bcf, 0x0c3ef153, 0x1a9b6629, 0x11c73b3a, 
-	0x20000000, 0x00000000, 0x1a9b6629, 0x11c73b3a, 0x0c3ef153, 0x1d906bcf, 0xf9c1d1f1, 0x1f6297d0, 
-	0x00000000, 0x20000000, 0xf3c10ead, 0x1d906bcf, 0xe95f619a, 0x16a09e66, 0xe26f9431, 0x0c3ef153, 
-	0x16a09e66, 0x16a09e66, 0x11c73b3a, 0x1a9b6629, 0x0c3ef153, 0x1d906bcf, 0x063e2e0f, 0x1f6297d0, 
-	0xe95f619a, 0x16a09e66, 0xe09d6830, 0x063e2e0f, 0xe26f9431, 0xf3c10ead, 0xee38c4c6, 0xe56499d7, 
+#include "aac_rom.h"
 
-	0x20000000, 0x00000000, 0x1fd88da4, 0x0322f4d8, 0x1f6297d0, 0x063e2e0f, 0x1e9f4157, 0x094a0317, 
-	0x20000000, 0x00000000, 0x1ff621e3, 0x0191f65f, 0x1fd88da4, 0x0322f4d8, 0x1fa7557f, 0x04b2041c, 
-	0x20000000, 0x00000000, 0x1fa7557f, 0x04b2041c, 0x1e9f4157, 0x094a0317, 0x1ced7af4, 0x0dae8805, 
-	0x1d906bcf, 0x0c3ef153, 0x1c38b2f2, 0x0f15ae9c, 0x1a9b6629, 0x11c73b3a, 0x18bc806b, 0x144cf325, 
-	0x1f6297d0, 0x063e2e0f, 0x1f0a7efc, 0x07c67e5f, 0x1e9f4157, 0x094a0317, 0x1e212105, 0x0ac7cd3b, 
-	0x1a9b6629, 0x11c73b3a, 0x17b5df22, 0x157d6935, 0x144cf325, 0x18bc806b, 0x10738799, 0x1b728345, 
-	0x16a09e66, 0x16a09e66, 0x144cf325, 0x18bc806b, 0x11c73b3a, 0x1a9b6629, 0x0f15ae9c, 0x1c38b2f2, 
-	0x1d906bcf, 0x0c3ef153, 0x1ced7af4, 0x0dae8805, 0x1c38b2f2, 0x0f15ae9c, 0x1b728345, 0x10738799, 
-	0x0c3ef153, 0x1d906bcf, 0x07c67e5f, 0x1f0a7efc, 0x0322f4d8, 0x1fd88da4, 0xfe6e09a1, 0x1ff621e3, 
-	0x0c3ef153, 0x1d906bcf, 0x094a0317, 0x1e9f4157, 0x063e2e0f, 0x1f6297d0, 0x0322f4d8, 0x1fd88da4, 
-	0x1a9b6629, 0x11c73b3a, 0x19b3e048, 0x130ff7fd, 0x18bc806b, 0x144cf325, 0x17b5df22, 0x157d6935, 
-	0xf9c1d1f1, 0x1f6297d0, 0xf53832c5, 0x1e212105, 0xf0ea5164, 0x1c38b2f2, 0xecf00803, 0x19b3e048, 
-	0x00000000, 0x20000000, 0xfcdd0b28, 0x1fd88da4, 0xf9c1d1f1, 0x1f6297d0, 0xf6b5fce9, 0x1e9f4157, 
-	0x16a09e66, 0x16a09e66, 0x157d6935, 0x17b5df22, 0x144cf325, 0x18bc806b, 0x130ff7fd, 0x19b3e048, 
-	0xe95f619a, 0x16a09e66, 0xe64c1fb8, 0x130ff7fd, 0xe3c74d0e, 0x0f15ae9c, 0xe1dedefb, 0x0ac7cd3b, 
-	0xf3c10ead, 0x1d906bcf, 0xf0ea5164, 0x1c38b2f2, 0xee38c4c6, 0x1a9b6629, 0xebb30cdb, 0x18bc806b, 
-	0x11c73b3a, 0x1a9b6629, 0x10738799, 0x1b728345, 0x0f15ae9c, 0x1c38b2f2, 0x0dae8805, 0x1ced7af4, 
-	0xe09d6830, 0x063e2e0f, 0xe009de1d, 0x0191f65f, 0xe027725c, 0xfcdd0b28, 0xe0f58104, 0xf83981a1, 
-	0xe95f619a, 0x16a09e66, 0xe7437f95, 0x144cf325, 0xe56499d7, 0x11c73b3a, 0xe3c74d0e, 0x0f15ae9c, 
-	0x0c3ef153, 0x1d906bcf, 0x0ac7cd3b, 0x1e212105, 0x094a0317, 0x1e9f4157, 0x07c67e5f, 0x1f0a7efc, 
-	0xe26f9431, 0xf3c10ead, 0xe48d7cbb, 0xef8c7867, 0xe7437f95, 0xebb30cdb, 0xea8296cb, 0xe84a20de, 
-	0xe26f9431, 0x0c3ef153, 0xe160bea9, 0x094a0317, 0xe09d6830, 0x063e2e0f, 0xe027725c, 0x0322f4d8, 
-	0x063e2e0f, 0x1f6297d0, 0x04b2041c, 0x1fa7557f, 0x0322f4d8, 0x1fd88da4, 0x0191f65f, 0x1ff621e3, 
-	0xee38c4c6, 0xe56499d7, 0xf25177fb, 0xe312850c, 0xf6b5fce9, 0xe160bea9, 0xfb4dfbe4, 0xe058aa81, 
+#if defined (ARMV5E) && !defined (ARMV7Neon)
 
-	0x20000000, 0x00000000, 0x1ffd8861, 0x00c90ab0, 0x1ff621e3, 0x0191f65f, 0x1fe9cdad, 0x025aa412, 
-	0x20000000, 0x00000000, 0x1fff6217, 0x00648748, 0x1ffd8861, 0x00c90ab0, 0x1ffa72f0, 0x012d8657, 
-	0x20000000, 0x00000000, 0x1ffa72f0, 0x012d8657, 0x1fe9cdad, 0x025aa412, 0x1fce15fd, 0x0386f0b9, 
-	0x1fd88da4, 0x0322f4d8, 0x1fc26471, 0x03eac9cb, 0x1fa7557f, 0x04b2041c, 0x1f8764fa, 0x05788511, 
-	0x1ff621e3, 0x0191f65f, 0x1ff09566, 0x01f656e8, 0x1fe9cdad, 0x025aa412, 0x1fe1cafd, 0x02beda01, 
-	0x1fa7557f, 0x04b2041c, 0x1f7599a4, 0x05db7678, 0x1f38f3ac, 0x0702e09b, 0x1ef178a4, 0x0827dc07, 
-	0x1f6297d0, 0x063e2e0f, 0x1f38f3ac, 0x0702e09b, 0x1f0a7efc, 0x07c67e5f, 0x1ed740e7, 0x0888e931, 
-	0x1fd88da4, 0x0322f4d8, 0x1fce15fd, 0x0386f0b9, 0x1fc26471, 0x03eac9cb, 0x1fb57972, 0x044e7c34, 
-	0x1e9f4157, 0x094a0317, 0x1e426a4b, 0x0a68f121, 0x1ddb13b7, 0x0b844298, 0x1d696174, 0x0c9b9532, 
-	0x1e9f4157, 0x094a0317, 0x1e6288ec, 0x0a09ae4a, 0x1e212105, 0x0ac7cd3b, 0x1ddb13b7, 0x0b844298, 
-	0x1fa7557f, 0x04b2041c, 0x1f97f925, 0x05155dac, 0x1f8764fa, 0x05788511, 0x1f7599a4, 0x05db7678, 
-	0x1ced7af4, 0x0dae8805, 0x1c678b35, 0x0ebcbbae, 0x1bd7c0ac, 0x0fc5d26e, 0x1b3e4d3f, 0x10c9704d, 
-	0x1d906bcf, 0x0c3ef153, 0x1d4134d1, 0x0cf7bca2, 0x1ced7af4, 0x0dae8805, 0x1c954b21, 0x0e63374d, 
-	0x1f6297d0, 0x063e2e0f, 0x1f4e603b, 0x06a0a809, 0x1f38f3ac, 0x0702e09b, 0x1f2252f7, 0x0764d3f9, 
-	0x1a9b6629, 0x11c73b3a, 0x19ef43ef, 0x12bedb26, 0x193a224a, 0x13affa29, 0x187c4010, 0x149a449c, 
-	0x1c38b2f2, 0x0f15ae9c, 0x1bd7c0ac, 0x0fc5d26e, 0x1b728345, 0x10738799, 0x1b090a58, 0x111eb354, 
-	0x1f0a7efc, 0x07c67e5f, 0x1ef178a4, 0x0827dc07, 0x1ed740e7, 0x0888e931, 0x1ebbd8c9, 0x08e9a220, 
-	0x17b5df22, 0x157d6935, 0x16e74455, 0x16591926, 0x1610b755, 0x172d0838, 0x15328293, 0x17f8ece3, 
-	0x1a9b6629, 0x11c73b3a, 0x1a29a7a0, 0x126d054d, 0x19b3e048, 0x130ff7fd, 0x193a224a, 0x13affa29, 
-	0x1e9f4157, 0x094a0317, 0x1e817bab, 0x09aa0861, 0x1e6288ec, 0x0a09ae4a, 0x1e426a4b, 0x0a68f121, 
-	0x144cf325, 0x18bc806b, 0x136058b1, 0x19777ef5, 0x126d054d, 0x1a29a7a0, 0x11734d64, 0x1ad2bc9e, 
-	0x18bc806b, 0x144cf325, 0x183b0e0c, 0x14e6cabc, 0x17b5df22, 0x157d6935, 0x172d0838, 0x1610b755, 
-	0x1e212105, 0x0ac7cd3b, 0x1dfeae62, 0x0b263eef, 0x1ddb13b7, 0x0b844298, 0x1db65262, 0x0be1d499, 
-	0x10738799, 0x1b728345, 0x0f6e0ca9, 0x1c08c426, 0x0e63374d, 0x1c954b21, 0x0d536416, 0x1d17e774, 
-	0x16a09e66, 0x16a09e66, 0x1610b755, 0x172d0838, 0x157d6935, 0x17b5df22, 0x14e6cabc, 0x183b0e0c, 
-	0x1d906bcf, 0x0c3ef153, 0x1d696174, 0x0c9b9532, 0x1d4134d1, 0x0cf7bca2, 0x1d17e774, 0x0d536416, 
-	0x0c3ef153, 0x1d906bcf, 0x0b263eef, 0x1dfeae62, 0x0a09ae4a, 0x1e6288ec, 0x08e9a220, 0x1ebbd8c9, 
-	0x144cf325, 0x18bc806b, 0x13affa29, 0x193a224a, 0x130ff7fd, 0x19b3e048, 0x126d054d, 0x1a29a7a0, 
-	0x1ced7af4, 0x0dae8805, 0x1cc1f0f4, 0x0e0924ec, 0x1c954b21, 0x0e63374d, 0x1c678b35, 0x0ebcbbae, 
-	0x07c67e5f, 0x1f0a7efc, 0x06a0a809, 0x1f4e603b, 0x05788511, 0x1f8764fa, 0x044e7c34, 0x1fb57972, 
-	0x11c73b3a, 0x1a9b6629, 0x111eb354, 0x1b090a58, 0x10738799, 0x1b728345, 0x0fc5d26e, 0x1bd7c0ac, 
-	0x1c38b2f2, 0x0f15ae9c, 0x1c08c426, 0x0f6e0ca9, 0x1bd7c0ac, 0x0fc5d26e, 0x1ba5aa67, 0x101cfc87, 
-	0x0322f4d8, 0x1fd88da4, 0x01f656e8, 0x1ff09566, 0x00c90ab0, 0x1ffd8861, 0xff9b78b8, 0x1fff6217, 
-	0x0f15ae9c, 0x1c38b2f2, 0x0e63374d, 0x1c954b21, 0x0dae8805, 0x1ced7af4, 0x0cf7bca2, 0x1d4134d1, 
-	0x1b728345, 0x10738799, 0x1b3e4d3f, 0x10c9704d, 0x1b090a58, 0x111eb354, 0x1ad2bc9e, 0x11734d64, 
-	0xfe6e09a1, 0x1ff621e3, 0xfd4125ff, 0x1fe1cafd, 0xfc153635, 0x1fc26471, 0xfaeaa254, 0x1f97f925, 
-	0x0c3ef153, 0x1d906bcf, 0x0b844298, 0x1ddb13b7, 0x0ac7cd3b, 0x1e212105, 0x0a09ae4a, 0x1e6288ec, 
-	0x1a9b6629, 0x11c73b3a, 0x1a63091b, 0x121a7999, 0x1a29a7a0, 0x126d054d, 0x19ef43ef, 0x12bedb26, 
-	0xf9c1d1f1, 0x1f6297d0, 0xf89b2c07, 0x1f2252f7, 0xf77716cf, 0x1ed740e7, 0xf655f79f, 0x1e817bab, 
-	0x094a0317, 0x1e9f4157, 0x0888e931, 0x1ed740e7, 0x07c67e5f, 0x1f0a7efc, 0x0702e09b, 0x1f38f3ac, 
-	0x19b3e048, 0x130ff7fd, 0x19777ef5, 0x136058b1, 0x193a224a, 0x13affa29, 0x18fbcca4, 0x13fed953, 
-	0xf53832c5, 0x1e212105, 0xf41e2b67, 0x1db65262, 0xf308435e, 0x1d4134d1, 0xf1f6db14, 0x1cc1f0f4, 
-	0x063e2e0f, 0x1f6297d0, 0x05788511, 0x1f8764fa, 0x04b2041c, 0x1fa7557f, 0x03eac9cb, 0x1fc26471, 
-	0x18bc806b, 0x144cf325, 0x187c4010, 0x149a449c, 0x183b0e0c, 0x14e6cabc, 0x17f8ece3, 0x15328293, 
-	0xf0ea5164, 0x1c38b2f2, 0xefe30379, 0x1ba5aa67, 0xeee14cac, 0x1b090a58, 0xede58667, 0x1a63091b, 
-	0x0322f4d8, 0x1fd88da4, 0x025aa412, 0x1fe9cdad, 0x0191f65f, 0x1ff621e3, 0x00c90ab0, 0x1ffd8861, 
-	0x17b5df22, 0x157d6935, 0x1771e75f, 0x15c77bbe, 0x172d0838, 0x1610b755, 0x16e74455, 0x16591926, 
-	0xecf00803, 0x19b3e048, 0xec0126ad, 0x18fbcca4, 0xeb193544, 0x183b0e0c, 0xea388442, 0x1771e75f, 
-	0x00000000, 0x20000000, 0xff36f550, 0x1ffd8861, 0xfe6e09a1, 0x1ff621e3, 0xfda55bee, 0x1fe9cdad, 
-	0x16a09e66, 0x16a09e66, 0x16591926, 0x16e74455, 0x1610b755, 0x172d0838, 0x15c77bbe, 0x1771e75f, 
-	0xe95f619a, 0x16a09e66, 0xe88e18a1, 0x15c77bbe, 0xe7c4f1f4, 0x14e6cabc, 0xe704335c, 0x13fed953, 
-	0xfcdd0b28, 0x1fd88da4, 0xfc153635, 0x1fc26471, 0xfb4dfbe4, 0x1fa7557f, 0xfa877aef, 0x1f8764fa, 
-	0x157d6935, 0x17b5df22, 0x15328293, 0x17f8ece3, 0x14e6cabc, 0x183b0e0c, 0x149a449c, 0x187c4010, 
-	0xe64c1fb8, 0x130ff7fd, 0xe59cf6e5, 0x121a7999, 0xe4f6f5a8, 0x111eb354, 0xe45a5599, 0x101cfc87, 
-	0xf9c1d1f1, 0x1f6297d0, 0xf8fd1f65, 0x1f38f3ac, 0xf83981a1, 0x1f0a7efc, 0xf77716cf, 0x1ed740e7, 
-	0x144cf325, 0x18bc806b, 0x13fed953, 0x18fbcca4, 0x13affa29, 0x193a224a, 0x136058b1, 0x19777ef5, 
-	0xe3c74d0e, 0x0f15ae9c, 0xe33e0f0c, 0x0e0924ec, 0xe2becb2f, 0x0cf7bca2, 0xe249ad9e, 0x0be1d499, 
-	0xf6b5fce9, 0x1e9f4157, 0xf5f651b6, 0x1e6288ec, 0xf53832c5, 0x1e212105, 0xf47bbd68, 0x1ddb13b7, 
-	0x130ff7fd, 0x19b3e048, 0x12bedb26, 0x19ef43ef, 0x126d054d, 0x1a29a7a0, 0x121a7999, 0x1a63091b, 
-	0xe1dedefb, 0x0ac7cd3b, 0xe17e8455, 0x09aa0861, 0xe128bf19, 0x0888e931, 0xe0ddad09, 0x0764d3f9, 
-	0xf3c10ead, 0x1d906bcf, 0xf308435e, 0x1d4134d1, 0xf25177fb, 0x1ced7af4, 0xf19cc8b3, 0x1c954b21, 
-	0x11c73b3a, 0x1a9b6629, 0x11734d64, 0x1ad2bc9e, 0x111eb354, 0x1b090a58, 0x10c9704d, 0x1b3e4d3f, 
-	0xe09d6830, 0x063e2e0f, 0xe06806db, 0x05155dac, 0xe03d9b8f, 0x03eac9cb, 0xe01e3503, 0x02beda01, 
-	0xf0ea5164, 0x1c38b2f2, 0xf03a2d92, 0x1bd7c0ac, 0xef8c7867, 0x1b728345, 0xeee14cac, 0x1b090a58, 
-	0x10738799, 0x1b728345, 0x101cfc87, 0x1ba5aa67, 0x0fc5d26e, 0x1bd7c0ac, 0x0f6e0ca9, 0x1c08c426, 
-	0xe009de1d, 0x0191f65f, 0xe0009de9, 0x00648748, 0xe002779f, 0xff36f550, 0xe00f6a9a, 0xfe09a918, 
-	0xee38c4c6, 0x1a9b6629, 0xed92fab3, 0x1a29a7a0, 0xecf00803, 0x19b3e048, 0xec5005d7, 0x193a224a, 
-	0x0f15ae9c, 0x1c38b2f2, 0x0ebcbbae, 0x1c678b35, 0x0e63374d, 0x1c954b21, 0x0e0924ec, 0x1cc1f0f4, 
-	0xe027725c, 0xfcdd0b28, 0xe04a868e, 0xfbb183cc, 0xe0789b06, 0xfa877aef, 0xe0b19fc5, 0xf95f57f7, 
-	0xebb30cdb, 0x18bc806b, 0xeb193544, 0x183b0e0c, 0xea8296cb, 0x17b5df22, 0xe9ef48ab, 0x172d0838, 
-	0x0dae8805, 0x1ced7af4, 0x0d536416, 0x1d17e774, 0x0cf7bca2, 0x1d4134d1, 0x0c9b9532, 0x1d696174, 
-	0xe0f58104, 0xf83981a1, 0xe1442737, 0xf7165de0, 0xe19d7714, 0xf5f651b6, 0xe201519e, 0xf4d9c111, 
-	0xe95f619a, 0x16a09e66, 0xe8d2f7c8, 0x1610b755, 0xe84a20de, 0x157d6935, 0xe7c4f1f4, 0x14e6cabc, 
-	0x0c3ef153, 0x1d906bcf, 0x0be1d499, 0x1db65262, 0x0b844298, 0x1ddb13b7, 0x0b263eef, 0x1dfeae62, 
-	0xe26f9431, 0xf3c10ead, 0xe2e8188c, 0xf2ac9bea, 0xe36ab4df, 0xf19cc8b3, 0xe3f73bda, 0xf091f357, 
-	0xe7437f95, 0x144cf325, 0xe6c5ddb6, 0x13affa29, 0xe64c1fb8, 0x130ff7fd, 0xe5d65860, 0x126d054d, 
-	0x0ac7cd3b, 0x1e212105, 0x0a68f121, 0x1e426a4b, 0x0a09ae4a, 0x1e6288ec, 0x09aa0861, 0x1e817bab, 
-	0xe48d7cbb, 0xef8c7867, 0xe52d4362, 0xee8cb29c, 0xe5d65860, 0xed92fab3, 0xe688810b, 0xec9fa74f, 
-	0xe56499d7, 0x11c73b3a, 0xe4f6f5a8, 0x111eb354, 0xe48d7cbb, 0x10738799, 0xe4283f54, 0x0fc5d26e, 
-	0x094a0317, 0x1e9f4157, 0x08e9a220, 0x1ebbd8c9, 0x0888e931, 0x1ed740e7, 0x0827dc07, 0x1ef178a4, 
-	0xe7437f95, 0xebb30cdb, 0xe807131d, 0xeacd7d6d, 0xe8d2f7c8, 0xe9ef48ab, 0xe9a6e6da, 0xe918bbab, 
-	0xe3c74d0e, 0x0f15ae9c, 0xe36ab4df, 0x0e63374d, 0xe312850c, 0x0dae8805, 0xe2becb2f, 0x0cf7bca2, 
-	0x07c67e5f, 0x1f0a7efc, 0x0764d3f9, 0x1f2252f7, 0x0702e09b, 0x1f38f3ac, 0x06a0a809, 0x1f4e603b, 
-	0xea8296cb, 0xe84a20de, 0xeb65bb64, 0xe783bff0, 0xec5005d7, 0xe6c5ddb6, 0xed4124da, 0xe610bc11, 
-	0xe26f9431, 0x0c3ef153, 0xe224ec49, 0x0b844298, 0xe1dedefb, 0x0ac7cd3b, 0xe19d7714, 0x0a09ae4a, 
-	0x063e2e0f, 0x1f6297d0, 0x05db7678, 0x1f7599a4, 0x05788511, 0x1f8764fa, 0x05155dac, 0x1f97f925, 
-	0xee38c4c6, 0xe56499d7, 0xef368fb3, 0xe4c1b2c1, 0xf03a2d92, 0xe4283f54, 0xf1434452, 0xe39874cb, 
-	0xe160bea9, 0x094a0317, 0xe128bf19, 0x0888e931, 0xe0f58104, 0x07c67e5f, 0xe0c70c54, 0x0702e09b, 
-	0x04b2041c, 0x1fa7557f, 0x044e7c34, 0x1fb57972, 0x03eac9cb, 0x1fc26471, 0x0386f0b9, 0x1fce15fd, 
-	0xf25177fb, 0xe312850c, 0xf3646ace, 0xe2969e8c, 0xf47bbd68, 0xe224ec49, 0xf5970edf, 0xe1bd95b5, 
-	0xe09d6830, 0x063e2e0f, 0xe0789b06, 0x05788511, 0xe058aa81, 0x04b2041c, 0xe03d9b8f, 0x03eac9cb, 
-	0x0322f4d8, 0x1fd88da4, 0x02beda01, 0x1fe1cafd, 0x025aa412, 0x1fe9cdad, 0x01f656e8, 0x1ff09566, 
-	0xf6b5fce9, 0xe160bea9, 0xf7d823f9, 0xe10e875c, 0xf8fd1f65, 0xe0c70c54, 0xfa248988, 0xe08a665c, 
-	0xe027725c, 0x0322f4d8, 0xe0163253, 0x025aa412, 0xe009de1d, 0x0191f65f, 0xe002779f, 0x00c90ab0, 
-	0x0191f65f, 0x1ff621e3, 0x012d8657, 0x1ffa72f0, 0x00c90ab0, 0x1ffd8861, 0x00648748, 0x1fff6217, 
-	0xfb4dfbe4, 0xe058aa81, 0xfc790f47, 0xe031ea03, 0xfda55bee, 0xe0163253, 0xfed279a9, 0xe0058d10

-};

-

-const int twidTab64[4*6 + 16*6] = {

-	0x20000000, 0x00000000, 0x16a09e66, 0x16a09e66, 0x00000000, 0x20000000, 0xe95f619a, 0x16a09e66, 
-	0x20000000, 0x00000000, 0x1d906bcf, 0x0c3ef153, 0x16a09e66, 0x16a09e66, 0x0c3ef153, 0x1d906bcf, 
-	0x20000000, 0x00000000, 0x0c3ef153, 0x1d906bcf, 0xe95f619a, 0x16a09e66, 0xe26f9431, 0xf3c10ead, 
+/*
+ *  Q30 for 128 and 1024
+ *
+ * for (i = 0; i < num/4; i++) {
+ *   angle = (i + 0.125) * M_PI / num;
+ *   x = cos(angle) * (1 << 30);
+ *   x = sin(angle) * (1 << 30);
+ *
+ *   angle = (num/2 - 1 - i + 0.125) * M_PI / num;
+ *   x = cos(angle) * (1 << 30);
+ *   x = sin(angle) * (1 << 30);
+ * }
+ */
+const int cossintab[128 + 1024] = {
+	/* 128 */
+	0x3fffec43, 0x003243f1, 0x015fd4d2, 0x3ffc38d1, 0x3ff9c13a, 0x01c454f5, 0x02f1b755, 0x3feea776,
+	0x3fe9b8a9, 0x03562038, 0x0483259d, 0x3fd73a4a, 0x3fcfd50b, 0x04e767c5, 0x0613e1c5, 0x3fb5f4ea,
+	0x3fac1a5b, 0x0677edbb, 0x07a3adff, 0x3f8adc77, 0x3f7e8e1e, 0x08077457, 0x09324ca7, 0x3f55f796,
+	0x3f473759, 0x0995bdfd, 0x0abf8043, 0x3f174e70, 0x3f061e95, 0x0b228d42, 0x0c4b0b94, 0x3eceeaad,
+	0x3ebb4ddb, 0x0cada4f5, 0x0dd4b19a, 0x3e7cd778, 0x3e66d0b4, 0x0e36c82a, 0x0f5c35a3, 0x3e212179,
+	0x3e08b42a, 0x0fbdba40, 0x10e15b4e, 0x3dbbd6d4, 0x3da106bd, 0x11423ef0, 0x1263e699, 0x3d4d0728,
+	0x3d2fd86c, 0x12c41a4f, 0x13e39be9, 0x3cd4c38b, 0x3cb53aaa, 0x144310dd, 0x15604013, 0x3c531e88,
+	0x3c314060, 0x15bee78c, 0x16d99864, 0x3bc82c1f, 0x3ba3fde7, 0x173763c9, 0x184f6aab, 0x3b3401bb,
+	0x3b0d8909, 0x18ac4b87, 0x19c17d44, 0x3a96b636, 0x3a6df8f8, 0x1a1d6544, 0x1b2f971e, 0x39f061d2,
+	0x39c5664f, 0x1b8a7815, 0x1c997fc4, 0x39411e33, 0x3913eb0e, 0x1cf34baf, 0x1dfeff67, 0x38890663,
+	0x3859a292, 0x1e57a86d, 0x1f5fdee6, 0x37c836c2, 0x3796a996, 0x1fb7575c, 0x20bbe7d8, 0x36fecd0e,
+	0x36cb1e2a, 0x21122240, 0x2212e492, 0x362ce855, 0x35f71fb1, 0x2267d3a0, 0x2364a02e, 0x3552a8f4,
+	0x351acedd, 0x23b836ca, 0x24b0e699, 0x34703095, 0x34364da6, 0x250317df, 0x25f78497, 0x3385a222,
+	0x3349bf48, 0x264843d9, 0x273847c8, 0x329321c7, 0x32554840, 0x27878893, 0x2872feb6, 0x3198d4ea,
+	0x31590e3e, 0x28c0b4d2, 0x29a778db, 0x3096e223, 0x30553828, 0x29f3984c, 0x2ad586a3, 0x2f8d713a,
+	0x2f49ee0f, 0x2b2003ac, 0x2bfcf97c, 0x2e7cab1c, 0x2e37592c, 0x2c45c8a0, 0x2d1da3d5, 0x2d64b9da,
+	/* 1024 */
+	0x3fffffb1, 0x0006487f, 0x002bfb74, 0x3ffff0e3, 0x3fffe705, 0x00388c6e, 0x005e3f4c, 0x3fffba9b,
+	0x3fffa6de, 0x006ad03b, 0x009082ea, 0x3fff5cd8, 0x3fff3f3c, 0x009d13c5, 0x00c2c62f, 0x3ffed79b,
+	0x3ffeb021, 0x00cf56ef, 0x00f508fc, 0x3ffe2ae5, 0x3ffdf98c, 0x01019998, 0x01274b31, 0x3ffd56b5,
+	0x3ffd1b7e, 0x0133dba3, 0x01598cb1, 0x3ffc5b0c, 0x3ffc15f7, 0x01661cf0, 0x018bcd5b, 0x3ffb37ec,
+	0x3ffae8f9, 0x01985d60, 0x01be0d11, 0x3ff9ed53, 0x3ff99483, 0x01ca9cd4, 0x01f04bb4, 0x3ff87b44,
+	0x3ff81896, 0x01fcdb2e, 0x02228924, 0x3ff6e1bf, 0x3ff67534, 0x022f184d, 0x0254c544, 0x3ff520c5,
+	0x3ff4aa5d, 0x02615414, 0x0286fff3, 0x3ff33858, 0x3ff2b813, 0x02938e62, 0x02b93914, 0x3ff12878,
+	0x3ff09e56, 0x02c5c71a, 0x02eb7086, 0x3feef126, 0x3fee5d28, 0x02f7fe1c, 0x031da62b, 0x3fec9265,
+	0x3febf48b, 0x032a3349, 0x034fd9e5, 0x3fea0c35, 0x3fe96480, 0x035c6682, 0x03820b93, 0x3fe75e98,
+	0x3fe6ad08, 0x038e97a9, 0x03b43b17, 0x3fe48990, 0x3fe3ce26, 0x03c0c69e, 0x03e66852, 0x3fe18d1f,
+	0x3fe0c7da, 0x03f2f342, 0x04189326, 0x3fde6945, 0x3fdd9a27, 0x04251d77, 0x044abb73, 0x3fdb1e06,
+	0x3fda450f, 0x0457451d, 0x047ce11a, 0x3fd7ab64, 0x3fd6c894, 0x04896a16, 0x04af03fc, 0x3fd4115f,
+	0x3fd324b7, 0x04bb8c42, 0x04e123fa, 0x3fd04ffc, 0x3fcf597c, 0x04edab83, 0x051340f6, 0x3fcc673b,
+	0x3fcb66e4, 0x051fc7b9, 0x05455ad1, 0x3fc8571f, 0x3fc74cf3, 0x0551e0c7, 0x0577716b, 0x3fc41fac,
+	0x3fc30baa, 0x0583f68c, 0x05a984a6, 0x3fbfc0e3, 0x3fbea30c, 0x05b608eb, 0x05db9463, 0x3fbb3ac7,
+	0x3fba131b, 0x05e817c3, 0x060da083, 0x3fb68d5b, 0x3fb55bdc, 0x061a22f7, 0x063fa8e7, 0x3fb1b8a2,
+	0x3fb07d50, 0x064c2a67, 0x0671ad71, 0x3facbc9f, 0x3fab777b, 0x067e2df5, 0x06a3ae00, 0x3fa79954,
+	0x3fa64a5f, 0x06b02d81, 0x06d5aa77, 0x3fa24ec6, 0x3fa0f600, 0x06e228ee, 0x0707a2b7, 0x3f9cdcf7,
+	0x3f9b7a62, 0x0714201b, 0x073996a1, 0x3f9743eb, 0x3f95d787, 0x074612eb, 0x076b8616, 0x3f9183a5,
+	0x3f900d72, 0x0778013d, 0x079d70f7, 0x3f8b9c28, 0x3f8a1c29, 0x07a9eaf5, 0x07cf5726, 0x3f858d79,
+	0x3f8403ae, 0x07dbcff2, 0x08013883, 0x3f7f579b, 0x3f7dc405, 0x080db016, 0x083314f1, 0x3f78fa92,
+	0x3f775d31, 0x083f8b43, 0x0864ec4f, 0x3f727661, 0x3f70cf38, 0x08716159, 0x0896be80, 0x3f6bcb0e,
+	0x3f6a1a1c, 0x08a3323a, 0x08c88b65, 0x3f64f89b, 0x3f633de2, 0x08d4fdc6, 0x08fa52de, 0x3f5dff0e,
+	0x3f5c3a8f, 0x0906c3e0, 0x092c14ce, 0x3f56de6a, 0x3f551026, 0x09388469, 0x095dd116, 0x3f4f96b4,
+	0x3f4dbeac, 0x096a3f42, 0x098f8796, 0x3f4827f0, 0x3f464626, 0x099bf44c, 0x09c13831, 0x3f409223,
+	0x3f3ea697, 0x09cda368, 0x09f2e2c7, 0x3f38d552, 0x3f36e006, 0x09ff4c78, 0x0a24873a, 0x3f30f181,
+	0x3f2ef276, 0x0a30ef5e, 0x0a56256c, 0x3f28e6b6, 0x3f26ddec, 0x0a628bfa, 0x0a87bd3d, 0x3f20b4f5,
+	0x3f1ea26e, 0x0a94222f, 0x0ab94e8f, 0x3f185c43, 0x3f164001, 0x0ac5b1dc, 0x0aead944, 0x3f0fdca5,
+	0x3f0db6a9, 0x0af73ae5, 0x0b1c5d3d, 0x3f073621, 0x3f05066d, 0x0b28bd2a, 0x0b4dda5c, 0x3efe68bc,
+	0x3efc2f50, 0x0b5a388d, 0x0b7f5081, 0x3ef5747b, 0x3ef3315a, 0x0b8bacf0, 0x0bb0bf8f, 0x3eec5965,
+	0x3eea0c8e, 0x0bbd1a33, 0x0be22766, 0x3ee3177e, 0x3ee0c0f4, 0x0bee8038, 0x0c1387e9, 0x3ed9aecc,
+	0x3ed74e91, 0x0c1fdee1, 0x0c44e0f9, 0x3ed01f55, 0x3ecdb56a, 0x0c513610, 0x0c763278, 0x3ec66920,
+	0x3ec3f585, 0x0c8285a5, 0x0ca77c47, 0x3ebc8c31, 0x3eba0ee9, 0x0cb3cd84, 0x0cd8be47, 0x3eb2888f,
+	0x3eb0019c, 0x0ce50d8c, 0x0d09f85b, 0x3ea85e41, 0x3ea5cda3, 0x0d1645a0, 0x0d3b2a64, 0x3e9e0d4c,
+	0x3e9b7306, 0x0d4775a1, 0x0d6c5443, 0x3e9395b7, 0x3e90f1ca, 0x0d789d71, 0x0d9d75db, 0x3e88f788,
+	0x3e8649f5, 0x0da9bcf2, 0x0dce8f0d, 0x3e7e32c6, 0x3e7b7b90, 0x0ddad406, 0x0dff9fba, 0x3e734778,
+	0x3e70869f, 0x0e0be28e, 0x0e30a7c5, 0x3e6835a4, 0x3e656b2b, 0x0e3ce86b, 0x0e61a70f, 0x3e5cfd51,
+	0x3e5a2939, 0x0e6de580, 0x0e929d7a, 0x3e519e86, 0x3e4ec0d1, 0x0e9ed9af, 0x0ec38ae8, 0x3e46194a,
+	0x3e4331fa, 0x0ecfc4d9, 0x0ef46f3b, 0x3e3a6da4, 0x3e377cbb, 0x0f00a6df, 0x0f254a53, 0x3e2e9b9c,
+	0x3e2ba11b, 0x0f317fa5, 0x0f561c15, 0x3e22a338, 0x3e1f9f21, 0x0f624f0c, 0x0f86e460, 0x3e168480,
+	0x3e1376d5, 0x0f9314f5, 0x0fb7a317, 0x3e0a3f7b, 0x3e07283f, 0x0fc3d143, 0x0fe8581d, 0x3dfdd432,
+	0x3dfab365, 0x0ff483d7, 0x10190352, 0x3df142ab, 0x3dee1851, 0x10252c94, 0x1049a49a, 0x3de48aef,
+	0x3de15708, 0x1055cb5b, 0x107a3bd5, 0x3dd7ad05, 0x3dd46f94, 0x1086600e, 0x10aac8e6, 0x3dcaa8f5,
+	0x3dc761fc, 0x10b6ea90, 0x10db4baf, 0x3dbd7ec7, 0x3dba2e48, 0x10e76ac3, 0x110bc413, 0x3db02e84,
+	0x3dacd481, 0x1117e088, 0x113c31f3, 0x3da2b834, 0x3d9f54af, 0x11484bc2, 0x116c9531, 0x3d951bde,
+	0x3d91aed9, 0x1178ac53, 0x119cedaf, 0x3d87598c, 0x3d83e309, 0x11a9021d, 0x11cd3b50, 0x3d797145,
+	0x3d75f147, 0x11d94d02, 0x11fd7df6, 0x3d6b6313, 0x3d67d99b, 0x12098ce5, 0x122db583, 0x3d5d2efe,
+	0x3d599c0e, 0x1239c1a7, 0x125de1da, 0x3d4ed50f, 0x3d4b38aa, 0x1269eb2b, 0x128e02dc, 0x3d40554e,
+	0x3d3caf76, 0x129a0954, 0x12be186c, 0x3d31afc5, 0x3d2e007c, 0x12ca1c03, 0x12ee226c, 0x3d22e47c,
+	0x3d1f2bc5, 0x12fa231b, 0x131e20c0, 0x3d13f37e, 0x3d10315a, 0x132a1e7e, 0x134e1348, 0x3d04dcd2,
+	0x3d011145, 0x135a0e0e, 0x137df9e7, 0x3cf5a082, 0x3cf1cb8e, 0x1389f1af, 0x13add481, 0x3ce63e98,
+	0x3ce2603f, 0x13b9c943, 0x13dda2f7, 0x3cd6b71e, 0x3cd2cf62, 0x13e994ab, 0x140d652c, 0x3cc70a1c,
+	0x3cc318ff, 0x141953cb, 0x143d1b02, 0x3cb7379c, 0x3cb33d22, 0x14490685, 0x146cc45c, 0x3ca73fa9,
+	0x3ca33bd3, 0x1478acbc, 0x149c611d, 0x3c97224c, 0x3c93151d, 0x14a84652, 0x14cbf127, 0x3c86df8e,
+	0x3c82c909, 0x14d7d32a, 0x14fb745e, 0x3c76777b, 0x3c7257a2, 0x15075327, 0x152aeaa3, 0x3c65ea1c,
+	0x3c61c0f1, 0x1536c62b, 0x155a53d9, 0x3c55377b, 0x3c510501, 0x15662c18, 0x1589afe3, 0x3c445fa2,
+	0x3c4023dd, 0x159584d3, 0x15b8fea4, 0x3c33629d, 0x3c2f1d8e, 0x15c4d03e, 0x15e83fff, 0x3c224075,
+	0x3c1df21f, 0x15f40e3a, 0x161773d6, 0x3c10f935, 0x3c0ca19b, 0x16233eac, 0x16469a0d, 0x3bff8ce8,
+	0x3bfb2c0c, 0x16526176, 0x1675b286, 0x3bedfb99, 0x3be9917e, 0x1681767c, 0x16a4bd25, 0x3bdc4552,
+	0x3bd7d1fa, 0x16b07d9f, 0x16d3b9cc, 0x3bca6a1d, 0x3bc5ed8d, 0x16df76c3, 0x1702a85e, 0x3bb86a08,
+	0x3bb3e440, 0x170e61cc, 0x173188be, 0x3ba6451b, 0x3ba1b620, 0x173d3e9b, 0x17605ad0, 0x3b93fb63,
+	0x3b8f6337, 0x176c0d15, 0x178f1e76, 0x3b818ceb, 0x3b7ceb90, 0x179acd1c, 0x17bdd394, 0x3b6ef9be,
+	0x3b6a4f38, 0x17c97e93, 0x17ec7a0d, 0x3b5c41e8, 0x3b578e39, 0x17f8215e, 0x181b11c4, 0x3b496574,
+	0x3b44a8a0, 0x1826b561, 0x18499a9d, 0x3b36646e, 0x3b319e77, 0x18553a7d, 0x1878147a, 0x3b233ee1,
+	0x3b1e6fca, 0x1883b097, 0x18a67f3f, 0x3b0ff4d9, 0x3b0b1ca6, 0x18b21791, 0x18d4dad0, 0x3afc8663,
+	0x3af7a516, 0x18e06f50, 0x1903270f, 0x3ae8f38b, 0x3ae40926, 0x190eb7b7, 0x193163e1, 0x3ad53c5b,
+	0x3ad048e3, 0x193cf0a9, 0x195f9128, 0x3ac160e1, 0x3abc6458, 0x196b1a09, 0x198daec8, 0x3aad6129,
+	0x3aa85b92, 0x199933bb, 0x19bbbca6, 0x3a993d3e, 0x3a942e9d, 0x19c73da3, 0x19e9baa3, 0x3a84f52f,
+	0x3a7fdd86, 0x19f537a4, 0x1a17a8a5, 0x3a708906, 0x3a6b6859, 0x1a2321a2, 0x1a45868e, 0x3a5bf8d1,
+	0x3a56cf23, 0x1a50fb81, 0x1a735442, 0x3a47449c, 0x3a4211f0, 0x1a7ec524, 0x1aa111a6, 0x3a326c74,
+	0x3a2d30cd, 0x1aac7e6f, 0x1acebe9d, 0x3a1d7066, 0x3a182bc8, 0x1ada2746, 0x1afc5b0a, 0x3a08507f,
+	0x3a0302ed, 0x1b07bf8c, 0x1b29e6d2, 0x39f30ccc, 0x39edb649, 0x1b354727, 0x1b5761d8, 0x39dda55a,
+	0x39d845e9, 0x1b62bdf8, 0x1b84cc01, 0x39c81a36, 0x39c2b1da, 0x1b9023e5, 0x1bb22530, 0x39b26b6d,
+	0x39acfa2b, 0x1bbd78d2, 0x1bdf6d4a, 0x399c990d, 0x39971ee7, 0x1beabca1, 0x1c0ca432, 0x3986a324,
+	0x3981201e, 0x1c17ef39, 0x1c39c9cd, 0x397089bf, 0x396afddc, 0x1c45107c, 0x1c66ddfe, 0x395a4ceb,
+	0x3954b82e, 0x1c72204f, 0x1c93e0ab, 0x3943ecb6, 0x393e4f23, 0x1c9f1e96, 0x1cc0d1b6, 0x392d692f,
+	0x3927c2c9, 0x1ccc0b35, 0x1cedb106, 0x3916c262, 0x3911132d, 0x1cf8e611, 0x1d1a7e7d, 0x38fff85e,
+	0x38fa405e, 0x1d25af0d, 0x1d473a00, 0x38e90b31, 0x38e34a69, 0x1d52660f, 0x1d73e374, 0x38d1fae9,
+	0x38cc315d, 0x1d7f0afb, 0x1da07abc, 0x38bac795, 0x38b4f547, 0x1dab9db5, 0x1dccffbf, 0x38a37142,
+	0x389d9637, 0x1dd81e21, 0x1df9725f, 0x388bf7ff, 0x3886143b, 0x1e048c24, 0x1e25d282, 0x38745bdb,
+	0x386e6f60, 0x1e30e7a4, 0x1e52200c, 0x385c9ce3, 0x3856a7b6, 0x1e5d3084, 0x1e7e5ae2, 0x3844bb28,
+	0x383ebd4c, 0x1e8966a8, 0x1eaa82e9, 0x382cb6b7, 0x3826b030, 0x1eb589f7, 0x1ed69805, 0x38148f9f,
+	0x380e8071, 0x1ee19a54, 0x1f029a1c, 0x37fc45ef, 0x37f62e1d, 0x1f0d97a5, 0x1f2e8911, 0x37e3d9b7,
+	0x37ddb945, 0x1f3981ce, 0x1f5a64cb, 0x37cb4b04, 0x37c521f6, 0x1f6558b5, 0x1f862d2d, 0x37b299e7,
+	0x37ac6841, 0x1f911c3d, 0x1fb1e21d, 0x3799c66f, 0x37938c34, 0x1fbccc4d, 0x1fdd8381, 0x3780d0aa,
+	0x377a8ddf, 0x1fe868c8, 0x2009113c, 0x3767b8a9, 0x37616d51, 0x2013f196, 0x20348b35, 0x374e7e7b,
+	0x37482a9a, 0x203f6699, 0x205ff14f, 0x3735222f, 0x372ec5c9, 0x206ac7b8, 0x208b4372, 0x371ba3d4,
+	0x37153eee, 0x209614d9, 0x20b68181, 0x3702037c, 0x36fb9618, 0x20c14ddf, 0x20e1ab63, 0x36e84135,
+	0x36e1cb58, 0x20ec72b1, 0x210cc0fc, 0x36ce5d10, 0x36c7debd, 0x21178334, 0x2137c232, 0x36b4571b,
+	0x36add058, 0x21427f4d, 0x2162aeea, 0x369a2f69, 0x3693a038, 0x216d66e2, 0x218d870b, 0x367fe608,
+	0x36794e6e, 0x219839d8, 0x21b84a79, 0x36657b08, 0x365edb09, 0x21c2f815, 0x21e2f91a, 0x364aee7b,
+	0x3644461b, 0x21eda17f, 0x220d92d4, 0x36304070, 0x36298fb4, 0x221835fb, 0x2238178d, 0x361570f8,
+	0x360eb7e3, 0x2242b56f, 0x22628729, 0x35fa8023, 0x35f3beba, 0x226d1fc1, 0x228ce191, 0x35df6e03,
+	0x35d8a449, 0x229774d7, 0x22b726a8, 0x35c43aa7, 0x35bd68a1, 0x22c1b496, 0x22e15655, 0x35a8e621,
+	0x35a20bd3, 0x22ebdee5, 0x230b707e, 0x358d7081, 0x35868def, 0x2315f3a8, 0x23357509, 0x3571d9d9,
+	0x356aef08, 0x233ff2c8, 0x235f63dc, 0x35562239, 0x354f2f2c, 0x2369dc29, 0x23893cdd, 0x353a49b2,
+	0x35334e6f, 0x2393afb2, 0x23b2fff3, 0x351e5056, 0x35174ce0, 0x23bd6d48, 0x23dcad03, 0x35023636,
+	0x34fb2a92, 0x23e714d3, 0x240643f4, 0x34e5fb63, 0x34dee795, 0x2410a639, 0x242fc4ad, 0x34c99fef,
+	0x34c283fb, 0x243a215f, 0x24592f13, 0x34ad23eb, 0x34a5ffd5, 0x2463862c, 0x2482830d, 0x34908768,
+	0x34895b36, 0x248cd487, 0x24abc082, 0x3473ca79, 0x346c962f, 0x24b60c57, 0x24d4e757, 0x3456ed2f,
+	0x344fb0d1, 0x24df2d81, 0x24fdf775, 0x3439ef9c, 0x3432ab2e, 0x250837ed, 0x2526f0c1, 0x341cd1d2,
+	0x34158559, 0x25312b81, 0x254fd323, 0x33ff93e2, 0x33f83f62, 0x255a0823, 0x25789e80, 0x33e235df,
+	0x33dad95e, 0x2582cdbc, 0x25a152c0, 0x33c4b7db, 0x33bd535c, 0x25ab7c30, 0x25c9efca, 0x33a719e8,
+	0x339fad70, 0x25d41369, 0x25f27584, 0x33895c18, 0x3381e7ac, 0x25fc934b, 0x261ae3d6, 0x336b7e7e,
+	0x33640223, 0x2624fbbf, 0x26433aa7, 0x334d812d, 0x3345fce6, 0x264d4cac, 0x266b79dd, 0x332f6435,
+	0x3327d808, 0x267585f8, 0x2693a161, 0x331127ab, 0x3309939c, 0x269da78b, 0x26bbb119, 0x32f2cba1,
+	0x32eb2fb5, 0x26c5b14c, 0x26e3a8ec, 0x32d45029, 0x32ccac64, 0x26eda322, 0x270b88c2, 0x32b5b557,
+	0x32ae09be, 0x27157cf5, 0x27335082, 0x3296fb3d, 0x328f47d5, 0x273d3eac, 0x275b0014, 0x327821ee,
+	0x327066bc, 0x2764e82f, 0x27829760, 0x3259297d, 0x32516686, 0x278c7965, 0x27aa164c, 0x323a11fe,
+	0x32324746, 0x27b3f235, 0x27d17cc1, 0x321adb83, 0x3213090f, 0x27db5288, 0x27f8caa5, 0x31fb8620,
+	0x31f3abf5, 0x28029a45, 0x281fffe2, 0x31dc11e8, 0x31d4300b, 0x2829c954, 0x28471c5e, 0x31bc7eee,
+	0x31b49564, 0x2850df9d, 0x286e2002, 0x319ccd46, 0x3194dc14, 0x2877dd07, 0x28950ab6, 0x317cfd04,
+	0x3175042e, 0x289ec17a, 0x28bbdc61, 0x315d0e3b, 0x31550dc6, 0x28c58cdf, 0x28e294eb, 0x313d00ff,
+	0x3134f8f1, 0x28ec3f1e, 0x2909343e, 0x311cd564, 0x3114c5c0, 0x2912d81f, 0x292fba40, 0x30fc8b7d,
+	0x30f47449, 0x293957c9, 0x295626da, 0x30dc235e, 0x30d404a0, 0x295fbe06, 0x297c79f5, 0x30bb9d1c,
+	0x30b376d8, 0x29860abd, 0x29a2b378, 0x309af8ca, 0x3092cb05, 0x29ac3dd7, 0x29c8d34d, 0x307a367c,
+	0x3072013c, 0x29d2573c, 0x29eed95b, 0x30595648, 0x30511991, 0x29f856d5, 0x2a14c58b, 0x30385840,
+	0x30301418, 0x2a1e3c8a, 0x2a3a97c7, 0x30173c7a, 0x300ef0e5, 0x2a440844, 0x2a604ff5, 0x2ff6030a,
+	0x2fedb00d, 0x2a69b9ec, 0x2a85ee00, 0x2fd4ac04, 0x2fcc51a5, 0x2a8f516b, 0x2aab71d0, 0x2fb3377c,
+	0x2faad5c1, 0x2ab4cea9, 0x2ad0db4e, 0x2f91a589, 0x2f893c75, 0x2ada318e, 0x2af62a63, 0x2f6ff63d,
+	0x2f6785d7, 0x2aff7a05, 0x2b1b5ef8, 0x2f4e29af, 0x2f45b1fb, 0x2b24a7f6, 0x2b4078f5, 0x2f2c3ff2,
+	0x2f23c0f6, 0x2b49bb4a, 0x2b657844, 0x2f0a391d, 0x2f01b2de, 0x2b6eb3ea, 0x2b8a5cce, 0x2ee81543,
+	0x2edf87c6, 0x2b9391c0, 0x2baf267d, 0x2ec5d479, 0x2ebd3fc4, 0x2bb854b4, 0x2bd3d53a, 0x2ea376d6,
+	0x2e9adaee, 0x2bdcfcb0, 0x2bf868ed, 0x2e80fc6e, 0x2e785958, 0x2c01899e, 0x2c1ce181, 0x2e5e6556,
+	0x2e55bb17, 0x2c25fb66, 0x2c413edf, 0x2e3bb1a4, 0x2e330042, 0x2c4a51f3, 0x2c6580f1, 0x2e18e16d,
+	0x2e1028ed, 0x2c6e8d2e, 0x2c89a79f, 0x2df5f4c7, 0x2ded352f, 0x2c92ad01, 0x2cadb2d5, 0x2dd2ebc7,
+	0x2dca251c, 0x2cb6b155, 0x2cd1a27b, 0x2dafc683, 0x2da6f8ca, 0x2cda9a14, 0x2cf5767c, 0x2d8c8510,
+	0x2d83b04f, 0x2cfe6728, 0x2d192ec1, 0x2d692784, 0x2d604bc0, 0x2d22187a, 0x2d3ccb34, 0x2d45adf6
+};
 
-	0x20000000, 0x00000000, 0x1f6297d0, 0x063e2e0f, 0x1d906bcf, 0x0c3ef153, 0x1a9b6629, 0x11c73b3a, 
-	0x20000000, 0x00000000, 0x1fd88da4, 0x0322f4d8, 0x1f6297d0, 0x063e2e0f, 0x1e9f4157, 0x094a0317, 
-	0x20000000, 0x00000000, 0x1e9f4157, 0x094a0317, 0x1a9b6629, 0x11c73b3a, 0x144cf325, 0x18bc806b, 
-	0x16a09e66, 0x16a09e66, 0x11c73b3a, 0x1a9b6629, 0x0c3ef153, 0x1d906bcf, 0x063e2e0f, 0x1f6297d0, 
-	0x1d906bcf, 0x0c3ef153, 0x1c38b2f2, 0x0f15ae9c, 0x1a9b6629, 0x11c73b3a, 0x18bc806b, 0x144cf325, 
-	0x0c3ef153, 0x1d906bcf, 0x0322f4d8, 0x1fd88da4, 0xf9c1d1f1, 0x1f6297d0, 0xf0ea5164, 0x1c38b2f2, 
-	0x00000000, 0x20000000, 0xf9c1d1f1, 0x1f6297d0, 0xf3c10ead, 0x1d906bcf, 0xee38c4c6, 0x1a9b6629, 
-	0x16a09e66, 0x16a09e66, 0x144cf325, 0x18bc806b, 0x11c73b3a, 0x1a9b6629, 0x0f15ae9c, 0x1c38b2f2, 
-	0xe95f619a, 0x16a09e66, 0xe3c74d0e, 0x0f15ae9c, 0xe09d6830, 0x063e2e0f, 0xe027725c, 0xfcdd0b28, 
-	0xe95f619a, 0x16a09e66, 0xe56499d7, 0x11c73b3a, 0xe26f9431, 0x0c3ef153, 0xe09d6830, 0x063e2e0f, 
-	0x0c3ef153, 0x1d906bcf, 0x094a0317, 0x1e9f4157, 0x063e2e0f, 0x1f6297d0, 0x0322f4d8, 0x1fd88da4, 
-	0xe26f9431, 0xf3c10ead, 0xe7437f95, 0xebb30cdb, 0xee38c4c6, 0xe56499d7, 0xf6b5fce9, 0xe160bea9

-};

-

+
+const int twidTab512[(8*6 + 32*6 + 128*6)/2] = {
+	0x40000000, 0x40000000, 0x40000000, 0x3b20187d,
+	0x3ec50c7c, 0x3536238e, 0x2d412d41, 0x3b20187d,
+	0x187d3b20, 0x187d3b20, 0x3536238e, 0xf3843ec5,
+	0x00004000, 0x2d412d41, 0xd2bf2d41, 0xe7833b20,
+	0x238e3536, 0xc13b0c7c, 0xd2bf2d41, 0x187d3b20,
+	0xc4e0e783, 0xc4e0187d, 0x0c7c3ec5, 0xdc72caca,
+
+	0x40000000, 0x40000000, 0x40000000, 0x3fb10645,
+	0x3fec0323, 0x3f4e0964, 0x3ec50c7c, 0x3fb10645,
+	0x3d3e1294, 0x3d3e1294, 0x3f4e0964, 0x39da1b5d,
+	0x3b20187d, 0x3ec50c7c, 0x3536238e, 0x38711e2b,
+	0x3e140f8c, 0x2f6b2afa, 0x3536238e, 0x3d3e1294,
+	0x28993179, 0x31792899, 0x3c42158f, 0x20e736e5,
+	0x2d412d41, 0x3b20187d, 0x187d3b20, 0x28993179,
+	0x39da1b5d, 0x0f8c3e14, 0x238e3536, 0x38711e2b,
+	0x06453fb1, 0x1e2b3871, 0x36e520e7, 0xfcdd3fec,
+	0x187d3b20, 0x3536238e, 0xf3843ec5, 0x12943d3e,
+	0x3367261f, 0xea713c42, 0x0c7c3ec5, 0x31792899,
+	0xe1d53871, 0x06453fb1, 0x2f6b2afa, 0xd9e13367,
+	0x00004000, 0x2d412d41, 0xd2bf2d41, 0xf9bb3fb1,
+	0x2afa2f6b, 0xcc99261f, 0xf3843ec5, 0x28993179,
+	0xc78f1e2b, 0xed6c3d3e, 0x261f3367, 0xc3be158f,
+	0xe7833b20, 0x238e3536, 0xc13b0c7c, 0xe1d53871,
+	0x20e736e5, 0xc0140323, 0xdc723536, 0x1e2b3871,
+	0xc04ff9bb, 0xd7673179, 0x1b5d39da, 0xc1ecf074,
+	0xd2bf2d41, 0x187d3b20, 0xc4e0e783, 0xce872899,
+	0x158f3c42, 0xc91bdf19, 0xcaca238e, 0x12943d3e,
+	0xce87d767, 0xc78f1e2b, 0x0f8c3e14, 0xd506d095,
+	0xc4e0187d, 0x0c7c3ec5, 0xdc72caca, 0xc2c21294,
+	0x09643f4e, 0xe4a3c626, 0xc13b0c7c, 0x06453fb1,
+	0xed6cc2c2, 0xc04f0645, 0x03233fec, 0xf69cc0b2,
+
+	0x40000000, 0x40000000, 0x40000000, 0x3ffb0192,
+	0x3ffe00c9, 0x3ff4025b, 0x3fec0323, 0x3ffb0192,
+	0x3fd304b5, 0x3fd304b5, 0x3ff4025b, 0x3f9c070d,
+	0x3fb10645, 0x3fec0323, 0x3f4e0964, 0x3f8407d5,
+	0x3fe103ec, 0x3eeb0bb6, 0x3f4e0964, 0x3fd304b5,
+	0x3e710e05, 0x3f0e0af1, 0x3fc3057d, 0x3de2104f,
+	0x3ec50c7c, 0x3fb10645, 0x3d3e1294, 0x3e710e05,
+	0x3f9c070d, 0x3c8414d1, 0x3e140f8c, 0x3f8407d5,
+	0x3bb61708, 0x3dae1111, 0x3f6a089c, 0x3ad21937,
+	0x3d3e1294, 0x3f4e0964, 0x39da1b5d, 0x3cc51413,
+	0x3f2f0a2a, 0x38cf1d79, 0x3c42158f, 0x3f0e0af1,
+	0x37af1f8b, 0x3bb61708, 0x3eeb0bb6, 0x367c2192,
+	0x3b20187d, 0x3ec50c7c, 0x3536238e, 0x3a8219ef,
+	0x3e9c0d41, 0x33de257d, 0x39da1b5d, 0x3e710e05,
+	0x3274275f, 0x392a1cc6, 0x3e440ec9, 0x30f82934,
+	0x38711e2b, 0x3e140f8c, 0x2f6b2afa, 0x37af1f8b,
+	0x3de2104f, 0x2dce2cb2, 0x36e520e7, 0x3dae1111,
+	0x2c212e5a, 0x3612223d, 0x3d7711d3, 0x2a652ff1,
+	0x3536238e, 0x3d3e1294, 0x28993179, 0x345324da,
+	0x3d021354, 0x26c032ee, 0x3367261f, 0x3cc51413,
+	0x24da3453, 0x3274275f, 0x3c8414d1, 0x22e635a5,
+	0x31792899, 0x3c42158f, 0x20e736e5, 0x307629cd,
+	0x3bfd164c, 0x1edc3811, 0x2f6b2afa, 0x3bb61708,
+	0x1cc6392a, 0x2e5a2c21, 0x3b6c17c3, 0x1aa63a2f,
+	0x2d412d41, 0x3b20187d, 0x187d3b20, 0x2c212e5a,
+	0x3ad21937, 0x164c3bfd, 0x2afa2f6b, 0x3a8219ef,
+	0x14133cc5, 0x29cd3076, 0x3a2f1aa6, 0x11d33d77,
+	0x28993179, 0x39da1b5d, 0x0f8c3e14, 0x275f3274,
+	0x39831c12, 0x0d413e9c, 0x261f3367, 0x392a1cc6,
+	0x0af13f0e, 0x24da3453, 0x38cf1d79, 0x089c3f6a,
+	0x238e3536, 0x38711e2b, 0x06453fb1, 0x223d3612,
+	0x38111edc, 0x03ec3fe1, 0x20e736e5, 0x37af1f8b,
+	0x01923ffb, 0x1f8b37af, 0x374b2039, 0xff373ffe,
+	0x1e2b3871, 0x36e520e7, 0xfcdd3fec, 0x1cc6392a,
+	0x367c2192, 0xfa833fc3, 0x1b5d39da, 0x3612223d,
+	0xf82b3f84, 0x19ef3a82, 0x35a522e6, 0xf5d63f2f,
+	0x187d3b20, 0x3536238e, 0xf3843ec5, 0x17083bb6,
+	0x34c62434, 0xf1373e44, 0x158f3c42, 0x345324da,
+	0xeeef3dae, 0x14133cc5, 0x33de257d, 0xecac3d02,
+	0x12943d3e, 0x3367261f, 0xea713c42, 0x11113dae,
+	0x32ee26c0, 0xe83d3b6c, 0x0f8c3e14, 0x3274275f,
+	0xe6113a82, 0x0e053e71, 0x31f727fd, 0xe3ee3983,
+	0x0c7c3ec5, 0x31792899, 0xe1d53871, 0x0af13f0e,
+	0x30f82934, 0xdfc7374b, 0x09643f4e, 0x307629cd,
+	0xddc33612, 0x07d53f84, 0x2ff12a65, 0xdbcc34c6,
+	0x06453fb1, 0x2f6b2afa, 0xd9e13367, 0x04b53fd3,
+	0x2ee32b8e, 0xd80331f7, 0x03233fec, 0x2e5a2c21,
+	0xd6333076, 0x01923ffb, 0x2dce2cb2, 0xd4722ee3,
+	0x00004000, 0x2d412d41, 0xd2bf2d41, 0xfe6e3ffb,
+	0x2cb22dce, 0xd11d2b8e, 0xfcdd3fec, 0x2c212e5a,
+	0xcf8a29cd, 0xfb4b3fd3, 0x2b8e2ee3, 0xce0927fd,
+	0xf9bb3fb1, 0x2afa2f6b, 0xcc99261f, 0xf82b3f84,
+	0x2a652ff1, 0xcb3a2434, 0xf69c3f4e, 0x29cd3076,
+	0xc9ee223d, 0xf50f3f0e, 0x293430f8, 0xc8b52039,
+	0xf3843ec5, 0x28993179, 0xc78f1e2b, 0xf1fb3e71,
+	0x27fd31f7, 0xc67d1c12, 0xf0743e14, 0x275f3274,
+	0xc57e19ef, 0xeeef3dae, 0x26c032ee, 0xc49417c3,
+	0xed6c3d3e, 0x261f3367, 0xc3be158f, 0xebed3cc5,
+	0x257d33de, 0xc2fe1354, 0xea713c42, 0x24da3453,
+	0xc2521111, 0xe8f83bb6, 0x243434c6, 0xc1bc0ec9,
+	0xe7833b20, 0x238e3536, 0xc13b0c7c, 0xe6113a82,
+	0x22e635a5, 0xc0d10a2a, 0xe4a339da, 0x223d3612,
+	0xc07c07d5, 0xe33a392a, 0x2192367c, 0xc03d057d,
+	0xe1d53871, 0x20e736e5, 0xc0140323, 0xe07537af,
+	0x2039374b, 0xc00200c9, 0xdf1936e5, 0x1f8b37af,
+	0xc005fe6e, 0xddc33612, 0x1edc3811, 0xc01ffc14,
+	0xdc723536, 0x1e2b3871, 0xc04ff9bb, 0xdb263453,
+	0x1d7938cf, 0xc096f764, 0xd9e13367, 0x1cc6392a,
+	0xc0f2f50f, 0xd8a13274, 0x1c123983, 0xc164f2bf,
+	0xd7673179, 0x1b5d39da, 0xc1ecf074, 0xd6333076,
+	0x1aa63a2f, 0xc289ee2d, 0xd5062f6b, 0x19ef3a82,
+	0xc33bebed, 0xd3df2e5a, 0x19373ad2, 0xc403e9b4,
+	0xd2bf2d41, 0x187d3b20, 0xc4e0e783, 0xd1a62c21,
+	0x17c33b6c, 0xc5d1e55a, 0xd0952afa, 0x17083bb6,
+	0xc6d6e33a, 0xcf8a29cd, 0x164c3bfd, 0xc7efe124,
+	0xce872899, 0x158f3c42, 0xc91bdf19, 0xcd8c275f,
+	0x14d13c84, 0xca5bdd1a, 0xcc99261f, 0x14133cc5,
+	0xcbaddb26, 0xcbad24da, 0x13543d02, 0xcd12d940,
+	0xcaca238e, 0x12943d3e, 0xce87d767, 0xc9ee223d,
+	0x11d33d77, 0xd00fd59b, 0xc91b20e7, 0x11113dae,
+	0xd1a6d3df, 0xc8511f8b, 0x104f3de2, 0xd34ed232,
+	0xc78f1e2b, 0x0f8c3e14, 0xd506d095, 0xc6d61cc6,
+	0x0ec93e44, 0xd6cccf08, 0xc6261b5d, 0x0e053e71,
+	0xd8a1cd8c, 0xc57e19ef, 0x0d413e9c, 0xda83cc22,
+	0xc4e0187d, 0x0c7c3ec5, 0xdc72caca, 0xc44a1708,
+	0x0bb63eeb, 0xde6ec984, 0xc3be158f, 0x0af13f0e,
+	0xe075c851, 0xc33b1413, 0x0a2a3f2f, 0xe287c731,
+	0xc2c21294, 0x09643f4e, 0xe4a3c626, 0xc2521111,
+	0x089c3f6a, 0xe6c9c52e, 0xc1ec0f8c, 0x07d53f84,
+	0xe8f8c44a, 0xc18f0e05, 0x070d3f9c, 0xeb2fc37c,
+	0xc13b0c7c, 0x06453fb1, 0xed6cc2c2, 0xc0f20af1,
+	0x057d3fc3, 0xefb1c21e, 0xc0b20964, 0x04b53fd3,
+	0xf1fbc18f, 0xc07c07d5, 0x03ec3fe1, 0xf44ac115,
+	0xc04f0645, 0x03233fec, 0xf69cc0b2, 0xc02d04b5,
+	0x025b3ff4, 0xf8f3c064, 0xc0140323, 0x01923ffb,
+	0xfb4bc02d, 0xc0050192, 0x00c93ffe, 0xfda5c00c
+};
+
+const int twidTab64[(4*6 + 16*6)/2] = {
+	0x40000000, 0x40000000, 0x40000000, 0x2d412d41,
+	0x3b20187d, 0x187d3b20, 0x00004000, 0x2d412d41,
+	0xd2bf2d41, 0xd2bf2d41, 0x187d3b20, 0xc4e0e783,
+
+	0x40000000, 0x40000000, 0x40000000, 0x3ec50c7c,
+	0x3fb10645, 0x3d3e1294, 0x3b20187d, 0x3ec50c7c,
+	0x3536238e, 0x3536238e, 0x3d3e1294, 0x28993179,
+	0x2d412d41, 0x3b20187d, 0x187d3b20, 0x238e3536,
+	0x38711e2b, 0x06453fb1, 0x187d3b20, 0x3536238e,
+	0xf3843ec5, 0x0c7c3ec5, 0x31792899, 0xe1d53871,
+	0x00004000, 0x2d412d41, 0xd2bf2d41, 0xf3843ec5,
+	0x28993179, 0xc78f1e2b, 0xe7833b20, 0x238e3536,
+	0xc13b0c7c, 0xdc723536, 0x1e2b3871, 0xc04ff9bb,
+	0xd2bf2d41, 0x187d3b20, 0xc4e0e783, 0xcaca238e,
+	0x12943d3e, 0xce87d767, 0xc4e0187d, 0x0c7c3ec5,
+	0xdc72caca, 0xc13b0c7c, 0x06453fb1, 0xed6cc2c2
+};
+
+#elif defined ARMV7Neon
+/*
+ *  Q29 for 128 and 1024
+ *
+ * for (i = 0; i < num/4; i++) {
+ *   angle = (i + 0.125) * M_PI / num;
+ *   x = cos(angle) * (1 << 29);
+ *   x = sin(angle) * (1 << 29);
+ *
+ *   angle = (num/2 - 1 - i + 0.125) * M_PI / num;
+ *   x = cos(angle) * (1 << 29);
+ *   x = sin(angle) * (1 << 29);
+ * }
+ */
+const int cossintab[128 + 1024] = {
+	/* 128 */
+	0x1ffff621, 0x001921f9, 0x00afea69, 0x1ffe1c68, 0x1ffce09d, 0x00e22a7a, 0x0178dbaa, 0x1ff753bb,
+	0x1ff4dc55, 0x01ab101c, 0x024192cf, 0x1feb9d25, 0x1fe7ea85, 0x0273b3e2, 0x0309f0e2, 0x1fdafa75,
+	0x1fd60d2e, 0x033bf6dd, 0x03d1d700, 0x1fc56e3b, 0x1fbf470f, 0x0403ba2b, 0x04992653, 0x1faafbcb,
+	0x1fa39bac, 0x04cadefe, 0x055fc022, 0x1f8ba738, 0x1f830f4a, 0x059146a1, 0x062585ca, 0x1f677557,
+	0x1f5da6ed, 0x0656d27a, 0x06ea58cd, 0x1f3e6bbc, 0x1f33685a, 0x071b6415, 0x07ae1ad2, 0x1f1090bd,
+	0x1f045a15, 0x07dedd20, 0x0870ada7, 0x1eddeb6a, 0x1ed0835f, 0x08a11f78, 0x0931f34d, 0x1ea68394,
+	0x1e97ec36, 0x09620d27, 0x09f1cdf5, 0x1e6a61c5, 0x1e5a9d55, 0x0a21886e, 0x0ab02009, 0x1e298f44,
+	0x1e18a030, 0x0adf73c6, 0x0b6ccc32, 0x1de4160f, 0x1dd1fef4, 0x0b9bb1e5, 0x0c27b555, 0x1d9a00de,
+	0x1d86c484, 0x0c5625c3, 0x0ce0bea2, 0x1d4b5b1b, 0x1d36fc7c, 0x0d0eb2a2, 0x0d97cb8f, 0x1cf830e9,
+	0x1ce2b328, 0x0dc53c0a, 0x0e4cbfe2, 0x1ca08f1a, 0x1c89f587, 0x0e79a5d7, 0x0eff7fb3, 0x1c448331,
+	0x1c2cd149, 0x0f2bd437, 0x0fafef73, 0x1be41b61, 0x1bcb54cb, 0x0fdbabae, 0x105df3ec, 0x1b7f6687,
+	0x1b658f15, 0x10891120, 0x11097249, 0x1b16742a, 0x1afb8fd9, 0x1133e9d0, 0x11b25017, 0x1aa9547a,
+	0x1a8d676e, 0x11dc1b65, 0x1258734d, 0x1a38184a, 0x1a1b26d3, 0x12818bef, 0x12fbc24b, 0x19c2d111,
+	0x19a4dfa4, 0x132421ec, 0x139c23e4, 0x194990e4, 0x192aa420, 0x13c3c44a, 0x14397f5b, 0x18cc6a75,
+	0x18ac871f, 0x14605a69, 0x14d3bc6d, 0x184b7112, 0x182a9c14, 0x14f9cc26, 0x156ac352, 0x17c6b89d,
+	0x17a4f708, 0x159001d6, 0x15fe7cbe, 0x173e558e, 0x171bac96, 0x1622e450, 0x168ed1eb, 0x16b25ced,
+	/* 1024 */
+	0x1fffffd9, 0x0003243f, 0x0015fdba, 0x1ffff872, 0x1ffff382, 0x001c4637, 0x002f1fa6, 0x1fffdd4d,
+	0x1fffd36f, 0x0035681d, 0x00484175, 0x1fffae6c, 0x1fff9f9e, 0x004e89e3, 0x00616318, 0x1fff6bce,
+	0x1fff5811, 0x0067ab77, 0x007a847e, 0x1fff1572, 0x1ffefcc6, 0x0080cccc, 0x0093a599, 0x1ffeab5b,
+	0x1ffe8dbf, 0x0099edd2, 0x00acc658, 0x1ffe2d86, 0x1ffe0afc, 0x00b30e78, 0x00c5e6ad, 0x1ffd9bf6,
+	0x1ffd747c, 0x00cc2eb0, 0x00df0688, 0x1ffcf6aa, 0x1ffcca41, 0x00e54e6a, 0x00f825da, 0x1ffc3da2,
+	0x1ffc0c4b, 0x00fe6d97, 0x01114492, 0x1ffb70e0, 0x1ffb3a9a, 0x01178c27, 0x012a62a2, 0x1ffa9063,
+	0x1ffa552e, 0x0130aa0a, 0x01437ffa, 0x1ff99c2c, 0x1ff95c09, 0x0149c731, 0x015c9c8a, 0x1ff8943c,
+	0x1ff84f2b, 0x0162e38d, 0x0175b843, 0x1ff77893, 0x1ff72e94, 0x017bff0e, 0x018ed316, 0x1ff64932,
+	0x1ff5fa46, 0x019519a5, 0x01a7ecf2, 0x1ff5061b, 0x1ff4b240, 0x01ae3341, 0x01c105c9, 0x1ff3af4c,
+	0x1ff35684, 0x01c74bd5, 0x01da1d8c, 0x1ff244c8, 0x1ff1e713, 0x01e0634f, 0x01f33429, 0x1ff0c68f,
+	0x1ff063ed, 0x01f979a1, 0x020c4993, 0x1fef34a3, 0x1feecd14, 0x02128ebb, 0x02255db9, 0x1fed8f03,
+	0x1fed2287, 0x022ba28f, 0x023e708d, 0x1febd5b2, 0x1feb644a, 0x0244b50b, 0x025781fe, 0x1fea08b0,
+	0x1fe9925c, 0x025dc621, 0x027091fd, 0x1fe827fe, 0x1fe7acbe, 0x0276d5c1, 0x0289a07b, 0x1fe6339d,
+	0x1fe5b372, 0x028fe3dd, 0x02a2ad69, 0x1fe42b90, 0x1fe3a679, 0x02a8f063, 0x02bbb8b6, 0x1fe20fd6,
+	0x1fe185d5, 0x02c1fb46, 0x02d4c253, 0x1fdfe071, 0x1fdf5186, 0x02db0475, 0x02edca32, 0x1fdd9d64,
+	0x1fdd098e, 0x02f40be2, 0x0306d042, 0x1fdb46ae, 0x1fdaadee, 0x030d117c, 0x031fd474, 0x1fd8dc51,
+	0x1fd83ea8, 0x03261534, 0x0338d6b8, 0x1fd65e4f, 0x1fd5bbbd, 0x033f16fb, 0x0351d700, 0x1fd3ccaa,
+	0x1fd32530, 0x035816c1, 0x036ad53c, 0x1fd12763, 0x1fd07b00, 0x03711477, 0x0383d15c, 0x1fce6e7c,
+	0x1fcdbd31, 0x038a100e, 0x039ccb51, 0x1fcba1f5, 0x1fcaebc3, 0x03a30975, 0x03b5c30b, 0x1fc8c1d2,
+	0x1fc806b9, 0x03bc009f, 0x03ceb87c, 0x1fc5ce14, 0x1fc50e14, 0x03d4f57a, 0x03e7ab93, 0x1fc2c6bd,
+	0x1fc201d7, 0x03ede7f9, 0x04009c42, 0x1fbfabcd, 0x1fbee202, 0x0406d80b, 0x04198a78, 0x1fbc7d49,
+	0x1fbbae99, 0x041fc5a1, 0x04327628, 0x1fb93b31, 0x1fb8679c, 0x0438b0ac, 0x044b5f40, 0x1fb5e587,
+	0x1fb50d0e, 0x0451991d, 0x046445b2, 0x1fb27c4e, 0x1fb19ef1, 0x046a7ee3, 0x047d296f, 0x1faeff87,
+	0x1fae1d47, 0x048361f0, 0x04960a67, 0x1fab6f35, 0x1faa8813, 0x049c4235, 0x04aee88b, 0x1fa7cb5a,
+	0x1fa6df56, 0x04b51fa1, 0x04c7c3cb, 0x1fa413f8, 0x1fa32313, 0x04cdfa26, 0x04e09c18, 0x1fa04912,
+	0x1f9f534c, 0x04e6d1b4, 0x04f97163, 0x1f9c6aa9, 0x1f9b7003, 0x04ffa63c, 0x0512439d, 0x1f9878c1,
+	0x1f97793b, 0x051877af, 0x052b12b6, 0x1f94735b, 0x1f936ef6, 0x053145fd, 0x0543de9e, 0x1f905a7a,
+	0x1f8f5137, 0x054a1117, 0x055ca748, 0x1f8c2e21, 0x1f8b2000, 0x0562d8ee, 0x05756ca2, 0x1f87ee52,
+	0x1f86db55, 0x057b9d73, 0x058e2e9f, 0x1f839b10, 0x1f828336, 0x05945e95, 0x05a6ed2e, 0x1f7f345e,
+	0x1f7e17a8, 0x05ad1c47, 0x05bfa840, 0x1f7aba3e, 0x1f7998ad, 0x05c5d678, 0x05d85fc7, 0x1f762cb2,
+	0x1f750647, 0x05de8d19, 0x05f113b3, 0x1f718bbf, 0x1f70607a, 0x05f7401c, 0x0609c3f5, 0x1f6cd766,
+	0x1f6ba748, 0x060fef71, 0x0622707d, 0x1f680fab, 0x1f66dab5, 0x06289b08, 0x063b193c, 0x1f633490,
+	0x1f61fac3, 0x064142d3, 0x0653be23, 0x1f5e4619, 0x1f5d0775, 0x0659e6c2, 0x066c5f24, 0x1f594448,
+	0x1f5800ce, 0x067286c6, 0x0684fc2e, 0x1f542f21, 0x1f52e6d2, 0x068b22d0, 0x069d9532, 0x1f4f06a6,
+	0x1f4db983, 0x06a3bad0, 0x06b62a22, 0x1f49cadc, 0x1f4878e5, 0x06bc4eb9, 0x06cebaee, 0x1f447bc4,
+	0x1f4324fb, 0x06d4de79, 0x06e74786, 0x1f3f1963, 0x1f3dbdc8, 0x06ed6a03, 0x06ffcfdd, 0x1f39a3bc,
+	0x1f384350, 0x0705f147, 0x071853e3, 0x1f341ad2, 0x1f32b595, 0x071e7436, 0x0730d388, 0x1f2e7ea9,
+	0x1f2d149d, 0x0736f2c0, 0x07494ebd, 0x1f28cf43, 0x1f276069, 0x074f6cd7, 0x0761c574, 0x1f230ca5,
+	0x1f2198fd, 0x0767e26c, 0x077a379d, 0x1f1d36d2, 0x1f1bbe5d, 0x07805370, 0x0792a52a, 0x1f174dce,
+	0x1f15d08d, 0x0798bfd3, 0x07ab0e0a, 0x1f11519c, 0x1f0fcf91, 0x07b12786, 0x07c37230, 0x1f0b4240,
+	0x1f09bb6b, 0x07c98a7a, 0x07dbd18c, 0x1f051fbe, 0x1f03941f, 0x07e1e8a1, 0x07f42c0e, 0x1efeea19,
+	0x1efd59b3, 0x07fa41eb, 0x080c81a9, 0x1ef8a155, 0x1ef70c28, 0x0812964a, 0x0824d24d, 0x1ef24577,
+	0x1ef0ab84, 0x082ae5ad, 0x083d1dea, 0x1eebd682, 0x1eea37ca, 0x08433007, 0x08556473, 0x1ee5547a,
+	0x1ee3b0fe, 0x085b7548, 0x086da5d8, 0x1edebf64, 0x1edd1724, 0x0873b562, 0x0885e209, 0x1ed81742,
+	0x1ed66a41, 0x088bf044, 0x089e18f9, 0x1ed15c1a, 0x1ecfaa57, 0x08a425e1, 0x08b64a98, 0x1eca8def,
+	0x1ec8d76c, 0x08bc562a, 0x08ce76d8, 0x1ec3acc6, 0x1ec1f184, 0x08d4810f, 0x08e69da8, 0x1ebcb8a3,
+	0x1ebaf8a3, 0x08eca681, 0x08febefb, 0x1eb5b18a, 0x1eb3eccd, 0x0904c673, 0x0916dac2, 0x1eae977f,
+	0x1eacce07, 0x091ce0d4, 0x092ef0ed, 0x1ea76a87, 0x1ea59c55, 0x0934f596, 0x0947016e, 0x1ea02aa7,
+	0x1e9e57bb, 0x094d04aa, 0x095f0c36, 0x1e98d7e2, 0x1e97003e, 0x09650e01, 0x09771136, 0x1e91723e,
+	0x1e8f95e3, 0x097d118d, 0x098f1060, 0x1e89f9bf, 0x1e8818ad, 0x09950f3f, 0x09a709a4, 0x1e826e69,
+	0x1e8088a2, 0x09ad0707, 0x09befcf4, 0x1e7ad041, 0x1e78e5c7, 0x09c4f8d8, 0x09d6ea40, 0x1e731f4c,
+	0x1e71301f, 0x09dce4a1, 0x09eed17b, 0x1e6b5b8f, 0x1e6967b1, 0x09f4ca56, 0x0a06b296, 0x1e63850e,
+	0x1e618c80, 0x0a0ca9e6, 0x0a1e8d81, 0x1e5b9bce, 0x1e599e91, 0x0a248343, 0x0a36622e, 0x1e539fd4,
+	0x1e519dea, 0x0a3c565e, 0x0a4e308f, 0x1e4b9126, 0x1e498a8e, 0x0a542329, 0x0a65f894, 0x1e436fc7,
+	0x1e416485, 0x0a6be995, 0x0a7dba2f, 0x1e3b3bbd, 0x1e392bd1, 0x0a83a993, 0x0a957551, 0x1e32f50e,
+	0x1e30e079, 0x0a9b6315, 0x0aad29ec, 0x1e2a9bbd, 0x1e288281, 0x0ab3160c, 0x0ac4d7f1, 0x1e222fd1,
+	0x1e2011ee, 0x0acac26a, 0x0adc7f52, 0x1e19b14f, 0x1e178ec7, 0x0ae2681f, 0x0af41fff, 0x1e11203b,
+	0x1e0ef910, 0x0afa071d, 0x0b0bb9eb, 0x1e087c9b, 0x1e0650ce, 0x0b119f56, 0x0b234d07, 0x1dffc674,
+	0x1dfd9606, 0x0b2930bb, 0x0b3ad943, 0x1df6fdcc, 0x1df4c8bf, 0x0b40bb3e, 0x0b525e92, 0x1dee22a9,
+	0x1debe8fd, 0x0b583ecf, 0x0b69dce6, 0x1de5350f, 0x1de2f6c6, 0x0b6fbb62, 0x0b81542f, 0x1ddc3504,
+	0x1dd9f220, 0x0b8730e6, 0x0b98c45f, 0x1dd3228e, 0x1dd0db10, 0x0b9e9f4d, 0x0bb02d68, 0x1dc9fdb2,
+	0x1dc7b19b, 0x0bb6068a, 0x0bc78f3b, 0x1dc0c676, 0x1dbe75c8, 0x0bcd668e, 0x0bdee9ca, 0x1db77cdf,
+	0x1db5279c, 0x0be4bf4a, 0x0bf63d07, 0x1dae20f4, 0x1dabc71d, 0x0bfc10af, 0x0c0d88e2, 0x1da4b2ba,
+	0x1da25450, 0x0c135ab0, 0x0c24cd4e, 0x1d9b3237, 0x1d98cf3b, 0x0c2a9d3e, 0x0c3c0a3d, 0x1d919f70,
+	0x1d8f37e5, 0x0c41d84b, 0x0c533fa0, 0x1d87fa6d, 0x1d858e53, 0x0c590bc9, 0x0c6a6d68, 0x1d7e4332,
+	0x1d7bd28b, 0x0c7037a8, 0x0c819388, 0x1d7479c5, 0x1d720493, 0x0c875bdb, 0x0c98b1f0, 0x1d6a9e2e,
+	0x1d682472, 0x0c9e7854, 0x0cafc894, 0x1d60b070, 0x1d5e322c, 0x0cb58d04, 0x0cc6d764, 0x1d56b094,
+	0x1d542dc9, 0x0ccc99de, 0x0cddde53, 0x1d4c9e9f, 0x1d4a174f, 0x0ce39ed2, 0x0cf4dd52, 0x1d427a97,
+	0x1d3feec3, 0x0cfa9bd2, 0x0d0bd452, 0x1d384483, 0x1d35b42d, 0x0d1190d1, 0x0d22c347, 0x1d2dfc68,
+	0x1d2b6791, 0x0d287dc1, 0x0d39aa21, 0x1d23a24e, 0x1d2108f8, 0x0d3f6292, 0x0d5088d3, 0x1d19363a,
+	0x1d169867, 0x0d563f38, 0x0d675f4e, 0x1d0eb833, 0x1d0c15e4, 0x0d6d13a3, 0x0d7e2d85, 0x1d04283f,
+	0x1d018176, 0x0d83dfc6, 0x0d94f369, 0x1cf98666, 0x1cf6db24, 0x0d9aa393, 0x0dabb0ec, 0x1ceed2ad,
+	0x1cec22f4, 0x0db15efc, 0x0dc26600, 0x1ce40d1b, 0x1ce158ed, 0x0dc811f3, 0x0dd91298, 0x1cd935b7,
+	0x1cd67d15, 0x0ddebc69, 0x0defb6a5, 0x1cce4c87, 0x1ccb8f74, 0x0df55e51, 0x0e065219, 0x1cc35192,
+	0x1cc0900f, 0x0e0bf79c, 0x0e1ce4e6, 0x1cb844df, 0x1cb57eee, 0x0e22883e, 0x0e336eff, 0x1cad2675,
+	0x1caa5c17, 0x0e391027, 0x0e49f055, 0x1ca1f65b, 0x1c9f2792, 0x0e4f8f4b, 0x0e6068db, 0x1c96b497,
+	0x1c93e165, 0x0e66059a, 0x0e76d883, 0x1c8b6131, 0x1c888997, 0x0e7c7308, 0x0e8d3f3e, 0x1c7ffc2f,
+	0x1c7d202f, 0x0e92d787, 0x0ea39d00, 0x1c748599, 0x1c71a535, 0x0ea93308, 0x0eb9f1ba, 0x1c68fd75,
+	0x1c6618ae, 0x0ebf857d, 0x0ed03d5e, 0x1c5d63ca, 0x1c5a7aa4, 0x0ed5ceda, 0x0ee67fdf, 0x1c51b8a1,
+	0x1c4ecb1c, 0x0eec0f10, 0x0efcb92f, 0x1c45fc00, 0x1c430a1d, 0x0f024612, 0x0f12e941, 0x1c3a2ded,
+	0x1c3737b0, 0x0f1873d2, 0x0f291006, 0x1c2e4e72, 0x1c2b53db, 0x0f2e9842, 0x0f3f2d71, 0x1c225d94,
+	0x1c1f5ea6, 0x0f44b354, 0x0f554175, 0x1c165b5b, 0x1c135818, 0x0f5ac4fc, 0x0f6b4c03, 0x1c0a47cf,
+	0x1c074038, 0x0f70cd2a, 0x0f814d0e, 0x1bfe22f8, 0x1bfb170f, 0x0f86cbd3, 0x0f974489, 0x1bf1ecdb,
+	0x1beedca2, 0x0f9cc0e7, 0x0fad3265, 0x1be5a582, 0x1be290fb, 0x0fb2ac5a, 0x0fc31697, 0x1bd94cf4,
+	0x1bd63421, 0x0fc88e1e, 0x0fd8f10f, 0x1bcce337, 0x1bc9c61a, 0x0fde6626, 0x0feec1c0, 0x1bc06855,
+	0x1bbd46f0, 0x0ff43464, 0x1004889e, 0x1bb3dc55, 0x1bb0b6a9, 0x1009f8cb, 0x101a459a, 0x1ba73f3d,
+	0x1ba4154d, 0x101fb34d, 0x102ff8a8, 0x1b9a9117, 0x1b9762e4, 0x103563dc, 0x1045a1b9, 0x1b8dd1ea,
+	0x1b8a9f77, 0x104b0a6c, 0x105b40c1, 0x1b8101be, 0x1b7dcb0c, 0x1060a6ef, 0x1070d5b1, 0x1b74209b,
+	0x1b70e5ac, 0x10763958, 0x1086607e, 0x1b672e88, 0x1b63ef5f, 0x108bc19a, 0x109be119, 0x1b5a2b8e,
+	0x1b56e82c, 0x10a13fa6, 0x10b15775, 0x1b4d17b4, 0x1b49d01c, 0x10b6b371, 0x10c6c385, 0x1b3ff304,
+	0x1b3ca737, 0x10cc1cec, 0x10dc253c, 0x1b32bd84, 0x1b2f6d85, 0x10e17c0b, 0x10f17c8d, 0x1b25773d,
+	0x1b22230e, 0x10f6d0c0, 0x1106c96a, 0x1b182038, 0x1b14c7da, 0x110c1afe, 0x111c0bc6, 0x1b0ab87c,
+	0x1b075bf1, 0x11215ab8, 0x11314395, 0x1afd4012, 0x1af9df5d, 0x11368fe1, 0x114670c8, 0x1aefb702,
+	0x1aec5225, 0x114bba6b, 0x115b9354, 0x1ae21d54, 0x1adeb451, 0x1160da4b, 0x1170ab2a, 0x1ad47311,
+	0x1ad105e9, 0x1175ef72, 0x1185b83f, 0x1ac6b841, 0x1ac346f8, 0x118af9d4, 0x119aba84, 0x1ab8ecec,
+	0x1ab57784, 0x119ff964, 0x11afb1ee, 0x1aab111c, 0x1aa79796, 0x11b4ee14, 0x11c49e6f, 0x1a9d24d9,
+	0x1a99a737, 0x11c9d7d9, 0x11d97ff9, 0x1a8f282b, 0x1a8ba670, 0x11deb6a4, 0x11ee5682, 0x1a811b1b,
+	0x1a7d9549, 0x11f38a6a, 0x120321fa, 0x1a72fdb2, 0x1a6f73ca, 0x1208531c, 0x1217e256, 0x1a64cff8,
+	0x1a6141fd, 0x121d10af, 0x122c9789, 0x1a5691f5, 0x1a52ffeb, 0x1231c316, 0x12414186, 0x1a4843b4,
+	0x1a44ad9b, 0x12466a44, 0x1255e041, 0x1a39e53d, 0x1a364b17, 0x125b062b, 0x126a73ac, 0x1a2b7698,
+	0x1a27d868, 0x126f96c1, 0x127efbbb, 0x1a1cf7ce, 0x1a195597, 0x12841bf6, 0x12937861, 0x1a0e68e9,
+	0x1a0ac2ac, 0x129895c0, 0x12a7e991, 0x19ffc9f1, 0x19fc1fb1, 0x12ad0412, 0x12bc4f40, 0x19f11af0,
+	0x19ed6caf, 0x12c166de, 0x12d0a960, 0x19e25bee, 0x19dea9ae, 0x12d5be18, 0x12e4f7e5, 0x19d38cf4,
+	0x19cfd6b8, 0x12ea09b4, 0x12f93ac2, 0x19c4ae0c, 0x19c0f3d6, 0x12fe49a6, 0x130d71eb, 0x19b5bf3f,
+	0x19b20111, 0x13127de0, 0x13219d53, 0x19a6c096, 0x19a2fe73, 0x1326a656, 0x1335bcef, 0x1997b21b,
+	0x1993ec04, 0x133ac2fc, 0x1349d0b0, 0x198893d6, 0x1984c9ce, 0x134ed3c5, 0x135dd88c, 0x197965d0,
+	0x197597da, 0x1362d8a6, 0x1371d476, 0x196a2815, 0x19665632, 0x1376d191, 0x1385c461, 0x195adaab,
+	0x195704df, 0x138abe7b, 0x1399a841, 0x194b7d9e, 0x1947a3eb, 0x139e9f56, 0x13ad800a, 0x193c10f7,
+	0x1938335e, 0x13b27417, 0x13c14bb0, 0x192c94bf, 0x1928b343, 0x13c63cb2, 0x13d50b26, 0x191d08ff,
+	0x191923a3, 0x13d9f91b, 0x13e8be60, 0x190d6dc1, 0x19098488, 0x13eda944, 0x13fc6553, 0x18fdc310,
+	0x18f9d5fa, 0x14014d23, 0x140ffff1, 0x18ee08f4, 0x18ea1805, 0x1414e4aa, 0x14238e2f, 0x18de3f77,
+	0x18da4ab2, 0x14286fce, 0x14371001, 0x18ce66a3, 0x18ca6e0a, 0x143bee83, 0x144a855b, 0x18be7e82,
+	0x18ba8217, 0x144f60bd, 0x145dee30, 0x18ae871e, 0x18aa86e3, 0x1462c670, 0x14714a76, 0x189e8080,
+	0x189a7c78, 0x14761f8f, 0x14849a1f, 0x188e6ab2, 0x188a62e0, 0x14896c0f, 0x1497dd20, 0x187e45be,
+	0x187a3a25, 0x149cabe4, 0x14ab136d, 0x186e11af, 0x186a0250, 0x14afdf03, 0x14be3cfa, 0x185dce8e,
+	0x1859bb6c, 0x14c3055e, 0x14d159bc, 0x184d7c65, 0x18496583, 0x14d61eeb, 0x14e469a6, 0x183d1b3e,
+	0x1839009e, 0x14e92b9e, 0x14f76cad, 0x182cab24, 0x18288cc8, 0x14fc2b6a, 0x150a62c6, 0x181c2c20,
+	0x18180a0c, 0x150f1e45, 0x151d4be3, 0x180b9e3d, 0x18077873, 0x15220422, 0x153027fb, 0x17fb0185,
+	0x17f6d807, 0x1534dcf6, 0x1542f700, 0x17ea5602, 0x17e628d3, 0x1547a8b5, 0x1555b8e8, 0x17d99bbe,
+	0x17d56ae0, 0x155a6754, 0x15686da7, 0x17c8d2c4, 0x17c49e3b, 0x156d18c7, 0x157b1532, 0x17b7fb1f,
+	0x17b3c2ec, 0x157fbd03, 0x158daf7c, 0x17a714d7, 0x17a2d8fe, 0x159253fb, 0x15a03c7a, 0x17961ff9,
+	0x1791e07b, 0x15a4dda5, 0x15b2bc22, 0x17851c8e, 0x1780d96f, 0x15b759f5, 0x15c52e67, 0x17740aa1,
+	0x176fc3e3, 0x15c9c8e0, 0x15d7933f, 0x1762ea3d, 0x175e9fe2, 0x15dc2a5a, 0x15e9ea9d, 0x1751bb6b,
+	0x174d6d77, 0x15ee7e58, 0x15fc3477, 0x17407e37, 0x173c2cac, 0x1600c4cf, 0x160e70c1, 0x172f32ab,
+	0x172add8c, 0x1612fdb3, 0x16209f70, 0x171dd8d2, 0x17198021, 0x162528fa, 0x1632c078, 0x170c70b7,
+	0x17081477, 0x16374697, 0x1644d3d0, 0x16fafa64, 0x16f69a97, 0x16495680, 0x1656d96a, 0x16e975e4,
+	0x16e5128e, 0x165b58aa, 0x1668d13e, 0x16d7e341, 0x16d37c65, 0x166d4d0a, 0x167abb3e, 0x16c64288,
+	0x16c1d827, 0x167f3394, 0x168c9760, 0x16b493c2, 0x16b025e0, 0x16910c3d, 0x169e659a, 0x16a2d6fb
+};
+
+const int twidTab512[8*6 + 32*6 + 128*6] = {
+	0x20000000, 0x00000000, 0x1d906bcf, 0x0c3ef153, 0x16a09e66, 0x16a09e66, 0x0c3ef153, 0x1d906bcf,
+	0x20000000, 0x00000000, 0x1f6297d0, 0x063e2e0f, 0x1d906bcf, 0x0c3ef153, 0x1a9b6629, 0x11c73b3a,
+	0x20000000, 0x00000000, 0x1a9b6629, 0x11c73b3a, 0x0c3ef153, 0x1d906bcf, 0xf9c1d1f1, 0x1f6297d0,
+	0x00000000, 0x20000000, 0xf3c10ead, 0x1d906bcf, 0xe95f619a, 0x16a09e66, 0xe26f9431, 0x0c3ef153,
+	0x16a09e66, 0x16a09e66, 0x11c73b3a, 0x1a9b6629, 0x0c3ef153, 0x1d906bcf, 0x063e2e0f, 0x1f6297d0,
+	0xe95f619a, 0x16a09e66, 0xe09d6830, 0x063e2e0f, 0xe26f9431, 0xf3c10ead, 0xee38c4c6, 0xe56499d7,
+
+	0x20000000, 0x00000000, 0x1fd88da4, 0x0322f4d8, 0x1f6297d0, 0x063e2e0f, 0x1e9f4157, 0x094a0317,
+	0x20000000, 0x00000000, 0x1ff621e3, 0x0191f65f, 0x1fd88da4, 0x0322f4d8, 0x1fa7557f, 0x04b2041c,
+	0x20000000, 0x00000000, 0x1fa7557f, 0x04b2041c, 0x1e9f4157, 0x094a0317, 0x1ced7af4, 0x0dae8805,
+	0x1d906bcf, 0x0c3ef153, 0x1c38b2f2, 0x0f15ae9c, 0x1a9b6629, 0x11c73b3a, 0x18bc806b, 0x144cf325,
+	0x1f6297d0, 0x063e2e0f, 0x1f0a7efc, 0x07c67e5f, 0x1e9f4157, 0x094a0317, 0x1e212105, 0x0ac7cd3b,
+	0x1a9b6629, 0x11c73b3a, 0x17b5df22, 0x157d6935, 0x144cf325, 0x18bc806b, 0x10738799, 0x1b728345,
+	0x16a09e66, 0x16a09e66, 0x144cf325, 0x18bc806b, 0x11c73b3a, 0x1a9b6629, 0x0f15ae9c, 0x1c38b2f2,
+	0x1d906bcf, 0x0c3ef153, 0x1ced7af4, 0x0dae8805, 0x1c38b2f2, 0x0f15ae9c, 0x1b728345, 0x10738799,
+	0x0c3ef153, 0x1d906bcf, 0x07c67e5f, 0x1f0a7efc, 0x0322f4d8, 0x1fd88da4, 0xfe6e09a1, 0x1ff621e3,
+	0x0c3ef153, 0x1d906bcf, 0x094a0317, 0x1e9f4157, 0x063e2e0f, 0x1f6297d0, 0x0322f4d8, 0x1fd88da4,
+	0x1a9b6629, 0x11c73b3a, 0x19b3e048, 0x130ff7fd, 0x18bc806b, 0x144cf325, 0x17b5df22, 0x157d6935,
+	0xf9c1d1f1, 0x1f6297d0, 0xf53832c5, 0x1e212105, 0xf0ea5164, 0x1c38b2f2, 0xecf00803, 0x19b3e048,
+	0x00000000, 0x20000000, 0xfcdd0b28, 0x1fd88da4, 0xf9c1d1f1, 0x1f6297d0, 0xf6b5fce9, 0x1e9f4157,
+	0x16a09e66, 0x16a09e66, 0x157d6935, 0x17b5df22, 0x144cf325, 0x18bc806b, 0x130ff7fd, 0x19b3e048,
+	0xe95f619a, 0x16a09e66, 0xe64c1fb8, 0x130ff7fd, 0xe3c74d0e, 0x0f15ae9c, 0xe1dedefb, 0x0ac7cd3b,
+	0xf3c10ead, 0x1d906bcf, 0xf0ea5164, 0x1c38b2f2, 0xee38c4c6, 0x1a9b6629, 0xebb30cdb, 0x18bc806b,
+	0x11c73b3a, 0x1a9b6629, 0x10738799, 0x1b728345, 0x0f15ae9c, 0x1c38b2f2, 0x0dae8805, 0x1ced7af4,
+	0xe09d6830, 0x063e2e0f, 0xe009de1d, 0x0191f65f, 0xe027725c, 0xfcdd0b28, 0xe0f58104, 0xf83981a1,
+	0xe95f619a, 0x16a09e66, 0xe7437f95, 0x144cf325, 0xe56499d7, 0x11c73b3a, 0xe3c74d0e, 0x0f15ae9c,
+	0x0c3ef153, 0x1d906bcf, 0x0ac7cd3b, 0x1e212105, 0x094a0317, 0x1e9f4157, 0x07c67e5f, 0x1f0a7efc,
+	0xe26f9431, 0xf3c10ead, 0xe48d7cbb, 0xef8c7867, 0xe7437f95, 0xebb30cdb, 0xea8296cb, 0xe84a20de,
+	0xe26f9431, 0x0c3ef153, 0xe160bea9, 0x094a0317, 0xe09d6830, 0x063e2e0f, 0xe027725c, 0x0322f4d8,
+	0x063e2e0f, 0x1f6297d0, 0x04b2041c, 0x1fa7557f, 0x0322f4d8, 0x1fd88da4, 0x0191f65f, 0x1ff621e3,
+	0xee38c4c6, 0xe56499d7, 0xf25177fb, 0xe312850c, 0xf6b5fce9, 0xe160bea9, 0xfb4dfbe4, 0xe058aa81,
+
+	0x20000000, 0x00000000, 0x1ffd8861, 0x00c90ab0, 0x1ff621e3, 0x0191f65f, 0x1fe9cdad, 0x025aa412,
+	0x20000000, 0x00000000, 0x1fff6217, 0x00648748, 0x1ffd8861, 0x00c90ab0, 0x1ffa72f0, 0x012d8657,
+	0x20000000, 0x00000000, 0x1ffa72f0, 0x012d8657, 0x1fe9cdad, 0x025aa412, 0x1fce15fd, 0x0386f0b9,
+	0x1fd88da4, 0x0322f4d8, 0x1fc26471, 0x03eac9cb, 0x1fa7557f, 0x04b2041c, 0x1f8764fa, 0x05788511,
+	0x1ff621e3, 0x0191f65f, 0x1ff09566, 0x01f656e8, 0x1fe9cdad, 0x025aa412, 0x1fe1cafd, 0x02beda01,
+	0x1fa7557f, 0x04b2041c, 0x1f7599a4, 0x05db7678, 0x1f38f3ac, 0x0702e09b, 0x1ef178a4, 0x0827dc07,
+	0x1f6297d0, 0x063e2e0f, 0x1f38f3ac, 0x0702e09b, 0x1f0a7efc, 0x07c67e5f, 0x1ed740e7, 0x0888e931,
+	0x1fd88da4, 0x0322f4d8, 0x1fce15fd, 0x0386f0b9, 0x1fc26471, 0x03eac9cb, 0x1fb57972, 0x044e7c34,
+	0x1e9f4157, 0x094a0317, 0x1e426a4b, 0x0a68f121, 0x1ddb13b7, 0x0b844298, 0x1d696174, 0x0c9b9532,
+	0x1e9f4157, 0x094a0317, 0x1e6288ec, 0x0a09ae4a, 0x1e212105, 0x0ac7cd3b, 0x1ddb13b7, 0x0b844298,
+	0x1fa7557f, 0x04b2041c, 0x1f97f925, 0x05155dac, 0x1f8764fa, 0x05788511, 0x1f7599a4, 0x05db7678,
+	0x1ced7af4, 0x0dae8805, 0x1c678b35, 0x0ebcbbae, 0x1bd7c0ac, 0x0fc5d26e, 0x1b3e4d3f, 0x10c9704d,
+	0x1d906bcf, 0x0c3ef153, 0x1d4134d1, 0x0cf7bca2, 0x1ced7af4, 0x0dae8805, 0x1c954b21, 0x0e63374d,
+	0x1f6297d0, 0x063e2e0f, 0x1f4e603b, 0x06a0a809, 0x1f38f3ac, 0x0702e09b, 0x1f2252f7, 0x0764d3f9,
+	0x1a9b6629, 0x11c73b3a, 0x19ef43ef, 0x12bedb26, 0x193a224a, 0x13affa29, 0x187c4010, 0x149a449c,
+	0x1c38b2f2, 0x0f15ae9c, 0x1bd7c0ac, 0x0fc5d26e, 0x1b728345, 0x10738799, 0x1b090a58, 0x111eb354,
+	0x1f0a7efc, 0x07c67e5f, 0x1ef178a4, 0x0827dc07, 0x1ed740e7, 0x0888e931, 0x1ebbd8c9, 0x08e9a220,
+	0x17b5df22, 0x157d6935, 0x16e74455, 0x16591926, 0x1610b755, 0x172d0838, 0x15328293, 0x17f8ece3,
+	0x1a9b6629, 0x11c73b3a, 0x1a29a7a0, 0x126d054d, 0x19b3e048, 0x130ff7fd, 0x193a224a, 0x13affa29,
+	0x1e9f4157, 0x094a0317, 0x1e817bab, 0x09aa0861, 0x1e6288ec, 0x0a09ae4a, 0x1e426a4b, 0x0a68f121,
+	0x144cf325, 0x18bc806b, 0x136058b1, 0x19777ef5, 0x126d054d, 0x1a29a7a0, 0x11734d64, 0x1ad2bc9e,
+	0x18bc806b, 0x144cf325, 0x183b0e0c, 0x14e6cabc, 0x17b5df22, 0x157d6935, 0x172d0838, 0x1610b755,
+	0x1e212105, 0x0ac7cd3b, 0x1dfeae62, 0x0b263eef, 0x1ddb13b7, 0x0b844298, 0x1db65262, 0x0be1d499,
+	0x10738799, 0x1b728345, 0x0f6e0ca9, 0x1c08c426, 0x0e63374d, 0x1c954b21, 0x0d536416, 0x1d17e774,
+	0x16a09e66, 0x16a09e66, 0x1610b755, 0x172d0838, 0x157d6935, 0x17b5df22, 0x14e6cabc, 0x183b0e0c,
+	0x1d906bcf, 0x0c3ef153, 0x1d696174, 0x0c9b9532, 0x1d4134d1, 0x0cf7bca2, 0x1d17e774, 0x0d536416,
+	0x0c3ef153, 0x1d906bcf, 0x0b263eef, 0x1dfeae62, 0x0a09ae4a, 0x1e6288ec, 0x08e9a220, 0x1ebbd8c9,
+	0x144cf325, 0x18bc806b, 0x13affa29, 0x193a224a, 0x130ff7fd, 0x19b3e048, 0x126d054d, 0x1a29a7a0,
+	0x1ced7af4, 0x0dae8805, 0x1cc1f0f4, 0x0e0924ec, 0x1c954b21, 0x0e63374d, 0x1c678b35, 0x0ebcbbae,
+	0x07c67e5f, 0x1f0a7efc, 0x06a0a809, 0x1f4e603b, 0x05788511, 0x1f8764fa, 0x044e7c34, 0x1fb57972,
+	0x11c73b3a, 0x1a9b6629, 0x111eb354, 0x1b090a58, 0x10738799, 0x1b728345, 0x0fc5d26e, 0x1bd7c0ac,
+	0x1c38b2f2, 0x0f15ae9c, 0x1c08c426, 0x0f6e0ca9, 0x1bd7c0ac, 0x0fc5d26e, 0x1ba5aa67, 0x101cfc87,
+	0x0322f4d8, 0x1fd88da4, 0x01f656e8, 0x1ff09566, 0x00c90ab0, 0x1ffd8861, 0xff9b78b8, 0x1fff6217,
+	0x0f15ae9c, 0x1c38b2f2, 0x0e63374d, 0x1c954b21, 0x0dae8805, 0x1ced7af4, 0x0cf7bca2, 0x1d4134d1,
+	0x1b728345, 0x10738799, 0x1b3e4d3f, 0x10c9704d, 0x1b090a58, 0x111eb354, 0x1ad2bc9e, 0x11734d64,
+	0xfe6e09a1, 0x1ff621e3, 0xfd4125ff, 0x1fe1cafd, 0xfc153635, 0x1fc26471, 0xfaeaa254, 0x1f97f925,
+	0x0c3ef153, 0x1d906bcf, 0x0b844298, 0x1ddb13b7, 0x0ac7cd3b, 0x1e212105, 0x0a09ae4a, 0x1e6288ec,
+	0x1a9b6629, 0x11c73b3a, 0x1a63091b, 0x121a7999, 0x1a29a7a0, 0x126d054d, 0x19ef43ef, 0x12bedb26,
+	0xf9c1d1f1, 0x1f6297d0, 0xf89b2c07, 0x1f2252f7, 0xf77716cf, 0x1ed740e7, 0xf655f79f, 0x1e817bab,
+	0x094a0317, 0x1e9f4157, 0x0888e931, 0x1ed740e7, 0x07c67e5f, 0x1f0a7efc, 0x0702e09b, 0x1f38f3ac,
+	0x19b3e048, 0x130ff7fd, 0x19777ef5, 0x136058b1, 0x193a224a, 0x13affa29, 0x18fbcca4, 0x13fed953,
+	0xf53832c5, 0x1e212105, 0xf41e2b67, 0x1db65262, 0xf308435e, 0x1d4134d1, 0xf1f6db14, 0x1cc1f0f4,
+	0x063e2e0f, 0x1f6297d0, 0x05788511, 0x1f8764fa, 0x04b2041c, 0x1fa7557f, 0x03eac9cb, 0x1fc26471,
+	0x18bc806b, 0x144cf325, 0x187c4010, 0x149a449c, 0x183b0e0c, 0x14e6cabc, 0x17f8ece3, 0x15328293,
+	0xf0ea5164, 0x1c38b2f2, 0xefe30379, 0x1ba5aa67, 0xeee14cac, 0x1b090a58, 0xede58667, 0x1a63091b,
+	0x0322f4d8, 0x1fd88da4, 0x025aa412, 0x1fe9cdad, 0x0191f65f, 0x1ff621e3, 0x00c90ab0, 0x1ffd8861,
+	0x17b5df22, 0x157d6935, 0x1771e75f, 0x15c77bbe, 0x172d0838, 0x1610b755, 0x16e74455, 0x16591926,
+	0xecf00803, 0x19b3e048, 0xec0126ad, 0x18fbcca4, 0xeb193544, 0x183b0e0c, 0xea388442, 0x1771e75f,
+	0x00000000, 0x20000000, 0xff36f550, 0x1ffd8861, 0xfe6e09a1, 0x1ff621e3, 0xfda55bee, 0x1fe9cdad,
+	0x16a09e66, 0x16a09e66, 0x16591926, 0x16e74455, 0x1610b755, 0x172d0838, 0x15c77bbe, 0x1771e75f,
+	0xe95f619a, 0x16a09e66, 0xe88e18a1, 0x15c77bbe, 0xe7c4f1f4, 0x14e6cabc, 0xe704335c, 0x13fed953,
+	0xfcdd0b28, 0x1fd88da4, 0xfc153635, 0x1fc26471, 0xfb4dfbe4, 0x1fa7557f, 0xfa877aef, 0x1f8764fa,
+	0x157d6935, 0x17b5df22, 0x15328293, 0x17f8ece3, 0x14e6cabc, 0x183b0e0c, 0x149a449c, 0x187c4010,
+	0xe64c1fb8, 0x130ff7fd, 0xe59cf6e5, 0x121a7999, 0xe4f6f5a8, 0x111eb354, 0xe45a5599, 0x101cfc87,
+	0xf9c1d1f1, 0x1f6297d0, 0xf8fd1f65, 0x1f38f3ac, 0xf83981a1, 0x1f0a7efc, 0xf77716cf, 0x1ed740e7,
+	0x144cf325, 0x18bc806b, 0x13fed953, 0x18fbcca4, 0x13affa29, 0x193a224a, 0x136058b1, 0x19777ef5,
+	0xe3c74d0e, 0x0f15ae9c, 0xe33e0f0c, 0x0e0924ec, 0xe2becb2f, 0x0cf7bca2, 0xe249ad9e, 0x0be1d499,
+	0xf6b5fce9, 0x1e9f4157, 0xf5f651b6, 0x1e6288ec, 0xf53832c5, 0x1e212105, 0xf47bbd68, 0x1ddb13b7,
+	0x130ff7fd, 0x19b3e048, 0x12bedb26, 0x19ef43ef, 0x126d054d, 0x1a29a7a0, 0x121a7999, 0x1a63091b,
+	0xe1dedefb, 0x0ac7cd3b, 0xe17e8455, 0x09aa0861, 0xe128bf19, 0x0888e931, 0xe0ddad09, 0x0764d3f9,
+	0xf3c10ead, 0x1d906bcf, 0xf308435e, 0x1d4134d1, 0xf25177fb, 0x1ced7af4, 0xf19cc8b3, 0x1c954b21,
+	0x11c73b3a, 0x1a9b6629, 0x11734d64, 0x1ad2bc9e, 0x111eb354, 0x1b090a58, 0x10c9704d, 0x1b3e4d3f,
+	0xe09d6830, 0x063e2e0f, 0xe06806db, 0x05155dac, 0xe03d9b8f, 0x03eac9cb, 0xe01e3503, 0x02beda01,
+	0xf0ea5164, 0x1c38b2f2, 0xf03a2d92, 0x1bd7c0ac, 0xef8c7867, 0x1b728345, 0xeee14cac, 0x1b090a58,
+	0x10738799, 0x1b728345, 0x101cfc87, 0x1ba5aa67, 0x0fc5d26e, 0x1bd7c0ac, 0x0f6e0ca9, 0x1c08c426,
+	0xe009de1d, 0x0191f65f, 0xe0009de9, 0x00648748, 0xe002779f, 0xff36f550, 0xe00f6a9a, 0xfe09a918,
+	0xee38c4c6, 0x1a9b6629, 0xed92fab3, 0x1a29a7a0, 0xecf00803, 0x19b3e048, 0xec5005d7, 0x193a224a,
+	0x0f15ae9c, 0x1c38b2f2, 0x0ebcbbae, 0x1c678b35, 0x0e63374d, 0x1c954b21, 0x0e0924ec, 0x1cc1f0f4,
+	0xe027725c, 0xfcdd0b28, 0xe04a868e, 0xfbb183cc, 0xe0789b06, 0xfa877aef, 0xe0b19fc5, 0xf95f57f7,
+	0xebb30cdb, 0x18bc806b, 0xeb193544, 0x183b0e0c, 0xea8296cb, 0x17b5df22, 0xe9ef48ab, 0x172d0838,
+	0x0dae8805, 0x1ced7af4, 0x0d536416, 0x1d17e774, 0x0cf7bca2, 0x1d4134d1, 0x0c9b9532, 0x1d696174,
+	0xe0f58104, 0xf83981a1, 0xe1442737, 0xf7165de0, 0xe19d7714, 0xf5f651b6, 0xe201519e, 0xf4d9c111,
+	0xe95f619a, 0x16a09e66, 0xe8d2f7c8, 0x1610b755, 0xe84a20de, 0x157d6935, 0xe7c4f1f4, 0x14e6cabc,
+	0x0c3ef153, 0x1d906bcf, 0x0be1d499, 0x1db65262, 0x0b844298, 0x1ddb13b7, 0x0b263eef, 0x1dfeae62,
+	0xe26f9431, 0xf3c10ead, 0xe2e8188c, 0xf2ac9bea, 0xe36ab4df, 0xf19cc8b3, 0xe3f73bda, 0xf091f357,
+	0xe7437f95, 0x144cf325, 0xe6c5ddb6, 0x13affa29, 0xe64c1fb8, 0x130ff7fd, 0xe5d65860, 0x126d054d,
+	0x0ac7cd3b, 0x1e212105, 0x0a68f121, 0x1e426a4b, 0x0a09ae4a, 0x1e6288ec, 0x09aa0861, 0x1e817bab,
+	0xe48d7cbb, 0xef8c7867, 0xe52d4362, 0xee8cb29c, 0xe5d65860, 0xed92fab3, 0xe688810b, 0xec9fa74f,
+	0xe56499d7, 0x11c73b3a, 0xe4f6f5a8, 0x111eb354, 0xe48d7cbb, 0x10738799, 0xe4283f54, 0x0fc5d26e,
+	0x094a0317, 0x1e9f4157, 0x08e9a220, 0x1ebbd8c9, 0x0888e931, 0x1ed740e7, 0x0827dc07, 0x1ef178a4,
+	0xe7437f95, 0xebb30cdb, 0xe807131d, 0xeacd7d6d, 0xe8d2f7c8, 0xe9ef48ab, 0xe9a6e6da, 0xe918bbab,
+	0xe3c74d0e, 0x0f15ae9c, 0xe36ab4df, 0x0e63374d, 0xe312850c, 0x0dae8805, 0xe2becb2f, 0x0cf7bca2,
+	0x07c67e5f, 0x1f0a7efc, 0x0764d3f9, 0x1f2252f7, 0x0702e09b, 0x1f38f3ac, 0x06a0a809, 0x1f4e603b,
+	0xea8296cb, 0xe84a20de, 0xeb65bb64, 0xe783bff0, 0xec5005d7, 0xe6c5ddb6, 0xed4124da, 0xe610bc11,
+	0xe26f9431, 0x0c3ef153, 0xe224ec49, 0x0b844298, 0xe1dedefb, 0x0ac7cd3b, 0xe19d7714, 0x0a09ae4a,
+	0x063e2e0f, 0x1f6297d0, 0x05db7678, 0x1f7599a4, 0x05788511, 0x1f8764fa, 0x05155dac, 0x1f97f925,
+	0xee38c4c6, 0xe56499d7, 0xef368fb3, 0xe4c1b2c1, 0xf03a2d92, 0xe4283f54, 0xf1434452, 0xe39874cb,
+	0xe160bea9, 0x094a0317, 0xe128bf19, 0x0888e931, 0xe0f58104, 0x07c67e5f, 0xe0c70c54, 0x0702e09b,
+	0x04b2041c, 0x1fa7557f, 0x044e7c34, 0x1fb57972, 0x03eac9cb, 0x1fc26471, 0x0386f0b9, 0x1fce15fd,
+	0xf25177fb, 0xe312850c, 0xf3646ace, 0xe2969e8c, 0xf47bbd68, 0xe224ec49, 0xf5970edf, 0xe1bd95b5,
+	0xe09d6830, 0x063e2e0f, 0xe0789b06, 0x05788511, 0xe058aa81, 0x04b2041c, 0xe03d9b8f, 0x03eac9cb,
+	0x0322f4d8, 0x1fd88da4, 0x02beda01, 0x1fe1cafd, 0x025aa412, 0x1fe9cdad, 0x01f656e8, 0x1ff09566,
+	0xf6b5fce9, 0xe160bea9, 0xf7d823f9, 0xe10e875c, 0xf8fd1f65, 0xe0c70c54, 0xfa248988, 0xe08a665c,
+	0xe027725c, 0x0322f4d8, 0xe0163253, 0x025aa412, 0xe009de1d, 0x0191f65f, 0xe002779f, 0x00c90ab0,
+	0x0191f65f, 0x1ff621e3, 0x012d8657, 0x1ffa72f0, 0x00c90ab0, 0x1ffd8861, 0x00648748, 0x1fff6217,
+	0xfb4dfbe4, 0xe058aa81, 0xfc790f47, 0xe031ea03, 0xfda55bee, 0xe0163253, 0xfed279a9, 0xe0058d10
+};
+
+const int twidTab64[4*6 + 16*6] = {
+	0x20000000, 0x00000000, 0x16a09e66, 0x16a09e66, 0x00000000, 0x20000000, 0xe95f619a, 0x16a09e66,
+	0x20000000, 0x00000000, 0x1d906bcf, 0x0c3ef153, 0x16a09e66, 0x16a09e66, 0x0c3ef153, 0x1d906bcf,
+	0x20000000, 0x00000000, 0x0c3ef153, 0x1d906bcf, 0xe95f619a, 0x16a09e66, 0xe26f9431, 0xf3c10ead,
+
+	0x20000000, 0x00000000, 0x1f6297d0, 0x063e2e0f, 0x1d906bcf, 0x0c3ef153, 0x1a9b6629, 0x11c73b3a,
+	0x20000000, 0x00000000, 0x1fd88da4, 0x0322f4d8, 0x1f6297d0, 0x063e2e0f, 0x1e9f4157, 0x094a0317,
+	0x20000000, 0x00000000, 0x1e9f4157, 0x094a0317, 0x1a9b6629, 0x11c73b3a, 0x144cf325, 0x18bc806b,
+	0x16a09e66, 0x16a09e66, 0x11c73b3a, 0x1a9b6629, 0x0c3ef153, 0x1d906bcf, 0x063e2e0f, 0x1f6297d0,
+	0x1d906bcf, 0x0c3ef153, 0x1c38b2f2, 0x0f15ae9c, 0x1a9b6629, 0x11c73b3a, 0x18bc806b, 0x144cf325,
+	0x0c3ef153, 0x1d906bcf, 0x0322f4d8, 0x1fd88da4, 0xf9c1d1f1, 0x1f6297d0, 0xf0ea5164, 0x1c38b2f2,
+	0x00000000, 0x20000000, 0xf9c1d1f1, 0x1f6297d0, 0xf3c10ead, 0x1d906bcf, 0xee38c4c6, 0x1a9b6629,
+	0x16a09e66, 0x16a09e66, 0x144cf325, 0x18bc806b, 0x11c73b3a, 0x1a9b6629, 0x0f15ae9c, 0x1c38b2f2,
+	0xe95f619a, 0x16a09e66, 0xe3c74d0e, 0x0f15ae9c, 0xe09d6830, 0x063e2e0f, 0xe027725c, 0xfcdd0b28,
+	0xe95f619a, 0x16a09e66, 0xe56499d7, 0x11c73b3a, 0xe26f9431, 0x0c3ef153, 0xe09d6830, 0x063e2e0f,
+	0x0c3ef153, 0x1d906bcf, 0x094a0317, 0x1e9f4157, 0x063e2e0f, 0x1f6297d0, 0x0322f4d8, 0x1fd88da4,
+	0xe26f9431, 0xf3c10ead, 0xe7437f95, 0xebb30cdb, 0xee38c4c6, 0xe56499d7, 0xf6b5fce9, 0xe160bea9
+};
+
 #else
 
-/* 

- *  Q30 for 128 and 1024 

- *

- * for (i = 0; i < num/4; i++) {

- *   angle = (i + 0.125) * M_PI / num;

- *   x = cos(angle) * (1 << 30);

- *   x = sin(angle) * (1 << 30);

- * 

- *   angle = (num/2 - 1 - i + 0.125) * M_PI / num;

- *   x = cos(angle) * (1 << 30);

- *   x = sin(angle) * (1 << 30);

- * }

- */

-const int cossintab[128 + 1024] = {

-	/* 128 */

-	0x3fffec43, 0x003243f1, 0x015fd4d2, 0x3ffc38d1, 0x3ff9c13a, 0x01c454f5, 0x02f1b755, 0x3feea776, 

-	0x3fe9b8a9, 0x03562038, 0x0483259d, 0x3fd73a4a, 0x3fcfd50b, 0x04e767c5, 0x0613e1c5, 0x3fb5f4ea, 

-	0x3fac1a5b, 0x0677edbb, 0x07a3adff, 0x3f8adc77, 0x3f7e8e1e, 0x08077457, 0x09324ca7, 0x3f55f796, 

-	0x3f473759, 0x0995bdfd, 0x0abf8043, 0x3f174e70, 0x3f061e95, 0x0b228d42, 0x0c4b0b94, 0x3eceeaad, 

-	0x3ebb4ddb, 0x0cada4f5, 0x0dd4b19a, 0x3e7cd778, 0x3e66d0b4, 0x0e36c82a, 0x0f5c35a3, 0x3e212179, 

-	0x3e08b42a, 0x0fbdba40, 0x10e15b4e, 0x3dbbd6d4, 0x3da106bd, 0x11423ef0, 0x1263e699, 0x3d4d0728, 

-	0x3d2fd86c, 0x12c41a4f, 0x13e39be9, 0x3cd4c38b, 0x3cb53aaa, 0x144310dd, 0x15604013, 0x3c531e88, 

-	0x3c314060, 0x15bee78c, 0x16d99864, 0x3bc82c1f, 0x3ba3fde7, 0x173763c9, 0x184f6aab, 0x3b3401bb, 

-	0x3b0d8909, 0x18ac4b87, 0x19c17d44, 0x3a96b636, 0x3a6df8f8, 0x1a1d6544, 0x1b2f971e, 0x39f061d2, 

-	0x39c5664f, 0x1b8a7815, 0x1c997fc4, 0x39411e33, 0x3913eb0e, 0x1cf34baf, 0x1dfeff67, 0x38890663, 

-	0x3859a292, 0x1e57a86d, 0x1f5fdee6, 0x37c836c2, 0x3796a996, 0x1fb7575c, 0x20bbe7d8, 0x36fecd0e, 

-	0x36cb1e2a, 0x21122240, 0x2212e492, 0x362ce855, 0x35f71fb1, 0x2267d3a0, 0x2364a02e, 0x3552a8f4, 

-	0x351acedd, 0x23b836ca, 0x24b0e699, 0x34703095, 0x34364da6, 0x250317df, 0x25f78497, 0x3385a222, 

-	0x3349bf48, 0x264843d9, 0x273847c8, 0x329321c7, 0x32554840, 0x27878893, 0x2872feb6, 0x3198d4ea, 

-	0x31590e3e, 0x28c0b4d2, 0x29a778db, 0x3096e223, 0x30553828, 0x29f3984c, 0x2ad586a3, 0x2f8d713a, 

-	0x2f49ee0f, 0x2b2003ac, 0x2bfcf97c, 0x2e7cab1c, 0x2e37592c, 0x2c45c8a0, 0x2d1da3d5, 0x2d64b9da, 

-	/* 1024 */

-	0x3fffffb1, 0x0006487f, 0x002bfb74, 0x3ffff0e3, 0x3fffe705, 0x00388c6e, 0x005e3f4c, 0x3fffba9b, 

-	0x3fffa6de, 0x006ad03b, 0x009082ea, 0x3fff5cd8, 0x3fff3f3c, 0x009d13c5, 0x00c2c62f, 0x3ffed79b, 

-	0x3ffeb021, 0x00cf56ef, 0x00f508fc, 0x3ffe2ae5, 0x3ffdf98c, 0x01019998, 0x01274b31, 0x3ffd56b5, 

-	0x3ffd1b7e, 0x0133dba3, 0x01598cb1, 0x3ffc5b0c, 0x3ffc15f7, 0x01661cf0, 0x018bcd5b, 0x3ffb37ec, 

-	0x3ffae8f9, 0x01985d60, 0x01be0d11, 0x3ff9ed53, 0x3ff99483, 0x01ca9cd4, 0x01f04bb4, 0x3ff87b44, 

-	0x3ff81896, 0x01fcdb2e, 0x02228924, 0x3ff6e1bf, 0x3ff67534, 0x022f184d, 0x0254c544, 0x3ff520c5, 

-	0x3ff4aa5d, 0x02615414, 0x0286fff3, 0x3ff33858, 0x3ff2b813, 0x02938e62, 0x02b93914, 0x3ff12878, 

-	0x3ff09e56, 0x02c5c71a, 0x02eb7086, 0x3feef126, 0x3fee5d28, 0x02f7fe1c, 0x031da62b, 0x3fec9265, 

-	0x3febf48b, 0x032a3349, 0x034fd9e5, 0x3fea0c35, 0x3fe96480, 0x035c6682, 0x03820b93, 0x3fe75e98, 

-	0x3fe6ad08, 0x038e97a9, 0x03b43b17, 0x3fe48990, 0x3fe3ce26, 0x03c0c69e, 0x03e66852, 0x3fe18d1f, 

-	0x3fe0c7da, 0x03f2f342, 0x04189326, 0x3fde6945, 0x3fdd9a27, 0x04251d77, 0x044abb73, 0x3fdb1e06, 

-	0x3fda450f, 0x0457451d, 0x047ce11a, 0x3fd7ab64, 0x3fd6c894, 0x04896a16, 0x04af03fc, 0x3fd4115f, 

-	0x3fd324b7, 0x04bb8c42, 0x04e123fa, 0x3fd04ffc, 0x3fcf597c, 0x04edab83, 0x051340f6, 0x3fcc673b, 

-	0x3fcb66e4, 0x051fc7b9, 0x05455ad1, 0x3fc8571f, 0x3fc74cf3, 0x0551e0c7, 0x0577716b, 0x3fc41fac, 

-	0x3fc30baa, 0x0583f68c, 0x05a984a6, 0x3fbfc0e3, 0x3fbea30c, 0x05b608eb, 0x05db9463, 0x3fbb3ac7, 

-	0x3fba131b, 0x05e817c3, 0x060da083, 0x3fb68d5b, 0x3fb55bdc, 0x061a22f7, 0x063fa8e7, 0x3fb1b8a2, 

-	0x3fb07d50, 0x064c2a67, 0x0671ad71, 0x3facbc9f, 0x3fab777b, 0x067e2df5, 0x06a3ae00, 0x3fa79954, 

-	0x3fa64a5f, 0x06b02d81, 0x06d5aa77, 0x3fa24ec6, 0x3fa0f600, 0x06e228ee, 0x0707a2b7, 0x3f9cdcf7, 

-	0x3f9b7a62, 0x0714201b, 0x073996a1, 0x3f9743eb, 0x3f95d787, 0x074612eb, 0x076b8616, 0x3f9183a5, 

-	0x3f900d72, 0x0778013d, 0x079d70f7, 0x3f8b9c28, 0x3f8a1c29, 0x07a9eaf5, 0x07cf5726, 0x3f858d79, 

-	0x3f8403ae, 0x07dbcff2, 0x08013883, 0x3f7f579b, 0x3f7dc405, 0x080db016, 0x083314f1, 0x3f78fa92, 

-	0x3f775d31, 0x083f8b43, 0x0864ec4f, 0x3f727661, 0x3f70cf38, 0x08716159, 0x0896be80, 0x3f6bcb0e, 

-	0x3f6a1a1c, 0x08a3323a, 0x08c88b65, 0x3f64f89b, 0x3f633de2, 0x08d4fdc6, 0x08fa52de, 0x3f5dff0e, 

-	0x3f5c3a8f, 0x0906c3e0, 0x092c14ce, 0x3f56de6a, 0x3f551026, 0x09388469, 0x095dd116, 0x3f4f96b4, 

-	0x3f4dbeac, 0x096a3f42, 0x098f8796, 0x3f4827f0, 0x3f464626, 0x099bf44c, 0x09c13831, 0x3f409223, 

-	0x3f3ea697, 0x09cda368, 0x09f2e2c7, 0x3f38d552, 0x3f36e006, 0x09ff4c78, 0x0a24873a, 0x3f30f181, 

-	0x3f2ef276, 0x0a30ef5e, 0x0a56256c, 0x3f28e6b6, 0x3f26ddec, 0x0a628bfa, 0x0a87bd3d, 0x3f20b4f5, 

-	0x3f1ea26e, 0x0a94222f, 0x0ab94e8f, 0x3f185c43, 0x3f164001, 0x0ac5b1dc, 0x0aead944, 0x3f0fdca5, 

-	0x3f0db6a9, 0x0af73ae5, 0x0b1c5d3d, 0x3f073621, 0x3f05066d, 0x0b28bd2a, 0x0b4dda5c, 0x3efe68bc, 

-	0x3efc2f50, 0x0b5a388d, 0x0b7f5081, 0x3ef5747b, 0x3ef3315a, 0x0b8bacf0, 0x0bb0bf8f, 0x3eec5965, 

-	0x3eea0c8e, 0x0bbd1a33, 0x0be22766, 0x3ee3177e, 0x3ee0c0f4, 0x0bee8038, 0x0c1387e9, 0x3ed9aecc, 

-	0x3ed74e91, 0x0c1fdee1, 0x0c44e0f9, 0x3ed01f55, 0x3ecdb56a, 0x0c513610, 0x0c763278, 0x3ec66920, 

-	0x3ec3f585, 0x0c8285a5, 0x0ca77c47, 0x3ebc8c31, 0x3eba0ee9, 0x0cb3cd84, 0x0cd8be47, 0x3eb2888f, 

-	0x3eb0019c, 0x0ce50d8c, 0x0d09f85b, 0x3ea85e41, 0x3ea5cda3, 0x0d1645a0, 0x0d3b2a64, 0x3e9e0d4c, 

-	0x3e9b7306, 0x0d4775a1, 0x0d6c5443, 0x3e9395b7, 0x3e90f1ca, 0x0d789d71, 0x0d9d75db, 0x3e88f788, 

-	0x3e8649f5, 0x0da9bcf2, 0x0dce8f0d, 0x3e7e32c6, 0x3e7b7b90, 0x0ddad406, 0x0dff9fba, 0x3e734778, 

-	0x3e70869f, 0x0e0be28e, 0x0e30a7c5, 0x3e6835a4, 0x3e656b2b, 0x0e3ce86b, 0x0e61a70f, 0x3e5cfd51, 

-	0x3e5a2939, 0x0e6de580, 0x0e929d7a, 0x3e519e86, 0x3e4ec0d1, 0x0e9ed9af, 0x0ec38ae8, 0x3e46194a, 

-	0x3e4331fa, 0x0ecfc4d9, 0x0ef46f3b, 0x3e3a6da4, 0x3e377cbb, 0x0f00a6df, 0x0f254a53, 0x3e2e9b9c, 

-	0x3e2ba11b, 0x0f317fa5, 0x0f561c15, 0x3e22a338, 0x3e1f9f21, 0x0f624f0c, 0x0f86e460, 0x3e168480, 

-	0x3e1376d5, 0x0f9314f5, 0x0fb7a317, 0x3e0a3f7b, 0x3e07283f, 0x0fc3d143, 0x0fe8581d, 0x3dfdd432, 

-	0x3dfab365, 0x0ff483d7, 0x10190352, 0x3df142ab, 0x3dee1851, 0x10252c94, 0x1049a49a, 0x3de48aef, 

-	0x3de15708, 0x1055cb5b, 0x107a3bd5, 0x3dd7ad05, 0x3dd46f94, 0x1086600e, 0x10aac8e6, 0x3dcaa8f5, 

-	0x3dc761fc, 0x10b6ea90, 0x10db4baf, 0x3dbd7ec7, 0x3dba2e48, 0x10e76ac3, 0x110bc413, 0x3db02e84, 

-	0x3dacd481, 0x1117e088, 0x113c31f3, 0x3da2b834, 0x3d9f54af, 0x11484bc2, 0x116c9531, 0x3d951bde, 

-	0x3d91aed9, 0x1178ac53, 0x119cedaf, 0x3d87598c, 0x3d83e309, 0x11a9021d, 0x11cd3b50, 0x3d797145, 

-	0x3d75f147, 0x11d94d02, 0x11fd7df6, 0x3d6b6313, 0x3d67d99b, 0x12098ce5, 0x122db583, 0x3d5d2efe, 

-	0x3d599c0e, 0x1239c1a7, 0x125de1da, 0x3d4ed50f, 0x3d4b38aa, 0x1269eb2b, 0x128e02dc, 0x3d40554e, 

-	0x3d3caf76, 0x129a0954, 0x12be186c, 0x3d31afc5, 0x3d2e007c, 0x12ca1c03, 0x12ee226c, 0x3d22e47c, 

-	0x3d1f2bc5, 0x12fa231b, 0x131e20c0, 0x3d13f37e, 0x3d10315a, 0x132a1e7e, 0x134e1348, 0x3d04dcd2, 

-	0x3d011145, 0x135a0e0e, 0x137df9e7, 0x3cf5a082, 0x3cf1cb8e, 0x1389f1af, 0x13add481, 0x3ce63e98, 

-	0x3ce2603f, 0x13b9c943, 0x13dda2f7, 0x3cd6b71e, 0x3cd2cf62, 0x13e994ab, 0x140d652c, 0x3cc70a1c, 

-	0x3cc318ff, 0x141953cb, 0x143d1b02, 0x3cb7379c, 0x3cb33d22, 0x14490685, 0x146cc45c, 0x3ca73fa9, 

-	0x3ca33bd3, 0x1478acbc, 0x149c611d, 0x3c97224c, 0x3c93151d, 0x14a84652, 0x14cbf127, 0x3c86df8e, 

-	0x3c82c909, 0x14d7d32a, 0x14fb745e, 0x3c76777b, 0x3c7257a2, 0x15075327, 0x152aeaa3, 0x3c65ea1c, 

-	0x3c61c0f1, 0x1536c62b, 0x155a53d9, 0x3c55377b, 0x3c510501, 0x15662c18, 0x1589afe3, 0x3c445fa2, 

-	0x3c4023dd, 0x159584d3, 0x15b8fea4, 0x3c33629d, 0x3c2f1d8e, 0x15c4d03e, 0x15e83fff, 0x3c224075, 

-	0x3c1df21f, 0x15f40e3a, 0x161773d6, 0x3c10f935, 0x3c0ca19b, 0x16233eac, 0x16469a0d, 0x3bff8ce8, 

-	0x3bfb2c0c, 0x16526176, 0x1675b286, 0x3bedfb99, 0x3be9917e, 0x1681767c, 0x16a4bd25, 0x3bdc4552, 

-	0x3bd7d1fa, 0x16b07d9f, 0x16d3b9cc, 0x3bca6a1d, 0x3bc5ed8d, 0x16df76c3, 0x1702a85e, 0x3bb86a08, 

-	0x3bb3e440, 0x170e61cc, 0x173188be, 0x3ba6451b, 0x3ba1b620, 0x173d3e9b, 0x17605ad0, 0x3b93fb63, 

-	0x3b8f6337, 0x176c0d15, 0x178f1e76, 0x3b818ceb, 0x3b7ceb90, 0x179acd1c, 0x17bdd394, 0x3b6ef9be, 

-	0x3b6a4f38, 0x17c97e93, 0x17ec7a0d, 0x3b5c41e8, 0x3b578e39, 0x17f8215e, 0x181b11c4, 0x3b496574, 

-	0x3b44a8a0, 0x1826b561, 0x18499a9d, 0x3b36646e, 0x3b319e77, 0x18553a7d, 0x1878147a, 0x3b233ee1, 

-	0x3b1e6fca, 0x1883b097, 0x18a67f3f, 0x3b0ff4d9, 0x3b0b1ca6, 0x18b21791, 0x18d4dad0, 0x3afc8663, 

-	0x3af7a516, 0x18e06f50, 0x1903270f, 0x3ae8f38b, 0x3ae40926, 0x190eb7b7, 0x193163e1, 0x3ad53c5b, 

-	0x3ad048e3, 0x193cf0a9, 0x195f9128, 0x3ac160e1, 0x3abc6458, 0x196b1a09, 0x198daec8, 0x3aad6129, 

-	0x3aa85b92, 0x199933bb, 0x19bbbca6, 0x3a993d3e, 0x3a942e9d, 0x19c73da3, 0x19e9baa3, 0x3a84f52f, 

-	0x3a7fdd86, 0x19f537a4, 0x1a17a8a5, 0x3a708906, 0x3a6b6859, 0x1a2321a2, 0x1a45868e, 0x3a5bf8d1, 

-	0x3a56cf23, 0x1a50fb81, 0x1a735442, 0x3a47449c, 0x3a4211f0, 0x1a7ec524, 0x1aa111a6, 0x3a326c74, 

-	0x3a2d30cd, 0x1aac7e6f, 0x1acebe9d, 0x3a1d7066, 0x3a182bc8, 0x1ada2746, 0x1afc5b0a, 0x3a08507f, 

-	0x3a0302ed, 0x1b07bf8c, 0x1b29e6d2, 0x39f30ccc, 0x39edb649, 0x1b354727, 0x1b5761d8, 0x39dda55a, 

-	0x39d845e9, 0x1b62bdf8, 0x1b84cc01, 0x39c81a36, 0x39c2b1da, 0x1b9023e5, 0x1bb22530, 0x39b26b6d, 

-	0x39acfa2b, 0x1bbd78d2, 0x1bdf6d4a, 0x399c990d, 0x39971ee7, 0x1beabca1, 0x1c0ca432, 0x3986a324, 

-	0x3981201e, 0x1c17ef39, 0x1c39c9cd, 0x397089bf, 0x396afddc, 0x1c45107c, 0x1c66ddfe, 0x395a4ceb, 

-	0x3954b82e, 0x1c72204f, 0x1c93e0ab, 0x3943ecb6, 0x393e4f23, 0x1c9f1e96, 0x1cc0d1b6, 0x392d692f, 

-	0x3927c2c9, 0x1ccc0b35, 0x1cedb106, 0x3916c262, 0x3911132d, 0x1cf8e611, 0x1d1a7e7d, 0x38fff85e, 

-	0x38fa405e, 0x1d25af0d, 0x1d473a00, 0x38e90b31, 0x38e34a69, 0x1d52660f, 0x1d73e374, 0x38d1fae9, 

-	0x38cc315d, 0x1d7f0afb, 0x1da07abc, 0x38bac795, 0x38b4f547, 0x1dab9db5, 0x1dccffbf, 0x38a37142, 

-	0x389d9637, 0x1dd81e21, 0x1df9725f, 0x388bf7ff, 0x3886143b, 0x1e048c24, 0x1e25d282, 0x38745bdb, 

-	0x386e6f60, 0x1e30e7a4, 0x1e52200c, 0x385c9ce3, 0x3856a7b6, 0x1e5d3084, 0x1e7e5ae2, 0x3844bb28, 

-	0x383ebd4c, 0x1e8966a8, 0x1eaa82e9, 0x382cb6b7, 0x3826b030, 0x1eb589f7, 0x1ed69805, 0x38148f9f, 

-	0x380e8071, 0x1ee19a54, 0x1f029a1c, 0x37fc45ef, 0x37f62e1d, 0x1f0d97a5, 0x1f2e8911, 0x37e3d9b7, 

-	0x37ddb945, 0x1f3981ce, 0x1f5a64cb, 0x37cb4b04, 0x37c521f6, 0x1f6558b5, 0x1f862d2d, 0x37b299e7, 

-	0x37ac6841, 0x1f911c3d, 0x1fb1e21d, 0x3799c66f, 0x37938c34, 0x1fbccc4d, 0x1fdd8381, 0x3780d0aa, 

-	0x377a8ddf, 0x1fe868c8, 0x2009113c, 0x3767b8a9, 0x37616d51, 0x2013f196, 0x20348b35, 0x374e7e7b, 

-	0x37482a9a, 0x203f6699, 0x205ff14f, 0x3735222f, 0x372ec5c9, 0x206ac7b8, 0x208b4372, 0x371ba3d4, 

-	0x37153eee, 0x209614d9, 0x20b68181, 0x3702037c, 0x36fb9618, 0x20c14ddf, 0x20e1ab63, 0x36e84135, 

-	0x36e1cb58, 0x20ec72b1, 0x210cc0fc, 0x36ce5d10, 0x36c7debd, 0x21178334, 0x2137c232, 0x36b4571b, 

-	0x36add058, 0x21427f4d, 0x2162aeea, 0x369a2f69, 0x3693a038, 0x216d66e2, 0x218d870b, 0x367fe608, 

-	0x36794e6e, 0x219839d8, 0x21b84a79, 0x36657b08, 0x365edb09, 0x21c2f815, 0x21e2f91a, 0x364aee7b, 

-	0x3644461b, 0x21eda17f, 0x220d92d4, 0x36304070, 0x36298fb4, 0x221835fb, 0x2238178d, 0x361570f8, 

-	0x360eb7e3, 0x2242b56f, 0x22628729, 0x35fa8023, 0x35f3beba, 0x226d1fc1, 0x228ce191, 0x35df6e03, 

-	0x35d8a449, 0x229774d7, 0x22b726a8, 0x35c43aa7, 0x35bd68a1, 0x22c1b496, 0x22e15655, 0x35a8e621, 

-	0x35a20bd3, 0x22ebdee5, 0x230b707e, 0x358d7081, 0x35868def, 0x2315f3a8, 0x23357509, 0x3571d9d9, 

-	0x356aef08, 0x233ff2c8, 0x235f63dc, 0x35562239, 0x354f2f2c, 0x2369dc29, 0x23893cdd, 0x353a49b2, 

-	0x35334e6f, 0x2393afb2, 0x23b2fff3, 0x351e5056, 0x35174ce0, 0x23bd6d48, 0x23dcad03, 0x35023636, 

-	0x34fb2a92, 0x23e714d3, 0x240643f4, 0x34e5fb63, 0x34dee795, 0x2410a639, 0x242fc4ad, 0x34c99fef, 

-	0x34c283fb, 0x243a215f, 0x24592f13, 0x34ad23eb, 0x34a5ffd5, 0x2463862c, 0x2482830d, 0x34908768, 

-	0x34895b36, 0x248cd487, 0x24abc082, 0x3473ca79, 0x346c962f, 0x24b60c57, 0x24d4e757, 0x3456ed2f, 

-	0x344fb0d1, 0x24df2d81, 0x24fdf775, 0x3439ef9c, 0x3432ab2e, 0x250837ed, 0x2526f0c1, 0x341cd1d2, 

-	0x34158559, 0x25312b81, 0x254fd323, 0x33ff93e2, 0x33f83f62, 0x255a0823, 0x25789e80, 0x33e235df, 

-	0x33dad95e, 0x2582cdbc, 0x25a152c0, 0x33c4b7db, 0x33bd535c, 0x25ab7c30, 0x25c9efca, 0x33a719e8, 

-	0x339fad70, 0x25d41369, 0x25f27584, 0x33895c18, 0x3381e7ac, 0x25fc934b, 0x261ae3d6, 0x336b7e7e, 

-	0x33640223, 0x2624fbbf, 0x26433aa7, 0x334d812d, 0x3345fce6, 0x264d4cac, 0x266b79dd, 0x332f6435, 

-	0x3327d808, 0x267585f8, 0x2693a161, 0x331127ab, 0x3309939c, 0x269da78b, 0x26bbb119, 0x32f2cba1, 

-	0x32eb2fb5, 0x26c5b14c, 0x26e3a8ec, 0x32d45029, 0x32ccac64, 0x26eda322, 0x270b88c2, 0x32b5b557, 

-	0x32ae09be, 0x27157cf5, 0x27335082, 0x3296fb3d, 0x328f47d5, 0x273d3eac, 0x275b0014, 0x327821ee, 

-	0x327066bc, 0x2764e82f, 0x27829760, 0x3259297d, 0x32516686, 0x278c7965, 0x27aa164c, 0x323a11fe, 

-	0x32324746, 0x27b3f235, 0x27d17cc1, 0x321adb83, 0x3213090f, 0x27db5288, 0x27f8caa5, 0x31fb8620, 

-	0x31f3abf5, 0x28029a45, 0x281fffe2, 0x31dc11e8, 0x31d4300b, 0x2829c954, 0x28471c5e, 0x31bc7eee, 

-	0x31b49564, 0x2850df9d, 0x286e2002, 0x319ccd46, 0x3194dc14, 0x2877dd07, 0x28950ab6, 0x317cfd04, 

-	0x3175042e, 0x289ec17a, 0x28bbdc61, 0x315d0e3b, 0x31550dc6, 0x28c58cdf, 0x28e294eb, 0x313d00ff, 

-	0x3134f8f1, 0x28ec3f1e, 0x2909343e, 0x311cd564, 0x3114c5c0, 0x2912d81f, 0x292fba40, 0x30fc8b7d, 

-	0x30f47449, 0x293957c9, 0x295626da, 0x30dc235e, 0x30d404a0, 0x295fbe06, 0x297c79f5, 0x30bb9d1c, 

-	0x30b376d8, 0x29860abd, 0x29a2b378, 0x309af8ca, 0x3092cb05, 0x29ac3dd7, 0x29c8d34d, 0x307a367c, 

-	0x3072013c, 0x29d2573c, 0x29eed95b, 0x30595648, 0x30511991, 0x29f856d5, 0x2a14c58b, 0x30385840, 

-	0x30301418, 0x2a1e3c8a, 0x2a3a97c7, 0x30173c7a, 0x300ef0e5, 0x2a440844, 0x2a604ff5, 0x2ff6030a, 

-	0x2fedb00d, 0x2a69b9ec, 0x2a85ee00, 0x2fd4ac04, 0x2fcc51a5, 0x2a8f516b, 0x2aab71d0, 0x2fb3377c, 

-	0x2faad5c1, 0x2ab4cea9, 0x2ad0db4e, 0x2f91a589, 0x2f893c75, 0x2ada318e, 0x2af62a63, 0x2f6ff63d, 

-	0x2f6785d7, 0x2aff7a05, 0x2b1b5ef8, 0x2f4e29af, 0x2f45b1fb, 0x2b24a7f6, 0x2b4078f5, 0x2f2c3ff2, 

-	0x2f23c0f6, 0x2b49bb4a, 0x2b657844, 0x2f0a391d, 0x2f01b2de, 0x2b6eb3ea, 0x2b8a5cce, 0x2ee81543, 

-	0x2edf87c6, 0x2b9391c0, 0x2baf267d, 0x2ec5d479, 0x2ebd3fc4, 0x2bb854b4, 0x2bd3d53a, 0x2ea376d6, 

-	0x2e9adaee, 0x2bdcfcb0, 0x2bf868ed, 0x2e80fc6e, 0x2e785958, 0x2c01899e, 0x2c1ce181, 0x2e5e6556, 

-	0x2e55bb17, 0x2c25fb66, 0x2c413edf, 0x2e3bb1a4, 0x2e330042, 0x2c4a51f3, 0x2c6580f1, 0x2e18e16d, 

-	0x2e1028ed, 0x2c6e8d2e, 0x2c89a79f, 0x2df5f4c7, 0x2ded352f, 0x2c92ad01, 0x2cadb2d5, 0x2dd2ebc7, 

-	0x2dca251c, 0x2cb6b155, 0x2cd1a27b, 0x2dafc683, 0x2da6f8ca, 0x2cda9a14, 0x2cf5767c, 0x2d8c8510, 

-	0x2d83b04f, 0x2cfe6728, 0x2d192ec1, 0x2d692784, 0x2d604bc0, 0x2d22187a, 0x2d3ccb34, 0x2d45adf6

+/*
+ *  Q30 for 128 and 1024
+ *
+ * for (i = 0; i < num/4; i++) {
+ *   angle = (i + 0.125) * M_PI / num;
+ *   x = cos(angle) * (1 << 30);
+ *   x = sin(angle) * (1 << 30);
+ *
+ *   angle = (num/2 - 1 - i + 0.125) * M_PI / num;
+ *   x = cos(angle) * (1 << 30);
+ *   x = sin(angle) * (1 << 30);
+ * }
+ */
+const int cossintab[128 + 1024] = {
+	/* 128 */
+	0x3fffec43, 0x003243f1, 0x015fd4d2, 0x3ffc38d1, 0x3ff9c13a, 0x01c454f5, 0x02f1b755, 0x3feea776,
+	0x3fe9b8a9, 0x03562038, 0x0483259d, 0x3fd73a4a, 0x3fcfd50b, 0x04e767c5, 0x0613e1c5, 0x3fb5f4ea,
+	0x3fac1a5b, 0x0677edbb, 0x07a3adff, 0x3f8adc77, 0x3f7e8e1e, 0x08077457, 0x09324ca7, 0x3f55f796,
+	0x3f473759, 0x0995bdfd, 0x0abf8043, 0x3f174e70, 0x3f061e95, 0x0b228d42, 0x0c4b0b94, 0x3eceeaad,
+	0x3ebb4ddb, 0x0cada4f5, 0x0dd4b19a, 0x3e7cd778, 0x3e66d0b4, 0x0e36c82a, 0x0f5c35a3, 0x3e212179,
+	0x3e08b42a, 0x0fbdba40, 0x10e15b4e, 0x3dbbd6d4, 0x3da106bd, 0x11423ef0, 0x1263e699, 0x3d4d0728,
+	0x3d2fd86c, 0x12c41a4f, 0x13e39be9, 0x3cd4c38b, 0x3cb53aaa, 0x144310dd, 0x15604013, 0x3c531e88,
+	0x3c314060, 0x15bee78c, 0x16d99864, 0x3bc82c1f, 0x3ba3fde7, 0x173763c9, 0x184f6aab, 0x3b3401bb,
+	0x3b0d8909, 0x18ac4b87, 0x19c17d44, 0x3a96b636, 0x3a6df8f8, 0x1a1d6544, 0x1b2f971e, 0x39f061d2,
+	0x39c5664f, 0x1b8a7815, 0x1c997fc4, 0x39411e33, 0x3913eb0e, 0x1cf34baf, 0x1dfeff67, 0x38890663,
+	0x3859a292, 0x1e57a86d, 0x1f5fdee6, 0x37c836c2, 0x3796a996, 0x1fb7575c, 0x20bbe7d8, 0x36fecd0e,
+	0x36cb1e2a, 0x21122240, 0x2212e492, 0x362ce855, 0x35f71fb1, 0x2267d3a0, 0x2364a02e, 0x3552a8f4,
+	0x351acedd, 0x23b836ca, 0x24b0e699, 0x34703095, 0x34364da6, 0x250317df, 0x25f78497, 0x3385a222,
+	0x3349bf48, 0x264843d9, 0x273847c8, 0x329321c7, 0x32554840, 0x27878893, 0x2872feb6, 0x3198d4ea,
+	0x31590e3e, 0x28c0b4d2, 0x29a778db, 0x3096e223, 0x30553828, 0x29f3984c, 0x2ad586a3, 0x2f8d713a,
+	0x2f49ee0f, 0x2b2003ac, 0x2bfcf97c, 0x2e7cab1c, 0x2e37592c, 0x2c45c8a0, 0x2d1da3d5, 0x2d64b9da,
+	/* 1024 */
+	0x3fffffb1, 0x0006487f, 0x002bfb74, 0x3ffff0e3, 0x3fffe705, 0x00388c6e, 0x005e3f4c, 0x3fffba9b,
+	0x3fffa6de, 0x006ad03b, 0x009082ea, 0x3fff5cd8, 0x3fff3f3c, 0x009d13c5, 0x00c2c62f, 0x3ffed79b,
+	0x3ffeb021, 0x00cf56ef, 0x00f508fc, 0x3ffe2ae5, 0x3ffdf98c, 0x01019998, 0x01274b31, 0x3ffd56b5,
+	0x3ffd1b7e, 0x0133dba3, 0x01598cb1, 0x3ffc5b0c, 0x3ffc15f7, 0x01661cf0, 0x018bcd5b, 0x3ffb37ec,
+	0x3ffae8f9, 0x01985d60, 0x01be0d11, 0x3ff9ed53, 0x3ff99483, 0x01ca9cd4, 0x01f04bb4, 0x3ff87b44,
+	0x3ff81896, 0x01fcdb2e, 0x02228924, 0x3ff6e1bf, 0x3ff67534, 0x022f184d, 0x0254c544, 0x3ff520c5,
+	0x3ff4aa5d, 0x02615414, 0x0286fff3, 0x3ff33858, 0x3ff2b813, 0x02938e62, 0x02b93914, 0x3ff12878,
+	0x3ff09e56, 0x02c5c71a, 0x02eb7086, 0x3feef126, 0x3fee5d28, 0x02f7fe1c, 0x031da62b, 0x3fec9265,
+	0x3febf48b, 0x032a3349, 0x034fd9e5, 0x3fea0c35, 0x3fe96480, 0x035c6682, 0x03820b93, 0x3fe75e98,
+	0x3fe6ad08, 0x038e97a9, 0x03b43b17, 0x3fe48990, 0x3fe3ce26, 0x03c0c69e, 0x03e66852, 0x3fe18d1f,
+	0x3fe0c7da, 0x03f2f342, 0x04189326, 0x3fde6945, 0x3fdd9a27, 0x04251d77, 0x044abb73, 0x3fdb1e06,
+	0x3fda450f, 0x0457451d, 0x047ce11a, 0x3fd7ab64, 0x3fd6c894, 0x04896a16, 0x04af03fc, 0x3fd4115f,
+	0x3fd324b7, 0x04bb8c42, 0x04e123fa, 0x3fd04ffc, 0x3fcf597c, 0x04edab83, 0x051340f6, 0x3fcc673b,
+	0x3fcb66e4, 0x051fc7b9, 0x05455ad1, 0x3fc8571f, 0x3fc74cf3, 0x0551e0c7, 0x0577716b, 0x3fc41fac,
+	0x3fc30baa, 0x0583f68c, 0x05a984a6, 0x3fbfc0e3, 0x3fbea30c, 0x05b608eb, 0x05db9463, 0x3fbb3ac7,
+	0x3fba131b, 0x05e817c3, 0x060da083, 0x3fb68d5b, 0x3fb55bdc, 0x061a22f7, 0x063fa8e7, 0x3fb1b8a2,
+	0x3fb07d50, 0x064c2a67, 0x0671ad71, 0x3facbc9f, 0x3fab777b, 0x067e2df5, 0x06a3ae00, 0x3fa79954,
+	0x3fa64a5f, 0x06b02d81, 0x06d5aa77, 0x3fa24ec6, 0x3fa0f600, 0x06e228ee, 0x0707a2b7, 0x3f9cdcf7,
+	0x3f9b7a62, 0x0714201b, 0x073996a1, 0x3f9743eb, 0x3f95d787, 0x074612eb, 0x076b8616, 0x3f9183a5,
+	0x3f900d72, 0x0778013d, 0x079d70f7, 0x3f8b9c28, 0x3f8a1c29, 0x07a9eaf5, 0x07cf5726, 0x3f858d79,
+	0x3f8403ae, 0x07dbcff2, 0x08013883, 0x3f7f579b, 0x3f7dc405, 0x080db016, 0x083314f1, 0x3f78fa92,
+	0x3f775d31, 0x083f8b43, 0x0864ec4f, 0x3f727661, 0x3f70cf38, 0x08716159, 0x0896be80, 0x3f6bcb0e,
+	0x3f6a1a1c, 0x08a3323a, 0x08c88b65, 0x3f64f89b, 0x3f633de2, 0x08d4fdc6, 0x08fa52de, 0x3f5dff0e,
+	0x3f5c3a8f, 0x0906c3e0, 0x092c14ce, 0x3f56de6a, 0x3f551026, 0x09388469, 0x095dd116, 0x3f4f96b4,
+	0x3f4dbeac, 0x096a3f42, 0x098f8796, 0x3f4827f0, 0x3f464626, 0x099bf44c, 0x09c13831, 0x3f409223,
+	0x3f3ea697, 0x09cda368, 0x09f2e2c7, 0x3f38d552, 0x3f36e006, 0x09ff4c78, 0x0a24873a, 0x3f30f181,
+	0x3f2ef276, 0x0a30ef5e, 0x0a56256c, 0x3f28e6b6, 0x3f26ddec, 0x0a628bfa, 0x0a87bd3d, 0x3f20b4f5,
+	0x3f1ea26e, 0x0a94222f, 0x0ab94e8f, 0x3f185c43, 0x3f164001, 0x0ac5b1dc, 0x0aead944, 0x3f0fdca5,
+	0x3f0db6a9, 0x0af73ae5, 0x0b1c5d3d, 0x3f073621, 0x3f05066d, 0x0b28bd2a, 0x0b4dda5c, 0x3efe68bc,
+	0x3efc2f50, 0x0b5a388d, 0x0b7f5081, 0x3ef5747b, 0x3ef3315a, 0x0b8bacf0, 0x0bb0bf8f, 0x3eec5965,
+	0x3eea0c8e, 0x0bbd1a33, 0x0be22766, 0x3ee3177e, 0x3ee0c0f4, 0x0bee8038, 0x0c1387e9, 0x3ed9aecc,
+	0x3ed74e91, 0x0c1fdee1, 0x0c44e0f9, 0x3ed01f55, 0x3ecdb56a, 0x0c513610, 0x0c763278, 0x3ec66920,
+	0x3ec3f585, 0x0c8285a5, 0x0ca77c47, 0x3ebc8c31, 0x3eba0ee9, 0x0cb3cd84, 0x0cd8be47, 0x3eb2888f,
+	0x3eb0019c, 0x0ce50d8c, 0x0d09f85b, 0x3ea85e41, 0x3ea5cda3, 0x0d1645a0, 0x0d3b2a64, 0x3e9e0d4c,
+	0x3e9b7306, 0x0d4775a1, 0x0d6c5443, 0x3e9395b7, 0x3e90f1ca, 0x0d789d71, 0x0d9d75db, 0x3e88f788,
+	0x3e8649f5, 0x0da9bcf2, 0x0dce8f0d, 0x3e7e32c6, 0x3e7b7b90, 0x0ddad406, 0x0dff9fba, 0x3e734778,
+	0x3e70869f, 0x0e0be28e, 0x0e30a7c5, 0x3e6835a4, 0x3e656b2b, 0x0e3ce86b, 0x0e61a70f, 0x3e5cfd51,
+	0x3e5a2939, 0x0e6de580, 0x0e929d7a, 0x3e519e86, 0x3e4ec0d1, 0x0e9ed9af, 0x0ec38ae8, 0x3e46194a,
+	0x3e4331fa, 0x0ecfc4d9, 0x0ef46f3b, 0x3e3a6da4, 0x3e377cbb, 0x0f00a6df, 0x0f254a53, 0x3e2e9b9c,
+	0x3e2ba11b, 0x0f317fa5, 0x0f561c15, 0x3e22a338, 0x3e1f9f21, 0x0f624f0c, 0x0f86e460, 0x3e168480,
+	0x3e1376d5, 0x0f9314f5, 0x0fb7a317, 0x3e0a3f7b, 0x3e07283f, 0x0fc3d143, 0x0fe8581d, 0x3dfdd432,
+	0x3dfab365, 0x0ff483d7, 0x10190352, 0x3df142ab, 0x3dee1851, 0x10252c94, 0x1049a49a, 0x3de48aef,
+	0x3de15708, 0x1055cb5b, 0x107a3bd5, 0x3dd7ad05, 0x3dd46f94, 0x1086600e, 0x10aac8e6, 0x3dcaa8f5,
+	0x3dc761fc, 0x10b6ea90, 0x10db4baf, 0x3dbd7ec7, 0x3dba2e48, 0x10e76ac3, 0x110bc413, 0x3db02e84,
+	0x3dacd481, 0x1117e088, 0x113c31f3, 0x3da2b834, 0x3d9f54af, 0x11484bc2, 0x116c9531, 0x3d951bde,
+	0x3d91aed9, 0x1178ac53, 0x119cedaf, 0x3d87598c, 0x3d83e309, 0x11a9021d, 0x11cd3b50, 0x3d797145,
+	0x3d75f147, 0x11d94d02, 0x11fd7df6, 0x3d6b6313, 0x3d67d99b, 0x12098ce5, 0x122db583, 0x3d5d2efe,
+	0x3d599c0e, 0x1239c1a7, 0x125de1da, 0x3d4ed50f, 0x3d4b38aa, 0x1269eb2b, 0x128e02dc, 0x3d40554e,
+	0x3d3caf76, 0x129a0954, 0x12be186c, 0x3d31afc5, 0x3d2e007c, 0x12ca1c03, 0x12ee226c, 0x3d22e47c,
+	0x3d1f2bc5, 0x12fa231b, 0x131e20c0, 0x3d13f37e, 0x3d10315a, 0x132a1e7e, 0x134e1348, 0x3d04dcd2,
+	0x3d011145, 0x135a0e0e, 0x137df9e7, 0x3cf5a082, 0x3cf1cb8e, 0x1389f1af, 0x13add481, 0x3ce63e98,
+	0x3ce2603f, 0x13b9c943, 0x13dda2f7, 0x3cd6b71e, 0x3cd2cf62, 0x13e994ab, 0x140d652c, 0x3cc70a1c,
+	0x3cc318ff, 0x141953cb, 0x143d1b02, 0x3cb7379c, 0x3cb33d22, 0x14490685, 0x146cc45c, 0x3ca73fa9,
+	0x3ca33bd3, 0x1478acbc, 0x149c611d, 0x3c97224c, 0x3c93151d, 0x14a84652, 0x14cbf127, 0x3c86df8e,
+	0x3c82c909, 0x14d7d32a, 0x14fb745e, 0x3c76777b, 0x3c7257a2, 0x15075327, 0x152aeaa3, 0x3c65ea1c,
+	0x3c61c0f1, 0x1536c62b, 0x155a53d9, 0x3c55377b, 0x3c510501, 0x15662c18, 0x1589afe3, 0x3c445fa2,
+	0x3c4023dd, 0x159584d3, 0x15b8fea4, 0x3c33629d, 0x3c2f1d8e, 0x15c4d03e, 0x15e83fff, 0x3c224075,
+	0x3c1df21f, 0x15f40e3a, 0x161773d6, 0x3c10f935, 0x3c0ca19b, 0x16233eac, 0x16469a0d, 0x3bff8ce8,
+	0x3bfb2c0c, 0x16526176, 0x1675b286, 0x3bedfb99, 0x3be9917e, 0x1681767c, 0x16a4bd25, 0x3bdc4552,
+	0x3bd7d1fa, 0x16b07d9f, 0x16d3b9cc, 0x3bca6a1d, 0x3bc5ed8d, 0x16df76c3, 0x1702a85e, 0x3bb86a08,
+	0x3bb3e440, 0x170e61cc, 0x173188be, 0x3ba6451b, 0x3ba1b620, 0x173d3e9b, 0x17605ad0, 0x3b93fb63,
+	0x3b8f6337, 0x176c0d15, 0x178f1e76, 0x3b818ceb, 0x3b7ceb90, 0x179acd1c, 0x17bdd394, 0x3b6ef9be,
+	0x3b6a4f38, 0x17c97e93, 0x17ec7a0d, 0x3b5c41e8, 0x3b578e39, 0x17f8215e, 0x181b11c4, 0x3b496574,
+	0x3b44a8a0, 0x1826b561, 0x18499a9d, 0x3b36646e, 0x3b319e77, 0x18553a7d, 0x1878147a, 0x3b233ee1,
+	0x3b1e6fca, 0x1883b097, 0x18a67f3f, 0x3b0ff4d9, 0x3b0b1ca6, 0x18b21791, 0x18d4dad0, 0x3afc8663,
+	0x3af7a516, 0x18e06f50, 0x1903270f, 0x3ae8f38b, 0x3ae40926, 0x190eb7b7, 0x193163e1, 0x3ad53c5b,
+	0x3ad048e3, 0x193cf0a9, 0x195f9128, 0x3ac160e1, 0x3abc6458, 0x196b1a09, 0x198daec8, 0x3aad6129,
+	0x3aa85b92, 0x199933bb, 0x19bbbca6, 0x3a993d3e, 0x3a942e9d, 0x19c73da3, 0x19e9baa3, 0x3a84f52f,
+	0x3a7fdd86, 0x19f537a4, 0x1a17a8a5, 0x3a708906, 0x3a6b6859, 0x1a2321a2, 0x1a45868e, 0x3a5bf8d1,
+	0x3a56cf23, 0x1a50fb81, 0x1a735442, 0x3a47449c, 0x3a4211f0, 0x1a7ec524, 0x1aa111a6, 0x3a326c74,
+	0x3a2d30cd, 0x1aac7e6f, 0x1acebe9d, 0x3a1d7066, 0x3a182bc8, 0x1ada2746, 0x1afc5b0a, 0x3a08507f,
+	0x3a0302ed, 0x1b07bf8c, 0x1b29e6d2, 0x39f30ccc, 0x39edb649, 0x1b354727, 0x1b5761d8, 0x39dda55a,
+	0x39d845e9, 0x1b62bdf8, 0x1b84cc01, 0x39c81a36, 0x39c2b1da, 0x1b9023e5, 0x1bb22530, 0x39b26b6d,
+	0x39acfa2b, 0x1bbd78d2, 0x1bdf6d4a, 0x399c990d, 0x39971ee7, 0x1beabca1, 0x1c0ca432, 0x3986a324,
+	0x3981201e, 0x1c17ef39, 0x1c39c9cd, 0x397089bf, 0x396afddc, 0x1c45107c, 0x1c66ddfe, 0x395a4ceb,
+	0x3954b82e, 0x1c72204f, 0x1c93e0ab, 0x3943ecb6, 0x393e4f23, 0x1c9f1e96, 0x1cc0d1b6, 0x392d692f,
+	0x3927c2c9, 0x1ccc0b35, 0x1cedb106, 0x3916c262, 0x3911132d, 0x1cf8e611, 0x1d1a7e7d, 0x38fff85e,
+	0x38fa405e, 0x1d25af0d, 0x1d473a00, 0x38e90b31, 0x38e34a69, 0x1d52660f, 0x1d73e374, 0x38d1fae9,
+	0x38cc315d, 0x1d7f0afb, 0x1da07abc, 0x38bac795, 0x38b4f547, 0x1dab9db5, 0x1dccffbf, 0x38a37142,
+	0x389d9637, 0x1dd81e21, 0x1df9725f, 0x388bf7ff, 0x3886143b, 0x1e048c24, 0x1e25d282, 0x38745bdb,
+	0x386e6f60, 0x1e30e7a4, 0x1e52200c, 0x385c9ce3, 0x3856a7b6, 0x1e5d3084, 0x1e7e5ae2, 0x3844bb28,
+	0x383ebd4c, 0x1e8966a8, 0x1eaa82e9, 0x382cb6b7, 0x3826b030, 0x1eb589f7, 0x1ed69805, 0x38148f9f,
+	0x380e8071, 0x1ee19a54, 0x1f029a1c, 0x37fc45ef, 0x37f62e1d, 0x1f0d97a5, 0x1f2e8911, 0x37e3d9b7,
+	0x37ddb945, 0x1f3981ce, 0x1f5a64cb, 0x37cb4b04, 0x37c521f6, 0x1f6558b5, 0x1f862d2d, 0x37b299e7,
+	0x37ac6841, 0x1f911c3d, 0x1fb1e21d, 0x3799c66f, 0x37938c34, 0x1fbccc4d, 0x1fdd8381, 0x3780d0aa,
+	0x377a8ddf, 0x1fe868c8, 0x2009113c, 0x3767b8a9, 0x37616d51, 0x2013f196, 0x20348b35, 0x374e7e7b,
+	0x37482a9a, 0x203f6699, 0x205ff14f, 0x3735222f, 0x372ec5c9, 0x206ac7b8, 0x208b4372, 0x371ba3d4,
+	0x37153eee, 0x209614d9, 0x20b68181, 0x3702037c, 0x36fb9618, 0x20c14ddf, 0x20e1ab63, 0x36e84135,
+	0x36e1cb58, 0x20ec72b1, 0x210cc0fc, 0x36ce5d10, 0x36c7debd, 0x21178334, 0x2137c232, 0x36b4571b,
+	0x36add058, 0x21427f4d, 0x2162aeea, 0x369a2f69, 0x3693a038, 0x216d66e2, 0x218d870b, 0x367fe608,
+	0x36794e6e, 0x219839d8, 0x21b84a79, 0x36657b08, 0x365edb09, 0x21c2f815, 0x21e2f91a, 0x364aee7b,
+	0x3644461b, 0x21eda17f, 0x220d92d4, 0x36304070, 0x36298fb4, 0x221835fb, 0x2238178d, 0x361570f8,
+	0x360eb7e3, 0x2242b56f, 0x22628729, 0x35fa8023, 0x35f3beba, 0x226d1fc1, 0x228ce191, 0x35df6e03,
+	0x35d8a449, 0x229774d7, 0x22b726a8, 0x35c43aa7, 0x35bd68a1, 0x22c1b496, 0x22e15655, 0x35a8e621,
+	0x35a20bd3, 0x22ebdee5, 0x230b707e, 0x358d7081, 0x35868def, 0x2315f3a8, 0x23357509, 0x3571d9d9,
+	0x356aef08, 0x233ff2c8, 0x235f63dc, 0x35562239, 0x354f2f2c, 0x2369dc29, 0x23893cdd, 0x353a49b2,
+	0x35334e6f, 0x2393afb2, 0x23b2fff3, 0x351e5056, 0x35174ce0, 0x23bd6d48, 0x23dcad03, 0x35023636,
+	0x34fb2a92, 0x23e714d3, 0x240643f4, 0x34e5fb63, 0x34dee795, 0x2410a639, 0x242fc4ad, 0x34c99fef,
+	0x34c283fb, 0x243a215f, 0x24592f13, 0x34ad23eb, 0x34a5ffd5, 0x2463862c, 0x2482830d, 0x34908768,
+	0x34895b36, 0x248cd487, 0x24abc082, 0x3473ca79, 0x346c962f, 0x24b60c57, 0x24d4e757, 0x3456ed2f,
+	0x344fb0d1, 0x24df2d81, 0x24fdf775, 0x3439ef9c, 0x3432ab2e, 0x250837ed, 0x2526f0c1, 0x341cd1d2,
+	0x34158559, 0x25312b81, 0x254fd323, 0x33ff93e2, 0x33f83f62, 0x255a0823, 0x25789e80, 0x33e235df,
+	0x33dad95e, 0x2582cdbc, 0x25a152c0, 0x33c4b7db, 0x33bd535c, 0x25ab7c30, 0x25c9efca, 0x33a719e8,
+	0x339fad70, 0x25d41369, 0x25f27584, 0x33895c18, 0x3381e7ac, 0x25fc934b, 0x261ae3d6, 0x336b7e7e,
+	0x33640223, 0x2624fbbf, 0x26433aa7, 0x334d812d, 0x3345fce6, 0x264d4cac, 0x266b79dd, 0x332f6435,
+	0x3327d808, 0x267585f8, 0x2693a161, 0x331127ab, 0x3309939c, 0x269da78b, 0x26bbb119, 0x32f2cba1,
+	0x32eb2fb5, 0x26c5b14c, 0x26e3a8ec, 0x32d45029, 0x32ccac64, 0x26eda322, 0x270b88c2, 0x32b5b557,
+	0x32ae09be, 0x27157cf5, 0x27335082, 0x3296fb3d, 0x328f47d5, 0x273d3eac, 0x275b0014, 0x327821ee,
+	0x327066bc, 0x2764e82f, 0x27829760, 0x3259297d, 0x32516686, 0x278c7965, 0x27aa164c, 0x323a11fe,
+	0x32324746, 0x27b3f235, 0x27d17cc1, 0x321adb83, 0x3213090f, 0x27db5288, 0x27f8caa5, 0x31fb8620,
+	0x31f3abf5, 0x28029a45, 0x281fffe2, 0x31dc11e8, 0x31d4300b, 0x2829c954, 0x28471c5e, 0x31bc7eee,
+	0x31b49564, 0x2850df9d, 0x286e2002, 0x319ccd46, 0x3194dc14, 0x2877dd07, 0x28950ab6, 0x317cfd04,
+	0x3175042e, 0x289ec17a, 0x28bbdc61, 0x315d0e3b, 0x31550dc6, 0x28c58cdf, 0x28e294eb, 0x313d00ff,
+	0x3134f8f1, 0x28ec3f1e, 0x2909343e, 0x311cd564, 0x3114c5c0, 0x2912d81f, 0x292fba40, 0x30fc8b7d,
+	0x30f47449, 0x293957c9, 0x295626da, 0x30dc235e, 0x30d404a0, 0x295fbe06, 0x297c79f5, 0x30bb9d1c,
+	0x30b376d8, 0x29860abd, 0x29a2b378, 0x309af8ca, 0x3092cb05, 0x29ac3dd7, 0x29c8d34d, 0x307a367c,
+	0x3072013c, 0x29d2573c, 0x29eed95b, 0x30595648, 0x30511991, 0x29f856d5, 0x2a14c58b, 0x30385840,
+	0x30301418, 0x2a1e3c8a, 0x2a3a97c7, 0x30173c7a, 0x300ef0e5, 0x2a440844, 0x2a604ff5, 0x2ff6030a,
+	0x2fedb00d, 0x2a69b9ec, 0x2a85ee00, 0x2fd4ac04, 0x2fcc51a5, 0x2a8f516b, 0x2aab71d0, 0x2fb3377c,
+	0x2faad5c1, 0x2ab4cea9, 0x2ad0db4e, 0x2f91a589, 0x2f893c75, 0x2ada318e, 0x2af62a63, 0x2f6ff63d,
+	0x2f6785d7, 0x2aff7a05, 0x2b1b5ef8, 0x2f4e29af, 0x2f45b1fb, 0x2b24a7f6, 0x2b4078f5, 0x2f2c3ff2,
+	0x2f23c0f6, 0x2b49bb4a, 0x2b657844, 0x2f0a391d, 0x2f01b2de, 0x2b6eb3ea, 0x2b8a5cce, 0x2ee81543,
+	0x2edf87c6, 0x2b9391c0, 0x2baf267d, 0x2ec5d479, 0x2ebd3fc4, 0x2bb854b4, 0x2bd3d53a, 0x2ea376d6,
+	0x2e9adaee, 0x2bdcfcb0, 0x2bf868ed, 0x2e80fc6e, 0x2e785958, 0x2c01899e, 0x2c1ce181, 0x2e5e6556,
+	0x2e55bb17, 0x2c25fb66, 0x2c413edf, 0x2e3bb1a4, 0x2e330042, 0x2c4a51f3, 0x2c6580f1, 0x2e18e16d,
+	0x2e1028ed, 0x2c6e8d2e, 0x2c89a79f, 0x2df5f4c7, 0x2ded352f, 0x2c92ad01, 0x2cadb2d5, 0x2dd2ebc7,
+	0x2dca251c, 0x2cb6b155, 0x2cd1a27b, 0x2dafc683, 0x2da6f8ca, 0x2cda9a14, 0x2cf5767c, 0x2d8c8510,
+	0x2d83b04f, 0x2cfe6728, 0x2d192ec1, 0x2d692784, 0x2d604bc0, 0x2d22187a, 0x2d3ccb34, 0x2d45adf6
 };
 
-const int twidTab512[8*6 + 32*6 + 128*6] = {

-	0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x3b20d79e, 0x187de2a6, 

-	0x3ec52f9f, 0x0c7c5c1e, 0x3536cc52, 0x238e7673, 0x2d413ccc, 0x2d413ccc, 0x3b20d79e, 0x187de2a6, 

-	0x187de2a6, 0x3b20d79e, 0x187de2a6, 0x3b20d79e, 0x3536cc52, 0x238e7673, 0xf383a3e2, 0x3ec52f9f, 

-	0x00000000, 0x40000000, 0x2d413ccc, 0x2d413ccc, 0xd2bec334, 0x2d413ccc, 0xe7821d5a, 0x3b20d79e, 

-	0x238e7673, 0x3536cc52, 0xc13ad061, 0x0c7c5c1e, 0xd2bec334, 0x2d413ccc, 0x187de2a6, 0x3b20d79e, 

-	0xc4df2862, 0xe7821d5a, 0xc4df2862, 0x187de2a6, 0x0c7c5c1e, 0x3ec52f9f, 0xdc71898d, 0xcac933ae, 

-

-	0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x3fb11b47, 0x0645e9af, 

-	0x3fec43c6, 0x0323ecbe, 0x3f4eaafe, 0x09640837, 0x3ec52f9f, 0x0c7c5c1e, 0x3fb11b47, 0x0645e9af, 

-	0x3d3e82ad, 0x1294062e, 0x3d3e82ad, 0x1294062e, 0x3f4eaafe, 0x09640837, 0x39daf5e8, 0x1b5d1009, 

-	0x3b20d79e, 0x187de2a6, 0x3ec52f9f, 0x0c7c5c1e, 0x3536cc52, 0x238e7673, 0x387165e3, 0x1e2b5d38, 

-	0x3e14fdf7, 0x0f8cfcbd, 0x2f6bbe44, 0x2afad269, 0x3536cc52, 0x238e7673, 0x3d3e82ad, 0x1294062e, 

-	0x2899e64a, 0x317900d6, 0x317900d6, 0x2899e64a, 0x3c424209, 0x158f9a75, 0x20e70f32, 0x36e5068a, 

-	0x2d413ccc, 0x2d413ccc, 0x3b20d79e, 0x187de2a6, 0x187de2a6, 0x3b20d79e, 0x2899e64a, 0x317900d6, 

-	0x39daf5e8, 0x1b5d1009, 0x0f8cfcbd, 0x3e14fdf7, 0x238e7673, 0x3536cc52, 0x387165e3, 0x1e2b5d38, 

-	0x0645e9af, 0x3fb11b47, 0x1e2b5d38, 0x387165e3, 0x36e5068a, 0x20e70f32, 0xfcdc1342, 0x3fec43c6, 

-	0x187de2a6, 0x3b20d79e, 0x3536cc52, 0x238e7673, 0xf383a3e2, 0x3ec52f9f, 0x1294062e, 0x3d3e82ad, 

-	0x3367c08f, 0x261feff9, 0xea70658b, 0x3c424209, 0x0c7c5c1e, 0x3ec52f9f, 0x317900d6, 0x2899e64a, 

-	0xe1d4a2c8, 0x387165e3, 0x0645e9af, 0x3fb11b47, 0x2f6bbe44, 0x2afad269, 0xd9e01007, 0x3367c08f, 

-	0x00000000, 0x40000000, 0x2d413ccc, 0x2d413ccc, 0xd2bec334, 0x2d413ccc, 0xf9ba1651, 0x3fb11b47, 

-	0x2afad269, 0x2f6bbe44, 0xcc983f71, 0x261feff9, 0xf383a3e2, 0x3ec52f9f, 0x2899e64a, 0x317900d6, 

-	0xc78e9a1d, 0x1e2b5d38, 0xed6bf9d2, 0x3d3e82ad, 0x261feff9, 0x3367c08f, 0xc3bdbdf7, 0x158f9a75, 

-	0xe7821d5a, 0x3b20d79e, 0x238e7673, 0x3536cc52, 0xc13ad061, 0x0c7c5c1e, 0xe1d4a2c8, 0x387165e3, 

-	0x20e70f32, 0x36e5068a, 0xc013bc3a, 0x0323ecbe, 0xdc71898d, 0x3536cc52, 0x1e2b5d38, 0x387165e3, 

-	0xc04ee4b9, 0xf9ba1651, 0xd76619b6, 0x317900d6, 0x1b5d1009, 0x39daf5e8, 0xc1eb0209, 0xf0730343, 

-	0xd2bec334, 0x2d413ccc, 0x187de2a6, 0x3b20d79e, 0xc4df2862, 0xe7821d5a, 0xce86ff2a, 0x2899e64a, 

-	0x158f9a75, 0x3c424209, 0xc91af976, 0xdf18f0ce, 0xcac933ae, 0x238e7673, 0x1294062e, 0x3d3e82ad, 

-	0xce86ff2a, 0xd76619b6, 0xc78e9a1d, 0x1e2b5d38, 0x0f8cfcbd, 0x3e14fdf7, 0xd5052d97, 0xd09441bc, 

-	0xc4df2862, 0x187de2a6, 0x0c7c5c1e, 0x3ec52f9f, 0xdc71898d, 0xcac933ae, 0xc2c17d53, 0x1294062e, 

-	0x09640837, 0x3f4eaafe, 0xe4a2eff7, 0xc6250a18, 0xc13ad061, 0x0c7c5c1e, 0x0645e9af, 0x3fb11b47, 

-	0xed6bf9d2, 0xc2c17d53, 0xc04ee4b9, 0x0645e9af, 0x0323ecbe, 0x3fec43c6, 0xf69bf7c9, 0xc0b15502, 

-

-	0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x3ffb10c1, 0x0192155f, 

-	0x3ffec42d, 0x00c90e8f, 0x3ff4e5df, 0x025b0cae, 0x3fec43c6, 0x0323ecbe, 0x3ffb10c1, 0x0192155f, 

-	0x3fd39b5a, 0x04b54824, 0x3fd39b5a, 0x04b54824, 0x3ff4e5df, 0x025b0cae, 0x3f9c2bfa, 0x070de171, 

-	0x3fb11b47, 0x0645e9af, 0x3fec43c6, 0x0323ecbe, 0x3f4eaafe, 0x09640837, 0x3f84c8e1, 0x07d59395, 

-	0x3fe12acb, 0x03ecadcf, 0x3eeb3347, 0x0bb6ecef, 0x3f4eaafe, 0x09640837, 0x3fd39b5a, 0x04b54824, 

-	0x3e71e758, 0x0e05c135, 0x3f0ec9f4, 0x0af10a22, 0x3fc395f9, 0x057db402, 0x3de2f147, 0x104fb80e, 

-	0x3ec52f9f, 0x0c7c5c1e, 0x3fb11b47, 0x0645e9af, 0x3d3e82ad, 0x1294062e, 0x3e71e758, 0x0e05c135, 

-	0x3f9c2bfa, 0x070de171, 0x3c84d496, 0x14d1e242, 0x3e14fdf7, 0x0f8cfcbd, 0x3f84c8e1, 0x07d59395, 

-	0x3bb6276d, 0x17088530, 0x3dae81ce, 0x1111d262, 0x3f6af2e3, 0x089cf867, 0x3ad2c2e7, 0x19372a63, 

-	0x3d3e82ad, 0x1294062e, 0x3f4eaafe, 0x09640837, 0x39daf5e8, 0x1b5d1009, 0x3cc511d8, 0x14135c94, 

-	0x3f2ff249, 0x0a2abb58, 0x38cf1669, 0x1d79775b, 0x3c424209, 0x158f9a75, 0x3f0ec9f4, 0x0af10a22, 

-	0x37af8158, 0x1f8ba4db, 0x3bb6276d, 0x17088530, 0x3eeb3347, 0x0bb6ecef, 0x367c9a7d, 0x2192e09a, 

-	0x3b20d79e, 0x187de2a6, 0x3ec52f9f, 0x0c7c5c1e, 0x3536cc52, 0x238e7673, 0x3a8269a2, 0x19ef7943, 

-	0x3e9cc076, 0x0d415012, 0x33de87de, 0x257db64b, 0x39daf5e8, 0x1b5d1009, 0x3e71e758, 0x0e05c135, 

-	0x32744493, 0x275ff452, 0x392a9642, 0x1cc66e99, 0x3e44a5ee, 0x0ec9a7f2, 0x30f8801f, 0x29348937, 

-	0x387165e3, 0x1e2b5d38, 0x3e14fdf7, 0x0f8cfcbd, 0x2f6bbe44, 0x2afad269, 0x37af8158, 0x1f8ba4db, 

-	0x3de2f147, 0x104fb80e, 0x2dce88a9, 0x2cb2324b, 0x36e5068a, 0x20e70f32, 0x3dae81ce, 0x1111d262, 

-	0x2c216eaa, 0x2e5a106f, 0x361214b0, 0x223d66a8, 0x3d77b191, 0x11d3443f, 0x2a650525, 0x2ff1d9c6, 

-	0x3536cc52, 0x238e7673, 0x3d3e82ad, 0x1294062e, 0x2899e64a, 0x317900d6, 0x34534f40, 0x24da0a99, 

-	0x3d02f756, 0x135410c2, 0x26c0b162, 0x32eefde9, 0x3367c08f, 0x261feff9, 0x3cc511d8, 0x14135c94, 

-	0x24da0a99, 0x34534f40, 0x32744493, 0x275ff452, 0x3c84d496, 0x14d1e242, 0x22e69ac7, 0x35a5793c, 

-	0x317900d6, 0x2899e64a, 0x3c424209, 0x158f9a75, 0x20e70f32, 0x36e5068a, 0x30761c17, 0x29cd9577, 

-	0x3bfd5cc4, 0x164c7ddd, 0x1edc1952, 0x3811884c, 0x2f6bbe44, 0x2afad269, 0x3bb6276d, 0x17088530, 

-	0x1cc66e99, 0x392a9642, 0x2e5a106f, 0x2c216eaa, 0x3b6ca4c4, 0x17c3a931, 0x1aa6c82b, 0x3a2fcee8, 

-	0x2d413ccc, 0x2d413ccc, 0x3b20d79e, 0x187de2a6, 0x187de2a6, 0x3b20d79e, 0x2c216eaa, 0x2e5a106f, 

-	0x3ad2c2e7, 0x19372a63, 0x164c7ddd, 0x3bfd5cc4, 0x2afad269, 0x2f6bbe44, 0x3a8269a2, 0x19ef7943, 

-	0x14135c94, 0x3cc511d8, 0x29cd9577, 0x30761c17, 0x3a2fcee8, 0x1aa6c82b, 0x11d3443f, 0x3d77b191, 

-	0x2899e64a, 0x317900d6, 0x39daf5e8, 0x1b5d1009, 0x0f8cfcbd, 0x3e14fdf7, 0x275ff452, 0x32744493, 

-	0x3983e1e7, 0x1c1249d8, 0x0d415012, 0x3e9cc076, 0x261feff9, 0x3367c08f, 0x392a9642, 0x1cc66e99, 

-	0x0af10a22, 0x3f0ec9f4, 0x24da0a99, 0x34534f40, 0x38cf1669, 0x1d79775b, 0x089cf867, 0x3f6af2e3, 

-	0x238e7673, 0x3536cc52, 0x387165e3, 0x1e2b5d38, 0x0645e9af, 0x3fb11b47, 0x223d66a8, 0x361214b0, 

-	0x3811884c, 0x1edc1952, 0x03ecadcf, 0x3fe12acb, 0x20e70f32, 0x36e5068a, 0x37af8158, 0x1f8ba4db, 

-	0x0192155f, 0x3ffb10c1, 0x1f8ba4db, 0x37af8158, 0x374b54ce, 0x2039f90e, 0xff36f171, 0x3ffec42d, 

-	0x1e2b5d38, 0x387165e3, 0x36e5068a, 0x20e70f32, 0xfcdc1342, 0x3fec43c6, 0x1cc66e99, 0x392a9642, 

-	0x367c9a7d, 0x2192e09a, 0xfa824bfe, 0x3fc395f9, 0x1b5d1009, 0x39daf5e8, 0x361214b0, 0x223d66a8, 

-	0xf82a6c6b, 0x3f84c8e1, 0x19ef7943, 0x3a8269a2, 0x35a5793c, 0x22e69ac7, 0xf5d544a8, 0x3f2ff249, 

-	0x187de2a6, 0x3b20d79e, 0x3536cc52, 0x238e7673, 0xf383a3e2, 0x3ec52f9f, 0x17088530, 0x3bb6276d, 

-	0x34c61236, 0x2434f332, 0xf136580e, 0x3e44a5ee, 0x158f9a75, 0x3c424209, 0x34534f40, 0x24da0a99, 

-	0xeeee2d9e, 0x3dae81ce, 0x14135c94, 0x3cc511d8, 0x33de87de, 0x257db64b, 0xecabef3e, 0x3d02f756, 

-	0x1294062e, 0x3d3e82ad, 0x3367c08f, 0x261feff9, 0xea70658b, 0x3c424209, 0x1111d262, 0x3dae81ce, 

-	0x32eefde9, 0x26c0b162, 0xe83c56cf, 0x3b6ca4c4, 0x0f8cfcbd, 0x3e14fdf7, 0x32744493, 0x275ff452, 

-	0xe61086bd, 0x3a8269a2, 0x0e05c135, 0x3e71e758, 0x31f79947, 0x27fdb2a6, 0xe3edb628, 0x3983e1e7, 

-	0x0c7c5c1e, 0x3ec52f9f, 0x317900d6, 0x2899e64a, 0xe1d4a2c8, 0x387165e3, 0x0af10a22, 0x3f0ec9f4, 

-	0x30f8801f, 0x29348937, 0xdfc606f2, 0x374b54ce, 0x09640837, 0x3f4eaafe, 0x30761c17, 0x29cd9577, 

-	0xddc29958, 0x361214b0, 0x07d59395, 0x3f84c8e1, 0x2ff1d9c6, 0x2a650525, 0xdbcb0cce, 0x34c61236, 

-	0x0645e9af, 0x3fb11b47, 0x2f6bbe44, 0x2afad269, 0xd9e01007, 0x3367c08f, 0x04b54824, 0x3fd39b5a, 

-	0x2ee3cebe, 0x2b8ef77c, 0xd8024d5a, 0x31f79947, 0x0323ecbe, 0x3fec43c6, 0x2e5a106f, 0x2c216eaa, 

-	0xd6326a89, 0x30761c17, 0x0192155f, 0x3ffb10c1, 0x2dce88a9, 0x2cb2324b, 0xd4710884, 0x2ee3cebe, 

-	0x00000000, 0x40000000, 0x2d413ccc, 0x2d413ccc, 0xd2bec334, 0x2d413ccc, 0xfe6deaa1, 0x3ffb10c1, 

-	0x2cb2324b, 0x2dce88a9, 0xd11c3142, 0x2b8ef77c, 0xfcdc1342, 0x3fec43c6, 0x2c216eaa, 0x2e5a106f, 

-	0xcf89e3e9, 0x29cd9577, 0xfb4ab7dc, 0x3fd39b5a, 0x2b8ef77c, 0x2ee3cebe, 0xce0866b9, 0x27fdb2a6, 

-	0xf9ba1651, 0x3fb11b47, 0x2afad269, 0x2f6bbe44, 0xcc983f71, 0x261feff9, 0xf82a6c6b, 0x3f84c8e1, 

-	0x2a650525, 0x2ff1d9c6, 0xcb39edca, 0x2434f332, 0xf69bf7c9, 0x3f4eaafe, 0x29cd9577, 0x30761c17, 

-	0xc9edeb50, 0x223d66a8, 0xf50ef5de, 0x3f0ec9f4, 0x29348937, 0x30f8801f, 0xc8b4ab32, 0x2039f90e, 

-	0xf383a3e2, 0x3ec52f9f, 0x2899e64a, 0x317900d6, 0xc78e9a1d, 0x1e2b5d38, 0xf1fa3ecb, 0x3e71e758, 

-	0x27fdb2a6, 0x31f79947, 0xc67c1e19, 0x1c1249d8, 0xf0730343, 0x3e14fdf7, 0x275ff452, 0x32744493, 

-	0xc57d965e, 0x19ef7943, 0xeeee2d9e, 0x3dae81ce, 0x26c0b162, 0x32eefde9, 0xc4935b3c, 0x17c3a931, 

-	0xed6bf9d2, 0x3d3e82ad, 0x261feff9, 0x3367c08f, 0xc3bdbdf7, 0x158f9a75, 0xebeca36c, 0x3cc511d8, 

-	0x257db64b, 0x33de87de, 0xc2fd08aa, 0x135410c2, 0xea70658b, 0x3c424209, 0x24da0a99, 0x34534f40, 

-	0xc2517e32, 0x1111d262, 0xe8f77ad0, 0x3bb6276d, 0x2434f332, 0x34c61236, 0xc1bb5a12, 0x0ec9a7f2, 

-	0xe7821d5a, 0x3b20d79e, 0x238e7673, 0x3536cc52, 0xc13ad061, 0x0c7c5c1e, 0xe61086bd, 0x3a8269a2, 

-	0x22e69ac7, 0x35a5793c, 0xc0d00db7, 0x0a2abb58, 0xe4a2eff7, 0x39daf5e8, 0x223d66a8, 0x361214b0, 

-	0xc07b371f, 0x07d59395, 0xe3399167, 0x392a9642, 0x2192e09a, 0x367c9a7d, 0xc03c6a07, 0x057db402, 

-	0xe1d4a2c8, 0x387165e3, 0x20e70f32, 0x36e5068a, 0xc013bc3a, 0x0323ecbe, 0xe0745b25, 0x37af8158, 

-	0x2039f90e, 0x374b54ce, 0xc0013bd3, 0x00c90e8f, 0xdf18f0ce, 0x36e5068a, 0x1f8ba4db, 0x37af8158, 

-	0xc004ef3f, 0xfe6deaa1, 0xddc29958, 0x361214b0, 0x1edc1952, 0x3811884c, 0xc01ed535, 0xfc135231, 

-	0xdc71898d, 0x3536cc52, 0x1e2b5d38, 0x387165e3, 0xc04ee4b9, 0xf9ba1651, 0xdb25f567, 0x34534f40, 

-	0x1d79775b, 0x38cf1669, 0xc0950d1d, 0xf7630799, 0xd9e01007, 0x3367c08f, 0x1cc66e99, 0x392a9642, 

-	0xc0f1360c, 0xf50ef5de, 0xd8a00bae, 0x32744493, 0x1c1249d8, 0x3983e1e7, 0xc1633f8a, 0xf2beafee, 

-	0xd76619b6, 0x317900d6, 0x1b5d1009, 0x39daf5e8, 0xc1eb0209, 0xf0730343, 0xd6326a89, 0x30761c17, 

-	0x1aa6c82b, 0x3a2fcee8, 0xc2884e6f, 0xee2cbbc1, 0xd5052d97, 0x2f6bbe44, 0x19ef7943, 0x3a8269a2, 

-	0xc33aee28, 0xebeca36c, 0xd3de9156, 0x2e5a106f, 0x19372a63, 0x3ad2c2e7, 0xc402a33c, 0xe9b38223, 

-	0xd2bec334, 0x2d413ccc, 0x187de2a6, 0x3b20d79e, 0xc4df2862, 0xe7821d5a, 0xd1a5ef91, 0x2c216eaa, 

-	0x17c3a931, 0x3b6ca4c4, 0xc5d03118, 0xe55937d5, 0xd09441bc, 0x2afad269, 0x17088530, 0x3bb6276d, 

-	0xc6d569be, 0xe3399167, 0xcf89e3e9, 0x29cd9577, 0x164c7ddd, 0x3bfd5cc4, 0xc7ee77b4, 0xe123e6ae, 

-	0xce86ff2a, 0x2899e64a, 0x158f9a75, 0x3c424209, 0xc91af976, 0xdf18f0ce, 0xcd8bbb6d, 0x275ff452, 

-	0x14d1e242, 0x3c84d496, 0xca5a86c4, 0xdd196539, 0xcc983f71, 0x261feff9, 0x14135c94, 0x3cc511d8, 

-	0xcbacb0c0, 0xdb25f567, 0xcbacb0c0, 0x24da0a99, 0x135410c2, 0x3d02f756, 0xcd110217, 0xd93f4e9e, 

-	0xcac933ae, 0x238e7673, 0x1294062e, 0x3d3e82ad, 0xce86ff2a, 0xd76619b6, 0xc9edeb50, 0x223d66a8, 

-	0x11d3443f, 0x3d77b191, 0xd00e263a, 0xd59afadb, 0xc91af976, 0x20e70f32, 0x1111d262, 0x3dae81ce, 

-	0xd1a5ef91, 0xd3de9156, 0xc8507ea8, 0x1f8ba4db, 0x104fb80e, 0x3de2f147, 0xd34dcdb5, 0xd2317757, 

-	0xc78e9a1d, 0x1e2b5d38, 0x0f8cfcbd, 0x3e14fdf7, 0xd5052d97, 0xd09441bc, 0xc6d569be, 0x1cc66e99, 

-	0x0ec9a7f2, 0x3e44a5ee, 0xd6cb76c9, 0xcf077fe1, 0xc6250a18, 0x1b5d1009, 0x0e05c135, 0x3e71e758, 

-	0xd8a00bae, 0xcd8bbb6d, 0xc57d965e, 0x19ef7943, 0x0d415012, 0x3e9cc076, 0xda8249b5, 0xcc217822, 

-	0xc4df2862, 0x187de2a6, 0x0c7c5c1e, 0x3ec52f9f, 0xdc71898d, 0xcac933ae, 0xc449d893, 0x17088530, 

-	0x0bb6ecef, 0x3eeb3347, 0xde6d1f66, 0xc9836583, 0xc3bdbdf7, 0x158f9a75, 0x0af10a22, 0x3f0ec9f4, 

-	0xe0745b25, 0xc8507ea8, 0xc33aee28, 0x14135c94, 0x0a2abb58, 0x3f2ff249, 0xe28688a5, 0xc730e997, 

-	0xc2c17d53, 0x1294062e, 0x09640837, 0x3f4eaafe, 0xe4a2eff7, 0xc6250a18, 0xc2517e32, 0x1111d262, 

-	0x089cf867, 0x3f6af2e3, 0xe6c8d59d, 0xc52d3d19, 0xc1eb0209, 0x0f8cfcbd, 0x07d59395, 0x3f84c8e1, 

-	0xe8f77ad0, 0xc449d893, 0xc18e18a8, 0x0e05c135, 0x070de171, 0x3f9c2bfa, 0xeb2e1dbe, 0xc37b2b6a, 

-	0xc13ad061, 0x0c7c5c1e, 0x0645e9af, 0x3fb11b47, 0xed6bf9d2, 0xc2c17d53, 0xc0f1360c, 0x0af10a22, 

-	0x057db402, 0x3fc395f9, 0xefb047f2, 0xc21d0eb9, 0xc0b15502, 0x09640837, 0x04b54824, 0x3fd39b5a, 

-	0xf1fa3ecb, 0xc18e18a8, 0xc07b371f, 0x07d59395, 0x03ecadcf, 0x3fe12acb, 0xf4491311, 0xc114ccb9, 

-	0xc04ee4b9, 0x0645e9af, 0x0323ecbe, 0x3fec43c6, 0xf69bf7c9, 0xc0b15502, 0xc02c64a6, 0x04b54824, 

-	0x025b0cae, 0x3ff4e5df, 0xf8f21e8f, 0xc063d406, 0xc013bc3a, 0x0323ecbe, 0x0192155f, 0x3ffb10c1, 

-	0xfb4ab7dc, 0xc02c64a6, 0xc004ef3f, 0x0192155f, 0x00c90e8f, 0x3ffec42d, 0xfda4f352, 0xc00b1a21

-};

-

-const int twidTab64[4*6 + 16*6] = {

-	0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x2d413ccc, 0x2d413ccc, 

-	0x3b20d79e, 0x187de2a6, 0x187de2a6, 0x3b20d79e, 0x00000000, 0x40000000, 0x2d413ccc, 0x2d413ccc, 

-	0xd2bec334, 0x2d413ccc, 0xd2bec334, 0x2d413ccc, 0x187de2a6, 0x3b20d79e, 0xc4df2862, 0xe7821d5a, 

-

-	0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x3ec52f9f, 0x0c7c5c1e, 

-	0x3fb11b47, 0x0645e9af, 0x3d3e82ad, 0x1294062e, 0x3b20d79e, 0x187de2a6, 0x3ec52f9f, 0x0c7c5c1e, 

-	0x3536cc52, 0x238e7673, 0x3536cc52, 0x238e7673, 0x3d3e82ad, 0x1294062e, 0x2899e64a, 0x317900d6, 

-	0x2d413ccc, 0x2d413ccc, 0x3b20d79e, 0x187de2a6, 0x187de2a6, 0x3b20d79e, 0x238e7673, 0x3536cc52, 

-	0x387165e3, 0x1e2b5d38, 0x0645e9af, 0x3fb11b47, 0x187de2a6, 0x3b20d79e, 0x3536cc52, 0x238e7673, 

-	0xf383a3e2, 0x3ec52f9f, 0x0c7c5c1e, 0x3ec52f9f, 0x317900d6, 0x2899e64a, 0xe1d4a2c8, 0x387165e3, 

-	0x00000000, 0x40000000, 0x2d413ccc, 0x2d413ccc, 0xd2bec334, 0x2d413ccc, 0xf383a3e2, 0x3ec52f9f, 

-	0x2899e64a, 0x317900d6, 0xc78e9a1d, 0x1e2b5d38, 0xe7821d5a, 0x3b20d79e, 0x238e7673, 0x3536cc52, 

-	0xc13ad061, 0x0c7c5c1e, 0xdc71898d, 0x3536cc52, 0x1e2b5d38, 0x387165e3, 0xc04ee4b9, 0xf9ba1651, 

-	0xd2bec334, 0x2d413ccc, 0x187de2a6, 0x3b20d79e, 0xc4df2862, 0xe7821d5a, 0xcac933ae, 0x238e7673, 

-	0x1294062e, 0x3d3e82ad, 0xce86ff2a, 0xd76619b6, 0xc4df2862, 0x187de2a6, 0x0c7c5c1e, 0x3ec52f9f, 

-	0xdc71898d, 0xcac933ae, 0xc13ad061, 0x0c7c5c1e, 0x0645e9af, 0x3fb11b47, 0xed6bf9d2, 0xc2c17d53 

-};

-#endif  //ARMV5E

-

-const int ShortWindowSine[FRAME_LEN_SHORT/2] ={  

-	0x00c97fff, 0x025b7ffa, 0x03ed7ff1, 0x057f7fe2, 0x07117fce, 0x08a27fb5, 0x0a337f98, 0x0bc47f75, 

-	0x0d547f4e, 0x0ee47f22, 0x10737ef0, 0x12017eba, 0x138f7e7f, 0x151c7e3f, 0x16a87dfb, 0x18337db1, 

-	0x19be7d63, 0x1b477d0f, 0x1cd07cb7, 0x1e577c5a, 0x1fdd7bf9, 0x21627b92, 0x22e57b27, 0x24677ab7, 

-	0x25e87a42, 0x276879c9, 0x28e5794a, 0x2a6278c8, 0x2bdc7840, 0x2d5577b4, 0x2ecc7723, 0x3042768e, 

-	0x31b575f4, 0x33277556, 0x349774b3, 0x3604740b, 0x3770735f, 0x38d972af, 0x3a4071fa, 0x3ba57141, 

-	0x3d087083, 0x3e686fc2, 0x3fc66efb, 0x41216e31, 0x427a6d62, 0x43d16c8f, 0x45246bb8, 0x46756add, 

-	0x47c469fd, 0x490f691a, 0x4a586832, 0x4b9e6747, 0x4ce16657, 0x4e216564, 0x4f5e646c, 0x50986371, 

-	0x51cf6272, 0x5303616f, 0x54336068, 0x55605f5e, 0x568a5e50, 0x57b15d3e, 0x58d45c29, 0x59f45b10

+const int twidTab512[8*6 + 32*6 + 128*6] = {
+	0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x3b20d79e, 0x187de2a6,
+	0x3ec52f9f, 0x0c7c5c1e, 0x3536cc52, 0x238e7673, 0x2d413ccc, 0x2d413ccc, 0x3b20d79e, 0x187de2a6,
+	0x187de2a6, 0x3b20d79e, 0x187de2a6, 0x3b20d79e, 0x3536cc52, 0x238e7673, 0xf383a3e2, 0x3ec52f9f,
+	0x00000000, 0x40000000, 0x2d413ccc, 0x2d413ccc, 0xd2bec334, 0x2d413ccc, 0xe7821d5a, 0x3b20d79e,
+	0x238e7673, 0x3536cc52, 0xc13ad061, 0x0c7c5c1e, 0xd2bec334, 0x2d413ccc, 0x187de2a6, 0x3b20d79e,
+	0xc4df2862, 0xe7821d5a, 0xc4df2862, 0x187de2a6, 0x0c7c5c1e, 0x3ec52f9f, 0xdc71898d, 0xcac933ae,
+
+	0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x3fb11b47, 0x0645e9af,
+	0x3fec43c6, 0x0323ecbe, 0x3f4eaafe, 0x09640837, 0x3ec52f9f, 0x0c7c5c1e, 0x3fb11b47, 0x0645e9af,
+	0x3d3e82ad, 0x1294062e, 0x3d3e82ad, 0x1294062e, 0x3f4eaafe, 0x09640837, 0x39daf5e8, 0x1b5d1009,
+	0x3b20d79e, 0x187de2a6, 0x3ec52f9f, 0x0c7c5c1e, 0x3536cc52, 0x238e7673, 0x387165e3, 0x1e2b5d38,
+	0x3e14fdf7, 0x0f8cfcbd, 0x2f6bbe44, 0x2afad269, 0x3536cc52, 0x238e7673, 0x3d3e82ad, 0x1294062e,
+	0x2899e64a, 0x317900d6, 0x317900d6, 0x2899e64a, 0x3c424209, 0x158f9a75, 0x20e70f32, 0x36e5068a,
+	0x2d413ccc, 0x2d413ccc, 0x3b20d79e, 0x187de2a6, 0x187de2a6, 0x3b20d79e, 0x2899e64a, 0x317900d6,
+	0x39daf5e8, 0x1b5d1009, 0x0f8cfcbd, 0x3e14fdf7, 0x238e7673, 0x3536cc52, 0x387165e3, 0x1e2b5d38,
+	0x0645e9af, 0x3fb11b47, 0x1e2b5d38, 0x387165e3, 0x36e5068a, 0x20e70f32, 0xfcdc1342, 0x3fec43c6,
+	0x187de2a6, 0x3b20d79e, 0x3536cc52, 0x238e7673, 0xf383a3e2, 0x3ec52f9f, 0x1294062e, 0x3d3e82ad,
+	0x3367c08f, 0x261feff9, 0xea70658b, 0x3c424209, 0x0c7c5c1e, 0x3ec52f9f, 0x317900d6, 0x2899e64a,
+	0xe1d4a2c8, 0x387165e3, 0x0645e9af, 0x3fb11b47, 0x2f6bbe44, 0x2afad269, 0xd9e01007, 0x3367c08f,
+	0x00000000, 0x40000000, 0x2d413ccc, 0x2d413ccc, 0xd2bec334, 0x2d413ccc, 0xf9ba1651, 0x3fb11b47,
+	0x2afad269, 0x2f6bbe44, 0xcc983f71, 0x261feff9, 0xf383a3e2, 0x3ec52f9f, 0x2899e64a, 0x317900d6,
+	0xc78e9a1d, 0x1e2b5d38, 0xed6bf9d2, 0x3d3e82ad, 0x261feff9, 0x3367c08f, 0xc3bdbdf7, 0x158f9a75,
+	0xe7821d5a, 0x3b20d79e, 0x238e7673, 0x3536cc52, 0xc13ad061, 0x0c7c5c1e, 0xe1d4a2c8, 0x387165e3,
+	0x20e70f32, 0x36e5068a, 0xc013bc3a, 0x0323ecbe, 0xdc71898d, 0x3536cc52, 0x1e2b5d38, 0x387165e3,
+	0xc04ee4b9, 0xf9ba1651, 0xd76619b6, 0x317900d6, 0x1b5d1009, 0x39daf5e8, 0xc1eb0209, 0xf0730343,
+	0xd2bec334, 0x2d413ccc, 0x187de2a6, 0x3b20d79e, 0xc4df2862, 0xe7821d5a, 0xce86ff2a, 0x2899e64a,
+	0x158f9a75, 0x3c424209, 0xc91af976, 0xdf18f0ce, 0xcac933ae, 0x238e7673, 0x1294062e, 0x3d3e82ad,
+	0xce86ff2a, 0xd76619b6, 0xc78e9a1d, 0x1e2b5d38, 0x0f8cfcbd, 0x3e14fdf7, 0xd5052d97, 0xd09441bc,
+	0xc4df2862, 0x187de2a6, 0x0c7c5c1e, 0x3ec52f9f, 0xdc71898d, 0xcac933ae, 0xc2c17d53, 0x1294062e,
+	0x09640837, 0x3f4eaafe, 0xe4a2eff7, 0xc6250a18, 0xc13ad061, 0x0c7c5c1e, 0x0645e9af, 0x3fb11b47,
+	0xed6bf9d2, 0xc2c17d53, 0xc04ee4b9, 0x0645e9af, 0x0323ecbe, 0x3fec43c6, 0xf69bf7c9, 0xc0b15502,
+
+	0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x3ffb10c1, 0x0192155f,
+	0x3ffec42d, 0x00c90e8f, 0x3ff4e5df, 0x025b0cae, 0x3fec43c6, 0x0323ecbe, 0x3ffb10c1, 0x0192155f,
+	0x3fd39b5a, 0x04b54824, 0x3fd39b5a, 0x04b54824, 0x3ff4e5df, 0x025b0cae, 0x3f9c2bfa, 0x070de171,
+	0x3fb11b47, 0x0645e9af, 0x3fec43c6, 0x0323ecbe, 0x3f4eaafe, 0x09640837, 0x3f84c8e1, 0x07d59395,
+	0x3fe12acb, 0x03ecadcf, 0x3eeb3347, 0x0bb6ecef, 0x3f4eaafe, 0x09640837, 0x3fd39b5a, 0x04b54824,
+	0x3e71e758, 0x0e05c135, 0x3f0ec9f4, 0x0af10a22, 0x3fc395f9, 0x057db402, 0x3de2f147, 0x104fb80e,
+	0x3ec52f9f, 0x0c7c5c1e, 0x3fb11b47, 0x0645e9af, 0x3d3e82ad, 0x1294062e, 0x3e71e758, 0x0e05c135,
+	0x3f9c2bfa, 0x070de171, 0x3c84d496, 0x14d1e242, 0x3e14fdf7, 0x0f8cfcbd, 0x3f84c8e1, 0x07d59395,
+	0x3bb6276d, 0x17088530, 0x3dae81ce, 0x1111d262, 0x3f6af2e3, 0x089cf867, 0x3ad2c2e7, 0x19372a63,
+	0x3d3e82ad, 0x1294062e, 0x3f4eaafe, 0x09640837, 0x39daf5e8, 0x1b5d1009, 0x3cc511d8, 0x14135c94,
+	0x3f2ff249, 0x0a2abb58, 0x38cf1669, 0x1d79775b, 0x3c424209, 0x158f9a75, 0x3f0ec9f4, 0x0af10a22,
+	0x37af8158, 0x1f8ba4db, 0x3bb6276d, 0x17088530, 0x3eeb3347, 0x0bb6ecef, 0x367c9a7d, 0x2192e09a,
+	0x3b20d79e, 0x187de2a6, 0x3ec52f9f, 0x0c7c5c1e, 0x3536cc52, 0x238e7673, 0x3a8269a2, 0x19ef7943,
+	0x3e9cc076, 0x0d415012, 0x33de87de, 0x257db64b, 0x39daf5e8, 0x1b5d1009, 0x3e71e758, 0x0e05c135,
+	0x32744493, 0x275ff452, 0x392a9642, 0x1cc66e99, 0x3e44a5ee, 0x0ec9a7f2, 0x30f8801f, 0x29348937,
+	0x387165e3, 0x1e2b5d38, 0x3e14fdf7, 0x0f8cfcbd, 0x2f6bbe44, 0x2afad269, 0x37af8158, 0x1f8ba4db,
+	0x3de2f147, 0x104fb80e, 0x2dce88a9, 0x2cb2324b, 0x36e5068a, 0x20e70f32, 0x3dae81ce, 0x1111d262,
+	0x2c216eaa, 0x2e5a106f, 0x361214b0, 0x223d66a8, 0x3d77b191, 0x11d3443f, 0x2a650525, 0x2ff1d9c6,
+	0x3536cc52, 0x238e7673, 0x3d3e82ad, 0x1294062e, 0x2899e64a, 0x317900d6, 0x34534f40, 0x24da0a99,
+	0x3d02f756, 0x135410c2, 0x26c0b162, 0x32eefde9, 0x3367c08f, 0x261feff9, 0x3cc511d8, 0x14135c94,
+	0x24da0a99, 0x34534f40, 0x32744493, 0x275ff452, 0x3c84d496, 0x14d1e242, 0x22e69ac7, 0x35a5793c,
+	0x317900d6, 0x2899e64a, 0x3c424209, 0x158f9a75, 0x20e70f32, 0x36e5068a, 0x30761c17, 0x29cd9577,
+	0x3bfd5cc4, 0x164c7ddd, 0x1edc1952, 0x3811884c, 0x2f6bbe44, 0x2afad269, 0x3bb6276d, 0x17088530,
+	0x1cc66e99, 0x392a9642, 0x2e5a106f, 0x2c216eaa, 0x3b6ca4c4, 0x17c3a931, 0x1aa6c82b, 0x3a2fcee8,
+	0x2d413ccc, 0x2d413ccc, 0x3b20d79e, 0x187de2a6, 0x187de2a6, 0x3b20d79e, 0x2c216eaa, 0x2e5a106f,
+	0x3ad2c2e7, 0x19372a63, 0x164c7ddd, 0x3bfd5cc4, 0x2afad269, 0x2f6bbe44, 0x3a8269a2, 0x19ef7943,
+	0x14135c94, 0x3cc511d8, 0x29cd9577, 0x30761c17, 0x3a2fcee8, 0x1aa6c82b, 0x11d3443f, 0x3d77b191,
+	0x2899e64a, 0x317900d6, 0x39daf5e8, 0x1b5d1009, 0x0f8cfcbd, 0x3e14fdf7, 0x275ff452, 0x32744493,
+	0x3983e1e7, 0x1c1249d8, 0x0d415012, 0x3e9cc076, 0x261feff9, 0x3367c08f, 0x392a9642, 0x1cc66e99,
+	0x0af10a22, 0x3f0ec9f4, 0x24da0a99, 0x34534f40, 0x38cf1669, 0x1d79775b, 0x089cf867, 0x3f6af2e3,
+	0x238e7673, 0x3536cc52, 0x387165e3, 0x1e2b5d38, 0x0645e9af, 0x3fb11b47, 0x223d66a8, 0x361214b0,
+	0x3811884c, 0x1edc1952, 0x03ecadcf, 0x3fe12acb, 0x20e70f32, 0x36e5068a, 0x37af8158, 0x1f8ba4db,
+	0x0192155f, 0x3ffb10c1, 0x1f8ba4db, 0x37af8158, 0x374b54ce, 0x2039f90e, 0xff36f171, 0x3ffec42d,
+	0x1e2b5d38, 0x387165e3, 0x36e5068a, 0x20e70f32, 0xfcdc1342, 0x3fec43c6, 0x1cc66e99, 0x392a9642,
+	0x367c9a7d, 0x2192e09a, 0xfa824bfe, 0x3fc395f9, 0x1b5d1009, 0x39daf5e8, 0x361214b0, 0x223d66a8,
+	0xf82a6c6b, 0x3f84c8e1, 0x19ef7943, 0x3a8269a2, 0x35a5793c, 0x22e69ac7, 0xf5d544a8, 0x3f2ff249,
+	0x187de2a6, 0x3b20d79e, 0x3536cc52, 0x238e7673, 0xf383a3e2, 0x3ec52f9f, 0x17088530, 0x3bb6276d,
+	0x34c61236, 0x2434f332, 0xf136580e, 0x3e44a5ee, 0x158f9a75, 0x3c424209, 0x34534f40, 0x24da0a99,
+	0xeeee2d9e, 0x3dae81ce, 0x14135c94, 0x3cc511d8, 0x33de87de, 0x257db64b, 0xecabef3e, 0x3d02f756,
+	0x1294062e, 0x3d3e82ad, 0x3367c08f, 0x261feff9, 0xea70658b, 0x3c424209, 0x1111d262, 0x3dae81ce,
+	0x32eefde9, 0x26c0b162, 0xe83c56cf, 0x3b6ca4c4, 0x0f8cfcbd, 0x3e14fdf7, 0x32744493, 0x275ff452,
+	0xe61086bd, 0x3a8269a2, 0x0e05c135, 0x3e71e758, 0x31f79947, 0x27fdb2a6, 0xe3edb628, 0x3983e1e7,
+	0x0c7c5c1e, 0x3ec52f9f, 0x317900d6, 0x2899e64a, 0xe1d4a2c8, 0x387165e3, 0x0af10a22, 0x3f0ec9f4,
+	0x30f8801f, 0x29348937, 0xdfc606f2, 0x374b54ce, 0x09640837, 0x3f4eaafe, 0x30761c17, 0x29cd9577,
+	0xddc29958, 0x361214b0, 0x07d59395, 0x3f84c8e1, 0x2ff1d9c6, 0x2a650525, 0xdbcb0cce, 0x34c61236,
+	0x0645e9af, 0x3fb11b47, 0x2f6bbe44, 0x2afad269, 0xd9e01007, 0x3367c08f, 0x04b54824, 0x3fd39b5a,
+	0x2ee3cebe, 0x2b8ef77c, 0xd8024d5a, 0x31f79947, 0x0323ecbe, 0x3fec43c6, 0x2e5a106f, 0x2c216eaa,
+	0xd6326a89, 0x30761c17, 0x0192155f, 0x3ffb10c1, 0x2dce88a9, 0x2cb2324b, 0xd4710884, 0x2ee3cebe,
+	0x00000000, 0x40000000, 0x2d413ccc, 0x2d413ccc, 0xd2bec334, 0x2d413ccc, 0xfe6deaa1, 0x3ffb10c1,
+	0x2cb2324b, 0x2dce88a9, 0xd11c3142, 0x2b8ef77c, 0xfcdc1342, 0x3fec43c6, 0x2c216eaa, 0x2e5a106f,
+	0xcf89e3e9, 0x29cd9577, 0xfb4ab7dc, 0x3fd39b5a, 0x2b8ef77c, 0x2ee3cebe, 0xce0866b9, 0x27fdb2a6,
+	0xf9ba1651, 0x3fb11b47, 0x2afad269, 0x2f6bbe44, 0xcc983f71, 0x261feff9, 0xf82a6c6b, 0x3f84c8e1,
+	0x2a650525, 0x2ff1d9c6, 0xcb39edca, 0x2434f332, 0xf69bf7c9, 0x3f4eaafe, 0x29cd9577, 0x30761c17,
+	0xc9edeb50, 0x223d66a8, 0xf50ef5de, 0x3f0ec9f4, 0x29348937, 0x30f8801f, 0xc8b4ab32, 0x2039f90e,
+	0xf383a3e2, 0x3ec52f9f, 0x2899e64a, 0x317900d6, 0xc78e9a1d, 0x1e2b5d38, 0xf1fa3ecb, 0x3e71e758,
+	0x27fdb2a6, 0x31f79947, 0xc67c1e19, 0x1c1249d8, 0xf0730343, 0x3e14fdf7, 0x275ff452, 0x32744493,
+	0xc57d965e, 0x19ef7943, 0xeeee2d9e, 0x3dae81ce, 0x26c0b162, 0x32eefde9, 0xc4935b3c, 0x17c3a931,
+	0xed6bf9d2, 0x3d3e82ad, 0x261feff9, 0x3367c08f, 0xc3bdbdf7, 0x158f9a75, 0xebeca36c, 0x3cc511d8,
+	0x257db64b, 0x33de87de, 0xc2fd08aa, 0x135410c2, 0xea70658b, 0x3c424209, 0x24da0a99, 0x34534f40,
+	0xc2517e32, 0x1111d262, 0xe8f77ad0, 0x3bb6276d, 0x2434f332, 0x34c61236, 0xc1bb5a12, 0x0ec9a7f2,
+	0xe7821d5a, 0x3b20d79e, 0x238e7673, 0x3536cc52, 0xc13ad061, 0x0c7c5c1e, 0xe61086bd, 0x3a8269a2,
+	0x22e69ac7, 0x35a5793c, 0xc0d00db7, 0x0a2abb58, 0xe4a2eff7, 0x39daf5e8, 0x223d66a8, 0x361214b0,
+	0xc07b371f, 0x07d59395, 0xe3399167, 0x392a9642, 0x2192e09a, 0x367c9a7d, 0xc03c6a07, 0x057db402,
+	0xe1d4a2c8, 0x387165e3, 0x20e70f32, 0x36e5068a, 0xc013bc3a, 0x0323ecbe, 0xe0745b25, 0x37af8158,
+	0x2039f90e, 0x374b54ce, 0xc0013bd3, 0x00c90e8f, 0xdf18f0ce, 0x36e5068a, 0x1f8ba4db, 0x37af8158,
+	0xc004ef3f, 0xfe6deaa1, 0xddc29958, 0x361214b0, 0x1edc1952, 0x3811884c, 0xc01ed535, 0xfc135231,
+	0xdc71898d, 0x3536cc52, 0x1e2b5d38, 0x387165e3, 0xc04ee4b9, 0xf9ba1651, 0xdb25f567, 0x34534f40,
+	0x1d79775b, 0x38cf1669, 0xc0950d1d, 0xf7630799, 0xd9e01007, 0x3367c08f, 0x1cc66e99, 0x392a9642,
+	0xc0f1360c, 0xf50ef5de, 0xd8a00bae, 0x32744493, 0x1c1249d8, 0x3983e1e7, 0xc1633f8a, 0xf2beafee,
+	0xd76619b6, 0x317900d6, 0x1b5d1009, 0x39daf5e8, 0xc1eb0209, 0xf0730343, 0xd6326a89, 0x30761c17,
+	0x1aa6c82b, 0x3a2fcee8, 0xc2884e6f, 0xee2cbbc1, 0xd5052d97, 0x2f6bbe44, 0x19ef7943, 0x3a8269a2,
+	0xc33aee28, 0xebeca36c, 0xd3de9156, 0x2e5a106f, 0x19372a63, 0x3ad2c2e7, 0xc402a33c, 0xe9b38223,
+	0xd2bec334, 0x2d413ccc, 0x187de2a6, 0x3b20d79e, 0xc4df2862, 0xe7821d5a, 0xd1a5ef91, 0x2c216eaa,
+	0x17c3a931, 0x3b6ca4c4, 0xc5d03118, 0xe55937d5, 0xd09441bc, 0x2afad269, 0x17088530, 0x3bb6276d,
+	0xc6d569be, 0xe3399167, 0xcf89e3e9, 0x29cd9577, 0x164c7ddd, 0x3bfd5cc4, 0xc7ee77b4, 0xe123e6ae,
+	0xce86ff2a, 0x2899e64a, 0x158f9a75, 0x3c424209, 0xc91af976, 0xdf18f0ce, 0xcd8bbb6d, 0x275ff452,
+	0x14d1e242, 0x3c84d496, 0xca5a86c4, 0xdd196539, 0xcc983f71, 0x261feff9, 0x14135c94, 0x3cc511d8,
+	0xcbacb0c0, 0xdb25f567, 0xcbacb0c0, 0x24da0a99, 0x135410c2, 0x3d02f756, 0xcd110217, 0xd93f4e9e,
+	0xcac933ae, 0x238e7673, 0x1294062e, 0x3d3e82ad, 0xce86ff2a, 0xd76619b6, 0xc9edeb50, 0x223d66a8,
+	0x11d3443f, 0x3d77b191, 0xd00e263a, 0xd59afadb, 0xc91af976, 0x20e70f32, 0x1111d262, 0x3dae81ce,
+	0xd1a5ef91, 0xd3de9156, 0xc8507ea8, 0x1f8ba4db, 0x104fb80e, 0x3de2f147, 0xd34dcdb5, 0xd2317757,
+	0xc78e9a1d, 0x1e2b5d38, 0x0f8cfcbd, 0x3e14fdf7, 0xd5052d97, 0xd09441bc, 0xc6d569be, 0x1cc66e99,
+	0x0ec9a7f2, 0x3e44a5ee, 0xd6cb76c9, 0xcf077fe1, 0xc6250a18, 0x1b5d1009, 0x0e05c135, 0x3e71e758,
+	0xd8a00bae, 0xcd8bbb6d, 0xc57d965e, 0x19ef7943, 0x0d415012, 0x3e9cc076, 0xda8249b5, 0xcc217822,
+	0xc4df2862, 0x187de2a6, 0x0c7c5c1e, 0x3ec52f9f, 0xdc71898d, 0xcac933ae, 0xc449d893, 0x17088530,
+	0x0bb6ecef, 0x3eeb3347, 0xde6d1f66, 0xc9836583, 0xc3bdbdf7, 0x158f9a75, 0x0af10a22, 0x3f0ec9f4,
+	0xe0745b25, 0xc8507ea8, 0xc33aee28, 0x14135c94, 0x0a2abb58, 0x3f2ff249, 0xe28688a5, 0xc730e997,
+	0xc2c17d53, 0x1294062e, 0x09640837, 0x3f4eaafe, 0xe4a2eff7, 0xc6250a18, 0xc2517e32, 0x1111d262,
+	0x089cf867, 0x3f6af2e3, 0xe6c8d59d, 0xc52d3d19, 0xc1eb0209, 0x0f8cfcbd, 0x07d59395, 0x3f84c8e1,
+	0xe8f77ad0, 0xc449d893, 0xc18e18a8, 0x0e05c135, 0x070de171, 0x3f9c2bfa, 0xeb2e1dbe, 0xc37b2b6a,
+	0xc13ad061, 0x0c7c5c1e, 0x0645e9af, 0x3fb11b47, 0xed6bf9d2, 0xc2c17d53, 0xc0f1360c, 0x0af10a22,
+	0x057db402, 0x3fc395f9, 0xefb047f2, 0xc21d0eb9, 0xc0b15502, 0x09640837, 0x04b54824, 0x3fd39b5a,
+	0xf1fa3ecb, 0xc18e18a8, 0xc07b371f, 0x07d59395, 0x03ecadcf, 0x3fe12acb, 0xf4491311, 0xc114ccb9,
+	0xc04ee4b9, 0x0645e9af, 0x0323ecbe, 0x3fec43c6, 0xf69bf7c9, 0xc0b15502, 0xc02c64a6, 0x04b54824,
+	0x025b0cae, 0x3ff4e5df, 0xf8f21e8f, 0xc063d406, 0xc013bc3a, 0x0323ecbe, 0x0192155f, 0x3ffb10c1,
+	0xfb4ab7dc, 0xc02c64a6, 0xc004ef3f, 0x0192155f, 0x00c90e8f, 0x3ffec42d, 0xfda4f352, 0xc00b1a21
 };
 
-const int LongWindowKBD[FRAME_LEN_LONG/2]={  
-	0x000a7fff, 0x000e7fff, 0x00127fff, 0x00157fff, 0x00197fff, 0x001c7fff, 0x00207fff, 0x00237fff, 

-	0x00267fff, 0x002a7fff, 0x002d7fff, 0x00307fff, 0x00347fff, 0x00387fff, 0x003b7fff, 0x003f7fff, 

-	0x00437fff, 0x00477fff, 0x004b7fff, 0x004f7fff, 0x00537fff, 0x00577fff, 0x005b7fff, 0x00607fff, 

-	0x00647fff, 0x00697fff, 0x006d7fff, 0x00727fff, 0x00777fff, 0x007c7fff, 0x00817fff, 0x00867fff, 

-	0x008b7fff, 0x00917fff, 0x00967fff, 0x009c7fff, 0x00a17fff, 0x00a77fff, 0x00ad7fff, 0x00b37fff, 

-	0x00b97fff, 0x00bf7fff, 0x00c67fff, 0x00cc7fff, 0x00d37fff, 0x00da7fff, 0x00e07fff, 0x00e77fff, 

-	0x00ee7fff, 0x00f57fff, 0x00fd7fff, 0x01047fff, 0x010c7fff, 0x01137fff, 0x011b7fff, 0x01237fff, 

-	0x012b7fff, 0x01337fff, 0x013c7ffe, 0x01447ffe, 0x014d7ffe, 0x01567ffe, 0x015f7ffe, 0x01687ffe, 

-	0x01717ffe, 0x017a7ffe, 0x01837ffe, 0x018d7ffe, 0x01977ffd, 0x01a17ffd, 0x01ab7ffd, 0x01b57ffd, 

-	0x01bf7ffd, 0x01ca7ffd, 0x01d47ffd, 0x01df7ffc, 0x01ea7ffc, 0x01f57ffc, 0x02007ffc, 0x020c7ffc, 

-	0x02177ffc, 0x02237ffb, 0x022f7ffb, 0x023b7ffb, 0x02477ffb, 0x02537ffb, 0x02607ffa, 0x026d7ffa, 

-	0x027a7ffa, 0x02877ffa, 0x02947ff9, 0x02a17ff9, 0x02af7ff9, 0x02bc7ff9, 0x02ca7ff8, 0x02d87ff8, 

-	0x02e77ff8, 0x02f57ff7, 0x03047ff7, 0x03127ff7, 0x03217ff6, 0x03317ff6, 0x03407ff5, 0x034f7ff5, 

-	0x035f7ff5, 0x036f7ff4, 0x037f7ff4, 0x038f7ff3, 0x03a07ff3, 0x03b07ff2, 0x03c17ff2, 0x03d27ff1, 

-	0x03e37ff1, 0x03f57ff0, 0x04067ff0, 0x04187fef, 0x042a7fef, 0x043c7fee, 0x044f7fed, 0x04617fed, 

-	0x04747fec, 0x04877feb, 0x049a7feb, 0x04ae7fea, 0x04c17fe9, 0x04d57fe9, 0x04e97fe8, 0x04fd7fe7, 

-	0x05127fe6, 0x05277fe5, 0x053b7fe5, 0x05507fe4, 0x05667fe3, 0x057b7fe2, 0x05917fe1, 0x05a77fe0, 

-	0x05bd7fdf, 0x05d37fde, 0x05ea7fdd, 0x06017fdc, 0x06187fdb, 0x062f7fda, 0x06467fd9, 0x065e7fd7, 

-	0x06767fd6, 0x068e7fd5, 0x06a67fd4, 0x06bf7fd2, 0x06d87fd1, 0x06f17fd0, 0x070a7fce, 0x07237fcd, 

-	0x073d7fcc, 0x07577fca, 0x07717fc9, 0x078c7fc7, 0x07a67fc5, 0x07c17fc4, 0x07dc7fc2, 0x07f77fc0, 

-	0x08137fbf, 0x082f7fbd, 0x084b7fbb, 0x08677fb9, 0x08847fb7, 0x08a07fb6, 0x08bd7fb4, 0x08da7fb2, 

-	0x08f87faf, 0x09167fad, 0x09347fab, 0x09527fa9, 0x09707fa7, 0x098f7fa5, 0x09ae7fa2, 0x09cd7fa0, 

-	0x09ec7f9d, 0x0a0c7f9b, 0x0a2c7f98, 0x0a4c7f96, 0x0a6c7f93, 0x0a8d7f91, 0x0aae7f8e, 0x0acf7f8b, 

-	0x0af07f88, 0x0b127f85, 0x0b337f82, 0x0b557f7f, 0x0b787f7c, 0x0b9a7f79, 0x0bbd7f76, 0x0be07f73, 

-	0x0c047f6f, 0x0c277f6c, 0x0c4b7f69, 0x0c6f7f65, 0x0c937f61, 0x0cb87f5e, 0x0cdd7f5a, 0x0d027f56, 

-	0x0d277f53, 0x0d4d7f4f, 0x0d737f4b, 0x0d997f47, 0x0dbf7f43, 0x0de67f3e, 0x0e0c7f3a, 0x0e347f36, 

-	0x0e5b7f31, 0x0e837f2d, 0x0eaa7f28, 0x0ed37f24, 0x0efb7f1f, 0x0f237f1a, 0x0f4c7f15, 0x0f757f10, 

-	0x0f9f7f0b, 0x0fc87f06, 0x0ff27f01, 0x101c7efb, 0x10477ef6, 0x10717ef0, 0x109c7eeb, 0x10c87ee5, 

-	0x10f37edf, 0x111f7eda, 0x114a7ed4, 0x11777ece, 0x11a37ec7, 0x11d07ec1, 0x11fd7ebb, 0x122a7eb4, 

-	0x12577eae, 0x12857ea7, 0x12b37ea0, 0x12e17e9a, 0x130f7e93, 0x133e7e8c, 0x136d7e84, 0x139c7e7d, 

-	0x13cc7e76, 0x13fb7e6e, 0x142b7e67, 0x145b7e5f, 0x148c7e57, 0x14bc7e4f, 0x14ed7e47, 0x151e7e3f, 

-	0x15507e37, 0x15817e2e, 0x15b37e26, 0x15e57e1d, 0x16187e14, 0x164a7e0b, 0x167d7e02, 0x16b07df9, 

-	0x16e47df0, 0x17177de6, 0x174b7ddd, 0x177f7dd3, 0x17b37dc9, 0x17e87dbf, 0x181d7db5, 0x18527dab, 

-	0x18877da1, 0x18bc7d96, 0x18f27d8c, 0x19287d81, 0x195e7d76, 0x19957d6b, 0x19cb7d60, 0x1a027d54, 

-	0x1a397d49, 0x1a717d3d, 0x1aa87d31, 0x1ae07d26, 0x1b187d19, 0x1b507d0d, 0x1b897d01, 0x1bc27cf4, 

-	0x1bfb7ce8, 0x1c347cdb, 0x1c6d7cce, 0x1ca77cc1, 0x1ce17cb3, 0x1d1b7ca6, 0x1d557c98, 0x1d8f7c8a, 

-	0x1dca7c7c, 0x1e057c6e, 0x1e407c60, 0x1e7b7c51, 0x1eb77c43, 0x1ef37c34, 0x1f2f7c25, 0x1f6b7c16, 

-	0x1fa77c06, 0x1fe47bf7, 0x20217be7, 0x205e7bd7, 0x209b7bc7, 0x20d87bb7, 0x21167ba6, 0x21547b96, 

-	0x21927b85, 0x21d07b74, 0x220e7b63, 0x224d7b52, 0x228c7b40, 0x22cb7b2e, 0x230a7b1c, 0x23497b0a, 

-	0x23897af8, 0x23c87ae6, 0x24087ad3, 0x24487ac0, 0x24897aad, 0x24c97a9a, 0x250a7a86, 0x254b7a73, 

-	0x258c7a5f, 0x25cd7a4b, 0x260e7a36, 0x26507a22, 0x26917a0d, 0x26d379f8, 0x271579e3, 0x275779ce, 

-	0x279a79b8, 0x27dc79a3, 0x281f798d, 0x28627977, 0x28a57960, 0x28e8794a, 0x292b7933, 0x296f791c, 

-	0x29b27905, 0x29f678ed, 0x2a3a78d6, 0x2a7e78be, 0x2ac278a6, 0x2b07788d, 0x2b4b7875, 0x2b90785c, 

-	0x2bd47843, 0x2c19782a, 0x2c5e7810, 0x2ca477f7, 0x2ce977dd, 0x2d2e77c3, 0x2d7477a8, 0x2dba778e, 

-	0x2dff7773, 0x2e457758, 0x2e8b773d, 0x2ed27721, 0x2f187706, 0x2f5e76ea, 0x2fa576cd, 0x2fec76b1, 

-	0x30327694, 0x30797677, 0x30c0765a, 0x3107763d, 0x314e761f, 0x31967601, 0x31dd75e3, 0x322575c5, 

-	0x326c75a6, 0x32b47588, 0x32fc7569, 0x33447549, 0x338c752a, 0x33d4750a, 0x341c74ea, 0x346474ca, 

-	0x34ac74a9, 0x34f57488, 0x353d7467, 0x35857446, 0x35ce7424, 0x36177403, 0x365f73e1, 0x36a873be, 

-	0x36f1739c, 0x373a7379, 0x37837356, 0x37cc7333, 0x3815730f, 0x385e72ec, 0x38a772c8, 0x38f172a3, 

-	0x393a727f, 0x3983725a, 0x39cd7235, 0x3a167210, 0x3a6071ea, 0x3aa971c4, 0x3af3719e, 0x3b3c7178, 

-	0x3b867151, 0x3bd0712b, 0x3c197104, 0x3c6370dc, 0x3cad70b5, 0x3cf7708d, 0x3d407065, 0x3d8a703c, 

-	0x3dd47014, 0x3e1e6feb, 0x3e686fc2, 0x3eb16f98, 0x3efb6f6f, 0x3f456f45, 0x3f8f6f1b, 0x3fd96ef0, 

-	0x40236ec6, 0x406d6e9b, 0x40b66e70, 0x41006e44, 0x414a6e19, 0x41946ded, 0x41de6dc1, 0x42286d94, 

-	0x42716d68, 0x42bb6d3b, 0x43056d0d, 0x434f6ce0, 0x43986cb2, 0x43e26c84, 0x442c6c56, 0x44756c28, 

-	0x44bf6bf9, 0x45086bca, 0x45526b9b, 0x459b6b6b, 0x45e56b3c, 0x462e6b0c, 0x46786adb, 0x46c16aab, 

-	0x470a6a7a, 0x47536a49, 0x479c6a18, 0x47e569e7, 0x482e69b5, 0x48776983, 0x48c06951, 0x4909691e, 

-	0x495268ec, 0x499b68b9, 0x49e36885, 0x4a2c6852, 0x4a74681e, 0x4abd67ea, 0x4b0567b6, 0x4b4d6782, 

-	0x4b95674d, 0x4bde6718, 0x4c2666e3, 0x4c6d66ae, 0x4cb56678, 0x4cfd6642, 0x4d45660c, 0x4d8c65d6, 

-	0x4dd4659f, 0x4e1b6568, 0x4e626531, 0x4ea964fa, 0x4ef064c3, 0x4f37648b, 0x4f7e6453, 0x4fc5641b, 

-	0x500b63e2, 0x505263aa, 0x50986371, 0x50df6338, 0x512562fe, 0x516b62c5, 0x51b1628b, 0x51f66251, 

-	0x523c6217, 0x528161dc, 0x52c761a2, 0x530c6167, 0x5351612c, 0x539660f1, 0x53db60b5, 0x54206079, 

-	0x5464603d, 0x54a96001, 0x54ed5fc5, 0x55315f88, 0x55755f4b, 0x55b95f0e, 0x55fc5ed1, 0x56405e94, 

-	0x56835e56, 0x56c75e18, 0x570a5dda, 0x574d5d9c, 0x578f5d5e, 0x57d25d1f, 0x58145ce0, 0x58565ca1, 

+const int twidTab64[4*6 + 16*6] = {
+	0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x2d413ccc, 0x2d413ccc,
+	0x3b20d79e, 0x187de2a6, 0x187de2a6, 0x3b20d79e, 0x00000000, 0x40000000, 0x2d413ccc, 0x2d413ccc,
+	0xd2bec334, 0x2d413ccc, 0xd2bec334, 0x2d413ccc, 0x187de2a6, 0x3b20d79e, 0xc4df2862, 0xe7821d5a,
+
+	0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x3ec52f9f, 0x0c7c5c1e,
+	0x3fb11b47, 0x0645e9af, 0x3d3e82ad, 0x1294062e, 0x3b20d79e, 0x187de2a6, 0x3ec52f9f, 0x0c7c5c1e,
+	0x3536cc52, 0x238e7673, 0x3536cc52, 0x238e7673, 0x3d3e82ad, 0x1294062e, 0x2899e64a, 0x317900d6,
+	0x2d413ccc, 0x2d413ccc, 0x3b20d79e, 0x187de2a6, 0x187de2a6, 0x3b20d79e, 0x238e7673, 0x3536cc52,
+	0x387165e3, 0x1e2b5d38, 0x0645e9af, 0x3fb11b47, 0x187de2a6, 0x3b20d79e, 0x3536cc52, 0x238e7673,
+	0xf383a3e2, 0x3ec52f9f, 0x0c7c5c1e, 0x3ec52f9f, 0x317900d6, 0x2899e64a, 0xe1d4a2c8, 0x387165e3,
+	0x00000000, 0x40000000, 0x2d413ccc, 0x2d413ccc, 0xd2bec334, 0x2d413ccc, 0xf383a3e2, 0x3ec52f9f,
+	0x2899e64a, 0x317900d6, 0xc78e9a1d, 0x1e2b5d38, 0xe7821d5a, 0x3b20d79e, 0x238e7673, 0x3536cc52,
+	0xc13ad061, 0x0c7c5c1e, 0xdc71898d, 0x3536cc52, 0x1e2b5d38, 0x387165e3, 0xc04ee4b9, 0xf9ba1651,
+	0xd2bec334, 0x2d413ccc, 0x187de2a6, 0x3b20d79e, 0xc4df2862, 0xe7821d5a, 0xcac933ae, 0x238e7673,
+	0x1294062e, 0x3d3e82ad, 0xce86ff2a, 0xd76619b6, 0xc4df2862, 0x187de2a6, 0x0c7c5c1e, 0x3ec52f9f,
+	0xdc71898d, 0xcac933ae, 0xc13ad061, 0x0c7c5c1e, 0x0645e9af, 0x3fb11b47, 0xed6bf9d2, 0xc2c17d53
+};
+#endif  //ARMV5E
+
+const int ShortWindowSine[FRAME_LEN_SHORT/2] ={
+	0x00c97fff, 0x025b7ffa, 0x03ed7ff1, 0x057f7fe2, 0x07117fce, 0x08a27fb5, 0x0a337f98, 0x0bc47f75,
+	0x0d547f4e, 0x0ee47f22, 0x10737ef0, 0x12017eba, 0x138f7e7f, 0x151c7e3f, 0x16a87dfb, 0x18337db1,
+	0x19be7d63, 0x1b477d0f, 0x1cd07cb7, 0x1e577c5a, 0x1fdd7bf9, 0x21627b92, 0x22e57b27, 0x24677ab7,
+	0x25e87a42, 0x276879c9, 0x28e5794a, 0x2a6278c8, 0x2bdc7840, 0x2d5577b4, 0x2ecc7723, 0x3042768e,
+	0x31b575f4, 0x33277556, 0x349774b3, 0x3604740b, 0x3770735f, 0x38d972af, 0x3a4071fa, 0x3ba57141,
+	0x3d087083, 0x3e686fc2, 0x3fc66efb, 0x41216e31, 0x427a6d62, 0x43d16c8f, 0x45246bb8, 0x46756add,
+	0x47c469fd, 0x490f691a, 0x4a586832, 0x4b9e6747, 0x4ce16657, 0x4e216564, 0x4f5e646c, 0x50986371,
+	0x51cf6272, 0x5303616f, 0x54336068, 0x55605f5e, 0x568a5e50, 0x57b15d3e, 0x58d45c29, 0x59f45b10
+};
+
+const int LongWindowKBD[FRAME_LEN_LONG/2]={
+	0x000a7fff, 0x000e7fff, 0x00127fff, 0x00157fff, 0x00197fff, 0x001c7fff, 0x00207fff, 0x00237fff,
+	0x00267fff, 0x002a7fff, 0x002d7fff, 0x00307fff, 0x00347fff, 0x00387fff, 0x003b7fff, 0x003f7fff,
+	0x00437fff, 0x00477fff, 0x004b7fff, 0x004f7fff, 0x00537fff, 0x00577fff, 0x005b7fff, 0x00607fff,
+	0x00647fff, 0x00697fff, 0x006d7fff, 0x00727fff, 0x00777fff, 0x007c7fff, 0x00817fff, 0x00867fff,
+	0x008b7fff, 0x00917fff, 0x00967fff, 0x009c7fff, 0x00a17fff, 0x00a77fff, 0x00ad7fff, 0x00b37fff,
+	0x00b97fff, 0x00bf7fff, 0x00c67fff, 0x00cc7fff, 0x00d37fff, 0x00da7fff, 0x00e07fff, 0x00e77fff,
+	0x00ee7fff, 0x00f57fff, 0x00fd7fff, 0x01047fff, 0x010c7fff, 0x01137fff, 0x011b7fff, 0x01237fff,
+	0x012b7fff, 0x01337fff, 0x013c7ffe, 0x01447ffe, 0x014d7ffe, 0x01567ffe, 0x015f7ffe, 0x01687ffe,
+	0x01717ffe, 0x017a7ffe, 0x01837ffe, 0x018d7ffe, 0x01977ffd, 0x01a17ffd, 0x01ab7ffd, 0x01b57ffd,
+	0x01bf7ffd, 0x01ca7ffd, 0x01d47ffd, 0x01df7ffc, 0x01ea7ffc, 0x01f57ffc, 0x02007ffc, 0x020c7ffc,
+	0x02177ffc, 0x02237ffb, 0x022f7ffb, 0x023b7ffb, 0x02477ffb, 0x02537ffb, 0x02607ffa, 0x026d7ffa,
+	0x027a7ffa, 0x02877ffa, 0x02947ff9, 0x02a17ff9, 0x02af7ff9, 0x02bc7ff9, 0x02ca7ff8, 0x02d87ff8,
+	0x02e77ff8, 0x02f57ff7, 0x03047ff7, 0x03127ff7, 0x03217ff6, 0x03317ff6, 0x03407ff5, 0x034f7ff5,
+	0x035f7ff5, 0x036f7ff4, 0x037f7ff4, 0x038f7ff3, 0x03a07ff3, 0x03b07ff2, 0x03c17ff2, 0x03d27ff1,
+	0x03e37ff1, 0x03f57ff0, 0x04067ff0, 0x04187fef, 0x042a7fef, 0x043c7fee, 0x044f7fed, 0x04617fed,
+	0x04747fec, 0x04877feb, 0x049a7feb, 0x04ae7fea, 0x04c17fe9, 0x04d57fe9, 0x04e97fe8, 0x04fd7fe7,
+	0x05127fe6, 0x05277fe5, 0x053b7fe5, 0x05507fe4, 0x05667fe3, 0x057b7fe2, 0x05917fe1, 0x05a77fe0,
+	0x05bd7fdf, 0x05d37fde, 0x05ea7fdd, 0x06017fdc, 0x06187fdb, 0x062f7fda, 0x06467fd9, 0x065e7fd7,
+	0x06767fd6, 0x068e7fd5, 0x06a67fd4, 0x06bf7fd2, 0x06d87fd1, 0x06f17fd0, 0x070a7fce, 0x07237fcd,
+	0x073d7fcc, 0x07577fca, 0x07717fc9, 0x078c7fc7, 0x07a67fc5, 0x07c17fc4, 0x07dc7fc2, 0x07f77fc0,
+	0x08137fbf, 0x082f7fbd, 0x084b7fbb, 0x08677fb9, 0x08847fb7, 0x08a07fb6, 0x08bd7fb4, 0x08da7fb2,
+	0x08f87faf, 0x09167fad, 0x09347fab, 0x09527fa9, 0x09707fa7, 0x098f7fa5, 0x09ae7fa2, 0x09cd7fa0,
+	0x09ec7f9d, 0x0a0c7f9b, 0x0a2c7f98, 0x0a4c7f96, 0x0a6c7f93, 0x0a8d7f91, 0x0aae7f8e, 0x0acf7f8b,
+	0x0af07f88, 0x0b127f85, 0x0b337f82, 0x0b557f7f, 0x0b787f7c, 0x0b9a7f79, 0x0bbd7f76, 0x0be07f73,
+	0x0c047f6f, 0x0c277f6c, 0x0c4b7f69, 0x0c6f7f65, 0x0c937f61, 0x0cb87f5e, 0x0cdd7f5a, 0x0d027f56,
+	0x0d277f53, 0x0d4d7f4f, 0x0d737f4b, 0x0d997f47, 0x0dbf7f43, 0x0de67f3e, 0x0e0c7f3a, 0x0e347f36,
+	0x0e5b7f31, 0x0e837f2d, 0x0eaa7f28, 0x0ed37f24, 0x0efb7f1f, 0x0f237f1a, 0x0f4c7f15, 0x0f757f10,
+	0x0f9f7f0b, 0x0fc87f06, 0x0ff27f01, 0x101c7efb, 0x10477ef6, 0x10717ef0, 0x109c7eeb, 0x10c87ee5,
+	0x10f37edf, 0x111f7eda, 0x114a7ed4, 0x11777ece, 0x11a37ec7, 0x11d07ec1, 0x11fd7ebb, 0x122a7eb4,
+	0x12577eae, 0x12857ea7, 0x12b37ea0, 0x12e17e9a, 0x130f7e93, 0x133e7e8c, 0x136d7e84, 0x139c7e7d,
+	0x13cc7e76, 0x13fb7e6e, 0x142b7e67, 0x145b7e5f, 0x148c7e57, 0x14bc7e4f, 0x14ed7e47, 0x151e7e3f,
+	0x15507e37, 0x15817e2e, 0x15b37e26, 0x15e57e1d, 0x16187e14, 0x164a7e0b, 0x167d7e02, 0x16b07df9,
+	0x16e47df0, 0x17177de6, 0x174b7ddd, 0x177f7dd3, 0x17b37dc9, 0x17e87dbf, 0x181d7db5, 0x18527dab,
+	0x18877da1, 0x18bc7d96, 0x18f27d8c, 0x19287d81, 0x195e7d76, 0x19957d6b, 0x19cb7d60, 0x1a027d54,
+	0x1a397d49, 0x1a717d3d, 0x1aa87d31, 0x1ae07d26, 0x1b187d19, 0x1b507d0d, 0x1b897d01, 0x1bc27cf4,
+	0x1bfb7ce8, 0x1c347cdb, 0x1c6d7cce, 0x1ca77cc1, 0x1ce17cb3, 0x1d1b7ca6, 0x1d557c98, 0x1d8f7c8a,
+	0x1dca7c7c, 0x1e057c6e, 0x1e407c60, 0x1e7b7c51, 0x1eb77c43, 0x1ef37c34, 0x1f2f7c25, 0x1f6b7c16,
+	0x1fa77c06, 0x1fe47bf7, 0x20217be7, 0x205e7bd7, 0x209b7bc7, 0x20d87bb7, 0x21167ba6, 0x21547b96,
+	0x21927b85, 0x21d07b74, 0x220e7b63, 0x224d7b52, 0x228c7b40, 0x22cb7b2e, 0x230a7b1c, 0x23497b0a,
+	0x23897af8, 0x23c87ae6, 0x24087ad3, 0x24487ac0, 0x24897aad, 0x24c97a9a, 0x250a7a86, 0x254b7a73,
+	0x258c7a5f, 0x25cd7a4b, 0x260e7a36, 0x26507a22, 0x26917a0d, 0x26d379f8, 0x271579e3, 0x275779ce,
+	0x279a79b8, 0x27dc79a3, 0x281f798d, 0x28627977, 0x28a57960, 0x28e8794a, 0x292b7933, 0x296f791c,
+	0x29b27905, 0x29f678ed, 0x2a3a78d6, 0x2a7e78be, 0x2ac278a6, 0x2b07788d, 0x2b4b7875, 0x2b90785c,
+	0x2bd47843, 0x2c19782a, 0x2c5e7810, 0x2ca477f7, 0x2ce977dd, 0x2d2e77c3, 0x2d7477a8, 0x2dba778e,
+	0x2dff7773, 0x2e457758, 0x2e8b773d, 0x2ed27721, 0x2f187706, 0x2f5e76ea, 0x2fa576cd, 0x2fec76b1,
+	0x30327694, 0x30797677, 0x30c0765a, 0x3107763d, 0x314e761f, 0x31967601, 0x31dd75e3, 0x322575c5,
+	0x326c75a6, 0x32b47588, 0x32fc7569, 0x33447549, 0x338c752a, 0x33d4750a, 0x341c74ea, 0x346474ca,
+	0x34ac74a9, 0x34f57488, 0x353d7467, 0x35857446, 0x35ce7424, 0x36177403, 0x365f73e1, 0x36a873be,
+	0x36f1739c, 0x373a7379, 0x37837356, 0x37cc7333, 0x3815730f, 0x385e72ec, 0x38a772c8, 0x38f172a3,
+	0x393a727f, 0x3983725a, 0x39cd7235, 0x3a167210, 0x3a6071ea, 0x3aa971c4, 0x3af3719e, 0x3b3c7178,
+	0x3b867151, 0x3bd0712b, 0x3c197104, 0x3c6370dc, 0x3cad70b5, 0x3cf7708d, 0x3d407065, 0x3d8a703c,
+	0x3dd47014, 0x3e1e6feb, 0x3e686fc2, 0x3eb16f98, 0x3efb6f6f, 0x3f456f45, 0x3f8f6f1b, 0x3fd96ef0,
+	0x40236ec6, 0x406d6e9b, 0x40b66e70, 0x41006e44, 0x414a6e19, 0x41946ded, 0x41de6dc1, 0x42286d94,
+	0x42716d68, 0x42bb6d3b, 0x43056d0d, 0x434f6ce0, 0x43986cb2, 0x43e26c84, 0x442c6c56, 0x44756c28,
+	0x44bf6bf9, 0x45086bca, 0x45526b9b, 0x459b6b6b, 0x45e56b3c, 0x462e6b0c, 0x46786adb, 0x46c16aab,
+	0x470a6a7a, 0x47536a49, 0x479c6a18, 0x47e569e7, 0x482e69b5, 0x48776983, 0x48c06951, 0x4909691e,
+	0x495268ec, 0x499b68b9, 0x49e36885, 0x4a2c6852, 0x4a74681e, 0x4abd67ea, 0x4b0567b6, 0x4b4d6782,
+	0x4b95674d, 0x4bde6718, 0x4c2666e3, 0x4c6d66ae, 0x4cb56678, 0x4cfd6642, 0x4d45660c, 0x4d8c65d6,
+	0x4dd4659f, 0x4e1b6568, 0x4e626531, 0x4ea964fa, 0x4ef064c3, 0x4f37648b, 0x4f7e6453, 0x4fc5641b,
+	0x500b63e2, 0x505263aa, 0x50986371, 0x50df6338, 0x512562fe, 0x516b62c5, 0x51b1628b, 0x51f66251,
+	0x523c6217, 0x528161dc, 0x52c761a2, 0x530c6167, 0x5351612c, 0x539660f1, 0x53db60b5, 0x54206079,
+	0x5464603d, 0x54a96001, 0x54ed5fc5, 0x55315f88, 0x55755f4b, 0x55b95f0e, 0x55fc5ed1, 0x56405e94,
+	0x56835e56, 0x56c75e18, 0x570a5dda, 0x574d5d9c, 0x578f5d5e, 0x57d25d1f, 0x58145ce0, 0x58565ca1,
 	0x58995c62, 0x58da5c23, 0x591c5be3, 0x595e5ba4, 0x599f5b64, 0x59e05b24, 0x5a215ae3, 0x5a625aa3
 };
 
@@ -1070,279 +1070,279 @@
 
   \brief   these tables are used for the non
            linear quantizer and inverse quantizer
-           
+
 */
 const Word32 mTab_3_4[512] = {
-	0x4c1bf829, 0x4c3880de, 0x4c550603, 0x4c71879c, 
-	0x4c8e05aa, 0x4caa8030, 0x4cc6f72f, 0x4ce36aab, 
-	0x4cffdaa4, 0x4d1c471d, 0x4d38b019, 0x4d55159a, 
-	0x4d7177a1, 0x4d8dd631, 0x4daa314b, 0x4dc688f3, 
-	0x4de2dd2a, 0x4dff2df2, 0x4e1b7b4d, 0x4e37c53d, 
-	0x4e540bc5, 0x4e704ee6, 0x4e8c8ea3, 0x4ea8cafd, 
-	0x4ec503f7, 0x4ee13992, 0x4efd6bd0, 0x4f199ab4, 
-	0x4f35c640, 0x4f51ee75, 0x4f6e1356, 0x4f8a34e4, 
-	0x4fa65321, 0x4fc26e10, 0x4fde85b2, 0x4ffa9a0a, 
-	0x5016ab18, 0x5032b8e0, 0x504ec362, 0x506acaa1, 
-	0x5086cea0, 0x50a2cf5e, 0x50becce0, 0x50dac725, 
-	0x50f6be31, 0x5112b205, 0x512ea2a3, 0x514a900d, 
-	0x51667a45, 0x5182614c, 0x519e4524, 0x51ba25cf, 
-	0x51d60350, 0x51f1dda7, 0x520db4d6, 0x522988e0, 
-	0x524559c6, 0x52612789, 0x527cf22d, 0x5298b9b1, 
-	0x52b47e19, 0x52d03f65, 0x52ebfd98, 0x5307b8b4, 
-	0x532370b9, 0x533f25aa, 0x535ad789, 0x53768656, 
-	0x53923215, 0x53addac6, 0x53c9806b, 0x53e52306, 
-	0x5400c298, 0x541c5f24, 0x5437f8ab, 0x54538f2e, 
-	0x546f22af, 0x548ab330, 0x54a640b3, 0x54c1cb38, 
-	0x54dd52c2, 0x54f8d753, 0x551458eb, 0x552fd78d, 
-	0x554b5339, 0x5566cbf3, 0x558241bb, 0x559db492, 
-	0x55b9247b, 0x55d49177, 0x55effb87, 0x560b62ad, 
-	0x5626c6eb, 0x56422842, 0x565d86b4, 0x5678e242, 
-	0x56943aee, 0x56af90b9, 0x56cae3a4, 0x56e633b2, 
-	0x570180e4, 0x571ccb3b, 0x573812b8, 0x5753575e, 
-	0x576e992e, 0x5789d829, 0x57a51450, 0x57c04da6, 
-	0x57db842b, 0x57f6b7e1, 0x5811e8c9, 0x582d16e6, 
-	0x58484238, 0x58636ac0, 0x587e9081, 0x5899b37c, 
-	0x58b4d3b1, 0x58cff123, 0x58eb0bd3, 0x590623c2, 
-	0x592138f2, 0x593c4b63, 0x59575b19, 0x59726812, 
-	0x598d7253, 0x59a879da, 0x59c37eab, 0x59de80c6, 
-	0x59f9802d, 0x5a147ce0, 0x5a2f76e2, 0x5a4a6e34, 
-	0x5a6562d6, 0x5a8054cb, 0x5a9b4414, 0x5ab630b2, 
-	0x5ad11aa6, 0x5aec01f1, 0x5b06e696, 0x5b21c895, 
-	0x5b3ca7ef, 0x5b5784a6, 0x5b725ebc, 0x5b8d3631, 
-	0x5ba80b06, 0x5bc2dd3e, 0x5bddacd9, 0x5bf879d8, 
-	0x5c13443d, 0x5c2e0c09, 0x5c48d13e, 0x5c6393dc, 
-	0x5c7e53e5, 0x5c99115a, 0x5cb3cc3c, 0x5cce848d, 
-	0x5ce93a4e, 0x5d03ed80, 0x5d1e9e24, 0x5d394c3b, 
-	0x5d53f7c7, 0x5d6ea0c9, 0x5d894742, 0x5da3eb33, 
-	0x5dbe8c9e, 0x5dd92b84, 0x5df3c7e5, 0x5e0e61c3, 
-	0x5e28f920, 0x5e438dfc, 0x5e5e2059, 0x5e78b037, 
-	0x5e933d99, 0x5eadc87e, 0x5ec850e9, 0x5ee2d6da, 
-	0x5efd5a53, 0x5f17db54, 0x5f3259e0, 0x5f4cd5f6, 
-	0x5f674f99, 0x5f81c6c8, 0x5f9c3b87, 0x5fb6add4, 
-	0x5fd11db3, 0x5feb8b23, 0x6005f626, 0x60205ebd, 
-	0x603ac4e9, 0x605528ac, 0x606f8a05, 0x6089e8f7, 
-	0x60a44583, 0x60be9fa9, 0x60d8f76b, 0x60f34cca, 
-	0x610d9fc7, 0x6127f062, 0x61423e9e, 0x615c8a7a, 
-	0x6176d3f9, 0x61911b1b, 0x61ab5fe1, 0x61c5a24d, 
-	0x61dfe25f, 0x61fa2018, 0x62145b7a, 0x622e9485, 
-	0x6248cb3b, 0x6262ff9d, 0x627d31ab, 0x62976167, 
-	0x62b18ed1, 0x62cbb9eb, 0x62e5e2b6, 0x63000933, 
-	0x631a2d62, 0x63344f45, 0x634e6edd, 0x63688c2b, 
-	0x6382a730, 0x639cbfec, 0x63b6d661, 0x63d0ea90, 
-	0x63eafc7a, 0x64050c1f, 0x641f1982, 0x643924a2, 
-	0x64532d80, 0x646d341f, 0x6487387e, 0x64a13a9e, 
-	0x64bb3a81, 0x64d53828, 0x64ef3393, 0x65092cc4, 
-	0x652323bb, 0x653d1879, 0x65570b00, 0x6570fb50, 
-	0x658ae96b, 0x65a4d550, 0x65bebf01, 0x65d8a680, 
-	0x65f28bcc, 0x660c6ee8, 0x66264fd3, 0x66402e8f, 
-	0x665a0b1c, 0x6673e57d, 0x668dbdb0, 0x66a793b8, 
-	0x66c16795, 0x66db3949, 0x66f508d4, 0x670ed636, 
-	0x6728a172, 0x67426a87, 0x675c3177, 0x6775f643, 
-	0x678fb8eb, 0x67a97971, 0x67c337d5, 0x67dcf418, 
-	0x67f6ae3b, 0x6810663f, 0x682a1c25, 0x6843cfed, 
-	0x685d8199, 0x68773129, 0x6890de9f, 0x68aa89fa, 
-	0x68c4333d, 0x68ddda67, 0x68f77f7a, 0x69112277, 
-	0x692ac35e, 0x69446230, 0x695dfeee, 0x6977999a, 
-	0x69913232, 0x69aac8ba, 0x69c45d31, 0x69ddef98, 
-	0x69f77ff0, 0x6a110e3a, 0x6a2a9a77, 0x6a4424a8, 
-	0x6a5daccc, 0x6a7732e6, 0x6a90b6f6, 0x6aaa38fd, 
-	0x6ac3b8fb, 0x6add36f2, 0x6af6b2e2, 0x6b102ccd, 
-	0x6b29a4b2, 0x6b431a92, 0x6b5c8e6f, 0x6b76004a, 
-	0x6b8f7022, 0x6ba8ddf9, 0x6bc249d0, 0x6bdbb3a7, 
-	0x6bf51b80, 0x6c0e815a, 0x6c27e537, 0x6c414718, 
-	0x6c5aa6fd, 0x6c7404e7, 0x6c8d60d7, 0x6ca6bace, 
-	0x6cc012cc, 0x6cd968d2, 0x6cf2bce1, 0x6d0c0ef9, 
-	0x6d255f1d, 0x6d3ead4b, 0x6d57f985, 0x6d7143cc, 
-	0x6d8a8c21, 0x6da3d283, 0x6dbd16f5, 0x6dd65976, 
-	0x6def9a08, 0x6e08d8ab, 0x6e221560, 0x6e3b5027, 
-	0x6e548902, 0x6e6dbff1, 0x6e86f4f5, 0x6ea0280e, 
-	0x6eb9593e, 0x6ed28885, 0x6eebb5e3, 0x6f04e15a, 
-	0x6f1e0aea, 0x6f373294, 0x6f505859, 0x6f697c39, 
-	0x6f829e35, 0x6f9bbe4e, 0x6fb4dc85, 0x6fcdf8d9, 
-	0x6fe7134d, 0x70002be0, 0x70194293, 0x70325767, 
-	0x704b6a5d, 0x70647b76, 0x707d8ab1, 0x70969811, 
-	0x70afa394, 0x70c8ad3d, 0x70e1b50c, 0x70fabb01, 
-	0x7113bf1d, 0x712cc161, 0x7145c1ce, 0x715ec064, 
-	0x7177bd24, 0x7190b80f, 0x71a9b124, 0x71c2a866, 
-	0x71db9dd4, 0x71f49170, 0x720d8339, 0x72267331, 
-	0x723f6159, 0x72584db0, 0x72713838, 0x728a20f1, 
-	0x72a307db, 0x72bbecf9, 0x72d4d049, 0x72edb1ce, 
-	0x73069187, 0x731f6f75, 0x73384b98, 0x735125f3, 
-	0x7369fe84, 0x7382d54d, 0x739baa4e, 0x73b47d89, 
-	0x73cd4efd, 0x73e61eab, 0x73feec94, 0x7417b8b8, 
-	0x74308319, 0x74494bb6, 0x74621291, 0x747ad7aa, 
-	0x74939b02, 0x74ac5c98, 0x74c51c6f, 0x74ddda86, 
-	0x74f696de, 0x750f5178, 0x75280a54, 0x7540c174, 
-	0x755976d7, 0x75722a7e, 0x758adc69, 0x75a38c9b, 
-	0x75bc3b12, 0x75d4e7cf, 0x75ed92d4, 0x76063c21, 
-	0x761ee3b6, 0x76378994, 0x76502dbc, 0x7668d02e, 
-	0x768170eb, 0x769a0ff3, 0x76b2ad47, 0x76cb48e7, 
-	0x76e3e2d5, 0x76fc7b10, 0x7715119a, 0x772da673, 
-	0x7746399b, 0x775ecb13, 0x77775adc, 0x778fe8f6, 
-	0x77a87561, 0x77c1001f, 0x77d98930, 0x77f21095, 
-	0x780a964d, 0x78231a5b, 0x783b9cbd, 0x78541d75, 
-	0x786c9c84, 0x788519e9, 0x789d95a6, 0x78b60fbb, 
-	0x78ce8828, 0x78e6feef, 0x78ff740f, 0x7917e78a, 
-	0x7930595f, 0x7948c990, 0x7961381d, 0x7979a506, 
-	0x7992104c, 0x79aa79f0, 0x79c2e1f1, 0x79db4852, 
-	0x79f3ad11, 0x7a0c1031, 0x7a2471b0, 0x7a3cd191, 
-	0x7a552fd3, 0x7a6d8c76, 0x7a85e77d, 0x7a9e40e6, 
-	0x7ab698b2, 0x7aceeee3, 0x7ae74378, 0x7aff9673, 
-	0x7b17e7d2, 0x7b303799, 0x7b4885c5, 0x7b60d259, 
-	0x7b791d55, 0x7b9166b9, 0x7ba9ae86, 0x7bc1f4bc, 
-	0x7bda395c, 0x7bf27c66, 0x7c0abddb, 0x7c22fdbb, 
-	0x7c3b3c07, 0x7c5378c0, 0x7c6bb3e5, 0x7c83ed78, 
-	0x7c9c2579, 0x7cb45be9, 0x7ccc90c7, 0x7ce4c414, 
-	0x7cfcf5d2, 0x7d152600, 0x7d2d549f, 0x7d4581b0, 
-	0x7d5dad32, 0x7d75d727, 0x7d8dff8f, 0x7da6266a, 
-	0x7dbe4bba, 0x7dd66f7d, 0x7dee91b6, 0x7e06b264, 
-	0x7e1ed188, 0x7e36ef22, 0x7e4f0b34, 0x7e6725bd, 
-	0x7e7f3ebd, 0x7e975636, 0x7eaf6c28, 0x7ec78093, 
-	0x7edf9378, 0x7ef7a4d7, 0x7f0fb4b1, 0x7f27c307, 
-	0x7f3fcfd8, 0x7f57db25, 0x7f6fe4ef, 0x7f87ed36, 
+	0x4c1bf829, 0x4c3880de, 0x4c550603, 0x4c71879c,
+	0x4c8e05aa, 0x4caa8030, 0x4cc6f72f, 0x4ce36aab,
+	0x4cffdaa4, 0x4d1c471d, 0x4d38b019, 0x4d55159a,
+	0x4d7177a1, 0x4d8dd631, 0x4daa314b, 0x4dc688f3,
+	0x4de2dd2a, 0x4dff2df2, 0x4e1b7b4d, 0x4e37c53d,
+	0x4e540bc5, 0x4e704ee6, 0x4e8c8ea3, 0x4ea8cafd,
+	0x4ec503f7, 0x4ee13992, 0x4efd6bd0, 0x4f199ab4,
+	0x4f35c640, 0x4f51ee75, 0x4f6e1356, 0x4f8a34e4,
+	0x4fa65321, 0x4fc26e10, 0x4fde85b2, 0x4ffa9a0a,
+	0x5016ab18, 0x5032b8e0, 0x504ec362, 0x506acaa1,
+	0x5086cea0, 0x50a2cf5e, 0x50becce0, 0x50dac725,
+	0x50f6be31, 0x5112b205, 0x512ea2a3, 0x514a900d,
+	0x51667a45, 0x5182614c, 0x519e4524, 0x51ba25cf,
+	0x51d60350, 0x51f1dda7, 0x520db4d6, 0x522988e0,
+	0x524559c6, 0x52612789, 0x527cf22d, 0x5298b9b1,
+	0x52b47e19, 0x52d03f65, 0x52ebfd98, 0x5307b8b4,
+	0x532370b9, 0x533f25aa, 0x535ad789, 0x53768656,
+	0x53923215, 0x53addac6, 0x53c9806b, 0x53e52306,
+	0x5400c298, 0x541c5f24, 0x5437f8ab, 0x54538f2e,
+	0x546f22af, 0x548ab330, 0x54a640b3, 0x54c1cb38,
+	0x54dd52c2, 0x54f8d753, 0x551458eb, 0x552fd78d,
+	0x554b5339, 0x5566cbf3, 0x558241bb, 0x559db492,
+	0x55b9247b, 0x55d49177, 0x55effb87, 0x560b62ad,
+	0x5626c6eb, 0x56422842, 0x565d86b4, 0x5678e242,
+	0x56943aee, 0x56af90b9, 0x56cae3a4, 0x56e633b2,
+	0x570180e4, 0x571ccb3b, 0x573812b8, 0x5753575e,
+	0x576e992e, 0x5789d829, 0x57a51450, 0x57c04da6,
+	0x57db842b, 0x57f6b7e1, 0x5811e8c9, 0x582d16e6,
+	0x58484238, 0x58636ac0, 0x587e9081, 0x5899b37c,
+	0x58b4d3b1, 0x58cff123, 0x58eb0bd3, 0x590623c2,
+	0x592138f2, 0x593c4b63, 0x59575b19, 0x59726812,
+	0x598d7253, 0x59a879da, 0x59c37eab, 0x59de80c6,
+	0x59f9802d, 0x5a147ce0, 0x5a2f76e2, 0x5a4a6e34,
+	0x5a6562d6, 0x5a8054cb, 0x5a9b4414, 0x5ab630b2,
+	0x5ad11aa6, 0x5aec01f1, 0x5b06e696, 0x5b21c895,
+	0x5b3ca7ef, 0x5b5784a6, 0x5b725ebc, 0x5b8d3631,
+	0x5ba80b06, 0x5bc2dd3e, 0x5bddacd9, 0x5bf879d8,
+	0x5c13443d, 0x5c2e0c09, 0x5c48d13e, 0x5c6393dc,
+	0x5c7e53e5, 0x5c99115a, 0x5cb3cc3c, 0x5cce848d,
+	0x5ce93a4e, 0x5d03ed80, 0x5d1e9e24, 0x5d394c3b,
+	0x5d53f7c7, 0x5d6ea0c9, 0x5d894742, 0x5da3eb33,
+	0x5dbe8c9e, 0x5dd92b84, 0x5df3c7e5, 0x5e0e61c3,
+	0x5e28f920, 0x5e438dfc, 0x5e5e2059, 0x5e78b037,
+	0x5e933d99, 0x5eadc87e, 0x5ec850e9, 0x5ee2d6da,
+	0x5efd5a53, 0x5f17db54, 0x5f3259e0, 0x5f4cd5f6,
+	0x5f674f99, 0x5f81c6c8, 0x5f9c3b87, 0x5fb6add4,
+	0x5fd11db3, 0x5feb8b23, 0x6005f626, 0x60205ebd,
+	0x603ac4e9, 0x605528ac, 0x606f8a05, 0x6089e8f7,
+	0x60a44583, 0x60be9fa9, 0x60d8f76b, 0x60f34cca,
+	0x610d9fc7, 0x6127f062, 0x61423e9e, 0x615c8a7a,
+	0x6176d3f9, 0x61911b1b, 0x61ab5fe1, 0x61c5a24d,
+	0x61dfe25f, 0x61fa2018, 0x62145b7a, 0x622e9485,
+	0x6248cb3b, 0x6262ff9d, 0x627d31ab, 0x62976167,
+	0x62b18ed1, 0x62cbb9eb, 0x62e5e2b6, 0x63000933,
+	0x631a2d62, 0x63344f45, 0x634e6edd, 0x63688c2b,
+	0x6382a730, 0x639cbfec, 0x63b6d661, 0x63d0ea90,
+	0x63eafc7a, 0x64050c1f, 0x641f1982, 0x643924a2,
+	0x64532d80, 0x646d341f, 0x6487387e, 0x64a13a9e,
+	0x64bb3a81, 0x64d53828, 0x64ef3393, 0x65092cc4,
+	0x652323bb, 0x653d1879, 0x65570b00, 0x6570fb50,
+	0x658ae96b, 0x65a4d550, 0x65bebf01, 0x65d8a680,
+	0x65f28bcc, 0x660c6ee8, 0x66264fd3, 0x66402e8f,
+	0x665a0b1c, 0x6673e57d, 0x668dbdb0, 0x66a793b8,
+	0x66c16795, 0x66db3949, 0x66f508d4, 0x670ed636,
+	0x6728a172, 0x67426a87, 0x675c3177, 0x6775f643,
+	0x678fb8eb, 0x67a97971, 0x67c337d5, 0x67dcf418,
+	0x67f6ae3b, 0x6810663f, 0x682a1c25, 0x6843cfed,
+	0x685d8199, 0x68773129, 0x6890de9f, 0x68aa89fa,
+	0x68c4333d, 0x68ddda67, 0x68f77f7a, 0x69112277,
+	0x692ac35e, 0x69446230, 0x695dfeee, 0x6977999a,
+	0x69913232, 0x69aac8ba, 0x69c45d31, 0x69ddef98,
+	0x69f77ff0, 0x6a110e3a, 0x6a2a9a77, 0x6a4424a8,
+	0x6a5daccc, 0x6a7732e6, 0x6a90b6f6, 0x6aaa38fd,
+	0x6ac3b8fb, 0x6add36f2, 0x6af6b2e2, 0x6b102ccd,
+	0x6b29a4b2, 0x6b431a92, 0x6b5c8e6f, 0x6b76004a,
+	0x6b8f7022, 0x6ba8ddf9, 0x6bc249d0, 0x6bdbb3a7,
+	0x6bf51b80, 0x6c0e815a, 0x6c27e537, 0x6c414718,
+	0x6c5aa6fd, 0x6c7404e7, 0x6c8d60d7, 0x6ca6bace,
+	0x6cc012cc, 0x6cd968d2, 0x6cf2bce1, 0x6d0c0ef9,
+	0x6d255f1d, 0x6d3ead4b, 0x6d57f985, 0x6d7143cc,
+	0x6d8a8c21, 0x6da3d283, 0x6dbd16f5, 0x6dd65976,
+	0x6def9a08, 0x6e08d8ab, 0x6e221560, 0x6e3b5027,
+	0x6e548902, 0x6e6dbff1, 0x6e86f4f5, 0x6ea0280e,
+	0x6eb9593e, 0x6ed28885, 0x6eebb5e3, 0x6f04e15a,
+	0x6f1e0aea, 0x6f373294, 0x6f505859, 0x6f697c39,
+	0x6f829e35, 0x6f9bbe4e, 0x6fb4dc85, 0x6fcdf8d9,
+	0x6fe7134d, 0x70002be0, 0x70194293, 0x70325767,
+	0x704b6a5d, 0x70647b76, 0x707d8ab1, 0x70969811,
+	0x70afa394, 0x70c8ad3d, 0x70e1b50c, 0x70fabb01,
+	0x7113bf1d, 0x712cc161, 0x7145c1ce, 0x715ec064,
+	0x7177bd24, 0x7190b80f, 0x71a9b124, 0x71c2a866,
+	0x71db9dd4, 0x71f49170, 0x720d8339, 0x72267331,
+	0x723f6159, 0x72584db0, 0x72713838, 0x728a20f1,
+	0x72a307db, 0x72bbecf9, 0x72d4d049, 0x72edb1ce,
+	0x73069187, 0x731f6f75, 0x73384b98, 0x735125f3,
+	0x7369fe84, 0x7382d54d, 0x739baa4e, 0x73b47d89,
+	0x73cd4efd, 0x73e61eab, 0x73feec94, 0x7417b8b8,
+	0x74308319, 0x74494bb6, 0x74621291, 0x747ad7aa,
+	0x74939b02, 0x74ac5c98, 0x74c51c6f, 0x74ddda86,
+	0x74f696de, 0x750f5178, 0x75280a54, 0x7540c174,
+	0x755976d7, 0x75722a7e, 0x758adc69, 0x75a38c9b,
+	0x75bc3b12, 0x75d4e7cf, 0x75ed92d4, 0x76063c21,
+	0x761ee3b6, 0x76378994, 0x76502dbc, 0x7668d02e,
+	0x768170eb, 0x769a0ff3, 0x76b2ad47, 0x76cb48e7,
+	0x76e3e2d5, 0x76fc7b10, 0x7715119a, 0x772da673,
+	0x7746399b, 0x775ecb13, 0x77775adc, 0x778fe8f6,
+	0x77a87561, 0x77c1001f, 0x77d98930, 0x77f21095,
+	0x780a964d, 0x78231a5b, 0x783b9cbd, 0x78541d75,
+	0x786c9c84, 0x788519e9, 0x789d95a6, 0x78b60fbb,
+	0x78ce8828, 0x78e6feef, 0x78ff740f, 0x7917e78a,
+	0x7930595f, 0x7948c990, 0x7961381d, 0x7979a506,
+	0x7992104c, 0x79aa79f0, 0x79c2e1f1, 0x79db4852,
+	0x79f3ad11, 0x7a0c1031, 0x7a2471b0, 0x7a3cd191,
+	0x7a552fd3, 0x7a6d8c76, 0x7a85e77d, 0x7a9e40e6,
+	0x7ab698b2, 0x7aceeee3, 0x7ae74378, 0x7aff9673,
+	0x7b17e7d2, 0x7b303799, 0x7b4885c5, 0x7b60d259,
+	0x7b791d55, 0x7b9166b9, 0x7ba9ae86, 0x7bc1f4bc,
+	0x7bda395c, 0x7bf27c66, 0x7c0abddb, 0x7c22fdbb,
+	0x7c3b3c07, 0x7c5378c0, 0x7c6bb3e5, 0x7c83ed78,
+	0x7c9c2579, 0x7cb45be9, 0x7ccc90c7, 0x7ce4c414,
+	0x7cfcf5d2, 0x7d152600, 0x7d2d549f, 0x7d4581b0,
+	0x7d5dad32, 0x7d75d727, 0x7d8dff8f, 0x7da6266a,
+	0x7dbe4bba, 0x7dd66f7d, 0x7dee91b6, 0x7e06b264,
+	0x7e1ed188, 0x7e36ef22, 0x7e4f0b34, 0x7e6725bd,
+	0x7e7f3ebd, 0x7e975636, 0x7eaf6c28, 0x7ec78093,
+	0x7edf9378, 0x7ef7a4d7, 0x7f0fb4b1, 0x7f27c307,
+	0x7f3fcfd8, 0x7f57db25, 0x7f6fe4ef, 0x7f87ed36,
 	0x7f9ff3fb, 0x7fb7f93e, 0x7fcffcff, 0x7fe7ff40
 };
 
 const Word32 mTab_4_3[512]={
-	0x32cbfd4a, 0x32eddd70, 0x330fc339, 0x3331aea3, 
-	0x33539fac, 0x33759652, 0x33979294, 0x33b99470, 
-	0x33db9be4, 0x33fda8ed, 0x341fbb8b, 0x3441d3bb, 
-	0x3463f17c, 0x348614cc, 0x34a83da8, 0x34ca6c10, 
-	0x34eca001, 0x350ed979, 0x35311877, 0x35535cfa, 
-	0x3575a6fe, 0x3597f683, 0x35ba4b87, 0x35dca607, 
-	0x35ff0603, 0x36216b78, 0x3643d665, 0x366646c7, 
-	0x3688bc9e, 0x36ab37e8, 0x36cdb8a2, 0x36f03ecb, 
-	0x3712ca62, 0x37355b64, 0x3757f1d1, 0x377a8da5, 
-	0x379d2ee0, 0x37bfd580, 0x37e28184, 0x380532e8, 
-	0x3827e9ad, 0x384aa5d0, 0x386d674f, 0x38902e2a, 
-	0x38b2fa5d, 0x38d5cbe9, 0x38f8a2ca, 0x391b7eff, 
-	0x393e6088, 0x39614761, 0x3984338a, 0x39a72501, 
-	0x39ca1bc4, 0x39ed17d1, 0x3a101928, 0x3a331fc6, 
-	0x3a562baa, 0x3a793cd2, 0x3a9c533d, 0x3abf6ee9, 
-	0x3ae28fd5, 0x3b05b5ff, 0x3b28e165, 0x3b4c1206, 
-	0x3b6f47e0, 0x3b9282f2, 0x3bb5c33a, 0x3bd908b7, 
-	0x3bfc5368, 0x3c1fa349, 0x3c42f85b, 0x3c66529c, 
-	0x3c89b209, 0x3cad16a2, 0x3cd08065, 0x3cf3ef51, 
-	0x3d176364, 0x3d3adc9c, 0x3d5e5af8, 0x3d81de77, 
-	0x3da56717, 0x3dc8f4d6, 0x3dec87b4, 0x3e101fae, 
-	0x3e33bcc3, 0x3e575ef2, 0x3e7b063a, 0x3e9eb298, 
-	0x3ec2640c, 0x3ee61a93, 0x3f09d62d, 0x3f2d96d8, 
-	0x3f515c93, 0x3f75275b, 0x3f98f731, 0x3fbccc11, 
-	0x3fe0a5fc, 0x400484ef, 0x402868ea, 0x404c51e9, 
-	0x40703fee, 0x409432f5, 0x40b82afd, 0x40dc2806, 
-	0x41002a0d, 0x41243111, 0x41483d12, 0x416c4e0d, 
-	0x41906401, 0x41b47eed, 0x41d89ecf, 0x41fcc3a7, 
-	0x4220ed72, 0x42451c30, 0x42694fde, 0x428d887d, 
-	0x42b1c609, 0x42d60883, 0x42fa4fe8, 0x431e9c37, 
-	0x4342ed70, 0x43674390, 0x438b9e96, 0x43affe82, 
-	0x43d46351, 0x43f8cd03, 0x441d3b95, 0x4441af08, 
-	0x44662758, 0x448aa487, 0x44af2690, 0x44d3ad75, 
-	0x44f83933, 0x451cc9c8, 0x45415f35, 0x4565f977, 
-	0x458a988d, 0x45af3c76, 0x45d3e531, 0x45f892bc, 
-	0x461d4516, 0x4641fc3e, 0x4666b832, 0x468b78f2, 
-	0x46b03e7c, 0x46d508cf, 0x46f9d7e9, 0x471eabca, 
-	0x47438470, 0x476861d9, 0x478d4406, 0x47b22af3, 
-	0x47d716a1, 0x47fc070e, 0x4820fc39, 0x4845f620, 
-	0x486af4c3, 0x488ff820, 0x48b50035, 0x48da0d03, 
-	0x48ff1e87, 0x492434c0, 0x49494fad, 0x496e6f4d, 
-	0x4993939f, 0x49b8bca2, 0x49ddea54, 0x4a031cb4, 
-	0x4a2853c1, 0x4a4d8f7a, 0x4a72cfde, 0x4a9814eb, 
-	0x4abd5ea1, 0x4ae2acfd, 0x4b080000, 0x4b2d57a8, 
-	0x4b52b3f3, 0x4b7814e1, 0x4b9d7a70, 0x4bc2e49f, 
-	0x4be8536e, 0x4c0dc6db, 0x4c333ee4, 0x4c58bb89, 
-	0x4c7e3cc9, 0x4ca3c2a2, 0x4cc94d14, 0x4ceedc1c, 
-	0x4d146fbb, 0x4d3a07ef, 0x4d5fa4b6, 0x4d854611, 
-	0x4daaebfd, 0x4dd09679, 0x4df64585, 0x4e1bf91f, 
-	0x4e41b146, 0x4e676dfa, 0x4e8d2f38, 0x4eb2f501, 
-	0x4ed8bf52, 0x4efe8e2b, 0x4f24618a, 0x4f4a3970, 
-	0x4f7015d9, 0x4f95f6c6, 0x4fbbdc36, 0x4fe1c626, 
-	0x5007b497, 0x502da787, 0x50539ef5, 0x50799ae1, 
-	0x509f9b48, 0x50c5a02a, 0x50eba985, 0x5111b75a, 
-	0x5137c9a6, 0x515de069, 0x5183fba2, 0x51aa1b4f, 
-	0x51d03f70, 0x51f66803, 0x521c9508, 0x5242c67d, 
-	0x5268fc62, 0x528f36b5, 0x52b57575, 0x52dbb8a2, 
-	0x5302003a, 0x53284c3c, 0x534e9ca8, 0x5374f17c, 
-	0x539b4ab7, 0x53c1a858, 0x53e80a5f, 0x540e70ca, 
-	0x5434db98, 0x545b4ac8, 0x5481be5a, 0x54a8364b, 
-	0x54ceb29c, 0x54f5334c, 0x551bb858, 0x554241c1, 
-	0x5568cf85, 0x558f61a3, 0x55b5f81b, 0x55dc92eb, 
-	0x56033212, 0x5629d590, 0x56507d63, 0x5677298a, 
-	0x569dda05, 0x56c48ed3, 0x56eb47f2, 0x57120562, 
-	0x5738c721, 0x575f8d2f, 0x5786578a, 0x57ad2633, 
-	0x57d3f927, 0x57fad066, 0x5821abef, 0x58488bc0, 
-	0x586f6fda, 0x5896583b, 0x58bd44e2, 0x58e435ce, 
-	0x590b2aff, 0x59322473, 0x59592229, 0x59802420, 
-	0x59a72a59, 0x59ce34d0, 0x59f54387, 0x5a1c567b, 
-	0x5a436dac, 0x5a6a8919, 0x5a91a8c1, 0x5ab8cca3, 
-	0x5adff4be, 0x5b072111, 0x5b2e519c, 0x5b55865e, 
-	0x5b7cbf54, 0x5ba3fc80, 0x5bcb3ddf, 0x5bf28371, 
-	0x5c19cd35, 0x5c411b2a, 0x5c686d4f, 0x5c8fc3a4, 
-	0x5cb71e27, 0x5cde7cd7, 0x5d05dfb4, 0x5d2d46bd, 
-	0x5d54b1f0, 0x5d7c214e, 0x5da394d4, 0x5dcb0c83, 
-	0x5df28859, 0x5e1a0856, 0x5e418c78, 0x5e6914be, 
-	0x5e90a129, 0x5eb831b7, 0x5edfc667, 0x5f075f38, 
-	0x5f2efc29, 0x5f569d3a, 0x5f7e426a, 0x5fa5ebb7, 
-	0x5fcd9921, 0x5ff54aa8, 0x601d004a, 0x6044ba06, 
-	0x606c77dc, 0x609439ca, 0x60bbffd0, 0x60e3c9ee, 
-	0x610b9821, 0x61336a6a, 0x615b40c8, 0x61831b39, 
-	0x61aaf9bd, 0x61d2dc53, 0x61fac2fa, 0x6222adb2, 
-	0x624a9c79, 0x62728f4f, 0x629a8633, 0x62c28123, 
-	0x62ea8020, 0x63128329, 0x633a8a3c, 0x63629559, 
-	0x638aa47f, 0x63b2b7ad, 0x63dacee2, 0x6402ea1e, 
-	0x642b0960, 0x64532ca6, 0x647b53f1, 0x64a37f3f, 
-	0x64cbae8f, 0x64f3e1e2, 0x651c1935, 0x65445488, 
-	0x656c93db, 0x6594d72c, 0x65bd1e7b, 0x65e569c7, 
-	0x660db90f, 0x66360c53, 0x665e6391, 0x6686bec9, 
-	0x66af1dfa, 0x66d78123, 0x66ffe844, 0x6728535b, 
-	0x6750c268, 0x6779356b, 0x67a1ac62, 0x67ca274c, 
-	0x67f2a629, 0x681b28f9, 0x6843afb9, 0x686c3a6a, 
-	0x6894c90b, 0x68bd5b9b, 0x68e5f219, 0x690e8c84, 
-	0x69372add, 0x695fcd21, 0x69887350, 0x69b11d6a, 
-	0x69d9cb6d, 0x6a027d5a, 0x6a2b332f, 0x6a53eceb, 
-	0x6a7caa8d, 0x6aa56c16, 0x6ace3184, 0x6af6fad6, 
-	0x6b1fc80c, 0x6b489925, 0x6b716e20, 0x6b9a46fd, 
-	0x6bc323bb, 0x6bec0458, 0x6c14e8d5, 0x6c3dd130, 
-	0x6c66bd69, 0x6c8fad80, 0x6cb8a172, 0x6ce19940, 
-	0x6d0a94e9, 0x6d33946d, 0x6d5c97ca, 0x6d859eff, 
-	0x6daeaa0d, 0x6dd7b8f1, 0x6e00cbad, 0x6e29e23e, 
-	0x6e52fca4, 0x6e7c1adf, 0x6ea53cee, 0x6ece62cf, 
-	0x6ef78c83, 0x6f20ba09, 0x6f49eb5f, 0x6f732085, 
-	0x6f9c597b, 0x6fc59640, 0x6feed6d3, 0x70181b33, 
-	0x70416360, 0x706aaf59, 0x7093ff1d, 0x70bd52ab, 
-	0x70e6aa04, 0x71100525, 0x7139640f, 0x7162c6c1, 
-	0x718c2d3a, 0x71b5977a, 0x71df057f, 0x72087749, 
-	0x7231ecd8, 0x725b662a, 0x7284e33f, 0x72ae6417, 
-	0x72d7e8b0, 0x7301710a, 0x732afd24, 0x73548cfe, 
-	0x737e2097, 0x73a7b7ee, 0x73d15303, 0x73faf1d5, 
-	0x74249462, 0x744e3aac, 0x7477e4b0, 0x74a1926e, 
-	0x74cb43e6, 0x74f4f917, 0x751eb201, 0x75486ea1, 
-	0x75722ef9, 0x759bf307, 0x75c5baca, 0x75ef8642, 
-	0x7619556f, 0x7643284f, 0x766cfee2, 0x7696d928, 
-	0x76c0b71f, 0x76ea98c7, 0x77147e20, 0x773e6728, 
-	0x776853df, 0x77924445, 0x77bc3858, 0x77e63019, 
-	0x78102b85, 0x783a2a9e, 0x78642d62, 0x788e33d1, 
-	0x78b83de9, 0x78e24bab, 0x790c5d15, 0x79367228, 
-	0x79608ae1, 0x798aa742, 0x79b4c748, 0x79deeaf4, 
-	0x7a091245, 0x7a333d3a, 0x7a5d6bd2, 0x7a879e0e, 
-	0x7ab1d3ec, 0x7adc0d6b, 0x7b064a8c, 0x7b308b4d, 
-	0x7b5acfae, 0x7b8517ae, 0x7baf634c, 0x7bd9b289, 
-	0x7c040563, 0x7c2e5bda, 0x7c58b5ec, 0x7c83139b, 
-	0x7cad74e4, 0x7cd7d9c7, 0x7d024244, 0x7d2cae5a, 
-	0x7d571e09, 0x7d81914f, 0x7dac082d, 0x7dd682a1, 
-	0x7e0100ac, 0x7e2b824b, 0x7e560780, 0x7e809048, 
-	0x7eab1ca5, 0x7ed5ac94, 0x7f004015, 0x7f2ad729, 
+	0x32cbfd4a, 0x32eddd70, 0x330fc339, 0x3331aea3,
+	0x33539fac, 0x33759652, 0x33979294, 0x33b99470,
+	0x33db9be4, 0x33fda8ed, 0x341fbb8b, 0x3441d3bb,
+	0x3463f17c, 0x348614cc, 0x34a83da8, 0x34ca6c10,
+	0x34eca001, 0x350ed979, 0x35311877, 0x35535cfa,
+	0x3575a6fe, 0x3597f683, 0x35ba4b87, 0x35dca607,
+	0x35ff0603, 0x36216b78, 0x3643d665, 0x366646c7,
+	0x3688bc9e, 0x36ab37e8, 0x36cdb8a2, 0x36f03ecb,
+	0x3712ca62, 0x37355b64, 0x3757f1d1, 0x377a8da5,
+	0x379d2ee0, 0x37bfd580, 0x37e28184, 0x380532e8,
+	0x3827e9ad, 0x384aa5d0, 0x386d674f, 0x38902e2a,
+	0x38b2fa5d, 0x38d5cbe9, 0x38f8a2ca, 0x391b7eff,
+	0x393e6088, 0x39614761, 0x3984338a, 0x39a72501,
+	0x39ca1bc4, 0x39ed17d1, 0x3a101928, 0x3a331fc6,
+	0x3a562baa, 0x3a793cd2, 0x3a9c533d, 0x3abf6ee9,
+	0x3ae28fd5, 0x3b05b5ff, 0x3b28e165, 0x3b4c1206,
+	0x3b6f47e0, 0x3b9282f2, 0x3bb5c33a, 0x3bd908b7,
+	0x3bfc5368, 0x3c1fa349, 0x3c42f85b, 0x3c66529c,
+	0x3c89b209, 0x3cad16a2, 0x3cd08065, 0x3cf3ef51,
+	0x3d176364, 0x3d3adc9c, 0x3d5e5af8, 0x3d81de77,
+	0x3da56717, 0x3dc8f4d6, 0x3dec87b4, 0x3e101fae,
+	0x3e33bcc3, 0x3e575ef2, 0x3e7b063a, 0x3e9eb298,
+	0x3ec2640c, 0x3ee61a93, 0x3f09d62d, 0x3f2d96d8,
+	0x3f515c93, 0x3f75275b, 0x3f98f731, 0x3fbccc11,
+	0x3fe0a5fc, 0x400484ef, 0x402868ea, 0x404c51e9,
+	0x40703fee, 0x409432f5, 0x40b82afd, 0x40dc2806,
+	0x41002a0d, 0x41243111, 0x41483d12, 0x416c4e0d,
+	0x41906401, 0x41b47eed, 0x41d89ecf, 0x41fcc3a7,
+	0x4220ed72, 0x42451c30, 0x42694fde, 0x428d887d,
+	0x42b1c609, 0x42d60883, 0x42fa4fe8, 0x431e9c37,
+	0x4342ed70, 0x43674390, 0x438b9e96, 0x43affe82,
+	0x43d46351, 0x43f8cd03, 0x441d3b95, 0x4441af08,
+	0x44662758, 0x448aa487, 0x44af2690, 0x44d3ad75,
+	0x44f83933, 0x451cc9c8, 0x45415f35, 0x4565f977,
+	0x458a988d, 0x45af3c76, 0x45d3e531, 0x45f892bc,
+	0x461d4516, 0x4641fc3e, 0x4666b832, 0x468b78f2,
+	0x46b03e7c, 0x46d508cf, 0x46f9d7e9, 0x471eabca,
+	0x47438470, 0x476861d9, 0x478d4406, 0x47b22af3,
+	0x47d716a1, 0x47fc070e, 0x4820fc39, 0x4845f620,
+	0x486af4c3, 0x488ff820, 0x48b50035, 0x48da0d03,
+	0x48ff1e87, 0x492434c0, 0x49494fad, 0x496e6f4d,
+	0x4993939f, 0x49b8bca2, 0x49ddea54, 0x4a031cb4,
+	0x4a2853c1, 0x4a4d8f7a, 0x4a72cfde, 0x4a9814eb,
+	0x4abd5ea1, 0x4ae2acfd, 0x4b080000, 0x4b2d57a8,
+	0x4b52b3f3, 0x4b7814e1, 0x4b9d7a70, 0x4bc2e49f,
+	0x4be8536e, 0x4c0dc6db, 0x4c333ee4, 0x4c58bb89,
+	0x4c7e3cc9, 0x4ca3c2a2, 0x4cc94d14, 0x4ceedc1c,
+	0x4d146fbb, 0x4d3a07ef, 0x4d5fa4b6, 0x4d854611,
+	0x4daaebfd, 0x4dd09679, 0x4df64585, 0x4e1bf91f,
+	0x4e41b146, 0x4e676dfa, 0x4e8d2f38, 0x4eb2f501,
+	0x4ed8bf52, 0x4efe8e2b, 0x4f24618a, 0x4f4a3970,
+	0x4f7015d9, 0x4f95f6c6, 0x4fbbdc36, 0x4fe1c626,
+	0x5007b497, 0x502da787, 0x50539ef5, 0x50799ae1,
+	0x509f9b48, 0x50c5a02a, 0x50eba985, 0x5111b75a,
+	0x5137c9a6, 0x515de069, 0x5183fba2, 0x51aa1b4f,
+	0x51d03f70, 0x51f66803, 0x521c9508, 0x5242c67d,
+	0x5268fc62, 0x528f36b5, 0x52b57575, 0x52dbb8a2,
+	0x5302003a, 0x53284c3c, 0x534e9ca8, 0x5374f17c,
+	0x539b4ab7, 0x53c1a858, 0x53e80a5f, 0x540e70ca,
+	0x5434db98, 0x545b4ac8, 0x5481be5a, 0x54a8364b,
+	0x54ceb29c, 0x54f5334c, 0x551bb858, 0x554241c1,
+	0x5568cf85, 0x558f61a3, 0x55b5f81b, 0x55dc92eb,
+	0x56033212, 0x5629d590, 0x56507d63, 0x5677298a,
+	0x569dda05, 0x56c48ed3, 0x56eb47f2, 0x57120562,
+	0x5738c721, 0x575f8d2f, 0x5786578a, 0x57ad2633,
+	0x57d3f927, 0x57fad066, 0x5821abef, 0x58488bc0,
+	0x586f6fda, 0x5896583b, 0x58bd44e2, 0x58e435ce,
+	0x590b2aff, 0x59322473, 0x59592229, 0x59802420,
+	0x59a72a59, 0x59ce34d0, 0x59f54387, 0x5a1c567b,
+	0x5a436dac, 0x5a6a8919, 0x5a91a8c1, 0x5ab8cca3,
+	0x5adff4be, 0x5b072111, 0x5b2e519c, 0x5b55865e,
+	0x5b7cbf54, 0x5ba3fc80, 0x5bcb3ddf, 0x5bf28371,
+	0x5c19cd35, 0x5c411b2a, 0x5c686d4f, 0x5c8fc3a4,
+	0x5cb71e27, 0x5cde7cd7, 0x5d05dfb4, 0x5d2d46bd,
+	0x5d54b1f0, 0x5d7c214e, 0x5da394d4, 0x5dcb0c83,
+	0x5df28859, 0x5e1a0856, 0x5e418c78, 0x5e6914be,
+	0x5e90a129, 0x5eb831b7, 0x5edfc667, 0x5f075f38,
+	0x5f2efc29, 0x5f569d3a, 0x5f7e426a, 0x5fa5ebb7,
+	0x5fcd9921, 0x5ff54aa8, 0x601d004a, 0x6044ba06,
+	0x606c77dc, 0x609439ca, 0x60bbffd0, 0x60e3c9ee,
+	0x610b9821, 0x61336a6a, 0x615b40c8, 0x61831b39,
+	0x61aaf9bd, 0x61d2dc53, 0x61fac2fa, 0x6222adb2,
+	0x624a9c79, 0x62728f4f, 0x629a8633, 0x62c28123,
+	0x62ea8020, 0x63128329, 0x633a8a3c, 0x63629559,
+	0x638aa47f, 0x63b2b7ad, 0x63dacee2, 0x6402ea1e,
+	0x642b0960, 0x64532ca6, 0x647b53f1, 0x64a37f3f,
+	0x64cbae8f, 0x64f3e1e2, 0x651c1935, 0x65445488,
+	0x656c93db, 0x6594d72c, 0x65bd1e7b, 0x65e569c7,
+	0x660db90f, 0x66360c53, 0x665e6391, 0x6686bec9,
+	0x66af1dfa, 0x66d78123, 0x66ffe844, 0x6728535b,
+	0x6750c268, 0x6779356b, 0x67a1ac62, 0x67ca274c,
+	0x67f2a629, 0x681b28f9, 0x6843afb9, 0x686c3a6a,
+	0x6894c90b, 0x68bd5b9b, 0x68e5f219, 0x690e8c84,
+	0x69372add, 0x695fcd21, 0x69887350, 0x69b11d6a,
+	0x69d9cb6d, 0x6a027d5a, 0x6a2b332f, 0x6a53eceb,
+	0x6a7caa8d, 0x6aa56c16, 0x6ace3184, 0x6af6fad6,
+	0x6b1fc80c, 0x6b489925, 0x6b716e20, 0x6b9a46fd,
+	0x6bc323bb, 0x6bec0458, 0x6c14e8d5, 0x6c3dd130,
+	0x6c66bd69, 0x6c8fad80, 0x6cb8a172, 0x6ce19940,
+	0x6d0a94e9, 0x6d33946d, 0x6d5c97ca, 0x6d859eff,
+	0x6daeaa0d, 0x6dd7b8f1, 0x6e00cbad, 0x6e29e23e,
+	0x6e52fca4, 0x6e7c1adf, 0x6ea53cee, 0x6ece62cf,
+	0x6ef78c83, 0x6f20ba09, 0x6f49eb5f, 0x6f732085,
+	0x6f9c597b, 0x6fc59640, 0x6feed6d3, 0x70181b33,
+	0x70416360, 0x706aaf59, 0x7093ff1d, 0x70bd52ab,
+	0x70e6aa04, 0x71100525, 0x7139640f, 0x7162c6c1,
+	0x718c2d3a, 0x71b5977a, 0x71df057f, 0x72087749,
+	0x7231ecd8, 0x725b662a, 0x7284e33f, 0x72ae6417,
+	0x72d7e8b0, 0x7301710a, 0x732afd24, 0x73548cfe,
+	0x737e2097, 0x73a7b7ee, 0x73d15303, 0x73faf1d5,
+	0x74249462, 0x744e3aac, 0x7477e4b0, 0x74a1926e,
+	0x74cb43e6, 0x74f4f917, 0x751eb201, 0x75486ea1,
+	0x75722ef9, 0x759bf307, 0x75c5baca, 0x75ef8642,
+	0x7619556f, 0x7643284f, 0x766cfee2, 0x7696d928,
+	0x76c0b71f, 0x76ea98c7, 0x77147e20, 0x773e6728,
+	0x776853df, 0x77924445, 0x77bc3858, 0x77e63019,
+	0x78102b85, 0x783a2a9e, 0x78642d62, 0x788e33d1,
+	0x78b83de9, 0x78e24bab, 0x790c5d15, 0x79367228,
+	0x79608ae1, 0x798aa742, 0x79b4c748, 0x79deeaf4,
+	0x7a091245, 0x7a333d3a, 0x7a5d6bd2, 0x7a879e0e,
+	0x7ab1d3ec, 0x7adc0d6b, 0x7b064a8c, 0x7b308b4d,
+	0x7b5acfae, 0x7b8517ae, 0x7baf634c, 0x7bd9b289,
+	0x7c040563, 0x7c2e5bda, 0x7c58b5ec, 0x7c83139b,
+	0x7cad74e4, 0x7cd7d9c7, 0x7d024244, 0x7d2cae5a,
+	0x7d571e09, 0x7d81914f, 0x7dac082d, 0x7dd682a1,
+	0x7e0100ac, 0x7e2b824b, 0x7e560780, 0x7e809048,
+	0x7eab1ca5, 0x7ed5ac94, 0x7f004015, 0x7f2ad729,
 	0x7f5571cd, 0x7f801003, 0x7faab1c8, 0x7fd5571d
 };
 
-

-const Word32 invSBF[24] = {

-  0x3FFD34FC, 0x2D3F8000, 0x24F18C7E, 0x1FFE9A7E, 

-  0x1C9DF10C, 0x1A1F851A, 0x182FE994, 0x169FC000, 

-  0x15542AAA, 0x143C31C2, 0x134B1B6C, 0x127920BE, 

-  0x11BF2FCC, 0x111A749E, 0x1085FC42, 0x0FFFA7BE, 

-  0x0F855818, 0x0F14EE56, 0x0EAE6A78, 0x0E4EF886, 

-  0x0DF69880, 0x0DA49568, 0x0D578542, 0x0D101D0C

-};

+
+const Word32 invSBF[24] = {
+  0x3FFD34FC, 0x2D3F8000, 0x24F18C7E, 0x1FFE9A7E,
+  0x1C9DF10C, 0x1A1F851A, 0x182FE994, 0x169FC000,
+  0x15542AAA, 0x143C31C2, 0x134B1B6C, 0x127920BE,
+  0x11BF2FCC, 0x111A749E, 0x1085FC42, 0x0FFFA7BE,
+  0x0F855818, 0x0F14EE56, 0x0EAE6A78, 0x0E4EF886,
+  0x0DF69880, 0x0DA49568, 0x0D578542, 0x0D101D0C
+};
 
 const Word16 pow2tominusNover16[17] = {
   0x7fff, 0x7a93, 0x7560, 0x7066,
@@ -1350,43 +1350,43 @@
   0x5a82, 0x56ac, 0x52ff, 0x4f7b,
   0x4c1c, 0x48e2, 0x45cb, 0x42d5,
   0x4000
-};

-

-const Word16 sideInfoTabLong[MAX_SFB_LONG + 1] = {

-  9, 9, 9, 9, 9, 9, 9, 9, 9, 

-  9, 9, 9, 9, 9, 9, 9, 9, 9, 

-  9, 9, 9, 9, 9, 9, 9, 9, 9, 

-  9, 9, 9, 9, 14, 14, 14, 14, 

-  14, 14, 14, 14, 14, 14, 14, 

-  14, 14, 14, 14, 14, 14, 14, 

-  14, 14, 14

-};

-

-const Word16 sideInfoTabShort[MAX_SFB_SHORT + 1] = {

-  7, 7, 7, 7, 7, 7, 7, 10, 10, 

-  10, 10, 10, 10, 10, 13, 13

+};
+
+const Word16 sideInfoTabLong[MAX_SFB_LONG + 1] = {
+  9, 9, 9, 9, 9, 9, 9, 9, 9,
+  9, 9, 9, 9, 9, 9, 9, 9, 9,
+  9, 9, 9, 9, 9, 9, 9, 9, 9,
+  9, 9, 9, 9, 14, 14, 14, 14,
+  14, 14, 14, 14, 14, 14, 14,
+  14, 14, 14, 14, 14, 14, 14,
+  14, 14, 14
+};
+
+const Word16 sideInfoTabShort[MAX_SFB_SHORT + 1] = {
+  7, 7, 7, 7, 7, 7, 7, 10, 10,
+  10, 10, 10, 10, 10, 13, 13
 };
 
 Word32 specExpMantTableComb_enc[4][14] =
 {
-  {0x40000000,  0x50a28be6,  0x6597fa95,  0x40000000, 
-   0x50a28be6,  0x6597fa95,  0x40000000,  0x50a28be6, 
-   0x6597fa95,  0x40000000,  0x50a28be6,  0x6597fa95, 
-   0x40000000,  0x50a28be6}, 
+  {0x40000000,  0x50a28be6,  0x6597fa95,  0x40000000,
+   0x50a28be6,  0x6597fa95,  0x40000000,  0x50a28be6,
+   0x6597fa95,  0x40000000,  0x50a28be6,  0x6597fa95,
+   0x40000000,  0x50a28be6},
 
-  {0x4c1bf829,  0x5fe4435e,  0x78d0df9c,  0x4c1bf829, 
-   0x5fe4435e,  0x78d0df9c,  0x4c1bf829,  0x5fe4435e, 
-   0x78d0df9c,  0x4c1bf829,  0x5fe4435e,  0x78d0df9c, 
-   0x4c1bf829,  0x5fe4435e}, 
+  {0x4c1bf829,  0x5fe4435e,  0x78d0df9c,  0x4c1bf829,
+   0x5fe4435e,  0x78d0df9c,  0x4c1bf829,  0x5fe4435e,
+   0x78d0df9c,  0x4c1bf829,  0x5fe4435e,  0x78d0df9c,
+   0x4c1bf829,  0x5fe4435e},
 
-  {0x5a82799a,  0x7208f81d,  0x47d66b0f,  0x5a82799a, 
-   0x7208f81d,  0x47d66b0f,  0x5a82799a,  0x7208f81d, 
-   0x47d66b0f,  0x5a82799a,  0x7208f81d,  0x47d66b0f, 
-   0x5a82799a,  0x7208f81d}, 
+  {0x5a82799a,  0x7208f81d,  0x47d66b0f,  0x5a82799a,
+   0x7208f81d,  0x47d66b0f,  0x5a82799a,  0x7208f81d,
+   0x47d66b0f,  0x5a82799a,  0x7208f81d,  0x47d66b0f,
+   0x5a82799a,  0x7208f81d},
 
-  {0x6ba27e65,  0x43ce3e4b,  0x556e0424,  0x6ba27e65, 
-   0x43ce3e4b,  0x556e0424,  0x6ba27e65,  0x43ce3e4b, 
-   0x556e0424,  0x6ba27e65,  0x43ce3e4b,  0x556e0424, 
+  {0x6ba27e65,  0x43ce3e4b,  0x556e0424,  0x6ba27e65,
+   0x43ce3e4b,  0x556e0424,  0x6ba27e65,  0x43ce3e4b,
+   0x556e0424,  0x6ba27e65,  0x43ce3e4b,  0x556e0424,
    0x6ba27e65,  0x43ce3e4b}
 };
 
@@ -1398,33 +1398,33 @@
   {1, 3, 4, 5, 7, 8, 9, 11, 12, 13, 15, 16, 17, 19}
 };
 
-const Word16 quantBorders[4][4] = {

-  /* pow(1.0-0.4054, 4/3)/16 * pow(2, (0..3)/4) */

-  {0x0400, 0x0ee7, 0x1c86, 0x2c0d},

-  /* pow(2.0-0.4054, 4/3)/16 * pow(2, (0..3)/4) */

-  {0x04c2, 0x11b9, 0x21eb, 0x3463},

-  /* pow(3.0-0.4054, 4/3)/16 * pow(2, (0..3)/4) */

-  {0x05a8, 0x1514, 0x2856, 0x3e4c},

-  /* pow(4.0-0.4054, 4/3)/16 * pow(2, (0..3)/4) */

-  {0x06ba, 0x1911, 0x2ff8, 0x4a16},

-};

-
-const Word16 quantRecon[4][3] = {

-  {0x0800, 0x1429, 0x229d},

-  {0x0983, 0x17f9, 0x292a},

-  {0x0b50, 0x1c82, 0x30f4},

-  {0x0d74, 0x21e7, 0x3a37},

+const Word16 quantBorders[4][4] = {
+  /* pow(1.0-0.4054, 4/3)/16 * pow(2, (0..3)/4) */
+  {0x0400, 0x0ee7, 0x1c86, 0x2c0d},
+  /* pow(2.0-0.4054, 4/3)/16 * pow(2, (0..3)/4) */
+  {0x04c2, 0x11b9, 0x21eb, 0x3463},
+  /* pow(3.0-0.4054, 4/3)/16 * pow(2, (0..3)/4) */
+  {0x05a8, 0x1514, 0x2856, 0x3e4c},
+  /* pow(4.0-0.4054, 4/3)/16 * pow(2, (0..3)/4) */
+  {0x06ba, 0x1911, 0x2ff8, 0x4a16},
 };
 
-const int sampRateTab[NUM_SAMPLE_RATES] = {

-    96000, 88200, 64000, 48000, 44100, 32000, 

-	24000, 22050, 16000, 12000, 11025,  8000

+const Word16 quantRecon[4][3] = {
+  {0x0800, 0x1429, 0x229d},
+  {0x0983, 0x17f9, 0x292a},
+  {0x0b50, 0x1c82, 0x30f4},
+  {0x0d74, 0x21e7, 0x3a37},
+};
+
+const int sampRateTab[NUM_SAMPLE_RATES] = {
+    96000, 88200, 64000, 48000, 44100, 32000,
+	24000, 22050, 16000, 12000, 11025,  8000
 };
 
 
-const int	rates[8] = {		

-	160, 240, 320, 400, 480, 560, 640, 0

-};

+const int	rates[8] = {
+	160, 240, 320, 400, 480, 560, 640, 0
+};
 
 const int BandwithCoefTab[8][NUM_SAMPLE_RATES] = {
 	{ 7000,  7000,  4666,  3500,  3500,  2800,  2800,  2800,  2800,  2000,  2000,  2000},
@@ -1438,76 +1438,76 @@
 };
 
 
-/* total number of scale factor bands in one window */

-const UWord8 sfBandTotalShort[NUM_SAMPLE_RATES] = {

-    12, 12, 12, 14, 14, 14, 15, 15, 15, 15, 15, 15

-};

-

-const UWord8 sfBandTotalLong[NUM_SAMPLE_RATES] = {

-    41, 41, 47, 49, 49, 51, 47, 47, 43, 43, 43, 40

-};

-

-/* scale factor band tables */

-const int sfBandTabShortOffset[NUM_SAMPLE_RATES] = {0, 0, 0, 13, 13, 13, 28, 28, 44, 44, 44, 60};

-

-const short sfBandTabShort[76] = {

-	/* short block 64, 88, 96 kHz [13]  */

-	0,   4,   8,  12,  16,  20,  24,  32,  40,  48,  64,  92, 128,

-

-	/* short block 32, 44, 48 kHz [15]  */

-	0,   4,   8,  12,  16,  20,  28,  36,  44,  56,  68,  80,  96, 112, 128,

-

-	/* short block 22, 24 kHz [16]  */

-	0,   4,   8,  12,  16,  20,  24,  28,  36,  44,  52,  64,  76,  92, 108, 128,

-

-	/* short block 11, 12, 16 kHz [16] */

-	0,   4,   8,  12,  16,  20,  24,  28,  32,  40,  48,  60,  72,  88, 108, 128,

-

-	/* short block 8 kHz [16] */

-	0,   4,   8,  12,  16,  20,  24,  28,  36,  44,  52,  60,  72,  88, 108, 128

-};

-

-const int sfBandTabLongOffset[NUM_SAMPLE_RATES] = {0, 0, 42, 90, 90, 140, 192, 192, 240, 240, 240, 284};

-

-const short sfBandTabLong[325] = {

-	/* long block 88, 96 kHz [42]  */

-	  0,   4,   8,  12,  16,  20,  24,  28,  32,  36,  40,  44,  48,   52,

-	 56,  64,  72,  80,  88,  96, 108, 120, 132, 144, 156, 172, 188,  212,

-	240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, 960, 1024,

-

-	/* long block 64 kHz [48]  */

-	  0,   4,   8,  12,  16,  20,  24,  28,  32,  36,  40,  44,  48,  52,  56,   64,

-	 72,  80,  88, 100, 112, 124, 140, 156, 172, 192, 216, 240, 268, 304, 344,  384,

-	424, 464, 504, 544, 584, 624, 664, 704, 744, 784, 824, 864, 904, 944, 984, 1024,

-

-	/* long block 44, 48 kHz [50] */

-	  0,   4,   8,  12,  16,  20,  24,  28,  32,  36,  40,  48,  56,  64,  72,   80,  88,

-	 96, 108, 120, 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384,  416, 448,

-	480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024,

-

-	/* long block 32 kHz [52] */

-	  0,   4,   8,  12,  16,  20,  24,  28,  32,  36,  40,  48,  56,  64,  72,   80,  88,  96,

-	108, 120, 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416,  448, 480, 512,

-	544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024,

-

-	/* long block 22, 24 kHz [48] */

-	  0,   4,   8,  12,  16,  20,  24,  28,  32,  36,  40,  44,  52,  60,  68,   76,

-	 84,  92, 100, 108, 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260,  284,

-	308, 336, 364, 396, 432, 468, 508, 552, 600, 652, 704, 768, 832, 896, 960, 1024,

-

-	/* long block 11, 12, 16 kHz [44] */

-	  0,   8,  16,  24,  32,  40,  48,  56,  64,  72,  80,  88, 100,  112, 124,

-	136, 148, 160, 172, 184, 196, 212, 228, 244, 260, 280, 300, 320,  344, 368,

-	396, 424, 456, 492, 532, 572, 616, 664, 716, 772, 832, 896, 960, 1024,

-

-	/* long block 8 kHz [41]  */

-	  0,  12,  24,  36,  48,  60,  72,  84,  96, 108, 120, 132,  144, 156,

-	172, 188, 204, 220, 236, 252, 268, 288, 308, 328, 348, 372,  396, 420,

-	448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944, 1024

-};

+/* total number of scale factor bands in one window */
+const UWord8 sfBandTotalShort[NUM_SAMPLE_RATES] = {
+    12, 12, 12, 14, 14, 14, 15, 15, 15, 15, 15, 15
+};
+
+const UWord8 sfBandTotalLong[NUM_SAMPLE_RATES] = {
+    41, 41, 47, 49, 49, 51, 47, 47, 43, 43, 43, 40
+};
+
+/* scale factor band tables */
+const int sfBandTabShortOffset[NUM_SAMPLE_RATES] = {0, 0, 0, 13, 13, 13, 28, 28, 44, 44, 44, 60};
+
+const short sfBandTabShort[76] = {
+	/* short block 64, 88, 96 kHz [13]  */
+	0,   4,   8,  12,  16,  20,  24,  32,  40,  48,  64,  92, 128,
+
+	/* short block 32, 44, 48 kHz [15]  */
+	0,   4,   8,  12,  16,  20,  28,  36,  44,  56,  68,  80,  96, 112, 128,
+
+	/* short block 22, 24 kHz [16]  */
+	0,   4,   8,  12,  16,  20,  24,  28,  36,  44,  52,  64,  76,  92, 108, 128,
+
+	/* short block 11, 12, 16 kHz [16] */
+	0,   4,   8,  12,  16,  20,  24,  28,  32,  40,  48,  60,  72,  88, 108, 128,
+
+	/* short block 8 kHz [16] */
+	0,   4,   8,  12,  16,  20,  24,  28,  36,  44,  52,  60,  72,  88, 108, 128
+};
+
+const int sfBandTabLongOffset[NUM_SAMPLE_RATES] = {0, 0, 42, 90, 90, 140, 192, 192, 240, 240, 240, 284};
+
+const short sfBandTabLong[325] = {
+	/* long block 88, 96 kHz [42]  */
+	  0,   4,   8,  12,  16,  20,  24,  28,  32,  36,  40,  44,  48,   52,
+	 56,  64,  72,  80,  88,  96, 108, 120, 132, 144, 156, 172, 188,  212,
+	240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, 960, 1024,
+
+	/* long block 64 kHz [48]  */
+	  0,   4,   8,  12,  16,  20,  24,  28,  32,  36,  40,  44,  48,  52,  56,   64,
+	 72,  80,  88, 100, 112, 124, 140, 156, 172, 192, 216, 240, 268, 304, 344,  384,
+	424, 464, 504, 544, 584, 624, 664, 704, 744, 784, 824, 864, 904, 944, 984, 1024,
+
+	/* long block 44, 48 kHz [50] */
+	  0,   4,   8,  12,  16,  20,  24,  28,  32,  36,  40,  48,  56,  64,  72,   80,  88,
+	 96, 108, 120, 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384,  416, 448,
+	480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024,
+
+	/* long block 32 kHz [52] */
+	  0,   4,   8,  12,  16,  20,  24,  28,  32,  36,  40,  48,  56,  64,  72,   80,  88,  96,
+	108, 120, 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416,  448, 480, 512,
+	544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024,
+
+	/* long block 22, 24 kHz [48] */
+	  0,   4,   8,  12,  16,  20,  24,  28,  32,  36,  40,  44,  52,  60,  68,   76,
+	 84,  92, 100, 108, 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260,  284,
+	308, 336, 364, 396, 432, 468, 508, 552, 600, 652, 704, 768, 832, 896, 960, 1024,
+
+	/* long block 11, 12, 16 kHz [44] */
+	  0,   8,  16,  24,  32,  40,  48,  56,  64,  72,  80,  88, 100,  112, 124,
+	136, 148, 160, 172, 184, 196, 212, 228, 244, 260, 280, 300, 320,  344, 368,
+	396, 424, 456, 492, 532, 572, 616, 664, 716, 772, 832, 896, 960, 1024,
+
+	/* long block 8 kHz [41]  */
+	  0,  12,  24,  36,  48,  60,  72,  84,  96, 108, 120, 132,  144, 156,
+	172, 188, 204, 220, 236, 252, 268, 288, 308, 328, 348, 372,  396, 420,
+	448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944, 1024
+};
 
 /*
-  these tables are used only for counting and 
+  these tables are used only for counting and
   are stored in packed format
 */
 const UWord16 huff_ltab1_2[3][3][3][3]=
@@ -2260,12 +2260,12 @@
 };
 
 const Word32 m_log2_table[INT_BITS] = {
-  0x00000000,0x4ae00d00,0x2934f080,0x15c01a3f, 
-  0x0b31fb80,0x05aeb4e0,0x02dcf2d0,0x016fe50c, 
+  0x00000000,0x4ae00d00,0x2934f080,0x15c01a3f,
+  0x0b31fb80,0x05aeb4e0,0x02dcf2d0,0x016fe50c,
   0x00b84e23,0x005c3e10,0x002e24ca,0x001713d6,
   0x000b8a47,0x0005c53b,0x0002e2a3,0x00017153,
   0x0000b8aa,0x00005c55,0x00002e2b,0x00001715,
-  0x00000b8b,0x000005c5,0x000002e3,0x00000171, 
+  0x00000b8b,0x000005c5,0x000002e3,0x00000171,
   0x000000b9,0x0000005c,0x0000002e,0x00000017,
   0x0000000c,0x00000006,0x00000003,0x00000001
 };
@@ -2344,20 +2344,20 @@
 };
 
 
-const unsigned char bitrevTab[17 + 129] = 

-{

-/* 64 */

-0x01, 0x08, 0x02, 0x04, 0x03, 0x0c, 0x05, 0x0a, 0x07, 0x0e, 0x0b, 0x0d, 0x00, 0x06, 0x09, 0x0f,

-0x00,

-

-/* 512 */

-0x01, 0x40, 0x02, 0x20, 0x03, 0x60, 0x04, 0x10, 0x05, 0x50, 0x06, 0x30, 0x07, 0x70, 0x09, 0x48,

-0x0a, 0x28, 0x0b, 0x68, 0x0c, 0x18, 0x0d, 0x58, 0x0e, 0x38, 0x0f, 0x78, 0x11, 0x44, 0x12, 0x24,

-0x13, 0x64, 0x15, 0x54, 0x16, 0x34, 0x17, 0x74, 0x19, 0x4c, 0x1a, 0x2c, 0x1b, 0x6c, 0x1d, 0x5c,

-0x1e, 0x3c, 0x1f, 0x7c, 0x21, 0x42, 0x23, 0x62, 0x25, 0x52, 0x26, 0x32, 0x27, 0x72, 0x29, 0x4a,

-0x2b, 0x6a, 0x2d, 0x5a, 0x2e, 0x3a, 0x2f, 0x7a, 0x31, 0x46, 0x33, 0x66, 0x35, 0x56, 0x37, 0x76,

-0x39, 0x4e, 0x3b, 0x6e, 0x3d, 0x5e, 0x3f, 0x7e, 0x43, 0x61, 0x45, 0x51, 0x47, 0x71, 0x4b, 0x69,

-0x4d, 0x59, 0x4f, 0x79, 0x53, 0x65, 0x57, 0x75, 0x5b, 0x6d, 0x5f, 0x7d, 0x67, 0x73, 0x6f, 0x7b,

-0x00, 0x08, 0x14, 0x1c, 0x22, 0x2a, 0x36, 0x3e, 0x41, 0x49, 0x55, 0x5d, 0x63, 0x6b, 0x77, 0x7f,

-0x00,

+const unsigned char bitrevTab[17 + 129] =
+{
+/* 64 */
+0x01, 0x08, 0x02, 0x04, 0x03, 0x0c, 0x05, 0x0a, 0x07, 0x0e, 0x0b, 0x0d, 0x00, 0x06, 0x09, 0x0f,
+0x00,
+
+/* 512 */
+0x01, 0x40, 0x02, 0x20, 0x03, 0x60, 0x04, 0x10, 0x05, 0x50, 0x06, 0x30, 0x07, 0x70, 0x09, 0x48,
+0x0a, 0x28, 0x0b, 0x68, 0x0c, 0x18, 0x0d, 0x58, 0x0e, 0x38, 0x0f, 0x78, 0x11, 0x44, 0x12, 0x24,
+0x13, 0x64, 0x15, 0x54, 0x16, 0x34, 0x17, 0x74, 0x19, 0x4c, 0x1a, 0x2c, 0x1b, 0x6c, 0x1d, 0x5c,
+0x1e, 0x3c, 0x1f, 0x7c, 0x21, 0x42, 0x23, 0x62, 0x25, 0x52, 0x26, 0x32, 0x27, 0x72, 0x29, 0x4a,
+0x2b, 0x6a, 0x2d, 0x5a, 0x2e, 0x3a, 0x2f, 0x7a, 0x31, 0x46, 0x33, 0x66, 0x35, 0x56, 0x37, 0x76,
+0x39, 0x4e, 0x3b, 0x6e, 0x3d, 0x5e, 0x3f, 0x7e, 0x43, 0x61, 0x45, 0x51, 0x47, 0x71, 0x4b, 0x69,
+0x4d, 0x59, 0x4f, 0x79, 0x53, 0x65, 0x57, 0x75, 0x5b, 0x6d, 0x5f, 0x7d, 0x67, 0x73, 0x6f, 0x7b,
+0x00, 0x08, 0x14, 0x1c, 0x22, 0x2a, 0x36, 0x3e, 0x41, 0x49, 0x55, 0x5d, 0x63, 0x6b, 0x77, 0x7f,
+0x00,
 };
\ No newline at end of file
diff --git a/media/libstagefright/codecs/aacenc/src/aacenc.c b/media/libstagefright/codecs/aacenc/src/aacenc.c
index 552ae41..b5e8a9c 100644
--- a/media/libstagefright/codecs/aacenc/src/aacenc.c
+++ b/media/libstagefright/codecs/aacenc/src/aacenc.c
@@ -1,105 +1,105 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		aacenc.c

-

-	Content:	aac encoder interface functions

-

-*******************************************************************************/

-

-#include "voAAC.h"

-#include "typedef.h"

-#include "aacenc_core.h"

-#include "aac_rom.h"

-#include "cmnMemory.h"

-#include "memalign.h"

-

-/**

-* Init the audio codec module and return codec handle

-* \param phCodec [OUT] Return the video codec handle

-* \param vType	[IN] The codec type if the module support multi codec.

-* \param pUserData	[IN] The init param. It is memory operator or alloced memory

-* \retval VO_ERR_NONE Succeeded.

-*/

-VO_U32 VO_API voAACEncInit(VO_HANDLE * phCodec,VO_AUDIO_CODINGTYPE vType, VO_CODEC_INIT_USERDATA *pUserData)

-{

-	AAC_ENCODER*hAacEnc;

-	AACENC_CONFIG config;

-	int error;

-

-#ifdef USE_DEAULT_MEM

-	VO_MEM_OPERATOR voMemoprator;

-#endif

-	VO_MEM_OPERATOR *pMemOP;

-	int interMem;

-

-	interMem = 0;

-	error = 0;

-	

-	/* init the memory operator */

-	if(pUserData == NULL || pUserData->memflag != VO_IMF_USERMEMOPERATOR || pUserData->memData == NULL )

-	{

-#ifdef USE_DEAULT_MEM

-		voMemoprator.Alloc = cmnMemAlloc;

-		voMemoprator.Copy = cmnMemCopy;

-		voMemoprator.Free = cmnMemFree;

-		voMemoprator.Set = cmnMemSet;

-		voMemoprator.Check = cmnMemCheck;

-

-		interMem = 1;

-

-		pMemOP = &voMemoprator;

-#else

-		*phCodec = NULL;

-		return VO_ERR_INVALID_ARG;

-#endif

-	}

-	else

-	{

-		pMemOP = (VO_MEM_OPERATOR *)pUserData->memData;

-	}

-

-	/* init the aac encoder handle */

-	hAacEnc = (AAC_ENCODER*)mem_malloc(pMemOP, sizeof(AAC_ENCODER), 32, VO_INDEX_ENC_AAC);

-	if(NULL == hAacEnc)

-	{

-		error = 1;

-	}

-

-	if(!error)

-	{

-		/* init the aac encoder intra memory */

-		hAacEnc->intbuf = (short *)mem_malloc(pMemOP, AACENC_BLOCKSIZE*MAX_CHANNELS*sizeof(short), 32, VO_INDEX_ENC_AAC);

-		if(NULL == hAacEnc->intbuf)

-		{

-			error = 1;

-		}

-	}

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		aacenc.c
+
+	Content:	aac encoder interface functions
+
+*******************************************************************************/
+
+#include "voAAC.h"
+#include "typedef.h"
+#include "aacenc_core.h"
+#include "aac_rom.h"
+#include "cmnMemory.h"
+#include "memalign.h"
+
+/**
+* Init the audio codec module and return codec handle
+* \param phCodec [OUT] Return the video codec handle
+* \param vType	[IN] The codec type if the module support multi codec.
+* \param pUserData	[IN] The init param. It is memory operator or alloced memory
+* \retval VO_ERR_NONE Succeeded.
+*/
+VO_U32 VO_API voAACEncInit(VO_HANDLE * phCodec,VO_AUDIO_CODINGTYPE vType, VO_CODEC_INIT_USERDATA *pUserData)
+{
+	AAC_ENCODER*hAacEnc;
+	AACENC_CONFIG config;
+	int error;
+
+#ifdef USE_DEAULT_MEM
+	VO_MEM_OPERATOR voMemoprator;
+#endif
+	VO_MEM_OPERATOR *pMemOP;
+	int interMem;
+
+	interMem = 0;
+	error = 0;
+
+	/* init the memory operator */
+	if(pUserData == NULL || pUserData->memflag != VO_IMF_USERMEMOPERATOR || pUserData->memData == NULL )
+	{
+#ifdef USE_DEAULT_MEM
+		voMemoprator.Alloc = cmnMemAlloc;
+		voMemoprator.Copy = cmnMemCopy;
+		voMemoprator.Free = cmnMemFree;
+		voMemoprator.Set = cmnMemSet;
+		voMemoprator.Check = cmnMemCheck;
+
+		interMem = 1;
+
+		pMemOP = &voMemoprator;
+#else
+		*phCodec = NULL;
+		return VO_ERR_INVALID_ARG;
+#endif
+	}
+	else
+	{
+		pMemOP = (VO_MEM_OPERATOR *)pUserData->memData;
+	}
+
+	/* init the aac encoder handle */
+	hAacEnc = (AAC_ENCODER*)mem_malloc(pMemOP, sizeof(AAC_ENCODER), 32, VO_INDEX_ENC_AAC);
+	if(NULL == hAacEnc)
+	{
+		error = 1;
+	}
+
+	if(!error)
+	{
+		/* init the aac encoder intra memory */
+		hAacEnc->intbuf = (short *)mem_malloc(pMemOP, AACENC_BLOCKSIZE*MAX_CHANNELS*sizeof(short), 32, VO_INDEX_ENC_AAC);
+		if(NULL == hAacEnc->intbuf)
+		{
+			error = 1;
+		}
+	}
+
 	if (!error) {
 		/* init the aac encoder psychoacoustic */
 		error = (PsyNew(&hAacEnc->psyKernel, MAX_CHANNELS, pMemOP) ||
 			PsyOutNew(&hAacEnc->psyOut, pMemOP));
-	}

-

+	}
+
 	if (!error) {
 		/* init the aac encoder quantization elements */
 		error = QCOutNew(&hAacEnc->qcOut,MAX_CHANNELS, pMemOP);
-	}

-

+	}
+
 	if (!error) {
 		/* init the aac encoder quantization state */
 		error = QCNew(&hAacEnc->qcKernel, pMemOP);
@@ -113,383 +113,383 @@
 		{
 			mem_free(pMemOP, hAacEnc, VO_INDEX_ENC_AAC);
 			hAacEnc = NULL;
-		}		
+		}
 		*phCodec = NULL;
 		return VO_ERR_OUTOF_MEMORY;
-	}

-

-	/* init the aac encoder memory operator  */

-#ifdef USE_DEAULT_MEM

-	if(interMem)

-	{

-		hAacEnc->voMemoprator.Alloc = cmnMemAlloc;

-		hAacEnc->voMemoprator.Copy = cmnMemCopy;

-		hAacEnc->voMemoprator.Free = cmnMemFree;

-		hAacEnc->voMemoprator.Set = cmnMemSet;

-		hAacEnc->voMemoprator.Check = cmnMemCheck;

-

-		pMemOP = &hAacEnc->voMemoprator;

-	}

-#endif

-	/* init the aac encoder default parameter  */

-	if(hAacEnc->initOK == 0)

-	{

-		 AACENC_CONFIG config;

-		 config.adtsUsed = 1;

-		 config.bitRate = 128000;

-		 config.nChannelsIn = 2;

-		 config.nChannelsOut = 2;

-		 config.sampleRate = 44100;

-		 config.bandWidth = 20000;

-

-		 AacEncOpen(hAacEnc, config);

-	}

-

-	hAacEnc->voMemop = pMemOP;

-

-	*phCodec = hAacEnc;

-

-	return VO_ERR_NONE;

-}

-

-/**

-* Set input audio data.

-* \param hCodec [IN]] The Codec Handle which was created by Init function.

-* \param pInput [IN] The input buffer param.

-* \param pOutBuffer [OUT] The output buffer info.

-* \retval VO_ERR_NONE Succeeded.

-*/

-VO_U32 VO_API voAACEncSetInputData(VO_HANDLE hCodec, VO_CODECBUFFER * pInput)

-{

-	AAC_ENCODER *hAacEnc;

-	int  length;

-

-	if(NULL == hCodec || NULL == pInput || NULL == pInput->Buffer)

-	{

-		return VO_ERR_INVALID_ARG;

-	}

-	

-	hAacEnc = (AAC_ENCODER *)hCodec;

-	

-	/* init input pcm buffer and length*/

-	hAacEnc->inbuf = (short *)pInput->Buffer;

-	hAacEnc->inlen = pInput->Length / sizeof(short);

-	hAacEnc->uselength = 0;

-

-	hAacEnc->encbuf = hAacEnc->inbuf;

-	hAacEnc->enclen = hAacEnc->inlen;

-	

-	/* rebuild intra pcm buffer and length*/

-	if(hAacEnc->intlen)

-	{

-		length = min(hAacEnc->config.nChannelsIn*AACENC_BLOCKSIZE - hAacEnc->intlen, hAacEnc->inlen);

-		hAacEnc->voMemop->Copy(VO_INDEX_ENC_AAC, hAacEnc->intbuf + hAacEnc->intlen, 

-			hAacEnc->inbuf, length*sizeof(short));

-

-		hAacEnc->encbuf = hAacEnc->intbuf;

-		hAacEnc->enclen = hAacEnc->intlen + length;

-

-		hAacEnc->inbuf += length;

-		hAacEnc->inlen -= length;

-	}

-	

-	return VO_ERR_NONE;

-}

-

-/**

-* Get the outut audio data

-* \param hCodec [IN]] The Codec Handle which was created by Init function.

-* \param pOutBuffer [OUT] The output audio data

-* \param pOutInfo [OUT] The dec module filled audio format and used the input size.

-*						 pOutInfo->InputUsed is total used the input size.

-* \retval  VO_ERR_NONE Succeeded.

-*			VO_ERR_INPUT_BUFFER_SMALL. The input was finished or the input data was not enought.

-*/

-VO_U32 VO_API voAACEncGetOutputData(VO_HANDLE hCodec, VO_CODECBUFFER * pOutput, VO_AUDIO_OUTPUTINFO * pOutInfo)

-{

-	AAC_ENCODER* hAacEnc = (AAC_ENCODER*)hCodec;

-	Word16 numAncDataBytes=0;

-	Word32  inbuflen;

-	int ret, length;

-	if(NULL == hAacEnc)

-		return VO_ERR_INVALID_ARG;

-

-	 inbuflen = AACENC_BLOCKSIZE*hAacEnc->config.nChannelsIn;

-

-	 /* check the input pcm buffer and length*/

-	 if(NULL == hAacEnc->encbuf || hAacEnc->enclen < inbuflen)

-	 {

-		length = hAacEnc->enclen;		

-		if(hAacEnc->intlen == 0)

-		{	

-			hAacEnc->voMemop->Copy(VO_INDEX_ENC_AAC, hAacEnc->intbuf, 

-				hAacEnc->encbuf, length*sizeof(short));		

-			hAacEnc->uselength += length*sizeof(short);

-		}

-		else

-		{

-			hAacEnc->uselength += (length - hAacEnc->intlen)*sizeof(short);

-		}

-

-		hAacEnc->intlen = length;

-

-		pOutput->Length = 0;

-		if(pOutInfo)

-			pOutInfo->InputUsed = hAacEnc->uselength;

-		return VO_ERR_INPUT_BUFFER_SMALL;	

-	 }

-

-	 /* check the output aac buffer and length*/

-	 if(NULL == pOutput || NULL == pOutput->Buffer || pOutput->Length < (6144/8)*hAacEnc->config.nChannelsOut/(sizeof(Word32)))

-		 return VO_ERR_OUTPUT_BUFFER_SMALL;

-

-	 /* aac encoder core function */

-	 AacEncEncode( hAacEnc,

-			(Word16*)hAacEnc->encbuf,

-			NULL,

-			&numAncDataBytes,

-			pOutput->Buffer,

-			&pOutput->Length);

-

-	 /* update the input pcm buffer and length*/

-	 if(hAacEnc->intlen)

-	 {

-		length = inbuflen - hAacEnc->intlen;		

-		hAacEnc->encbuf = hAacEnc->inbuf;

-		hAacEnc->enclen = hAacEnc->inlen;

-		hAacEnc->uselength += length*sizeof(short);

-		hAacEnc->intlen = 0;

-	 }

-	 else

-	 {

-		 hAacEnc->encbuf = hAacEnc->encbuf + inbuflen;

-		 hAacEnc->enclen = hAacEnc->enclen - inbuflen;

-		 hAacEnc->uselength += inbuflen*sizeof(short);

-	 }	 

-

-	 /* update the output aac information */

-	if(pOutInfo)

-	{

-		pOutInfo->Format.Channels = hAacEnc->config.nChannelsOut;

-		pOutInfo->Format.SampleRate = hAacEnc->config.sampleRate;

-		pOutInfo->Format.SampleBits = 16;

-		pOutInfo->InputUsed = hAacEnc->uselength;

-	}

-

-	 return VO_ERR_NONE;

-}

-

-/**

-* Uninit the Codec.

-* \param hCodec [IN]] The Codec Handle which was created by Init function.

-* \retval VO_ERR_NONE Succeeded.

-*/

-VO_U32 VO_API voAACEncUninit(VO_HANDLE hCodec)

-{

-	AAC_ENCODER* hAacEnc = (AAC_ENCODER*)hCodec;

-	

-	if(NULL != hAacEnc)

-	{

-		/* close the aac encoder */

-		AacEncClose(hAacEnc, hAacEnc->voMemop);

-

-		/* free the aac encoder handle*/

-		mem_free(hAacEnc->voMemop, hAacEnc, VO_INDEX_ENC_AAC);

-		hAacEnc = NULL;

-	}	

-

-	return VO_ERR_NONE;

-}

-

-/**

-* Set the param for special target.

-* \param hCodec [IN]] The Codec Handle which was created by Init function.

-* \param uParamID [IN] The param ID.

-* \param pData [IN] The param value depend on the ID>

-* \retval VO_ERR_NONE Succeeded.

-*/

-VO_U32 VO_API voAACEncSetParam(VO_HANDLE hCodec, VO_S32 uParamID, VO_PTR pData)

-{

-	AACENC_CONFIG config;

-	AACENC_PARAM* pAAC_param;

-	VO_AUDIO_FORMAT *pWAV_Format;

-	AAC_ENCODER* hAacEnc = (AAC_ENCODER*)hCodec;

-	int ret, i, bitrate, tmp;

-	int SampleRateIdx;

-

-	if(NULL == hAacEnc)

-		return VO_ERR_INVALID_ARG;

-	

-	switch(uParamID)

-	{

-	case VO_PID_AAC_ENCPARAM:  /* init aac encoder parameter*/

-		AacInitDefaultConfig(&config);

-		if(pData == NULL)

-			return VO_ERR_INVALID_ARG;

-		pAAC_param = (AACENC_PARAM*)pData;

-		config.adtsUsed = pAAC_param->adtsUsed;

-		config.bitRate = pAAC_param->bitRate;

-		config.nChannelsIn = pAAC_param->nChannels;

-		config.nChannelsOut = pAAC_param->nChannels;

-		config.sampleRate = pAAC_param->sampleRate;

-

-		/* check the channel */

-		if(config.nChannelsIn< 1  || config.nChannelsIn > MAX_CHANNELS  ||

-             config.nChannelsOut < 1 || config.nChannelsOut > MAX_CHANNELS || config.nChannelsIn < config.nChannelsOut)

-			 return VO_ERR_AUDIO_UNSCHANNEL;

-

-		/* check the samplerate */

-		ret = -1;

-		for(i = 0; i < NUM_SAMPLE_RATES; i++)

-		{

-			if(config.sampleRate == sampRateTab[i])

-			{

-				ret = 0;

-				break;

-			}

-		}

-		if(ret < 0)

-			return VO_ERR_AUDIO_UNSSAMPLERATE;

-

-		SampleRateIdx = i;

-

-		tmp = 441;

-		if(config.sampleRate%8000 == 0) 

-			tmp =480;

-		/* check the bitrate */

-		if(config.bitRate!=0 && (config.bitRate/config.nChannelsOut < 4000) ||

-           (config.bitRate/config.nChannelsOut > 160000) || 

-		   (config.bitRate > config.sampleRate*6*config.nChannelsOut))

-		{

-			config.bitRate = 640*config.sampleRate/tmp*config.nChannelsOut;

-

-			if(config.bitRate/config.nChannelsOut < 4000)

-				config.bitRate = 4000 * config.nChannelsOut;

-			else if(config.bitRate > config.sampleRate*6*config.nChannelsOut)

-				config.bitRate = config.sampleRate*6*config.nChannelsOut;

-			else if(config.bitRate/config.nChannelsOut > 160000)

-				config.bitRate = config.nChannelsOut*160000;

-		}

-

-		/* check the bandwidth */

-		bitrate = config.bitRate / config.nChannelsOut;

-		bitrate = bitrate * tmp / config.sampleRate;

-

-		for (i = 0; rates[i]; i++)

-		{

-			if (rates[i] >= bitrate)

-				break;

-		}

-

-		config.bandWidth = BandwithCoefTab[i][SampleRateIdx];

-

-		/* init aac encoder core */

-		ret = AacEncOpen(hAacEnc, config);

-		if(ret) 

-			return VO_ERR_AUDIO_UNSFEATURE;

-		break;

-	case VO_PID_AUDIO_FORMAT:	/* init pcm channel and samplerate*/

-		AacInitDefaultConfig(&config);

-		if(pData == NULL)

-			return VO_ERR_INVALID_ARG;

-		pWAV_Format = (VO_AUDIO_FORMAT*)pData;

-		config.adtsUsed = 1;

-		config.nChannelsIn = pWAV_Format->Channels;

-		config.nChannelsOut = pWAV_Format->Channels;

-		config.sampleRate = pWAV_Format->SampleRate;

-

-		/* check the channel */

-		if(config.nChannelsIn< 1  || config.nChannelsIn > MAX_CHANNELS  ||

-             config.nChannelsOut < 1 || config.nChannelsOut > MAX_CHANNELS || config.nChannelsIn < config.nChannelsOut)

-			 return VO_ERR_AUDIO_UNSCHANNEL;

-

-		/* check the samplebits */

-		if(pWAV_Format->SampleBits != 16)

-		{

-			return VO_ERR_AUDIO_UNSFEATURE;

-		}

-

-		/* check the samplerate */

-		ret = -1;

-		for(i = 0; i < NUM_SAMPLE_RATES; i++)

-		{

-			if(config.sampleRate == sampRateTab[i])

-			{

-				ret = 0;

-				break;

-			}

-		}

-		if(ret < 0)

-			return VO_ERR_AUDIO_UNSSAMPLERATE;

-

-		SampleRateIdx = i;

-

-		/* update the bitrates */

-		tmp = 441;

-		if(config.sampleRate%8000 == 0) 

-			tmp =480;

-

-		config.bitRate = 640*config.sampleRate/tmp*config.nChannelsOut;

-

-		if(config.bitRate/config.nChannelsOut < 4000)

-			config.bitRate = 4000 * config.nChannelsOut;

-		else if(config.bitRate > config.sampleRate*6*config.nChannelsOut)

-			config.bitRate = config.sampleRate*6*config.nChannelsOut;

-		else if(config.bitRate/config.nChannelsOut > 160000)

-			config.bitRate = config.nChannelsOut*160000;

-

-		/* check the bandwidth */

-		bitrate = config.bitRate / config.nChannelsOut;

-		bitrate = bitrate * tmp / config.sampleRate;

-

-		for (i = 0; rates[i]; i++)

-		{

-			if (rates[i] >= bitrate)

-				break;

-		}

-

-		config.bandWidth = BandwithCoefTab[i][SampleRateIdx];

-		

-		/* init aac encoder core */

-		ret = AacEncOpen(hAacEnc, config);

-		if(ret) 

-			return VO_ERR_AUDIO_UNSFEATURE;

-		break;

-	default:

-		return VO_ERR_WRONG_PARAM_ID;

-	}

-

-	return VO_ERR_NONE;

-}

-

-/**

-* Get the param for special target.

-* \param hCodec [IN]] The Codec Handle which was created by Init function.

-* \param uParamID [IN] The param ID.

-* \param pData [IN] The param value depend on the ID>

-* \retval VO_ERR_NONE Succeeded.

-*/

-VO_U32 VO_API voAACEncGetParam(VO_HANDLE hCodec, VO_S32 uParamID, VO_PTR pData)

-{

-	return VO_ERR_NONE;

-}

-

-/**

- * Get audio codec API interface

- * \param pEncHandle [out] Return the AAC Encoder handle.

- * \retval VO_ERR_OK Succeeded.

- */

-VO_S32 VO_API voGetAACEncAPI(VO_AUDIO_CODECAPI * pDecHandle)

-{

-	if(pDecHandle == NULL)

-		return VO_ERR_INVALID_ARG;

-		

-	pDecHandle->Init = voAACEncInit;

-	pDecHandle->SetInputData = voAACEncSetInputData;

-	pDecHandle->GetOutputData = voAACEncGetOutputData;

-	pDecHandle->SetParam = voAACEncSetParam;

-	pDecHandle->GetParam = voAACEncGetParam;

-	pDecHandle->Uninit = voAACEncUninit;

-

-	return VO_ERR_NONE;

+	}
+
+	/* init the aac encoder memory operator  */
+#ifdef USE_DEAULT_MEM
+	if(interMem)
+	{
+		hAacEnc->voMemoprator.Alloc = cmnMemAlloc;
+		hAacEnc->voMemoprator.Copy = cmnMemCopy;
+		hAacEnc->voMemoprator.Free = cmnMemFree;
+		hAacEnc->voMemoprator.Set = cmnMemSet;
+		hAacEnc->voMemoprator.Check = cmnMemCheck;
+
+		pMemOP = &hAacEnc->voMemoprator;
+	}
+#endif
+	/* init the aac encoder default parameter  */
+	if(hAacEnc->initOK == 0)
+	{
+		 AACENC_CONFIG config;
+		 config.adtsUsed = 1;
+		 config.bitRate = 128000;
+		 config.nChannelsIn = 2;
+		 config.nChannelsOut = 2;
+		 config.sampleRate = 44100;
+		 config.bandWidth = 20000;
+
+		 AacEncOpen(hAacEnc, config);
+	}
+
+	hAacEnc->voMemop = pMemOP;
+
+	*phCodec = hAacEnc;
+
+	return VO_ERR_NONE;
+}
+
+/**
+* Set input audio data.
+* \param hCodec [IN]] The Codec Handle which was created by Init function.
+* \param pInput [IN] The input buffer param.
+* \param pOutBuffer [OUT] The output buffer info.
+* \retval VO_ERR_NONE Succeeded.
+*/
+VO_U32 VO_API voAACEncSetInputData(VO_HANDLE hCodec, VO_CODECBUFFER * pInput)
+{
+	AAC_ENCODER *hAacEnc;
+	int  length;
+
+	if(NULL == hCodec || NULL == pInput || NULL == pInput->Buffer)
+	{
+		return VO_ERR_INVALID_ARG;
+	}
+
+	hAacEnc = (AAC_ENCODER *)hCodec;
+
+	/* init input pcm buffer and length*/
+	hAacEnc->inbuf = (short *)pInput->Buffer;
+	hAacEnc->inlen = pInput->Length / sizeof(short);
+	hAacEnc->uselength = 0;
+
+	hAacEnc->encbuf = hAacEnc->inbuf;
+	hAacEnc->enclen = hAacEnc->inlen;
+
+	/* rebuild intra pcm buffer and length*/
+	if(hAacEnc->intlen)
+	{
+		length = min(hAacEnc->config.nChannelsIn*AACENC_BLOCKSIZE - hAacEnc->intlen, hAacEnc->inlen);
+		hAacEnc->voMemop->Copy(VO_INDEX_ENC_AAC, hAacEnc->intbuf + hAacEnc->intlen,
+			hAacEnc->inbuf, length*sizeof(short));
+
+		hAacEnc->encbuf = hAacEnc->intbuf;
+		hAacEnc->enclen = hAacEnc->intlen + length;
+
+		hAacEnc->inbuf += length;
+		hAacEnc->inlen -= length;
+	}
+
+	return VO_ERR_NONE;
+}
+
+/**
+* Get the outut audio data
+* \param hCodec [IN]] The Codec Handle which was created by Init function.
+* \param pOutBuffer [OUT] The output audio data
+* \param pOutInfo [OUT] The dec module filled audio format and used the input size.
+*						 pOutInfo->InputUsed is total used the input size.
+* \retval  VO_ERR_NONE Succeeded.
+*			VO_ERR_INPUT_BUFFER_SMALL. The input was finished or the input data was not enought.
+*/
+VO_U32 VO_API voAACEncGetOutputData(VO_HANDLE hCodec, VO_CODECBUFFER * pOutput, VO_AUDIO_OUTPUTINFO * pOutInfo)
+{
+	AAC_ENCODER* hAacEnc = (AAC_ENCODER*)hCodec;
+	Word16 numAncDataBytes=0;
+	Word32  inbuflen;
+	int ret, length;
+	if(NULL == hAacEnc)
+		return VO_ERR_INVALID_ARG;
+
+	 inbuflen = AACENC_BLOCKSIZE*hAacEnc->config.nChannelsIn;
+
+	 /* check the input pcm buffer and length*/
+	 if(NULL == hAacEnc->encbuf || hAacEnc->enclen < inbuflen)
+	 {
+		length = hAacEnc->enclen;
+		if(hAacEnc->intlen == 0)
+		{
+			hAacEnc->voMemop->Copy(VO_INDEX_ENC_AAC, hAacEnc->intbuf,
+				hAacEnc->encbuf, length*sizeof(short));
+			hAacEnc->uselength += length*sizeof(short);
+		}
+		else
+		{
+			hAacEnc->uselength += (length - hAacEnc->intlen)*sizeof(short);
+		}
+
+		hAacEnc->intlen = length;
+
+		pOutput->Length = 0;
+		if(pOutInfo)
+			pOutInfo->InputUsed = hAacEnc->uselength;
+		return VO_ERR_INPUT_BUFFER_SMALL;
+	 }
+
+	 /* check the output aac buffer and length*/
+	 if(NULL == pOutput || NULL == pOutput->Buffer || pOutput->Length < (6144/8)*hAacEnc->config.nChannelsOut/(sizeof(Word32)))
+		 return VO_ERR_OUTPUT_BUFFER_SMALL;
+
+	 /* aac encoder core function */
+	 AacEncEncode( hAacEnc,
+			(Word16*)hAacEnc->encbuf,
+			NULL,
+			&numAncDataBytes,
+			pOutput->Buffer,
+			&pOutput->Length);
+
+	 /* update the input pcm buffer and length*/
+	 if(hAacEnc->intlen)
+	 {
+		length = inbuflen - hAacEnc->intlen;
+		hAacEnc->encbuf = hAacEnc->inbuf;
+		hAacEnc->enclen = hAacEnc->inlen;
+		hAacEnc->uselength += length*sizeof(short);
+		hAacEnc->intlen = 0;
+	 }
+	 else
+	 {
+		 hAacEnc->encbuf = hAacEnc->encbuf + inbuflen;
+		 hAacEnc->enclen = hAacEnc->enclen - inbuflen;
+		 hAacEnc->uselength += inbuflen*sizeof(short);
+	 }
+
+	 /* update the output aac information */
+	if(pOutInfo)
+	{
+		pOutInfo->Format.Channels = hAacEnc->config.nChannelsOut;
+		pOutInfo->Format.SampleRate = hAacEnc->config.sampleRate;
+		pOutInfo->Format.SampleBits = 16;
+		pOutInfo->InputUsed = hAacEnc->uselength;
+	}
+
+	 return VO_ERR_NONE;
+}
+
+/**
+* Uninit the Codec.
+* \param hCodec [IN]] The Codec Handle which was created by Init function.
+* \retval VO_ERR_NONE Succeeded.
+*/
+VO_U32 VO_API voAACEncUninit(VO_HANDLE hCodec)
+{
+	AAC_ENCODER* hAacEnc = (AAC_ENCODER*)hCodec;
+
+	if(NULL != hAacEnc)
+	{
+		/* close the aac encoder */
+		AacEncClose(hAacEnc, hAacEnc->voMemop);
+
+		/* free the aac encoder handle*/
+		mem_free(hAacEnc->voMemop, hAacEnc, VO_INDEX_ENC_AAC);
+		hAacEnc = NULL;
+	}
+
+	return VO_ERR_NONE;
+}
+
+/**
+* Set the param for special target.
+* \param hCodec [IN]] The Codec Handle which was created by Init function.
+* \param uParamID [IN] The param ID.
+* \param pData [IN] The param value depend on the ID>
+* \retval VO_ERR_NONE Succeeded.
+*/
+VO_U32 VO_API voAACEncSetParam(VO_HANDLE hCodec, VO_S32 uParamID, VO_PTR pData)
+{
+	AACENC_CONFIG config;
+	AACENC_PARAM* pAAC_param;
+	VO_AUDIO_FORMAT *pWAV_Format;
+	AAC_ENCODER* hAacEnc = (AAC_ENCODER*)hCodec;
+	int ret, i, bitrate, tmp;
+	int SampleRateIdx;
+
+	if(NULL == hAacEnc)
+		return VO_ERR_INVALID_ARG;
+
+	switch(uParamID)
+	{
+	case VO_PID_AAC_ENCPARAM:  /* init aac encoder parameter*/
+		AacInitDefaultConfig(&config);
+		if(pData == NULL)
+			return VO_ERR_INVALID_ARG;
+		pAAC_param = (AACENC_PARAM*)pData;
+		config.adtsUsed = pAAC_param->adtsUsed;
+		config.bitRate = pAAC_param->bitRate;
+		config.nChannelsIn = pAAC_param->nChannels;
+		config.nChannelsOut = pAAC_param->nChannels;
+		config.sampleRate = pAAC_param->sampleRate;
+
+		/* check the channel */
+		if(config.nChannelsIn< 1  || config.nChannelsIn > MAX_CHANNELS  ||
+             config.nChannelsOut < 1 || config.nChannelsOut > MAX_CHANNELS || config.nChannelsIn < config.nChannelsOut)
+			 return VO_ERR_AUDIO_UNSCHANNEL;
+
+		/* check the samplerate */
+		ret = -1;
+		for(i = 0; i < NUM_SAMPLE_RATES; i++)
+		{
+			if(config.sampleRate == sampRateTab[i])
+			{
+				ret = 0;
+				break;
+			}
+		}
+		if(ret < 0)
+			return VO_ERR_AUDIO_UNSSAMPLERATE;
+
+		SampleRateIdx = i;
+
+		tmp = 441;
+		if(config.sampleRate%8000 == 0)
+			tmp =480;
+		/* check the bitrate */
+		if(config.bitRate!=0 && (config.bitRate/config.nChannelsOut < 4000) ||
+           (config.bitRate/config.nChannelsOut > 160000) ||
+		   (config.bitRate > config.sampleRate*6*config.nChannelsOut))
+		{
+			config.bitRate = 640*config.sampleRate/tmp*config.nChannelsOut;
+
+			if(config.bitRate/config.nChannelsOut < 4000)
+				config.bitRate = 4000 * config.nChannelsOut;
+			else if(config.bitRate > config.sampleRate*6*config.nChannelsOut)
+				config.bitRate = config.sampleRate*6*config.nChannelsOut;
+			else if(config.bitRate/config.nChannelsOut > 160000)
+				config.bitRate = config.nChannelsOut*160000;
+		}
+
+		/* check the bandwidth */
+		bitrate = config.bitRate / config.nChannelsOut;
+		bitrate = bitrate * tmp / config.sampleRate;
+
+		for (i = 0; rates[i]; i++)
+		{
+			if (rates[i] >= bitrate)
+				break;
+		}
+
+		config.bandWidth = BandwithCoefTab[i][SampleRateIdx];
+
+		/* init aac encoder core */
+		ret = AacEncOpen(hAacEnc, config);
+		if(ret)
+			return VO_ERR_AUDIO_UNSFEATURE;
+		break;
+	case VO_PID_AUDIO_FORMAT:	/* init pcm channel and samplerate*/
+		AacInitDefaultConfig(&config);
+		if(pData == NULL)
+			return VO_ERR_INVALID_ARG;
+		pWAV_Format = (VO_AUDIO_FORMAT*)pData;
+		config.adtsUsed = 1;
+		config.nChannelsIn = pWAV_Format->Channels;
+		config.nChannelsOut = pWAV_Format->Channels;
+		config.sampleRate = pWAV_Format->SampleRate;
+
+		/* check the channel */
+		if(config.nChannelsIn< 1  || config.nChannelsIn > MAX_CHANNELS  ||
+             config.nChannelsOut < 1 || config.nChannelsOut > MAX_CHANNELS || config.nChannelsIn < config.nChannelsOut)
+			 return VO_ERR_AUDIO_UNSCHANNEL;
+
+		/* check the samplebits */
+		if(pWAV_Format->SampleBits != 16)
+		{
+			return VO_ERR_AUDIO_UNSFEATURE;
+		}
+
+		/* check the samplerate */
+		ret = -1;
+		for(i = 0; i < NUM_SAMPLE_RATES; i++)
+		{
+			if(config.sampleRate == sampRateTab[i])
+			{
+				ret = 0;
+				break;
+			}
+		}
+		if(ret < 0)
+			return VO_ERR_AUDIO_UNSSAMPLERATE;
+
+		SampleRateIdx = i;
+
+		/* update the bitrates */
+		tmp = 441;
+		if(config.sampleRate%8000 == 0)
+			tmp =480;
+
+		config.bitRate = 640*config.sampleRate/tmp*config.nChannelsOut;
+
+		if(config.bitRate/config.nChannelsOut < 4000)
+			config.bitRate = 4000 * config.nChannelsOut;
+		else if(config.bitRate > config.sampleRate*6*config.nChannelsOut)
+			config.bitRate = config.sampleRate*6*config.nChannelsOut;
+		else if(config.bitRate/config.nChannelsOut > 160000)
+			config.bitRate = config.nChannelsOut*160000;
+
+		/* check the bandwidth */
+		bitrate = config.bitRate / config.nChannelsOut;
+		bitrate = bitrate * tmp / config.sampleRate;
+
+		for (i = 0; rates[i]; i++)
+		{
+			if (rates[i] >= bitrate)
+				break;
+		}
+
+		config.bandWidth = BandwithCoefTab[i][SampleRateIdx];
+
+		/* init aac encoder core */
+		ret = AacEncOpen(hAacEnc, config);
+		if(ret)
+			return VO_ERR_AUDIO_UNSFEATURE;
+		break;
+	default:
+		return VO_ERR_WRONG_PARAM_ID;
+	}
+
+	return VO_ERR_NONE;
+}
+
+/**
+* Get the param for special target.
+* \param hCodec [IN]] The Codec Handle which was created by Init function.
+* \param uParamID [IN] The param ID.
+* \param pData [IN] The param value depend on the ID>
+* \retval VO_ERR_NONE Succeeded.
+*/
+VO_U32 VO_API voAACEncGetParam(VO_HANDLE hCodec, VO_S32 uParamID, VO_PTR pData)
+{
+	return VO_ERR_NONE;
+}
+
+/**
+ * Get audio codec API interface
+ * \param pEncHandle [out] Return the AAC Encoder handle.
+ * \retval VO_ERR_OK Succeeded.
+ */
+VO_S32 VO_API voGetAACEncAPI(VO_AUDIO_CODECAPI * pDecHandle)
+{
+	if(pDecHandle == NULL)
+		return VO_ERR_INVALID_ARG;
+
+	pDecHandle->Init = voAACEncInit;
+	pDecHandle->SetInputData = voAACEncSetInputData;
+	pDecHandle->GetOutputData = voAACEncGetOutputData;
+	pDecHandle->SetParam = voAACEncSetParam;
+	pDecHandle->GetParam = voAACEncGetParam;
+	pDecHandle->Uninit = voAACEncUninit;
+
+	return VO_ERR_NONE;
 }
\ No newline at end of file
diff --git a/media/libstagefright/codecs/aacenc/src/aacenc_core.c b/media/libstagefright/codecs/aacenc/src/aacenc_core.c
index 616475c..2b3bd48 100644
--- a/media/libstagefright/codecs/aacenc/src/aacenc_core.c
+++ b/media/libstagefright/codecs/aacenc/src/aacenc_core.c
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		aacenc_core.c

-

-	Content:	aac encoder core functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		aacenc_core.c
+
+	Content:	aac encoder core functions
+
 *******************************************************************************/
 
 #include "typedef.h"
@@ -43,8 +43,8 @@
   config->adtsUsed        = 1;
   config->nChannelsIn     = 2;
   config->nChannelsOut    = 2;
-  config->bitRate         = 128000;                      
-  config->bandWidth       = 0;                           
+  config->bitRate         = 128000;
+  config->bandWidth       = 0;
 }
 
 /********************************************************************************
@@ -58,16 +58,16 @@
                      const  AACENC_CONFIG     config   /* pre-initialized config struct */
                      )
 {
-  Word32 i;

+  Word32 i;
   Word32 error = 0;
-  Word16 profile = 1;

+  Word16 profile = 1;
 
   ELEMENT_INFO *elInfo = NULL;
-   
+
   if (hAacEnc==0) {
-    error=1;                                  
+    error=1;
   }
-   
+
   if (!error) {
     hAacEnc->config = config;
   }
@@ -76,14 +76,14 @@
     error = InitElementInfo (config.nChannelsOut,
                              &hAacEnc->elInfo);
   }
-

+
   if (!error) {
     elInfo = &hAacEnc->elInfo;
   }
 
   if (!error) {
     /* use or not tns tool for long and short block */
-	 Word16 tnsMask=3;      
+	 Word16 tnsMask=3;
 
 	/* init encoder psychoacoustic */
     error = psyMainInit(&hAacEnc->psyKernel,
@@ -95,8 +95,8 @@
   }
 
  /* use or not adts header */
-  if(!error) {

-	  hAacEnc->qcOut.qcElement.adtsUsed = config.adtsUsed;

+  if(!error) {
+	  hAacEnc->qcOut.qcElement.adtsUsed = config.adtsUsed;
   }
 
   /* init encoder quantization */
@@ -107,10 +107,10 @@
     qcInit.elInfo = &hAacEnc->elInfo;
 
     qcInit.maxBits = (Word16) (MAXBITS_COEF*elInfo->nChannelsInEl);
-    qcInit.bitRes = qcInit.maxBits;                                      
+    qcInit.bitRes = qcInit.maxBits;
     qcInit.averageBits = (Word16) ((config.bitRate * FRAME_LEN_LONG) / config.sampleRate);
 
-    qcInit.padding.paddingRest = config.sampleRate;                          
+    qcInit.padding.paddingRest = config.sampleRate;
 
     qcInit.meanPe = (Word16) ((10 * FRAME_LEN_LONG * hAacEnc->config.bandWidth) /
                                               (config.sampleRate>>1));
@@ -118,17 +118,17 @@
     qcInit.maxBitFac = (Word16) ((100 * (MAXBITS_COEF-MINBITS_COEF)* elInfo->nChannelsInEl)/
                                                  (qcInit.averageBits?qcInit.averageBits:1));
 
-    qcInit.bitrate = config.bitRate;                                     
+    qcInit.bitrate = config.bitRate;
 
     error = QCInit(&hAacEnc->qcKernel, &qcInit);
   }
 
   /* init bitstream encoder */
   if (!error) {
-    hAacEnc->bseInit.nChannels   = elInfo->nChannelsInEl;                
-    hAacEnc->bseInit.bitrate     = config.bitRate;                       
-    hAacEnc->bseInit.sampleRate  = config.sampleRate;                    
-    hAacEnc->bseInit.profile     = profile;                              
+    hAacEnc->bseInit.nChannels   = elInfo->nChannelsInEl;
+    hAacEnc->bseInit.bitrate     = config.bitRate;
+    hAacEnc->bseInit.sampleRate  = config.sampleRate;
+    hAacEnc->bseInit.profile     = profile;
   }
 
   return error;
@@ -152,14 +152,14 @@
   ELEMENT_INFO *elInfo = &aacEnc->elInfo;
   Word16 globUsedBits;
   Word16 ancDataBytes, ancDataBytesLeft;
-  
-  ancDataBytes = ancDataBytesLeft = *numAncBytes;                          
+
+  ancDataBytes = ancDataBytesLeft = *numAncBytes;
 
   /* init output aac data buffer and length */
   aacEnc->hBitStream = CreateBitBuffer(&aacEnc->bitStream, outBytes, *numOutBytes);
 
   /* psychoacoustic process */
-  psyMain(aacEnc->config.nChannelsOut,    
+  psyMain(aacEnc->config.nChannelsOut,
           elInfo,
           timeSignal,
           &aacEnc->psyKernel.psyData[elInfo->ChannelIndex[0]],
@@ -175,9 +175,9 @@
   AdjustBitrate(&aacEnc->qcKernel,
                 aacEnc->config.bitRate,
                 aacEnc->config.sampleRate);
-    
+
   /* quantization and coding process */
-  QCMain(&aacEnc->qcKernel,         
+  QCMain(&aacEnc->qcKernel,
          &aacEnc->qcKernel.elementBits,
          &aacEnc->qcKernel.adjThr.adjThrStateElem,
          &aacEnc->psyOut.psyOutChannel[elInfo->ChannelIndex[0]],
@@ -193,19 +193,19 @@
                          &aacEnc->qcOut);
 
   /* write bitstream process */
-  WriteBitstream(aacEnc->hBitStream,				 
+  WriteBitstream(aacEnc->hBitStream,
                  *elInfo,
                  &aacEnc->qcOut,
                  &aacEnc->psyOut,
-                 &globUsedBits,				 
-                 ancBytes,

+                 &globUsedBits,
+                 ancBytes,
 				 aacEnc->psyKernel.sampleRateIdx);
 
   updateBitres(&aacEnc->qcKernel,
                &aacEnc->qcOut);
 
   /* write out the bitstream */
-  *numOutBytes = GetBitsAvail(aacEnc->hBitStream) >> 3;

+  *numOutBytes = GetBitsAvail(aacEnc->hBitStream) >> 3;
 
   return 0;
 }
@@ -219,7 +219,7 @@
 **********************************************************************************/
 void AacEncClose (AAC_ENCODER* hAacEnc, VO_MEM_OPERATOR *pMemOP)
 {
-  if (hAacEnc) {  
+  if (hAacEnc) {
     QCDelete(&hAacEnc->qcKernel, pMemOP);
 
     QCOutDelete(&hAacEnc->qcOut, pMemOP);
diff --git a/media/libstagefright/codecs/aacenc/src/adj_thr.c b/media/libstagefright/codecs/aacenc/src/adj_thr.c
index 0dbd216..c656f65 100644
--- a/media/libstagefright/codecs/aacenc/src/adj_thr.c
+++ b/media/libstagefright/codecs/aacenc/src/adj_thr.c
@@ -1,26 +1,26 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		adj_thr.c

-

-	Content:	Threshold compensation functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		adj_thr.c
+
+	Content:	Threshold compensation functions
+
 *******************************************************************************/
 
-#include "basic_op.h"

+#include "basic_op.h"
 #include "oper_32b.h"
 #include "adj_thr_data.h"
 #include "adj_thr.h"
@@ -29,14 +29,14 @@
 
 
 #define  minSnrLimit    0x6666 /* 1 dB */
-#define  PEBITS_COEF	0x170a /* 0.18*(1 << 15)*/

-

-#define  HOLE_THR_LONG	0x2873	/* 0.316*(1 << 15) */

-#define  HOLE_THR_SHORT 0x4000  /* 0.5  *(1 << 15) */

-

-#define  MS_THRSPREAD_COEF 0x7333  /* 0.9 * (1 << 15) */

-

-#define	 MIN_SNR_COEF	   0x651f  /* 3.16* (1 << (15 - 2)) */

+#define  PEBITS_COEF	0x170a /* 0.18*(1 << 15)*/
+
+#define  HOLE_THR_LONG	0x2873	/* 0.316*(1 << 15) */
+#define  HOLE_THR_SHORT 0x4000  /* 0.5  *(1 << 15) */
+
+#define  MS_THRSPREAD_COEF 0x7333  /* 0.9 * (1 << 15) */
+
+#define	 MIN_SNR_COEF	   0x651f  /* 3.16* (1 << (15 - 2)) */
 
 /* values for avoid hole flag */
 enum _avoid_hole_state {
@@ -67,15 +67,15 @@
                           PSY_OUT_CHANNEL psyOutChannel[MAX_CHANNELS],
                           const Word16 nChannels)
 {
-  Word16 ch, sfb, sfbGrp;

+  Word16 ch, sfb, sfbGrp;
   Word32 *pthrExp, *psfbThre;
   for (ch=0; ch<nChannels; ch++) {
-    PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];

-	 for(sfbGrp = 0; sfbGrp < psyOutChan->sfbCnt; sfbGrp+= psyOutChan->sfbPerGroup)	 

-	  pthrExp = &(thrExp[ch][sfbGrp]);

-	  psfbThre = psyOutChan->sfbThreshold + sfbGrp;

+    PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
+	 for(sfbGrp = 0; sfbGrp < psyOutChan->sfbCnt; sfbGrp+= psyOutChan->sfbPerGroup)
+	  pthrExp = &(thrExp[ch][sfbGrp]);
+	  psfbThre = psyOutChan->sfbThreshold + sfbGrp;
 	  for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-		*pthrExp = rsqrt(rsqrt(*psfbThre,INT_BITS),INT_BITS);

+		*pthrExp = rsqrt(rsqrt(*psfbThre,INT_BITS),INT_BITS);
 		pthrExp++; psfbThre++;
       }
   }
@@ -96,29 +96,29 @@
   Word32 nSfb, avgEn;
   Word16 log_avgEn = 0;
   Word32 startRatio_x_avgEn = 0;
-                                                                           
+
 
   for (ch=0; ch<nChannels; ch++) {
     PSY_OUT_CHANNEL* psyOutChan = &psyOutChannel[ch];
 
     /* calc average energy per scalefactor band */
-    avgEn = 0;                                                           
-    nSfb = 0;                                                            
+    avgEn = 0;
+    nSfb = 0;
     for (sfbOffs=0; sfbOffs<psyOutChan->sfbCnt; sfbOffs+=psyOutChan->sfbPerGroup) {
       for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
         avgEn = L_add(avgEn, psyOutChan->sfbEnergy[sfbOffs+sfb]);
         nSfb = nSfb + 1;
       }
     }
-     
+
     if (nSfb > 0) {
-	  avgEn = avgEn / nSfb;

+	  avgEn = avgEn / nSfb;
 
       log_avgEn = iLog4(avgEn);
       startRatio_x_avgEn = fixmul(msaParam->startRatio, avgEn);
     }
 
-    
+
     /* reduce minSnr requirement by minSnr^minSnrRed dependent on avgEn/sfbEn */
     for (sfbOffs=0; sfbOffs<psyOutChan->sfbCnt; sfbOffs+=psyOutChan->sfbPerGroup) {
       for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
@@ -126,22 +126,22 @@
           Word16 dbRatio, minSnrRed;
           Word32 snrRed;
           Word16 newMinSnr;
-          
+
           dbRatio = log_avgEn - logSfbEnergy[ch][sfbOffs+sfb];
           dbRatio = dbRatio + (dbRatio << 1);
 
           minSnrRed = 110 - ((dbRatio + (dbRatio << 1)) >> 2);
-          minSnrRed = max(minSnrRed, 20); /* 110: (0.375(redOffs)+1)*80,  
+          minSnrRed = max(minSnrRed, 20); /* 110: (0.375(redOffs)+1)*80,
                                                3: 0.00375(redRatioFac)*80
                                                20: 0.25(maxRed) * 80 */
 
-          snrRed = minSnrRed * iLog4((psyOutChan->sfbMinSnr[sfbOffs+sfb] << 16)); 
-          /* 
+          snrRed = minSnrRed * iLog4((psyOutChan->sfbMinSnr[sfbOffs+sfb] << 16));
+          /*
              snrRedI si now scaled by 80 (minSnrRed) and 4 (ffr_iLog4)
           */
-        
+
           newMinSnr = round16(pow2_xy(snrRed,80*4));
-         
+
           psyOutChan->sfbMinSnr[sfbOffs+sfb] = min(newMinSnr, minSnrLimit);
         }
       }
@@ -169,21 +169,21 @@
 
   for (ch=0; ch<nChannels; ch++) {
     PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
-     
+
     if (psyOutChan->windowSequence != SHORT_WINDOW) {
       for(sfbGrp = 0;sfbGrp < psyOutChan->sfbCnt;sfbGrp+= psyOutChan->sfbPerGroup){
-         psfbSpreadEn = psyOutChan->sfbSpreadedEnergy + sfbGrp;

+         psfbSpreadEn = psyOutChan->sfbSpreadedEnergy + sfbGrp;
 		 for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-			*psfbSpreadEn = *psfbSpreadEn >> 1;  /* 0.5 */

+			*psfbSpreadEn = *psfbSpreadEn >> 1;  /* 0.5 */
 			++psfbSpreadEn;
         }
       }
     }
     else {
-      for(sfbGrp = 0;sfbGrp < psyOutChan->sfbCnt;sfbGrp+= psyOutChan->sfbPerGroup){

+      for(sfbGrp = 0;sfbGrp < psyOutChan->sfbCnt;sfbGrp+= psyOutChan->sfbPerGroup){
 		psfbSpreadEn = psyOutChan->sfbSpreadedEnergy + sfbGrp;
         for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-          *psfbSpreadEn = (*psfbSpreadEn >> 1) + (*psfbSpreadEn >> 3);  /* 0.63 */

+          *psfbSpreadEn = (*psfbSpreadEn >> 1) + (*psfbSpreadEn >> 3);  /* 0.63 */
 		  ++psfbSpreadEn;
         }
       }
@@ -194,55 +194,55 @@
   if (ahParam->modifyMinSnr) {
     for(ch=0; ch<nChannels; ch++) {
       PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
-         
+
       if (psyOutChan->windowSequence != SHORT_WINDOW)
         threshold = HOLE_THR_LONG;
       else
         threshold = HOLE_THR_SHORT;
 
       for(sfbGrp = 0;sfbGrp < psyOutChan->sfbCnt;sfbGrp+= psyOutChan->sfbPerGroup){
-        Word16 *psfbMinSnr = psyOutChan->sfbMinSnr + sfbGrp;

+        Word16 *psfbMinSnr = psyOutChan->sfbMinSnr + sfbGrp;
 		for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
           Word32 sfbEn, sfbEnm1, sfbEnp1, avgEn;
-             
+
           if (sfb > 0)
             sfbEnm1 = psyOutChan->sfbEnergy[sfbGrp+sfb-1];
           else
             sfbEnm1 = psyOutChan->sfbEnergy[sfbGrp];
-             
+
           if (sfb < (psyOutChan->maxSfbPerGroup-1))
             sfbEnp1 = psyOutChan->sfbEnergy[sfbGrp+sfb+1];
           else
             sfbEnp1 = psyOutChan->sfbEnergy[sfbGrp+sfb];
           avgEn = (sfbEnm1 + sfbEnp1) >> 1;
-          sfbEn = psyOutChan->sfbEnergy[sfbGrp+sfb];                             
-             
+          sfbEn = psyOutChan->sfbEnergy[sfbGrp+sfb];
+
           if (sfbEn > avgEn && avgEn > 0) {
             Word32 tmpMinSnr;
-            shift = norm_l(sfbEn);

+            shift = norm_l(sfbEn);
 			tmpMinSnr = Div_32(L_mpy_ls(avgEn, minSnrLimit) << shift, sfbEn << shift );
-            tmpMinSnr = max(tmpMinSnr, HOLE_THR_LONG);                  
+            tmpMinSnr = max(tmpMinSnr, HOLE_THR_LONG);
             tmpMinSnr = max(tmpMinSnr, threshold);
             *psfbMinSnr = min(*psfbMinSnr, tmpMinSnr);
           }
           /* valley ? */
-             
+
           if ((sfbEn < (avgEn >> 1)) && (sfbEn > 0)) {
             Word32 tmpMinSnr;
-            Word32 minSnrEn = L_mpy_wx(avgEn, *psfbMinSnr);                 
-             
-            if(minSnrEn < sfbEn) {

+            Word32 minSnrEn = L_mpy_wx(avgEn, *psfbMinSnr);
+
+            if(minSnrEn < sfbEn) {
 			  shift = norm_l(sfbEn);
               tmpMinSnr = Div_32( minSnrEn << shift, sfbEn<<shift);
             }
             else {
-              tmpMinSnr = MAX_16;                                             
+              tmpMinSnr = MAX_16;
             }
             tmpMinSnr = min(minSnrLimit, tmpMinSnr);
 
             *psfbMinSnr =
               (min((tmpMinSnr >>  2), mult(*psfbMinSnr, MIN_SNR_COEF)) << 2);
-          }

+          }
 		  psfbMinSnr++;
         }
       }
@@ -251,7 +251,7 @@
 
   /* stereo: adapt the minimum requirements sfbMinSnr of mid and
      side channels */
-   
+
   if (nChannels == 2) {
     PSY_OUT_CHANNEL *psyOutChanM = &psyOutChannel[0];
     PSY_OUT_CHANNEL *psyOutChanS = &psyOutChannel[1];
@@ -260,30 +260,30 @@
         Word32 sfbEnM = psyOutChanM->sfbEnergy[sfb];
         Word32 sfbEnS = psyOutChanS->sfbEnergy[sfb];
         Word32 maxSfbEn = max(sfbEnM, sfbEnS);
-        Word32 maxThr = L_mpy_wx(maxSfbEn, psyOutChanM->sfbMinSnr[sfb]) >> 1;        
-         
+        Word32 maxThr = L_mpy_wx(maxSfbEn, psyOutChanM->sfbMinSnr[sfb]) >> 1;
+
         if(maxThr >= sfbEnM) {
-          psyOutChanM->sfbMinSnr[sfb] = MAX_16;                                          
+          psyOutChanM->sfbMinSnr[sfb] = MAX_16;
         }
         else {
-          shift = norm_l(sfbEnM); 

-		  psyOutChanM->sfbMinSnr[sfb] = min(max(psyOutChanM->sfbMinSnr[sfb], 

+          shift = norm_l(sfbEnM);
+		  psyOutChanM->sfbMinSnr[sfb] = min(max(psyOutChanM->sfbMinSnr[sfb],
 			  round16(Div_32(maxThr<<shift, sfbEnM << shift))), minSnrLimit);
         }
-         
+
         if(maxThr >= sfbEnS) {
           psyOutChanS->sfbMinSnr[sfb] = MAX_16;
         }
-        else {

+        else {
 		  shift = norm_l(sfbEnS);
-          psyOutChanS->sfbMinSnr[sfb] = min(max(psyOutChanS->sfbMinSnr[sfb], 

+          psyOutChanS->sfbMinSnr[sfb] = min(max(psyOutChanS->sfbMinSnr[sfb],
 			  round16(Div_32(maxThr << shift, sfbEnS << shift))), minSnrLimit);
         }
 
-         
+
         if (sfbEnM > psyOutChanM->sfbSpreadedEnergy[sfb])
           psyOutChanS->sfbSpreadedEnergy[sfb] = L_mpy_ls(sfbEnS, MS_THRSPREAD_COEF);
-         
+
         if (sfbEnS > psyOutChanS->sfbSpreadedEnergy[sfb])
           psyOutChanM->sfbSpreadedEnergy[sfb] = L_mpy_ls(sfbEnM, MS_THRSPREAD_COEF);
       }
@@ -295,9 +295,9 @@
   for(ch=0; ch<nChannels; ch++) {
     PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
     for(sfbGrp = 0;sfbGrp < psyOutChan->sfbCnt;sfbGrp+= psyOutChan->sfbPerGroup){
-      Word16 *pahFlag = ahFlag[ch] + sfbGrp;

+      Word16 *pahFlag = ahFlag[ch] + sfbGrp;
 	  for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-               
+
         if ((psyOutChan->sfbSpreadedEnergy[sfbGrp+sfb] > psyOutChan->sfbEnergy[sfbGrp+sfb]) ||
             (psyOutChan->sfbEnergy[sfbGrp+sfb] <= psyOutChan->sfbThreshold[sfbGrp+sfb]) ||
             (psyOutChan->sfbMinSnr[sfbGrp+sfb] == MAX_16)) {
@@ -308,7 +308,7 @@
         }
       }
       for (sfb=psyOutChan->maxSfbPerGroup; sfb<psyOutChan->sfbPerGroup; sfb++) {
-        *pahFlag++ = NO_AH;                                                          
+        *pahFlag++ = NO_AH;
       }
     }
   }
@@ -328,18 +328,18 @@
                        PSY_OUT_CHANNEL  psyOutChannel[MAX_CHANNELS],
                        const Word16     nChannels)
 {
-  Word16 ch, sfb, sfbGrp;

+  Word16 ch, sfb, sfbGrp;
   int ipe, iconstPart, inActiveLines;
 
-  ipe = 0;                                                       
-  iconstPart = 0;                                                
-  inActiveLines = 0;                                             
+  ipe = 0;
+  iconstPart = 0;
+  inActiveLines = 0;
   for(ch=0; ch<nChannels; ch++) {
     PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
     PE_CHANNEL_DATA *peChanData = &peData->peChannelData[ch];
     for(sfbGrp = 0;sfbGrp < psyOutChan->sfbCnt;sfbGrp+= psyOutChan->sfbPerGroup){
       for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-         
+
         if (ahFlag[ch][sfbGrp+sfb] < AH_ACTIVE) {
           ipe = ipe + peChanData->sfbPe[sfbGrp+sfb];
           iconstPart = iconstPart + peChanData->sfbConstPart[sfbGrp+sfb];
@@ -347,11 +347,11 @@
         }
       }
     }
-  }

+  }
 
-  *pe = saturate(ipe);                                                       
-  *constPart = saturate(iconstPart);                                                
-  *nActiveLines = saturate(inActiveLines);  
+  *pe = saturate(ipe);
+  *constPart = saturate(iconstPart);
+  *nActiveLines = saturate(inActiveLines);
 }
 
 /********************************************************************************
@@ -367,16 +367,16 @@
                              const Word32     redVal)
 {
   Word32 sfbThrReduced;
-  Word32 *psfbEn, *psfbThr;     

-  Word16 ch, sfb, sfbGrp;

+  Word32 *psfbEn, *psfbThr;
+  Word16 ch, sfb, sfbGrp;
 
   for(ch=0; ch<nChannels; ch++) {
     PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
     for(sfbGrp=0; sfbGrp<psyOutChan->sfbCnt; sfbGrp+=psyOutChan->sfbPerGroup) {
- 	  psfbEn  = psyOutChan->sfbEnergy + sfbGrp;                                      

-      psfbThr = psyOutChan->sfbThreshold + sfbGrp;

+ 	  psfbEn  = psyOutChan->sfbEnergy + sfbGrp;
+      psfbThr = psyOutChan->sfbThreshold + sfbGrp;
 	  for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-         
+
         if (*psfbEn > *psfbThr) {
           /* threshold reduction formula */
           Word32 tmp = thrExp[ch][sfbGrp+sfb] + redVal;
@@ -384,15 +384,15 @@
           sfbThrReduced = fixmul(tmp, tmp);
           /* avoid holes */
           tmp = L_mpy_ls(*psfbEn, psyOutChan->sfbMinSnr[sfbGrp+sfb]);
-             
-          if ((sfbThrReduced > tmp) && 
+
+          if ((sfbThrReduced > tmp) &&
               (ahFlag[ch][sfbGrp+sfb] != NO_AH)){
             sfbThrReduced = max(tmp, *psfbThr);
-            ahFlag[ch][sfbGrp+sfb] = AH_ACTIVE;                                          
+            ahFlag[ch][sfbGrp+sfb] = AH_ACTIVE;
           }
 		  *psfbThr = sfbThrReduced;
-        }

-

+        }
+
 		psfbEn++;  psfbThr++;
       }
     }
@@ -419,52 +419,52 @@
   PSY_OUT_CHANNEL *psyOutChan;
   PE_CHANNEL_DATA *peChanData;
   Word32 deltaSfbPe;
-  Word32 normFactor;

-  Word32 *psfbPeFactors;

+  Word32 normFactor;
+  Word32 *psfbPeFactors;
   Word16 *psfbNActiveLines, *pahFlag;
   Word32 sfbEn, sfbThr;
   Word32 sfbThrReduced;
 
   /* for each sfb calc relative factors for pe changes */
-  normFactor = 1;                                                                        
+  normFactor = 1;
   for(ch=0; ch<nChannels; ch++) {
     psyOutChan = &psyOutChannel[ch];
     peChanData = &peData->peChannelData[ch];
     for(sfbGrp = 0;sfbGrp < psyOutChan->sfbCnt;sfbGrp+= psyOutChan->sfbPerGroup){
-      psfbPeFactors = peData->sfbPeFactors[ch] + sfbGrp;

-	  psfbNActiveLines = peChanData->sfbNActiveLines + sfbGrp;

-	  pahFlag = ahFlag[ch] + sfbGrp;

+      psfbPeFactors = peData->sfbPeFactors[ch] + sfbGrp;
+	  psfbNActiveLines = peChanData->sfbNActiveLines + sfbGrp;
+	  pahFlag = ahFlag[ch] + sfbGrp;
 	  for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
         Word32 redThrExp = thrExp[ch][sfbGrp+sfb] + redVal;
-             
+
         if (((*pahFlag < AH_ACTIVE) || (deltaPe > 0)) && (redThrExp > 0) ) {
-            
+
           *psfbPeFactors = (*psfbNActiveLines) * (0x7fffffff / redThrExp);
           normFactor = L_add(normFactor, *psfbPeFactors);
         }
         else {
-          *psfbPeFactors = 0;                                              
-        }

-		psfbPeFactors++; 

+          *psfbPeFactors = 0;
+        }
+		psfbPeFactors++;
 		pahFlag++; psfbNActiveLines++;
       }
     }
   }
 
- 
+
   /* calculate new thresholds */
   for(ch=0; ch<nChannels; ch++) {
     psyOutChan = &psyOutChannel[ch];
     peChanData = &peData->peChannelData[ch];
     for(sfbGrp = 0;sfbGrp < psyOutChan->sfbCnt;sfbGrp+= psyOutChan->sfbPerGroup){
-      psfbPeFactors = peData->sfbPeFactors[ch] + sfbGrp;

-	  psfbNActiveLines = peChanData->sfbNActiveLines + sfbGrp;

-	  pahFlag = ahFlag[ch] + sfbGrp;

+      psfbPeFactors = peData->sfbPeFactors[ch] + sfbGrp;
+	  psfbNActiveLines = peChanData->sfbNActiveLines + sfbGrp;
+	  pahFlag = ahFlag[ch] + sfbGrp;
 	  for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
         /* pe difference for this sfb */
         deltaSfbPe = *psfbPeFactors * deltaPe;
 
-		/* thr3(n) = thr2(n)*2^deltaSfbPe/b(n) */         
+		/* thr3(n) = thr2(n)*2^deltaSfbPe/b(n) */
         if (*psfbNActiveLines > 0) {
           /* new threshold */
           Word32 thrFactor;
@@ -476,7 +476,7 @@
               reduce threshold
             */
             thrFactor = pow2_xy(L_negate(deltaSfbPe), (normFactor* (*psfbNActiveLines)));
-              
+
             sfbThrReduced = L_mpy_ls(sfbThr, round16(thrFactor));
           }
           else {
@@ -484,30 +484,30 @@
               increase threshold
             */
             thrFactor = pow2_xy(deltaSfbPe, (normFactor * (*psfbNActiveLines)));
-              
-             
+
+
             if(thrFactor > sfbThr) {
-              shift = norm_l(thrFactor);

+              shift = norm_l(thrFactor);
 			  sfbThrReduced = Div_32( sfbThr << shift, thrFactor<<shift );
             }
             else {
-              sfbThrReduced = MAX_32;                                                                            
+              sfbThrReduced = MAX_32;
             }
 
           }
-            
+
           /* avoid hole */
           sfbEn = L_mpy_ls(sfbEn, psyOutChan->sfbMinSnr[sfbGrp+sfb]);
-             
+
           if ((sfbThrReduced > sfbEn) &&
               (*pahFlag == AH_INACTIVE)) {
             sfbThrReduced = max(sfbEn, sfbThr);
-            *pahFlag = AH_ACTIVE;                                                                  
+            *pahFlag = AH_ACTIVE;
           }
 
-          psyOutChan->sfbThreshold[sfbGrp+sfb] = sfbThrReduced;  
-        }

-

+          psyOutChan->sfbThreshold[sfbGrp+sfb] = sfbThrReduced;
+        }
+
 		pahFlag++; psfbNActiveLines++; psfbPeFactors++;
       }
     }
@@ -521,8 +521,8 @@
 * description: if the desired pe can not be reached, reduce pe by reducing minSnr
 *
 **********************************************************************************/
-static void reduceMinSnr(PSY_OUT_CHANNEL  psyOutChannel[MAX_CHANNELS], 
-                         PE_DATA         *peData, 
+static void reduceMinSnr(PSY_OUT_CHANNEL  psyOutChannel[MAX_CHANNELS],
+                         PE_DATA         *peData,
                          Word16           ahFlag[MAX_CHANNELS][MAX_GROUPED_SFB],
                          const Word16     nChannels,
                          const Word16     desiredPe)
@@ -531,20 +531,20 @@
   Word16 deltaPe;
 
   /* start at highest freq down to 0 */
-  sfbSubWin = psyOutChannel[0].maxSfbPerGroup;                                                 
+  sfbSubWin = psyOutChannel[0].maxSfbPerGroup;
   while (peData->pe > desiredPe && sfbSubWin > 0) {
-       
+
     sfbSubWin = sfbSubWin - 1;
     /* loop over all subwindows */
     for (sfb=sfbSubWin; sfb<psyOutChannel[0].sfbCnt;
         sfb+=psyOutChannel[0].sfbPerGroup) {
       /* loop over all channels */
-		PE_CHANNEL_DATA* peChan = peData->peChannelData;

-		PSY_OUT_CHANNEL* psyOutCh = psyOutChannel;

-		for (ch=0; ch<nChannels; ch++) {           
+		PE_CHANNEL_DATA* peChan = peData->peChannelData;
+		PSY_OUT_CHANNEL* psyOutCh = psyOutChannel;
+		for (ch=0; ch<nChannels; ch++) {
         if (ahFlag[ch][sfb] != NO_AH &&
             psyOutCh->sfbMinSnr[sfb] < minSnrLimit) {
-          psyOutCh->sfbMinSnr[sfb] = minSnrLimit;                                      
+          psyOutCh->sfbMinSnr[sfb] = minSnrLimit;
           psyOutCh->sfbThreshold[sfb] =
             L_mpy_ls(psyOutCh->sfbEnergy[sfb], psyOutCh->sfbMinSnr[sfb]);
 
@@ -552,12 +552,12 @@
           deltaPe = ((peChan->sfbNLines4[sfb] + (peChan->sfbNLines4[sfb] >> 1)) >> 2) -
               peChan->sfbPe[sfb];
           peData->pe = peData->pe + deltaPe;
-          peChan->pe = peChan->pe + deltaPe;		  
-        }

+          peChan->pe = peChan->pe + deltaPe;
+        }
 		peChan += 1; psyOutCh += 1;
       }
       /* stop if enough has been saved */
-       
+
       if (peData->pe <= desiredPe)
         break;
     }
@@ -567,13 +567,13 @@
 /********************************************************************************
 *
 * function name:allowMoreHoles
-* description: if the desired pe can not be reached, some more scalefactor bands  
+* description: if the desired pe can not be reached, some more scalefactor bands
 *              have to be quantized to zero
 *
 **********************************************************************************/
-static void allowMoreHoles(PSY_OUT_CHANNEL  psyOutChannel[MAX_CHANNELS], 
+static void allowMoreHoles(PSY_OUT_CHANNEL  psyOutChannel[MAX_CHANNELS],
                            PSY_OUT_ELEMENT *psyOutElement,
-                           PE_DATA         *peData, 
+                           PE_DATA         *peData,
                            Word16           ahFlag[MAX_CHANNELS][MAX_GROUPED_SFB],
                            const AH_PARAM  *ahParam,
                            const Word16     nChannels,
@@ -582,46 +582,46 @@
   Word16 ch, sfb;
   Word16 actPe, shift;
 
-  actPe = peData->pe;                                                                    
+  actPe = peData->pe;
 
   /* for MS allow hole in the channel with less energy */
-     
+
   if (nChannels==2 &&
       psyOutChannel[0].windowSequence==psyOutChannel[1].windowSequence) {
     PSY_OUT_CHANNEL *psyOutChanL = &psyOutChannel[0];
     PSY_OUT_CHANNEL *psyOutChanR = &psyOutChannel[1];
     for (sfb=0; sfb<psyOutChanL->sfbCnt; sfb++) {
       Word32 minEn;
-       
+
       if (psyOutElement->toolsInfo.msMask[sfb]) {
         /* allow hole in side channel ? */
         minEn = L_mpy_ls(psyOutChanL->sfbEnergy[sfb], (minSnrLimit * psyOutChanL->sfbMinSnr[sfb]) >> 16);
-           
+
         if (ahFlag[1][sfb] != NO_AH &&
             minEn > psyOutChanR->sfbEnergy[sfb]) {
-          ahFlag[1][sfb] = NO_AH;                                                                
+          ahFlag[1][sfb] = NO_AH;
           psyOutChanR->sfbThreshold[sfb] = L_add(psyOutChanR->sfbEnergy[sfb], psyOutChanR->sfbEnergy[sfb]);
           actPe = actPe - peData->peChannelData[1].sfbPe[sfb];
         }
         /* allow hole in mid channel ? */
         else {
         minEn = L_mpy_ls(psyOutChanR->sfbEnergy[sfb], (minSnrLimit * psyOutChanR->sfbMinSnr[sfb]) >> 16);
-             
+
           if (ahFlag[0][sfb]!= NO_AH &&
               minEn > psyOutChanL->sfbEnergy[sfb]) {
-            ahFlag[0][sfb] = NO_AH;                                                              
+            ahFlag[0][sfb] = NO_AH;
             psyOutChanL->sfbThreshold[sfb] = L_add(psyOutChanL->sfbEnergy[sfb], psyOutChanL->sfbEnergy[sfb]);
             actPe = actPe - peData->peChannelData[0].sfbPe[sfb];
           }
         }
-         
+
         if (actPe < desiredPe)
           break;
       }
     }
   }
 
-  /* subsequently erase bands */   
+  /* subsequently erase bands */
   if (actPe > desiredPe) {
     Word16 startSfb[2];
     Word32 avgEn, minEn;
@@ -634,20 +634,20 @@
 
     /* do not go below startSfb */
     for (ch=0; ch<nChannels; ch++) {
-         
+
       if (psyOutChannel[ch].windowSequence != SHORT_WINDOW)
         startSfb[ch] = ahParam->startSfbL;
       else
         startSfb[ch] = ahParam->startSfbS;
     }
 
-    avgEn = 0;                                                           
-    minEn = MAX_32;                                                      
-    ahCnt = 0;                                                           
+    avgEn = 0;
+    minEn = MAX_32;
+    ahCnt = 0;
     for (ch=0; ch<nChannels; ch++) {
       PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
       for (sfb=startSfb[ch]; sfb<psyOutChan->sfbCnt; sfb++) {
-           
+
         if ((ahFlag[ch][sfb] != NO_AH) &&
             (psyOutChan->sfbEnergy[sfb] > psyOutChan->sfbThreshold[sfb])) {
           minEn = min(minEn, psyOutChan->sfbEnergy[sfb]);
@@ -656,10 +656,10 @@
         }
       }
     }
-     
+
     if(ahCnt) {
       Word32 iahCnt;
-      shift = norm_l(ahCnt);

+      shift = norm_l(ahCnt);
 	  iahCnt = Div_32( 1 << shift, ahCnt << shift );
       avgEn = fixmul(avgEn, iahCnt);
     }
@@ -674,46 +674,46 @@
 
     /* start with lowest energy border at highest sfb */
     maxSfb = psyOutChannel[0].sfbCnt - 1;
-    minSfb = startSfb[0];                                                                
-     
+    minSfb = startSfb[0];
+
     if (nChannels == 2) {
       maxSfb = max(maxSfb, (psyOutChannel[1].sfbCnt - 1));
       minSfb = min(minSfb, startSfb[1]);
     }
 
-    sfb = maxSfb;                                                                        
-    enIdx = 0;                                                                           
-    done = 0;                                                                            
+    sfb = maxSfb;
+    enIdx = 0;
+    done = 0;
     while (!done) {
-       
+
       for (ch=0; ch<nChannels; ch++) {
         PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
-           
+
         if (sfb>=startSfb[ch] && sfb<psyOutChan->sfbCnt) {
           /* sfb energy below border ? */
-             
+
           if (ahFlag[ch][sfb] != NO_AH && psyOutChan->sfbEnergy[sfb] < en[enIdx]){
             /* allow hole */
-            ahFlag[ch][sfb] = NO_AH;                                                     
+            ahFlag[ch][sfb] = NO_AH;
             psyOutChan->sfbThreshold[sfb] = L_add(psyOutChan->sfbEnergy[sfb], psyOutChan->sfbEnergy[sfb]);
             actPe = actPe - peData->peChannelData[ch].sfbPe[sfb];
           }
-           
+
           if (actPe < desiredPe) {
-            done = 1;                                                                    
+            done = 1;
             break;
           }
         }
       }
       sfb = sfb - 1;
-       
+
       if (sfb < minSfb) {
         /* restart with next energy border */
-        sfb = maxSfb;                                                                    
+        sfb = maxSfb;
         enIdx = enIdx + 1;
-         
+
         if (enIdx - 4 >= 0)
-          done = 1;                                                                      
+          done = 1;
       }
     }
   }
@@ -748,13 +748,13 @@
 
   initAvoidHoleFlag(peData->ahFlag, psyOutChannel, psyOutElement, nChannels, ahParam);
 
-  noRedPe = peData->pe;                                                          
-  constPart = peData->constPart;                                                 
-  nActiveLines = peData->nActiveLines;       
+  noRedPe = peData->pe;
+  constPart = peData->constPart;
+  nActiveLines = peData->nActiveLines;
 
   /* first guess of reduction value t^0.25 = 2^((a-pen)/4*b) */
   avgThrExp = pow2_xy((constPart - noRedPe), (nActiveLines << 2));
-  
+
   /* r1 = 2^((a-per)/4*b) - t^0.25 */
   redVal = pow2_xy((constPart - desiredPe), (nActiveLines << 2)) - avgThrExp;
 
@@ -763,40 +763,40 @@
 
   /* pe after first guess */
   calcSfbPe(peData, psyOutChannel, nChannels);
-  redPe = peData->pe;                                                            
+  redPe = peData->pe;
 
-  iter = 0;                                                                      
+  iter = 0;
   do {
     /* pe for bands where avoid hole is inactive */
     calcPeNoAH(&redPeNoAH, &constPartNoAH, &nActiveLinesNoAH,
                peData, peData->ahFlag, psyOutChannel, nChannels);
 
     desiredPeNoAH = desiredPe -(redPe - redPeNoAH);
-     
+
     if (desiredPeNoAH < 0) {
-      desiredPeNoAH = 0;                                                         
+      desiredPeNoAH = 0;
     }
 
     /* second guess */
-     
+
     if (nActiveLinesNoAH > 0) {
-		
+
 		avgThrExp = pow2_xy((constPartNoAH - redPeNoAH), (nActiveLinesNoAH << 2));
-		
+
 		redVal = (redVal + pow2_xy((constPartNoAH - desiredPeNoAH), (nActiveLinesNoAH << 2))) - avgThrExp;
-		
+
 		/* reduce thresholds */
 		reduceThresholds(psyOutChannel, peData->ahFlag, peData->thrExp, nChannels, redVal);
     }
 
     calcSfbPe(peData, psyOutChannel, nChannels);
-    redPe = peData->pe;                                                          
+    redPe = peData->pe;
 
     iter = iter+1;
-       
+
   } while ((20 * abs_s(redPe - desiredPe) > desiredPe) && (iter < 2));
 
-   
+
   if ((100 * redPe < 115 * desiredPe)) {
     correctThresh(psyOutChannel, peData->ahFlag, peData, peData->thrExp, redVal,
                   nChannels, desiredPe - redPe);
@@ -831,7 +831,7 @@
   fillLevel = max(fillLevel, clipLow);
   fillLevel = min(fillLevel, clipHigh);
 
-  if(clipHigh-clipLow)

+  if(clipHigh-clipLow)
   bitsave = (maxBitSave - (((maxBitSave-minBitSave)*(fillLevel-clipLow))/
                               (clipHigh-clipLow)));
 
@@ -860,10 +860,10 @@
   fillLevel = max(fillLevel, clipLow);
   fillLevel = min(fillLevel, clipHigh);
 
-  if(clipHigh-clipLow)

+  if(clipHigh-clipLow)
   bitspend = (minBitSpend + ((maxBitSpend - minBitSpend)*(fillLevel - clipLow) /
                                 (clipHigh-clipLow)));
-                            
+
   return (bitspend);
 }
 
@@ -884,19 +884,19 @@
   Word16 minFacHi, maxFacHi, minFacLo, maxFacLo;
   Word16 diff;
   Word16 minDiff = extract_l(currPe / 6);
-  minFacHi = 30;                                                         
-  maxFacHi = 100;                                                        
-  minFacLo = 14;                                                         
-  maxFacLo = 7;                                                          
+  minFacHi = 30;
+  maxFacHi = 100;
+  minFacLo = 14;
+  maxFacLo = 7;
 
   diff = currPe - *peMax ;
-   
+
   if (diff > 0) {
     *peMin = *peMin + ((diff * minFacHi) / 100);
     *peMax = *peMax + ((diff * maxFacHi) / 100);
   } else {
     diff = *peMin - currPe;
-     
+
     if (diff > 0) {
       *peMin = *peMin - ((diff * minFacLo) / 100);
       *peMax = *peMax - ((diff * maxFacLo) / 100);
@@ -906,7 +906,7 @@
     }
   }
 
-   
+
   if ((*peMax - *peMin) < minDiff) {
     Word16 partLo, partHi;
 
@@ -964,12 +964,12 @@
                           bresParam->clipSpendLow, bresParam->clipSpendHigh,
                           bresParam->minBitSpend, bresParam->maxBitSpend);
 
-  if(adjThrChan->peMax != adjThrChan->peMin)

+  if(adjThrChan->peMax != adjThrChan->peMin)
 	bitresFac = (100 - bitSave) + extract_l(((bitSpend + bitSave) * (pex - adjThrChan->peMin)) /
                     (adjThrChan->peMax - adjThrChan->peMin));
   else
 	bitresFac = 0x7fff;
-               
+
   bitresFac = min(bitresFac,
                     (100-30 + extract_l((100 * bitresBits) / avgBits)));
 
@@ -995,23 +995,23 @@
 
   /* common for all elements: */
   /* parameters for bitres control */
-  hAdjThr->bresParamLong.clipSaveLow   =  20;                    
-  hAdjThr->bresParamLong.clipSaveHigh  =  95;                    
-  hAdjThr->bresParamLong.minBitSave    =  -5;                    
-  hAdjThr->bresParamLong.maxBitSave    =  30;                    
-  hAdjThr->bresParamLong.clipSpendLow  =  20;                    
-  hAdjThr->bresParamLong.clipSpendHigh =  95;                    
-  hAdjThr->bresParamLong.minBitSpend   = -10;                    
-  hAdjThr->bresParamLong.maxBitSpend   =  40;                    
+  hAdjThr->bresParamLong.clipSaveLow   =  20;
+  hAdjThr->bresParamLong.clipSaveHigh  =  95;
+  hAdjThr->bresParamLong.minBitSave    =  -5;
+  hAdjThr->bresParamLong.maxBitSave    =  30;
+  hAdjThr->bresParamLong.clipSpendLow  =  20;
+  hAdjThr->bresParamLong.clipSpendHigh =  95;
+  hAdjThr->bresParamLong.minBitSpend   = -10;
+  hAdjThr->bresParamLong.maxBitSpend   =  40;
 
-  hAdjThr->bresParamShort.clipSaveLow   =  20;                   
-  hAdjThr->bresParamShort.clipSaveHigh  =  75;                   
-  hAdjThr->bresParamShort.minBitSave    =   0;                   
-  hAdjThr->bresParamShort.maxBitSave    =  20;                   
-  hAdjThr->bresParamShort.clipSpendLow  =  20;                   
-  hAdjThr->bresParamShort.clipSpendHigh =  75;                   
-  hAdjThr->bresParamShort.minBitSpend   = -5;                    
-  hAdjThr->bresParamShort.maxBitSpend   =  50;                   
+  hAdjThr->bresParamShort.clipSaveLow   =  20;
+  hAdjThr->bresParamShort.clipSaveHigh  =  75;
+  hAdjThr->bresParamShort.minBitSave    =   0;
+  hAdjThr->bresParamShort.maxBitSave    =  20;
+  hAdjThr->bresParamShort.clipSpendLow  =  20;
+  hAdjThr->bresParamShort.clipSpendHigh =  75;
+  hAdjThr->bresParamShort.minBitSpend   = -5;
+  hAdjThr->bresParamShort.maxBitSpend   =  50;
 
   /* specific for each element: */
 
@@ -1020,7 +1020,7 @@
   atsElem->peMax = extract_l(((120*meanPe) / 100));
 
   /* additional pe offset to correct pe2bits for low bitrates */
-  atsElem->peOffset = 0;                             
+  atsElem->peOffset = 0;
   if (chBitrate < 32000) {
     atsElem->peOffset = max(50, (100 - extract_l((100 * chBitrate) / 32000)));
   }
@@ -1039,24 +1039,24 @@
 
   /* minSnr adaptation */
   /* maximum reduction of minSnr goes down to minSnr^maxRed */
-  msaParam->maxRed = 0x20000000;     /* *0.25f /                        
+  msaParam->maxRed = 0x20000000;     /* *0.25f /
   /* start adaptation of minSnr for avgEn/sfbEn > startRatio */
-  msaParam->startRatio = 0x0ccccccd; /* 10 */                        
+  msaParam->startRatio = 0x0ccccccd; /* 10 */
   /* maximum minSnr reduction to minSnr^maxRed is reached for
      avgEn/sfbEn >= maxRatio */
-  msaParam->maxRatio =  0x0020c49c; /* 1000 */                         
+  msaParam->maxRatio =  0x0020c49c; /* 1000 */
   /* helper variables to interpolate minSnr reduction for
      avgEn/sfbEn between startRatio and maxRatio */
 
-  msaParam->redRatioFac = 0xfb333333; /* -0.75/20 */         
+  msaParam->redRatioFac = 0xfb333333; /* -0.75/20 */
 
-  msaParam->redOffs = 0x30000000;  /* msaParam->redRatioFac * 10*log10(msaParam->startRatio) */  
+  msaParam->redOffs = 0x30000000;  /* msaParam->redRatioFac * 10*log10(msaParam->startRatio) */
 
-       
+
   /* pe correction */
-  atsElem->peLast = 0;                                                 
-  atsElem->dynBitsLast = 0;                                            
-  atsElem->peCorrectionFactor = 100; /* 1.0 */                         
+  atsElem->peLast = 0;
+  atsElem->dynBitsLast = 0;
+  atsElem->peCorrectionFactor = 100; /* 1.0 */
 
 }
 
@@ -1069,20 +1069,20 @@
 *****************************************************************************/
 static void calcPeCorrection(Word16 *correctionFac,
                              const Word16 peAct,
-                             const Word16 peLast, 
-                             const Word16 bitsLast) 
+                             const Word16 peLast,
+                             const Word16 bitsLast)
 {
   Word32 peAct100 = 100 * peAct;
   Word32 peLast100 = 100 * peLast;
   Word16 peBitsLast = bits2pe(bitsLast);
-           
+
   if ((bitsLast > 0) &&
       (peAct100 < (150 * peLast)) &&  (peAct100 > (70 * peLast)) &&
       ((120 * peBitsLast) > peLast100 ) && (( 65 * peBitsLast) < peLast100))
     {
       Word16 newFac = (100 * peLast) / peBitsLast;
       /* dead zone */
-       
+
       if (newFac < 100) {
         newFac = min(((110 * newFac) / 100), 100);
         newFac = max(newFac, 85);
@@ -1091,13 +1091,13 @@
         newFac = max(((90 * newFac) / 100), 100);
         newFac = min(newFac, 115);
       }
-         
+
       if ((newFac > 100 && *correctionFac < 100) ||
           (newFac < 100 && *correctionFac > 100)) {
-        *correctionFac = 100;                                                    
+        *correctionFac = 100;
       }
       /* faster adaptation towards 1.0, slower in the other direction */
-             
+
       if ((*correctionFac < 100 && newFac < *correctionFac) ||
           (*correctionFac > 100 && newFac > *correctionFac))
         *correctionFac = (85 * *correctionFac + 15 * newFac) / 100;
@@ -1107,7 +1107,7 @@
       *correctionFac = max(*correctionFac, 85);
     }
   else {
-    *correctionFac = 100;                                                        
+    *correctionFac = 100;
   }
 }
 
@@ -1123,40 +1123,40 @@
                       PSY_OUT_ELEMENT *psyOutElement,
                       Word16          *chBitDistribution,
                       Word16           logSfbEnergy[MAX_CHANNELS][MAX_GROUPED_SFB],
-                      Word16           sfbNRelevantLines[MAX_CHANNELS][MAX_GROUPED_SFB],                      
+                      Word16           sfbNRelevantLines[MAX_CHANNELS][MAX_GROUPED_SFB],
                       QC_OUT_ELEMENT  *qcOE,
 					  ELEMENT_BITS	  *elBits,
 					  const Word16     nChannels,
                       const Word16     maxBitFac)
 {
-  PE_DATA peData;  
+  PE_DATA peData;
   Word16 noRedPe, grantedPe, grantedPeCorr;
   Word16 curWindowSequence;
   Word16 bitFactor;
   Word16 avgBits = (elBits->averageBits - (qcOE->staticBitsUsed + qcOE->ancBitsUsed));
-  Word16 bitresBits = elBits->bitResLevel; 
+  Word16 bitresBits = elBits->bitResLevel;
   Word16 maxBitresBits = elBits->maxBits;
   Word16 sideInfoBits = (qcOE->staticBitsUsed + qcOE->ancBitsUsed);
   Word16 ch;
-   
+
   prepareSfbPe(&peData, psyOutChannel, logSfbEnergy, sfbNRelevantLines, nChannels, AdjThrStateElement->peOffset);
-   
+
   /* pe without reduction */
   calcSfbPe(&peData, psyOutChannel, nChannels);
-  noRedPe = peData.pe;                                                   
+  noRedPe = peData.pe;
 
 
-  curWindowSequence = LONG_WINDOW;                                       
-   
+  curWindowSequence = LONG_WINDOW;
+
   if (nChannels == 2) {
-       
+
     if ((psyOutChannel[0].windowSequence == SHORT_WINDOW) ||
         (psyOutChannel[1].windowSequence == SHORT_WINDOW)) {
-      curWindowSequence = SHORT_WINDOW;                                  
+      curWindowSequence = SHORT_WINDOW;
     }
   }
   else {
-    curWindowSequence = psyOutChannel[0].windowSequence;                 
+    curWindowSequence = psyOutChannel[0].windowSequence;
   }
 
 
@@ -1170,13 +1170,13 @@
   grantedPe = ((bitFactor * bits2pe(avgBits)) / 100);
 
   /* correction of pe value */
-  calcPeCorrection(&(AdjThrStateElement->peCorrectionFactor), 
+  calcPeCorrection(&(AdjThrStateElement->peCorrectionFactor),
                    min(grantedPe, noRedPe),
-                   AdjThrStateElement->peLast, 
+                   AdjThrStateElement->peLast,
                    AdjThrStateElement->dynBitsLast);
   grantedPeCorr = (grantedPe * AdjThrStateElement->peCorrectionFactor) / 100;
 
-     
+
   if (grantedPeCorr < noRedPe && noRedPe > peData.offset) {
     /* calc threshold necessary for desired pe */
     adaptThresholdsToPe(psyOutChannel,
@@ -1192,20 +1192,20 @@
   /* calculate relative distribution */
   for (ch=0; ch<nChannels; ch++) {
     Word16 peOffsDiff = peData.pe - peData.offset;
-    chBitDistribution[ch] = 200;                                                 
-     
+    chBitDistribution[ch] = 200;
+
     if (peOffsDiff > 0) {
       Word32 temp = 1000 - (nChannels * 200);
-      chBitDistribution[ch] = chBitDistribution[ch] +

+      chBitDistribution[ch] = chBitDistribution[ch] +
 		  (temp * peData.peChannelData[ch].pe) / peOffsDiff;
     }
   }
 
   /* store pe */
-  qcOE->pe = noRedPe;                                                            
+  qcOE->pe = noRedPe;
 
   /* update last pe */
-  AdjThrStateElement->peLast = grantedPe;                                        
+  AdjThrStateElement->peLast = grantedPe;
 }
 
 /********************************************************************************
@@ -1217,7 +1217,7 @@
 void AdjThrUpdate(ATS_ELEMENT *AdjThrStateElement,
                   const Word16 dynBitsUsed)
 {
-  AdjThrStateElement->dynBitsLast = dynBitsUsed;                                 
+  AdjThrStateElement->dynBitsLast = dynBitsUsed;
 }
 
 
diff --git a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/AutoCorrelation_v5.s b/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/AutoCorrelation_v5.s
index 48edd4f..e705197 100644
--- a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/AutoCorrelation_v5.s
+++ b/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/AutoCorrelation_v5.s
@@ -1,167 +1,167 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-

-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

-@	File:		AutoCorrelation_v5.s

-@

-@	Content:	AutoCorrelation function armv5 assemble

-@

-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

-

-

-	.section .text	

-	.global	AutoCorrelation

-

-AutoCorrelation:

-	stmdb     sp!, {r4 - r11, lr}

-

-  sub     r13, r13, #20                     

-

-  mov     r5, r0                            

-  mov     r7, r1                            

-  mov     r9, r3                            

-  mov     r2, r2, lsl #16                      

-  mov     r0, #0          

-  mov     r4, r2, asr #16                   

-  mov     r8, #0                            

-  cmp     r4, #0                            

-  ble     L136        

-	

-	cmp     r4, #8 

-	mov		  r2, #0 

-  blt     L133   

-

-	sub     r12, r4, #8                

-L132:  

-  ldr     r6, [r5, r2]  

-	add		  r2, r2, #4

-	smulbb  r3, r6, r6

-	ldr     r1, [r5, r2] 

-	smultt	r10, r6, r6

-	mov		  r3, r3, asr #9

-	smulbb	r6, r1, r1

-	mov		  r10, r10, asr #9

-	qadd	  r0, r0, r3

-	smultt	r11, r1, r1

-	add     r2, r2, #4

-	qadd	  r0, r0, r10

-	mov		  r6, r6, asr #9

-	mov		  r11, r11, asr #9

-	ldr		  r1, [r5, r2]

-	qadd	  r0, r0, r6

-	smulbb	r10, r1, r1

-	smultt	r6, r1, r1

-	qadd	  r0, r0, r11

-	mov		  r10, r10, asr #9

-	mov		  r6, r6, asr #9

-	qadd	  r0, r0, r10

-	add     r2, r2, #4

-	add     r8, r8, #6

-

-	qadd	  r0, r0, r6

-	cmp     r8, r12                            

-  blt     L132	                  

-L133:                         

-  ldrsh   r6, [r5, r2]                      

-  mul     r10, r6, r6   

-	add     r2, r2, #2                     

-  mov     r1, r10, asr #9                    

-  qadd    r0, r0, r1

-L134:                         

-  add     r8, r8, #1                        

-  cmp     r8, r4                            

-  blt     L133                            

-L135:                        

-L136:                         

-  str     r0, [r7, #0]                      

-  cmp     r0, #0                            

-  beq     L1320                           

-L137:                         

-  mov     r2, r9, lsl #16                   

-	mov     r8, #1                                

-  mov     r2, r2, asr #16                   

-  cmp     r2, #1                            

-  ble     L1319                           

-L138:                        

-L139:                         

-  sub     r4, r4, #1                        

-  mov     r14, #0                           

-  mov     r3, #0                            

-  cmp     r4, #0                            

-  ble     L1317                           

-L1310:                       

-  cmp     r4, #6                            

-  addlt   r6, r5, r8, lsl #1                

-  blt     L1314                           

-L1311:                        

-  add     r6, r5, r8, lsl #1                

-  sub     r12, r4, #6                       

-  str     r8, [r13, #8]                     

-  str     r7, [r13, #4]                     

-L1312:                        

-  mov     r1, r3, lsl #1                    

-  ldrsh   r7, [r6, r1]                      

-  ldrsh   r10, [r5, r1]  

-  add     r8, r1, r6 

-	add     r9, r5, r1                       

-	mul     r7, r10, r7

-  ldrsh   r1, [r8, #2] 

-	ldrsh   r10, [r8, #4]   

-  add     r7, r14, r7, asr #9  	                                             

-  ldrsh   r0, [r9, #2]                          

-  ldrsh   r11, [r9, #4]                   

-  mul     r1, r0, r1                        

-  ldrsh   r14, [r8, #6]                     

-  mul     r10, r11, r10          

-	add     r7, r7, r1, asr #9            

-  ldrsh   r8, [r8, #8] 

-	add     r3, r3, #5

-	ldrsh   r11, [r9, #6]                  

-  ldrsh   r1, [r9, #8]                      

-  mul     r14, r11, r14                     

-  add     r7, r7, r10, asr #9       

-  mul     r1, r1, r8                             

-  add     r14, r7, r14, asr #9              

-	cmp     r3, r12 

-  add     r14, r14, r1, asr #9              

-  ble     L1312                           

-L1313:                        

-  ldr     r8, [r13, #8]                     

-  ldr     r7, [r13, #4]                     

-L1314:                        

-L1315:                        

-  mov     r12, r3, lsl #1                   

-  ldrsh   r9, [r6, r12]                     

-  ldrsh   r12, [r5, r12]                    

-  add     r3, r3, #1                        

-  cmp     r3, r4                            

-  mul     r12, r12, r9                      

-  add     r14, r14, r12, asr #9             

-  blt     L1315                           

-L1316:                        

-L1317:                        

-  str     r14, [r7, +r8, lsl #2]            

-  add     r8, r8, #1                        

-  cmp     r8, r2                            

-  blt     L139   

-	                         

-L1319:

-L1320:

-	add     r13, r13, #20                    

-	ldmia   sp!, {r4 - r11, pc}

-

-	@ENDP  @ |AutoCorrelation|

-	.end

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+
+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+@	File:		AutoCorrelation_v5.s
+@
+@	Content:	AutoCorrelation function armv5 assemble
+@
+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+
+
+	.section .text
+	.global	AutoCorrelation
+
+AutoCorrelation:
+	stmdb     sp!, {r4 - r11, lr}
+
+  sub     r13, r13, #20
+
+  mov     r5, r0
+  mov     r7, r1
+  mov     r9, r3
+  mov     r2, r2, lsl #16
+  mov     r0, #0
+  mov     r4, r2, asr #16
+  mov     r8, #0
+  cmp     r4, #0
+  ble     L136
+
+	cmp     r4, #8
+	mov		  r2, #0
+  blt     L133
+
+	sub     r12, r4, #8
+L132:
+  ldr     r6, [r5, r2]
+	add		  r2, r2, #4
+	smulbb  r3, r6, r6
+	ldr     r1, [r5, r2]
+	smultt	r10, r6, r6
+	mov		  r3, r3, asr #9
+	smulbb	r6, r1, r1
+	mov		  r10, r10, asr #9
+	qadd	  r0, r0, r3
+	smultt	r11, r1, r1
+	add     r2, r2, #4
+	qadd	  r0, r0, r10
+	mov		  r6, r6, asr #9
+	mov		  r11, r11, asr #9
+	ldr		  r1, [r5, r2]
+	qadd	  r0, r0, r6
+	smulbb	r10, r1, r1
+	smultt	r6, r1, r1
+	qadd	  r0, r0, r11
+	mov		  r10, r10, asr #9
+	mov		  r6, r6, asr #9
+	qadd	  r0, r0, r10
+	add     r2, r2, #4
+	add     r8, r8, #6
+
+	qadd	  r0, r0, r6
+	cmp     r8, r12
+  blt     L132
+L133:
+  ldrsh   r6, [r5, r2]
+  mul     r10, r6, r6
+	add     r2, r2, #2
+  mov     r1, r10, asr #9
+  qadd    r0, r0, r1
+L134:
+  add     r8, r8, #1
+  cmp     r8, r4
+  blt     L133
+L135:
+L136:
+  str     r0, [r7, #0]
+  cmp     r0, #0
+  beq     L1320
+L137:
+  mov     r2, r9, lsl #16
+	mov     r8, #1
+  mov     r2, r2, asr #16
+  cmp     r2, #1
+  ble     L1319
+L138:
+L139:
+  sub     r4, r4, #1
+  mov     r14, #0
+  mov     r3, #0
+  cmp     r4, #0
+  ble     L1317
+L1310:
+  cmp     r4, #6
+  addlt   r6, r5, r8, lsl #1
+  blt     L1314
+L1311:
+  add     r6, r5, r8, lsl #1
+  sub     r12, r4, #6
+  str     r8, [r13, #8]
+  str     r7, [r13, #4]
+L1312:
+  mov     r1, r3, lsl #1
+  ldrsh   r7, [r6, r1]
+  ldrsh   r10, [r5, r1]
+  add     r8, r1, r6
+	add     r9, r5, r1
+	mul     r7, r10, r7
+  ldrsh   r1, [r8, #2]
+	ldrsh   r10, [r8, #4]
+  add     r7, r14, r7, asr #9
+  ldrsh   r0, [r9, #2]
+  ldrsh   r11, [r9, #4]
+  mul     r1, r0, r1
+  ldrsh   r14, [r8, #6]
+  mul     r10, r11, r10
+	add     r7, r7, r1, asr #9
+  ldrsh   r8, [r8, #8]
+	add     r3, r3, #5
+	ldrsh   r11, [r9, #6]
+  ldrsh   r1, [r9, #8]
+  mul     r14, r11, r14
+  add     r7, r7, r10, asr #9
+  mul     r1, r1, r8
+  add     r14, r7, r14, asr #9
+	cmp     r3, r12
+  add     r14, r14, r1, asr #9
+  ble     L1312
+L1313:
+  ldr     r8, [r13, #8]
+  ldr     r7, [r13, #4]
+L1314:
+L1315:
+  mov     r12, r3, lsl #1
+  ldrsh   r9, [r6, r12]
+  ldrsh   r12, [r5, r12]
+  add     r3, r3, #1
+  cmp     r3, r4
+  mul     r12, r12, r9
+  add     r14, r14, r12, asr #9
+  blt     L1315
+L1316:
+L1317:
+  str     r14, [r7, +r8, lsl #2]
+  add     r8, r8, #1
+  cmp     r8, r2
+  blt     L139
+
+L1319:
+L1320:
+	add     r13, r13, #20
+	ldmia   sp!, {r4 - r11, pc}
+
+	@ENDP  @ |AutoCorrelation|
+	.end
diff --git a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/CalcWindowEnergy_v5.s b/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/CalcWindowEnergy_v5.s
index 7997e98..b30e8cb 100644
--- a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/CalcWindowEnergy_v5.s
+++ b/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/CalcWindowEnergy_v5.s
@@ -1,112 +1,112 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-

-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

-@	File:		CalcWindowEnergy_v5.s

-@

-@	Content:	CalcWindowEnergy function armv5 assemble

-@

-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

-

-	.section .text

-	

-	.global	CalcWindowEnergy

-

-CalcWindowEnergy:

-	stmdb   sp!, {r4 - r11, lr}

-	sub     r13, r13, #20 

-

-  mov     r3, r3, lsl #16                         

-	ldr     r10, [r0, #168]                    @ states0 = blockSwitchingControl->iirStates[0];

-  mov     r3, r3, asr #16 

-	ldr     r11, [r0, #172]                    @ states1 = blockSwitchingControl->iirStates[1];

-

-	mov     r2, r2, lsl #16

-	ldr     r12, hiPassCoeff                   @ Coeff0 = hiPassCoeff[0];      

-  mov     r2, r2, asr #16

-	ldr     r14, hiPassCoeff + 4			         @ Coeff1 = hiPassCoeff[1];

-	

-	mov			r8, #0							               @ w=0

-	mov			r5, #0							               @ wOffset = 0;

-	

-BLOCK_BEGIN:

-	mov			r6, #0                             @ accuUE = 0; 

-	mov			r7, #0								             @ accuFE = 0; 

-	mov			r4, #0							               @ i=0

-		                   

-	str			r8, [r13, #4]	

-	str			r0, [r13, #8]	

-	str			r3, [r13, #12]

-	

-ENERGY_BEG:	

-	mov     r9, r5, lsl #1  

-	ldrsh   r9, [r1, r9]											@ tempUnfiltered = timeSignal[tidx];

-

-	add			r5, r5, r2												@ tidx = tidx + chIncrement;

-	

-	smulwb	r3, r14, r9												@ accu1 = L_mpy_ls(Coeff1, tempUnfiltered);	

-	smull		r0, r8, r12, r11									@ accu2 = fixmul( Coeff0, states1 );

-	

-	mov			r3, r3, lsl #1

-	mov			r8, r8, lsl #1

-

-	sub			r0, r3, r10												@ accu3 = accu1 - states0;	

-	sub			r8,	r0, r8												@ out = accu3 - accu2;

-

-	mov		  r10, r3														@ states0 = accu1;

-	mov		  r11, r8														@ states1 = out;  

-	

-	mul		  r3, r9, r9	

-	mov     r8, r8, asr #16

-	

-	add		  r4, r4, #1

-	add     r6, r6, r3, asr #7

-

-	mul		  r9, r8, r8	

-	ldr		  r3, [r13, #12]

-

-	add		  r7, r7, r9, asr #7

-		

-	cmp     r4, r3                            

-  blt     ENERGY_BEG       

-	

-	ldr		  r0, [r13, #8]

-	ldr		  r8, [r13, #4]

-	

-ENERGY_END:

-	add		  r4, r0, r8, lsl #2

-

-	str     r6, [r4, #72]         

-	add		  r8, r8, #1	           

-  str     r7, [r4, #136]                   

-

-	cmp		  r8, #8

-	blt		  BLOCK_BEGIN                  	                        

-

-BLOCK_END:

-	str     r10, [r0, #168]                    

-  str     r11, [r0, #172]                    

-  mov     r0, #1            

-	                

-  add     r13, r13, #20   

-	ldmia   sp!, {r4 - r11, pc}                  

-

-hiPassCoeff:

-	.word 0xbec8b439

-	.word	0x609d4952

-		

-	@ENDP

-	.end

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+
+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+@	File:		CalcWindowEnergy_v5.s
+@
+@	Content:	CalcWindowEnergy function armv5 assemble
+@
+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+
+	.section .text
+
+	.global	CalcWindowEnergy
+
+CalcWindowEnergy:
+	stmdb   sp!, {r4 - r11, lr}
+	sub     r13, r13, #20
+
+  mov     r3, r3, lsl #16
+	ldr     r10, [r0, #168]                    @ states0 = blockSwitchingControl->iirStates[0];
+  mov     r3, r3, asr #16
+	ldr     r11, [r0, #172]                    @ states1 = blockSwitchingControl->iirStates[1];
+
+	mov     r2, r2, lsl #16
+	ldr     r12, hiPassCoeff                   @ Coeff0 = hiPassCoeff[0];
+  mov     r2, r2, asr #16
+	ldr     r14, hiPassCoeff + 4			         @ Coeff1 = hiPassCoeff[1];
+
+	mov			r8, #0							               @ w=0
+	mov			r5, #0							               @ wOffset = 0;
+
+BLOCK_BEGIN:
+	mov			r6, #0                             @ accuUE = 0;
+	mov			r7, #0								             @ accuFE = 0;
+	mov			r4, #0							               @ i=0
+
+	str			r8, [r13, #4]
+	str			r0, [r13, #8]
+	str			r3, [r13, #12]
+
+ENERGY_BEG:
+	mov     r9, r5, lsl #1
+	ldrsh   r9, [r1, r9]											@ tempUnfiltered = timeSignal[tidx];
+
+	add			r5, r5, r2												@ tidx = tidx + chIncrement;
+
+	smulwb	r3, r14, r9												@ accu1 = L_mpy_ls(Coeff1, tempUnfiltered);
+	smull		r0, r8, r12, r11									@ accu2 = fixmul( Coeff0, states1 );
+
+	mov			r3, r3, lsl #1
+	mov			r8, r8, lsl #1
+
+	sub			r0, r3, r10												@ accu3 = accu1 - states0;
+	sub			r8,	r0, r8												@ out = accu3 - accu2;
+
+	mov		  r10, r3														@ states0 = accu1;
+	mov		  r11, r8														@ states1 = out;
+
+	mul		  r3, r9, r9
+	mov     r8, r8, asr #16
+
+	add		  r4, r4, #1
+	add     r6, r6, r3, asr #7
+
+	mul		  r9, r8, r8
+	ldr		  r3, [r13, #12]
+
+	add		  r7, r7, r9, asr #7
+
+	cmp     r4, r3
+  blt     ENERGY_BEG
+
+	ldr		  r0, [r13, #8]
+	ldr		  r8, [r13, #4]
+
+ENERGY_END:
+	add		  r4, r0, r8, lsl #2
+
+	str     r6, [r4, #72]
+	add		  r8, r8, #1
+  str     r7, [r4, #136]
+
+	cmp		  r8, #8
+	blt		  BLOCK_BEGIN
+
+BLOCK_END:
+	str     r10, [r0, #168]
+  str     r11, [r0, #172]
+  mov     r0, #1
+
+  add     r13, r13, #20
+	ldmia   sp!, {r4 - r11, pc}
+
+hiPassCoeff:
+	.word 0xbec8b439
+	.word	0x609d4952
+
+	@ENDP
+	.end
diff --git a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/PrePostMDCT_v5.s b/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/PrePostMDCT_v5.s
index d4d3edb..103cc91 100644
--- a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/PrePostMDCT_v5.s
+++ b/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/PrePostMDCT_v5.s
@@ -1,131 +1,131 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-

-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

-@	File:		PrePostMDCT_v5.s

-@

-@	Content:	premdct and postmdct function armv5 assemble

-@

-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

-

-	.section .text

-	.global	PreMDCT

-

-PreMDCT:

-	stmdb       sp!, {r4 - r11, lr}

-	

-	add         r9, r0, r1, lsl #2

-	sub         r3, r9, #8

-

-	movs        r1, r1, asr #2

-	beq         PreMDCT_END

-	

-PreMDCT_LOOP:

-	ldr					r8, [r2], #4

-	ldr					r9, [r2], #4

-	

-	ldrd				r4, [r0]

-	ldrd				r6, [r3]

-	

-	smull				r14, r11, r4, r8					@ MULHIGH(tr1, cosa)

-	smull    			r10, r12, r7, r8					@ MULHIGH(ti1, cosa)

-		

-	smull				r14, r8, r7, r9						@ MULHIGH(ti1, sina)

-	smull				r7, r10, r4, r9						@ MULHIGH(tr1, sina)	

-		

-	add					r11, r11, r8						@ MULHIGH(cosa, tr1) + MULHIGH(sina, ti1)@	

-	sub					r7, r12, r10						@ MULHIGH(ti1, cosa) - MULHIGH(tr1, sina)

-	

-	ldr					r8, [r2], #4

-	ldr					r9, [r2], #4

-	

-	smull				r14, r4, r6, r8						@ MULHIGH(tr2, cosa)

-	smull    			r10, r12, r5, r8					@ MULHIGH(ti2, cosa)

-		

-	smull				r14, r8, r5, r9						@ MULHIGH(ti2, sina)

-	smull				r5, r10, r6, r9						@ MULHIGH(tr2, sina)

-	

-	add					r8, r8, r4

-	sub					r9, r12, r10

-	

-	mov					r6, r11		

-

-	strd				r6, [r0]	

-	strd				r8, [r3]

-	

-	subs				r1, r1, #1

-	sub					r3, r3, #8

-	add 				r0, r0, #8

-	bne					PreMDCT_LOOP

-

-PreMDCT_END:

-	ldmia       sp!, {r4 - r11, pc}

-	@ENDP  @ |PreMDCT|

-	

-	.section .text

-	.global	PostMDCT

-

-PostMDCT:

-	stmdb       sp!, {r4 - r11, lr}

-	

-	add         r9, r0, r1, lsl #2

-	sub         r3, r9, #8

-

-	movs        r1, r1, asr #2

-	beq         PostMDCT_END

-	

-PostMDCT_LOOP:

-	ldr					r8, [r2], #4					

-	ldr					r9, [r2], #4

-	

-	ldrd				r4, [r0]

-	ldrd				r6, [r3]

-	

-	smull				r14, r11, r4, r8					@ MULHIGH(tr1, cosa)

-	smull    			r10, r12, r5, r8					@ MULHIGH(ti1, cosa)

-		

-	smull				r14, r8, r5, r9						@ MULHIGH(ti1, sina)

-	smull				r5, r10, r4, r9						@ MULHIGH(tr1, sina)	

-		

-	add					r4, r11, r8							@ MULHIGH(cosa, tr1) + MULHIGH(sina, ti1)@	

-	sub					r11, r10, r12						@ MULHIGH(ti1, cosa) - MULHIGH(tr1, sina)@

-	

-	ldr					r8, [r2], #4						@

-	ldr					r9, [r2], #4

-	

-	smull				r14, r5, r6, r8						@ MULHIGH(tr2, cosa)

-	smull    			r10, r12, r7, r8					@ MULHIGH(ti2, cosa)

-		

-	smull				r14, r8, r7, r9						@ MULHIGH(ti2, sina)

-	smull				r7, r10, r6, r9						@ MULHIGH(tr2, sina)

-	

-	add					r6, r8, r5							@ MULHIGH(cosb, tr2) + MULHIGH(sinb, ti2)@

-	sub					r5, r10, r12						@ MULHIGH(sinb, tr2) - MULHIGH(cosb, ti2)@

-	

-	mov					r7, r11				

-

-	strd				r4, [r0]

-	strd				r6, [r3]

-	

-	subs				r1, r1, #1

-	sub					r3, r3, #8

-	add 				r0, r0, #8

-	bne					PostMDCT_LOOP

-

-PostMDCT_END:

-	ldmia       sp!, {r4 - r11, pc}

-	@ENDP  @ |PostMDCT|

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+
+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+@	File:		PrePostMDCT_v5.s
+@
+@	Content:	premdct and postmdct function armv5 assemble
+@
+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+
+	.section .text
+	.global	PreMDCT
+
+PreMDCT:
+	stmdb       sp!, {r4 - r11, lr}
+
+	add         r9, r0, r1, lsl #2
+	sub         r3, r9, #8
+
+	movs        r1, r1, asr #2
+	beq         PreMDCT_END
+
+PreMDCT_LOOP:
+	ldr					r8, [r2], #4
+	ldr					r9, [r2], #4
+
+	ldrd				r4, [r0]
+	ldrd				r6, [r3]
+
+	smull				r14, r11, r4, r8					@ MULHIGH(tr1, cosa)
+	smull    			r10, r12, r7, r8					@ MULHIGH(ti1, cosa)
+
+	smull				r14, r8, r7, r9						@ MULHIGH(ti1, sina)
+	smull				r7, r10, r4, r9						@ MULHIGH(tr1, sina)
+
+	add					r11, r11, r8						@ MULHIGH(cosa, tr1) + MULHIGH(sina, ti1)@
+	sub					r7, r12, r10						@ MULHIGH(ti1, cosa) - MULHIGH(tr1, sina)
+
+	ldr					r8, [r2], #4
+	ldr					r9, [r2], #4
+
+	smull				r14, r4, r6, r8						@ MULHIGH(tr2, cosa)
+	smull    			r10, r12, r5, r8					@ MULHIGH(ti2, cosa)
+
+	smull				r14, r8, r5, r9						@ MULHIGH(ti2, sina)
+	smull				r5, r10, r6, r9						@ MULHIGH(tr2, sina)
+
+	add					r8, r8, r4
+	sub					r9, r12, r10
+
+	mov					r6, r11
+
+	strd				r6, [r0]
+	strd				r8, [r3]
+
+	subs				r1, r1, #1
+	sub					r3, r3, #8
+	add 				r0, r0, #8
+	bne					PreMDCT_LOOP
+
+PreMDCT_END:
+	ldmia       sp!, {r4 - r11, pc}
+	@ENDP  @ |PreMDCT|
+
+	.section .text
+	.global	PostMDCT
+
+PostMDCT:
+	stmdb       sp!, {r4 - r11, lr}
+
+	add         r9, r0, r1, lsl #2
+	sub         r3, r9, #8
+
+	movs        r1, r1, asr #2
+	beq         PostMDCT_END
+
+PostMDCT_LOOP:
+	ldr					r8, [r2], #4
+	ldr					r9, [r2], #4
+
+	ldrd				r4, [r0]
+	ldrd				r6, [r3]
+
+	smull				r14, r11, r4, r8					@ MULHIGH(tr1, cosa)
+	smull    			r10, r12, r5, r8					@ MULHIGH(ti1, cosa)
+
+	smull				r14, r8, r5, r9						@ MULHIGH(ti1, sina)
+	smull				r5, r10, r4, r9						@ MULHIGH(tr1, sina)
+
+	add					r4, r11, r8							@ MULHIGH(cosa, tr1) + MULHIGH(sina, ti1)@
+	sub					r11, r10, r12						@ MULHIGH(ti1, cosa) - MULHIGH(tr1, sina)@
+
+	ldr					r8, [r2], #4						@
+	ldr					r9, [r2], #4
+
+	smull				r14, r5, r6, r8						@ MULHIGH(tr2, cosa)
+	smull    			r10, r12, r7, r8					@ MULHIGH(ti2, cosa)
+
+	smull				r14, r8, r7, r9						@ MULHIGH(ti2, sina)
+	smull				r7, r10, r6, r9						@ MULHIGH(tr2, sina)
+
+	add					r6, r8, r5							@ MULHIGH(cosb, tr2) + MULHIGH(sinb, ti2)@
+	sub					r5, r10, r12						@ MULHIGH(sinb, tr2) - MULHIGH(cosb, ti2)@
+
+	mov					r7, r11
+
+	strd				r4, [r0]
+	strd				r6, [r3]
+
+	subs				r1, r1, #1
+	sub					r3, r3, #8
+	add 				r0, r0, #8
+	bne					PostMDCT_LOOP
+
+PostMDCT_END:
+	ldmia       sp!, {r4 - r11, pc}
+	@ENDP  @ |PostMDCT|
 	.end
\ No newline at end of file
diff --git a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/R4R8First_v5.s b/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/R4R8First_v5.s
index 370daf4..72cb9a3c 100644
--- a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/R4R8First_v5.s
+++ b/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/R4R8First_v5.s
@@ -1,252 +1,252 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-

-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

-@	File:		R4R8First_v5.s

-@

-@	Content:	Radix8First and Radix4First function armv5 assemble

-@

-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

-

-	.section .text

-	.global	Radix4First

-

-Radix4First:

-	stmdb       sp!, {r4 - r11, lr}

-	

-	movs				r10, r1

-	mov					r11, r0

-	beq					Radix4First_END

-		

-Radix4First_LOOP:

-	ldrd				r0, [r11]

-	ldrd				r2, [r11, #8]

-	ldrd				r4, [r11, #16]

-	ldrd				r6, [r11, #24]

-	

-	add					r8, r0, r2

-	add					r9, r1, r3

-	

-	sub					r0, r0, r2

-	sub					r1, r1, r3

-	

-	add					r2, r4, r6

-	add					r3, r5, r7

-	

-	sub					r4, r4, r6

-	sub					r5, r5, r7

-	

-	add					r6, r8, r2

-	add					r7, r9, r3

-	

-	sub					r8, r8, r2

-	sub					r9, r9, r3

-	

-	add					r2, r0, r5

-	sub					r3, r1, r4

-	

-	sub					r0, r0, r5

-	add					r1, r1, r4

-	

-	strd				r6, [r11]

-	strd				r2, [r11, #8]

-	strd				r8, [r11, #16]

-	strd				r0, [r11, #24]

-	

-	subs				r10, r10, #1

-	add					r11, r11, #32

-	bne					Radix4First_LOOP

-

-Radix4First_END:

-	ldmia       sp!, {r4 - r11, pc}

-	@ENDP  @ |Radix4First|

-	

-	.section .text

-	.global	Radix8First

-

-Radix8First:

-	stmdb       sp!, {r4 - r11, lr}

-	sub         sp, sp, #0x24

-	

-	mov				  r12, r1

-	mov					r14, r0

-	cmp					r12, #0

-	beq					Radix8First_END

-	

-Radix8First_LOOP:

-	ldrd				r0, [r14]		

-	ldrd				r2, [r14, #8]

-	ldrd				r4, [r14, #16]

-	ldrd				r6, [r14, #24]

-	

-	add					r8, r0, r2					@ r0 = buf[0] + buf[2]@

-	add					r9, r1, r3					@ i0 = buf[1] + buf[3]@

-	

-	sub					r0, r0, r2					@ r1 = buf[0] - buf[2]@

-	sub					r1, r1, r3					@ i1 = buf[1] - buf[3]@

-	

-	add					r2, r4, r6					@	r2 = buf[4] + buf[6]@

-	add					r3, r5, r7					@ i2 = buf[5] + buf[7]@

-	

-	sub					r4, r4, r6					@	r3 = buf[4] - buf[6]@

-	sub					r5, r5, r7					@ i3 = buf[5] - buf[7]@

-	

-	add					r6, r8, r2					@ r4 = (r0 + r2) >> 1@

-	add					r7, r9, r3					@ i4 = (i0 + i2) >> 1@

-	

-	sub					r8, r8, r2					@	r5 = (r0 - r2) >> 1@

-	sub					r9, r9, r3					@ i5 = (i0 - i2) >> 1@

-	

-	sub					r2, r0, r5					@ r6 = (r1 - i3) >> 1@

-	add					r3, r1, r4					@ i6 = (i1 + r3) >> 1@

-	

-	add					r0, r0, r5					@ r7 = (r1 + i3) >> 1@

-	sub					r1, r1, r4					@ i7 = (i1 - r3) >> 1@

-	

-	mov					r6, r6, asr #1			@

-	mov					r7, r7, asr #1			@

-	

-	mov					r8, r8, asr #1

-	mov					r9, r9, asr #1

-	

-	mov					r2, r2, asr #1

-	mov					r3, r3, asr #1

-	

-	mov					r0, r0, asr #1

-	mov					r1, r1, asr #1	

-	

-	str					r6, [sp]

-	str					r7, [sp, #4]

-	

-	str					r8, [sp, #8]

-	str					r9, [sp, #12]

-	

-	str					r2, [sp, #16]

-	str					r3, [sp, #20]	

-	

-	str					r0, [sp, #24]

-	str					r1, [sp, #28]	

-	

-	ldrd				r2, [r14, #32]		

-	ldrd				r4, [r14, #40]

-	ldrd				r6, [r14, #48]

-	ldrd				r8, [r14, #56]

-	

-	add					r0, r2, r4					@ r0 = buf[ 8] + buf[10]@

-	add					r1, r3, r5					@ i0 = buf[ 9] + buf[11]@

-	

-	sub					r2, r2, r4					@ r1 = buf[ 8] - buf[10]@

-	sub					r3, r3, r5					@ i1 = buf[ 9] - buf[11]@

-	

-	add					r4, r6, r8					@ r2 = buf[12] + buf[14]@

-	add					r5, r7, r9					@ i2 = buf[13] + buf[15]@

-	

-	sub					r6, r6, r8					@ r3 = buf[12] - buf[14]@

-	sub					r7, r7, r9					@	i3 = buf[13] - buf[15]@

-	

-	add					r8, r0, r4					@ t0 = (r0 + r2)

-	add					r9, r1, r5					@ t1 = (i0 + i2)

-	

-	sub					r0, r0, r4					@ t2 = (r0 - r2)

-	sub					r1, r1, r5					@ t3 = (i0 - i2)

-	

-	mov					r8, r8, asr #1

-	ldr					r4, [sp]

-	

-	mov					r9, r9, asr #1

-	ldr					r5, [sp, #4]

-	

-	mov					r0, r0, asr #1		

-	mov					r1, r1, asr #1

-	

-	add					r10, r4, r8					@ buf[ 0] = r4 + t0@

-	add					r11, r5, r9					@ buf[ 1] = i4 + t1@

-	

-	sub					r4,  r4, r8					@ buf[ 8] = r4 - t0@

-	sub					r5,  r5, r9					@	buf[ 9] = i4 - t1@

-	

- 	strd				r10, [r14]

- 	strd				r4,  [r14, #32]

- 	

- 	ldr					r10, [sp, #8]

- 	ldr					r11, [sp, #12]

- 	

- 	add					r4, r10, r1					@ buf[ 4] = r5 + t3@

- 	sub					r5, r11, r0					@	buf[ 5] = i5 - t2@

- 	

- 	sub					r10, r10, r1				@ buf[12] = r5 - t3@

- 	add					r11, r11, r0				@ buf[13] = i5 + t2@

- 	

- 	strd				r4,  [r14, #16]

- 	strd				r10, [r14, #48]

- 	

- 	sub					r0, r2, r7					@ r0 = r1 - i3@

- 	add					r1, r3, r6					@ i0 = i1 + r3@

- 

-  ldr					r11, DATATab

- 	

- 	add					r2, r2, r7					@ r2 = r1 + i3@

- 	sub					r3, r3, r6					@ i2 = i1 - r3@

- 	

-	sub					r4, r0, r1					@ r0 - i0

-	add					r5, r0, r1					@ r0 + i0

-	

-	sub					r0, r2, r3					@ r2 - i2

-	add					r1, r2, r3					@ r2 + i2

-	

-	smull				r8, r6, r4, r11								

-	smull				r9, r7, r5, r11								

-	

-	ldr					r2, [sp, #16]

-	ldr					r3, [sp, #20]

-	

-	smull				r8, r4, r0, r11								

-	smull				r9, r5, r1, r11								

-	

-	ldr					r10, [sp, #24]

-	ldr					r11, [sp, #28]

-	

-	sub					r8, r2, r6

-	sub					r9, r3, r7

-	

-	add					r2, r2, r6

-	add					r3, r3, r7

-	

-	add					r6, r10, r5

-	sub					r7, r11, r4

-	

-	sub					r0, r10, r5

-	add					r1, r11, r4

-	

-	strd				r6, [r14, #8]

-	strd				r8, [r14, #24]

-	strd				r0, [r14, #40]

-	strd				r2, [r14, #56]

-	

-	subs				r12, r12, #1

-	add					r14, r14, #64

-	

-	bne					Radix8First_LOOP

-	

-Radix8First_END:

-	add         sp, sp, #0x24

-	ldmia       sp!, {r4 - r11, pc}

-	

-DATATab:

-	.word       0x5a82799a

-	

-	@ENDP  @ |Radix8First|

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+
+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+@	File:		R4R8First_v5.s
+@
+@	Content:	Radix8First and Radix4First function armv5 assemble
+@
+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+
+	.section .text
+	.global	Radix4First
+
+Radix4First:
+	stmdb       sp!, {r4 - r11, lr}
+
+	movs				r10, r1
+	mov					r11, r0
+	beq					Radix4First_END
+
+Radix4First_LOOP:
+	ldrd				r0, [r11]
+	ldrd				r2, [r11, #8]
+	ldrd				r4, [r11, #16]
+	ldrd				r6, [r11, #24]
+
+	add					r8, r0, r2
+	add					r9, r1, r3
+
+	sub					r0, r0, r2
+	sub					r1, r1, r3
+
+	add					r2, r4, r6
+	add					r3, r5, r7
+
+	sub					r4, r4, r6
+	sub					r5, r5, r7
+
+	add					r6, r8, r2
+	add					r7, r9, r3
+
+	sub					r8, r8, r2
+	sub					r9, r9, r3
+
+	add					r2, r0, r5
+	sub					r3, r1, r4
+
+	sub					r0, r0, r5
+	add					r1, r1, r4
+
+	strd				r6, [r11]
+	strd				r2, [r11, #8]
+	strd				r8, [r11, #16]
+	strd				r0, [r11, #24]
+
+	subs				r10, r10, #1
+	add					r11, r11, #32
+	bne					Radix4First_LOOP
+
+Radix4First_END:
+	ldmia       sp!, {r4 - r11, pc}
+	@ENDP  @ |Radix4First|
+
+	.section .text
+	.global	Radix8First
+
+Radix8First:
+	stmdb       sp!, {r4 - r11, lr}
+	sub         sp, sp, #0x24
+
+	mov				  r12, r1
+	mov					r14, r0
+	cmp					r12, #0
+	beq					Radix8First_END
+
+Radix8First_LOOP:
+	ldrd				r0, [r14]
+	ldrd				r2, [r14, #8]
+	ldrd				r4, [r14, #16]
+	ldrd				r6, [r14, #24]
+
+	add					r8, r0, r2					@ r0 = buf[0] + buf[2]@
+	add					r9, r1, r3					@ i0 = buf[1] + buf[3]@
+
+	sub					r0, r0, r2					@ r1 = buf[0] - buf[2]@
+	sub					r1, r1, r3					@ i1 = buf[1] - buf[3]@
+
+	add					r2, r4, r6					@	r2 = buf[4] + buf[6]@
+	add					r3, r5, r7					@ i2 = buf[5] + buf[7]@
+
+	sub					r4, r4, r6					@	r3 = buf[4] - buf[6]@
+	sub					r5, r5, r7					@ i3 = buf[5] - buf[7]@
+
+	add					r6, r8, r2					@ r4 = (r0 + r2) >> 1@
+	add					r7, r9, r3					@ i4 = (i0 + i2) >> 1@
+
+	sub					r8, r8, r2					@	r5 = (r0 - r2) >> 1@
+	sub					r9, r9, r3					@ i5 = (i0 - i2) >> 1@
+
+	sub					r2, r0, r5					@ r6 = (r1 - i3) >> 1@
+	add					r3, r1, r4					@ i6 = (i1 + r3) >> 1@
+
+	add					r0, r0, r5					@ r7 = (r1 + i3) >> 1@
+	sub					r1, r1, r4					@ i7 = (i1 - r3) >> 1@
+
+	mov					r6, r6, asr #1			@
+	mov					r7, r7, asr #1			@
+
+	mov					r8, r8, asr #1
+	mov					r9, r9, asr #1
+
+	mov					r2, r2, asr #1
+	mov					r3, r3, asr #1
+
+	mov					r0, r0, asr #1
+	mov					r1, r1, asr #1
+
+	str					r6, [sp]
+	str					r7, [sp, #4]
+
+	str					r8, [sp, #8]
+	str					r9, [sp, #12]
+
+	str					r2, [sp, #16]
+	str					r3, [sp, #20]
+
+	str					r0, [sp, #24]
+	str					r1, [sp, #28]
+
+	ldrd				r2, [r14, #32]
+	ldrd				r4, [r14, #40]
+	ldrd				r6, [r14, #48]
+	ldrd				r8, [r14, #56]
+
+	add					r0, r2, r4					@ r0 = buf[ 8] + buf[10]@
+	add					r1, r3, r5					@ i0 = buf[ 9] + buf[11]@
+
+	sub					r2, r2, r4					@ r1 = buf[ 8] - buf[10]@
+	sub					r3, r3, r5					@ i1 = buf[ 9] - buf[11]@
+
+	add					r4, r6, r8					@ r2 = buf[12] + buf[14]@
+	add					r5, r7, r9					@ i2 = buf[13] + buf[15]@
+
+	sub					r6, r6, r8					@ r3 = buf[12] - buf[14]@
+	sub					r7, r7, r9					@	i3 = buf[13] - buf[15]@
+
+	add					r8, r0, r4					@ t0 = (r0 + r2)
+	add					r9, r1, r5					@ t1 = (i0 + i2)
+
+	sub					r0, r0, r4					@ t2 = (r0 - r2)
+	sub					r1, r1, r5					@ t3 = (i0 - i2)
+
+	mov					r8, r8, asr #1
+	ldr					r4, [sp]
+
+	mov					r9, r9, asr #1
+	ldr					r5, [sp, #4]
+
+	mov					r0, r0, asr #1
+	mov					r1, r1, asr #1
+
+	add					r10, r4, r8					@ buf[ 0] = r4 + t0@
+	add					r11, r5, r9					@ buf[ 1] = i4 + t1@
+
+	sub					r4,  r4, r8					@ buf[ 8] = r4 - t0@
+	sub					r5,  r5, r9					@	buf[ 9] = i4 - t1@
+
+ 	strd				r10, [r14]
+ 	strd				r4,  [r14, #32]
+
+ 	ldr					r10, [sp, #8]
+ 	ldr					r11, [sp, #12]
+
+ 	add					r4, r10, r1					@ buf[ 4] = r5 + t3@
+ 	sub					r5, r11, r0					@	buf[ 5] = i5 - t2@
+
+ 	sub					r10, r10, r1				@ buf[12] = r5 - t3@
+ 	add					r11, r11, r0				@ buf[13] = i5 + t2@
+
+ 	strd				r4,  [r14, #16]
+ 	strd				r10, [r14, #48]
+
+ 	sub					r0, r2, r7					@ r0 = r1 - i3@
+ 	add					r1, r3, r6					@ i0 = i1 + r3@
+
+  ldr					r11, DATATab
+
+ 	add					r2, r2, r7					@ r2 = r1 + i3@
+ 	sub					r3, r3, r6					@ i2 = i1 - r3@
+
+	sub					r4, r0, r1					@ r0 - i0
+	add					r5, r0, r1					@ r0 + i0
+
+	sub					r0, r2, r3					@ r2 - i2
+	add					r1, r2, r3					@ r2 + i2
+
+	smull				r8, r6, r4, r11
+	smull				r9, r7, r5, r11
+
+	ldr					r2, [sp, #16]
+	ldr					r3, [sp, #20]
+
+	smull				r8, r4, r0, r11
+	smull				r9, r5, r1, r11
+
+	ldr					r10, [sp, #24]
+	ldr					r11, [sp, #28]
+
+	sub					r8, r2, r6
+	sub					r9, r3, r7
+
+	add					r2, r2, r6
+	add					r3, r3, r7
+
+	add					r6, r10, r5
+	sub					r7, r11, r4
+
+	sub					r0, r10, r5
+	add					r1, r11, r4
+
+	strd				r6, [r14, #8]
+	strd				r8, [r14, #24]
+	strd				r0, [r14, #40]
+	strd				r2, [r14, #56]
+
+	subs				r12, r12, #1
+	add					r14, r14, #64
+
+	bne					Radix8First_LOOP
+
+Radix8First_END:
+	add         sp, sp, #0x24
+	ldmia       sp!, {r4 - r11, pc}
+
+DATATab:
+	.word       0x5a82799a
+
+	@ENDP  @ |Radix8First|
 	.end
\ No newline at end of file
diff --git a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/Radix4FFT_v5.s b/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/Radix4FFT_v5.s
index db8e5d8..e81c82e 100644
--- a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/Radix4FFT_v5.s
+++ b/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/Radix4FFT_v5.s
@@ -1,169 +1,169 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-

-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

-@	File:		Radix4FFT_v5.s

-@

-@	Content:	Radix4FFT armv5 assemble

-@

-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

-	.section .text

-	.global	Radix4FFT

-

-Radix4FFT:

-	stmdb     sp!, {r4 - r11, lr}

-	sub       sp, sp, #32                     

-

-	mov			r1, r1, asr #2

-	cmp     r1, #0       

-	beq     Radix4FFT_END                            

-                       

-Radix4FFT_LOOP1:          

-	mov     r14, r0          							@ xptr = buf@          

-	mov		r10, r1 												@ i = num@

-	mov     r9, r2, lsl #3  							@ step = 2*bgn@

-	cmp     r10, #0  

-	str		r0, [sp] 

-	str		r1, [sp, #4]      

-	str		r2, [sp, #8]

-	str		r3, [sp, #12]  

-	beq     Radix4FFT_LOOP1_END                            	    

-     

-Radix4FFT_LOOP2:                       

-	mov     r12, r3				        				@ csptr = twidTab@

-	mov		r11, r2												@ j = bgn

-	cmp     r11, #0        

-	str		r10, [sp, #16]

-	beq     Radix4FFT_LOOP2_END                         

-	 

-Radix4FFT_LOOP3:                          

-	str			r11, [sp, #20]	 

-	

-	ldrd		r0, [r14, #0]									@ r0 = xptr[0]@ r1 = xptr[1]@

-	add			r14, r14, r9 	 								@ xptr += step@

-	

-	ldrd		r10,	[r14, #0]  					 			@ r2 = xptr[0]@ r3 = xptr[1]@	

-	ldr			r8, [r12], #4									@ cosxsinx = csptr[0]@

-	

-	smulwt	r4, r10, r8										@ L_mpy_wx(cosx, t0)

-	smulwt	r3, r11, r8										@ L_mpy_wx(cosx, t1)

-	

-	smlawb	r2, r11, r8, r4								@ r2 = L_mpy_wx(cosx, t0) + L_mpy_wx(sinx, t1)@

-	smulwb	r5, r10, r8										@ L_mpy_wx(sinx, t0)

-	

-	mov			r10, r0, asr #2								@ t0 = r0 >> 2@

-	mov			r11, r1, asr #2								@	t1 = r1 >> 2@

-		

-	sub			r3, r3, r5										@ r3 = L_mpy_wx(cosx, t1) - L_mpy_wx(sinx, t0)@

-	add     r14, r14, r9 	 								@ xptr += step@

-	

-	sub			r0, r10, r2										@ r0 = t0 - r2@

-	sub			r1, r11, r3									  @ r1 = t1 - r3@

-	

-	add			r2, r10, r2										@ r2 = t0 + r2@

-	add			r3, r11, r3										@ r3 = t1 + r3@

-	

-	str			r2, [sp, #24]

-	str			r3, [sp, #28]

-	

-	ldrd		r10, [r14, #0]								@ r4 = xptr[0]@ r5 = xptr[1]@

-	ldr			r8, [r12], #4									@ cosxsinx = csptr[1]@

-	

-	smulwt	r6, r10, r8										@ L_mpy_wx(cosx, t0)

-	smulwt	r5, r11, r8										@ L_mpy_wx(cosx, t1)

-	

-	smlawb	r4, r11, r8, r6								@ r4 = L_mpy_wx(cosx, t0) + L_mpy_wx(sinx, t1)@

-	smulwb	r7, r10, r8										@ L_mpy_wx(sinx, t0)

-	

-	add			r14, r14, r9									@ xptr += step@

-	sub			r5, r5, r7										@ r5 = L_mpy_wx(cosx, t1) - L_mpy_wx(sinx, t0)@

-		

-	ldrd		r10, [r14]										@ r6 = xptr[0]@ r7 = xptr[1]@

-	ldr			r8, [r12], #4									@ cosxsinx = csptr[1]@

-	

-	smulwt	r2, r10, r8										@ L_mpy_wx(cosx, t0)

-	smulwt	r7, r11, r8										@ L_mpy_wx(cosx, t1)

-	

-	smlawb	r6, r11, r8, r2								@ r4 = L_mpy_wx(cosx, t0) + L_mpy_wx(sinx, t1)@

-	smulwb	r3, r10, r8										@ L_mpy_wx(sinx, t0)

-	

-	mov			r10, r4												@ t0 = r4@

-	mov			r11, r5												@ t1 = r5@	

-	

-	sub			r7, r7, r3										@ r5 = L_mpy_wx(cosx, t1) - L_mpy_wx(sinx, t0)@

-	

-

-	add			r4,  r10, r6									@	r4 = t0 + r6@	

-	sub			r5, r7, r11										@ r5 = r7 - t1@

-	

-	sub			r6, r10, r6										@ r6 = t0 - r6@

-	add			r7, r7, r11										@ r7 = r7 + t1@

-	

-	ldr			r2, [sp, #24]

-	ldr			r3, [sp, #28]

-	

-	add			r10, r0, r5										@ xptr[0] = r0 + r5@

-	add			r11, r1, r6										@ xptr[0] = r1 + r6

-	

-	strd		r10, [r14]										

-	sub			r14, r14, r9									@ xptr -= step@

-	

-	sub			r10, r2, r4										@	xptr[0] = r2 - r4@

-	sub			r11, r3, r7										@ xptr[1] = r3 - r7@

-	

-	strd		r10, [r14]				

-	sub			r14, r14, r9									@ xptr -= step@

-	

-	sub			r10, r0, r5										@ xptr[0] = r0 - r5@

-	sub			r11, r1, r6										@ xptr[0] = r1 - r6

-	

-	strd		r10, [r14]										

-	sub			r14, r14, r9									@ xptr -= step@

-	

-	add			r10, r2, r4										@	xptr[0] = r2 - r4@

-	add			r11, r3, r7										@ xptr[1] = r3 - r7@

-	

-	strd		r10, [r14]				

-	add			r14, r14, #8									@ xptr += 2@

-	

-	ldr			r11, [sp, #20]

-	subs		r11, r11, #1

-	bne			Radix4FFT_LOOP3	

-	 

-Radix4FFT_LOOP2_END:           

-	ldr			r10, [sp, #16]

-	ldr			r3, [sp, #12]

-	ldr			r2, [sp, #8]

-	rsb			r8, r9, r9, lsl #2   

-	sub			r10, r10, #1

-	add			r14, r14, r8		      

-	cmp			r10, #0  

-	bhi     Radix4FFT_LOOP2           

-                        

-Radix4FFT_LOOP1_END:               

-	ldr     r0, [sp]    

-	ldr		r1, [sp, #4]

-	add     r3, r3, r8, asr #1

-	mov     r2, r2, lsl #2 

-	movs    r1, r1, asr #2 

-	bne     Radix4FFT_LOOP1          

-                        

-Radix4FFT_END:                        

-	add     sp, sp, #32                  

-	ldmia   sp!, {r4 - r11, pc}

-		

-	@ENDP  @ |Radix4FFT|

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+
+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+@	File:		Radix4FFT_v5.s
+@
+@	Content:	Radix4FFT armv5 assemble
+@
+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+	.section .text
+	.global	Radix4FFT
+
+Radix4FFT:
+	stmdb     sp!, {r4 - r11, lr}
+	sub       sp, sp, #32
+
+	mov			r1, r1, asr #2
+	cmp     r1, #0
+	beq     Radix4FFT_END
+
+Radix4FFT_LOOP1:
+	mov     r14, r0          							@ xptr = buf@
+	mov		r10, r1 												@ i = num@
+	mov     r9, r2, lsl #3  							@ step = 2*bgn@
+	cmp     r10, #0
+	str		r0, [sp]
+	str		r1, [sp, #4]
+	str		r2, [sp, #8]
+	str		r3, [sp, #12]
+	beq     Radix4FFT_LOOP1_END
+
+Radix4FFT_LOOP2:
+	mov     r12, r3				        				@ csptr = twidTab@
+	mov		r11, r2												@ j = bgn
+	cmp     r11, #0
+	str		r10, [sp, #16]
+	beq     Radix4FFT_LOOP2_END
+
+Radix4FFT_LOOP3:
+	str			r11, [sp, #20]
+
+	ldrd		r0, [r14, #0]									@ r0 = xptr[0]@ r1 = xptr[1]@
+	add			r14, r14, r9 	 								@ xptr += step@
+
+	ldrd		r10,	[r14, #0]  					 			@ r2 = xptr[0]@ r3 = xptr[1]@
+	ldr			r8, [r12], #4									@ cosxsinx = csptr[0]@
+
+	smulwt	r4, r10, r8										@ L_mpy_wx(cosx, t0)
+	smulwt	r3, r11, r8										@ L_mpy_wx(cosx, t1)
+
+	smlawb	r2, r11, r8, r4								@ r2 = L_mpy_wx(cosx, t0) + L_mpy_wx(sinx, t1)@
+	smulwb	r5, r10, r8										@ L_mpy_wx(sinx, t0)
+
+	mov			r10, r0, asr #2								@ t0 = r0 >> 2@
+	mov			r11, r1, asr #2								@	t1 = r1 >> 2@
+
+	sub			r3, r3, r5										@ r3 = L_mpy_wx(cosx, t1) - L_mpy_wx(sinx, t0)@
+	add     r14, r14, r9 	 								@ xptr += step@
+
+	sub			r0, r10, r2										@ r0 = t0 - r2@
+	sub			r1, r11, r3									  @ r1 = t1 - r3@
+
+	add			r2, r10, r2										@ r2 = t0 + r2@
+	add			r3, r11, r3										@ r3 = t1 + r3@
+
+	str			r2, [sp, #24]
+	str			r3, [sp, #28]
+
+	ldrd		r10, [r14, #0]								@ r4 = xptr[0]@ r5 = xptr[1]@
+	ldr			r8, [r12], #4									@ cosxsinx = csptr[1]@
+
+	smulwt	r6, r10, r8										@ L_mpy_wx(cosx, t0)
+	smulwt	r5, r11, r8										@ L_mpy_wx(cosx, t1)
+
+	smlawb	r4, r11, r8, r6								@ r4 = L_mpy_wx(cosx, t0) + L_mpy_wx(sinx, t1)@
+	smulwb	r7, r10, r8										@ L_mpy_wx(sinx, t0)
+
+	add			r14, r14, r9									@ xptr += step@
+	sub			r5, r5, r7										@ r5 = L_mpy_wx(cosx, t1) - L_mpy_wx(sinx, t0)@
+
+	ldrd		r10, [r14]										@ r6 = xptr[0]@ r7 = xptr[1]@
+	ldr			r8, [r12], #4									@ cosxsinx = csptr[1]@
+
+	smulwt	r2, r10, r8										@ L_mpy_wx(cosx, t0)
+	smulwt	r7, r11, r8										@ L_mpy_wx(cosx, t1)
+
+	smlawb	r6, r11, r8, r2								@ r4 = L_mpy_wx(cosx, t0) + L_mpy_wx(sinx, t1)@
+	smulwb	r3, r10, r8										@ L_mpy_wx(sinx, t0)
+
+	mov			r10, r4												@ t0 = r4@
+	mov			r11, r5												@ t1 = r5@
+
+	sub			r7, r7, r3										@ r5 = L_mpy_wx(cosx, t1) - L_mpy_wx(sinx, t0)@
+
+
+	add			r4,  r10, r6									@	r4 = t0 + r6@
+	sub			r5, r7, r11										@ r5 = r7 - t1@
+
+	sub			r6, r10, r6										@ r6 = t0 - r6@
+	add			r7, r7, r11										@ r7 = r7 + t1@
+
+	ldr			r2, [sp, #24]
+	ldr			r3, [sp, #28]
+
+	add			r10, r0, r5										@ xptr[0] = r0 + r5@
+	add			r11, r1, r6										@ xptr[0] = r1 + r6
+
+	strd		r10, [r14]
+	sub			r14, r14, r9									@ xptr -= step@
+
+	sub			r10, r2, r4										@	xptr[0] = r2 - r4@
+	sub			r11, r3, r7										@ xptr[1] = r3 - r7@
+
+	strd		r10, [r14]
+	sub			r14, r14, r9									@ xptr -= step@
+
+	sub			r10, r0, r5										@ xptr[0] = r0 - r5@
+	sub			r11, r1, r6										@ xptr[0] = r1 - r6
+
+	strd		r10, [r14]
+	sub			r14, r14, r9									@ xptr -= step@
+
+	add			r10, r2, r4										@	xptr[0] = r2 - r4@
+	add			r11, r3, r7										@ xptr[1] = r3 - r7@
+
+	strd		r10, [r14]
+	add			r14, r14, #8									@ xptr += 2@
+
+	ldr			r11, [sp, #20]
+	subs		r11, r11, #1
+	bne			Radix4FFT_LOOP3
+
+Radix4FFT_LOOP2_END:
+	ldr			r10, [sp, #16]
+	ldr			r3, [sp, #12]
+	ldr			r2, [sp, #8]
+	rsb			r8, r9, r9, lsl #2
+	sub			r10, r10, #1
+	add			r14, r14, r8
+	cmp			r10, #0
+	bhi     Radix4FFT_LOOP2
+
+Radix4FFT_LOOP1_END:
+	ldr     r0, [sp]
+	ldr		r1, [sp, #4]
+	add     r3, r3, r8, asr #1
+	mov     r2, r2, lsl #2
+	movs    r1, r1, asr #2
+	bne     Radix4FFT_LOOP1
+
+Radix4FFT_END:
+	add     sp, sp, #32
+	ldmia   sp!, {r4 - r11, pc}
+
+	@ENDP  @ |Radix4FFT|
 	.end
\ No newline at end of file
diff --git a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/band_nrg_v5.s b/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/band_nrg_v5.s
index a463dfd..4789f6d 100644
--- a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/band_nrg_v5.s
+++ b/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/band_nrg_v5.s
@@ -1,204 +1,204 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-

-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

-@	File:		band_nrg_v5.s

-@

-@	Content:	CalcBandEnergy and CalcBandEnergyMS function armv5 assemble

-@

-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

-

-	.section .text

-

-	.global	CalcBandEnergy

-

-CalcBandEnergy:

-	stmdb   sp!, {r4 - r11, lr}	

-                   

-  mov     r2, r2, lsl #16                   

-	ldr     r12, [r13, #36]

-	mov			r9, #0

-  mov     r5, r2, asr #16    

-	mov			r4, #0               

-  cmp     r5, #0	

-	ble     L212 

-

-L22:

-  mov     r2, r4, lsl #1                    

-  ldrsh   r10, [r1, r2]                     

-  add     r11, r1, r2                       

-  ldrsh   r2, [r11, #2]    

-	mov     r14, #0                 

-  cmp     r10, r2                           

-  bge     L28 

-	

-L23:

-	ldr     r11, [r0, +r10, lsl #2]	

-  add     r10, r10, #1    

-	ldr     r6, [r0, +r10, lsl #2]	

-	smull   r11, r7, r11, r11

-	add     r10, r10, #1 

-	smull	  r6, r8, r6, r6

-	ldr     r11, [r0, +r10, lsl #2]

-	qadd	  r14, r14, r7

-	add     r10, r10, #1

-	smull	  r11, r7, r11, r11

-	ldr     r6, [r0, +r10, lsl #2]

-	qadd	  r14, r14, r8

-	smull	  r6, r8, r6, r6

-  add     r10, r10, #1 

-	qadd	  r14, r14, r7

-	cmp     r10, r2

-	qadd	  r14, r14, r8

-	blt     L23   

-

-L28:	

-	qadd	  r14, r14, r14

-	str     r14, [r3, +r4, lsl #2]

-	add     r4, r4, #1 

-	qadd	  r9, r9, r14

-	cmp     r4, r5                          

-

-  blt     L22       	

-

-L212:	

-	str     r9, [r12, #0]                     

-	ldmia   sp!, {r4 - r11, pc}

-	

-	@ENDP  ; |CalcBandEnergy|

-	

-	.global	CalcBandEnergyMS

-

-CalcBandEnergyMS:

-	stmdb   sp!, {r4 - r11, lr}

-	sub     r13, r13, #24

-	

-	mov     r12, #0 

-  mov     r3, r3, lsl #16  

-  mov     r14, #0 

-	mov     r3, r3, asr #16      

-	cmp     r3, #0          

-	mov		  r4, #0                  

-  ble     L315    

-	

-L32:	

-	mov		  r5, r4, lsl #1

-	mov		  r6, #0

-	ldrsh   r10, [r2, r5]

-	add     r5, r2, r5

-	mov		  r7, #0

-	ldrsh	  r11, [r5, #2]                        

-	cmp     r10, r11                          

-  bge     L39    

-

-	str		  r3, [r13, #4]

-	str		  r4, [r13, #8]

-	str		  r12, [r13, #12]

-	str		  r14, [r13, #16]

-

-L33:	

-	ldr     r8, [r0, +r10, lsl #2]                    

-	ldr     r9, [r1, +r10, lsl #2]

-	mov		  r8, r8, asr #1

-	add		  r10, r10, #1

-	mov		  r9, r9, asr #1

-

-	ldr     r12, [r0, +r10, lsl #2]          

-	add		  r5, r8, r9	          

-	ldr     r14, [r1, +r10, lsl #2]

-	sub		  r8, r8, r9

-

-	smull   r5, r3, r5, r5 

-	mov		  r12, r12, asr #1

-	smull   r8, r4, r8, r8 

-	mov		  r14, r14, asr #1

-

-	qadd	  r6, r6, r3

-	add		  r5, r12, r14

-	qadd	  r7, r7, r4

-	sub		  r8, r12, r14

-

-	smull   r5, r3, r5, r5 

-	add		  r10, r10, #1

-	smull   r8, r4, r8, r8 

-		

-	qadd	  r6, r6, r3

-	qadd	  r7, r7, r4

-

-	ldr     r8, [r0, +r10, lsl #2]                    

-	ldr     r9, [r1, +r10, lsl #2]

-	mov		  r8, r8, asr #1

-	add		  r10, r10, #1

-	mov		  r9, r9, asr #1

-

-	ldr     r12, [r0, +r10, lsl #2]          

-	add		  r5, r8, r9	          

-	ldr     r14, [r1, +r10, lsl #2]

-	sub		  r8, r8, r9

-

-	smull   r5, r3, r5, r5 

-	mov		  r12, r12, asr #1

-	smull   r8, r4, r8, r8 

-	mov		  r14, r14, asr #1

-

-	qadd	  r6, r6, r3

-	add		  r5, r12, r14

-	qadd	  r7, r7, r4

-	sub		  r8, r12, r14

-

-	smull   r5, r3, r5, r5 

-	add		  r10, r10, #1

-	smull   r8, r4, r8, r8 

-		

-	qadd	  r6, r6, r3

-	qadd	  r7, r7, r4

-

-	cmp     r10, r11

-	

-	blt		  L33

-

-	ldr		  r3, [r13, #4]

-	ldr		  r4, [r13, #8]	

-	ldr		  r12, [r13, #12]

-	ldr		  r14, [r13, #16]

-L39:	

-	qadd	  r6, r6, r6

-	qadd	  r7, r7, r7	

-	

-	ldr		  r8, [r13, #60]

-	ldr		  r9, [r13, #68]

-

-	qadd	  r12, r12, r6

-	qadd	  r14, r14, r7

-	

-	str		  r6, [r8, +r4, lsl #2]       

-	str     r7, [r9, +r4, lsl #2]    

-	

-	add		  r4, r4, #1

-	cmp		  r4, r3

-	blt     L32            

-

-L315:

-	ldr		  r8, [r13, #64]

-	ldr		  r9, [r13, #72]

-	str		  r12, [r8, #0]

-	str		  r14, [r9, #0]

-

-	add     r13, r13, #24

-	ldmia   sp!, {r4 - r11, pc}

-	@ENDP  ; |CalcBandEnergyMS|

-

-	.end

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+
+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+@	File:		band_nrg_v5.s
+@
+@	Content:	CalcBandEnergy and CalcBandEnergyMS function armv5 assemble
+@
+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+
+	.section .text
+
+	.global	CalcBandEnergy
+
+CalcBandEnergy:
+	stmdb   sp!, {r4 - r11, lr}
+
+  mov     r2, r2, lsl #16
+	ldr     r12, [r13, #36]
+	mov			r9, #0
+  mov     r5, r2, asr #16
+	mov			r4, #0
+  cmp     r5, #0
+	ble     L212
+
+L22:
+  mov     r2, r4, lsl #1
+  ldrsh   r10, [r1, r2]
+  add     r11, r1, r2
+  ldrsh   r2, [r11, #2]
+	mov     r14, #0
+  cmp     r10, r2
+  bge     L28
+
+L23:
+	ldr     r11, [r0, +r10, lsl #2]
+  add     r10, r10, #1
+	ldr     r6, [r0, +r10, lsl #2]
+	smull   r11, r7, r11, r11
+	add     r10, r10, #1
+	smull	  r6, r8, r6, r6
+	ldr     r11, [r0, +r10, lsl #2]
+	qadd	  r14, r14, r7
+	add     r10, r10, #1
+	smull	  r11, r7, r11, r11
+	ldr     r6, [r0, +r10, lsl #2]
+	qadd	  r14, r14, r8
+	smull	  r6, r8, r6, r6
+  add     r10, r10, #1
+	qadd	  r14, r14, r7
+	cmp     r10, r2
+	qadd	  r14, r14, r8
+	blt     L23
+
+L28:
+	qadd	  r14, r14, r14
+	str     r14, [r3, +r4, lsl #2]
+	add     r4, r4, #1
+	qadd	  r9, r9, r14
+	cmp     r4, r5
+
+  blt     L22
+
+L212:
+	str     r9, [r12, #0]
+	ldmia   sp!, {r4 - r11, pc}
+
+	@ENDP  ; |CalcBandEnergy|
+
+	.global	CalcBandEnergyMS
+
+CalcBandEnergyMS:
+	stmdb   sp!, {r4 - r11, lr}
+	sub     r13, r13, #24
+
+	mov     r12, #0
+  mov     r3, r3, lsl #16
+  mov     r14, #0
+	mov     r3, r3, asr #16
+	cmp     r3, #0
+	mov		  r4, #0
+  ble     L315
+
+L32:
+	mov		  r5, r4, lsl #1
+	mov		  r6, #0
+	ldrsh   r10, [r2, r5]
+	add     r5, r2, r5
+	mov		  r7, #0
+	ldrsh	  r11, [r5, #2]
+	cmp     r10, r11
+  bge     L39
+
+	str		  r3, [r13, #4]
+	str		  r4, [r13, #8]
+	str		  r12, [r13, #12]
+	str		  r14, [r13, #16]
+
+L33:
+	ldr     r8, [r0, +r10, lsl #2]
+	ldr     r9, [r1, +r10, lsl #2]
+	mov		  r8, r8, asr #1
+	add		  r10, r10, #1
+	mov		  r9, r9, asr #1
+
+	ldr     r12, [r0, +r10, lsl #2]
+	add		  r5, r8, r9
+	ldr     r14, [r1, +r10, lsl #2]
+	sub		  r8, r8, r9
+
+	smull   r5, r3, r5, r5
+	mov		  r12, r12, asr #1
+	smull   r8, r4, r8, r8
+	mov		  r14, r14, asr #1
+
+	qadd	  r6, r6, r3
+	add		  r5, r12, r14
+	qadd	  r7, r7, r4
+	sub		  r8, r12, r14
+
+	smull   r5, r3, r5, r5
+	add		  r10, r10, #1
+	smull   r8, r4, r8, r8
+
+	qadd	  r6, r6, r3
+	qadd	  r7, r7, r4
+
+	ldr     r8, [r0, +r10, lsl #2]
+	ldr     r9, [r1, +r10, lsl #2]
+	mov		  r8, r8, asr #1
+	add		  r10, r10, #1
+	mov		  r9, r9, asr #1
+
+	ldr     r12, [r0, +r10, lsl #2]
+	add		  r5, r8, r9
+	ldr     r14, [r1, +r10, lsl #2]
+	sub		  r8, r8, r9
+
+	smull   r5, r3, r5, r5
+	mov		  r12, r12, asr #1
+	smull   r8, r4, r8, r8
+	mov		  r14, r14, asr #1
+
+	qadd	  r6, r6, r3
+	add		  r5, r12, r14
+	qadd	  r7, r7, r4
+	sub		  r8, r12, r14
+
+	smull   r5, r3, r5, r5
+	add		  r10, r10, #1
+	smull   r8, r4, r8, r8
+
+	qadd	  r6, r6, r3
+	qadd	  r7, r7, r4
+
+	cmp     r10, r11
+
+	blt		  L33
+
+	ldr		  r3, [r13, #4]
+	ldr		  r4, [r13, #8]
+	ldr		  r12, [r13, #12]
+	ldr		  r14, [r13, #16]
+L39:
+	qadd	  r6, r6, r6
+	qadd	  r7, r7, r7
+
+	ldr		  r8, [r13, #60]
+	ldr		  r9, [r13, #68]
+
+	qadd	  r12, r12, r6
+	qadd	  r14, r14, r7
+
+	str		  r6, [r8, +r4, lsl #2]
+	str     r7, [r9, +r4, lsl #2]
+
+	add		  r4, r4, #1
+	cmp		  r4, r3
+	blt     L32
+
+L315:
+	ldr		  r8, [r13, #64]
+	ldr		  r9, [r13, #72]
+	str		  r12, [r8, #0]
+	str		  r14, [r9, #0]
+
+	add     r13, r13, #24
+	ldmia   sp!, {r4 - r11, pc}
+	@ENDP  ; |CalcBandEnergyMS|
+
+	.end
diff --git a/media/libstagefright/codecs/aacenc/src/asm/ARMV7/PrePostMDCT_v7.s b/media/libstagefright/codecs/aacenc/src/asm/ARMV7/PrePostMDCT_v7.s
index bf7dcbad..64d767a 100644
--- a/media/libstagefright/codecs/aacenc/src/asm/ARMV7/PrePostMDCT_v7.s
+++ b/media/libstagefright/codecs/aacenc/src/asm/ARMV7/PrePostMDCT_v7.s
@@ -1,135 +1,135 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-

-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

-@	File:		PrePostMDCT_v7.s

-@

-@	Content:	premdct and postmdct function armv7 assemble

-@

-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

-

-	.section .text

-	.global	PreMDCT

-

-PreMDCT:

-	stmdb     sp!, {r4 - r11, lr}

-	

-	add         r9, r0, r1, lsl #2

-	sub         r3, r9, #32

-

-	movs        r1, r1, asr #2

-	beq         PreMDCT_END	

-	

-PreMDCT_LOOP:

-	VLD4.I32			{d0, d2, d4, d6}, [r2]!				@ cosa = *csptr++@ sina = *csptr++@

-	VLD4.I32			{d1, d3, d5, d7}, [r2]!				@ cosb = *csptr++@ sinb = *csptr++@

-	VLD2.I32			{d8, d9, d10, d11}, [r0]			@ tr1 = *(buf0 + 0)@ ti2 = *(buf0 + 1)@

-	VLD2.I32			{d13, d15}, [r3]!					@ tr2 = *(buf1 - 1)@ ti1 = *(buf1 + 0)@

-	VLD2.I32			{d12, d14}, [r3]!					@ tr2 = *(buf1 - 1)@ ti1 = *(buf1 + 0)@

-		

-	VREV64.32			Q8, Q7	

-	VREV64.32			Q9, Q6

-

-	

-	VQDMULH.S32		Q10, Q0, Q4								@ MULHIGH(cosa, tr1)

-	VQDMULH.S32		Q11, Q1, Q8								@ MULHIGH(sina, ti1)

-	VQDMULH.S32		Q12, Q0, Q8								@ MULHIGH(cosa, ti1)

-	VQDMULH.S32		Q13, Q1, Q4								@ MULHIGH(sina, tr1)

-		

-	VADD.S32			Q0, Q10, Q11						@ *buf0++ = MULHIGH(cosa, tr1) + MULHIGH(sina, ti1)@

-	VSUB.S32			Q1, Q12, Q13						@ *buf0++ = MULHIGH(cosa, ti1) - MULHIGH(sina, tr1)@

-	

-	VST2.I32			{d0, d1, d2, d3}, [r0]!

-	sub						r3, r3, #32

-	

-	VQDMULH.S32		Q10, Q2, Q9										@ MULHIGH(cosb, tr2)

-	VQDMULH.S32		Q11, Q3, Q5										@ MULHIGH(sinb, ti2)

-	VQDMULH.S32		Q12, Q2, Q5										@ MULHIGH(cosb, ti2)

-	VQDMULH.S32		Q13, Q3, Q9										@ MULHIGH(sinb, tr2)

-		

-	VADD.S32			Q0, Q10, Q11									@ MULHIGH(cosa, tr2) + MULHIGH(sina, ti2)@

-	VSUB.S32			Q1, Q12, Q13									@ MULHIGH(cosa, ti2) - MULHIGH(sina, tr2)@

-	

-	VREV64.32			Q3, Q1

-	VREV64.32			Q2, Q0

-		

-	VST2.I32		{d5, d7}, [r3]!	

-	VST2.I32		{d4, d6}, [r3]! 

-	

-	subs     		r1, r1, #4

-	sub		  		r3, r3, #64	

-	bne       	PreMDCT_LOOP

-	

-PreMDCT_END:

-	ldmia     sp!, {r4 - r11, pc}

-	@ENDP  @ |PreMDCT|

-

-	.section .text

-	.global	PostMDCT

-

-PostMDCT:

-	stmdb     sp!, {r4 - r11, lr}

-	

-	add         r9, r0, r1, lsl #2

-	sub         r3, r9, #32

-

-	movs        r1, r1, asr #2

-	beq         PostMDCT_END

-	

-PostMDCT_LOOP:

-	VLD4.I32			{d0, d2, d4, d6}, [r2]!				@ cosa = *csptr++@ sina = *csptr++@

-	VLD4.I32			{d1, d3, d5, d7}, [r2]!				@ cosb = *csptr++@ sinb = *csptr++@

-	VLD2.I32			{d8, d9, d10, d11}, [r0]			@ tr1 = *(zbuf1 + 0)@ ti1 = *(zbuf1 + 1)@

-	VLD2.I32			{d13, d15}, [r3]!							@ tr2 = *(zbuf2 - 1)@ ti2 = *(zbuf2 + 0)@

-	VLD2.I32			{d12, d14}, [r3]!							@ tr2 = *(zbuf2 - 1)@ ti2 = *(zbuf2 + 0)@	

-

-	VREV64.32			Q8, Q6	

-	VREV64.32			Q9, Q7			

-	

-	VQDMULH.S32		Q10, Q0, Q4										@ MULHIGH(cosa, tr1)

-	VQDMULH.S32		Q11, Q1, Q5										@ MULHIGH(sina, ti1)

-	VQDMULH.S32		Q12, Q0, Q5										@ MULHIGH(cosa, ti1)

-	VQDMULH.S32		Q13, Q1, Q4										@ MULHIGH(sina, tr1)

-		

-	VADD.S32			Q0, Q10, Q11									@ *buf0++ = MULHIGH(cosa, tr1) + MULHIGH(sina, ti1)@

-	VSUB.S32			Q5, Q13, Q12									@ *buf1-- = MULHIGH(sina, tr1) - MULHIGH(cosa, ti1)@

-	

-	VQDMULH.S32		Q10, Q2, Q8										@ MULHIGH(cosb, tr2)

-	VQDMULH.S32		Q11, Q3, Q9										@ MULHIGH(sinb, ti2)

-	VQDMULH.S32		Q12, Q2, Q9										@ MULHIGH(cosb, ti2)

-	VQDMULH.S32		Q13, Q3, Q8										@ MULHIGH(sinb, tr2)

-		

-	VADD.S32			Q4, Q10, Q11									@ *buf1-- = MULHIGH(cosa, tr2) + MULHIGH(sina, ti2)@

-	VSUB.S32			Q1, Q13, Q12									@ *buf0++ = MULHIGH(sina, tr2) - MULHIGH(cosa, ti2)@	

-	

-	VREV64.32			Q2, Q4

-	VREV64.32			Q3, Q5	

-	

-	sub						r3, r3, #32	

-	VST2.I32			{d0, d1, d2, d3}, [r0]!

-		

-	VST2.I32			{d5, d7}, [r3]!	

-	VST2.I32			{d4, d6}, [r3]! 

-	

-	subs     			r1, r1, #4

-	sub		  			r3, r3, #64		

-	bne       	PostMDCT_LOOP

-

-PostMDCT_END:

-	ldmia     sp!, {r4 - r11, pc}

-

-	@ENDP  		@ |PostMDCT|

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+
+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+@	File:		PrePostMDCT_v7.s
+@
+@	Content:	premdct and postmdct function armv7 assemble
+@
+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+
+	.section .text
+	.global	PreMDCT
+
+PreMDCT:
+	stmdb     sp!, {r4 - r11, lr}
+
+	add         r9, r0, r1, lsl #2
+	sub         r3, r9, #32
+
+	movs        r1, r1, asr #2
+	beq         PreMDCT_END
+
+PreMDCT_LOOP:
+	VLD4.I32			{d0, d2, d4, d6}, [r2]!				@ cosa = *csptr++@ sina = *csptr++@
+	VLD4.I32			{d1, d3, d5, d7}, [r2]!				@ cosb = *csptr++@ sinb = *csptr++@
+	VLD2.I32			{d8, d9, d10, d11}, [r0]			@ tr1 = *(buf0 + 0)@ ti2 = *(buf0 + 1)@
+	VLD2.I32			{d13, d15}, [r3]!					@ tr2 = *(buf1 - 1)@ ti1 = *(buf1 + 0)@
+	VLD2.I32			{d12, d14}, [r3]!					@ tr2 = *(buf1 - 1)@ ti1 = *(buf1 + 0)@
+
+	VREV64.32			Q8, Q7
+	VREV64.32			Q9, Q6
+
+
+	VQDMULH.S32		Q10, Q0, Q4								@ MULHIGH(cosa, tr1)
+	VQDMULH.S32		Q11, Q1, Q8								@ MULHIGH(sina, ti1)
+	VQDMULH.S32		Q12, Q0, Q8								@ MULHIGH(cosa, ti1)
+	VQDMULH.S32		Q13, Q1, Q4								@ MULHIGH(sina, tr1)
+
+	VADD.S32			Q0, Q10, Q11						@ *buf0++ = MULHIGH(cosa, tr1) + MULHIGH(sina, ti1)@
+	VSUB.S32			Q1, Q12, Q13						@ *buf0++ = MULHIGH(cosa, ti1) - MULHIGH(sina, tr1)@
+
+	VST2.I32			{d0, d1, d2, d3}, [r0]!
+	sub						r3, r3, #32
+
+	VQDMULH.S32		Q10, Q2, Q9										@ MULHIGH(cosb, tr2)
+	VQDMULH.S32		Q11, Q3, Q5										@ MULHIGH(sinb, ti2)
+	VQDMULH.S32		Q12, Q2, Q5										@ MULHIGH(cosb, ti2)
+	VQDMULH.S32		Q13, Q3, Q9										@ MULHIGH(sinb, tr2)
+
+	VADD.S32			Q0, Q10, Q11									@ MULHIGH(cosa, tr2) + MULHIGH(sina, ti2)@
+	VSUB.S32			Q1, Q12, Q13									@ MULHIGH(cosa, ti2) - MULHIGH(sina, tr2)@
+
+	VREV64.32			Q3, Q1
+	VREV64.32			Q2, Q0
+
+	VST2.I32		{d5, d7}, [r3]!
+	VST2.I32		{d4, d6}, [r3]!
+
+	subs     		r1, r1, #4
+	sub		  		r3, r3, #64
+	bne       	PreMDCT_LOOP
+
+PreMDCT_END:
+	ldmia     sp!, {r4 - r11, pc}
+	@ENDP  @ |PreMDCT|
+
+	.section .text
+	.global	PostMDCT
+
+PostMDCT:
+	stmdb     sp!, {r4 - r11, lr}
+
+	add         r9, r0, r1, lsl #2
+	sub         r3, r9, #32
+
+	movs        r1, r1, asr #2
+	beq         PostMDCT_END
+
+PostMDCT_LOOP:
+	VLD4.I32			{d0, d2, d4, d6}, [r2]!				@ cosa = *csptr++@ sina = *csptr++@
+	VLD4.I32			{d1, d3, d5, d7}, [r2]!				@ cosb = *csptr++@ sinb = *csptr++@
+	VLD2.I32			{d8, d9, d10, d11}, [r0]			@ tr1 = *(zbuf1 + 0)@ ti1 = *(zbuf1 + 1)@
+	VLD2.I32			{d13, d15}, [r3]!							@ tr2 = *(zbuf2 - 1)@ ti2 = *(zbuf2 + 0)@
+	VLD2.I32			{d12, d14}, [r3]!							@ tr2 = *(zbuf2 - 1)@ ti2 = *(zbuf2 + 0)@
+
+	VREV64.32			Q8, Q6
+	VREV64.32			Q9, Q7
+
+	VQDMULH.S32		Q10, Q0, Q4										@ MULHIGH(cosa, tr1)
+	VQDMULH.S32		Q11, Q1, Q5										@ MULHIGH(sina, ti1)
+	VQDMULH.S32		Q12, Q0, Q5										@ MULHIGH(cosa, ti1)
+	VQDMULH.S32		Q13, Q1, Q4										@ MULHIGH(sina, tr1)
+
+	VADD.S32			Q0, Q10, Q11									@ *buf0++ = MULHIGH(cosa, tr1) + MULHIGH(sina, ti1)@
+	VSUB.S32			Q5, Q13, Q12									@ *buf1-- = MULHIGH(sina, tr1) - MULHIGH(cosa, ti1)@
+
+	VQDMULH.S32		Q10, Q2, Q8										@ MULHIGH(cosb, tr2)
+	VQDMULH.S32		Q11, Q3, Q9										@ MULHIGH(sinb, ti2)
+	VQDMULH.S32		Q12, Q2, Q9										@ MULHIGH(cosb, ti2)
+	VQDMULH.S32		Q13, Q3, Q8										@ MULHIGH(sinb, tr2)
+
+	VADD.S32			Q4, Q10, Q11									@ *buf1-- = MULHIGH(cosa, tr2) + MULHIGH(sina, ti2)@
+	VSUB.S32			Q1, Q13, Q12									@ *buf0++ = MULHIGH(sina, tr2) - MULHIGH(cosa, ti2)@
+
+	VREV64.32			Q2, Q4
+	VREV64.32			Q3, Q5
+
+	sub						r3, r3, #32
+	VST2.I32			{d0, d1, d2, d3}, [r0]!
+
+	VST2.I32			{d5, d7}, [r3]!
+	VST2.I32			{d4, d6}, [r3]!
+
+	subs     			r1, r1, #4
+	sub		  			r3, r3, #64
+	bne       	PostMDCT_LOOP
+
+PostMDCT_END:
+	ldmia     sp!, {r4 - r11, pc}
+
+	@ENDP  		@ |PostMDCT|
 	.end
\ No newline at end of file
diff --git a/media/libstagefright/codecs/aacenc/src/asm/ARMV7/R4R8First_v7.s b/media/libstagefright/codecs/aacenc/src/asm/ARMV7/R4R8First_v7.s
index 99ee68b..7fc5520 100644
--- a/media/libstagefright/codecs/aacenc/src/asm/ARMV7/R4R8First_v7.s
+++ b/media/libstagefright/codecs/aacenc/src/asm/ARMV7/R4R8First_v7.s
@@ -1,146 +1,146 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-

-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

-@	File:		R4R8First_v7.s

-@

-@	Content:	Radix8First and Radix4First function armv7 assemble

-@

-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

-

-	.section .text

-	.global	Radix8First

-

-Radix8First:

-	stmdb     		sp!, {r4 - r11, lr}

-

-	ldr       		r3, SQRT1_2

-	cmp       		r1, #0

-	

-	VDUP.I32  		Q15, r3	

-	beq       		Radix8First_END

-	

-Radix8First_LOOP:

-	VLD1.I32			{d0, d1, d2, d3},	[r0]!

-	VLD1.I32			{d8, d9, d10, d11},	[r0]!

-		

-	VADD.S32			d4, d0, d1		@ r0 = buf[0] + buf[2]@i0 = buf[1] + buf[3]@

-	VSUB.S32			d5, d0, d1		@ r1 = buf[0] - buf[2]@i1 = buf[1] - buf[3]@	

-	VSUB.S32			d7, d2, d3		@ r2 = buf[4] - buf[6]@i2 = buf[5] - buf[7]@	

-	VADD.S32			d6, d2, d3		@ r3 = buf[4] + buf[6]@i3 = buf[5] + buf[7]@

-	VREV64.I32			d7, d7	

-	

-	VADD.S32			Q0, Q2, Q3		@ r4 = (r0 + r2)@i4 = (i0 + i2)@i6 = (i1 + r3)@r7 = (r1 + i3)

-	VSUB.S32			Q1, Q2, Q3		@ r5 = (r0 - r2)@i5 = (i0 - i2)@r6 = (r1 - i3)@i7 = (i1 - r3)@

-

-	VREV64.I32			d3, d3	

-

-	VADD.S32			d4, d8, d9		@ r0 = buf[ 8] + buf[10]@i0 = buf[ 9] + buf[11]@

-	VSUB.S32			d7, d10, d11	@ r1 = buf[12] - buf[14]@i1 = buf[13] - buf[15]@	

-	VADD.S32			d6, d10, d11	@ r2 = buf[12] + buf[14]@i2 = buf[13] + buf[15]@

-	VREV64.I32			d7, d7	

-	VSUB.S32			d5, d8, d9		@ r3 = buf[ 8] - buf[10]@i3 = buf[ 9] - buf[11]@

-	

-	VTRN.32				d1, d3	

-	

-	VADD.S32			Q4, Q2, Q3		@ t0 = (r0 + r2) >> 1@t1 = (i0 + i2) >> 1@i0 = i1 + r3@r2 = r1 + i3@

-	VSUB.S32			Q5, Q2, Q3		@ t2 = (r0 - r2) >> 1@t3 = (i0 - i2) >> 1@r0 = r1 - i3@i2 = i1 - r3@

-	

-	VREV64.I32			d3, d3

-	

-	VSHR.S32			d8, d8, #1		 

-	VSHR.S32			Q0, Q0, #1

-	VREV64.I32			d10, d10

-	VTRN.32				d11, d9

-	VSHR.S32			Q1, Q1, #1

-	VSHR.S32			d10, d10, #1

-	VREV64.I32			d9, d9

-	

-	sub       			r0, r0, #0x40

-	

-	VADD.S32			d12, d0, d8

-	VSUB.S32			d16, d0, d8	

-	VADD.S32			d14, d2, d10

-	VSUB.S32			d18, d2, d10

-	

-	VSUB.S32			d4, d11, d9

-	VADD.S32			d5, d11, d9

-	

-	VREV64.I32			d18, d18

-	

-	VQDMULH.S32			Q3, Q2, Q15

-	VTRN.32				d14, d18

-	VTRN.32				d6, d7

-	VREV64.I32			d18, d18	

-	

-	VSUB.S32			d15, d3, d6

-	VREV64.I32			d7, d7

-	VADD.S32			d19, d3, d6

-	VADD.S32			d13, d1, d7

-	VSUB.S32			d17, d1, d7

-	

-	VREV64.I32			d17, d17

-	VTRN.32				d13, d17

-	VREV64.I32			d17, d17

-	

-	subs       			r1, r1, #1	

-	

-	VST1.I32			{d12, d13, d14, d15}, [r0]!

-	VST1.I32			{d16, d17, d18, d19}, [r0]!	

-	bne       			Radix8First_LOOP

-	

-Radix8First_END:

-	ldmia     sp!, {r4 - r11, pc}	

-SQRT1_2:

-	.word      0x2d413ccd

-	

-	@ENDP  @ |Radix8First|

-	

-	.section .text

-	.global	Radix4First

-

-Radix4First:

-	stmdb     	sp!, {r4 - r11, lr}

-

-	cmp       	r1, #0

-	beq       	Radix4First_END

-	

-Radix4First_LOOP:

-	VLD1.I32			{d0, d1, d2, d3}, [r0]					

-	

-	VADD.S32			d4, d0, d1							@ r0 = buf[0] + buf[2]@ r1 = buf[1] + buf[3]@		

-	VSUB.S32			d5, d0, d1							@ r2 = buf[0] - buf[2]@ r3 = buf[1] - buf[3]@

-	VSUB.S32			d7, d2, d3							@ r4 = buf[4] + buf[6]@ r5 = buf[5] + buf[7]@

-	VADD.S32			d6, d2, d3							@ r6 = buf[4] - buf[6]@ r7 = buf[5] - buf[7]@

-	

-	VREV64.I32		d7, d7									@ 

-	

-	VADD.S32			Q4, Q2, Q3

-	VSUB.S32			Q5, Q2, Q3

-	

-	VREV64.I32		d11, d11

-	VTRN.32				d9, d11

-	subs       		r1, r1, #1	

-	VREV64.I32		d11, d11

-	VST1.I32			{d8, d9, d10, d11}, [r0]!

-

-	bne       		Radix4First_LOOP

-	

-Radix4First_END:

-	ldmia    		sp!, {r4 - r11, pc}

-

-	@ENDP  @ |Radix4First|

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+
+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+@	File:		R4R8First_v7.s
+@
+@	Content:	Radix8First and Radix4First function armv7 assemble
+@
+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+
+	.section .text
+	.global	Radix8First
+
+Radix8First:
+	stmdb     		sp!, {r4 - r11, lr}
+
+	ldr       		r3, SQRT1_2
+	cmp       		r1, #0
+
+	VDUP.I32  		Q15, r3
+	beq       		Radix8First_END
+
+Radix8First_LOOP:
+	VLD1.I32			{d0, d1, d2, d3},	[r0]!
+	VLD1.I32			{d8, d9, d10, d11},	[r0]!
+
+	VADD.S32			d4, d0, d1		@ r0 = buf[0] + buf[2]@i0 = buf[1] + buf[3]@
+	VSUB.S32			d5, d0, d1		@ r1 = buf[0] - buf[2]@i1 = buf[1] - buf[3]@
+	VSUB.S32			d7, d2, d3		@ r2 = buf[4] - buf[6]@i2 = buf[5] - buf[7]@
+	VADD.S32			d6, d2, d3		@ r3 = buf[4] + buf[6]@i3 = buf[5] + buf[7]@
+	VREV64.I32			d7, d7
+
+	VADD.S32			Q0, Q2, Q3		@ r4 = (r0 + r2)@i4 = (i0 + i2)@i6 = (i1 + r3)@r7 = (r1 + i3)
+	VSUB.S32			Q1, Q2, Q3		@ r5 = (r0 - r2)@i5 = (i0 - i2)@r6 = (r1 - i3)@i7 = (i1 - r3)@
+
+	VREV64.I32			d3, d3
+
+	VADD.S32			d4, d8, d9		@ r0 = buf[ 8] + buf[10]@i0 = buf[ 9] + buf[11]@
+	VSUB.S32			d7, d10, d11	@ r1 = buf[12] - buf[14]@i1 = buf[13] - buf[15]@
+	VADD.S32			d6, d10, d11	@ r2 = buf[12] + buf[14]@i2 = buf[13] + buf[15]@
+	VREV64.I32			d7, d7
+	VSUB.S32			d5, d8, d9		@ r3 = buf[ 8] - buf[10]@i3 = buf[ 9] - buf[11]@
+
+	VTRN.32				d1, d3
+
+	VADD.S32			Q4, Q2, Q3		@ t0 = (r0 + r2) >> 1@t1 = (i0 + i2) >> 1@i0 = i1 + r3@r2 = r1 + i3@
+	VSUB.S32			Q5, Q2, Q3		@ t2 = (r0 - r2) >> 1@t3 = (i0 - i2) >> 1@r0 = r1 - i3@i2 = i1 - r3@
+
+	VREV64.I32			d3, d3
+
+	VSHR.S32			d8, d8, #1
+	VSHR.S32			Q0, Q0, #1
+	VREV64.I32			d10, d10
+	VTRN.32				d11, d9
+	VSHR.S32			Q1, Q1, #1
+	VSHR.S32			d10, d10, #1
+	VREV64.I32			d9, d9
+
+	sub       			r0, r0, #0x40
+
+	VADD.S32			d12, d0, d8
+	VSUB.S32			d16, d0, d8
+	VADD.S32			d14, d2, d10
+	VSUB.S32			d18, d2, d10
+
+	VSUB.S32			d4, d11, d9
+	VADD.S32			d5, d11, d9
+
+	VREV64.I32			d18, d18
+
+	VQDMULH.S32			Q3, Q2, Q15
+	VTRN.32				d14, d18
+	VTRN.32				d6, d7
+	VREV64.I32			d18, d18
+
+	VSUB.S32			d15, d3, d6
+	VREV64.I32			d7, d7
+	VADD.S32			d19, d3, d6
+	VADD.S32			d13, d1, d7
+	VSUB.S32			d17, d1, d7
+
+	VREV64.I32			d17, d17
+	VTRN.32				d13, d17
+	VREV64.I32			d17, d17
+
+	subs       			r1, r1, #1
+
+	VST1.I32			{d12, d13, d14, d15}, [r0]!
+	VST1.I32			{d16, d17, d18, d19}, [r0]!
+	bne       			Radix8First_LOOP
+
+Radix8First_END:
+	ldmia     sp!, {r4 - r11, pc}
+SQRT1_2:
+	.word      0x2d413ccd
+
+	@ENDP  @ |Radix8First|
+
+	.section .text
+	.global	Radix4First
+
+Radix4First:
+	stmdb     	sp!, {r4 - r11, lr}
+
+	cmp       	r1, #0
+	beq       	Radix4First_END
+
+Radix4First_LOOP:
+	VLD1.I32			{d0, d1, d2, d3}, [r0]
+
+	VADD.S32			d4, d0, d1							@ r0 = buf[0] + buf[2]@ r1 = buf[1] + buf[3]@
+	VSUB.S32			d5, d0, d1							@ r2 = buf[0] - buf[2]@ r3 = buf[1] - buf[3]@
+	VSUB.S32			d7, d2, d3							@ r4 = buf[4] + buf[6]@ r5 = buf[5] + buf[7]@
+	VADD.S32			d6, d2, d3							@ r6 = buf[4] - buf[6]@ r7 = buf[5] - buf[7]@
+
+	VREV64.I32		d7, d7									@
+
+	VADD.S32			Q4, Q2, Q3
+	VSUB.S32			Q5, Q2, Q3
+
+	VREV64.I32		d11, d11
+	VTRN.32				d9, d11
+	subs       		r1, r1, #1
+	VREV64.I32		d11, d11
+	VST1.I32			{d8, d9, d10, d11}, [r0]!
+
+	bne       		Radix4First_LOOP
+
+Radix4First_END:
+	ldmia    		sp!, {r4 - r11, pc}
+
+	@ENDP  @ |Radix4First|
 	.end
\ No newline at end of file
diff --git a/media/libstagefright/codecs/aacenc/src/asm/ARMV7/Radix4FFT_v7.s b/media/libstagefright/codecs/aacenc/src/asm/ARMV7/Radix4FFT_v7.s
index e1a8438..b8655ae 100644
--- a/media/libstagefright/codecs/aacenc/src/asm/ARMV7/Radix4FFT_v7.s
+++ b/media/libstagefright/codecs/aacenc/src/asm/ARMV7/Radix4FFT_v7.s
@@ -1,143 +1,143 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-

-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

-@	File:		Radix4FFT_v7.s

-@

-@	Content:	Radix4FFT armv7 assemble

-@

-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

-

-	.section .text

-	.global	Radix4FFT

-

-Radix4FFT:

-	stmdb    sp!, {r4 - r11, lr}

-

-	mov			r1, r1, asr #2

-	cmp     	r1, #0                            

-	beq     	Radix4FFT_END                            

-                        

-Radix4FFT_LOOP1:                         

-	mov     	r5, r2, lsl #1  

-	mov     	r8, r0          

-	mov     	r7, r1  

-	mov     	r5, r5, lsl #2   

-	cmp     	r1, #0          

-	rsbeq   	r12, r5, r5, lsl #2 

-	beq     	Radix4FFT_LOOP1_END              

-                         

-	rsb     	r12, r5, r5, lsl #2   

-	 

-Radix4FFT_LOOP2:                        

-	mov     	r6, r3 

-	mov     	r4, r2  

-	cmp     	r2, #0        

-	beq     	Radix4FFT_LOOP2_END         

-  

-Radix4FFT_LOOP3:                          

-	@r0 = xptr[0]@

-	@r1 = xptr[1]@

-	VLD2.I32			{D0, D1, D2, D3}, [r8]				

-	VLD2.I32			{D28, D29, D30, D31}, [r6]!		@ cosx = csptr[0]@ sinx = csptr[1]@

-	

-	add					r8, r8, r5										@ xptr += step@	

-	VLD2.I32			{D4, D5, D6,D7}, [r8]					@ r2 = xptr[0]@ r3 = xptr[1]@

-	

-	VQDMULH.S32		Q10, Q2, Q14									@ MULHIGH(cosx, t0)

-	VQDMULH.S32		Q11, Q3, Q15									@ MULHIGH(sinx, t1)

-	VQDMULH.S32		Q12, Q3, Q14									@ MULHIGH(cosx, t1)

-	VQDMULH.S32		Q13, Q2, Q15									@ MULHIGH(sinx, t0)

-		

-	VADD.S32			Q2, Q10, Q11									@ MULHIGH(cosx, t0) + MULHIGH(sinx, t1)

-	VSUB.S32			Q3, Q12, Q13									@ MULHIGH(cosx, t1) - MULHIGH(sinx, t0)

-	

-	add					r8, r8, r5										@ xptr += step@

-	VSHR.S32			Q10, Q0, #2										@ t0 = r0 >> 2@

-	VSHR.S32			Q11, Q1, #2										@ t1 = r1 >> 2@

-	

-	VSUB.S32			Q0,	Q10, Q2										@ r0 = t0 - r2@

-	VSUB.S32			Q1,	Q11, Q3										@ r1 = t1 - r3@

-	VADD.S32			Q2, Q10, Q2										@ r2 = t0 + r2@

-	VADD.S32			Q3, Q11, Q3										@ r3 = t1 + r3@

-		

-	VLD2.I32			{D8, D9, D10, D11}, [r8]	

-	VLD2.I32			{D28, D29, D30, D31}, [r6]!	

-	add						r8, r8, r5

-

-	VQDMULH.S32		Q10, Q4, Q14									@ MULHIGH(cosx, t0)

-	VQDMULH.S32		Q11, Q5, Q15									@ MULHIGH(sinx, t1)

-	VQDMULH.S32		Q12, Q5, Q14									@ MULHIGH(cosx, t1)

-	VQDMULH.S32		Q13, Q4, Q15									@ MULHIGH(sinx, t0)

-		

-	VADD.S32			Q8, Q10, Q11									@ MULHIGH(cosx, t0) + MULHIGH(sinx, t1)

-	VSUB.S32			Q9, Q12, Q13									@ MULHIGH(cosx, t1) - MULHIGH(sinx, t0)	

-	

-	VLD2.I32		{D12, D13, D14, D15}, [r8]	

-	VLD2.I32		{D28, D29, D30, D31}, [r6]!

-	

-	VQDMULH.S32		Q10, Q6, Q14									@ MULHIGH(cosx, t0)

-	VQDMULH.S32		Q11, Q7, Q15									@ MULHIGH(sinx, t1)

-	VQDMULH.S32		Q12, Q7, Q14									@ MULHIGH(cosx, t1)

-	VQDMULH.S32		Q13, Q6, Q15									@ MULHIGH(sinx, t0)

-		

-	VADD.S32			Q6, Q10, Q11									@ MULHIGH(cosx, t0) + MULHIGH(sinx, t1)

-	VSUB.S32			Q7, Q12, Q13									@ MULHIGH(cosx, t1) - MULHIGH(sinx, t0)		

-	

-	VADD.S32			Q4, Q8, Q6										@ r4 = t0 + r6@

-	VSUB.S32			Q5, Q7, Q9										@ r5 = r7 - t1@

-	VSUB.S32			Q6, Q8, Q6										@ r6 = t0 - r6@

-	VADD.S32			Q7, Q7, Q9										@ r7 = r7 + t1@

-	

-	VADD.S32			Q8, Q0, Q5										@ xptr[0] = r0 + r5@

-	VADD.S32			Q9, Q1, Q6										@ xptr[1] = r1 + r6@

-	VST2.I32			{D16, D17, D18, D19}, [r8]

-	

-	VSUB.S32			Q10, Q2, Q4										@ xptr[0] = r2 - r4@

-	sub					r8, r8, r5										@ xptr -= step@

-	VSUB.S32			Q11, Q3, Q7										@ xptr[1] = r3 - r7@

-	VST2.I32			{D20, D21, D22, D23}, [r8]

-		

-	VSUB.S32			Q8, Q0, Q5										@ xptr[0] = r0 - r5@

-	sub					r8, r8, r5										@ xptr -= step@

-	VSUB.S32			Q9, Q1, Q6										@ xptr[1] = r1 - r6@

-	VST2.I32			{D16, D17, D18, D19}, [r8]

-		

-	VADD.S32			Q10, Q2, Q4										@ xptr[0] = r2 + r4@

-	sub					r8, r8, r5										@ xptr -= step@

-	VADD.S32			Q11, Q3, Q7										@ xptr[1] = r3 + r7@

-	VST2.I32			{D20, D21, D22, D23}, [r8]!

-		

-	subs    			r4, r4, #4 

-	bne     			Radix4FFT_LOOP3 

-	                         

-Radix4FFT_LOOP2_END:                         

-	add     			r8, r8, r12    

-	sub    				r7, r7, #1     

-	cmp					r7, #0

-	bhi     			Radix4FFT_LOOP2           

-                        

-Radix4FFT_LOOP1_END:                        

-	add     			r3, r12, r3    

-	mov     			r2, r2, lsl #2 

-	movs    			r1, r1, asr #2 

-	bne     			Radix4FFT_LOOP1          

-                        

-Radix4FFT_END:        

-	ldmia   			sp!, {r4 - r11, pc}

-		

-	@ENDP  @ |Radix4FFT|

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+
+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+@	File:		Radix4FFT_v7.s
+@
+@	Content:	Radix4FFT armv7 assemble
+@
+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
+
+	.section .text
+	.global	Radix4FFT
+
+Radix4FFT:
+	stmdb    sp!, {r4 - r11, lr}
+
+	mov			r1, r1, asr #2
+	cmp     	r1, #0
+	beq     	Radix4FFT_END
+
+Radix4FFT_LOOP1:
+	mov     	r5, r2, lsl #1
+	mov     	r8, r0
+	mov     	r7, r1
+	mov     	r5, r5, lsl #2
+	cmp     	r1, #0
+	rsbeq   	r12, r5, r5, lsl #2
+	beq     	Radix4FFT_LOOP1_END
+
+	rsb     	r12, r5, r5, lsl #2
+
+Radix4FFT_LOOP2:
+	mov     	r6, r3
+	mov     	r4, r2
+	cmp     	r2, #0
+	beq     	Radix4FFT_LOOP2_END
+
+Radix4FFT_LOOP3:
+	@r0 = xptr[0]@
+	@r1 = xptr[1]@
+	VLD2.I32			{D0, D1, D2, D3}, [r8]
+	VLD2.I32			{D28, D29, D30, D31}, [r6]!		@ cosx = csptr[0]@ sinx = csptr[1]@
+
+	add					r8, r8, r5										@ xptr += step@
+	VLD2.I32			{D4, D5, D6,D7}, [r8]					@ r2 = xptr[0]@ r3 = xptr[1]@
+
+	VQDMULH.S32		Q10, Q2, Q14									@ MULHIGH(cosx, t0)
+	VQDMULH.S32		Q11, Q3, Q15									@ MULHIGH(sinx, t1)
+	VQDMULH.S32		Q12, Q3, Q14									@ MULHIGH(cosx, t1)
+	VQDMULH.S32		Q13, Q2, Q15									@ MULHIGH(sinx, t0)
+
+	VADD.S32			Q2, Q10, Q11									@ MULHIGH(cosx, t0) + MULHIGH(sinx, t1)
+	VSUB.S32			Q3, Q12, Q13									@ MULHIGH(cosx, t1) - MULHIGH(sinx, t0)
+
+	add					r8, r8, r5										@ xptr += step@
+	VSHR.S32			Q10, Q0, #2										@ t0 = r0 >> 2@
+	VSHR.S32			Q11, Q1, #2										@ t1 = r1 >> 2@
+
+	VSUB.S32			Q0,	Q10, Q2										@ r0 = t0 - r2@
+	VSUB.S32			Q1,	Q11, Q3										@ r1 = t1 - r3@
+	VADD.S32			Q2, Q10, Q2										@ r2 = t0 + r2@
+	VADD.S32			Q3, Q11, Q3										@ r3 = t1 + r3@
+
+	VLD2.I32			{D8, D9, D10, D11}, [r8]
+	VLD2.I32			{D28, D29, D30, D31}, [r6]!
+	add						r8, r8, r5
+
+	VQDMULH.S32		Q10, Q4, Q14									@ MULHIGH(cosx, t0)
+	VQDMULH.S32		Q11, Q5, Q15									@ MULHIGH(sinx, t1)
+	VQDMULH.S32		Q12, Q5, Q14									@ MULHIGH(cosx, t1)
+	VQDMULH.S32		Q13, Q4, Q15									@ MULHIGH(sinx, t0)
+
+	VADD.S32			Q8, Q10, Q11									@ MULHIGH(cosx, t0) + MULHIGH(sinx, t1)
+	VSUB.S32			Q9, Q12, Q13									@ MULHIGH(cosx, t1) - MULHIGH(sinx, t0)
+
+	VLD2.I32		{D12, D13, D14, D15}, [r8]
+	VLD2.I32		{D28, D29, D30, D31}, [r6]!
+
+	VQDMULH.S32		Q10, Q6, Q14									@ MULHIGH(cosx, t0)
+	VQDMULH.S32		Q11, Q7, Q15									@ MULHIGH(sinx, t1)
+	VQDMULH.S32		Q12, Q7, Q14									@ MULHIGH(cosx, t1)
+	VQDMULH.S32		Q13, Q6, Q15									@ MULHIGH(sinx, t0)
+
+	VADD.S32			Q6, Q10, Q11									@ MULHIGH(cosx, t0) + MULHIGH(sinx, t1)
+	VSUB.S32			Q7, Q12, Q13									@ MULHIGH(cosx, t1) - MULHIGH(sinx, t0)
+
+	VADD.S32			Q4, Q8, Q6										@ r4 = t0 + r6@
+	VSUB.S32			Q5, Q7, Q9										@ r5 = r7 - t1@
+	VSUB.S32			Q6, Q8, Q6										@ r6 = t0 - r6@
+	VADD.S32			Q7, Q7, Q9										@ r7 = r7 + t1@
+
+	VADD.S32			Q8, Q0, Q5										@ xptr[0] = r0 + r5@
+	VADD.S32			Q9, Q1, Q6										@ xptr[1] = r1 + r6@
+	VST2.I32			{D16, D17, D18, D19}, [r8]
+
+	VSUB.S32			Q10, Q2, Q4										@ xptr[0] = r2 - r4@
+	sub					r8, r8, r5										@ xptr -= step@
+	VSUB.S32			Q11, Q3, Q7										@ xptr[1] = r3 - r7@
+	VST2.I32			{D20, D21, D22, D23}, [r8]
+
+	VSUB.S32			Q8, Q0, Q5										@ xptr[0] = r0 - r5@
+	sub					r8, r8, r5										@ xptr -= step@
+	VSUB.S32			Q9, Q1, Q6										@ xptr[1] = r1 - r6@
+	VST2.I32			{D16, D17, D18, D19}, [r8]
+
+	VADD.S32			Q10, Q2, Q4										@ xptr[0] = r2 + r4@
+	sub					r8, r8, r5										@ xptr -= step@
+	VADD.S32			Q11, Q3, Q7										@ xptr[1] = r3 + r7@
+	VST2.I32			{D20, D21, D22, D23}, [r8]!
+
+	subs    			r4, r4, #4
+	bne     			Radix4FFT_LOOP3
+
+Radix4FFT_LOOP2_END:
+	add     			r8, r8, r12
+	sub    				r7, r7, #1
+	cmp					r7, #0
+	bhi     			Radix4FFT_LOOP2
+
+Radix4FFT_LOOP1_END:
+	add     			r3, r12, r3
+	mov     			r2, r2, lsl #2
+	movs    			r1, r1, asr #2
+	bne     			Radix4FFT_LOOP1
+
+Radix4FFT_END:
+	ldmia   			sp!, {r4 - r11, pc}
+
+	@ENDP  @ |Radix4FFT|
 	.end
\ No newline at end of file
diff --git a/media/libstagefright/codecs/aacenc/src/band_nrg.c b/media/libstagefright/codecs/aacenc/src/band_nrg.c
index 666c4ca..7501af1 100644
--- a/media/libstagefright/codecs/aacenc/src/band_nrg.c
+++ b/media/libstagefright/codecs/aacenc/src/band_nrg.c
@@ -1,35 +1,35 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		band_nrg.c

-

-	Content:	Band/Line energy calculations functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		band_nrg.c
+
+	Content:	Band/Line energy calculations functions
+
 *******************************************************************************/
 
-#include "basic_op.h"

+#include "basic_op.h"
 #include "band_nrg.h"
 
-#ifndef ARMV5E

+#ifndef ARMV5E
 /********************************************************************************
 *
 * function name: CalcBandEnergy
 * description:   Calc sfb-bandwise mdct-energies for left and right channel
 *
-**********************************************************************************/

+**********************************************************************************/
 void CalcBandEnergy(const Word32 *mdctSpectrum,
                     const Word16 *bandOffset,
                     const Word16  numBands,
@@ -37,18 +37,18 @@
                     Word32       *bandEnergySum)
 {
   Word32 i, j;
-  Word32 accuSum = 0;                                            
+  Word32 accuSum = 0;
 
   for (i=0; i<numBands; i++) {
-    Word32 accu = 0;                                             
+    Word32 accu = 0;
     for (j=bandOffset[i]; j<bandOffset[i+1]; j++)
-      accu = L_add(accu, MULHIGH(mdctSpectrum[j], mdctSpectrum[j]));

-

+      accu = L_add(accu, MULHIGH(mdctSpectrum[j], mdctSpectrum[j]));
+
 	accu = L_add(accu, accu);
     accuSum = L_add(accuSum, accu);
-    bandEnergy[i] = accu;                                        
+    bandEnergy[i] = accu;
   }
-  *bandEnergySum = accuSum;                                      
+  *bandEnergySum = accuSum;
 }
 
 /********************************************************************************
@@ -68,15 +68,15 @@
 {
 
   Word32 i, j;
-  Word32 accuMidSum = 0;        
-  Word32 accuSideSum = 0;                                          
- 
+  Word32 accuMidSum = 0;
+  Word32 accuSideSum = 0;
+
 
   for(i=0; i<numBands; i++) {
     Word32 accuMid = 0;
-    Word32 accuSide = 0;                                           
+    Word32 accuSide = 0;
     for (j=bandOffset[i]; j<bandOffset[i+1]; j++) {
-      Word32 specm, specs; 
+      Word32 specm, specs;
       Word32 l, r;
 
       l = mdctSpectrumLeft[j] >> 1;
@@ -86,17 +86,17 @@
       accuMid = L_add(accuMid, MULHIGH(specm, specm));
       accuSide = L_add(accuSide, MULHIGH(specs, specs));
     }
-    

-	accuMid = L_add(accuMid, accuMid);

-	accuSide = L_add(accuSide, accuSide);

-	bandEnergyMid[i] = accuMid;                                  
+
+	accuMid = L_add(accuMid, accuMid);
+	accuSide = L_add(accuSide, accuSide);
+	bandEnergyMid[i] = accuMid;
     accuMidSum = L_add(accuMidSum, accuMid);
-    bandEnergySide[i] = accuSide;                                
+    bandEnergySide[i] = accuSide;
     accuSideSum = L_add(accuSideSum, accuSide);
-    
+
   }
-  *bandEnergyMidSum = accuMidSum;                                
-  *bandEnergySideSum = accuSideSum;                              
+  *bandEnergyMidSum = accuMidSum;
+  *bandEnergySideSum = accuSideSum;
 }
 
 #endif
\ No newline at end of file
diff --git a/media/libstagefright/codecs/aacenc/src/bit_cnt.c b/media/libstagefright/codecs/aacenc/src/bit_cnt.c
index 24837e8..9fe511cd 100644
--- a/media/libstagefright/codecs/aacenc/src/bit_cnt.c
+++ b/media/libstagefright/codecs/aacenc/src/bit_cnt.c
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		bit_cnt.c

-

-	Content:	Huffman Bitcounter & coder functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		bit_cnt.c
+
+	Content:	Huffman Bitcounter & coder functions
+
 *******************************************************************************/
 
 #include "bit_cnt.h"
@@ -26,14 +26,14 @@
 #define HI_LTAB(a) (a>>8)
 #define LO_LTAB(a) (a & 0xff)
 
-#define EXPAND(a)  ((((Word32)(a&0xff00)) << 8)|(Word32)(a&0xff)) 
+#define EXPAND(a)  ((((Word32)(a&0xff00)) << 8)|(Word32)(a&0xff))
 
 
 /*****************************************************************************
 *
 * function name: count1_2_3_4_5_6_7_8_9_10_11
-* description:  counts tables 1-11 
-* returns:      
+* description:  counts tables 1-11
+* returns:
 * input:        quantized spectrum
 * output:       bitCount for tables 1-11
 *
@@ -45,52 +45,52 @@
 {
   Word32 t0,t1,t2,t3,i;
   Word32 bc1_2,bc3_4,bc5_6,bc7_8,bc9_10;
-  Word16 bc11,sc;

-  
-  bc1_2=0;                               
-  bc3_4=0;                               
-  bc5_6=0;                               
-  bc7_8=0;                               
-  bc9_10=0;                              
-  bc11=0;                                
-  sc=0;                                  
+  Word16 bc11,sc;
+
+  bc1_2=0;
+  bc3_4=0;
+  bc5_6=0;
+  bc7_8=0;
+  bc9_10=0;
+  bc11=0;
+  sc=0;
 
   for(i=0;i<width;i+=4){
-    
-    t0= values[i+0];                     
-    t1= values[i+1];                     
-    t2= values[i+2];                     
-    t3= values[i+3];                     
-  
+
+    t0= values[i+0];
+    t1= values[i+1];
+    t2= values[i+2];
+    t3= values[i+3];
+
     /* 1,2 */
 
-    bc1_2 = bc1_2 + EXPAND(huff_ltab1_2[t0+1][t1+1][t2+1][t3+1]);              
+    bc1_2 = bc1_2 + EXPAND(huff_ltab1_2[t0+1][t1+1][t2+1][t3+1]);
 
     /* 5,6 */
-    bc5_6 = bc5_6 + EXPAND(huff_ltab5_6[t0+4][t1+4]);                          
-    bc5_6 = bc5_6 + EXPAND(huff_ltab5_6[t2+4][t3+4]);                          
+    bc5_6 = bc5_6 + EXPAND(huff_ltab5_6[t0+4][t1+4]);
+    bc5_6 = bc5_6 + EXPAND(huff_ltab5_6[t2+4][t3+4]);
 
     t0=ABS(t0);
     t1=ABS(t1);
     t2=ABS(t2);
     t3=ABS(t3);
 
-    
-    bc3_4 = bc3_4 + EXPAND(huff_ltab3_4[t0][t1][t2][t3]);                      
-    
-    bc7_8 = bc7_8 + EXPAND(huff_ltab7_8[t0][t1]);                              
-    bc7_8 = bc7_8 + EXPAND(huff_ltab7_8[t2][t3]);                              
-    
-    bc9_10 = bc9_10 + EXPAND(huff_ltab9_10[t0][t1]);                           
-    bc9_10 = bc9_10 + EXPAND(huff_ltab9_10[t2][t3]);                           
-    
+
+    bc3_4 = bc3_4 + EXPAND(huff_ltab3_4[t0][t1][t2][t3]);
+
+    bc7_8 = bc7_8 + EXPAND(huff_ltab7_8[t0][t1]);
+    bc7_8 = bc7_8 + EXPAND(huff_ltab7_8[t2][t3]);
+
+    bc9_10 = bc9_10 + EXPAND(huff_ltab9_10[t0][t1]);
+    bc9_10 = bc9_10 + EXPAND(huff_ltab9_10[t2][t3]);
+
     bc11 = bc11 + huff_ltab11[t0][t1];
     bc11 = bc11 + huff_ltab11[t2][t3];
-   
-           
+
+
     sc = sc + (t0>0) + (t1>0) + (t2>0) + (t3>0);
   }
-  
+
   bitCount[1]=extract_h(bc1_2);
   bitCount[2]=extract_l(bc1_2);
   bitCount[3]=extract_h(bc3_4) + sc;
@@ -108,8 +108,8 @@
 /*****************************************************************************
 *
 * function name: count3_4_5_6_7_8_9_10_11
-* description:  counts tables 3-11 
-* returns:      
+* description:  counts tables 3-11
+* returns:
 * input:        quantized spectrum
 * output:       bitCount for tables 3-11
 *
@@ -122,26 +122,26 @@
   Word32 t0,t1,t2,t3, i;
   Word32 bc3_4,bc5_6,bc7_8,bc9_10;
   Word16 bc11,sc;
-    
-  bc3_4=0;                               
-  bc5_6=0;                               
-  bc7_8=0;                               
-  bc9_10=0;                              
-  bc11=0;                                
-  sc=0;                                  
+
+  bc3_4=0;
+  bc5_6=0;
+  bc7_8=0;
+  bc9_10=0;
+  bc11=0;
+  sc=0;
 
   for(i=0;i<width;i+=4){
 
-    t0= values[i+0];                     
-    t1= values[i+1];                     
-    t2= values[i+2];                     
-    t3= values[i+3];                     
-    
+    t0= values[i+0];
+    t1= values[i+1];
+    t2= values[i+2];
+    t3= values[i+3];
+
     /*
       5,6
     */
-    bc5_6 = bc5_6 + EXPAND(huff_ltab5_6[t0+4][t1+4]);                          
-    bc5_6 = bc5_6 + EXPAND(huff_ltab5_6[t2+4][t3+4]);                          
+    bc5_6 = bc5_6 + EXPAND(huff_ltab5_6[t0+4][t1+4]);
+    bc5_6 = bc5_6 + EXPAND(huff_ltab5_6[t2+4][t3+4]);
 
     t0=ABS(t0);
     t1=ABS(t1);
@@ -149,23 +149,23 @@
     t3=ABS(t3);
 
 
-    bc3_4 = bc3_4 + EXPAND(huff_ltab3_4[t0][t1][t2][t3]);                      
-                                                                                                                
-    bc7_8 = bc7_8 + EXPAND(huff_ltab7_8[t0][t1]);                              
-    bc7_8 = bc7_8 + EXPAND(huff_ltab7_8[t2][t3]);                              
-    
-    bc9_10 = bc9_10 + EXPAND(huff_ltab9_10[t0][t1]);                           
-    bc9_10 = bc9_10 + EXPAND(huff_ltab9_10[t2][t3]);                           
-                                                                                                                
+    bc3_4 = bc3_4 + EXPAND(huff_ltab3_4[t0][t1][t2][t3]);
+
+    bc7_8 = bc7_8 + EXPAND(huff_ltab7_8[t0][t1]);
+    bc7_8 = bc7_8 + EXPAND(huff_ltab7_8[t2][t3]);
+
+    bc9_10 = bc9_10 + EXPAND(huff_ltab9_10[t0][t1]);
+    bc9_10 = bc9_10 + EXPAND(huff_ltab9_10[t2][t3]);
+
     bc11 = bc11 + huff_ltab11[t0][t1];
     bc11 = bc11 + huff_ltab11[t2][t3];
 
-           
-    sc = sc + (t0>0) + (t1>0) + (t2>0) + (t3>0);   
-  }

-  
-  bitCount[1]=INVALID_BITCOUNT;                          
-  bitCount[2]=INVALID_BITCOUNT;                          
+
+    sc = sc + (t0>0) + (t1>0) + (t2>0) + (t3>0);
+  }
+
+  bitCount[1]=INVALID_BITCOUNT;
+  bitCount[2]=INVALID_BITCOUNT;
   bitCount[3]=extract_h(bc3_4) + sc;
   bitCount[4]=extract_l(bc3_4) + sc;
   bitCount[5]=extract_h(bc5_6);
@@ -175,7 +175,7 @@
   bitCount[9]=extract_h(bc9_10) + sc;
   bitCount[10]=extract_l(bc9_10) + sc;
   bitCount[11]=bc11 + sc;
-  
+
 }
 
 
@@ -183,8 +183,8 @@
 /*****************************************************************************
 *
 * function name: count5_6_7_8_9_10_11
-* description:  counts tables 5-11 
-* returns:      
+* description:  counts tables 5-11
+* returns:
 * input:        quantized spectrum
 * output:       bitCount for tables 5-11
 *
@@ -196,35 +196,35 @@
 
   Word32 t0,t1,i;
   Word32 bc5_6,bc7_8,bc9_10;
-  Word16 bc11,sc;

+  Word16 bc11,sc;
 
-  bc5_6=0;                               
-  bc7_8=0;                               
-  bc9_10=0;                              
-  bc11=0;                                
-  sc=0;                                  
+  bc5_6=0;
+  bc7_8=0;
+  bc9_10=0;
+  bc11=0;
+  sc=0;
 
   for(i=0;i<width;i+=2){
 
-    t0 = values[i+0];                    
-    t1 = values[i+1];                    
+    t0 = values[i+0];
+    t1 = values[i+1];
 
-    bc5_6 = bc5_6 + EXPAND(huff_ltab5_6[t0+4][t1+4]);                  
+    bc5_6 = bc5_6 + EXPAND(huff_ltab5_6[t0+4][t1+4]);
 
     t0=ABS(t0);
     t1=ABS(t1);
-     
-    bc7_8 = bc7_8 + EXPAND(huff_ltab7_8[t0][t1]);                      
-    bc9_10 = bc9_10 + EXPAND(huff_ltab9_10[t0][t1]);                   
+
+    bc7_8 = bc7_8 + EXPAND(huff_ltab7_8[t0][t1]);
+    bc9_10 = bc9_10 + EXPAND(huff_ltab9_10[t0][t1]);
     bc11 = bc11 + huff_ltab11[t0][t1];
-    
-       
+
+
     sc = sc + (t0>0) + (t1>0);
   }
-  bitCount[1]=INVALID_BITCOUNT;                          
-  bitCount[2]=INVALID_BITCOUNT;                          
-  bitCount[3]=INVALID_BITCOUNT;                          
-  bitCount[4]=INVALID_BITCOUNT;                          
+  bitCount[1]=INVALID_BITCOUNT;
+  bitCount[2]=INVALID_BITCOUNT;
+  bitCount[3]=INVALID_BITCOUNT;
+  bitCount[4]=INVALID_BITCOUNT;
   bitCount[5]=extract_h(bc5_6);
   bitCount[6]=extract_l(bc5_6);
   bitCount[7]=extract_h(bc7_8) + sc;
@@ -232,15 +232,15 @@
   bitCount[9]=extract_h(bc9_10) + sc;
   bitCount[10]=extract_l(bc9_10) + sc;
   bitCount[11]=bc11 + sc;
-  
+
 }
 
 
 /*****************************************************************************
 *
 * function name: count7_8_9_10_11
-* description:  counts tables 7-11 
-* returns:      
+* description:  counts tables 7-11
+* returns:
 * input:        quantized spectrum
 * output:       bitCount for tables 7-11
 *
@@ -253,184 +253,184 @@
   Word32 t0,t1, i;
   Word32 bc7_8,bc9_10;
   Word16 bc11,sc;
-    
-  bc7_8=0;                       
-  bc9_10=0;                      
-  bc11=0;                        
-  sc=0;                          
+
+  bc7_8=0;
+  bc9_10=0;
+  bc11=0;
+  sc=0;
 
   for(i=0;i<width;i+=2){
 
     t0=ABS(values[i+0]);
     t1=ABS(values[i+1]);
 
-    bc7_8 = bc7_8 + EXPAND(huff_ltab7_8[t0][t1]);                      
-    bc9_10 = bc9_10 + EXPAND(huff_ltab9_10[t0][t1]);                   
+    bc7_8 = bc7_8 + EXPAND(huff_ltab7_8[t0][t1]);
+    bc9_10 = bc9_10 + EXPAND(huff_ltab9_10[t0][t1]);
     bc11 = bc11 + huff_ltab11[t0][t1];
-   
-       
+
+
     sc = sc + (t0>0) + (t1>0);
   }
-  bitCount[1]=INVALID_BITCOUNT;                  
-  bitCount[2]=INVALID_BITCOUNT;                  
-  bitCount[3]=INVALID_BITCOUNT;                  
-  bitCount[4]=INVALID_BITCOUNT;                  
-  bitCount[5]=INVALID_BITCOUNT;                  
-  bitCount[6]=INVALID_BITCOUNT;                  
+  bitCount[1]=INVALID_BITCOUNT;
+  bitCount[2]=INVALID_BITCOUNT;
+  bitCount[3]=INVALID_BITCOUNT;
+  bitCount[4]=INVALID_BITCOUNT;
+  bitCount[5]=INVALID_BITCOUNT;
+  bitCount[6]=INVALID_BITCOUNT;
   bitCount[7]=extract_h(bc7_8) + sc;
   bitCount[8]=extract_l(bc7_8) + sc;
   bitCount[9]=extract_h(bc9_10) + sc;
   bitCount[10]=extract_l(bc9_10) + sc;
   bitCount[11]=bc11 + sc;
-  
+
 }
 
 /*****************************************************************************
 *
 * function name: count9_10_11
-* description:  counts tables 9-11 
-* returns:      
+* description:  counts tables 9-11
+* returns:
 * input:        quantized spectrum
 * output:       bitCount for tables 9-11
 *
 *****************************************************************************/
-static void count9_10_11(const Word16 *values,

-                         const Word16  width,

-                         Word16       *bitCount)

-{

-

-  Word32 t0,t1,i;  

-  Word32 bc9_10;

-  Word16 bc11,sc;

-

-  bc9_10=0;                              

-  bc11=0;                                

-  sc=0;                                  

-

-  for(i=0;i<width;i+=2){

-

-    t0=ABS(values[i+0]);

-    t1=ABS(values[i+1]);

-    

-

-    bc9_10 += EXPAND(huff_ltab9_10[t0][t1]);           

-    bc11 = bc11 + huff_ltab11[t0][t1];

-

-       

-    sc = sc + (t0>0) + (t1>0);

-  }

-  bitCount[1]=INVALID_BITCOUNT;          

-  bitCount[2]=INVALID_BITCOUNT;          

-  bitCount[3]=INVALID_BITCOUNT;          

-  bitCount[4]=INVALID_BITCOUNT;          

-  bitCount[5]=INVALID_BITCOUNT;          

-  bitCount[6]=INVALID_BITCOUNT;          

-  bitCount[7]=INVALID_BITCOUNT;          

-  bitCount[8]=INVALID_BITCOUNT;          

-  bitCount[9]=extract_h(bc9_10) + sc;

-  bitCount[10]=extract_l(bc9_10) + sc;

-  bitCount[11]=bc11 + sc;

-  

+static void count9_10_11(const Word16 *values,
+                         const Word16  width,
+                         Word16       *bitCount)
+{
+
+  Word32 t0,t1,i;
+  Word32 bc9_10;
+  Word16 bc11,sc;
+
+  bc9_10=0;
+  bc11=0;
+  sc=0;
+
+  for(i=0;i<width;i+=2){
+
+    t0=ABS(values[i+0]);
+    t1=ABS(values[i+1]);
+
+
+    bc9_10 += EXPAND(huff_ltab9_10[t0][t1]);
+    bc11 = bc11 + huff_ltab11[t0][t1];
+
+
+    sc = sc + (t0>0) + (t1>0);
+  }
+  bitCount[1]=INVALID_BITCOUNT;
+  bitCount[2]=INVALID_BITCOUNT;
+  bitCount[3]=INVALID_BITCOUNT;
+  bitCount[4]=INVALID_BITCOUNT;
+  bitCount[5]=INVALID_BITCOUNT;
+  bitCount[6]=INVALID_BITCOUNT;
+  bitCount[7]=INVALID_BITCOUNT;
+  bitCount[8]=INVALID_BITCOUNT;
+  bitCount[9]=extract_h(bc9_10) + sc;
+  bitCount[10]=extract_l(bc9_10) + sc;
+  bitCount[11]=bc11 + sc;
+
 }
- 
+
 /*****************************************************************************
 *
 * function name: count11
-* description:  counts table 11 
-* returns:      
+* description:  counts table 11
+* returns:
 * input:        quantized spectrum
 * output:       bitCount for table 11
 *
 *****************************************************************************/
- static void count11(const Word16 *values,

-                    const Word16  width,

-                    Word16        *bitCount)

-{

-  Word32 t0,t1,i;

-  Word16 bc11,sc;  

-

-  bc11=0;                        

-  sc=0;                          

-  for(i=0;i<width;i+=2){

-    t0=ABS(values[i+0]);

-    t1=ABS(values[i+1]);

-    bc11 = bc11 + huff_ltab11[t0][t1];

-

-       

-    sc = sc + (t0>0) + (t1>0);

-  }

-

-  bitCount[1]=INVALID_BITCOUNT;                  

-  bitCount[2]=INVALID_BITCOUNT;                  

-  bitCount[3]=INVALID_BITCOUNT;                  

-  bitCount[4]=INVALID_BITCOUNT;                  

-  bitCount[5]=INVALID_BITCOUNT;                  

-  bitCount[6]=INVALID_BITCOUNT;                  

-  bitCount[7]=INVALID_BITCOUNT;                  

-  bitCount[8]=INVALID_BITCOUNT;                  

-  bitCount[9]=INVALID_BITCOUNT;                  

-  bitCount[10]=INVALID_BITCOUNT;                 

-  bitCount[11]=bc11 + sc;

+ static void count11(const Word16 *values,
+                    const Word16  width,
+                    Word16        *bitCount)
+{
+  Word32 t0,t1,i;
+  Word16 bc11,sc;
+
+  bc11=0;
+  sc=0;
+  for(i=0;i<width;i+=2){
+    t0=ABS(values[i+0]);
+    t1=ABS(values[i+1]);
+    bc11 = bc11 + huff_ltab11[t0][t1];
+
+
+    sc = sc + (t0>0) + (t1>0);
+  }
+
+  bitCount[1]=INVALID_BITCOUNT;
+  bitCount[2]=INVALID_BITCOUNT;
+  bitCount[3]=INVALID_BITCOUNT;
+  bitCount[4]=INVALID_BITCOUNT;
+  bitCount[5]=INVALID_BITCOUNT;
+  bitCount[6]=INVALID_BITCOUNT;
+  bitCount[7]=INVALID_BITCOUNT;
+  bitCount[8]=INVALID_BITCOUNT;
+  bitCount[9]=INVALID_BITCOUNT;
+  bitCount[10]=INVALID_BITCOUNT;
+  bitCount[11]=bc11 + sc;
 }
 
 /*****************************************************************************
 *
 * function name: countEsc
-* description:  counts table 11 (with Esc) 
-* returns:      
+* description:  counts table 11 (with Esc)
+* returns:
 * input:        quantized spectrum
 * output:       bitCount for tables 11 (with Esc)
 *
 *****************************************************************************/
 
-static void countEsc(const Word16 *values,

-                     const Word16  width,

-                     Word16       *bitCount)

-{

-  Word32 t0,t1,t00,t01,i;

-  Word16 bc11,ec,sc;  

-

-  bc11=0;                                

-  sc=0;                                  

-  ec=0;                                  

-  for(i=0;i<width;i+=2){

-    t0=ABS(values[i+0]);

-    t1=ABS(values[i+1]);

-    

-       

-    sc = sc + (t0>0) + (t1>0);

-

-    t00 = min(t0,16);

-    t01 = min(t1,16);

-    bc11 = bc11 + huff_ltab11[t00][t01];

-    

-     

-    if(t0 >= 16){

-      ec = ec + 5;

-      while(sub(t0=(t0 >> 1), 16) >= 0) {

-        ec = ec + 2;

-      }

-    }

-    

-     

-    if(t1 >= 16){

-      ec = ec + 5;

-      while(sub(t1=(t1 >> 1), 16) >= 0) {

-        ec = ec + 2;

-      }

-    }

-  }

-  bitCount[1]=INVALID_BITCOUNT;          

-  bitCount[2]=INVALID_BITCOUNT;          

-  bitCount[3]=INVALID_BITCOUNT;          

-  bitCount[4]=INVALID_BITCOUNT;          

-  bitCount[5]=INVALID_BITCOUNT;          

-  bitCount[6]=INVALID_BITCOUNT;          

-  bitCount[7]=INVALID_BITCOUNT;          

-  bitCount[8]=INVALID_BITCOUNT;          

-  bitCount[9]=INVALID_BITCOUNT;          

-  bitCount[10]=INVALID_BITCOUNT;         

-  bitCount[11]=bc11 + sc + ec;

+static void countEsc(const Word16 *values,
+                     const Word16  width,
+                     Word16       *bitCount)
+{
+  Word32 t0,t1,t00,t01,i;
+  Word16 bc11,ec,sc;
+
+  bc11=0;
+  sc=0;
+  ec=0;
+  for(i=0;i<width;i+=2){
+    t0=ABS(values[i+0]);
+    t1=ABS(values[i+1]);
+
+
+    sc = sc + (t0>0) + (t1>0);
+
+    t00 = min(t0,16);
+    t01 = min(t1,16);
+    bc11 = bc11 + huff_ltab11[t00][t01];
+
+
+    if(t0 >= 16){
+      ec = ec + 5;
+      while(sub(t0=(t0 >> 1), 16) >= 0) {
+        ec = ec + 2;
+      }
+    }
+
+
+    if(t1 >= 16){
+      ec = ec + 5;
+      while(sub(t1=(t1 >> 1), 16) >= 0) {
+        ec = ec + 2;
+      }
+    }
+  }
+  bitCount[1]=INVALID_BITCOUNT;
+  bitCount[2]=INVALID_BITCOUNT;
+  bitCount[3]=INVALID_BITCOUNT;
+  bitCount[4]=INVALID_BITCOUNT;
+  bitCount[5]=INVALID_BITCOUNT;
+  bitCount[6]=INVALID_BITCOUNT;
+  bitCount[7]=INVALID_BITCOUNT;
+  bitCount[8]=INVALID_BITCOUNT;
+  bitCount[9]=INVALID_BITCOUNT;
+  bitCount[10]=INVALID_BITCOUNT;
+  bitCount[11]=bc11 + sc + ec;
 }
 
 
@@ -463,7 +463,7 @@
 /*****************************************************************************
 *
 * function name: bitCount
-* description:  count bits 
+* description:  count bits
 *
 *****************************************************************************/
 Word16 bitCount(const Word16 *values,
@@ -474,7 +474,7 @@
   /*
     check if we can use codebook 0
   */
-     
+
   if(maxVal == 0)
     bitCount[0] = 0;
   else
@@ -489,379 +489,379 @@
 /*****************************************************************************
 *
 * function name: codeValues
-* description:  write huffum bits 
+* description:  write huffum bits
 *
 *****************************************************************************/
-Word16 codeValues(Word16 *values, Word16 width, Word16 codeBook, HANDLE_BIT_BUF hBitstream)

-{

-

-  Word32 i, t0, t1, t2, t3, t00, t01;

-  Word16 codeWord, codeLength;

-  Word16 sign, signLength;

-

-   

-  switch (codeBook) {

-    case CODE_BOOK_ZERO_NO:

-      break;

-

-    case CODE_BOOK_1_NO:

-      for(i=0; i<width; i+=4) {

-        t0         = values[i+0];                                        

-        t1         = values[i+1];                                        

-        t2         = values[i+2];                                        

-        t3         = values[i+3];                                        

-        codeWord   = huff_ctab1[t0+1][t1+1][t2+1][t3+1];                 

-        codeLength = HI_LTAB(huff_ltab1_2[t0+1][t1+1][t2+1][t3+1]);      

-        WriteBits(hBitstream, codeWord, codeLength);        

-      }

-      break;

-

-    case CODE_BOOK_2_NO:

-      for(i=0; i<width; i+=4) {

-        t0         = values[i+0];                                        

-        t1         = values[i+1];                                        

-        t2         = values[i+2];                                        

-        t3         = values[i+3];                                        

-        codeWord   = huff_ctab2[t0+1][t1+1][t2+1][t3+1];                 

-        codeLength = LO_LTAB(huff_ltab1_2[t0+1][t1+1][t2+1][t3+1]);      

-        WriteBits(hBitstream,codeWord,codeLength);

-      }

-      break;

-

-    case CODE_BOOK_3_NO:

-      for(i=0; i<width; i+=4) {

-        sign=0;                                                          

-        signLength=0;                                                    

-        t0 = values[i+0];                                                

-         

-        if(t0 != 0){

-          signLength = signLength + 1;

-          sign = sign << 1; 

-           

-          if(t0 < 0){

-            sign|=1;                                                     

-            t0=-t0;

-          }

-        }

-        t1 = values[i+1];                                                

-         

-        if(t1 != 0){

-          signLength = signLength + 1;

-          sign = sign << 1; 

-           

-          if(t1 < 0){

-            sign|=1;                                                     

-            t1=-t1;

-          }

-        }

-        t2 = values[i+2];                                                

-         

-        if(t2 != 0){

-          signLength = signLength + 1;

-          sign = sign << 1; 

-           

-          if(t2 < 0){

-            sign|=1;                                                     

-            t2=-t2;

-          }

-        }

-        t3 = values[i+3];                                                

-        if(t3 != 0){

-          signLength = signLength + 1;

-          sign = sign << 1; 

-           

-          if(t3 < 0){

-            sign|=1;                                                     

-            t3=-t3;

-          }

-        }

-

-        codeWord   = huff_ctab3[t0][t1][t2][t3];                         

-        codeLength = HI_LTAB(huff_ltab3_4[t0][t1][t2][t3]);              

-        WriteBits(hBitstream,codeWord,codeLength);

-        WriteBits(hBitstream,sign,signLength);

-      }

-      break;

-

-    case CODE_BOOK_4_NO:

-      for(i=0; i<width; i+=4) {

-        sign=0;                                                          

-        signLength=0;                                                    

-        t0 = values[i+0];                                                

-         

-        if(t0 != 0){                                                             

-          signLength = signLength + 1;

-          sign = sign << 1; 

-          if(t0 < 0){                                                            

-            sign|=1;                                                     

-            t0=-t0;                                                          

-          }

-        }                                                                        

-        t1 = values[i+1];                                                

-         

-        if(t1 != 0){                                                             

-          signLength = signLength + 1;

-          sign = sign << 1; 

-           

-          if(t1 < 0){                                                            

-            sign|=1;                                                     

-            t1=-t1;                                                          

-          }                                                                      

-        }                                                                        

-        t2 = values[i+2];                                                

-         

-        if(t2 != 0){                                                    

-          signLength = signLength + 1;

-          sign = sign << 1; 

-           

-          if(t2 < 0){                                                   

-            sign|=1;                                                     

-            t2=-t2;                                                 

-          }                                                             

-        }                                                               

-        t3 = values[i+3];                                                

-         

-        if(t3 != 0){                                                    

-          signLength = signLength + 1;

-          sign = sign << 1; 

-           

-          if(t3 < 0){                                                   

-            sign|=1;                                                     

-            t3=-t3;                                                 

-          }                                                             

-        }                                                               

-        codeWord   = huff_ctab4[t0][t1][t2][t3];                         

-        codeLength = LO_LTAB(huff_ltab3_4[t0][t1][t2][t3]);              

-        WriteBits(hBitstream,codeWord,codeLength);                      

-        WriteBits(hBitstream,sign,signLength);                          

-      }                                                                 

-      break;                                                            

-                                                                        

-    case CODE_BOOK_5_NO:                                                

-      for(i=0; i<width; i+=2) {                                         

-        t0         = values[i+0];                                         

-        t1         = values[i+1];                                        

-        codeWord   = huff_ctab5[t0+4][t1+4];                             

-        codeLength = HI_LTAB(huff_ltab5_6[t0+4][t1+4]);                  

-        WriteBits(hBitstream,codeWord,codeLength);

-      }

-      break;

-

-    case CODE_BOOK_6_NO:

-      for(i=0; i<width; i+=2) {

-        t0         = values[i+0];                                        

-        t1         = values[i+1];                                        

-        codeWord   = huff_ctab6[t0+4][t1+4];                             

-        codeLength = LO_LTAB(huff_ltab5_6[t0+4][t1+4]);                  

-        WriteBits(hBitstream,codeWord,codeLength);

-      }

-      break;

-

-    case CODE_BOOK_7_NO:

-      for(i=0; i<width; i+=2){

-        sign=0;                                                          

-        signLength=0;                                                    

-        t0 = values[i+0];                                                

-         

-        if(t0 != 0){

-          signLength = signLength + 1;

-          sign = sign << 1; 

-           

-          if(t0 < 0){

-            sign|=1;                                                     

-            t0=-t0;

-          }

-        }

-

-        t1 = values[i+1];                                                

-         

-        if(t1 != 0){

-          signLength = signLength + 1;

-          sign = sign << 1; 

-           

-          if(t1 < 0){

-            sign|=1;                                                     

-            t1=-t1;

-          }

-        }

-        codeWord   = huff_ctab7[t0][t1];                                 

-        codeLength = HI_LTAB(huff_ltab7_8[t0][t1]);                      

-        WriteBits(hBitstream,codeWord,codeLength);

-        WriteBits(hBitstream,sign,signLength);

-      }

-      break;

-

-    case CODE_BOOK_8_NO:

-      for(i=0; i<width; i+=2) {

-        sign=0;                                                          

-        signLength=0;                                                    

-        t0 = values[i+0];                                                

-                                                                           

-        if(t0 != 0){                                                             

-          signLength = signLength + 1;                                       

-          sign = sign << 1;                                                   

-                                                                           

-          if(t0 < 0){                                                            

-            sign|=1;                                                     

-            t0=-t0;                                                        

-          }                                                                      

-        }                                                                        

-                                                                                 

-        t1 = values[i+1];                                                

-                                                                           

-        if(t1 != 0){                                                             

-          signLength = signLength + 1;                                       

-          sign = sign << 1;                                                   

-                                                                           

-          if(t1 < 0){                                                            

-            sign|=1;                                                     

-            t1=-t1;                                                        

-          }                                                                      

-        }                                                                        

-        codeWord   = huff_ctab8[t0][t1];                                 

-        codeLength = LO_LTAB(huff_ltab7_8[t0][t1]);                      

-        WriteBits(hBitstream,codeWord,codeLength);

-        WriteBits(hBitstream,sign,signLength);

-      }

-      break;

-

-    case CODE_BOOK_9_NO:

-      for(i=0; i<width; i+=2) {

-        sign=0;                                                          

-        signLength=0;                                                    

-        t0 = values[i+0];                                                

-                                                                           

-        if(t0 != 0){                                                             

-          signLength = signLength + 1;                                       

-          sign = sign << 1;                                                   

-                                                                           

-          if(t0 < 0){                                                            

-            sign|=1;                                                     

-            t0=-t0;                                                        

-          }                                                                      

-        }                                                                        

-                                                                                 

-        t1 = values[i+1];                                                

-                                                                           

-        if(t1 != 0){                                                             

-          signLength = signLength + 1;                                       

-          sign = sign << 1;                                                   

-                                                                           

-          if(t1 < 0){                                                            

-            sign|=1;                                                     

-            t1=-t1;                                                        

-          }                                                                      

-        }                                                                        

-        codeWord   = huff_ctab9[t0][t1];                                 

-        codeLength = HI_LTAB(huff_ltab9_10[t0][t1]);                     

-        WriteBits(hBitstream,codeWord,codeLength);

-        WriteBits(hBitstream,sign,signLength);

-      }

-      break;

-

-    case CODE_BOOK_10_NO:

-      for(i=0; i<width; i+=2) {

-        sign=0;                                                          

-        signLength=0;                                                    

-        t0 = values[i+0];                                                

-                                                                           

-        if(t0 != 0){                                                             

-          signLength = signLength + 1;                                       

-          sign = sign << 1;                                                   

-                                                                           

-          if(t0 < 0){                                                            

-            sign|=1;                                                     

-            t0=-t0;                                                        

-          }                                                                      

-        }                                                                        

-                                                                                 

-        t1 = values[i+1];                                                

-                                                                           

-        if(t1 != 0){                                                             

-          signLength = signLength + 1;                                       

-          sign = sign << 1;                                                   

-                                                                           

-          if(t1 < 0){                                                            

-            sign|=1;                                                     

-            t1=-t1;                                                        

-          }                                                                      

-        }                                                                        

-        codeWord   = huff_ctab10[t0][t1];                                

-        codeLength = LO_LTAB(huff_ltab9_10[t0][t1]);                     

-        WriteBits(hBitstream,codeWord,codeLength);

-        WriteBits(hBitstream,sign,signLength);

-      }

-      break;

-

-    case CODE_BOOK_ESC_NO:

-      for(i=0; i<width; i+=2) {

-        sign=0;                                                  

-        signLength=0;                                            

-        t0 = values[i+0];                                        

-                                                                   

-        if(t0 != 0){                                                     

-          signLength = signLength + 1;                               

-          sign = sign << 1;                                           

-                                                                   

-          if(t0 < 0){                                                    

-            sign|=1;                                             

-            t0=-t0;                                                

-          }                                                              

-        }                                                                

-                                                                         

-        t1 = values[i+1];                                        

-                                                                   

-        if(t1 != 0){                                                     

-          signLength = signLength + 1;                               

-          sign = sign << 1;                                           

-                                                                   

-          if(t1 < 0){                                                    

-            sign|=1;                                             

-            t1=-t1;                                                

-          }                                                              

-        }                                                                

-        t00 = min(t0,16);

-        t01 = min(t1,16);

-

-        codeWord   = huff_ctab11[t00][t01];                      

-        codeLength = huff_ltab11[t00][t01];                      

-        WriteBits(hBitstream,codeWord,codeLength);

-        WriteBits(hBitstream,sign,signLength);

-         

-        if(t0 >= 16){

-          Word16 n, p;

-          n=0;                                                   

-          p=t0;                                                  

-          while(sub(p=(p >> 1), 16) >= 0){

-             

-            WriteBits(hBitstream,1,1);

-            n = n + 1;

-          }

-          WriteBits(hBitstream,0,1);

-          n = n + 4;

-          WriteBits(hBitstream,(t0 - (1 << n)),n);

-        }

-         

-        if(t1 >= 16){

-          Word16 n, p;

-          n=0;                                                   

-          p=t1;                                                  

-          while(sub(p=(p >> 1), 16) >= 0){

-             

-            WriteBits(hBitstream,1,1);

-            n = n + 1;

-          }

-          WriteBits(hBitstream,0,1);

-          n = n + 4;

-          WriteBits(hBitstream,(t1 - (1 << n)),n);

-        }

-      }

-      break;

-

-    default:

-      break;

-  }

-  return(0);

+Word16 codeValues(Word16 *values, Word16 width, Word16 codeBook, HANDLE_BIT_BUF hBitstream)
+{
+
+  Word32 i, t0, t1, t2, t3, t00, t01;
+  UWord16 codeWord, codeLength;
+  Word16 sign, signLength;
+
+
+  switch (codeBook) {
+    case CODE_BOOK_ZERO_NO:
+      break;
+
+    case CODE_BOOK_1_NO:
+      for(i=0; i<width; i+=4) {
+        t0         = values[i+0];
+        t1         = values[i+1];
+        t2         = values[i+2];
+        t3         = values[i+3];
+        codeWord   = huff_ctab1[t0+1][t1+1][t2+1][t3+1];
+        codeLength = HI_LTAB(huff_ltab1_2[t0+1][t1+1][t2+1][t3+1]);
+        WriteBits(hBitstream, codeWord, codeLength);
+      }
+      break;
+
+    case CODE_BOOK_2_NO:
+      for(i=0; i<width; i+=4) {
+        t0         = values[i+0];
+        t1         = values[i+1];
+        t2         = values[i+2];
+        t3         = values[i+3];
+        codeWord   = huff_ctab2[t0+1][t1+1][t2+1][t3+1];
+        codeLength = LO_LTAB(huff_ltab1_2[t0+1][t1+1][t2+1][t3+1]);
+        WriteBits(hBitstream,codeWord,codeLength);
+      }
+      break;
+
+    case CODE_BOOK_3_NO:
+      for(i=0; i<width; i+=4) {
+        sign=0;
+        signLength=0;
+        t0 = values[i+0];
+
+        if(t0 != 0){
+          signLength = signLength + 1;
+          sign = sign << 1;
+
+          if(t0 < 0){
+            sign|=1;
+            t0=-t0;
+          }
+        }
+        t1 = values[i+1];
+
+        if(t1 != 0){
+          signLength = signLength + 1;
+          sign = sign << 1;
+
+          if(t1 < 0){
+            sign|=1;
+            t1=-t1;
+          }
+        }
+        t2 = values[i+2];
+
+        if(t2 != 0){
+          signLength = signLength + 1;
+          sign = sign << 1;
+
+          if(t2 < 0){
+            sign|=1;
+            t2=-t2;
+          }
+        }
+        t3 = values[i+3];
+        if(t3 != 0){
+          signLength = signLength + 1;
+          sign = sign << 1;
+
+          if(t3 < 0){
+            sign|=1;
+            t3=-t3;
+          }
+        }
+
+        codeWord   = huff_ctab3[t0][t1][t2][t3];
+        codeLength = HI_LTAB(huff_ltab3_4[t0][t1][t2][t3]);
+        WriteBits(hBitstream,codeWord,codeLength);
+        WriteBits(hBitstream,sign,signLength);
+      }
+      break;
+
+    case CODE_BOOK_4_NO:
+      for(i=0; i<width; i+=4) {
+        sign=0;
+        signLength=0;
+        t0 = values[i+0];
+
+        if(t0 != 0){
+          signLength = signLength + 1;
+          sign = sign << 1;
+          if(t0 < 0){
+            sign|=1;
+            t0=-t0;
+          }
+        }
+        t1 = values[i+1];
+
+        if(t1 != 0){
+          signLength = signLength + 1;
+          sign = sign << 1;
+
+          if(t1 < 0){
+            sign|=1;
+            t1=-t1;
+          }
+        }
+        t2 = values[i+2];
+
+        if(t2 != 0){
+          signLength = signLength + 1;
+          sign = sign << 1;
+
+          if(t2 < 0){
+            sign|=1;
+            t2=-t2;
+          }
+        }
+        t3 = values[i+3];
+
+        if(t3 != 0){
+          signLength = signLength + 1;
+          sign = sign << 1;
+
+          if(t3 < 0){
+            sign|=1;
+            t3=-t3;
+          }
+        }
+        codeWord   = huff_ctab4[t0][t1][t2][t3];
+        codeLength = LO_LTAB(huff_ltab3_4[t0][t1][t2][t3]);
+        WriteBits(hBitstream,codeWord,codeLength);
+        WriteBits(hBitstream,sign,signLength);
+      }
+      break;
+
+    case CODE_BOOK_5_NO:
+      for(i=0; i<width; i+=2) {
+        t0         = values[i+0];
+        t1         = values[i+1];
+        codeWord   = huff_ctab5[t0+4][t1+4];
+        codeLength = HI_LTAB(huff_ltab5_6[t0+4][t1+4]);
+        WriteBits(hBitstream,codeWord,codeLength);
+      }
+      break;
+
+    case CODE_BOOK_6_NO:
+      for(i=0; i<width; i+=2) {
+        t0         = values[i+0];
+        t1         = values[i+1];
+        codeWord   = huff_ctab6[t0+4][t1+4];
+        codeLength = LO_LTAB(huff_ltab5_6[t0+4][t1+4]);
+        WriteBits(hBitstream,codeWord,codeLength);
+      }
+      break;
+
+    case CODE_BOOK_7_NO:
+      for(i=0; i<width; i+=2){
+        sign=0;
+        signLength=0;
+        t0 = values[i+0];
+
+        if(t0 != 0){
+          signLength = signLength + 1;
+          sign = sign << 1;
+
+          if(t0 < 0){
+            sign|=1;
+            t0=-t0;
+          }
+        }
+
+        t1 = values[i+1];
+
+        if(t1 != 0){
+          signLength = signLength + 1;
+          sign = sign << 1;
+
+          if(t1 < 0){
+            sign|=1;
+            t1=-t1;
+          }
+        }
+        codeWord   = huff_ctab7[t0][t1];
+        codeLength = HI_LTAB(huff_ltab7_8[t0][t1]);
+        WriteBits(hBitstream,codeWord,codeLength);
+        WriteBits(hBitstream,sign,signLength);
+      }
+      break;
+
+    case CODE_BOOK_8_NO:
+      for(i=0; i<width; i+=2) {
+        sign=0;
+        signLength=0;
+        t0 = values[i+0];
+
+        if(t0 != 0){
+          signLength = signLength + 1;
+          sign = sign << 1;
+
+          if(t0 < 0){
+            sign|=1;
+            t0=-t0;
+          }
+        }
+
+        t1 = values[i+1];
+
+        if(t1 != 0){
+          signLength = signLength + 1;
+          sign = sign << 1;
+
+          if(t1 < 0){
+            sign|=1;
+            t1=-t1;
+          }
+        }
+        codeWord   = huff_ctab8[t0][t1];
+        codeLength = LO_LTAB(huff_ltab7_8[t0][t1]);
+        WriteBits(hBitstream,codeWord,codeLength);
+        WriteBits(hBitstream,sign,signLength);
+      }
+      break;
+
+    case CODE_BOOK_9_NO:
+      for(i=0; i<width; i+=2) {
+        sign=0;
+        signLength=0;
+        t0 = values[i+0];
+
+        if(t0 != 0){
+          signLength = signLength + 1;
+          sign = sign << 1;
+
+          if(t0 < 0){
+            sign|=1;
+            t0=-t0;
+          }
+        }
+
+        t1 = values[i+1];
+
+        if(t1 != 0){
+          signLength = signLength + 1;
+          sign = sign << 1;
+
+          if(t1 < 0){
+            sign|=1;
+            t1=-t1;
+          }
+        }
+        codeWord   = huff_ctab9[t0][t1];
+        codeLength = HI_LTAB(huff_ltab9_10[t0][t1]);
+        WriteBits(hBitstream,codeWord,codeLength);
+        WriteBits(hBitstream,sign,signLength);
+      }
+      break;
+
+    case CODE_BOOK_10_NO:
+      for(i=0; i<width; i+=2) {
+        sign=0;
+        signLength=0;
+        t0 = values[i+0];
+
+        if(t0 != 0){
+          signLength = signLength + 1;
+          sign = sign << 1;
+
+          if(t0 < 0){
+            sign|=1;
+            t0=-t0;
+          }
+        }
+
+        t1 = values[i+1];
+
+        if(t1 != 0){
+          signLength = signLength + 1;
+          sign = sign << 1;
+
+          if(t1 < 0){
+            sign|=1;
+            t1=-t1;
+          }
+        }
+        codeWord   = huff_ctab10[t0][t1];
+        codeLength = LO_LTAB(huff_ltab9_10[t0][t1]);
+        WriteBits(hBitstream,codeWord,codeLength);
+        WriteBits(hBitstream,sign,signLength);
+      }
+      break;
+
+    case CODE_BOOK_ESC_NO:
+      for(i=0; i<width; i+=2) {
+        sign=0;
+        signLength=0;
+        t0 = values[i+0];
+
+        if(t0 != 0){
+          signLength = signLength + 1;
+          sign = sign << 1;
+
+          if(t0 < 0){
+            sign|=1;
+            t0=-t0;
+          }
+        }
+
+        t1 = values[i+1];
+
+        if(t1 != 0){
+          signLength = signLength + 1;
+          sign = sign << 1;
+
+          if(t1 < 0){
+            sign|=1;
+            t1=-t1;
+          }
+        }
+        t00 = min(t0,16);
+        t01 = min(t1,16);
+
+        codeWord   = huff_ctab11[t00][t01];
+        codeLength = huff_ltab11[t00][t01];
+        WriteBits(hBitstream,codeWord,codeLength);
+        WriteBits(hBitstream,sign,signLength);
+
+        if(t0 >= 16){
+          Word16 n, p;
+          n=0;
+          p=t0;
+          while(sub(p=(p >> 1), 16) >= 0){
+
+            WriteBits(hBitstream,1,1);
+            n = n + 1;
+          }
+          WriteBits(hBitstream,0,1);
+          n = n + 4;
+          WriteBits(hBitstream,(t0 - (1 << n)),n);
+        }
+
+        if(t1 >= 16){
+          Word16 n, p;
+          n=0;
+          p=t1;
+          while(sub(p=(p >> 1), 16) >= 0){
+
+            WriteBits(hBitstream,1,1);
+            n = n + 1;
+          }
+          WriteBits(hBitstream,0,1);
+          n = n + 4;
+          WriteBits(hBitstream,(t1 - (1 << n)),n);
+        }
+      }
+      break;
+
+    default:
+      break;
+  }
+  return(0);
 }
 
 Word16 bitCountScalefactorDelta(Word16 delta)
@@ -871,15 +871,15 @@
 
 Word16 codeScalefactorDelta(Word16 delta, HANDLE_BIT_BUF hBitstream)
 {
-  Word32 codeWord; 
+  Word32 codeWord;
   Word16 codeLength;
-  
-   
+
+
   if(delta > CODE_BOOK_SCF_LAV || delta < -CODE_BOOK_SCF_LAV)
     return(1);
-  
-  codeWord   = huff_ctabscf[delta + CODE_BOOK_SCF_LAV];            
-  codeLength = huff_ltabscf[delta + CODE_BOOK_SCF_LAV];            
+
+  codeWord   = huff_ctabscf[delta + CODE_BOOK_SCF_LAV];
+  codeLength = huff_ltabscf[delta + CODE_BOOK_SCF_LAV];
   WriteBits(hBitstream,codeWord,codeLength);
   return(0);
 }
diff --git a/media/libstagefright/codecs/aacenc/src/bitbuffer.c b/media/libstagefright/codecs/aacenc/src/bitbuffer.c
index 3248f0b..5615ac3 100644
--- a/media/libstagefright/codecs/aacenc/src/bitbuffer.c
+++ b/media/libstagefright/codecs/aacenc/src/bitbuffer.c
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		bitbuffer.c

-

-	Content:	Bit Buffer Management functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		bitbuffer.c
+
+	Content:	Bit Buffer Management functions
+
 *******************************************************************************/
 
 #include "bitbuffer.h"
@@ -32,15 +32,15 @@
                                 UWord8 **pBitBufWord,
                                 Word16   cnt)
 {
-  *pBitBufWord += cnt;                                                                  
+  *pBitBufWord += cnt;
 
-                                                                                        
+
   if(*pBitBufWord > hBitBuf->pBitBufEnd) {
-    *pBitBufWord -= (hBitBuf->pBitBufEnd - hBitBuf->pBitBufBase + 1);                   
+    *pBitBufWord -= (hBitBuf->pBitBufEnd - hBitBuf->pBitBufBase + 1);
   }
-                                                                                        
+
   if(*pBitBufWord < hBitBuf->pBitBufBase) {
-    *pBitBufWord += (hBitBuf->pBitBufEnd - hBitBuf->pBitBufBase + 1);                   
+    *pBitBufWord += (hBitBuf->pBitBufEnd - hBitBuf->pBitBufBase + 1);
   }
 }
 
@@ -57,18 +57,18 @@
 {
   assert(bitBufSize*8 <= 32768);
 
-  hBitBuf->pBitBufBase = pBitBufBase;                                                    
-  hBitBuf->pBitBufEnd  = pBitBufBase + bitBufSize - 1;                                  
+  hBitBuf->pBitBufBase = pBitBufBase;
+  hBitBuf->pBitBufEnd  = pBitBufBase + bitBufSize - 1;
 
-  hBitBuf->pWriteNext  = pBitBufBase;                                                    
+  hBitBuf->pWriteNext  = pBitBufBase;
 
   hBitBuf->cache       = 0;
-  
-  hBitBuf->wBitPos     = 0;                                                              
-  hBitBuf->cntBits     = 0;   
-  
-  hBitBuf->size        = (bitBufSize << 3);                                             
-  hBitBuf->isValid     = 1;                                                              
+
+  hBitBuf->wBitPos     = 0;
+  hBitBuf->cntBits     = 0;
+
+  hBitBuf->size        = (bitBufSize << 3);
+  hBitBuf->isValid     = 1;
 
   return hBitBuf;
 }
@@ -81,9 +81,9 @@
 *****************************************************************************/
 void DeleteBitBuffer(HANDLE_BIT_BUF *hBitBuf)
 {
-  if(*hBitBuf)

-	(*hBitBuf)->isValid = 0;                                                               
-  *hBitBuf = NULL;                                                                       
+  if(*hBitBuf)
+	(*hBitBuf)->isValid = 0;
+  *hBitBuf = NULL;
 }
 
 /*****************************************************************************
@@ -96,15 +96,15 @@
                  UWord8 *pBitBufBase,
                  Word16  bitBufSize)
 {
-  hBitBuf->pBitBufBase = pBitBufBase;                                                    
-  hBitBuf->pBitBufEnd  = pBitBufBase + bitBufSize - 1;                                  
+  hBitBuf->pBitBufBase = pBitBufBase;
+  hBitBuf->pBitBufEnd  = pBitBufBase + bitBufSize - 1;
 
-                                                 
-  hBitBuf->pWriteNext  = pBitBufBase;                                                    
 
-  hBitBuf->wBitPos     = 0;    
-  hBitBuf->cntBits     = 0;    
-  
+  hBitBuf->pWriteNext  = pBitBufBase;
+
+  hBitBuf->wBitPos     = 0;
+  hBitBuf->cntBits     = 0;
+
   hBitBuf->cache	   = 0;
 }
 
@@ -117,7 +117,7 @@
 void CopyBitBuf(HANDLE_BIT_BUF hBitBufSrc,
                 HANDLE_BIT_BUF hBitBufDst)
 {
-  *hBitBufDst = *hBitBufSrc;                                                             
+  *hBitBufDst = *hBitBufSrc;
 }
 
 /*****************************************************************************
@@ -148,25 +148,25 @@
   if(noBitsToWrite == 0)
 	  return noBitsToWrite;
 
-  hBitBuf->cntBits += noBitsToWrite;   
+  hBitBuf->cntBits += noBitsToWrite;
 
   wBitPos = hBitBuf->wBitPos;
   wBitPos += noBitsToWrite;
-  writeValue <<= 32 - wBitPos;	
+  writeValue <<= 32 - wBitPos;
   writeValue |= hBitBuf->cache;
-  
-  while (wBitPos >= 8) 
+
+  while (wBitPos >= 8)
   {
 	  UWord8 tmp;
 	  tmp = (UWord8)((writeValue >> 24) & 0xFF);
-	  
-	  *hBitBuf->pWriteNext++ = tmp;		
+
+	  *hBitBuf->pWriteNext++ = tmp;
 	  writeValue <<= 8;
 	  wBitPos -= 8;
   }
-  
+
   hBitBuf->wBitPos = wBitPos;
   hBitBuf->cache = writeValue;
-                                                                                     
+
   return noBitsToWrite;
 }
diff --git a/media/libstagefright/codecs/aacenc/src/bitenc.c b/media/libstagefright/codecs/aacenc/src/bitenc.c
index 588c2da1..fcc12dd 100644
--- a/media/libstagefright/codecs/aacenc/src/bitenc.c
+++ b/media/libstagefright/codecs/aacenc/src/bitenc.c
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		bitenc.c

-

-	Content:	Bitstream encoder functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		bitenc.c
+
+	Content:	Bitstream encoder functions
+
 *******************************************************************************/
 
 #include "bitenc.h"
@@ -46,10 +46,10 @@
   Word16 i,sfb;
   Word16 dbgVal;
   SECTION_INFO* psectioninfo;
-  dbgVal = GetBitsAvail(hBitStream);                                     
+  dbgVal = GetBitsAvail(hBitStream);
 
   for(i=0; i<sectionData->noOfSections; i++) {
-    psectioninfo = &(sectionData->sectionInfo[i]);

+    psectioninfo = &(sectionData->sectionInfo[i]);
 	/*
        huffencode spectral data for this section
     */
@@ -100,7 +100,7 @@
   WriteBits(hBitStream,blockType,2);
   WriteBits(hBitStream,windowShape,1);
 
-   
+
   switch(blockType){
     case LONG_WINDOW:
     case START_WINDOW:
@@ -137,30 +137,30 @@
   Word16 sectLen;
   Word16 i;
   Word16 dbgVal=GetBitsAvail(hBitStream);
-       
 
-   
+
+
   switch(sectionData->blockType)
   {
     case LONG_WINDOW:
     case START_WINDOW:
     case STOP_WINDOW:
-      sectEscapeVal = SECT_ESC_VAL_LONG;                 
-      sectLenBits   = SECT_BITS_LONG;                    
+      sectEscapeVal = SECT_ESC_VAL_LONG;
+      sectLenBits   = SECT_BITS_LONG;
       break;
 
     case SHORT_WINDOW:
-      sectEscapeVal = SECT_ESC_VAL_SHORT;                
-      sectLenBits   = SECT_BITS_SHORT;                   
+      sectEscapeVal = SECT_ESC_VAL_SHORT;
+      sectLenBits   = SECT_BITS_SHORT;
       break;
   }
 
   for(i=0;i<sectionData->noOfSections;i++) {
     WriteBits(hBitStream,sectionData->sectionInfo[i].codeBook,4);
-    sectLen = sectionData->sectionInfo[i].sfbCnt;        
+    sectLen = sectionData->sectionInfo[i].sfbCnt;
 
     while(sectLen >= sectEscapeVal) {
-       
+
       WriteBits(hBitStream,sectEscapeVal,sectLenBits);
       sectLen = sectLen - sectEscapeVal;
     }
@@ -183,24 +183,24 @@
 {
   Word16 i,j,lastValScf,deltaScf;
   Word16 dbgVal = GetBitsAvail(hBitStream);
-  SECTION_INFO* psectioninfo; 
+  SECTION_INFO* psectioninfo;
 
-  lastValScf=scalefac[sectionData->firstScf];                    
+  lastValScf=scalefac[sectionData->firstScf];
 
   for(i=0;i<sectionData->noOfSections;i++){
-    psectioninfo = &(sectionData->sectionInfo[i]); 
+    psectioninfo = &(sectionData->sectionInfo[i]);
     if (psectioninfo->codeBook != CODE_BOOK_ZERO_NO){
       for (j=psectioninfo->sfbStart;
            j<psectioninfo->sfbStart+psectioninfo->sfbCnt; j++){
-         
+
         if(maxValueInSfb[j] == 0) {
-          deltaScf = 0;                                          
+          deltaScf = 0;
         }
         else {
           deltaScf = lastValScf - scalefac[j];
-          lastValScf = scalefac[j];                              
+          lastValScf = scalefac[j];
         }
-         
+
         if(codeScalefactorDelta(deltaScf,hBitStream)){
           return(1);
         }
@@ -227,7 +227,7 @@
 {
   Word16 sfb, sfbOff;
 
-   
+
   switch(msDigest)
   {
     case MS_NONE:
@@ -242,7 +242,7 @@
       WriteBits(hBitStream,SI_MS_MASK_SOME,2);
       for(sfbOff = 0; sfbOff < sfbCnt; sfbOff+=grpSfb) {
         for(sfb=0; sfb<maxSfb; sfb++) {
-             
+
           if(jsFlags[sfbOff+sfb] & MS_ON) {
             WriteBits(hBitStream,1,1);
           }
@@ -272,7 +272,7 @@
   Word16 coefBits;
   Flag isShort;
 
-       
+
   if (blockType==2) {
     isShort = 1;
     numOfWindows = TRANS_FAC;
@@ -282,52 +282,52 @@
     numOfWindows = 1;
   }
 
-  tnsPresent=0;                                                  
+  tnsPresent=0;
   for (i=0; i<numOfWindows; i++) {
-     
+
     if (tnsInfo.tnsActive[i]) {
-      tnsPresent=1;                                              
+      tnsPresent=1;
     }
   }
-   
+
   if (tnsPresent==0) {
     WriteBits(hBitStream,0,1);
   }
   else{ /* there is data to be written*/
     WriteBits(hBitStream,1,1); /*data_present */
     for (i=0; i<numOfWindows; i++) {
-       
+
       WriteBits(hBitStream,tnsInfo.tnsActive[i],(isShort?1:2));
-       
+
       if (tnsInfo.tnsActive[i]) {
-         
+
         WriteBits(hBitStream,((tnsInfo.coefRes[i] - 4)==0?1:0),1);
-         
+
         WriteBits(hBitStream,tnsInfo.length[i],(isShort?4:6));
-         
+
         WriteBits(hBitStream,tnsInfo.order[i],(isShort?3:5));
-         
+
         if (tnsInfo.order[i]){
           WriteBits(hBitStream, FILTER_DIRECTION, 1);
-           
+
           if(tnsInfo.coefRes[i] == 4) {
-            coefBits = 3;                                                
+            coefBits = 3;
             for(k=0; k<tnsInfo.order[i]; k++) {
-                 
+
               if (tnsInfo.coef[i*TNS_MAX_ORDER_SHORT+k] > 3 ||
                   tnsInfo.coef[i*TNS_MAX_ORDER_SHORT+k] < -4) {
-                coefBits = 4;                                            
+                coefBits = 4;
                 break;
               }
             }
           }
           else {
-            coefBits = 2;                                                
+            coefBits = 2;
             for(k=0; k<tnsInfo.order[i]; k++) {
-                 
+
               if (tnsInfo.coef[i*TNS_MAX_ORDER_SHORT+k] > 1 ||
                   tnsInfo.coef[i*TNS_MAX_ORDER_SHORT+k] < -2) {
-                coefBits = 3;                                            
+                coefBits = 3;
                 break;
               }
             }
@@ -335,7 +335,7 @@
           WriteBits(hBitStream, tnsInfo.coefRes[i] - coefBits, 1); /*coef_compres*/
           for (k=0; k<tnsInfo.order[i]; k++ ) {
             static const Word16 rmask[] = {0,1,3,7,15};
-             
+
             WriteBits(hBitStream,tnsInfo.coef[i*TNS_MAX_ORDER_SHORT+k] & rmask[coefBits],coefBits);
           }
         }
@@ -397,7 +397,7 @@
 
   encodeGlobalGain(globalGain, logNorm,scf[sectionData->firstScf], hBitStream);
 
-   
+
   if(!commonWindow) {
     encodeIcsInfo(sectionData->blockType, windowShape, groupingMask, sectionData, hBitStream);
   }
@@ -536,7 +536,7 @@
     Write fill Element(s):
     amount of a fill element can be 7+X*8 Bits, X element of [0..270]
   */
-    
+
   while(totFillBits >= (3+4)) {
     cnt = min(((totFillBits - (3+4)) >> 3), ((1<<4)-1));
 
@@ -545,7 +545,7 @@
 
     totFillBits = totFillBits - (3+4);
 
-     
+
     if ((cnt == (1<<4)-1)) {
 
       esc_count = min( ((totFillBits >> 3) - ((1<<4)-1)), (1<<8)-1);
@@ -555,7 +555,7 @@
     }
 
     for(i=0;i<cnt;i++) {
-       
+
       if(ancBytes)
         WriteBits(hBitStream, *ancBytes++,8);
       else
@@ -564,7 +564,7 @@
     }
   }
 }
-

+
 /*****************************************************************************
 *
 * function name: WriteBitStream
@@ -576,48 +576,48 @@
                        ELEMENT_INFO elInfo,
                        QC_OUT *qcOut,
                        PSY_OUT *psyOut,
-                       Word16 *globUsedBits,					   
-                       const UWord8 *ancBytes,

+                       Word16 *globUsedBits,
+                       const UWord8 *ancBytes,
 					   Word16 sampindex
                        ) /* returns error code */
 {
   Word16 bitMarkUp;
   Word16 elementUsedBits;
-  Word16 frameBits=0;

-

-  /*   struct bitbuffer bsWriteCopy; */

-  bitMarkUp = GetBitsAvail(hBitStream); 

-  if(qcOut->qcElement.adtsUsed)  /*  write adts header*/

-  {

-	  WriteBits(hBitStream, 0xFFF, 12); /* 12 bit Syncword */

-	  WriteBits(hBitStream, 1, 1); /* ID == 0 for MPEG4 AAC, 1 for MPEG2 AAC */

-	  WriteBits(hBitStream, 0, 2); /* layer == 0 */

-	  WriteBits(hBitStream, 1, 1); /* protection absent */

-	  WriteBits(hBitStream, 1, 2); /* profile */

-	  WriteBits(hBitStream, sampindex, 4); /* sampling rate */

-	  WriteBits(hBitStream, 0, 1); /* private bit */

-	  WriteBits(hBitStream, elInfo.nChannelsInEl, 3); /* ch. config (must be > 0) */

-								   /* simply using numChannels only works for

-									6 channels or less, else a channel

-									configuration should be written */

-	  WriteBits(hBitStream, 0, 1); /* original/copy */

-	  WriteBits(hBitStream, 0, 1); /* home */	  

-	  

-	  /* Variable ADTS header */

-	  WriteBits(hBitStream, 0, 1); /* copyr. id. bit */

-	  WriteBits(hBitStream, 0, 1); /* copyr. id. start */

-	  WriteBits(hBitStream, *globUsedBits >> 3, 13);

-	  WriteBits(hBitStream, 0x7FF, 11); /* buffer fullness (0x7FF for VBR) */

-	  WriteBits(hBitStream, 0, 2); /* raw data blocks (0+1=1) */  

-  }

+  Word16 frameBits=0;
 
-  *globUsedBits=0;                                               
+  /*   struct bitbuffer bsWriteCopy; */
+  bitMarkUp = GetBitsAvail(hBitStream);
+  if(qcOut->qcElement.adtsUsed)  /*  write adts header*/
+  {
+	  WriteBits(hBitStream, 0xFFF, 12); /* 12 bit Syncword */
+	  WriteBits(hBitStream, 1, 1); /* ID == 0 for MPEG4 AAC, 1 for MPEG2 AAC */
+	  WriteBits(hBitStream, 0, 2); /* layer == 0 */
+	  WriteBits(hBitStream, 1, 1); /* protection absent */
+	  WriteBits(hBitStream, 1, 2); /* profile */
+	  WriteBits(hBitStream, sampindex, 4); /* sampling rate */
+	  WriteBits(hBitStream, 0, 1); /* private bit */
+	  WriteBits(hBitStream, elInfo.nChannelsInEl, 3); /* ch. config (must be > 0) */
+								   /* simply using numChannels only works for
+									6 channels or less, else a channel
+									configuration should be written */
+	  WriteBits(hBitStream, 0, 1); /* original/copy */
+	  WriteBits(hBitStream, 0, 1); /* home */
+
+	  /* Variable ADTS header */
+	  WriteBits(hBitStream, 0, 1); /* copyr. id. bit */
+	  WriteBits(hBitStream, 0, 1); /* copyr. id. start */
+	  WriteBits(hBitStream, *globUsedBits >> 3, 13);
+	  WriteBits(hBitStream, 0x7FF, 11); /* buffer fullness (0x7FF for VBR) */
+	  WriteBits(hBitStream, 0, 2); /* raw data blocks (0+1=1) */
+  }
+
+  *globUsedBits=0;
 
   {
 
     Word16 *sfbOffset[2];
     TNS_INFO tnsInfo[2];
-    elementUsedBits = 0;                                         
+    elementUsedBits = 0;
 
     switch (elInfo.elType) {
 
@@ -636,7 +636,7 @@
         {
           Word16 msDigest;
           Word16 *msFlags = psyOut->psyOutElement.toolsInfo.msMask;
-          msDigest = psyOut->psyOutElement.toolsInfo.msDigest;                        
+          msDigest = psyOut->psyOutElement.toolsInfo.msDigest;
           sfbOffset[0] =
             psyOut->psyOutChannel[elInfo.ChannelIndex[0]].sfbOffsets;
           sfbOffset[1] =
@@ -668,20 +668,20 @@
   }
 
   writeFillElement(NULL,
-                   qcOut->totFillBits, 
+                   qcOut->totFillBits,
                    hBitStream);
 
   WriteBits(hBitStream,ID_END,3);
 
   /* byte alignement */
-  WriteBits(hBitStream,0, (8 - (hBitStream->cntBits & 7)) & 7);          
-  
+  WriteBits(hBitStream,0, (8 - (hBitStream->cntBits & 7)) & 7);
+
   *globUsedBits = *globUsedBits- bitMarkUp;
-  bitMarkUp = GetBitsAvail(hBitStream);                                  
+  bitMarkUp = GetBitsAvail(hBitStream);
   *globUsedBits = *globUsedBits + bitMarkUp;
   frameBits = frameBits + *globUsedBits;
 
-   
+
   if (frameBits !=  (qcOut->totStaticBitsUsed+qcOut->totDynBitsUsed + qcOut->totAncBitsUsed +
                      qcOut->totFillBits + qcOut->alignBits)) {
     return(-1);
diff --git a/media/libstagefright/codecs/aacenc/src/block_switch.c b/media/libstagefright/codecs/aacenc/src/block_switch.c
index c0054f7..47fd15e 100644
--- a/media/libstagefright/codecs/aacenc/src/block_switch.c
+++ b/media/libstagefright/codecs/aacenc/src/block_switch.c
@@ -1,27 +1,27 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		block_switch.c

-

-	Content:	Block switching functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		block_switch.c
+
+	Content:	Block switching functions
+
 *******************************************************************************/
 
-#include "typedef.h"

-#include "basic_op.h"

+#include "typedef.h"
+#include "basic_op.h"
 #include "oper_32b.h"
 #include "psy_const.h"
 #include "block_switch.h"
@@ -52,7 +52,7 @@
   IIR high pass coeffs
 */
 Word32 hiPassCoeff[BLOCK_SWITCHING_IIR_LEN] = {
-  0xbec8b439, 0x609d4952  /* -0.5095f, 0.7548f */ 
+  0xbec8b439, 0x609d4952  /* -0.5095f, 0.7548f */
 };
 
 static const Word32 accWindowNrgFac = 0x26666666;                   /* factor for accumulating filtered window energies 0.3 */
@@ -76,8 +76,8 @@
                           const Word32 bitRate, const Word16 nChannels)
 {
   /* select attackRatio */
-           
-  if ((sub(nChannels,1)==0 && L_sub(bitRate, 24000) > 0) || 
+
+  if ((sub(nChannels,1)==0 && L_sub(bitRate, 24000) > 0) ||
       (sub(nChannels,1)>0 && bitRate > (nChannels * 16000))) {
     blockSwitchingControl->invAttackRatio = invAttackRatioHighBr;
   }
@@ -116,7 +116,7 @@
 
   /* Reset grouping info */
   for (i=0; i<TRANS_FAC; i++) {
-    blockSwitchingControl->groupLen[i] = 0;                                      
+    blockSwitchingControl->groupLen[i] = 0;
   }
 
 
@@ -125,21 +125,21 @@
                                                           &blockSwitchingControl->attackIndex,
                                                           BLOCK_SWITCH_WINDOWS);
 
-  blockSwitchingControl->attackIndex = blockSwitchingControl->lastAttackIndex;   
+  blockSwitchingControl->attackIndex = blockSwitchingControl->lastAttackIndex;
 
   /* Set grouping info */
-  blockSwitchingControl->noOfGroups = MAX_NO_OF_GROUPS;                          
+  blockSwitchingControl->noOfGroups = MAX_NO_OF_GROUPS;
 
   for (i=0; i<MAX_NO_OF_GROUPS; i++) {
-    blockSwitchingControl->groupLen[i] = suggestedGroupingTable[blockSwitchingControl->attackIndex][i];  
-  }

-	
+    blockSwitchingControl->groupLen[i] = suggestedGroupingTable[blockSwitchingControl->attackIndex][i];
+  }
+
   /* if the samplerate is less than 16000, it should be all the short block, avoid pre&post echo */
   if(sampleRate >= 16000) {
 	  /* Save current window energy as last window energy */
 	  for (w=0; w<BLOCK_SWITCH_WINDOWS; w++) {
-		  blockSwitchingControl->windowNrg[0][w] = blockSwitchingControl->windowNrg[1][w];             
-		  blockSwitchingControl->windowNrgF[0][w] = blockSwitchingControl->windowNrgF[1][w];           
+		  blockSwitchingControl->windowNrg[0][w] = blockSwitchingControl->windowNrg[1][w];
+		  blockSwitchingControl->windowNrgF[0][w] = blockSwitchingControl->windowNrgF[1][w];
 	  }
 
 
@@ -147,10 +147,10 @@
 	  CalcWindowEnergy(blockSwitchingControl, timeSignal, chIncrement, BLOCK_SWITCH_WINDOW_LEN);
 
 	  /* reset attack */
-	  blockSwitchingControl->attack = FALSE;                                         
+	  blockSwitchingControl->attack = FALSE;
 
-	  enMax = 0;                                                                     
-	  enM1 = blockSwitchingControl->windowNrgF[0][BLOCK_SWITCH_WINDOWS-1];           
+	  enMax = 0;
+	  enM1 = blockSwitchingControl->windowNrgF[0][BLOCK_SWITCH_WINDOWS-1];
 
 	  for (w=0; w<BLOCK_SWITCH_WINDOWS; w++) {
 		  Word32 enM1_Tmp, accWindowNrg_Tmp, windowNrgF_Tmp;
@@ -172,15 +172,15 @@
 		  /* if the energy with the ratio is bigger than the average, and the attack and short block  */
 		  if ((fixmul(windowNrgF_Tmp, blockSwitchingControl->invAttackRatio) >> windowNrgF_Shf) >
 			  blockSwitchingControl->accWindowNrg ) {
-				  blockSwitchingControl->attack = TRUE;                                      
-				  blockSwitchingControl->lastAttackIndex = w;                                
+				  blockSwitchingControl->attack = TRUE;
+				  blockSwitchingControl->lastAttackIndex = w;
 		  }
-		  enM1 = blockSwitchingControl->windowNrgF[1][w];                              
+		  enM1 = blockSwitchingControl->windowNrgF[1][w];
 		  enMax = max(enMax, enM1);
 	  }
 
 	  if (enMax < minAttackNrg) {
-		  blockSwitchingControl->attack = FALSE;                                       
+		  blockSwitchingControl->attack = FALSE;
 	  }
   }
   else
@@ -188,22 +188,22 @@
 	  blockSwitchingControl->attack = TRUE;
   }
 
-  /* Check if attack spreads over frame border */     
+  /* Check if attack spreads over frame border */
   if ((!blockSwitchingControl->attack) && (blockSwitchingControl->lastattack)) {
-     
+
     if (blockSwitchingControl->attackIndex == TRANS_FAC-1) {
-      blockSwitchingControl->attack = TRUE;                                      
+      blockSwitchingControl->attack = TRUE;
     }
 
-    blockSwitchingControl->lastattack = FALSE;                                   
+    blockSwitchingControl->lastattack = FALSE;
   }
   else {
-    blockSwitchingControl->lastattack = blockSwitchingControl->attack;           
+    blockSwitchingControl->lastattack = blockSwitchingControl->attack;
   }
 
-  blockSwitchingControl->windowSequence =  blockSwitchingControl->nextwindowSequence;    
+  blockSwitchingControl->windowSequence =  blockSwitchingControl->nextwindowSequence;
 
-     
+
   if (blockSwitchingControl->attack) {
     blockSwitchingControl->nextwindowSequence = SHORT_WINDOW;
   }
@@ -211,27 +211,27 @@
     blockSwitchingControl->nextwindowSequence = LONG_WINDOW;
   }
 
-  /* update short block group */ 
+  /* update short block group */
   if (blockSwitchingControl->nextwindowSequence == SHORT_WINDOW) {
-     
+
     if (blockSwitchingControl->windowSequence== LONG_WINDOW) {
-      blockSwitchingControl->windowSequence = START_WINDOW;                      
+      blockSwitchingControl->windowSequence = START_WINDOW;
     }
-     
+
     if (blockSwitchingControl->windowSequence == STOP_WINDOW) {
-      blockSwitchingControl->windowSequence = SHORT_WINDOW;                      
-      blockSwitchingControl->noOfGroups = 3;                                     
-      blockSwitchingControl->groupLen[0] = 3;                                    
-      blockSwitchingControl->groupLen[1] = 3;                                    
-      blockSwitchingControl->groupLen[2] = 2;                                    
+      blockSwitchingControl->windowSequence = SHORT_WINDOW;
+      blockSwitchingControl->noOfGroups = 3;
+      blockSwitchingControl->groupLen[0] = 3;
+      blockSwitchingControl->groupLen[1] = 3;
+      blockSwitchingControl->groupLen[2] = 2;
     }
   }
 
-  /* update block type */  
+  /* update block type */
   if (blockSwitchingControl->nextwindowSequence == LONG_WINDOW) {
-     
+
     if (blockSwitchingControl->windowSequence == SHORT_WINDOW) {
-      blockSwitchingControl->nextwindowSequence = STOP_WINDOW;                   
+      blockSwitchingControl->nextwindowSequence = STOP_WINDOW;
     }
   }
 
@@ -252,17 +252,17 @@
   Word32 i, idx;
 
   /* Search maximum value in array and return index and value */
-  max = 0;                                                       
-  idx = 0;                                                       
+  max = 0;
+  idx = 0;
 
   for (i = 0; i < n; i++) {
-     
+
     if (in[i+1]  > max) {
-      max = in[i+1];                                             
-      idx = i;                                                   
+      max = in[i+1];
+      idx = i;
     }
   }
-  *index = idx;                                                  
+  *index = idx;
 
   return(max);
 }
@@ -274,7 +274,7 @@
 * returns:      TRUE if success
 *
 **********************************************************************************/
-#ifndef ARMV5E

+#ifndef ARMV5E
 Word32 CalcWindowEnergy(BLOCK_SWITCHING_CONTROL *blockSwitchingControl,
                         Word16 *timeSignal,
                         Word16 chIncrement,
@@ -283,46 +283,46 @@
   Word32 w, i, wOffset, tidx, ch;
   Word32 accuUE, accuFE;
   Word32 tempUnfiltered;
-  Word32 tempFiltered;

-  Word32 states0, states1;

-  Word32 Coeff0, Coeff1;

-

+  Word32 tempFiltered;
+  Word32 states0, states1;
+  Word32 Coeff0, Coeff1;
 
-  states0 = blockSwitchingControl->iirStates[0];

-  states1 = blockSwitchingControl->iirStates[1];

-  Coeff0 = hiPassCoeff[0];

+
+  states0 = blockSwitchingControl->iirStates[0];
+  states1 = blockSwitchingControl->iirStates[1];
+  Coeff0 = hiPassCoeff[0];
   Coeff1 = hiPassCoeff[1];
-  tidx = 0;                                                   
+  tidx = 0;
   for (w=0; w < BLOCK_SWITCH_WINDOWS; w++) {
 
-    accuUE = 0;                                                  
-    accuFE = 0;                                                  
+    accuUE = 0;
+    accuFE = 0;
 
     for(i=0; i<windowLen; i++) {
-	  Word32 accu1, accu2, accu3;

-	  Word32 out;

+	  Word32 accu1, accu2, accu3;
+	  Word32 out;
 	  tempUnfiltered = timeSignal[tidx];
       tidx = tidx + chIncrement;
-

-	  accu1 = L_mpy_ls(Coeff1, tempUnfiltered);

-	  accu2 = fixmul( Coeff0, states1 );

-	  accu3 = accu1 - states0;

-	  out = accu3 - accu2;

-

-	  states0 = accu1;             

-	  states1 = out;               

-

-      tempFiltered = extract_h(out);	  
+
+	  accu1 = L_mpy_ls(Coeff1, tempUnfiltered);
+	  accu2 = fixmul( Coeff0, states1 );
+	  accu3 = accu1 - states0;
+	  out = accu3 - accu2;
+
+	  states0 = accu1;
+	  states1 = out;
+
+      tempFiltered = extract_h(out);
       accuUE += (tempUnfiltered * tempUnfiltered) >> ENERGY_SHIFT;
       accuFE += (tempFiltered * tempFiltered) >> ENERGY_SHIFT;
     }
 
-    blockSwitchingControl->windowNrg[1][w] = accuUE;             
-    blockSwitchingControl->windowNrgF[1][w] = accuFE;            
+    blockSwitchingControl->windowNrg[1][w] = accuUE;
+    blockSwitchingControl->windowNrgF[1][w] = accuFE;
 
-  }

-

-  blockSwitchingControl->iirStates[0] = states0;

+  }
+
+  blockSwitchingControl->iirStates[0] = states0;
   blockSwitchingControl->iirStates[1] = states1;
 
   return(TRUE);
@@ -346,8 +346,8 @@
   accu2 = fixmul( coeff[0], states[1] );
   out = accu3 - accu2;
 
-  states[0] = accu1;             
-  states[1] = out;               
+  states[0] = accu1;
+  states[1] = out;
 
   return round16(out);
 }
@@ -374,54 +374,54 @@
                           const Word16 nChannels)
 {
   Word16 i;
-  Word16 patchType = LONG_WINDOW;                
+  Word16 patchType = LONG_WINDOW;
 
-   
+
   if (nChannels == 1) { /* Mono */
     if (blockSwitchingControlLeft->windowSequence != SHORT_WINDOW) {
-      blockSwitchingControlLeft->noOfGroups = 1;                         
-      blockSwitchingControlLeft->groupLen[0] = 1;                        
+      blockSwitchingControlLeft->noOfGroups = 1;
+      blockSwitchingControlLeft->groupLen[0] = 1;
 
       for (i=1; i<TRANS_FAC; i++) {
-        blockSwitchingControlLeft->groupLen[i] = 0;                      
+        blockSwitchingControlLeft->groupLen[i] = 0;
       }
     }
   }
   else { /* Stereo common Window */
-    patchType = synchronizedBlockTypeTable[patchType][blockSwitchingControlLeft->windowSequence];        
-    patchType = synchronizedBlockTypeTable[patchType][blockSwitchingControlRight->windowSequence];       
+    patchType = synchronizedBlockTypeTable[patchType][blockSwitchingControlLeft->windowSequence];
+    patchType = synchronizedBlockTypeTable[patchType][blockSwitchingControlRight->windowSequence];
 
     /* Set synchronized Blocktype */
-    blockSwitchingControlLeft->windowSequence = patchType;               
-    blockSwitchingControlRight->windowSequence = patchType;              
+    blockSwitchingControlLeft->windowSequence = patchType;
+    blockSwitchingControlRight->windowSequence = patchType;
 
-    /* Synchronize grouping info */     
+    /* Synchronize grouping info */
     if(patchType != SHORT_WINDOW) { /* Long Blocks */
       /* Set grouping info */
-      blockSwitchingControlLeft->noOfGroups = 1;                         
-      blockSwitchingControlRight->noOfGroups = 1;                        
-      blockSwitchingControlLeft->groupLen[0] = 1;                        
-      blockSwitchingControlRight->groupLen[0] = 1;                       
+      blockSwitchingControlLeft->noOfGroups = 1;
+      blockSwitchingControlRight->noOfGroups = 1;
+      blockSwitchingControlLeft->groupLen[0] = 1;
+      blockSwitchingControlRight->groupLen[0] = 1;
 
       for (i=1; i<TRANS_FAC; i++) {
-        blockSwitchingControlLeft->groupLen[i] = 0;                      
-        blockSwitchingControlRight->groupLen[i] = 0;                     
+        blockSwitchingControlLeft->groupLen[i] = 0;
+        blockSwitchingControlRight->groupLen[i] = 0;
       }
     }
     else {
-       
+
       if (blockSwitchingControlLeft->maxWindowNrg > blockSwitchingControlRight->maxWindowNrg) {
         /* Left Channel wins */
-        blockSwitchingControlRight->noOfGroups = blockSwitchingControlLeft->noOfGroups;          
+        blockSwitchingControlRight->noOfGroups = blockSwitchingControlLeft->noOfGroups;
         for (i=0; i<TRANS_FAC; i++) {
-          blockSwitchingControlRight->groupLen[i] = blockSwitchingControlLeft->groupLen[i];      
+          blockSwitchingControlRight->groupLen[i] = blockSwitchingControlLeft->groupLen[i];
         }
       }
       else {
         /* Right Channel wins */
-        blockSwitchingControlLeft->noOfGroups = blockSwitchingControlRight->noOfGroups;          
+        blockSwitchingControlLeft->noOfGroups = blockSwitchingControlRight->noOfGroups;
         for (i=0; i<TRANS_FAC; i++) {
-          blockSwitchingControlLeft->groupLen[i] = blockSwitchingControlRight->groupLen[i];      
+          blockSwitchingControlLeft->groupLen[i] = blockSwitchingControlRight->groupLen[i];
         }
       }
     }
diff --git a/media/libstagefright/codecs/aacenc/src/channel_map.c b/media/libstagefright/codecs/aacenc/src/channel_map.c
index 247293b..f6552ed 100644
--- a/media/libstagefright/codecs/aacenc/src/channel_map.c
+++ b/media/libstagefright/codecs/aacenc/src/channel_map.c
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		channel_map.c

-

-	Content:	channel mapping functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		channel_map.c
+
+	Content:	channel mapping functions
+
 *******************************************************************************/
 
 #include "channel_map.h"
@@ -29,32 +29,32 @@
 
 static Word16 initElement(ELEMENT_INFO* elInfo, ELEMENT_TYPE elType)
 {
-  Word16 error=0;                                    
+  Word16 error=0;
 
-  elInfo->elType=elType;                             
+  elInfo->elType=elType;
 
   switch(elInfo->elType) {
 
     case ID_SCE:
-      elInfo->nChannelsInEl=1;                       
+      elInfo->nChannelsInEl=1;
 
-      elInfo->ChannelIndex[0]=0;                     
+      elInfo->ChannelIndex[0]=0;
 
-      elInfo->instanceTag=0;                         
+      elInfo->instanceTag=0;
       break;
 
     case ID_CPE:
 
-      elInfo->nChannelsInEl=2;                        
+      elInfo->nChannelsInEl=2;
 
-      elInfo->ChannelIndex[0]=0;                      
-      elInfo->ChannelIndex[1]=1;                      
+      elInfo->ChannelIndex[0]=0;
+      elInfo->ChannelIndex[1]=1;
 
-      elInfo->instanceTag=0;                    
+      elInfo->instanceTag=0;
       break;
 
     default:
-      error=1;                                  
+      error=1;
   }
 
   return error;
@@ -64,11 +64,11 @@
 Word16 InitElementInfo (Word16 nChannels, ELEMENT_INFO* elInfo)
 {
   Word16 error;
-  error = 0;                                        
+  error = 0;
 
   switch(nChannels) {
 
-    case 1: 
+    case 1:
       initElement(elInfo, ID_SCE);
       break;
 
@@ -77,7 +77,7 @@
       break;
 
     default:
-      error=4;                                         
+      error=4;
   }
 
   return error;
@@ -91,18 +91,18 @@
                        Word16 staticBitsTot)
 {
   Word16 error;
-  error = 0;                                    
+  error = 0;
 
    switch(elInfo.nChannelsInEl) {
     case 1:
-      elementBits->chBitrate = bitrateTot;                     
+      elementBits->chBitrate = bitrateTot;
       elementBits->averageBits = averageBitsTot - staticBitsTot;
-      elementBits->maxBits = maxChannelBits;                   
+      elementBits->maxBits = maxChannelBits;
 
       elementBits->maxBitResBits = maxChannelBits - averageBitsTot;
-      elementBits->maxBitResBits = elementBits->maxBitResBits - (elementBits->maxBitResBits & 7); 
-      elementBits->bitResLevel = elementBits->maxBitResBits;   
-      elementBits->relativeBits  = 0x4000; /* 1.0f/2 */        
+      elementBits->maxBitResBits = elementBits->maxBitResBits - (elementBits->maxBitResBits & 7);
+      elementBits->bitResLevel = elementBits->maxBitResBits;
+      elementBits->relativeBits  = 0x4000; /* 1.0f/2 */
       break;
 
     case 2:
@@ -111,13 +111,13 @@
       elementBits->maxBits     = maxChannelBits << 1;
 
       elementBits->maxBitResBits = (maxChannelBits << 1) - averageBitsTot;
-      elementBits->maxBitResBits = elementBits->maxBitResBits - (elementBits->maxBitResBits & 7);   
-      elementBits->bitResLevel = elementBits->maxBitResBits;     
-      elementBits->relativeBits = 0x4000; /* 1.0f/2 */           
+      elementBits->maxBitResBits = elementBits->maxBitResBits - (elementBits->maxBitResBits & 7);
+      elementBits->bitResLevel = elementBits->maxBitResBits;
+      elementBits->relativeBits = 0x4000; /* 1.0f/2 */
       break;
 
     default:
-      error = 1;                                                 
+      error = 1;
   }
   return error;
 }
diff --git a/media/libstagefright/codecs/aacenc/src/dyn_bits.c b/media/libstagefright/codecs/aacenc/src/dyn_bits.c
index 3deacca..3d2efdc 100644
--- a/media/libstagefright/codecs/aacenc/src/dyn_bits.c
+++ b/media/libstagefright/codecs/aacenc/src/dyn_bits.c
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		dyn_bits.c

-

-	Content:	Noiseless coder module functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		dyn_bits.c
+
+	Content:	Noiseless coder module functions
+
 *******************************************************************************/
 
 #include "aac_rom.h"
@@ -45,12 +45,12 @@
   for (i=0; i<maxSfb; i++) {
     Word16 sfbWidth, maxVal;
 
-    sectionInfo[i].sfbCnt = 1;                                   
-    sectionInfo[i].sfbStart = i;                                 
-    sectionInfo[i].sectionBits = INVALID_BITCOUNT;               
-    sectionInfo[i].codeBook = -1;                                
-    sfbWidth = sfbOffset[i + 1] - sfbOffset[i];              
-    maxVal = sfbMax[i];                                          
+    sectionInfo[i].sfbCnt = 1;
+    sectionInfo[i].sfbStart = i;
+    sectionInfo[i].sectionBits = INVALID_BITCOUNT;
+    sectionInfo[i].codeBook = -1;
+    sfbWidth = sfbOffset[i + 1] - sfbOffset[i];
+    maxVal = sfbMax[i];
     bitCount(quantSpectrum + sfbOffset[i], sfbWidth, maxVal, bitLookUp[i]);
   }
 }
@@ -66,13 +66,13 @@
 findBestBook(const Word16 *bc, Word16 *book)
 {
   Word32 minBits, j;
-  minBits = INVALID_BITCOUNT;                                    
+  minBits = INVALID_BITCOUNT;
 
   for (j=0; j<=CODE_BOOK_ESC_NDX; j++) {
-     
+
     if (bc[j] < minBits) {
-      minBits = bc[j];                                           
-      *book = j;                                                 
+      minBits = bc[j];
+      *book = j;
     }
   }
   return extract_l(minBits);
@@ -82,12 +82,12 @@
 findMinMergeBits(const Word16 *bc1, const Word16 *bc2)
 {
   Word32 minBits, j, sum;
-  minBits = INVALID_BITCOUNT;                                    
+  minBits = INVALID_BITCOUNT;
 
   for (j=0; j<=CODE_BOOK_ESC_NDX; j++) {
     sum = bc1[j] + bc2[j];
     if (sum < minBits) {
-      minBits = sum;                                             
+      minBits = sum;
     }
   }
   return extract_l(minBits);
@@ -109,13 +109,13 @@
              const Word16 maxSfb, Word16 *maxNdx)
 {
   Word32 i, maxMergeGain;
-  maxMergeGain = 0;                                              
+  maxMergeGain = 0;
 
   for (i=0; i+sectionInfo[i].sfbCnt < maxSfb; i += sectionInfo[i].sfbCnt) {
-     
+
     if (mergeGainLookUp[i] > maxMergeGain) {
-      maxMergeGain = mergeGainLookUp[i];                         
-      *maxNdx = i;                                               
+      maxMergeGain = mergeGainLookUp[i];
+      *maxNdx = i;
     }
   }
   return extract_l(maxMergeGain);
@@ -159,7 +159,7 @@
 
   for (i=0; i<maxSfb; i++) {
     /* Side-Info bits will be calculated in Stage 1!  */
-     
+
     if (sectionInfo[i].sectionBits == INVALID_BITCOUNT) {
       sectionInfo[i].sectionBits = findBestBook(bitLookUp[i], &(sectionInfo[i].codeBook));
     }
@@ -177,16 +177,16 @@
          const Word16 maxSfb,
          const Word16 *sideInfoTab)
 {
-  SECTION_INFO * sectionInfo_s;

-  SECTION_INFO * sectionInfo_e;

+  SECTION_INFO * sectionInfo_s;
+  SECTION_INFO * sectionInfo_e;
   Word32 mergeStart, mergeEnd;
-  mergeStart = 0;                                                        
+  mergeStart = 0;
 
   do {
 
-    sectionInfo_s = sectionInfo + mergeStart;

+    sectionInfo_s = sectionInfo + mergeStart;
 	for (mergeEnd=mergeStart+1; mergeEnd<maxSfb; mergeEnd++) {
-      sectionInfo_e = sectionInfo + mergeEnd; 
+      sectionInfo_e = sectionInfo + mergeEnd;
       if (sectionInfo_s->codeBook != sectionInfo_e->codeBook)
         break;
       sectionInfo_s->sfbCnt += 1;
@@ -196,11 +196,11 @@
     }
 
     sectionInfo_s->sectionBits += sideInfoTab[sectionInfo_s->sfbCnt];
-    sectionInfo[mergeEnd - 1].sfbStart = sectionInfo_s->sfbStart;      /* speed up prev search */  
+    sectionInfo[mergeEnd - 1].sfbStart = sectionInfo_s->sfbStart;      /* speed up prev search */
 
-    mergeStart = mergeEnd;                                               
+    mergeStart = mergeEnd;
 
-     
+
   } while (mergeStart - maxSfb < 0);
 }
 
@@ -230,7 +230,7 @@
 
     maxMergeGain = findMaxMerge(mergeGainLookUp, sectionInfo, maxSfb, &maxNdx);
 
-     
+
     if (maxMergeGain <= 0)
       break;
 
@@ -244,7 +244,7 @@
 
     mergeBitLookUp(bitLookUp[maxNdx], bitLookUp[maxNdxNext]);
 
-     
+
     if (maxNdx != 0) {
       maxNdxLast = sectionInfo[maxNdx - 1].sfbStart;
       mergeGainLookUp[maxNdxLast] = CalcMergeGain(sectionInfo,
@@ -255,9 +255,9 @@
     }
     maxNdxNext = maxNdx + sectionInfo[maxNdx].sfbCnt;
 
-    sectionInfo[maxNdxNext - 1].sfbStart = sectionInfo[maxNdx].sfbStart;             
+    sectionInfo[maxNdxNext - 1].sfbStart = sectionInfo[maxNdx].sfbStart;
 
-     
+
     if (maxNdxNext - maxSfb < 0) {
       mergeGainLookUp[maxNdx] = CalcMergeGain(sectionInfo,
                                               bitLookUp,
@@ -286,7 +286,7 @@
 
   /*
     use appropriate side info table
-  */   
+  */
   switch (blockType)
   {
     case LONG_WINDOW:
@@ -300,11 +300,11 @@
   }
 
 
-  sectionData->noOfSections = 0;                                         
-  sectionData->huffmanBits = 0;                                          
-  sectionData->sideInfoBits = 0;                                         
+  sectionData->noOfSections = 0;
+  sectionData->huffmanBits = 0;
+  sectionData->sideInfoBits = 0;
 
-   
+
   if (sectionData->maxSfbPerGroup == 0)
     return;
 
@@ -353,7 +353,7 @@
       sectionData->huffmanBits = (sectionData->huffmanBits +
                                      (sectionInfo[i].sectionBits - sideInfoTab[sectionInfo[i].sfbCnt]));
       sectionData->sideInfoBits = (sectionData->sideInfoBits + sideInfoTab[sectionInfo[i].sfbCnt]);
-      sectionData->sectionInfo[sectionData->noOfSections] = sectionInfo[i];             
+      sectionData->sectionInfo[sectionData->noOfSections] = sectionInfo[i];
       sectionData->noOfSections = sectionData->noOfSections + 1;
     }
   }
@@ -372,9 +372,9 @@
                      SECTION_DATA * sectionData)
 
 {
-  SECTION_INFO *psectionInfo;

-  SECTION_INFO *psectionInfom;

-

+  SECTION_INFO *psectionInfo;
+  SECTION_INFO *psectionInfom;
+
   /* counter */
   Word32 i = 0; /* section counter */
   Word32 j = 0; /* sfb counter */
@@ -386,64 +386,64 @@
   Word32 lastValScf     = 0;
   Word32 deltaScf       = 0;
   Flag found            = 0;
-  Word32 scfSkipCounter = 0;           
-         
+  Word32 scfSkipCounter = 0;
 
-  sectionData->scalefacBits = 0;                                 
 
-   
+  sectionData->scalefacBits = 0;
+
+
   if (scalefacGain == NULL) {
     return;
   }
 
-  lastValScf = 0;                                                
-  sectionData->firstScf = 0;        

-  
+  lastValScf = 0;
+  sectionData->firstScf = 0;
+
   psectionInfo = sectionData->sectionInfo;
   for (i=0; i<sectionData->noOfSections; i++) {
-     
+
     if (psectionInfo->codeBook != CODE_BOOK_ZERO_NO) {
-      sectionData->firstScf = psectionInfo->sfbStart;      
-      lastValScf = scalefacGain[sectionData->firstScf];                  
+      sectionData->firstScf = psectionInfo->sfbStart;
+      lastValScf = scalefacGain[sectionData->firstScf];
       break;
-    }

+    }
 	psectionInfo += 1;
-  }

+  }
 
   psectionInfo = sectionData->sectionInfo;
   for (i=0; i<sectionData->noOfSections; i++, psectionInfo += 1) {
-       
+
     if (psectionInfo->codeBook != CODE_BOOK_ZERO_NO
         && psectionInfo->codeBook != CODE_BOOK_PNS_NO) {
       for (j = psectionInfo->sfbStart;
            j < (psectionInfo->sfbStart + psectionInfo->sfbCnt); j++) {
         /* check if we can repeat the last value to save bits */
-         
+
         if (maxValueInSfb[j] == 0) {
-          found = 0;                                                     
-           
+          found = 0;
+
           if (scfSkipCounter == 0) {
             /* end of section */
-             
+
             if (j - ((psectionInfo->sfbStart + psectionInfo->sfbCnt) - 1) == 0) {
-              found = 0;                                                 
+              found = 0;
             }
             else {
               for (k = j + 1; k < psectionInfo->sfbStart + psectionInfo->sfbCnt; k++) {
-                 
+
                 if (maxValueInSfb[k] != 0) {
                   int tmp = L_abs(scalefacGain[k] - lastValScf);
-				  found = 1;                                             
-                   
+				  found = 1;
+
                   if ( tmp < CODE_BOOK_SCF_LAV) {
                     /* save bits */
-                    deltaScf = 0;                                        
+                    deltaScf = 0;
                   }
                   else {
                     /* do not save bits */
                     deltaScf = lastValScf - scalefacGain[j];
-                    lastValScf = scalefacGain[j];                        
-                    scfSkipCounter = 0;                                  
+                    lastValScf = scalefacGain[j];
+                    scfSkipCounter = 0;
                   }
                   break;
                 }
@@ -451,50 +451,50 @@
                 scfSkipCounter = scfSkipCounter + 1;
               }
             }
-			

+
 			psectionInfom = psectionInfo + 1;
             /* search for the next maxValueInSfb[] != 0 in all other sections */
             for (m = i + 1; (m < sectionData->noOfSections) && (found == 0); m++) {
-                 
+
               if ((psectionInfom->codeBook != CODE_BOOK_ZERO_NO) &&
                   (psectionInfom->codeBook != CODE_BOOK_PNS_NO)) {
                 for (n = psectionInfom->sfbStart;
                      n < (psectionInfom->sfbStart + psectionInfom->sfbCnt); n++) {
-                   
+
                   if (maxValueInSfb[n] != 0) {
-                    found = 1;                                           
-                     
+                    found = 1;
+
                     if ( (abs_s(scalefacGain[n] - lastValScf) < CODE_BOOK_SCF_LAV)) {
-                      deltaScf = 0;                                      
+                      deltaScf = 0;
                     }
                     else {
                       deltaScf = (lastValScf - scalefacGain[j]);
-                      lastValScf = scalefacGain[j];                      
-                      scfSkipCounter = 0;                                
+                      lastValScf = scalefacGain[j];
+                      scfSkipCounter = 0;
                     }
                     break;
                   }
                   /* count scalefactor skip */
                   scfSkipCounter = scfSkipCounter + 1;
                 }
-              }

-

+              }
+
 			  psectionInfom += 1;
             }
-             
+
             if (found == 0) {
-              deltaScf = 0;                                              
-              scfSkipCounter = 0;                                        
+              deltaScf = 0;
+              scfSkipCounter = 0;
             }
           }
           else {
-            deltaScf = 0;                                                
+            deltaScf = 0;
             scfSkipCounter = scfSkipCounter - 1;
-          }

+          }
         }
         else {
           deltaScf = lastValScf - scalefacGain[j];
-          lastValScf = scalefacGain[j];                                  
+          lastValScf = scalefacGain[j];
         }
         sectionData->scalefacBits += bitCountScalefactorDelta(deltaScf);
       }
@@ -517,14 +517,14 @@
             const Word16  *sfbOffset,
             SECTION_DATA  *sectionData)
 {
-  sectionData->blockType      = blockType;                       
-  sectionData->sfbCnt         = sfbCnt;                          
-  sectionData->sfbPerGroup    = sfbPerGroup;           
+  sectionData->blockType      = blockType;
+  sectionData->sfbCnt         = sfbCnt;
+  sectionData->sfbPerGroup    = sfbPerGroup;
   if(sfbPerGroup)
-	sectionData->noOfGroups   = sfbCnt/sfbPerGroup; 
+	sectionData->noOfGroups   = sfbCnt/sfbPerGroup;
   else
 	sectionData->noOfGroups   = 0x7fff;
-  sectionData->maxSfbPerGroup = maxSfbPerGroup;                  
+  sectionData->maxSfbPerGroup = maxSfbPerGroup;
 
   noiselessCounter(sectionData,
                    sectionData->mergeGainLookUp,
@@ -539,7 +539,7 @@
            sectionData);
 
 
-  return (sectionData->huffmanBits + sectionData->sideInfoBits + 

+  return (sectionData->huffmanBits + sectionData->sideInfoBits +
 	      sectionData->scalefacBits);
 }
 
diff --git a/media/libstagefright/codecs/aacenc/src/grp_data.c b/media/libstagefright/codecs/aacenc/src/grp_data.c
index 08d9a76..7861e1c 100644
--- a/media/libstagefright/codecs/aacenc/src/grp_data.c
+++ b/media/libstagefright/codecs/aacenc/src/grp_data.c
@@ -1,26 +1,26 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		grp_data.c

-

-	Content:	Short block grouping function

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		grp_data.c
+
+	Content:	Short block grouping function
+
 *******************************************************************************/
 
-#include "basic_op.h"

+#include "basic_op.h"
 #include "psy_const.h"
 #include "interface.h"
 #include "grp_data.h"
@@ -57,29 +57,29 @@
 
   /* for short: regroup and  */
   /* cumulate energies und thresholds group-wise . */
-  
+
   /* calculate sfbCnt */
-  highestSfb = 0;                                        
+  highestSfb = 0;
   for (wnd=0; wnd<TRANS_FAC; wnd++) {
     for (sfb=sfbCnt - 1; sfb>=highestSfb; sfb--) {
       for (line=(sfbOffset[sfb + 1] - 1); line>=sfbOffset[sfb]; line--) {
-        
-        if (mdctSpectrum[wnd*FRAME_LEN_SHORT+line] != 0) break; 
+
+        if (mdctSpectrum[wnd*FRAME_LEN_SHORT+line] != 0) break;
       }
-      
+
       if (line >= sfbOffset[sfb]) break;
     }
     highestSfb = max(highestSfb, sfb);
   }
-  
+
   if (highestSfb < 0) {
-    highestSfb = 0;                                      
+    highestSfb = 0;
   }
   *maxSfbPerGroup = highestSfb + 1;
 
   /* calculate sfbOffset */
-  i = 0;                                                 
-  offset = 0;                                            
+  i = 0;
+  offset = 0;
   for (grp = 0; grp < noOfGroups; grp++) {
     for (sfb = 0; sfb < sfbCnt; sfb++) {
       groupedSfbOffset[i] = offset + sfbOffset[sfb] * groupLen[grp];
@@ -87,15 +87,15 @@
     }
     offset += groupLen[grp] * FRAME_LEN_SHORT;
   }
-  groupedSfbOffset[i] = FRAME_LEN_LONG;                  
+  groupedSfbOffset[i] = FRAME_LEN_LONG;
   i += 1;
 
   /* calculate minSnr */
-  i = 0;                                                 
-  offset = 0;                                            
+  i = 0;
+  offset = 0;
   for (grp = 0; grp < noOfGroups; grp++) {
     for (sfb = 0; sfb < sfbCnt; sfb++) {
-      groupedSfbMinSnr[i] = sfbMinSnr[sfb];              
+      groupedSfbMinSnr[i] = sfbMinSnr[sfb];
       i += 1;
     }
     offset += groupLen[grp] * FRAME_LEN_SHORT;
@@ -103,74 +103,74 @@
 
 
   /* sum up sfbThresholds */
-  wnd = 0;                                                       
-  i = 0;                                                         
+  wnd = 0;
+  i = 0;
   for (grp = 0; grp < noOfGroups; grp++) {
     for (sfb = 0; sfb < sfbCnt; sfb++) {
-      Word32 thresh = sfbThreshold->sfbShort[wnd][sfb];          
+      Word32 thresh = sfbThreshold->sfbShort[wnd][sfb];
       for (j=1; j<groupLen[grp]; j++) {
         thresh = L_add(thresh, sfbThreshold->sfbShort[wnd+j][sfb]);
       }
-      sfbThreshold->sfbLong[i] = thresh;                         
+      sfbThreshold->sfbLong[i] = thresh;
       i += 1;
     }
     wnd += groupLen[grp];
   }
 
   /* sum up sfbEnergies left/right */
-  wnd = 0;                                                       
-  i = 0;                                                         
+  wnd = 0;
+  i = 0;
   for (grp = 0; grp < noOfGroups; grp++) {
     for (sfb = 0; sfb < sfbCnt; sfb++) {
-      Word32 energy = sfbEnergy->sfbShort[wnd][sfb];             
+      Word32 energy = sfbEnergy->sfbShort[wnd][sfb];
       for (j=1; j<groupLen[grp]; j++) {
         energy = L_add(energy, sfbEnergy->sfbShort[wnd+j][sfb]);
       }
-      sfbEnergy->sfbLong[i] = energy;                            
+      sfbEnergy->sfbLong[i] = energy;
       i += 1;
     }
     wnd += groupLen[grp];
   }
 
   /* sum up sfbEnergies mid/side */
-  wnd = 0;                                                       
-  i = 0;                                                         
+  wnd = 0;
+  i = 0;
   for (grp = 0; grp < noOfGroups; grp++) {
     for (sfb = 0; sfb < sfbCnt; sfb++) {
-      Word32 energy = sfbEnergyMS->sfbShort[wnd][sfb];           
+      Word32 energy = sfbEnergyMS->sfbShort[wnd][sfb];
       for (j=1; j<groupLen[grp]; j++) {
         energy = L_add(energy, sfbEnergyMS->sfbShort[wnd+j][sfb]);
       }
-      sfbEnergyMS->sfbLong[i] = energy;                          
+      sfbEnergyMS->sfbLong[i] = energy;
       i += 1;
     }
     wnd += groupLen[grp];
   }
 
   /* sum up sfbSpreadedEnergies */
-  wnd = 0;                                                       
-  i = 0;                                                         
+  wnd = 0;
+  i = 0;
   for (grp = 0; grp < noOfGroups; grp++) {
     for (sfb = 0; sfb < sfbCnt; sfb++) {
-      Word32 energy = sfbSpreadedEnergy->sfbShort[wnd][sfb];     
+      Word32 energy = sfbSpreadedEnergy->sfbShort[wnd][sfb];
       for (j=1; j<groupLen[grp]; j++) {
         energy = L_add(energy, sfbSpreadedEnergy->sfbShort[wnd+j][sfb]);
       }
-      sfbSpreadedEnergy->sfbLong[i] = energy;                    
+      sfbSpreadedEnergy->sfbLong[i] = energy;
       i += 1;
     }
     wnd += groupLen[grp];
   }
 
   /* re-group spectrum */
-  wnd = 0;                                                       
-  i = 0;                                                         
+  wnd = 0;
+  i = 0;
   for (grp = 0; grp < noOfGroups; grp++) {
     for (sfb = 0; sfb < sfbCnt; sfb++) {
       for (j = 0; j < groupLen[grp]; j++) {
         Word16 lineOffset = FRAME_LEN_SHORT * (wnd + j);
         for (line = lineOffset + sfbOffset[sfb]; line < lineOffset + sfbOffset[sfb+1]; line++) {
-          tmpSpectrum[i] = mdctSpectrum[line];                   
+          tmpSpectrum[i] = mdctSpectrum[line];
           i = i + 1;
         }
       }
@@ -179,10 +179,10 @@
   }
 
   for(i=0;i<FRAME_LEN_LONG;i+=4) {
-    mdctSpectrum[i] = tmpSpectrum[i];  

-	mdctSpectrum[i+1] = tmpSpectrum[i+1];  

-	mdctSpectrum[i+2] = tmpSpectrum[i+2];  

-	mdctSpectrum[i+3] = tmpSpectrum[i+3];  	
+    mdctSpectrum[i] = tmpSpectrum[i];
+	mdctSpectrum[i+1] = tmpSpectrum[i+1];
+	mdctSpectrum[i+2] = tmpSpectrum[i+2];
+	mdctSpectrum[i+3] = tmpSpectrum[i+3];
   }
 }
 
diff --git a/media/libstagefright/codecs/aacenc/src/interface.c b/media/libstagefright/codecs/aacenc/src/interface.c
index 304b1d4..f2472d8 100644
--- a/media/libstagefright/codecs/aacenc/src/interface.c
+++ b/media/libstagefright/codecs/aacenc/src/interface.c
@@ -1,27 +1,27 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		interface.c

-

-	Content:	Interface psychoaccoustic/quantizer functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		interface.c
+
+	Content:	Interface psychoaccoustic/quantizer functions
+
 *******************************************************************************/
 
-#include "basic_op.h"

-#include "oper_32b.h"

+#include "basic_op.h"
+#include "oper_32b.h"
 #include "psy_const.h"
 #include "interface.h"
 
@@ -49,64 +49,64 @@
                     PSY_OUT_CHANNEL         *psyOutCh)
 {
   Word32 j;
-  Word32 grp; 
-  Word32 mask;

+  Word32 grp;
+  Word32 mask;
   Word16 *tmpV;
 
   /*
   copy values to psyOut
   */
-  psyOutCh->maxSfbPerGroup    = maxSfbPerGroup;                             
-  psyOutCh->sfbCnt            = groupedSfbCnt;   
+  psyOutCh->maxSfbPerGroup    = maxSfbPerGroup;
+  psyOutCh->sfbCnt            = groupedSfbCnt;
   if(noOfGroups)
 	psyOutCh->sfbPerGroup     = groupedSfbCnt/ noOfGroups;
   else
 	psyOutCh->sfbPerGroup     = 0x7fff;
-  psyOutCh->windowSequence    = windowSequence;                             
-  psyOutCh->windowShape       = windowShape;                                
-  psyOutCh->mdctScale         = mdctScale;                                  
+  psyOutCh->windowSequence    = windowSequence;
+  psyOutCh->windowShape       = windowShape;
+  psyOutCh->mdctScale         = mdctScale;
   psyOutCh->mdctSpectrum      = groupedMdctSpectrum;
   psyOutCh->sfbEnergy         = groupedSfbEnergy->sfbLong;
   psyOutCh->sfbThreshold      = groupedSfbThreshold->sfbLong;
   psyOutCh->sfbSpreadedEnergy = groupedSfbSpreadedEnergy->sfbLong;
-  
-  tmpV = psyOutCh->sfbOffsets;

+
+  tmpV = psyOutCh->sfbOffsets;
   for(j=0; j<groupedSfbCnt + 1; j++) {
       *tmpV++ = groupedSfbOffset[j];
   }
-  

+
   tmpV = psyOutCh->sfbMinSnr;
   for(j=0;j<groupedSfbCnt; j++) {
 	  *tmpV++ =   groupedSfbMinSnr[j];
   }
-  
+
   /* generate grouping mask */
-  mask = 0;                                                                      
+  mask = 0;
   for (grp = 0; grp < noOfGroups; grp++) {
     mask = mask << 1;
     for (j=1; j<groupLen[grp]; j++) {
       mask = mask << 1;
-      mask |= 1;                                                                 
+      mask |= 1;
     }
   }
-  psyOutCh->groupingMask = mask; 
-  
+  psyOutCh->groupingMask = mask;
+
   if (windowSequence != SHORT_WINDOW) {
-    psyOutCh->sfbEnSumLR =  sfbEnergySumLR.sfbLong;                              
-    psyOutCh->sfbEnSumMS =  sfbEnergySumMS.sfbLong;                              
+    psyOutCh->sfbEnSumLR =  sfbEnergySumLR.sfbLong;
+    psyOutCh->sfbEnSumMS =  sfbEnergySumMS.sfbLong;
   }
   else {
     Word32 i;
     Word32 accuSumMS=0;
-    Word32 accuSumLR=0;        

-	Word32 *pSumMS = sfbEnergySumMS.sfbShort;

+    Word32 accuSumLR=0;
+	Word32 *pSumMS = sfbEnergySumMS.sfbShort;
 	Word32 *pSumLR = sfbEnergySumLR.sfbShort;
 
     for (i=TRANS_FAC; i; i--) {
       accuSumLR = L_add(accuSumLR, *pSumLR); pSumLR++;
       accuSumMS = L_add(accuSumMS, *pSumMS); pSumMS++;
     }
-    psyOutCh->sfbEnSumMS = accuSumMS;                                            
-    psyOutCh->sfbEnSumLR = accuSumLR;                                            
+    psyOutCh->sfbEnSumMS = accuSumMS;
+    psyOutCh->sfbEnSumLR = accuSumLR;
   }
 }
diff --git a/media/libstagefright/codecs/aacenc/src/line_pe.c b/media/libstagefright/codecs/aacenc/src/line_pe.c
index da57647..480dc28 100644
--- a/media/libstagefright/codecs/aacenc/src/line_pe.c
+++ b/media/libstagefright/codecs/aacenc/src/line_pe.c
@@ -1,26 +1,26 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		line_pe.c

-

-	Content:	Perceptual entropie module functions

-

-*******************************************************************************/

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		line_pe.c
 
-#include "basic_op.h"

+	Content:	Perceptual entropie module functions
+
+*******************************************************************************/
+
+#include "basic_op.h"
 #include "oper_32b.h"
 #include "typedef.h"
 #include "line_pe.h"
@@ -45,20 +45,20 @@
                   const Word16 peOffset)
 {
   Word32 sfbGrp, sfb;
-  Word32 ch;     
+  Word32 ch;
 
   for(ch=0; ch<nChannels; ch++) {
     PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
     PE_CHANNEL_DATA *peChanData=&peData->peChannelData[ch];
     for(sfbGrp=0;sfbGrp<psyOutChan->sfbCnt; sfbGrp+=psyOutChan->sfbPerGroup){
       for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-	    peChanData->sfbNLines4[sfbGrp+sfb] = sfbNRelevantLines[ch][sfbGrp+sfb];          
-        sfbNRelevantLines[ch][sfbGrp+sfb] = sfbNRelevantLines[ch][sfbGrp+sfb] >> 2;    
-	    peChanData->sfbLdEnergy[sfbGrp+sfb] = logSfbEnergy[ch][sfbGrp+sfb];              
+	    peChanData->sfbNLines4[sfbGrp+sfb] = sfbNRelevantLines[ch][sfbGrp+sfb];
+        sfbNRelevantLines[ch][sfbGrp+sfb] = sfbNRelevantLines[ch][sfbGrp+sfb] >> 2;
+	    peChanData->sfbLdEnergy[sfbGrp+sfb] = logSfbEnergy[ch][sfbGrp+sfb];
       }
     }
   }
-  peData->offset = peOffset;                                                             
+  peData->offset = peOffset;
 }
 
 
@@ -75,35 +75,35 @@
   Word32 ch;
   Word32 sfbGrp, sfb;
   Word32 nLines4;
-  Word32 ldThr, ldRatio;

+  Word32 ldThr, ldRatio;
   Word32 pe, constPart, nActiveLines;
 
-  peData->pe = peData->offset;                                           
-  peData->constPart = 0;                                                 
-  peData->nActiveLines = 0;                                              
+  peData->pe = peData->offset;
+  peData->constPart = 0;
+  peData->nActiveLines = 0;
   for(ch=0; ch<nChannels; ch++) {
     PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
     PE_CHANNEL_DATA *peChanData = &peData->peChannelData[ch];
     const Word32 *sfbEnergy = psyOutChan->sfbEnergy;
     const Word32 *sfbThreshold = psyOutChan->sfbThreshold;
 
-    pe = 0;                                                  
-    constPart = 0;                                           
-    nActiveLines = 0;                                        
+    pe = 0;
+    constPart = 0;
+    nActiveLines = 0;
 
     for(sfbGrp=0; sfbGrp<psyOutChan->sfbCnt; sfbGrp+=psyOutChan->sfbPerGroup) {
       for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-        Word32 nrg = sfbEnergy[sfbGrp+sfb];                             
-        Word32 thres = sfbThreshold[sfbGrp+sfb];                           
-        Word32 sfbLDEn = peChanData->sfbLdEnergy[sfbGrp+sfb];

+        Word32 nrg = sfbEnergy[sfbGrp+sfb];
+        Word32 thres = sfbThreshold[sfbGrp+sfb];
+        Word32 sfbLDEn = peChanData->sfbLdEnergy[sfbGrp+sfb];
 
         if (nrg > thres) {
           ldThr = iLog4(thres);
 
           ldRatio = sfbLDEn - ldThr;
 
-          nLines4 = peChanData->sfbNLines4[sfbGrp+sfb];                    
-           
+          nLines4 = peChanData->sfbNLines4[sfbGrp+sfb];
+
           /* sfbPe = nl*log2(en/thr)*/
 		  if (ldRatio >= C1_I) {
             peChanData->sfbPe[sfbGrp+sfb] = (nLines4*ldRatio + 8) >> 4;
@@ -111,35 +111,35 @@
           }
           else {
 		  /* sfbPe = nl*(c2 + c3*log2(en/thr))*/
-            peChanData->sfbPe[sfbGrp+sfb] = extract_l((L_mpy_wx(

-                    (C2_I + C3_I * ldRatio * 2) << 4, nLines4) + 4) >> 3);

-            peChanData->sfbConstPart[sfbGrp+sfb] = extract_l(( L_mpy_wx(

-                    (C2_I + C3_I * sfbLDEn * 2) << 4, nLines4) + 4) >> 3);

+            peChanData->sfbPe[sfbGrp+sfb] = extract_l((L_mpy_wx(
+                    (C2_I + C3_I * ldRatio * 2) << 4, nLines4) + 4) >> 3);
+            peChanData->sfbConstPart[sfbGrp+sfb] = extract_l(( L_mpy_wx(
+                    (C2_I + C3_I * sfbLDEn * 2) << 4, nLines4) + 4) >> 3);
             nLines4 = (nLines4 * C3_I + (1024<<1)) >> 10;
           }
           peChanData->sfbNActiveLines[sfbGrp+sfb] = nLines4 >> 2;
         }
         else {
-          peChanData->sfbPe[sfbGrp+sfb] = 0;                             
-          peChanData->sfbConstPart[sfbGrp+sfb] = 0;                      
-          peChanData->sfbNActiveLines[sfbGrp+sfb] = 0;                   
+          peChanData->sfbPe[sfbGrp+sfb] = 0;
+          peChanData->sfbConstPart[sfbGrp+sfb] = 0;
+          peChanData->sfbNActiveLines[sfbGrp+sfb] = 0;
         }
         pe = pe + peChanData->sfbPe[sfbGrp+sfb];
         constPart = constPart + peChanData->sfbConstPart[sfbGrp+sfb];
         nActiveLines = nActiveLines + peChanData->sfbNActiveLines[sfbGrp+sfb];
       }
     }
-	

-	peChanData->pe = saturate(pe);                                                  

-    peChanData->constPart = saturate(constPart);                                           

-    peChanData->nActiveLines = saturate(nActiveLines);                                        

 
-    
+	peChanData->pe = saturate(pe);
+    peChanData->constPart = saturate(constPart);
+    peChanData->nActiveLines = saturate(nActiveLines);
+
+
 	pe += peData->pe;
-	peData->pe = saturate(pe); 
+	peData->pe = saturate(pe);
     constPart += peData->constPart;
-	peData->constPart = saturate(constPart); 
+	peData->constPart = saturate(constPart);
     nActiveLines += peData->nActiveLines;
 	peData->nActiveLines = saturate(nActiveLines);
-  } 
+  }
 }
diff --git a/media/libstagefright/codecs/aacenc/src/memalign.c b/media/libstagefright/codecs/aacenc/src/memalign.c
index 7d203527..bb266dc 100644
--- a/media/libstagefright/codecs/aacenc/src/memalign.c
+++ b/media/libstagefright/codecs/aacenc/src/memalign.c
@@ -23,11 +23,16 @@
 
 
 #include	"memalign.h"
+#ifdef _MSC_VER
+#include	<stddef.h>
+#else
+#include	<stdint.h>
+#endif
 
 /*****************************************************************************
 *
 * function name: mem_malloc
-* description:  malloc the alignments memory 
+* description:  malloc the alignments memory
 * returns:      the point of the memory
 *
 **********************************************************************************/
@@ -66,8 +71,8 @@
 		pMemop->Set(CodecID, tmp, 0, size + alignment);
 
 		mem_ptr =
-			(unsigned char *) ((unsigned int) (tmp + alignment - 1) &
-					(~((unsigned int) (alignment - 1))));
+			(unsigned char *) ((intptr_t) (tmp + alignment - 1) &
+					(~((intptr_t) (alignment - 1))));
 
 		if (mem_ptr == tmp)
 			mem_ptr += alignment;
diff --git a/media/libstagefright/codecs/aacenc/src/ms_stereo.c b/media/libstagefright/codecs/aacenc/src/ms_stereo.c
index c83d07b..2e34f14 100644
--- a/media/libstagefright/codecs/aacenc/src/ms_stereo.c
+++ b/media/libstagefright/codecs/aacenc/src/ms_stereo.c
@@ -1,26 +1,26 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		ms_stereo.c

-

-	Content:	MS stereo processing function

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		ms_stereo.c
+
+	Content:	MS stereo processing function
+
 *******************************************************************************/
 
-#include "basic_op.h"

+#include "basic_op.h"
 #include "oper_32b.h"
 #include "psy_const.h"
 #include "ms_stereo.h"
@@ -30,7 +30,7 @@
 *
 * function name: MsStereoProcessing
 * description:  detect use ms stereo or not
-*				if ((min(thrLn, thrRn)*min(thrLn, thrRn))/(enMn*enSn)) 
+*				if ((min(thrLn, thrRn)*min(thrLn, thrRn))/(enMn*enSn))
 *				>= ((thrLn *thrRn)/(enLn*enRn)) then ms stereo
 *
 **********************************************************************************/
@@ -51,7 +51,7 @@
                         const Word16  maxSfbPerGroup,
                         const Word16 *sfbOffset) {
   Word32 temp;
-  Word32 sfb,sfboffs, j; 
+  Word32 sfb,sfboffs, j;
   Word32 msMaskTrueSomewhere = 0;
   Word32 msMaskFalseSomewhere = 0;
 
@@ -64,75 +64,75 @@
       Word32 thrL, thrR, nrgL, nrgR;
       Word32 idx, shift;
 
-      idx = sfb + sfboffs;                                                                       
+      idx = sfb + sfboffs;
 
-      thrL = sfbThresholdLeft[idx];                                                                 
-      thrR = sfbThresholdRight[idx];                                                                
-      nrgL = sfbEnergyLeft[idx];                                                                    
-      nrgR = sfbEnergyRight[idx];                                                                   
+      thrL = sfbThresholdLeft[idx];
+      thrR = sfbThresholdRight[idx];
+      nrgL = sfbEnergyLeft[idx];
+      nrgR = sfbEnergyRight[idx];
 
       minThreshold = min(thrL, thrR);
 
       nrgL = max(nrgL,thrL) + 1;
-      shift = norm_l(nrgL);

+      shift = norm_l(nrgL);
 	  nrgL = Div_32(thrL << shift, nrgL << shift);
       nrgR = max(nrgR,thrR) + 1;
-      shift = norm_l(nrgR);

+      shift = norm_l(nrgR);
 	  nrgR = Div_32(thrR << shift, nrgR << shift);
 
 	  pnlr = fixmul(nrgL, nrgR);
 
-      nrgL = sfbEnergyMid[idx];                                                                     
-      nrgR = sfbEnergySide[idx];                                                                    
+      nrgL = sfbEnergyMid[idx];
+      nrgR = sfbEnergySide[idx];
 
       nrgL = max(nrgL,minThreshold) + 1;
-      shift = norm_l(nrgL);

+      shift = norm_l(nrgL);
 	  nrgL = Div_32(minThreshold << shift, nrgL << shift);
 
       nrgR = max(nrgR,minThreshold) + 1;
-      shift = norm_l(nrgR);

+      shift = norm_l(nrgR);
 	  nrgR = Div_32(minThreshold << shift, nrgR << shift);
 
       pnms = fixmul(nrgL, nrgR);
 
       temp = (pnlr + 1) / ((pnms >> 8) + 1);
 
-      temp = pnms - pnlr;                                                                     
+      temp = pnms - pnlr;
       if( temp > 0 ){
 
-        msMask[idx] = 1;                                                                            
-        msMaskTrueSomewhere = 1;                                                                    
+        msMask[idx] = 1;
+        msMaskTrueSomewhere = 1;
 
         for (j=sfbOffset[idx]; j<sfbOffset[idx+1]; j++) {
           Word32 left, right;
           left  = (mdctSpectrumLeft[j] >>  1);
           right = (mdctSpectrumRight[j] >> 1);
-          mdctSpectrumLeft[j] =  left + right;                                               
-          mdctSpectrumRight[j] =  left - right;                                              
+          mdctSpectrumLeft[j] =  left + right;
+          mdctSpectrumRight[j] =  left - right;
         }
-        
-        sfbThresholdLeft[idx] = minThreshold;                                                       
-        sfbThresholdRight[idx] = minThreshold;                                                      
-        sfbEnergyLeft[idx] = sfbEnergyMid[idx];                                                     
-        sfbEnergyRight[idx] = sfbEnergySide[idx];                                                   
 
-        sfbSpreadedEnRight[idx] = min(sfbSpreadedEnLeft[idx],sfbSpreadedEnRight[idx]) >> 1;  
-        sfbSpreadedEnLeft[idx] = sfbSpreadedEnRight[idx];                                           
-        
+        sfbThresholdLeft[idx] = minThreshold;
+        sfbThresholdRight[idx] = minThreshold;
+        sfbEnergyLeft[idx] = sfbEnergyMid[idx];
+        sfbEnergyRight[idx] = sfbEnergySide[idx];
+
+        sfbSpreadedEnRight[idx] = min(sfbSpreadedEnLeft[idx],sfbSpreadedEnRight[idx]) >> 1;
+        sfbSpreadedEnLeft[idx] = sfbSpreadedEnRight[idx];
+
       }
       else {
-        msMask[idx]  = 0;                                                                           
-        msMaskFalseSomewhere = 1;                                                                   
+        msMask[idx]  = 0;
+        msMaskFalseSomewhere = 1;
       }
-    }                                                                                               
-    if ( msMaskTrueSomewhere ) {                                                                    
+    }
+    if ( msMaskTrueSomewhere ) {
       if(msMaskFalseSomewhere ) {
-        *msDigest = SI_MS_MASK_SOME;                                                                
+        *msDigest = SI_MS_MASK_SOME;
       } else {
-        *msDigest = SI_MS_MASK_ALL;                                                                 
+        *msDigest = SI_MS_MASK_ALL;
       }
     } else {
-      *msDigest = SI_MS_MASK_NONE;                                                                  
+      *msDigest = SI_MS_MASK_NONE;
     }
   }
 
diff --git a/media/libstagefright/codecs/aacenc/src/pre_echo_control.c b/media/libstagefright/codecs/aacenc/src/pre_echo_control.c
index f59216e..1406e11 100644
--- a/media/libstagefright/codecs/aacenc/src/pre_echo_control.c
+++ b/media/libstagefright/codecs/aacenc/src/pre_echo_control.c
@@ -1,27 +1,27 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		pre_echo_control.c

-

-	Content:	Pre echo control functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		pre_echo_control.c
+
+	Content:	Pre echo control functions
+
 *******************************************************************************/
 
-#include "basic_op.h"

-#include "oper_32b.h"

+#include "basic_op.h"
+#include "oper_32b.h"
 
 #include "oper_32b.h"
 #include "pre_echo_control.h"
@@ -29,7 +29,7 @@
 
 /*****************************************************************************
 *
-* function name:InitPreEchoControl 
+* function name:InitPreEchoControl
 * description: init pre echo control parameter
 *
 *****************************************************************************/
@@ -40,13 +40,13 @@
   Word16 pb;
 
   for(pb=0; pb<numPb; pb++) {
-    pbThresholdNm1[pb] = pbThresholdQuiet[pb];                                   
+    pbThresholdNm1[pb] = pbThresholdQuiet[pb];
   }
 }
 
 /*****************************************************************************
 *
-* function name:PreEchoControl 
+* function name:PreEchoControl
 * description: update shreshold to avoid pre echo
 *			   thr(n) = max(rpmin*thrq(n), min(thrq(n), rpelev*thrq1(n)))
 *
@@ -68,22 +68,22 @@
   (void)maxAllowedIncreaseFactor;
 
   scaling = ((mdctScale - mdctScalenm1) << 1);
-   
+
   if ( scaling > 0 ) {
     for(i = 0; i < numPb; i++) {
       tmpThreshold1 = pbThresholdNm1[i] >> (scaling-1);
       tmpThreshold2 = L_mpy_ls(pbThreshold[i], minRemainingThresholdFactor);
 
       /* copy thresholds to internal memory */
-      pbThresholdNm1[i] = pbThreshold[i];                                        
+      pbThresholdNm1[i] = pbThreshold[i];
 
-       
+
       if(pbThreshold[i] > tmpThreshold1) {
-        pbThreshold[i] = tmpThreshold1;                                          
+        pbThreshold[i] = tmpThreshold1;
       }
-       
+
       if(tmpThreshold2 > pbThreshold[i]) {
-        pbThreshold[i] = tmpThreshold2;                                          
+        pbThreshold[i] = tmpThreshold2;
       }
 
     }
@@ -96,15 +96,15 @@
       tmpThreshold2 = L_mpy_ls(pbThreshold[i], minRemainingThresholdFactor);
 
       /* copy thresholds to internal memory */
-      pbThresholdNm1[i] = pbThreshold[i];                                        
+      pbThresholdNm1[i] = pbThreshold[i];
 
-       
+
       if(((pbThreshold[i] >> scaling) > tmpThreshold1)) {
         pbThreshold[i] = tmpThreshold1 << scaling;
       }
-       
+
       if(tmpThreshold2 > pbThreshold[i]) {
-        pbThreshold[i] = tmpThreshold2;                                          
+        pbThreshold[i] = tmpThreshold2;
       }
 
     }
diff --git a/media/libstagefright/codecs/aacenc/src/psy_configuration.c b/media/libstagefright/codecs/aacenc/src/psy_configuration.c
index 586e00f..02d92ab 100644
--- a/media/libstagefright/codecs/aacenc/src/psy_configuration.c
+++ b/media/libstagefright/codecs/aacenc/src/psy_configuration.c
@@ -1,26 +1,26 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		psy_configuration.c

-

-	Content:	Psychoaccoustic configuration functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		psy_configuration.c
+
+	Content:	Psychoaccoustic configuration functions
+
 *******************************************************************************/
 
-#include "basic_op.h"

+#include "basic_op.h"
 #include "oper_32b.h"
 #include "psy_configuration.h"
 #include "adj_thr.h"
@@ -29,10 +29,10 @@
 
 
 #define BARC_SCALE	100 /* integer barc values are scaled with 100 */
-#define LOG2_1000	301 /* log2*1000 */

-#define PI2_1000	1571 /* pi/2*1000*/

-#define ATAN_COEF1	3560 /* 1000/0.280872f*/

-#define ATAN_COEF2	281 /* 1000*0.280872f*/

+#define LOG2_1000	301 /* log2*1000 */
+#define PI2_1000	1571 /* pi/2*1000*/
+#define ATAN_COEF1	3560 /* 1000/0.280872f*/
+#define ATAN_COEF2	281 /* 1000*0.280872f*/
 
 
 typedef struct{
@@ -57,30 +57,30 @@
 static const Word16 maskHighSprEnLong = 20;      /* in 1dB/bark */
 static const Word16 maskHighSprEnLongLowBr = 15; /* in 1dB/bark */
 static const Word16 maskLowSprEnShort = 20;      /* in 1dB/bark */
-static const Word16 maskHighSprEnShort = 15;     /* in 1dB/bark */

-static const Word16 c_minRemainingThresholdFactor = 0x0148;    /* 0.01 *(1 << 15)*/

-static const Word32 c_maxsnr = 0x66666666;		 /* upper limit is -1 dB */

-static const Word32 c_minsnr = 0x00624dd3;		 /* lower limit is -25 dB */

-

-static const Word32 c_maxClipEnergyLong = 0x77359400;  /* 2.0e9f*/

-static const Word32 c_maxClipEnergyShort = 0x01dcd650; /* 2.0e9f/(AACENC_TRANS_FAC*AACENC_TRANS_FAC)*/

-

-

-Word32 GetSRIndex(Word32 sampleRate)

-{

-    if (92017 <= sampleRate) return 0;

-    if (75132 <= sampleRate) return 1;

-    if (55426 <= sampleRate) return 2;

-    if (46009 <= sampleRate) return 3;

-    if (37566 <= sampleRate) return 4;

-    if (27713 <= sampleRate) return 5;

-    if (23004 <= sampleRate) return 6;

-    if (18783 <= sampleRate) return 7;

-    if (13856 <= sampleRate) return 8;

-    if (11502 <= sampleRate) return 9;

-    if (9391 <= sampleRate) return 10;

-

-    return 11;

+static const Word16 maskHighSprEnShort = 15;     /* in 1dB/bark */
+static const Word16 c_minRemainingThresholdFactor = 0x0148;    /* 0.01 *(1 << 15)*/
+static const Word32 c_maxsnr = 0x66666666;		 /* upper limit is -1 dB */
+static const Word32 c_minsnr = 0x00624dd3;		 /* lower limit is -25 dB */
+
+static const Word32 c_maxClipEnergyLong = 0x77359400;  /* 2.0e9f*/
+static const Word32 c_maxClipEnergyShort = 0x01dcd650; /* 2.0e9f/(AACENC_TRANS_FAC*AACENC_TRANS_FAC)*/
+
+
+Word32 GetSRIndex(Word32 sampleRate)
+{
+    if (92017 <= sampleRate) return 0;
+    if (75132 <= sampleRate) return 1;
+    if (55426 <= sampleRate) return 2;
+    if (46009 <= sampleRate) return 3;
+    if (37566 <= sampleRate) return 4;
+    if (27713 <= sampleRate) return 5;
+    if (23004 <= sampleRate) return 6;
+    if (18783 <= sampleRate) return 7;
+    if (13856 <= sampleRate) return 8;
+    if (11502 <= sampleRate) return 9;
+    if (9391 <= sampleRate) return 10;
+
+    return 11;
 }
 
 
@@ -88,17 +88,17 @@
 *
 * function name: atan_1000
 * description:  calculates 1000*atan(x/1000)
-*               based on atan approx for x > 0				
-*				atan(x) = x/((float)1.0f+(float)0.280872f*x*x)  if x < 1

-*						= pi/2 - x/((float)0.280872f +x*x)	    if x >= 1

+*               based on atan approx for x > 0
+*				atan(x) = x/((float)1.0f+(float)0.280872f*x*x)  if x < 1
+*						= pi/2 - x/((float)0.280872f +x*x)	    if x >= 1
 * return:       1000*atan(x/1000)
 *
 **********************************************************************************/
-static Word16 atan_1000(Word32 val) 
+static Word16 atan_1000(Word32 val)
 {
   Word32 y;
 
-   
+
   if(L_sub(val, 1000) < 0) {
     y = extract_l(((1000 * val) / (1000 + ((val * val) / ATAN_COEF1))));
   }
@@ -126,9 +126,9 @@
   /* center frequency of fft line */
   center_freq = (fftLine * samplingFreq) / (noOfLines << 1);
   temp =  atan_1000((center_freq << 2) / (3*10));
-  bvalFFTLine = 
+  bvalFFTLine =
     (26600 * atan_1000((center_freq*76) / 100) + 7*temp*temp) / (2*1000*1000 / BARC_SCALE);
-  
+
   return saturate(bvalFFTLine);
 }
 
@@ -148,17 +148,17 @@
   for(i=0; i<numPb; i++) {
     Word16 bv1, bv2;
 
-     
+
     if (i>0)
       bv1 = (pbBarcVal[i] + pbBarcVal[i-1]) >> 1;
     else
       bv1 = pbBarcVal[i] >> 1;
 
-     
+
     if (i < (numPb - 1))
       bv2 = (pbBarcVal[i] + pbBarcVal[i+1]) >> 1;
     else {
-      bv2 = pbBarcVal[i];                                        
+      bv2 = pbBarcVal[i];
     }
 
     bv1 = min((bv1 / BARC_SCALE), max_bark);
@@ -166,9 +166,9 @@
 
     barcThrQuiet = min(BARC_THR_QUIET[bv1], BARC_THR_QUIET[bv2]);
 
-    
+
     /*
-      we calculate 
+      we calculate
       pow(10.0f,(float)(barcThrQuiet - ABS_LEV)*0.1)*(float)ABS_LOW*(pbOffset[i+1] - pbOffset[i]);
     */
 
@@ -196,47 +196,47 @@
   Word16 i;
   Word16 maskLowSprEn, maskHighSprEn;
 
-   
+
   if (sub(blockType, SHORT_WINDOW) != 0) {
-    maskLowSprEn = maskLowSprEnLong;                                     
-       
+    maskLowSprEn = maskLowSprEnLong;
+
     if (bitrate > 22000)
       maskHighSprEn = maskHighSprEnLong;
     else
       maskHighSprEn = maskHighSprEnLongLowBr;
   }
   else {
-    maskLowSprEn = maskLowSprEnShort;            
-    maskHighSprEn = maskHighSprEnShort;          
+    maskLowSprEn = maskLowSprEnShort;
+    maskHighSprEn = maskHighSprEnShort;
   }
 
   for(i=0; i<numPb; i++) {
-     
+
     if (i > 0) {
       Word32 dbVal;
       Word16 dbark = pbBarcValue[i] - pbBarcValue[i-1];
 
       /*
-        we calulate pow(10.0f, -0.1*dbVal/BARC_SCALE) 
+        we calulate pow(10.0f, -0.1*dbVal/BARC_SCALE)
       */
       dbVal = (maskHigh * dbark);
       pbMaskHiFactor[i] = round16(pow2_xy(L_negate(dbVal), (Word32)LOG2_1000));             /* 0.301 log10(2) */
-       
+
       dbVal = (maskLow * dbark);
-      pbMaskLoFactor[i-1] = round16(pow2_xy(L_negate(dbVal),(Word32)LOG2_1000)); 
-       
-      
+      pbMaskLoFactor[i-1] = round16(pow2_xy(L_negate(dbVal),(Word32)LOG2_1000));
+
+
       dbVal = (maskHighSprEn * dbark);
-      pbMaskHiFactorSprEn[i] =  round16(pow2_xy(L_negate(dbVal),(Word32)LOG2_1000)); 
+      pbMaskHiFactorSprEn[i] =  round16(pow2_xy(L_negate(dbVal),(Word32)LOG2_1000));
       dbVal = (maskLowSprEn * dbark);
       pbMaskLoFactorSprEn[i-1] = round16(pow2_xy(L_negate(dbVal),(Word32)LOG2_1000));
     }
     else {
-      pbMaskHiFactor[i] = 0;                     
-      pbMaskLoFactor[numPb-1] = 0;               
+      pbMaskHiFactor[i] = 0;
+      pbMaskLoFactor[numPb-1] = 0;
 
-      pbMaskHiFactorSprEn[i] = 0;                
-      pbMaskLoFactorSprEn[numPb-1] = 0;          
+      pbMaskHiFactorSprEn[i] = 0;
+      pbMaskLoFactorSprEn[numPb-1] = 0;
     }
   }
 
@@ -258,12 +258,12 @@
   Word16 i;
   Word16 pbBval0, pbBval1;
 
-  pbBval0 = 0;                                       
+  pbBval0 = 0;
 
   for(i=0; i<numPb; i++){
     pbBval1 = BarcLineValue(numLines, pbOffset[i+1], samplingFrequency);
     pbBval[i] = (pbBval0 + pbBval1) >> 1;
-    pbBval0 = pbBval1;                              
+    pbBval0 = pbBval1;
   }
 }
 
@@ -272,7 +272,7 @@
 *
 * function name: initMinSnr
 * description:  calculate min snr parameter
-*				minSnr(n) = 1/(2^sfbPemin(n)/w(n) - 1.5)

+*				minSnr(n) = 1/(2^sfbPemin(n)/w(n) - 1.5)
 *
 *****************************************************************************/
 static void initMinSnr(const Word32  bitrate,
@@ -295,38 +295,38 @@
 
   pePerWindow = bits2pe(extract_l((bitrate * numLines) / samplerate));
 
-  pbVal0 = 0;                                                    
+  pbVal0 = 0;
 
   for (sfb=0; sfb<sfbActive; sfb++) {
 
     pbVal1 = (pbBarcVal[sfb] << 1) - pbVal0;
     barcWidth = pbVal1 - pbVal0;
-    pbVal0 = pbVal1;                                             
+    pbVal0 = pbVal1;
 
-    /* allow at least 2.4% of pe for each active barc */

+    /* allow at least 2.4% of pe for each active barc */
 	pePart = ((pePerWindow * 24) * (max_bark * barcWidth)) /
         (pbBarcVal[sfbActive-1] * (sfbOffset[sfb+1] - sfbOffset[sfb]));
-   
-      
-    pePart = min(pePart, 8400); 
+
+
+    pePart = min(pePart, 8400);
     pePart = max(pePart, 1400);
 
-    /* minSnr(n) = 1/(2^sfbPemin(n)/w(n) - 1.5)*/

+    /* minSnr(n) = 1/(2^sfbPemin(n)/w(n) - 1.5)*/
 	/* we add an offset of 2^16 to the pow functions */
-	/* 0xc000 = 1.5*(1 << 15)*/

-      
+	/* 0xc000 = 1.5*(1 << 15)*/
+
     snr = pow2_xy((pePart - 16*1000),1000) - 0x0000c000;
-      
-    if(snr > 0x00008000)

-	{

-		shift = norm_l(snr);

-		snr = Div_32(0x00008000 << shift, snr << shift);  
+
+    if(snr > 0x00008000)
+	{
+		shift = norm_l(snr);
+		snr = Div_32(0x00008000 << shift, snr << shift);
 	}
 	else
 	{
 		snr = 0x7fffffff;
 	}
-      
+
     /* upper limit is -1 dB */
     snr = min(snr, c_maxsnr);
     /* lower limit is -25 dB */
@@ -347,16 +347,16 @@
                                 Word16 bandwidth,
                                 PSY_CONFIGURATION_LONG *psyConf)
 {
-  Word32 samplerateindex;

-  Word16 sfbBarcVal[MAX_SFB_LONG];

+  Word32 samplerateindex;
+  Word16 sfbBarcVal[MAX_SFB_LONG];
   Word16 sfb;
 
   /*
     init sfb table
-  */

-  samplerateindex = GetSRIndex(samplerate);  

-  psyConf->sfbCnt = sfBandTotalLong[samplerateindex];

-  psyConf->sfbOffset = sfBandTabLong + sfBandTabLongOffset[samplerateindex];

+  */
+  samplerateindex = GetSRIndex(samplerate);
+  psyConf->sfbCnt = sfBandTotalLong[samplerateindex];
+  psyConf->sfbOffset = sfBandTabLong + sfBandTabLongOffset[samplerateindex];
   psyConf->sampRateIdx = samplerateindex;
 
   /*
@@ -391,19 +391,19 @@
   /*
     init ratio
   */
-  psyConf->ratio = c_ratio;      
+  psyConf->ratio = c_ratio;
 
-  psyConf->maxAllowedIncreaseFactor = 2;              
-  psyConf->minRemainingThresholdFactor = c_minRemainingThresholdFactor;    /* 0.01 *(1 << 15)*/  
+  psyConf->maxAllowedIncreaseFactor = 2;
+  psyConf->minRemainingThresholdFactor = c_minRemainingThresholdFactor;    /* 0.01 *(1 << 15)*/
 
-  psyConf->clipEnergy = c_maxClipEnergyLong;                   
+  psyConf->clipEnergy = c_maxClipEnergyLong;
   psyConf->lowpassLine = extract_l((bandwidth<<1) * FRAME_LEN_LONG / samplerate);
 
   for (sfb = 0; sfb < psyConf->sfbCnt; sfb++) {
     if (sub(psyConf->sfbOffset[sfb], psyConf->lowpassLine) >= 0)
       break;
   }
-  psyConf->sfbActive = sfb;                 
+  psyConf->sfbActive = sfb;
 
   /*
     calculate minSnr
@@ -429,7 +429,7 @@
 Word16 InitPsyConfigurationShort(Word32 bitrate,
                                  Word32 samplerate,
                                  Word16 bandwidth,
-                                 PSY_CONFIGURATION_SHORT *psyConf) 

+                                 PSY_CONFIGURATION_SHORT *psyConf)
 {
   Word32 samplerateindex;
   Word16 sfbBarcVal[MAX_SFB_SHORT];
@@ -437,8 +437,8 @@
   /*
     init sfb table
   */
-  samplerateindex = GetSRIndex(samplerate);  

-  psyConf->sfbCnt = sfBandTotalShort[samplerateindex];

+  samplerateindex = GetSRIndex(samplerate);
+  psyConf->sfbCnt = sfBandTotalShort[samplerateindex];
   psyConf->sfbOffset = sfBandTabShort + sfBandTabShortOffset[samplerateindex];
   psyConf->sampRateIdx = samplerateindex;
   /*
@@ -473,21 +473,21 @@
   /*
     init ratio
   */
-  psyConf->ratio = c_ratio;                                                      
+  psyConf->ratio = c_ratio;
 
-  psyConf->maxAllowedIncreaseFactor = 2;                                         
-  psyConf->minRemainingThresholdFactor = c_minRemainingThresholdFactor;                            	 
+  psyConf->maxAllowedIncreaseFactor = 2;
+  psyConf->minRemainingThresholdFactor = c_minRemainingThresholdFactor;
 
-  psyConf->clipEnergy = c_maxClipEnergyShort;                                    
+  psyConf->clipEnergy = c_maxClipEnergyShort;
 
   psyConf->lowpassLine = extract_l(((bandwidth << 1) * FRAME_LEN_SHORT) / samplerate);
- 
+
   for (sfb = 0; sfb < psyConf->sfbCnt; sfb++) {
-     
+
     if (psyConf->sfbOffset[sfb] >= psyConf->lowpassLine)
       break;
   }
-  psyConf->sfbActive = sfb;                                                      
+  psyConf->sfbActive = sfb;
 
   /*
     calculate minSnr
diff --git a/media/libstagefright/codecs/aacenc/src/psy_main.c b/media/libstagefright/codecs/aacenc/src/psy_main.c
index 8746a72..085acb8 100644
--- a/media/libstagefright/codecs/aacenc/src/psy_main.c
+++ b/media/libstagefright/codecs/aacenc/src/psy_main.c
@@ -1,27 +1,27 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		psy_main.c

-

-	Content:	Psychoacoustic major functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		psy_main.c
+
+	Content:	Psychoacoustic major functions
+
 *******************************************************************************/
 
-#include "typedef.h"

-#include "basic_op.h"

+#include "typedef.h"
+#include "basic_op.h"
 #include "oper_32b.h"
 #include "psy_const.h"
 #include "block_switch.h"
@@ -77,29 +77,29 @@
 *****************************************************************************/
 Word16 PsyNew(PSY_KERNEL *hPsy, Word32 nChan, VO_MEM_OPERATOR *pMemOP)
 {
-  Word16 i;

-  Word32 *mdctSpectrum;

-  Word32 *scratchTNS;

-  Word16 *mdctDelayBuffer;

-  

-  mdctSpectrum = (Word32 *)mem_malloc(pMemOP, nChan * FRAME_LEN_LONG * sizeof(Word32), 32, VO_INDEX_ENC_AAC);

-  if(NULL == mdctSpectrum)

-	  return 1;

-

-  scratchTNS = (Word32 *)mem_malloc(pMemOP, nChan * FRAME_LEN_LONG * sizeof(Word32), 32, VO_INDEX_ENC_AAC);

-  if(NULL == scratchTNS)

-  {

-	  return 1;

-  }

-

-  mdctDelayBuffer = (Word16 *)mem_malloc(pMemOP, nChan * BLOCK_SWITCHING_OFFSET * sizeof(Word16), 32, VO_INDEX_ENC_AAC);

-  if(NULL == mdctDelayBuffer)

-  {

+  Word16 i;
+  Word32 *mdctSpectrum;
+  Word32 *scratchTNS;
+  Word16 *mdctDelayBuffer;
+
+  mdctSpectrum = (Word32 *)mem_malloc(pMemOP, nChan * FRAME_LEN_LONG * sizeof(Word32), 32, VO_INDEX_ENC_AAC);
+  if(NULL == mdctSpectrum)
 	  return 1;
-  }

-

+
+  scratchTNS = (Word32 *)mem_malloc(pMemOP, nChan * FRAME_LEN_LONG * sizeof(Word32), 32, VO_INDEX_ENC_AAC);
+  if(NULL == scratchTNS)
+  {
+	  return 1;
+  }
+
+  mdctDelayBuffer = (Word16 *)mem_malloc(pMemOP, nChan * BLOCK_SWITCHING_OFFSET * sizeof(Word16), 32, VO_INDEX_ENC_AAC);
+  if(NULL == mdctDelayBuffer)
+  {
+	  return 1;
+  }
+
   for (i=0; i<nChan; i++){
-    hPsy->psyData[i].mdctDelayBuffer = mdctDelayBuffer + i*BLOCK_SWITCHING_OFFSET;      
+    hPsy->psyData[i].mdctDelayBuffer = mdctDelayBuffer + i*BLOCK_SWITCHING_OFFSET;
     hPsy->psyData[i].mdctSpectrum = mdctSpectrum + i*FRAME_LEN_LONG;
   }
 
@@ -118,27 +118,27 @@
 *****************************************************************************/
 Word16 PsyDelete(PSY_KERNEL  *hPsy, VO_MEM_OPERATOR *pMemOP)
 {
-  Word32 nch;

-

-  if(hPsy)

-  {

-	if(hPsy->psyData[0].mdctDelayBuffer)

-		mem_free(pMemOP, hPsy->psyData[0].mdctDelayBuffer, VO_INDEX_ENC_AAC);

-      

-    if(hPsy->psyData[0].mdctSpectrum)

-		mem_free(pMemOP, hPsy->psyData[0].mdctSpectrum, VO_INDEX_ENC_AAC);

-

-    for (nch=0; nch<MAX_CHANNELS; nch++){

-	  hPsy->psyData[nch].mdctDelayBuffer = NULL;      

-	  hPsy->psyData[nch].mdctSpectrum = NULL;

-	}

-

-	if(hPsy->pScratchTns)

-	{

-		mem_free(pMemOP, hPsy->pScratchTns, VO_INDEX_ENC_AAC);

-		hPsy->pScratchTns = NULL;

-	}

-  }

+  Word32 nch;
+
+  if(hPsy)
+  {
+	if(hPsy->psyData[0].mdctDelayBuffer)
+		mem_free(pMemOP, hPsy->psyData[0].mdctDelayBuffer, VO_INDEX_ENC_AAC);
+
+    if(hPsy->psyData[0].mdctSpectrum)
+		mem_free(pMemOP, hPsy->psyData[0].mdctSpectrum, VO_INDEX_ENC_AAC);
+
+    for (nch=0; nch<MAX_CHANNELS; nch++){
+	  hPsy->psyData[nch].mdctDelayBuffer = NULL;
+	  hPsy->psyData[nch].mdctSpectrum = NULL;
+	}
+
+	if(hPsy->pScratchTns)
+	{
+		mem_free(pMemOP, hPsy->pScratchTns, VO_INDEX_ENC_AAC);
+		hPsy->pScratchTns = NULL;
+	}
+  }
 
   return 0;
 }
@@ -196,10 +196,10 @@
   err = InitPsyConfigurationLong(channelBitRate,
                                  sampleRate,
                                  bandwidth,
-                                 &(hPsy->psyConfLong));

-

+                                 &(hPsy->psyConfLong));
+
   if (!err) {
-      hPsy->sampleRateIdx = hPsy->psyConfLong.sampRateIdx;

+      hPsy->sampleRateIdx = hPsy->psyConfLong.sampRateIdx;
 	  err = InitTnsConfigurationLong(bitRate, sampleRate, channels,
                                    &hPsy->psyConfLong.tnsConf, &hPsy->psyConfLong, tnsMask&2);
   }
@@ -216,14 +216,14 @@
 
   if (!err)
     for(ch=0;ch < channels;ch++){
-  
+
       InitBlockSwitching(&hPsy->psyData[ch].blockSwitchingControl,
                          bitRate, channels);
 
       InitPreEchoControl(hPsy->psyData[ch].sfbThresholdnm1,
                          hPsy->psyConfLong.sfbCnt,
                          hPsy->psyConfLong.sfbThresholdQuiet);
-      hPsy->psyData[ch].mdctScalenm1 = 0;                                
+      hPsy->psyData[ch].mdctScalenm1 = 0;
     }
 
 	return(err);
@@ -241,7 +241,7 @@
 
 Word16 psyMain(Word16                   nChannels,
                ELEMENT_INFO            *elemInfo,
-               Word16                  *timeSignal, 
+               Word16                  *timeSignal,
                PSY_DATA                 psyData[MAX_CHANNELS],
                TNS_DATA                 tnsData[MAX_CHANNELS],
                PSY_CONFIGURATION_LONG  *hPsyConfLong,
@@ -260,10 +260,10 @@
   Word16 channels;
   Word16 maxScale;
 
-  channels = elemInfo->nChannelsInEl;                            
-  maxScale = 0;                                                  
+  channels = elemInfo->nChannelsInEl;
+  maxScale = 0;
 
-  /* block switching */

+  /* block switching */
   for(ch = 0; ch < channels; ch++) {
     BlockSwitching(&psyData[ch].blockSwitchingControl,
                    timeSignal+elemInfo->ChannelIndex[ch],
@@ -291,7 +291,7 @@
   /* common scaling for all channels */
   for (ch=0; ch<channels; ch++) {
     Word16 scaleDiff = maxScale - mdctScalingArray[ch];
-     
+
     if (scaleDiff > 0) {
       Word32 *Spectrum = psyData[ch].mdctSpectrum;
 	  for(line=0; line<FRAME_LEN_LONG; line++) {
@@ -299,11 +299,11 @@
 		Spectrum++;
       }
     }
-    psyData[ch].mdctScale = maxScale;                                    
+    psyData[ch].mdctScale = maxScale;
   }
 
   for (ch=0; ch<channels; ch++) {
-     
+
     if(psyData[ch].blockSwitchingControl.windowSequence != SHORT_WINDOW) {
       /* update long block parameter */
 	  advancePsychLong(&psyData[ch],
@@ -317,7 +317,7 @@
       /* determine maxSfb */
       for (sfb=hPsyConfLong->sfbCnt-1; sfb>=0; sfb--) {
         for (line=hPsyConfLong->sfbOffset[sfb+1] - 1; line>=hPsyConfLong->sfbOffset[sfb]; line--) {
-           
+
           if (psyData[ch].mdctSpectrum[line] != 0) break;
         }
         if (line >= hPsyConfLong->sfbOffset[sfb]) break;
@@ -326,7 +326,7 @@
 
       /* Calc bandwise energies for mid and side channel
          Do it only if 2 channels exist */
-       
+
       if (ch == 1)
         advancePsychLongMS(psyData, hPsyConfLong);
     }
@@ -341,7 +341,7 @@
 
       /* Calc bandwise energies for mid and side channel
          Do it only if 2 channels exist */
-       
+
       if (ch == 1)
         advancePsychShortMS (psyData, hPsyConfShort);
     }
@@ -349,7 +349,7 @@
 
   /* group short data */
   for(ch=0; ch<channels; ch++) {
-     
+
     if (psyData[ch].blockSwitchingControl.windowSequence == SHORT_WINDOW) {
       groupShortData(psyData[ch].mdctSpectrum,
                      pScratchTns,
@@ -374,10 +374,10 @@
     stereo Processing
   */
   if (channels == 2) {
-    psyOutElement->toolsInfo.msDigest = MS_NONE;                 
+    psyOutElement->toolsInfo.msDigest = MS_NONE;
     maxSfbPerGroup[0] = maxSfbPerGroup[1] = max(maxSfbPerGroup[0], maxSfbPerGroup[1]);
 
-     
+
     if (psyData[0].blockSwitchingControl.windowSequence != SHORT_WINDOW)
       MsStereoProcessing(psyData[0].sfbEnergy.sfbLong,
                          psyData[1].sfbEnergy.sfbLong,
@@ -420,7 +420,7 @@
     build output
   */
   for(ch=0;ch<channels;ch++) {
-     
+
     if (psyData[ch].blockSwitchingControl.windowSequence != SHORT_WINDOW)
       BuildInterface(psyData[ch].mdctSpectrum,
                      psyData[ch].mdctScale,
@@ -477,13 +477,13 @@
 {
   Word32 i;
   Word32 normEnergyShift = (psyData->mdctScale + 1) << 1; /* in reference code, mdct spectrum must be multipied with 2, so +1 */
-  Word32 clipEnergy = hPsyConfLong->clipEnergy >> normEnergyShift;

+  Word32 clipEnergy = hPsyConfLong->clipEnergy >> normEnergyShift;
   Word32 *data0, *data1, tdata;
 
   /* low pass */
-  data0 = psyData->mdctSpectrum + hPsyConfLong->lowpassLine;

+  data0 = psyData->mdctSpectrum + hPsyConfLong->lowpassLine;
   for(i=hPsyConfLong->lowpassLine; i<FRAME_LEN_LONG; i++) {
-    *data0++ = 0;                                
+    *data0++ = 0;
   }
 
   /* Calc sfb-bandwise mdct-energies for left and right channel */
@@ -505,7 +505,7 @@
             psyData->blockSwitchingControl.windowSequence,
             psyData->sfbEnergy.sfbLong);
 
-  /*  TnsSync */   
+  /*  TnsSync */
   if (ch == 1) {
     TnsSync(tnsData,
             tnsData2,
@@ -514,7 +514,7 @@
             psyData->blockSwitchingControl.windowSequence);
   }
 
-  /*  Tns Encoder */ 
+  /*  Tns Encoder */
   TnsEncode(&psyOutChannel->tnsInfo,
             tnsData,
             hPsyConfLong->sfbCnt,
@@ -525,27 +525,27 @@
             psyData->blockSwitchingControl.windowSequence);
 
   /* first part of threshold calculation */
-  data0 = psyData->sfbEnergy.sfbLong;

-  data1 = psyData->sfbThreshold.sfbLong;

+  data0 = psyData->sfbEnergy.sfbLong;
+  data1 = psyData->sfbThreshold.sfbLong;
   for (i=hPsyConfLong->sfbCnt; i; i--) {
     tdata = L_mpy_ls(*data0++, hPsyConfLong->ratio);
-    *data1++ = min(tdata, clipEnergy);

+    *data1++ = min(tdata, clipEnergy);
   }
 
-  /* Calc sfb-bandwise mdct-energies for left and right channel again */   
+  /* Calc sfb-bandwise mdct-energies for left and right channel again */
   if (tnsData->dataRaw.tnsLong.subBlockInfo.tnsActive!=0) {
-    Word16 tnsStartBand = hPsyConfLong->tnsConf.tnsStartBand;                            
+    Word16 tnsStartBand = hPsyConfLong->tnsConf.tnsStartBand;
     CalcBandEnergy( psyData->mdctSpectrum,
                     hPsyConfLong->sfbOffset+tnsStartBand,
                     hPsyConfLong->sfbActive - tnsStartBand,
                     psyData->sfbEnergy.sfbLong+tnsStartBand,
                     &psyData->sfbEnergySum.sfbLong);
-    

-	data0 = psyData->sfbEnergy.sfbLong;

-	tdata = psyData->sfbEnergySum.sfbLong;

+
+	data0 = psyData->sfbEnergy.sfbLong;
+	tdata = psyData->sfbEnergySum.sfbLong;
 	for (i=0; i<tnsStartBand; i++)
-      tdata += *data0++;

-

+      tdata += *data0++;
+
 	psyData->sfbEnergySum.sfbLong = tdata;
   }
 
@@ -557,21 +557,21 @@
                psyData->sfbThreshold.sfbLong);
 
   /* threshold in quiet */
-  data0 = psyData->sfbThreshold.sfbLong;

-  data1 = hPsyConfLong->sfbThresholdQuiet;

+  data0 = psyData->sfbThreshold.sfbLong;
+  data1 = hPsyConfLong->sfbThresholdQuiet;
   for (i=hPsyConfLong->sfbCnt; i; i--)
-  {

-	  *data0 = max(*data0, (*data1 >> normEnergyShift));

-	  data0++; data1++;

+  {
+	  *data0 = max(*data0, (*data1 >> normEnergyShift));
+	  data0++; data1++;
   }
 
-  /* preecho control */   
+  /* preecho control */
   if (psyData->blockSwitchingControl.windowSequence == STOP_WINDOW) {
-    data0 = psyData->sfbThresholdnm1;

-	for (i=hPsyConfLong->sfbCnt; i; i--) {

-      *data0++ = MAX_32;                              

-    }

-    psyData->mdctScalenm1 = 0;                                           
+    data0 = psyData->sfbThresholdnm1;
+	for (i=hPsyConfLong->sfbCnt; i; i--) {
+      *data0++ = MAX_32;
+    }
+    psyData->mdctScalenm1 = 0;
   }
 
   PreEchoControl( psyData->sfbThresholdnm1,
@@ -581,15 +581,15 @@
                   psyData->sfbThreshold.sfbLong,
                   psyData->mdctScale,
                   psyData->mdctScalenm1);
-  psyData->mdctScalenm1 = psyData->mdctScale;                            
+  psyData->mdctScalenm1 = psyData->mdctScale;
 
-   
+
   if (psyData->blockSwitchingControl.windowSequence== START_WINDOW) {
-    data0 = psyData->sfbThresholdnm1;

+    data0 = psyData->sfbThresholdnm1;
 	for (i=hPsyConfLong->sfbCnt; i; i--) {
-      *data0++ = MAX_32;                              
+      *data0++ = MAX_32;
     }
-    psyData->mdctScalenm1 = 0;                                           
+    psyData->mdctScalenm1 = 0;
   }
 
   /* apply tns mult table on cb thresholds */
@@ -600,16 +600,16 @@
 
 
   /* spreaded energy */
-  data0 = psyData->sfbSpreadedEnergy.sfbLong;

-  data1 = psyData->sfbEnergy.sfbLong;

+  data0 = psyData->sfbSpreadedEnergy.sfbLong;
+  data1 = psyData->sfbEnergy.sfbLong;
   for (i=hPsyConfLong->sfbCnt; i; i--) {
-    //psyData->sfbSpreadedEnergy.sfbLong[i] = psyData->sfbEnergy.sfbLong[i];       

+    //psyData->sfbSpreadedEnergy.sfbLong[i] = psyData->sfbEnergy.sfbLong[i];
 	  *data0++ = *data1++;
   }
 
   /* spreading energy */
   SpreadingMax(hPsyConfLong->sfbCnt,
-               hPsyConfLong->sfbMaskLowFactorSprEn, 
+               hPsyConfLong->sfbMaskLowFactorSprEn,
                hPsyConfLong->sfbMaskHighFactorSprEn,
                psyData->sfbSpreadedEnergy.sfbLong);
 
@@ -619,7 +619,7 @@
 /*****************************************************************************
 *
 * function name: advancePsychLongMS
-* description:   update mdct-energies for left add or minus right channel 
+* description:   update mdct-energies for left add or minus right channel
 *				for long block
 *
 *****************************************************************************/
@@ -657,16 +657,16 @@
   Word32 w;
   Word32 normEnergyShift = (psyData->mdctScale + 1) << 1; /* in reference code, mdct spectrum must be multipied with 2, so +1 */
   Word32 clipEnergy = hPsyConfShort->clipEnergy >> normEnergyShift;
-  Word32 wOffset = 0;     

+  Word32 wOffset = 0;
   Word32 *data0, *data1;
 
   for(w = 0; w < TRANS_FAC; w++) {
     Word32 i, tdata;
 
     /* low pass */
-    data0 = psyData->mdctSpectrum + wOffset + hPsyConfShort->lowpassLine;

+    data0 = psyData->mdctSpectrum + wOffset + hPsyConfShort->lowpassLine;
 	for(i=hPsyConfShort->lowpassLine; i<FRAME_LEN_SHORT; i++){
-      *data0++ = 0;                                      
+      *data0++ = 0;
     }
 
     /* Calc sfb-bandwise mdct-energies for left and right channel */
@@ -706,27 +706,27 @@
               psyData->blockSwitchingControl.windowSequence);
 
     /* first part of threshold calculation */
-    data0 = psyData->sfbThreshold.sfbShort[w];

-	data1 = psyData->sfbEnergy.sfbShort[w];

+    data0 = psyData->sfbThreshold.sfbShort[w];
+	data1 = psyData->sfbEnergy.sfbShort[w];
 	for (i=hPsyConfShort->sfbCnt; i; i--) {
       tdata = L_mpy_ls(*data1++, hPsyConfShort->ratio);
-      *data0++ = min(tdata, clipEnergy);

+      *data0++ = min(tdata, clipEnergy);
     }
 
-    /* Calc sfb-bandwise mdct-energies for left and right channel again */     
+    /* Calc sfb-bandwise mdct-energies for left and right channel again */
     if (tnsData->dataRaw.tnsShort.subBlockInfo[w].tnsActive != 0) {
-      Word16 tnsStartBand = hPsyConfShort->tnsConf.tnsStartBand;                            
+      Word16 tnsStartBand = hPsyConfShort->tnsConf.tnsStartBand;
       CalcBandEnergy( psyData->mdctSpectrum+wOffset,
                       hPsyConfShort->sfbOffset+tnsStartBand,
                       (hPsyConfShort->sfbActive - tnsStartBand),
                       psyData->sfbEnergy.sfbShort[w]+tnsStartBand,
-                      &psyData->sfbEnergySum.sfbShort[w]);

+                      &psyData->sfbEnergySum.sfbShort[w]);
 
-      tdata = psyData->sfbEnergySum.sfbShort[w];

-	  data0 = psyData->sfbEnergy.sfbShort[w];

+      tdata = psyData->sfbEnergySum.sfbShort[w];
+	  data0 = psyData->sfbEnergy.sfbShort[w];
 	  for (i=tnsStartBand; i; i--)
-        tdata += *data0++;

-

+        tdata += *data0++;
+
 	  psyData->sfbEnergySum.sfbShort[w] = tdata;
     }
 
@@ -738,17 +738,17 @@
 
 
     /* threshold in quiet */
-    data0 = psyData->sfbThreshold.sfbShort[w];

-	data1 = hPsyConfShort->sfbThresholdQuiet;

+    data0 = psyData->sfbThreshold.sfbShort[w];
+	data1 = hPsyConfShort->sfbThresholdQuiet;
 	for (i=hPsyConfShort->sfbCnt; i; i--)
-    {

-		*data0 = max(*data0, (*data1 >> normEnergyShift));

-

-		data0++; data1++;

-	}

+    {
+		*data0 = max(*data0, (*data1 >> normEnergyShift));
+
+		data0++; data1++;
+	}
 
 
-    /* preecho */     
+    /* preecho */
     PreEchoControl( psyData->sfbThresholdnm1,
                     hPsyConfShort->sfbCnt,
                     hPsyConfShort->maxAllowedIncreaseFactor,
@@ -764,20 +764,20 @@
                                psyData->sfbThreshold.sfbShort[w]);
 
     /* spreaded energy */
-    data0 = psyData->sfbSpreadedEnergy.sfbShort[w];

-	data1 = psyData->sfbEnergy.sfbShort[w];

+    data0 = psyData->sfbSpreadedEnergy.sfbShort[w];
+	data1 = psyData->sfbEnergy.sfbShort[w];
 	for (i=hPsyConfShort->sfbCnt; i; i--) {
 	  *data0++ = *data1++;
     }
     SpreadingMax(hPsyConfShort->sfbCnt,
-                 hPsyConfShort->sfbMaskLowFactorSprEn, 
+                 hPsyConfShort->sfbMaskLowFactorSprEn,
                  hPsyConfShort->sfbMaskHighFactorSprEn,
                  psyData->sfbSpreadedEnergy.sfbShort[w]);
 
     wOffset += FRAME_LEN_SHORT;
   } /* for TRANS_FAC */
 
-  psyData->mdctScalenm1 = psyData->mdctScale;              
+  psyData->mdctScalenm1 = psyData->mdctScale;
 
   return 0;
 }
@@ -785,7 +785,7 @@
 /*****************************************************************************
 *
 * function name: advancePsychShortMS
-* description:   update mdct-energies for left add or minus right channel 
+* description:   update mdct-energies for left add or minus right channel
 *				for short block
 *
 *****************************************************************************/
@@ -793,7 +793,7 @@
                                    const PSY_CONFIGURATION_SHORT *hPsyConfShort)
 {
   Word32 w, wOffset;
-  wOffset = 0;                                   
+  wOffset = 0;
   for(w=0; w<TRANS_FAC; w++) {
     CalcBandEnergyMS(psyData[0].mdctSpectrum+wOffset,
                      psyData[1].mdctSpectrum+wOffset,
diff --git a/media/libstagefright/codecs/aacenc/src/qc_main.c b/media/libstagefright/codecs/aacenc/src/qc_main.c
index a568020..df6d46e 100644
--- a/media/libstagefright/codecs/aacenc/src/qc_main.c
+++ b/media/libstagefright/codecs/aacenc/src/qc_main.c
@@ -1,27 +1,27 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		qc_main.c

-

-	Content:	Quantizing & coding functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		qc_main.c
+
+	Content:	Quantizing & coding functions
+
 *******************************************************************************/
 
-#include "basic_op.h"

-#include "oper_32b.h"

+#include "basic_op.h"
+#include "oper_32b.h"
 #include "qc_main.h"
 #include "quantize.h"
 #include "interface.h"
@@ -68,12 +68,12 @@
   result = (FRAME_LEN_LONG >> 3) * bitRate;
   quot = result / sampleRate;
 
-   
+
   if (mode == FRAME_LEN_BYTES_MODULO) {
     result -= quot * sampleRate;
   }
   else { /* FRAME_LEN_BYTES_INT */
-    result = quot;                                      
+    result = quot;
   }
 
   return result;
@@ -83,7 +83,7 @@
 *
 *  function name:framePadding
 *  description: Calculates if padding is needed for actual frame
-*  returns: paddingOn or not 
+*  returns: paddingOn or not
 *
 *****************************************************************************/
 static Word16 framePadding(Word32 bitRate,
@@ -93,16 +93,16 @@
   Word16 paddingOn;
   Word16 difference;
 
-  paddingOn = 0;                                                 
+  paddingOn = 0;
 
   difference = calcFrameLen( bitRate,
                              sampleRate,
                              FRAME_LEN_BYTES_MODULO );
   *paddingRest = *paddingRest - difference;
 
-   
+
   if (*paddingRest <= 0 ) {
-    paddingOn = 1;                                               
+    paddingOn = 1;
     *paddingRest = *paddingRest + sampleRate;
   }
 
@@ -120,33 +120,33 @@
 
 Word16 QCOutNew(QC_OUT *hQC, Word16 nChannels, VO_MEM_OPERATOR *pMemOP)
 {
-  Word32 i;

-  Word16 *quantSpec;

-  Word16 *scf;

-  UWord16 *maxValueInSfb;	
-	

-  quantSpec = (Word16 *)mem_malloc(pMemOP, nChannels * FRAME_LEN_LONG * sizeof(Word16), 32, VO_INDEX_ENC_AAC);

-  if(NULL == quantSpec)

+  Word32 i;
+  Word16 *quantSpec;
+  Word16 *scf;
+  UWord16 *maxValueInSfb;
+
+  quantSpec = (Word16 *)mem_malloc(pMemOP, nChannels * FRAME_LEN_LONG * sizeof(Word16), 32, VO_INDEX_ENC_AAC);
+  if(NULL == quantSpec)
 	  return 1;
-  scf = (Word16 *)mem_malloc(pMemOP, nChannels * MAX_GROUPED_SFB * sizeof(Word16), 32, VO_INDEX_ENC_AAC);     

-  if(NULL == scf)

-  {

-	  return 1;

+  scf = (Word16 *)mem_malloc(pMemOP, nChannels * MAX_GROUPED_SFB * sizeof(Word16), 32, VO_INDEX_ENC_AAC);
+  if(NULL == scf)
+  {
+	  return 1;
   }
-  maxValueInSfb = (UWord16 *)mem_malloc(pMemOP, nChannels * MAX_GROUPED_SFB * sizeof(UWord16), 32, VO_INDEX_ENC_AAC);

-  if(NULL == maxValueInSfb)

-  {

-	  return 1;

-  }

-

+  maxValueInSfb = (UWord16 *)mem_malloc(pMemOP, nChannels * MAX_GROUPED_SFB * sizeof(UWord16), 32, VO_INDEX_ENC_AAC);
+  if(NULL == maxValueInSfb)
+  {
+	  return 1;
+  }
+
   for (i=0; i<nChannels; i++) {
     hQC->qcChannel[i].quantSpec = quantSpec + i*FRAME_LEN_LONG;
-    
+
     hQC->qcChannel[i].maxValueInSfb = maxValueInSfb + i*MAX_GROUPED_SFB;
-    
+
     hQC->qcChannel[i].scf = scf + i*MAX_GROUPED_SFB;
   }
- 
+
   return 0;
 }
 
@@ -160,26 +160,26 @@
 **********************************************************************************/
 void QCOutDelete(QC_OUT* hQC, VO_MEM_OPERATOR *pMemOP)
 {
-   Word32 i;

-   if(hQC)

-   {

-      if(hQC->qcChannel[0].quantSpec);

-		 mem_free(pMemOP, hQC->qcChannel[0].quantSpec, VO_INDEX_ENC_AAC);

-    

-      if(hQC->qcChannel[0].maxValueInSfb)

-		  mem_free(pMemOP, hQC->qcChannel[0].maxValueInSfb, VO_INDEX_ENC_AAC);

-    

-	  if(hQC->qcChannel[0].scf)

-		  mem_free(pMemOP, hQC->qcChannel[0].scf, VO_INDEX_ENC_AAC);

-

-	  for (i=0; i<MAX_CHANNELS; i++) {

-		  hQC->qcChannel[i].quantSpec = NULL;

-		  

-		  hQC->qcChannel[i].maxValueInSfb = NULL;

-		  

-		  hQC->qcChannel[i].scf = NULL;

-	  }

-   } 
+   Word32 i;
+   if(hQC)
+   {
+      if(hQC->qcChannel[0].quantSpec);
+		 mem_free(pMemOP, hQC->qcChannel[0].quantSpec, VO_INDEX_ENC_AAC);
+
+      if(hQC->qcChannel[0].maxValueInSfb)
+		  mem_free(pMemOP, hQC->qcChannel[0].maxValueInSfb, VO_INDEX_ENC_AAC);
+
+	  if(hQC->qcChannel[0].scf)
+		  mem_free(pMemOP, hQC->qcChannel[0].scf, VO_INDEX_ENC_AAC);
+
+	  for (i=0; i<MAX_CHANNELS; i++) {
+		  hQC->qcChannel[i].quantSpec = NULL;
+
+		  hQC->qcChannel[i].maxValueInSfb = NULL;
+
+		  hQC->qcChannel[i].scf = NULL;
+	  }
+   }
 }
 
 /*********************************************************************************
@@ -204,8 +204,8 @@
 **********************************************************************************/
 void QCDelete(QC_STATE *hQC, VO_MEM_OPERATOR *pMemOP)
 {
- 
-  /* 
+
+  /*
      nothing to do
   */
   hQC=NULL;
@@ -221,15 +221,15 @@
 Word16 QCInit(QC_STATE *hQC,
               struct QC_INIT *init)
 {
-  hQC->nChannels       = init->elInfo->nChannelsInEl;              
-  hQC->maxBitsTot      = init->maxBits;                            
+  hQC->nChannels       = init->elInfo->nChannelsInEl;
+  hQC->maxBitsTot      = init->maxBits;
   hQC->bitResTot       = sub(init->bitRes, init->averageBits);
-  hQC->averageBitsTot  = init->averageBits;                        
-  hQC->maxBitFac       = init->maxBitFac;                          
+  hQC->averageBitsTot  = init->averageBits;
+  hQC->maxBitFac       = init->maxBitFac;
 
-  hQC->padding.paddingRest = init->padding.paddingRest;            
+  hQC->padding.paddingRest = init->padding.paddingRest;
 
-  hQC->globStatBits    = 3;                          /* for ID_END */ 
+  hQC->globStatBits    = 3;                          /* for ID_END */
 
   /* channel elements init */
   InitElementBits(&hQC->elementBits,
@@ -248,13 +248,13 @@
 
 
 /*********************************************************************************
-* 
+*
 * function name: QCMain
 * description:  quantization and coding the spectrum
 * returns:      0 if success
 *
 **********************************************************************************/
-Word16 QCMain(QC_STATE* hQC,              
+Word16 QCMain(QC_STATE* hQC,
               ELEMENT_BITS* elBits,
               ATS_ELEMENT* adjThrStateElement,
               PSY_OUT_CHANNEL  psyOutChannel[MAX_CHANNELS],  /* may be modified in-place */
@@ -262,34 +262,34 @@
               QC_OUT_CHANNEL  qcOutChannel[MAX_CHANNELS],    /* out                      */
               QC_OUT_ELEMENT* qcOutElement,
               Word16 nChannels,
-			  Word16 ancillaryDataBytes)      
+			  Word16 ancillaryDataBytes)
 {
   Word16 maxChDynBits[MAX_CHANNELS];
-  Word16 chBitDistribution[MAX_CHANNELS];  
+  Word16 chBitDistribution[MAX_CHANNELS];
   Word32 ch;
-   
+
   if (elBits->bitResLevel < 0) {
     return -1;
   }
-   
+
   if (elBits->bitResLevel > elBits->maxBitResBits) {
     return -1;
   }
 
   qcOutElement->staticBitsUsed = countStaticBitdemand(psyOutChannel,
                                                       psyOutElement,
-                                                      nChannels, 

+                                                      nChannels,
 													  qcOutElement->adtsUsed);
 
-   
+
   if (ancillaryDataBytes) {
     qcOutElement->ancBitsUsed = 7 + (ancillaryDataBytes << 3);
-     
+
     if (ancillaryDataBytes >= 15)
       qcOutElement->ancBitsUsed = qcOutElement->ancBitsUsed + 8;
   }
   else {
-    qcOutElement->ancBitsUsed = 0; 
+    qcOutElement->ancBitsUsed = 0;
   }
 
   CalcFormFactor(hQC->logSfbFormFactor, hQC->sfbNRelevantLines, hQC->logSfbEnergy, psyOutChannel, nChannels);
@@ -301,7 +301,7 @@
                    psyOutElement,
                    chBitDistribution,
                    hQC->logSfbEnergy,
-                   hQC->sfbNRelevantLines,                   
+                   hQC->sfbNRelevantLines,
                    qcOutElement,
 				   elBits,
 				   nChannels,
@@ -323,14 +323,14 @@
     maxChDynBits[ch] = extract_l(chBitDistribution[ch] * maxDynBits / 1000);
   }
 
-  qcOutElement->dynBitsUsed = 0;                                         
+  qcOutElement->dynBitsUsed = 0;
   for (ch = 0; ch < nChannels; ch++) {
     Word32 chDynBits;
     Flag   constraintsFulfilled;
     Word32 iter;
-    iter = 0;                                                          
+    iter = 0;
     do {
-      constraintsFulfilled = 1;                                        
+      constraintsFulfilled = 1;
 
       QuantizeSpectrum(psyOutChannel[ch].sfbCnt,
                        psyOutChannel[ch].maxSfbPerGroup,
@@ -340,14 +340,14 @@
                        qcOutChannel[ch].globalGain,
                        qcOutChannel[ch].scf,
                        qcOutChannel[ch].quantSpec);
-       
+
       if (calcMaxValueInSfb(psyOutChannel[ch].sfbCnt,
                             psyOutChannel[ch].maxSfbPerGroup,
                             psyOutChannel[ch].sfbPerGroup,
                             psyOutChannel[ch].sfbOffsets,
                             qcOutChannel[ch].quantSpec,
                             qcOutChannel[ch].maxValueInSfb) > MAX_QUANT) {
-        constraintsFulfilled = 0;                                        
+        constraintsFulfilled = 0;
       }
 
       chDynBits = dynBitCount(qcOutChannel[ch].quantSpec,
@@ -359,24 +359,24 @@
                               psyOutChannel[ch].sfbPerGroup,
                               psyOutChannel[ch].sfbOffsets,
                               &qcOutChannel[ch].sectionData);
-       
+
       if (chDynBits >= maxChDynBits[ch]) {
-        constraintsFulfilled = 0;                                        
+        constraintsFulfilled = 0;
       }
-       
+
       if (!constraintsFulfilled) {
         qcOutChannel[ch].globalGain = qcOutChannel[ch].globalGain + 1;
       }
 
       iter = iter + 1;
-       
+
     } while(!constraintsFulfilled);
 
     qcOutElement->dynBitsUsed = qcOutElement->dynBitsUsed + chDynBits;
 
-    qcOutChannel[ch].mdctScale    = psyOutChannel[ch].mdctScale;         
-    qcOutChannel[ch].groupingMask = psyOutChannel[ch].groupingMask;      
-    qcOutChannel[ch].windowShape  = psyOutChannel[ch].windowShape;       
+    qcOutChannel[ch].mdctScale    = psyOutChannel[ch].mdctScale;
+    qcOutChannel[ch].groupingMask = psyOutChannel[ch].groupingMask;
+    qcOutChannel[ch].windowShape  = psyOutChannel[ch].windowShape;
   }
 
   /* save dynBitsUsed for correction of bits2pe relation */
@@ -411,13 +411,13 @@
   Word16 sfbOffs, sfb;
   Word16 maxValueAll;
 
-  maxValueAll = 0;                                       
+  maxValueAll = 0;
 
   for(sfbOffs=0;sfbOffs<sfbCnt;sfbOffs+=sfbPerGroup) {
     for (sfb = 0; sfb < maxSfbPerGroup; sfb++) {
       Word16 line;
       Word16 maxThisSfb;
-      maxThisSfb = 0;                                    
+      maxThisSfb = 0;
 
       for (line = sfbOffset[sfbOffs+sfb]; line < sfbOffset[sfbOffs+sfb+1]; line++) {
         Word16 absVal;
@@ -425,7 +425,7 @@
         maxThisSfb = max(maxThisSfb, absVal);
       }
 
-      maxValue[sfbOffs+sfb] = maxThisSfb;                
+      maxValue[sfbOffs+sfb] = maxThisSfb;
       maxValueAll = max(maxValueAll, maxThisSfb);
     }
   }
@@ -441,15 +441,15 @@
 **********************************************************************************/
 void updateBitres(QC_STATE* qcKernel,
                   QC_OUT*   qcOut)
-                  
+
 {
   ELEMENT_BITS *elBits;
- 
-  qcKernel->bitResTot = 0;                               
+
+  qcKernel->bitResTot = 0;
 
   elBits = &qcKernel->elementBits;
 
-   
+
   if (elBits->averageBits > 0) {
     /* constant bitrate */
     Word16 bitsUsed;
@@ -460,8 +460,8 @@
   }
   else {
     /* variable bitrate */
-    elBits->bitResLevel = elBits->maxBits;           
-    qcKernel->bitResTot = qcKernel->maxBitsTot;      
+    elBits->bitResLevel = elBits->maxBits;
+    qcKernel->bitResTot = qcKernel->maxBitsTot;
   }
 }
 
@@ -474,57 +474,57 @@
 Word16 FinalizeBitConsumption(QC_STATE *qcKernel,
                               QC_OUT* qcOut)
 {
-  Word32 nFullFillElem;

-  Word32 totFillBits;

-  Word16 diffBits;  
+  Word32 nFullFillElem;
+  Word32 totFillBits;
+  Word16 diffBits;
   Word16 bitsUsed;
 
-  totFillBits = 0;                                       
+  totFillBits = 0;
 
-  qcOut->totStaticBitsUsed = qcKernel->globStatBits;     
+  qcOut->totStaticBitsUsed = qcKernel->globStatBits;
   qcOut->totStaticBitsUsed += qcOut->qcElement.staticBitsUsed;
   qcOut->totDynBitsUsed    = qcOut->qcElement.dynBitsUsed;
   qcOut->totAncBitsUsed    = qcOut->qcElement.ancBitsUsed;
   qcOut->totFillBits       = qcOut->qcElement.fillBits;
-   
+
   if (qcOut->qcElement.fillBits) {
     totFillBits += qcOut->qcElement.fillBits;
   }
 
-  nFullFillElem = (max((qcOut->totFillBits - 1), 0) / maxFillElemBits) * maxFillElemBits;

-  
+  nFullFillElem = (max((qcOut->totFillBits - 1), 0) / maxFillElemBits) * maxFillElemBits;
+
   qcOut->totFillBits = qcOut->totFillBits - nFullFillElem;
 
   /* check fill elements */
-   
+
   if (qcOut->totFillBits > 0) {
     /* minimum Fillelement contains 7 (TAG + byte cnt) bits */
     qcOut->totFillBits = max(7, qcOut->totFillBits);
     /* fill element size equals n*8 + 7 */
-    qcOut->totFillBits = qcOut->totFillBits + ((8 - ((qcOut->totFillBits - 7) & 0x0007)) & 0x0007);     
+    qcOut->totFillBits = qcOut->totFillBits + ((8 - ((qcOut->totFillBits - 7) & 0x0007)) & 0x0007);
   }
 
   qcOut->totFillBits = qcOut->totFillBits + nFullFillElem;
 
   /* now distribute extra fillbits and alignbits over channel elements */
   qcOut->alignBits = 7 - ((qcOut->totDynBitsUsed + qcOut->totStaticBitsUsed +
-                           qcOut->totAncBitsUsed + qcOut->totFillBits - 1) & 0x0007);             
+                           qcOut->totAncBitsUsed + qcOut->totFillBits - 1) & 0x0007);
 
-     
+
   if ( (qcOut->alignBits + qcOut->totFillBits - totFillBits == 8) &&
        (qcOut->totFillBits > 8))
     qcOut->totFillBits = qcOut->totFillBits - 8;
 
-   
+
   diffBits = qcOut->alignBits + qcOut->totFillBits - totFillBits;
-   
+
   if(diffBits>=0) {
     qcOut->qcElement.fillBits += diffBits;
   }
 
   bitsUsed = qcOut->totDynBitsUsed + qcOut->totStaticBitsUsed + qcOut->totAncBitsUsed;
   bitsUsed = bitsUsed + qcOut->totFillBits + qcOut->alignBits;
-   
+
   if (bitsUsed > qcKernel->maxBitsTot) {
     return -1;
   }
@@ -564,9 +564,9 @@
   codeBitsLast = hQC->averageBitsTot - hQC->globStatBits;
   codeBits     = frameLen - hQC->globStatBits;
 
-  /* calculate bits for every channel element */   
+  /* calculate bits for every channel element */
   if (codeBits != codeBitsLast) {
-    Word16 totalBits = 0;                                       
+    Word16 totalBits = 0;
 
     hQC->elementBits.averageBits = (hQC->elementBits.relativeBits * codeBits) >> 16; /* relativeBits was scaled down by 2 */
     totalBits += hQC->elementBits.averageBits;
@@ -574,7 +574,7 @@
     hQC->elementBits.averageBits = hQC->elementBits.averageBits + (codeBits - totalBits);
   }
 
-  hQC->averageBitsTot = frameLen;                        
+  hQC->averageBitsTot = frameLen;
 
   return 0;
 }
diff --git a/media/libstagefright/codecs/aacenc/src/quantize.c b/media/libstagefright/codecs/aacenc/src/quantize.c
index 205f167..54add2f 100644
--- a/media/libstagefright/codecs/aacenc/src/quantize.c
+++ b/media/libstagefright/codecs/aacenc/src/quantize.c
@@ -1,27 +1,27 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		quantize.c

-

-	Content:	quantization functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		quantize.c
+
+	Content:	quantization functions
+
 *******************************************************************************/
 
-#include "typedef.h"

-#include "basic_op.h"

+#include "typedef.h"
+#include "basic_op.h"
 #include "oper_32b.h"
 #include "quantize.h"
 #include "aac_rom.h"
@@ -34,32 +34,32 @@
 
 /*****************************************************************************
 *
-* function name:pow34 
-* description: calculate $x^{\frac{3}{4}}, for 0.5 < x < 1.0$.  
+* function name:pow34
+* description: calculate $x^{\frac{3}{4}}, for 0.5 < x < 1.0$.
 *
 *****************************************************************************/
 __inline Word32 pow34(Word32 x)
 {
   /* index table using MANT_DIGITS bits, but mask out the sign bit and the MSB
-     which is always one */   
+     which is always one */
   return mTab_3_4[(x >> (INT_BITS-2-MANT_DIGITS)) & (MANT_SIZE-1)];
 }
 
 
 /*****************************************************************************
 *
-* function name:quantizeSingleLine 
-* description: quantizes spectrum  
-*              quaSpectrum = mdctSpectrum^3/4*2^(-(3/16)*gain)    
+* function name:quantizeSingleLine
+* description: quantizes spectrum
+*              quaSpectrum = mdctSpectrum^3/4*2^(-(3/16)*gain)
 *
 *****************************************************************************/
 static Word16 quantizeSingleLine(const Word16 gain, const Word32 absSpectrum)
 {
   Word32 e, minusFinalExp, finalShift;
   Word32 x;
-  Word16 qua = 0;                        
+  Word16 qua = 0;
 
-   
+
   if (absSpectrum) {
     e = norm_l(absSpectrum);
     x = pow34(absSpectrum << e);
@@ -71,20 +71,20 @@
 
     /* separate the exponent into a shift, and a multiply */
     finalShift = minusFinalExp >> 4;
-     
+
     if (finalShift < INT_BITS) {
       x = L_mpy_wx(x, pow2tominusNover16[minusFinalExp & 15]);
 
       x += XROUND >> (INT_BITS - finalShift);
 
-      /* shift and quantize */

-	  finalShift--;

-

-	  if(finalShift >= 0)

-		  x >>= finalShift;

-	  else

-		  x <<= (-finalShift);

-		

+      /* shift and quantize */
+	  finalShift--;
+
+	  if(finalShift >= 0)
+		  x >>= finalShift;
+	  else
+		  x <<= (-finalShift);
+
 	  qua = saturate(x);
     }
   }
@@ -94,10 +94,10 @@
 
 /*****************************************************************************
 *
-* function name:quantizeLines 
-* description: quantizes spectrum lines  
-*              quaSpectrum = mdctSpectrum^3/4*2^(-(3/16)*gain)    
-*  input: global gain, number of lines to process, spectral data         
+* function name:quantizeLines
+* description: quantizes spectrum lines
+*              quaSpectrum = mdctSpectrum^3/4*2^(-(3/16)*gain)
+*  input: global gain, number of lines to process, spectral data
 *  output: quantized spectrum
 *
 *****************************************************************************/
@@ -108,53 +108,53 @@
 {
   Word32 line;
   Word32 m = gain&3;
-  Word32 g = (gain >> 2) + 4;

-  Word32 mdctSpeL;

+  Word32 g = (gain >> 2) + 4;
+  Word32 mdctSpeL;
   Word16 *pquat;
-    /* gain&3 */

-

-  pquat = quantBorders[m];

-

-  g += 16;

-  

-  if(g >= 0)

-  {

+    /* gain&3 */
+
+  pquat = quantBorders[m];
+
+  g += 16;
+
+  if(g >= 0)
+  {
 	for (line=0; line<noOfLines; line++) {
 	  Word32 qua;
-	  qua = 0;                                                     
-    

-	  mdctSpeL = mdctSpectrum[line];

-	
+	  qua = 0;
+
+	  mdctSpeL = mdctSpectrum[line];
+
 	  if (mdctSpeL) {
 		Word32 sa;
 		Word32 saShft;
 
         sa = L_abs(mdctSpeL);
-        //saShft = L_shr(sa, 16 + g);

+        //saShft = L_shr(sa, 16 + g);
 	    saShft = sa >> g;
 
         if (saShft > pquat[0]) {
-         
+
           if (saShft < pquat[1]) {
-             
+
             qua = mdctSpeL>0 ? 1 : -1;
 		  }
           else {
-           
+
             if (saShft < pquat[2]) {
-               
+
               qua = mdctSpeL>0 ? 2 : -2;
 			}
             else {
-             
+
               if (saShft < pquat[3]) {
-                 
+
                 qua = mdctSpeL>0 ? 3 : -3;
 			  }
               else {
                 qua = quantizeSingleLine(gain, sa);
                 /* adjust the sign. Since 0 < qua < 1, this cannot overflow. */
-               
+
                 if (mdctSpeL < 0)
                   qua = -qua;
 			  }
@@ -162,55 +162,55 @@
 		  }
 		}
 	  }
-      quaSpectrum[line] = qua ;                                    
-	}

-  }

-  else

-  {

-	for (line=0; line<noOfLines; line++) {

-	  Word32 qua;

-	  qua = 0;                                                     

-    

-	  mdctSpeL = mdctSpectrum[line];

-	

-	  if (mdctSpeL) {

-		Word32 sa;

-		Word32 saShft;

-

-        sa = L_abs(mdctSpeL);

-        saShft = sa << g;

-

-        if (saShft > pquat[0]) {

-         

-          if (saShft < pquat[1]) {

-             

-            qua = mdctSpeL>0 ? 1 : -1;

-		  }

-          else {

-           

-            if (saShft < pquat[2]) {

-               

-              qua = mdctSpeL>0 ? 2 : -2;

-			}

-            else {

-             

-              if (saShft < pquat[3]) {

-                 

-                qua = mdctSpeL>0 ? 3 : -3;

-			  }

-              else {

-                qua = quantizeSingleLine(gain, sa);

-                /* adjust the sign. Since 0 < qua < 1, this cannot overflow. */

-               

-                if (mdctSpeL < 0)

-                  qua = -qua;

-			  }

-			}

-		  }

-		}

-	  }

-      quaSpectrum[line] = qua ;                                    

-	}	  

+      quaSpectrum[line] = qua ;
+	}
+  }
+  else
+  {
+	for (line=0; line<noOfLines; line++) {
+	  Word32 qua;
+	  qua = 0;
+
+	  mdctSpeL = mdctSpectrum[line];
+
+	  if (mdctSpeL) {
+		Word32 sa;
+		Word32 saShft;
+
+        sa = L_abs(mdctSpeL);
+        saShft = sa << g;
+
+        if (saShft > pquat[0]) {
+
+          if (saShft < pquat[1]) {
+
+            qua = mdctSpeL>0 ? 1 : -1;
+		  }
+          else {
+
+            if (saShft < pquat[2]) {
+
+              qua = mdctSpeL>0 ? 2 : -2;
+			}
+            else {
+
+              if (saShft < pquat[3]) {
+
+                qua = mdctSpeL>0 ? 3 : -3;
+			  }
+              else {
+                qua = quantizeSingleLine(gain, sa);
+                /* adjust the sign. Since 0 < qua < 1, this cannot overflow. */
+
+                if (mdctSpeL < 0)
+                  qua = -qua;
+			  }
+			}
+		  }
+		}
+	  }
+      quaSpectrum[line] = qua ;
+	}
   }
 
 }
@@ -218,10 +218,10 @@
 
 /*****************************************************************************
 *
-* function name:iquantizeLines 
+* function name:iquantizeLines
 * description: iquantizes spectrum lines without sign
-*              mdctSpectrum = iquaSpectrum^4/3 *2^(0.25*gain) 
-* input: global gain, number of lines to process,quantized spectrum        
+*              mdctSpectrum = iquaSpectrum^4/3 *2^(0.25*gain)
+* input: global gain, number of lines to process,quantized spectrum
 * output: spectral data
 *
 *****************************************************************************/
@@ -234,11 +234,11 @@
   Word32   iquantizershift;
   Word32   line;
 
-  iquantizermod = gain & 3;                              
+  iquantizermod = gain & 3;
   iquantizershift = gain >> 2;
 
   for (line=0; line<noOfLines; line++) {
-     
+
     if( quantSpectrum[line] != 0 ) {
       Word32 accu;
       Word32 ex;
@@ -252,28 +252,28 @@
       accu = accu << ex;
       specExp = INT_BITS-1 - ex;
 
-      tabIndex = (accu >> (INT_BITS-2-MANT_DIGITS)) & (~MANT_SIZE);        
+      tabIndex = (accu >> (INT_BITS-2-MANT_DIGITS)) & (~MANT_SIZE);
 
       /* calculate "mantissa" ^4/3 */
-      s = mTab_4_3[tabIndex];                                                    
+      s = mTab_4_3[tabIndex];
 
       /* get approperiate exponent multiplier for specExp^3/4 combined with scfMod */
-      t = specExpMantTableComb_enc[iquantizermod][specExp];                      
+      t = specExpMantTableComb_enc[iquantizermod][specExp];
 
       /* multiply "mantissa" ^4/3 with exponent multiplier */
       accu = MULHIGH(s, t);
 
       /* get approperiate exponent shifter */
-      specExp = specExpTableComb_enc[iquantizermod][specExp];                    
+      specExp = specExpTableComb_enc[iquantizermod][specExp];
 
-      specExp += iquantizershift + 1;

-	  if(specExp >= 0)

-		  mdctSpectrum[line] = accu << specExp;

-	  else

+      specExp += iquantizershift + 1;
+	  if(specExp >= 0)
+		  mdctSpectrum[line] = accu << specExp;
+	  else
 		  mdctSpectrum[line] = accu >> (-specExp);
     }
     else {
-      mdctSpectrum[line] = 0;                                                    
+      mdctSpectrum[line] = 0;
     }
   }
 }
@@ -301,7 +301,7 @@
   for(sfbOffs=0;sfbOffs<sfbCnt;sfbOffs+=sfbPerGroup) {
     Word32 sfbNext ;
     for (sfb = 0; sfb < maxSfbPerGroup; sfb = sfbNext) {
-      Word16 scalefactor = scalefactors[sfbOffs+sfb];                          
+      Word16 scalefactor = scalefactors[sfbOffs+sfb];
       /* coalesce sfbs with the same scalefactor */
       for (sfbNext = sfb+1;
            sfbNext < maxSfbPerGroup && scalefactor == scalefactors[sfbOffs+sfbNext];
@@ -318,7 +318,7 @@
 
 /*****************************************************************************
 *
-* function name:calcSfbDist 
+* function name:calcSfbDist
 * description: quantizes and requantizes lines to calculate distortion
 * input:  number of lines to be quantized, ...
 * output: distortion
@@ -331,114 +331,114 @@
   Word32 line;
   Word32 dist;
   Word32 m = gain&3;
-  Word32 g = (gain >> 2) + 4;

-  Word32 g2 = (g << 1) + 1;

-  Word16 *pquat, *repquat;

+  Word32 g = (gain >> 2) + 4;
+  Word32 g2 = (g << 1) + 1;
+  Word16 *pquat, *repquat;
     /* gain&3 */
-

-  pquat = quantBorders[m];

+
+  pquat = quantBorders[m];
   repquat = quantRecon[m];
-	

-  dist = 0;  

-  g += 16;

-  if(g2 < 0 && g >= 0)

-  {	  
-	  g2 = -g2;

-	  for(line=0; line<sfbWidth; line++) {		  
-		  if (spec[line]) {			  
+
+  dist = 0;
+  g += 16;
+  if(g2 < 0 && g >= 0)
+  {
+	  g2 = -g2;
+	  for(line=0; line<sfbWidth; line++) {
+		  if (spec[line]) {
 			  Word32 diff;
 			  Word32 distSingle;
 			  Word32 sa;
 			  Word32 saShft;
 			  sa = L_abs(spec[line]);
 			  //saShft = round16(L_shr(sa, g));
-			  //saShft = L_shr(sa, 16+g);

-			  saShft = sa >> g;

+			  //saShft = L_shr(sa, 16+g);
+			  saShft = sa >> g;
 
-			  if (saShft < pquat[0]) {

-				  distSingle = (saShft * saShft) >> g2;

-			  }

-			  else {

-				  

-				  if (saShft < pquat[1]) {

-					  diff = saShft - repquat[0];

-					  distSingle = (diff * diff) >> g2;

-				  }

-				  else {

-					  

-					  if (saShft < pquat[2]) {

-						  diff = saShft - repquat[1];

-						  distSingle = (diff * diff) >> g2;

-					  }

-					  else {

-						  

-						  if (saShft < pquat[3]) {

-							  diff = saShft - repquat[2];

-							  distSingle = (diff * diff) >> g2;

-						  }

-						  else {

-							  Word16 qua = quantizeSingleLine(gain, sa);

-							  Word32 iqval, diff32;

-							  /* now that we have quantized x, re-quantize it. */

-							  iquantizeLines(gain, 1, &qua, &iqval);

-							  diff32 = sa - iqval;

-							  distSingle = fixmul(diff32, diff32);

-						  }

-					  }

-				  }

-			  }

-			  

-			  dist = L_add(dist, distSingle);

+			  if (saShft < pquat[0]) {
+				  distSingle = (saShft * saShft) >> g2;
+			  }
+			  else {
+
+				  if (saShft < pquat[1]) {
+					  diff = saShft - repquat[0];
+					  distSingle = (diff * diff) >> g2;
+				  }
+				  else {
+
+					  if (saShft < pquat[2]) {
+						  diff = saShft - repquat[1];
+						  distSingle = (diff * diff) >> g2;
+					  }
+					  else {
+
+						  if (saShft < pquat[3]) {
+							  diff = saShft - repquat[2];
+							  distSingle = (diff * diff) >> g2;
+						  }
+						  else {
+							  Word16 qua = quantizeSingleLine(gain, sa);
+							  Word32 iqval, diff32;
+							  /* now that we have quantized x, re-quantize it. */
+							  iquantizeLines(gain, 1, &qua, &iqval);
+							  diff32 = sa - iqval;
+							  distSingle = fixmul(diff32, diff32);
+						  }
+					  }
+				  }
+			  }
+
+			  dist = L_add(dist, distSingle);
 		  }
-	  }

-  }

-  else

-  {

-	  for(line=0; line<sfbWidth; line++) {		  

-		  if (spec[line]) {			  

-			  Word32 diff;

-			  Word32 distSingle;

-			  Word32 sa;

-			  Word32 saShft;

-			  sa = L_abs(spec[line]);

-			  //saShft = round16(L_shr(sa, g));

-			  saShft = L_shr(sa, g);

-

-			  if (saShft < pquat[0]) {

-				  distSingle = L_shl((saShft * saShft), g2);

-			  }

-			  else {

-				  

-				  if (saShft < pquat[1]) {

-					  diff = saShft - repquat[0];

-					  distSingle = L_shl((diff * diff), g2);

-				  }

-				  else {

-					  

-					  if (saShft < pquat[2]) {

-						  diff = saShft - repquat[1];

-						  distSingle = L_shl((diff * diff), g2);

-					  }

-					  else {

-						  

-						  if (saShft < pquat[3]) {

-							  diff = saShft - repquat[2];

-							  distSingle = L_shl((diff * diff), g2);

-						  }

-						  else {

-							  Word16 qua = quantizeSingleLine(gain, sa);

-							  Word32 iqval, diff32;

-							  /* now that we have quantized x, re-quantize it. */

-							  iquantizeLines(gain, 1, &qua, &iqval);

-							  diff32 = sa - iqval;

-							  distSingle = fixmul(diff32, diff32);

-						  }

-					  }

-				  }

-			  }

-			  dist = L_add(dist, distSingle);

-		  }

-	  }	  

+	  }
+  }
+  else
+  {
+	  for(line=0; line<sfbWidth; line++) {
+		  if (spec[line]) {
+			  Word32 diff;
+			  Word32 distSingle;
+			  Word32 sa;
+			  Word32 saShft;
+			  sa = L_abs(spec[line]);
+			  //saShft = round16(L_shr(sa, g));
+			  saShft = L_shr(sa, g);
+
+			  if (saShft < pquat[0]) {
+				  distSingle = L_shl((saShft * saShft), g2);
+			  }
+			  else {
+
+				  if (saShft < pquat[1]) {
+					  diff = saShft - repquat[0];
+					  distSingle = L_shl((diff * diff), g2);
+				  }
+				  else {
+
+					  if (saShft < pquat[2]) {
+						  diff = saShft - repquat[1];
+						  distSingle = L_shl((diff * diff), g2);
+					  }
+					  else {
+
+						  if (saShft < pquat[3]) {
+							  diff = saShft - repquat[2];
+							  distSingle = L_shl((diff * diff), g2);
+						  }
+						  else {
+							  Word16 qua = quantizeSingleLine(gain, sa);
+							  Word32 iqval, diff32;
+							  /* now that we have quantized x, re-quantize it. */
+							  iquantizeLines(gain, 1, &qua, &iqval);
+							  diff32 = sa - iqval;
+							  distSingle = fixmul(diff32, diff32);
+						  }
+					  }
+				  }
+			  }
+			  dist = L_add(dist, distSingle);
+		  }
+	  }
   }
 
   return dist;
diff --git a/media/libstagefright/codecs/aacenc/src/sf_estim.c b/media/libstagefright/codecs/aacenc/src/sf_estim.c
index d34b365..fe40137 100644
--- a/media/libstagefright/codecs/aacenc/src/sf_estim.c
+++ b/media/libstagefright/codecs/aacenc/src/sf_estim.c
@@ -1,26 +1,26 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		sf_estim.c

-

-	Content:	Scale factor estimation functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		sf_estim.c
+
+	Content:	Scale factor estimation functions
+
 *******************************************************************************/
 
-#include "basic_op.h"

+#include "basic_op.h"
 #include "oper_32b.h"
 #include "sf_estim.h"
 #include "quantize.h"
@@ -30,56 +30,56 @@
 static const Word16 MAX_SCF_DELTA = 60;
 
 /*!
-constants reference in comments 
+constants reference in comments
 
  C0 = 6.75f;
- C1 = -69.33295f;   -16/3*log(MAX_QUANT+0.5-logCon)/log(2) 
+ C1 = -69.33295f;   -16/3*log(MAX_QUANT+0.5-logCon)/log(2)
  C2 = 4.0f;
  C3 = 2.66666666f;
- 
-  PE_C1 = 3.0f;        log(8.0)/log(2) 
-  PE_C2 = 1.3219281f;  log(2.5)/log(2) 
-  PE_C3 = 0.5593573f;  1-C2/C1 
-  
+
+  PE_C1 = 3.0f;        log(8.0)/log(2)
+  PE_C2 = 1.3219281f;  log(2.5)/log(2)
+  PE_C3 = 0.5593573f;  1-C2/C1
+
 */
 
 #define FF_SQRT_BITS                    7
 #define FF_SQRT_TABLE_SIZE              (1<<FF_SQRT_BITS - 1<<(FF_SQRT_BITS-2))
-#define COEF08_31		0x66666666		/* 0.8*(1 << 31) */

-#define PE_C1_8			24				/* PE_C1*8 */

-#define PE_C2_16		21				/* PE_C2*8/PE_C3 */

-#define PE_SCALE		0x059a			/* 0.7 * (1 << (15 - 1 - 3))*/

-

-#define SCALE_ESTIMATE_COEF	0x5555		/* (8.8585/(4*log2(10))) * (1 << 15)*/

+#define COEF08_31		0x66666666		/* 0.8*(1 << 31) */
+#define PE_C1_8			24				/* PE_C1*8 */
+#define PE_C2_16		21				/* PE_C2*8/PE_C3 */
+#define PE_SCALE		0x059a			/* 0.7 * (1 << (15 - 1 - 3))*/
+
+#define SCALE_ESTIMATE_COEF	0x5555		/* (8.8585/(4*log2(10))) * (1 << 15)*/
 
 /*********************************************************************************
 *
 * function name: formfac_sqrt
-* description:  calculates sqrt(x)/256 
+* description:  calculates sqrt(x)/256
 *
 **********************************************************************************/
 __inline Word32 formfac_sqrt(Word32 x)
 {
 	Word32 y;
 	Word32 preshift, postshift;
-	
-	
+
+
 	if (x==0) return 0;
 	preshift  = norm_l(x) - (INT_BITS-1-FF_SQRT_BITS);
 	postshift = preshift >> 1;
 	preshift  = postshift << 1;
 	postshift = postshift + 8;	  /* sqrt/256 */
-	if(preshift >= 0)

-		y = x << preshift;        /* now 1/4 <= y < 1 */

-	else

-		y = x >> (-preshift);

-	y = formfac_sqrttable[y-32];

-	

-	if(postshift >= 0)

-		y = y >> postshift;

-	else

-		y = y << (-postshift);

-	

+	if(preshift >= 0)
+		y = x << preshift;        /* now 1/4 <= y < 1 */
+	else
+		y = x >> (-preshift);
+	y = formfac_sqrttable[y-32];
+
+	if(postshift >= 0)
+		y = y >> postshift;
+	else
+		y = y << (-postshift);
+
 	return y;
 }
 
@@ -97,25 +97,25 @@
                       Word16 *logSfbEnergy,
                       PSY_OUT_CHANNEL *psyOutChan)
 {
-	Word32 sfbw, sfbw1;

+	Word32 sfbw, sfbw1;
 	Word32 i, j;
 	Word32 sfbOffs, sfb, shift;
-	

-	sfbw = sfbw1 = 0;

+
+	sfbw = sfbw1 = 0;
 	for (sfbOffs=0; sfbOffs<psyOutChan->sfbCnt; sfbOffs+=psyOutChan->sfbPerGroup){
 		for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-			i = sfbOffs+sfb;      
-			
+			i = sfbOffs+sfb;
+
 			if (psyOutChan->sfbEnergy[i] > psyOutChan->sfbThreshold[i]) {
-				Word32 accu, avgFormFactor,iSfbWidth;

+				Word32 accu, avgFormFactor,iSfbWidth;
 				Word32 *mdctSpec;
-				sfbw = psyOutChan->sfbOffsets[i+1] - psyOutChan->sfbOffsets[i];

-				iSfbWidth = invSBF[(sfbw >> 2) - 1];

+				sfbw = psyOutChan->sfbOffsets[i+1] - psyOutChan->sfbOffsets[i];
+				iSfbWidth = invSBF[(sfbw >> 2) - 1];
 				mdctSpec = psyOutChan->mdctSpectrum + psyOutChan->sfbOffsets[i];
-				accu = 0;                                                                       
+				accu = 0;
 				/* calc sum of sqrt(spec) */
-				for (j=sfbw; j; j--) {

-					accu += formfac_sqrt(L_abs(*mdctSpec)); mdctSpec++;

+				for (j=sfbw; j; j--) {
+					accu += formfac_sqrt(L_abs(*mdctSpec)); mdctSpec++;
 				}
 				logSfbFormFactor[i] = iLog4(accu);
 				logSfbEnergy[i] = iLog4(psyOutChan->sfbEnergy[i]);
@@ -129,7 +129,7 @@
 			}
 			else {
 				/* set number of lines to zero */
-				sfbNRelevantLines[i] = 0;                                                       
+				sfbNRelevantLines[i] = 0;
 			}
 		}
 	}
@@ -141,68 +141,68 @@
 * description:  find better scalefactor with analysis by synthesis
 *
 **********************************************************************************/
-static Word16 improveScf(Word32 *spec, 
-                         Word16  sfbWidth, 
-                         Word32  thresh, 
+static Word16 improveScf(Word32 *spec,
+                         Word16  sfbWidth,
+                         Word32  thresh,
                          Word16  scf,
                          Word16  minScf,
-                         Word32 *dist, 
+                         Word32 *dist,
                          Word16 *minScfCalculated)
 {
 	Word32 cnt;
 	Word32 sfbDist;
 	Word32 scfBest;
 	Word32 thresh125 = L_add(thresh, (thresh >> 2));
-	
-	scfBest = scf;                                                       
-	
+
+	scfBest = scf;
+
 	/* calc real distortion */
 	sfbDist = calcSfbDist(spec, sfbWidth, scf);
-	*minScfCalculated = scf;     

-	if(!sfbDist)

+	*minScfCalculated = scf;
+	if(!sfbDist)
 	  return scfBest;
-	
+
 	if (sfbDist > thresh125) {
 		Word32 scfEstimated;
 		Word32 sfbDistBest;
-		scfEstimated = scf;                                               
-		sfbDistBest = sfbDist;                                            
-		
-		cnt = 0;                                                          
+		scfEstimated = scf;
+		sfbDistBest = sfbDist;
+
+		cnt = 0;
 		while (sfbDist > thresh125 && (cnt < 3)) {
-			
+
 			scf = scf + 1;
 			sfbDist = calcSfbDist(spec, sfbWidth, scf);
-			
+
 			if (sfbDist < sfbDistBest) {
-				scfBest = scf;                                              
-				sfbDistBest = sfbDist;                                      
+				scfBest = scf;
+				sfbDistBest = sfbDist;
 			}
 			cnt = cnt + 1;
 		}
-		cnt = 0;                                                          
-		scf = scfEstimated;                                               
-		sfbDist = sfbDistBest;                                            
+		cnt = 0;
+		scf = scfEstimated;
+		sfbDist = sfbDistBest;
 		while ((sfbDist > thresh125) && (cnt < 1) && (scf > minScf)) {
-			
+
 			scf = scf - 1;
 			sfbDist = calcSfbDist(spec, sfbWidth, scf);
-			
+
 			if (sfbDist < sfbDistBest) {
-				scfBest = scf;                                              
-				sfbDistBest = sfbDist;                                      
+				scfBest = scf;
+				sfbDistBest = sfbDist;
 			}
-			*minScfCalculated = scf;                                       
+			*minScfCalculated = scf;
 			cnt = cnt + 1;
-		}

-		*dist = sfbDistBest;                                              
+		}
+		*dist = sfbDistBest;
 	}
 	else {
-		Word32 sfbDistBest; 
+		Word32 sfbDistBest;
 		Word32 sfbDistAllowed;
 		Word32 thresh08 = fixmul(COEF08_31, thresh);
-		sfbDistBest = sfbDist;                                            
-		
+		sfbDistBest = sfbDist;
+
 		if (sfbDist < thresh08)
 			sfbDistAllowed = sfbDist;
 		else
@@ -210,16 +210,16 @@
 		for (cnt=0; cnt<3; cnt++) {
 			scf = scf + 1;
 			sfbDist = calcSfbDist(spec, sfbWidth, scf);
-			
+
 			if (fixmul(COEF08_31,sfbDist) < sfbDistAllowed) {
 				*minScfCalculated = scfBest + 1;
-				scfBest = scf;                                              
-				sfbDistBest = sfbDist;                                      
+				scfBest = scf;
+				sfbDistBest = sfbDist;
 			}
 		}
-		*dist = sfbDistBest;                                              
+		*dist = sfbDistBest;
 	}
-	
+
 	/* return best scalefactor */
 	return scfBest;
 }
@@ -233,10 +233,10 @@
 static Word16 countSingleScfBits(Word16 scf, Word16 scfLeft, Word16 scfRight)
 {
 	Word16 scfBits;
-	
+
 	scfBits = bitCountScalefactorDelta(scfLeft - scf) +
 		bitCountScalefactorDelta(scf - scfRight);
-	
+
 	return scfBits;
 }
 
@@ -245,7 +245,7 @@
 * function name: calcSingleSpecPe
 * description:  ldRatio = log2(en(n)) - 0,375*scfGain(n)
 *				nbits = 0.7*nLines*ldRation for ldRation >= c1
-*				nbits = 0.7*nLines*(c2 + c3*ldRatio) for ldRation < c1 
+*				nbits = 0.7*nLines*(c2 + c3*ldRatio) for ldRation < c1
 *
 **********************************************************************************/
 static Word16 calcSingleSpecPe(Word16 scf, Word16 sfbConstPePart, Word16 nLines)
@@ -253,18 +253,18 @@
 	Word32 specPe;
 	Word32 ldRatio;
 	Word32 scf3;
-	
+
 	ldRatio = sfbConstPePart << 3; /*  (sfbConstPePart -0.375*scf)*8 */
 	scf3 = scf + scf + scf;
 	ldRatio = ldRatio - scf3;
-    
+
 	if (ldRatio < PE_C1_8) {
-		/* 21 : 2*8*PE_C2, 2*PE_C3 ~ 1*/ 
+		/* 21 : 2*8*PE_C2, 2*PE_C3 ~ 1*/
 		ldRatio = (ldRatio + PE_C2_16) >> 1;
 	}
 	specPe = nLines * ldRatio;
 	specPe = (specPe * PE_SCALE) >> 14;
-	
+
 	return saturate(specPe);
 }
 
@@ -275,53 +275,53 @@
 * description:  count different scf bits used
 *
 **********************************************************************************/
-static Word16 countScfBitsDiff(Word16 *scfOld, Word16 *scfNew, 
+static Word16 countScfBitsDiff(Word16 *scfOld, Word16 *scfNew,
                                Word16 sfbCnt, Word16 startSfb, Word16 stopSfb)
 {
 	Word32 scfBitsDiff;
 	Word32 sfb, sfbLast;
 	Word32 sfbPrev, sfbNext;
-	
-	scfBitsDiff = 0;                                                      
-	sfb = 0;                                                              
-	
+
+	scfBitsDiff = 0;
+	sfb = 0;
+
 	/* search for first relevant sfb */
-	sfbLast = startSfb;                                                   
+	sfbLast = startSfb;
 	while (sfbLast < stopSfb && scfOld[sfbLast] == VOAAC_SHRT_MIN) {
-		
+
 		sfbLast = sfbLast + 1;
 	}
 	/* search for previous relevant sfb and count diff */
 	sfbPrev = startSfb - 1;
 	while ((sfbPrev>=0) && scfOld[sfbPrev] == VOAAC_SHRT_MIN) {
-		
+
 		sfbPrev = sfbPrev - 1;
 	}
-	
+
 	if (sfbPrev>=0) {
 		scfBitsDiff += bitCountScalefactorDelta(scfNew[sfbPrev] - scfNew[sfbLast]) -
 			bitCountScalefactorDelta(scfOld[sfbPrev] - scfOld[sfbLast]);
 	}
 	/* now loop through all sfbs and count diffs of relevant sfbs */
 	for (sfb=sfbLast+1; sfb<stopSfb; sfb++) {
-		
+
 		if (scfOld[sfb] != VOAAC_SHRT_MIN) {
 			scfBitsDiff += bitCountScalefactorDelta(scfNew[sfbLast] - scfNew[sfb]) -
 				bitCountScalefactorDelta(scfOld[sfbLast] - scfOld[sfb]);
-			sfbLast = sfb;                                                    
+			sfbLast = sfb;
 		}
 	}
 	/* search for next relevant sfb and count diff */
-	sfbNext = stopSfb;                                                    
+	sfbNext = stopSfb;
 	while (sfbNext < sfbCnt && scfOld[sfbNext] == VOAAC_SHRT_MIN) {
-		
+
 		sfbNext = sfbNext + 1;
 	}
-	
+
 	if (sfbNext < sfbCnt)
 		scfBitsDiff += bitCountScalefactorDelta(scfNew[sfbLast] - scfNew[sfbNext]) -
 		bitCountScalefactorDelta(scfOld[sfbLast] - scfOld[sfbNext]);
-	
+
 	return saturate(scfBitsDiff);
 }
 
@@ -331,52 +331,52 @@
                              Word16 *logSfbEnergy,
                              Word16 *logSfbFormFactor,
                              Word16 *sfbNRelevantLines,
-                             Word16 startSfb, 
+                             Word16 startSfb,
                              Word16 stopSfb)
 {
 	Word32 specPeDiff;
 	Word32 sfb;
-	
-	specPeDiff = 0;                                                       
-	
+
+	specPeDiff = 0;
+
 	/* loop through all sfbs and count pe difference */
 	for (sfb=startSfb; sfb<stopSfb; sfb++) {
-		
-		
+
+
 		if (scfOld[sfb] != VOAAC_SHRT_MIN) {
 			Word32 ldRatioOld, ldRatioNew;
 			Word32 scf3;
-			
-			
+
+
 			if (sfbConstPePart[sfb] == MIN_16) {
 				sfbConstPePart[sfb] = ((logSfbEnergy[sfb] -
 					logSfbFormFactor[sfb]) + 11-8*4+3) >> 2;
 			}
-			
-			
+
+
 			ldRatioOld = sfbConstPePart[sfb] << 3;
 			scf3 = scfOld[sfb] + scfOld[sfb] + scfOld[sfb];
 			ldRatioOld = ldRatioOld - scf3;
 			ldRatioNew = sfbConstPePart[sfb] << 3;
 			scf3 = scfNew[sfb] + scfNew[sfb] + scfNew[sfb];
 			ldRatioNew = ldRatioNew - scf3;
-			
+
 			if (ldRatioOld < PE_C1_8) {
 				/* 21 : 2*8*PE_C2, 2*PE_C3 ~ 1*/
 				ldRatioOld = (ldRatioOld + PE_C2_16) >> 1;
 			}
-			
+
 			if (ldRatioNew < PE_C1_8) {
 				/* 21 : 2*8*PE_C2, 2*PE_C3 ~ 1*/
 				ldRatioNew = (ldRatioNew + PE_C2_16) >> 1;
 			}
-			
+
 			specPeDiff +=  sfbNRelevantLines[sfb] * (ldRatioNew - ldRatioOld);
 		}
 	}
-	
+
 	specPeDiff = (specPeDiff * PE_SCALE) >> 14;
-	
+
 	return saturate(specPeDiff);
 }
 
@@ -390,9 +390,9 @@
 *
 **********************************************************************************/
 static void assimilateSingleScf(PSY_OUT_CHANNEL *psyOutChan,
-                                Word16 *scf, 
+                                Word16 *scf,
                                 Word16 *minScf,
-                                Word32 *sfbDist, 
+                                Word32 *sfbDist,
                                 Word16 *sfbConstPePart,
                                 Word16 *logSfbEnergy,
                                 Word16 *logSfbFormFactor,
@@ -411,94 +411,94 @@
 	Word16 *prevScfNext = psyOutChan->prevScfNext;
 	Word16 *deltaPeLast = psyOutChan->deltaPeLast;
 	Flag   updateMinScfCalculated;
-	
-	success = 0;                                                                  
-	deltaPe = 0;                                                                  
-	
+
+	success = 0;
+	deltaPe = 0;
+
 	for(j=0;j<psyOutChan->sfbCnt;j++){
-		prevScfLast[j] = MAX_16;                                                    
-		prevScfNext[j] = MAX_16;                                                    
-		deltaPeLast[j] = MAX_16;                                                    
-	}

-	
-	sfbLast = -1;                                                                 
-	sfbAct = -1;                                                                  
-	sfbNext = -1;                                                                 
+		prevScfLast[j] = MAX_16;
+		prevScfNext[j] = MAX_16;
+		deltaPeLast[j] = MAX_16;
+	}
+
+	sfbLast = -1;
+	sfbAct = -1;
+	sfbNext = -1;
 	scfLast = 0;
 	scfNext = 0;
-	scfMin = MAX_16;                                                              
+	scfMin = MAX_16;
 	do {
 		/* search for new relevant sfb */
 		sfbNext = sfbNext + 1;
 		while (sfbNext < psyOutChan->sfbCnt && scf[sfbNext] == MIN_16) {
-			
+
 			sfbNext = sfbNext + 1;
 		}
-		
+
 		if ((sfbLast>=0) && (sfbAct>=0) && sfbNext < psyOutChan->sfbCnt) {
 			/* relevant scfs to the left and to the right */
-			scfAct  = scf[sfbAct];                                                    
+			scfAct  = scf[sfbAct];
 			scfLast = scf + sfbLast;
 			scfNext = scf + sfbNext;
 			scfMin  = min(*scfLast, *scfNext);
 		}
 		else {
-			
+
 			if (sfbLast == -1 && (sfbAct>=0) && sfbNext < psyOutChan->sfbCnt) {
 				/* first relevant scf */
-				scfAct  = scf[sfbAct];                                                  
+				scfAct  = scf[sfbAct];
 				scfLast = &scfAct;
 				scfNext = scf + sfbNext;
-				scfMin  = *scfNext;                                                     
+				scfMin  = *scfNext;
 			}
 			else {
-				
+
 				if ((sfbLast>=0) && (sfbAct>=0) && sfbNext == psyOutChan->sfbCnt) {
 					/* last relevant scf */
-					scfAct  = scf[sfbAct];                                                
+					scfAct  = scf[sfbAct];
 					scfLast = scf + sfbLast;
 					scfNext = &scfAct;
-					scfMin  = *scfLast;                                                   
+					scfMin  = *scfLast;
 				}
 			}
 		}
-		
+
 		if (sfbAct>=0)
 			scfMin = max(scfMin, minScf[sfbAct]);
-		
-		if ((sfbAct >= 0) && 
-			(sfbLast>=0 || sfbNext < psyOutChan->sfbCnt) && 
-			scfAct > scfMin && 
-			(*scfLast != prevScfLast[sfbAct] || 
-			*scfNext != prevScfNext[sfbAct] || 
+
+		if ((sfbAct >= 0) &&
+			(sfbLast>=0 || sfbNext < psyOutChan->sfbCnt) &&
+			scfAct > scfMin &&
+			(*scfLast != prevScfLast[sfbAct] ||
+			*scfNext != prevScfNext[sfbAct] ||
 			deltaPe < deltaPeLast[sfbAct])) {
-			success = 0;                                                              
-			
-			/* estimate required bits for actual scf */			
+			success = 0;
+
+			/* estimate required bits for actual scf */
 			if (sfbConstPePart[sfbAct] == MIN_16) {
 				sfbConstPePart[sfbAct] = logSfbEnergy[sfbAct] -
 					logSfbFormFactor[sfbAct] + 11-8*4; /* 4*log2(6.75) - 32 */
-				
+
 				if (sfbConstPePart[sfbAct] < 0)
 					sfbConstPePart[sfbAct] = sfbConstPePart[sfbAct] + 3;
 				sfbConstPePart[sfbAct] = sfbConstPePart[sfbAct] >> 2;
 			}
-			
+
 			sfbPeOld = calcSingleSpecPe(scfAct, sfbConstPePart[sfbAct], sfbNRelevantLines[sfbAct]) +
 				countSingleScfBits(scfAct, *scfLast, *scfNext);
-			deltaPeNew = deltaPe;                                                     
-			updateMinScfCalculated = 1;                                               
+			deltaPeNew = deltaPe;
+			updateMinScfCalculated = 1;
 			do {
 				scfAct = scfAct - 1;
 				/* check only if the same check was not done before */
-				
+
 				if (scfAct < minScfCalculated[sfbAct]) {
 					sfbPeNew = calcSingleSpecPe(scfAct, sfbConstPePart[sfbAct], sfbNRelevantLines[sfbAct]) +
 						countSingleScfBits(scfAct, *scfLast, *scfNext);
-					/* use new scf if no increase in pe and 
+					/* use new scf if no increase in pe and
 					quantization error is smaller */
 					deltaPeTmp = deltaPe + sfbPeNew - sfbPeOld;
-					
+
 					if (deltaPeTmp < 10) {
 						sfbDistNew = calcSfbDist(psyOutChan->mdctSpectrum+
 							psyOutChan->sfbOffsets[sfbAct],
@@ -506,46 +506,46 @@
 							scfAct);
 						if (sfbDistNew < sfbDist[sfbAct]) {
 							/* success, replace scf by new one */
-							scf[sfbAct] = scfAct;                                     
-							sfbDist[sfbAct] = sfbDistNew;                             
-							deltaPeNew = deltaPeTmp;                                  
-							success = 1;                                              
+							scf[sfbAct] = scfAct;
+							sfbDist[sfbAct] = sfbDistNew;
+							deltaPeNew = deltaPeTmp;
+							success = 1;
 						}
 						/* mark as already checked */
-						
+
 						if (updateMinScfCalculated) {
-							minScfCalculated[sfbAct] = scfAct;                        
+							minScfCalculated[sfbAct] = scfAct;
 						}
 					}
 					else {
-						updateMinScfCalculated = 0;                                 
+						updateMinScfCalculated = 0;
 					}
 				}
-				
+
 			} while (scfAct > scfMin);
-			deltaPe = deltaPeNew;                                             
+			deltaPe = deltaPeNew;
 			/* save parameters to avoid multiple computations of the same sfb */
-			prevScfLast[sfbAct] = *scfLast;                                   
-			prevScfNext[sfbAct] = *scfNext;                                   
-			deltaPeLast[sfbAct] = deltaPe;                                    
+			prevScfLast[sfbAct] = *scfLast;
+			prevScfNext[sfbAct] = *scfNext;
+			deltaPeLast[sfbAct] = deltaPe;
 		}
-		
+
 		if (success && restartOnSuccess) {
 			/* start again at first sfb */
-			sfbLast = -1;                                                     
-			sfbAct  = -1;                                                     
-			sfbNext = -1;                                                     
+			sfbLast = -1;
+			sfbAct  = -1;
+			sfbNext = -1;
 			scfLast = 0;
 			scfNext = 0;
-			scfMin  = MAX_16;                                                 
-			success = 0;                                                      
+			scfMin  = MAX_16;
+			success = 0;
 		}
 		else {
 			/* shift sfbs for next band */
-			sfbLast = sfbAct;                                                 
-			sfbAct  = sfbNext;                                                
+			sfbLast = sfbAct;
+			sfbAct  = sfbNext;
 		}
-		
+
   } while (sfbNext < psyOutChan->sfbCnt);
 }
 
@@ -557,9 +557,9 @@
 *
 **********************************************************************************/
 static void assimilateMultipleScf(PSY_OUT_CHANNEL *psyOutChan,
-                                  Word16 *scf, 
+                                  Word16 *scf,
                                   Word16 *minScf,
-                                  Word32 *sfbDist, 
+                                  Word32 *sfbDist,
                                   Word16 *sfbConstPePart,
                                   Word16 *logSfbEnergy,
                                   Word16 *logSfbFormFactor,
@@ -574,95 +574,95 @@
 	Word32 *sfbDistNew = psyOutChan->sfbDistNew;
 	Word16 *scfTmp = psyOutChan->prevScfLast;
 
-	deltaPe = 0;                                                          
-	sfbCnt = psyOutChan->sfbCnt;                                          
-	
+	deltaPe = 0;
+	sfbCnt = psyOutChan->sfbCnt;
+
 	/* calc min and max scalfactors */
-	scfMin = MAX_16;                                                      
-	scfMax = MIN_16;                                                      
+	scfMin = MAX_16;
+	scfMax = MIN_16;
 	for (sfb=0; sfb<sfbCnt; sfb++) {
-		
+
 		if (scf[sfb] != MIN_16) {
 			scfMin = min(scfMin, scf[sfb]);
 			scfMax = max(scfMax, scf[sfb]);
 		}
 	}
-	
+
 	if (scfMax !=  MIN_16) {
-		
-		scfAct = scfMax;                                             
-		
+
+		scfAct = scfMax;
+
 		do {
 			scfAct = scfAct - 1;
 			for (sfb=0; sfb<sfbCnt; sfb++) {
-				scfTmp[sfb] = scf[sfb];                                         
+				scfTmp[sfb] = scf[sfb];
 			}
-			stopSfb = 0;                                                      
+			stopSfb = 0;
 			do {
-				sfb = stopSfb;                                                  
-				
+				sfb = stopSfb;
+
 				while (sfb < sfbCnt && (scf[sfb] == MIN_16 || scf[sfb] <= scfAct)) {
 					sfb = sfb + 1;
 				}
-				startSfb = sfb;                                                 
+				startSfb = sfb;
 				sfb = sfb + 1;
-				
+
 				while (sfb < sfbCnt && (scf[sfb] == MIN_16 || scf[sfb] > scfAct)) {
 					sfb = sfb + 1;
 				}
-				stopSfb = sfb;                                                  
-				
-				possibleRegionFound = 0;                                        
-				
+				stopSfb = sfb;
+
+				possibleRegionFound = 0;
+
 				if (startSfb < sfbCnt) {
-					possibleRegionFound = 1;                                      
+					possibleRegionFound = 1;
 					for (sfb=startSfb; sfb<stopSfb; sfb++) {
-						
+
 						if (scf[sfb]!=MIN_16) {
-							
+
 							if (scfAct < minScf[sfb]) {
-								possibleRegionFound = 0;                                
+								possibleRegionFound = 0;
 								break;
 							}
 						}
 					}
 				}
-				
-				
+
+
 				if (possibleRegionFound) { /* region found */
-					
+
 					/* replace scfs in region by scfAct */
 					for (sfb=startSfb; sfb<stopSfb; sfb++) {
-						
+
 						if (scfTmp[sfb]!=MIN_16)
-							scfTmp[sfb] = scfAct;                                     
+							scfTmp[sfb] = scfAct;
 					}
-					
+
 					/* estimate change in bit demand for new scfs */
 					deltaScfBits = countScfBitsDiff(scf,scfTmp,sfbCnt,startSfb,stopSfb);
 					deltaSpecPe = calcSpecPeDiff(scf, scfTmp, sfbConstPePart,
-						logSfbEnergy, logSfbFormFactor, sfbNRelevantLines, 
+						logSfbEnergy, logSfbFormFactor, sfbNRelevantLines,
 						startSfb, stopSfb);
 					deltaPeNew = deltaPe + deltaScfBits + deltaSpecPe;
-					
-					
+
+
 					if (deltaPeNew < 10) {
 						Word32 distOldSum, distNewSum;
-						
+
 						/* quantize and calc sum of new distortion */
-						distOldSum = 0;                                                     
-						distNewSum = 0;                                                     
+						distOldSum = 0;
+						distNewSum = 0;
 						for (sfb=startSfb; sfb<stopSfb; sfb++) {
-							
+
 							if (scfTmp[sfb] != MIN_16) {
 								distOldSum = L_add(distOldSum, sfbDist[sfb]);
-								
+
 								sfbDistNew[sfb] = calcSfbDist(psyOutChan->mdctSpectrum +
-									psyOutChan->sfbOffsets[sfb], 
+									psyOutChan->sfbOffsets[sfb],
 									(psyOutChan->sfbOffsets[sfb+1] - psyOutChan->sfbOffsets[sfb]),
 									scfAct);
-								
-								
+
+
 								if (sfbDistNew[sfb] > psyOutChan->sfbThreshold[sfb]) {
 									distNewSum = distOldSum << 1;
 									break;
@@ -670,20 +670,20 @@
 								distNewSum = L_add(distNewSum, sfbDistNew[sfb]);
 							}
 						}
-						
+
 						if (distNewSum < distOldSum) {
-							deltaPe = deltaPeNew;                                             
+							deltaPe = deltaPeNew;
 							for (sfb=startSfb; sfb<stopSfb; sfb++) {
-								
+
 								if (scf[sfb]!=MIN_16) {
-									scf[sfb] = scfAct;                                            
-									sfbDist[sfb] = sfbDistNew[sfb];                               
+									scf[sfb] = scfAct;
+									sfbDist[sfb] = sfbDistNew[sfb];
 								}
 							}
 						}
 					}
-				}        
-			} while (stopSfb <= sfbCnt);      
+				}
+			} while (stopSfb <= sfbCnt);
 		} while (scfAct > scfMin);
 	}
 }
@@ -710,125 +710,125 @@
 	Word32 *sfbDist = psyOutChan->sfbDist;
 	Word16 *minSfMaxQuant = psyOutChan->minSfMaxQuant;
 	Word16 *minScfCalculated = psyOutChan->minScfCalculated;
-	
-	
+
+
 	for (i=0; i<psyOutChan->sfbCnt; i++) {
-		Word32 sbfwith, sbfStart;

+		Word32 sbfwith, sbfStart;
 		Word32 *mdctSpec;
-		thresh = psyOutChan->sfbThreshold[i];                                       
-		energy = psyOutChan->sfbEnergy[i];                                          
-		

-		sbfStart = psyOutChan->sfbOffsets[i];

-		sbfwith = psyOutChan->sfbOffsets[i+1] - sbfStart;

-		mdctSpec = psyOutChan->mdctSpectrum+sbfStart;

-		
-		maxSpec = 0;                                                                
+		thresh = psyOutChan->sfbThreshold[i];
+		energy = psyOutChan->sfbEnergy[i];
+
+		sbfStart = psyOutChan->sfbOffsets[i];
+		sbfwith = psyOutChan->sfbOffsets[i+1] - sbfStart;
+		mdctSpec = psyOutChan->mdctSpectrum+sbfStart;
+
+		maxSpec = 0;
 		/* maximum of spectrum */
-		for (j=sbfwith; j; j-- ) {

-			Word32 absSpec = L_abs(*mdctSpec); mdctSpec++;

-			maxSpec |= absSpec;                                                       

+		for (j=sbfwith; j; j-- ) {
+			Word32 absSpec = L_abs(*mdctSpec); mdctSpec++;
+			maxSpec |= absSpec;
 		}
-		
+
 		/* scfs without energy or with thresh>energy are marked with MIN_16 */
-		scf[i] = MIN_16;                                                            
-		minSfMaxQuant[i] = MIN_16;    
-		
+		scf[i] = MIN_16;
+		minSfMaxQuant[i] = MIN_16;
+
 		if ((maxSpec > 0) && (energy > thresh)) {
-			
-			energyPart = logSfbFormFactor[i];                                         
-			thresholdPart = iLog4(thresh);  
-			/* -20 = 4*log2(6.75) - 32 */

+
+			energyPart = logSfbFormFactor[i];
+			thresholdPart = iLog4(thresh);
+			/* -20 = 4*log2(6.75) - 32 */
 			scfInt = ((thresholdPart - energyPart - 20) * SCALE_ESTIMATE_COEF) >> 15;
-			
+
 			minSfMaxQuant[i] = iLog4(maxSpec) - 68; /* 68  -16/3*log(MAX_QUANT+0.5-logCon)/log(2) + 1 */
-			
-			
+
+
 			if (minSfMaxQuant[i] > scfInt) {
-				scfInt = minSfMaxQuant[i];                                              
+				scfInt = minSfMaxQuant[i];
 			}
-			
+
 			/* find better scalefactor with analysis by synthesis */
-			scfInt = improveScf(psyOutChan->mdctSpectrum+sbfStart,

-				sbfwith,

-				thresh, scfInt, minSfMaxQuant[i], 

+			scfInt = improveScf(psyOutChan->mdctSpectrum+sbfStart,
+				sbfwith,
+				thresh, scfInt, minSfMaxQuant[i],
 				&sfbDist[i], &minScfCalculated[i]);
-			
-			scf[i] = scfInt;                                                          
+
+			scf[i] = scfInt;
 		}
 	}
-	
-	
+
+
 	/* scalefactor differece reduction  */
 	{
 		Word16 sfbConstPePart[MAX_GROUPED_SFB];
 		for(i=0;i<psyOutChan->sfbCnt;i++) {
-			sfbConstPePart[i] = MIN_16;                                               
+			sfbConstPePart[i] = MIN_16;
 		}
-		
-		assimilateSingleScf(psyOutChan, scf, 
+
+		assimilateSingleScf(psyOutChan, scf,
 			minSfMaxQuant, sfbDist, sfbConstPePart, logSfbEnergy,
 			logSfbFormFactor, sfbNRelevantLines, minScfCalculated, 1);
-		
-		assimilateMultipleScf(psyOutChan, scf, 
+
+		assimilateMultipleScf(psyOutChan, scf,
 			minSfMaxQuant, sfbDist, sfbConstPePart, logSfbEnergy,
 			logSfbFormFactor, sfbNRelevantLines);
 	}
 
 	/* get max scalefac for global gain */
-	maxScf = MIN_16;                                                              
-	minScf = MAX_16;                                                              
+	maxScf = MIN_16;
+	minScf = MAX_16;
 	for (i=0; i<psyOutChan->sfbCnt; i++) {
-		
+
 		if (maxScf < scf[i]) {
-			maxScf = scf[i];                                                          
+			maxScf = scf[i];
 		}
-		
+
 		if ((scf[i] != MIN_16) && (minScf > scf[i])) {
-			minScf = scf[i];                                                          
+			minScf = scf[i];
 		}
 	}
 	/* limit scf delta */
 	maxAllowedScf = minScf + MAX_SCF_DELTA;
 	for(i=0; i<psyOutChan->sfbCnt; i++) {
-		
+
 		if ((scf[i] != MIN_16) && (maxAllowedScf < scf[i])) {
-			scf[i] = maxAllowedScf;                                                   
+			scf[i] = maxAllowedScf;
 		}
 	}
 	/* new maxScf if any scf has been limited */
-	
+
 	if (maxAllowedScf < maxScf) {
-		maxScf = maxAllowedScf;                                                     
+		maxScf = maxAllowedScf;
 	}
-	
+
 	/* calc loop scalefactors */
-	
+
 	if (maxScf > MIN_16) {
-		*globalGain = maxScf;                                                       
-		lastSf = 0;                                                                 
-		
+		*globalGain = maxScf;
+		lastSf = 0;
+
 		for(i=0; i<psyOutChan->sfbCnt; i++) {
-			
+
 			if (scf[i] == MIN_16) {
-				scf[i] = lastSf;                                                        
+				scf[i] = lastSf;
 				/* set band explicitely to zero */
 				for (j=psyOutChan->sfbOffsets[i]; j<psyOutChan->sfbOffsets[i+1]; j++) {
-					psyOutChan->mdctSpectrum[j] = 0;                                      
+					psyOutChan->mdctSpectrum[j] = 0;
 				}
 			}
 			else {
 				scf[i] = maxScf - scf[i];
-				lastSf = scf[i];                                                        
+				lastSf = scf[i];
 			}
 		}
 	}
 	else{
-		*globalGain = 0;                                                            
+		*globalGain = 0;
 		/* set spectrum explicitely to zero */
 		for(i=0; i<psyOutChan->sfbCnt; i++) {
-			scf[i] = 0;                                                               
+			scf[i] = 0;
 			for (j=psyOutChan->sfbOffsets[i]; j<psyOutChan->sfbOffsets[i+1]; j++) {
-				psyOutChan->mdctSpectrum[j] = 0;                                        
+				psyOutChan->mdctSpectrum[j] = 0;
 			}
 		}
 	}
@@ -848,7 +848,7 @@
                const Word16 nChannels)
 {
 	Word16 j;
-	
+
 	for (j=0; j<nChannels; j++) {
 		CalcFormFactorChannel(logSfbFormFactor[j], sfbNRelevantLines[j], logSfbEnergy[j], &psyOutChannel[j]);
 	}
@@ -869,7 +869,7 @@
                      const Word16    nChannels)
 {
 	Word16 j;
-	
+
 	for (j=0; j<nChannels; j++) {
 		EstimateScaleFactorsChannel(&psyOutChannel[j],
 			qcOutChannel[j].scf,
diff --git a/media/libstagefright/codecs/aacenc/src/spreading.c b/media/libstagefright/codecs/aacenc/src/spreading.c
index e6fc7da..aaf2fff 100644
--- a/media/libstagefright/codecs/aacenc/src/spreading.c
+++ b/media/libstagefright/codecs/aacenc/src/spreading.c
@@ -1,29 +1,29 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		spreading.c

-

-	Content:	Spreading of energy function

-

-*******************************************************************************/

-

-#include "basic_op.h"

-#include "oper_32b.h"

-#include "spreading.h"

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		spreading.c
+
+	Content:	Spreading of energy function
+
+*******************************************************************************/
+
+#include "basic_op.h"
+#include "oper_32b.h"
+#include "spreading.h"
+
 /*********************************************************************************
 *
 * function name: SpreadingMax
@@ -31,22 +31,22 @@
 *				 higher frequencies thr(n) = max(thr(n), sh(n)*thr(n-1))
 *				 lower frequencies  thr(n) = max(thr(n), sl(n)*thr(n+1))
 *
-**********************************************************************************/

-void SpreadingMax(const Word16 pbCnt,

-                  const Word16 *maskLowFactor,

-                  const Word16 *maskHighFactor,

-                  Word32       *pbSpreadedEnergy)

-{

-  Word32 i;

-

-  /* slope to higher frequencies */

-  for (i=1; i<pbCnt; i++) {

-    pbSpreadedEnergy[i] = max(pbSpreadedEnergy[i],

-                                L_mpy_ls(pbSpreadedEnergy[i-1], maskHighFactor[i]));

-  }

-  /* slope to lower frequencies */

-  for (i=pbCnt - 2; i>=0; i--) {

-    pbSpreadedEnergy[i] = max(pbSpreadedEnergy[i],

-                                L_mpy_ls(pbSpreadedEnergy[i+1], maskLowFactor[i]));

-  }

-}

+**********************************************************************************/
+void SpreadingMax(const Word16 pbCnt,
+                  const Word16 *maskLowFactor,
+                  const Word16 *maskHighFactor,
+                  Word32       *pbSpreadedEnergy)
+{
+  Word32 i;
+
+  /* slope to higher frequencies */
+  for (i=1; i<pbCnt; i++) {
+    pbSpreadedEnergy[i] = max(pbSpreadedEnergy[i],
+                                L_mpy_ls(pbSpreadedEnergy[i-1], maskHighFactor[i]));
+  }
+  /* slope to lower frequencies */
+  for (i=pbCnt - 2; i>=0; i--) {
+    pbSpreadedEnergy[i] = max(pbSpreadedEnergy[i],
+                                L_mpy_ls(pbSpreadedEnergy[i+1], maskLowFactor[i]));
+  }
+}
diff --git a/media/libstagefright/codecs/aacenc/src/stat_bits.c b/media/libstagefright/codecs/aacenc/src/stat_bits.c
index 556104e..c2bd8bd 100644
--- a/media/libstagefright/codecs/aacenc/src/stat_bits.c
+++ b/media/libstagefright/codecs/aacenc/src/stat_bits.c
@@ -1,23 +1,23 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		stat_bits.c

-

-	Content:	Static bit counter functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		stat_bits.c
+
+	Content:	Static bit counter functions
+
 *******************************************************************************/
 
 #include "stat_bits.h"
@@ -52,9 +52,9 @@
                               struct TOOLSINFO *toolsInfo)
 {
   Word16 msBits, sfbOff, sfb;
-  msBits = 0;                                            
+  msBits = 0;
 
-   
+
   switch(toolsInfo->msDigest) {
     case MS_NONE:
     case MS_ALL:
@@ -82,37 +82,37 @@
   Flag tnsPresent;
   Word32 numOfWindows;
   Word32 count;
-  Word32 coefBits;

+  Word32 coefBits;
   Word16 *ptcoef;
 
-  count = 0;       

-  
+  count = 0;
+
   if (blockType == 2)
     numOfWindows = 8;
   else
     numOfWindows = 1;
-  tnsPresent = 0;                                        
+  tnsPresent = 0;
 
   for (i=0; i<numOfWindows; i++) {
-     
+
     if (tnsInfo->tnsActive[i]!=0) {
-      tnsPresent = 1;                                    
+      tnsPresent = 1;
     }
   }
-   
+
   if (tnsPresent) {
     /* there is data to be written*/
     /*count += 1; */
     for (i=0; i<numOfWindows; i++) {
-       
+
       if (blockType == 2)
         count += 1;
       else
         count += 2;
-       
+
       if (tnsInfo->tnsActive[i]) {
         count += 1;
-         
+
         if (blockType == 2) {
           count += 4;
           count += 3;
@@ -121,29 +121,29 @@
           count += 6;
           count += 5;
         }
-         
+
         if (tnsInfo->order[i]) {
           count += 1; /*direction*/
-          count += 1; /*coef_compression */	
-           
+          count += 1; /*coef_compression */
+
           if (tnsInfo->coefRes[i] == 4) {
-            ptcoef = tnsInfo->coef + i*TNS_MAX_ORDER_SHORT;

-			coefBits = 3;                                        
+            ptcoef = tnsInfo->coef + i*TNS_MAX_ORDER_SHORT;
+			coefBits = 3;
             for(k=0; k<tnsInfo->order[i]; k++) {
-                 
+
               if ((ptcoef[k] > 3) || (ptcoef[k] < -4)) {
-                coefBits = 4;                                    
+                coefBits = 4;
                 break;
               }
             }
           }
           else {
-            coefBits = 2;                                        
-            ptcoef = tnsInfo->coef + i*TNS_MAX_ORDER_SHORT;

+            coefBits = 2;
+            ptcoef = tnsInfo->coef + i*TNS_MAX_ORDER_SHORT;
 			for(k=0; k<tnsInfo->order[i]; k++) {
-                 
+
               if ((ptcoef[k] > 1) || (ptcoef[k] < -2)) {
-                coefBits = 3;                                    
+                coefBits = 3;
                 break;
               }
             }
@@ -154,15 +154,15 @@
         }
       }
     }
-  }

-  
+  }
+
   return count;
 }
 
 /**********************************************************************************
 *
 * function name: countTnsBits
-* description:   count tns bit demand  
+* description:   count tns bit demand
 *
 **********************************************************************************/
 static Word16 countTnsBits(TNS_INFO *tnsInfo,Word16 blockType)
@@ -173,29 +173,29 @@
 /*********************************************************************************
 *
 * function name: countStaticBitdemand
-* description:   count static bit demand include tns  
+* description:   count static bit demand include tns
 *
 **********************************************************************************/
 Word16 countStaticBitdemand(PSY_OUT_CHANNEL psyOutChannel[MAX_CHANNELS],
                             PSY_OUT_ELEMENT *psyOutElement,
-                            Word16 channels, 

+                            Word16 channels,
 							Word16 adtsUsed)
 {
   Word32 statBits;
   Word32 ch;
-  
-  statBits = 0;                                                  

-

+
+  statBits = 0;
+
   /* if adts used, add 56 bits */
   if(adtsUsed) statBits += 56;
 
-   
+
   switch (channels) {
     case 1:
       statBits += SI_ID_BITS+SI_SCE_BITS+SI_ICS_BITS;
       statBits += countTnsBits(&(psyOutChannel[0].tnsInfo),
                                psyOutChannel[0].windowSequence);
-       
+
       switch(psyOutChannel[0].windowSequence){
         case LONG_WINDOW:
         case START_WINDOW:
@@ -215,7 +215,7 @@
 								  psyOutChannel[0].sfbPerGroup,
 								  psyOutChannel[0].maxSfbPerGroup,
 								  &psyOutElement->toolsInfo);
-       
+
       switch (psyOutChannel[0].windowSequence) {
         case LONG_WINDOW:
         case START_WINDOW:
diff --git a/media/libstagefright/codecs/aacenc/src/tns.c b/media/libstagefright/codecs/aacenc/src/tns.c
index 96d890e..455a864 100644
--- a/media/libstagefright/codecs/aacenc/src/tns.c
+++ b/media/libstagefright/codecs/aacenc/src/tns.c
@@ -1,27 +1,27 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		tns.c

-

-	Content:	Definition TNS tools functions

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		tns.c
+
+	Content:	Definition TNS tools functions
+
 *******************************************************************************/
 
-#include "basic_op.h"

-#include "oper_32b.h"

+#include "basic_op.h"
+#include "oper_32b.h"
 #include "assert.h"
 #include "aac_rom.h"
 #include "psy_const.h"
@@ -32,23 +32,23 @@
 
 #define TNS_MODIFY_BEGIN         2600  /* Hz */
 #define RATIO_PATCH_LOWER_BORDER 380   /* Hz */
-#define TNS_GAIN_THRESH			 141   /* 1.41*100 */

-#define NORM_COEF				 0x028f5c28

+#define TNS_GAIN_THRESH			 141   /* 1.41*100 */
+#define NORM_COEF				 0x028f5c28
 
-static const Word32 TNS_PARCOR_THRESH = 0x0ccccccd; /* 0.1*(1 << 31) */

-/* Limit bands to > 2.0 kHz */

-static unsigned short tnsMinBandNumberLong[12] =

-{ 11, 12, 15, 16, 17, 20, 25, 26, 24, 28, 30, 31 };

-static unsigned short tnsMinBandNumberShort[12] =

-{ 2, 2, 2, 3, 3, 4, 6, 6, 8, 10, 10, 12 };

-

-/**************************************/

-/* Main/Low Profile TNS Parameters    */

-/**************************************/

-static unsigned short tnsMaxBandsLongMainLow[12] =

-{ 31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39 };

-

-static unsigned short tnsMaxBandsShortMainLow[12] =

+static const Word32 TNS_PARCOR_THRESH = 0x0ccccccd; /* 0.1*(1 << 31) */
+/* Limit bands to > 2.0 kHz */
+static unsigned short tnsMinBandNumberLong[12] =
+{ 11, 12, 15, 16, 17, 20, 25, 26, 24, 28, 30, 31 };
+static unsigned short tnsMinBandNumberShort[12] =
+{ 2, 2, 2, 3, 3, 4, 6, 6, 8, 10, 10, 12 };
+
+/**************************************/
+/* Main/Low Profile TNS Parameters    */
+/**************************************/
+static unsigned short tnsMaxBandsLongMainLow[12] =
+{ 31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39 };
+
+static unsigned short tnsMaxBandsShortMainLow[12] =
 { 9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14 };
 
 
@@ -100,20 +100,20 @@
   /*  assert(freq >= 0);  */
   shift = norm_l(fs);
   lineNumber = (extract_l(fixmul((bandStartOffset[numOfBands] << 2),Div_32(freq << shift,fs << shift))) + 1) >> 1;
- 
+
   /* freq > fs/2 */
-  temp = lineNumber - bandStartOffset[numOfBands] ;                                            
+  temp = lineNumber - bandStartOffset[numOfBands] ;
   if (temp >= 0)
     return numOfBands;
 
   /* find band the line number lies in */
   for (band=0; band<numOfBands; band++) {
-    temp = bandStartOffset[band + 1] - lineNumber;                                           
+    temp = bandStartOffset[band + 1] - lineNumber;
     if (temp > 0) break;
   }
 
   temp = (lineNumber - bandStartOffset[band]);
-  temp = (temp - (bandStartOffset[band + 1] - lineNumber));                                   
+  temp = (temp - (bandStartOffset[band + 1] - lineNumber));
   if ( temp > 0 )
   {
     band = band + 1;
@@ -139,25 +139,25 @@
 {
 
   Word32 bitratePerChannel;
-  tC->maxOrder     = TNS_MAX_ORDER;                                           
+  tC->maxOrder     = TNS_MAX_ORDER;
   tC->tnsStartFreq = 1275;
-  tC->coefRes      = 4;                                                                                 
-  
+  tC->coefRes      = 4;
+
   /* to avoid integer division */
-  if ( sub(channels,2) == 0 ) { 
-    bitratePerChannel = bitRate >> 1;    
+  if ( sub(channels,2) == 0 ) {
+    bitratePerChannel = bitRate >> 1;
   }
   else {
-    bitratePerChannel = bitRate;                                                                    
+    bitratePerChannel = bitRate;
   }
 
   tC->tnsMaxSfb = tnsMaxBandsLongMainLow[pC->sampRateIdx];
 
-  tC->tnsActive = active;                                                                           
+  tC->tnsActive = active;
 
   /* now calc band and line borders */
   tC->tnsStopBand = min(pC->sfbCnt, tC->tnsMaxSfb);
-  tC->tnsStopLine = pC->sfbOffset[tC->tnsStopBand];                                                 
+  tC->tnsStopLine = pC->sfbOffset[tC->tnsStopBand];
 
   tC->tnsStartBand = FreqToBandWithRounding(tC->tnsStartFreq, sampleRate,
                                             pC->sfbCnt, (const Word16*)pC->sfbOffset);
@@ -173,18 +173,18 @@
                                                      (const Word16*)pC->sfbOffset);
 
 
-  tC->tnsStartLine = pC->sfbOffset[tC->tnsStartBand];                                                                                                             
+  tC->tnsStartLine = pC->sfbOffset[tC->tnsStartBand];
 
   tC->lpcStopBand = tnsMaxBandsLongMainLow[pC->sampRateIdx];
   tC->lpcStopBand = min(tC->lpcStopBand, pC->sfbActive);
 
-  tC->lpcStopLine = pC->sfbOffset[tC->lpcStopBand];   

-  

+  tC->lpcStopLine = pC->sfbOffset[tC->lpcStopBand];
+
   tC->lpcStartBand = tnsMinBandNumberLong[pC->sampRateIdx];
 
-  tC->lpcStartLine = pC->sfbOffset[tC->lpcStartBand];                                               
+  tC->lpcStartLine = pC->sfbOffset[tC->lpcStartBand];
 
-  tC->threshold = TNS_GAIN_THRESH;                                                             
+  tC->threshold = TNS_GAIN_THRESH;
 
 
   return(0);
@@ -207,23 +207,23 @@
   Word32 bitratePerChannel;
   tC->maxOrder     = TNS_MAX_ORDER_SHORT;
   tC->tnsStartFreq = 2750;
-  tC->coefRes      = 3;                                                                                 
-  
+  tC->coefRes      = 3;
+
   /* to avoid integer division */
   if ( sub(channels,2) == 0 ) {
-    bitratePerChannel = L_shr(bitRate,1);    
+    bitratePerChannel = L_shr(bitRate,1);
   }
   else {
-    bitratePerChannel = bitRate;                                                                    
+    bitratePerChannel = bitRate;
   }
 
   tC->tnsMaxSfb = tnsMaxBandsShortMainLow[pC->sampRateIdx];
 
-  tC->tnsActive = active;                                                                           
+  tC->tnsActive = active;
 
   /* now calc band and line borders */
   tC->tnsStopBand = min(pC->sfbCnt, tC->tnsMaxSfb);
-  tC->tnsStopLine = pC->sfbOffset[tC->tnsStopBand];                                                 
+  tC->tnsStopLine = pC->sfbOffset[tC->tnsStopBand];
 
   tC->tnsStartBand=FreqToBandWithRounding(tC->tnsStartFreq, sampleRate,
                                           pC->sfbCnt, (const Word16*)pC->sfbOffset);
@@ -239,19 +239,19 @@
                                                      (const Word16*)pC->sfbOffset);
 
 
-  tC->tnsStartLine = pC->sfbOffset[tC->tnsStartBand];                                               
+  tC->tnsStartLine = pC->sfbOffset[tC->tnsStartBand];
 
-  tC->lpcStopBand = tnsMaxBandsShortMainLow[pC->sampRateIdx];

+  tC->lpcStopBand = tnsMaxBandsShortMainLow[pC->sampRateIdx];
 
   tC->lpcStopBand = min(tC->lpcStopBand, pC->sfbActive);
 
-  tC->lpcStopLine = pC->sfbOffset[tC->lpcStopBand];                                                 
+  tC->lpcStopLine = pC->sfbOffset[tC->lpcStopBand];
 
-  tC->lpcStartBand = tnsMinBandNumberShort[pC->sampRateIdx];

+  tC->lpcStartBand = tnsMinBandNumberShort[pC->sampRateIdx];
 
-  tC->lpcStartLine = pC->sfbOffset[tC->lpcStartBand];                                               
+  tC->lpcStartLine = pC->sfbOffset[tC->lpcStartBand];
 
-  tC->threshold = TNS_GAIN_THRESH;                                                             
+  tC->threshold = TNS_GAIN_THRESH;
 
   return(0);
 }
@@ -259,7 +259,7 @@
 /**
 *
 * function name: TnsDetect
-* description:  Calculate TNS filter and decide on TNS usage 
+* description:  Calculate TNS filter and decide on TNS usage
 * returns:		0 if success
 *
 */
@@ -278,7 +278,7 @@
   Word32* pWork32 = &pScratchTns[subBlockNumber >> 8];
   Word16* pWeightedSpectrum = (Word16 *)&pScratchTns[subBlockNumber >> 8];
 
-                                                                                                    
+
   if (tC.tnsActive) {
     CalcWeightedSpectrum(spectrum,
                          pWeightedSpectrum,
@@ -290,7 +290,7 @@
                          tC.lpcStopBand,
                          pWork32);
 
-    temp = blockType - SHORT_WINDOW;                                                          
+    temp = blockType - SHORT_WINDOW;
     if ( temp != 0 ) {
         predictionGain = CalcTnsFilter( &pWeightedSpectrum[tC.lpcStartLine],
                                         tC.acfWindow,
@@ -299,15 +299,15 @@
                                         tnsData->dataRaw.tnsLong.subBlockInfo.parcor);
 
 
-        temp = predictionGain - tC.threshold;                                                  
+        temp = predictionGain - tC.threshold;
         if ( temp > 0 ) {
-          tnsData->dataRaw.tnsLong.subBlockInfo.tnsActive = 1;                                      
+          tnsData->dataRaw.tnsLong.subBlockInfo.tnsActive = 1;
         }
         else {
-          tnsData->dataRaw.tnsLong.subBlockInfo.tnsActive = 0;                                      
+          tnsData->dataRaw.tnsLong.subBlockInfo.tnsActive = 0;
         }
 
-        tnsData->dataRaw.tnsLong.subBlockInfo.predictionGain = predictionGain;                      
+        tnsData->dataRaw.tnsLong.subBlockInfo.predictionGain = predictionGain;
     }
     else{
 
@@ -317,28 +317,28 @@
                                         tC.maxOrder,
                                         tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber].parcor);
 
-        temp = predictionGain - tC.threshold;                                                 
+        temp = predictionGain - tC.threshold;
         if ( temp > 0 ) {
-          tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber].tnsActive = 1;                     
+          tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber].tnsActive = 1;
         }
         else {
-          tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber].tnsActive = 0;                     
+          tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber].tnsActive = 0;
         }
 
-        tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber].predictionGain = predictionGain;     
+        tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber].predictionGain = predictionGain;
     }
 
   }
   else{
 
-    temp = blockType - SHORT_WINDOW;                                                          
+    temp = blockType - SHORT_WINDOW;
     if ( temp != 0 ) {
-        tnsData->dataRaw.tnsLong.subBlockInfo.tnsActive = 0;                                        
-        tnsData->dataRaw.tnsLong.subBlockInfo.predictionGain = 0;                                   
+        tnsData->dataRaw.tnsLong.subBlockInfo.tnsActive = 0;
+        tnsData->dataRaw.tnsLong.subBlockInfo.predictionGain = 0;
     }
     else {
-        tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber].tnsActive = 0;                       
-        tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber].predictionGain = 0;                  
+        tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber].tnsActive = 0;
+        tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber].predictionGain = 0;
     }
   }
 
@@ -362,21 +362,21 @@
    const TNS_SUBBLOCK_INFO *sbInfoSrc;
    Word32 i, temp;
 
-   temp =  blockType - SHORT_WINDOW;                                                           
+   temp =  blockType - SHORT_WINDOW;
    if ( temp != 0 ) {
-      sbInfoDest = &tnsDataDest->dataRaw.tnsLong.subBlockInfo;                                      
-      sbInfoSrc  = &tnsDataSrc->dataRaw.tnsLong.subBlockInfo;                                       
+      sbInfoDest = &tnsDataDest->dataRaw.tnsLong.subBlockInfo;
+      sbInfoSrc  = &tnsDataSrc->dataRaw.tnsLong.subBlockInfo;
    }
    else {
-      sbInfoDest = &tnsDataDest->dataRaw.tnsShort.subBlockInfo[subBlockNumber];                     
-      sbInfoSrc  = &tnsDataSrc->dataRaw.tnsShort.subBlockInfo[subBlockNumber];                      
+      sbInfoDest = &tnsDataDest->dataRaw.tnsShort.subBlockInfo[subBlockNumber];
+      sbInfoSrc  = &tnsDataSrc->dataRaw.tnsShort.subBlockInfo[subBlockNumber];
    }
 
    if (100*abs_s(sbInfoDest->predictionGain - sbInfoSrc->predictionGain) <
        (3 * sbInfoDest->predictionGain)) {
-      sbInfoDest->tnsActive = sbInfoSrc->tnsActive;                                                 
+      sbInfoDest->tnsActive = sbInfoSrc->tnsActive;
       for ( i=0; i< tC.maxOrder; i++) {
-        sbInfoDest->parcor[i] = sbInfoSrc->parcor[i];                                               
+        sbInfoDest->parcor[i] = sbInfoSrc->parcor[i];
       }
    }
 }
@@ -399,14 +399,14 @@
 {
   Word32 i;
   Word32 temp_s;
-  Word32 temp;

+  Word32 temp;
   TNS_SUBBLOCK_INFO *psubBlockInfo;
 
-  temp_s = blockType - SHORT_WINDOW;                                                             
-  if ( temp_s != 0) {                                                                               
-    psubBlockInfo = &tnsData->dataRaw.tnsLong.subBlockInfo;

+  temp_s = blockType - SHORT_WINDOW;
+  if ( temp_s != 0) {
+    psubBlockInfo = &tnsData->dataRaw.tnsLong.subBlockInfo;
 	if (psubBlockInfo->tnsActive == 0) {
-      tnsInfo->tnsActive[subBlockNumber] = 0;                                                       
+      tnsInfo->tnsActive[subBlockNumber] = 0;
       return(0);
     }
     else {
@@ -422,22 +422,22 @@
                    tC.coefRes);
 
       for (i=tC.maxOrder - 1; i>=0; i--)  {
-        temp = psubBlockInfo->parcor[i] - TNS_PARCOR_THRESH;         
+        temp = psubBlockInfo->parcor[i] - TNS_PARCOR_THRESH;
         if ( temp > 0 )
           break;
-        temp = psubBlockInfo->parcor[i] + TNS_PARCOR_THRESH;         
+        temp = psubBlockInfo->parcor[i] + TNS_PARCOR_THRESH;
         if ( temp < 0 )
           break;
       }
-      tnsInfo->order[subBlockNumber] = i + 1;                                                    
+      tnsInfo->order[subBlockNumber] = i + 1;
 
 
-      tnsInfo->tnsActive[subBlockNumber] = 1;                                                       
+      tnsInfo->tnsActive[subBlockNumber] = 1;
       for (i=subBlockNumber+1; i<TRANS_FAC; i++) {
-        tnsInfo->tnsActive[i] = 0;                                                                  
+        tnsInfo->tnsActive[i] = 0;
       }
-      tnsInfo->coefRes[subBlockNumber] = tC.coefRes;                                                
-      tnsInfo->length[subBlockNumber] = numOfSfb - tC.tnsStartBand;                                 
+      tnsInfo->coefRes[subBlockNumber] = tC.coefRes;
+      tnsInfo->length[subBlockNumber] = numOfSfb - tC.tnsStartBand;
 
 
       AnalysisFilterLattice(&(spectrum[tC.tnsStartLine]),
@@ -448,10 +448,10 @@
 
     }
   }     /* if (blockType!=SHORT_WINDOW) */
-  else /*short block*/ {                                                                            
-    psubBlockInfo = &tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber];

+  else /*short block*/ {
+    psubBlockInfo = &tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber];
 	if (psubBlockInfo->tnsActive == 0) {
-      tnsInfo->tnsActive[subBlockNumber] = 0;                                                       
+      tnsInfo->tnsActive[subBlockNumber] = 0;
       return(0);
     }
     else {
@@ -466,19 +466,19 @@
                    tC.maxOrder,
                    tC.coefRes);
       for (i=(tC.maxOrder - 1); i>=0; i--)  {
-        temp = psubBlockInfo->parcor[i] - TNS_PARCOR_THRESH;    
+        temp = psubBlockInfo->parcor[i] - TNS_PARCOR_THRESH;
          if ( temp > 0 )
           break;
 
-        temp = psubBlockInfo->parcor[i] + TNS_PARCOR_THRESH;    
+        temp = psubBlockInfo->parcor[i] + TNS_PARCOR_THRESH;
         if ( temp < 0 )
           break;
       }
-      tnsInfo->order[subBlockNumber] = i + 1;                                                    
+      tnsInfo->order[subBlockNumber] = i + 1;
 
-      tnsInfo->tnsActive[subBlockNumber] = 1;                                                       
-      tnsInfo->coefRes[subBlockNumber] = tC.coefRes;                                                
-      tnsInfo->length[subBlockNumber] = numOfSfb - tC.tnsStartBand;                             
+      tnsInfo->tnsActive[subBlockNumber] = 1;
+      tnsInfo->coefRes[subBlockNumber] = tC.coefRes;
+      tnsInfo->length[subBlockNumber] = numOfSfb - tC.tnsStartBand;
 
 
       AnalysisFilterLattice(&(spectrum[tC.tnsStartLine]), (tC.tnsStopLine - tC.tnsStartLine),
@@ -507,14 +507,14 @@
 {
   Word32 k;
 
-  Word32 accu_y = 0x40000000;                                                                     
+  Word32 accu_y = 0x40000000;
   accu_y = L_shr(accu_y,scale);
 
   for(k=1; k<INT_BITS; k++) {
-    const Word32 z = m_log2_table[k];                                                             
+    const Word32 z = m_log2_table[k];
 
     while(L_sub(x,z) >= 0) {
-       
+
       x = L_sub(x, z);
       accu_y = L_add(accu_y, (accu_y >> k));
     }
@@ -548,43 +548,43 @@
     Word32 maxWS;
     Word32 tnsSfbMean[MAX_SFB];    /* length [lpcStopBand-lpcStartBand] should be sufficient here */
 
-    maxWS = 0;                                                                                   
-  
+    maxWS = 0;
+
     /* calc 1.0*2^-INT_BITS/2/sqrt(en) */
     for( sfb = lpcStartBand; sfb < lpcStopBand; sfb++) {
 
-      tmp2 = sfbEnergy[sfb] - 2;                                                            
+      tmp2 = sfbEnergy[sfb] - 2;
       if( tmp2 > 0) {
         tmp = rsqrt(sfbEnergy[sfb], INT_BITS);
-		if(tmp > INT_BITS_SCAL) 

-		{

-			shift =  norm_l(tmp);

-			tmp = Div_32( INT_BITS_SCAL << shift, tmp << shift ); 
+		if(tmp > INT_BITS_SCAL)
+		{
+			shift =  norm_l(tmp);
+			tmp = Div_32( INT_BITS_SCAL << shift, tmp << shift );
 		}
 		else
 		{
-			tmp = 0x7fffffff; 
+			tmp = 0x7fffffff;
 		}
       }
       else {
-        tmp = 0x7fffffff;                                                                           
-      } 
-      tnsSfbMean[sfb] = tmp;                                                                        
+        tmp = 0x7fffffff;
+      }
+      tnsSfbMean[sfb] = tmp;
     }
 
     /* spread normalized values from sfbs to lines */
-    sfb = lpcStartBand;                                                                             
-    tmp = tnsSfbMean[sfb];                                                                          
+    sfb = lpcStartBand;
+    tmp = tnsSfbMean[sfb];
     for ( i=lpcStartLine; i<lpcStopLine; i++){
-      tmp_s = sfbOffset[sfb + 1] - i;                                                      
+      tmp_s = sfbOffset[sfb + 1] - i;
       if ( tmp_s == 0 ) {
         sfb = sfb + 1;
-        tmp2_s = sfb + 1 - lpcStopBand;                                                       
+        tmp2_s = sfb + 1 - lpcStopBand;
         if (tmp2_s <= 0) {
-          tmp = tnsSfbMean[sfb];                                                                    
+          tmp = tnsSfbMean[sfb];
         }
       }
-      pWork32[i] = tmp;                                                                    
+      pWork32[i] = tmp;
     }
     /*filter down*/
     for (i=(lpcStopLine - 2); i>=lpcStartLine; i--){
@@ -597,24 +597,24 @@
 
     /* weight and normalize */
     for (i=lpcStartLine; i<lpcStopLine; i++){
-      pWork32[i] = MULHIGH(pWork32[i], spectrum[i]);                               
-      maxWS |= L_abs(pWork32[i]);                                                          
+      pWork32[i] = MULHIGH(pWork32[i], spectrum[i]);
+      maxWS |= L_abs(pWork32[i]);
     }
     maxShift = norm_l(maxWS);
-

-	maxShift = 16 - maxShift;

-    if(maxShift >= 0)

-	{

-		for (i=lpcStartLine; i<lpcStopLine; i++){

-			weightedSpectrum[i] = pWork32[i] >> maxShift;

-		}

-    }

-	else

-	{

-		maxShift = -maxShift;

-		for (i=lpcStartLine; i<lpcStopLine; i++){

-			weightedSpectrum[i] = saturate(pWork32[i] << maxShift);

-		}

+
+	maxShift = 16 - maxShift;
+    if(maxShift >= 0)
+	{
+		for (i=lpcStartLine; i<lpcStopLine; i++){
+			weightedSpectrum[i] = pWork32[i] >> maxShift;
+		}
+    }
+	else
+	{
+		maxShift = -maxShift;
+		for (i=lpcStartLine; i<lpcStopLine; i++){
+			weightedSpectrum[i] = saturate(pWork32[i] << maxShift);
+		}
 	}
 }
 
@@ -646,7 +646,7 @@
   assert(tnsOrder <= TNS_MAX_ORDER);      /* remove asserts later? (btg) */
 
   for(i=0;i<tnsOrder;i++) {
-    parcor[i] = 0;                               
+    parcor[i] = 0;
   }
 
   AutoCorrelation(signal, parcorWorkBuffer, numOfLines, tnsOrderPlus1);
@@ -669,7 +669,7 @@
 * output:       acf values
 *
 *****************************************************************************/
-#ifndef ARMV5E

+#ifndef ARMV5E
 void AutoCorrelation(const Word16		 input[],
                             Word32       corr[],
                             Word16       samples,
@@ -678,15 +678,15 @@
   Word32 accu;
   Word32 scf;
 
-  scf = 10 - 1;                                                                                      
-

+  scf = 10 - 1;
+
   isamples = samples;
   /* calc first corrCoef:  R[0] = sum { t[i] * t[i] } ; i = 0..N-1 */
-  accu = 0;                                                                                      
+  accu = 0;
   for(j=0; j<isamples; j++) {
-    accu = L_add(accu, ((input[j] * input[j]) >> scf));

+    accu = L_add(accu, ((input[j] * input[j]) >> scf));
   }
-  corr[0] = accu;                                                                                
+  corr[0] = accu;
 
   /* early termination if all corr coeffs are likely going to be zero */
   if(corr[0] == 0) return ;
@@ -694,13 +694,13 @@
   /* calc all other corrCoef:  R[j] = sum { t[i] * t[i+j] } ; i = 0..(N-j-1), j=1..p */
   for(i=1; i<corrCoeff; i++) {
     isamples = isamples - 1;
-    accu = 0;                                                                                    
+    accu = 0;
     for(j=0; j<isamples; j++) {
-      accu = L_add(accu, ((input[j] * input[j+i]) >> scf));

+      accu = L_add(accu, ((input[j] * input[j+i]) >> scf));
     }
-    corr[i] = accu;                                                                              
+    corr[i] = accu;
   }
-}    
+}
 #endif
 
 /*****************************************************************************
@@ -720,46 +720,46 @@
   Word32 predictionGain = 0;
   Word32 num, denom;
   Word32 temp, workBuffer0;
-   
 
-  num = workBuffer[0];                                                                           
-  temp = workBuffer[numOfCoeff];                                                                 
+
+  num = workBuffer[0];
+  temp = workBuffer[numOfCoeff];
 
   for(i=0; i<numOfCoeff-1; i++) {
-    workBuffer[i + numOfCoeff] = workBuffer[i + 1];                                        
+    workBuffer[i + numOfCoeff] = workBuffer[i + 1];
   }
-  workBuffer[i + numOfCoeff] = temp;                                                                           
-  
+  workBuffer[i + numOfCoeff] = temp;
+
   for(i=0; i<numOfCoeff; i++) {
     Word32 refc;
 
-     
+
     if (workBuffer[0] < L_abs(workBuffer[i + numOfCoeff])) {
       return 0 ;
     }
-	shift = norm_l(workBuffer[0]);

+	shift = norm_l(workBuffer[0]);
 	workBuffer0 = Div_32(1 << shift, workBuffer[0] << shift);
     /* calculate refc = -workBuffer[numOfCoeff+i] / workBuffer[0]; -1 <= refc < 1 */
 	refc = L_negate(fixmul(workBuffer[numOfCoeff + i], workBuffer0));
 
-    reflCoeff[i] = refc;                                                                           
+    reflCoeff[i] = refc;
 
-    pWorkBuffer = &(workBuffer[numOfCoeff]);                                                        
+    pWorkBuffer = &(workBuffer[numOfCoeff]);
 
     for(j=i; j<numOfCoeff; j++) {
       Word32 accu1, accu2;
       accu1 = L_add(pWorkBuffer[j], fixmul(refc, workBuffer[j - i]));
       accu2 = L_add(workBuffer[j - i], fixmul(refc, pWorkBuffer[j]));
-      pWorkBuffer[j] = accu1;                                                                       
-      workBuffer[j - i] = accu2;                                                                 
+      pWorkBuffer[j] = accu1;
+      workBuffer[j - i] = accu2;
     }
   }
 
   denom = MULHIGH(workBuffer[0], NORM_COEF);
-   
+
   if (denom != 0) {
-    Word32 temp;

-	shift = norm_l(denom);

+    Word32 temp;
+	shift = norm_l(denom);
 	temp = Div_32(1 << shift, denom << shift);
     predictionGain = fixmul(num, temp);
   }
@@ -774,11 +774,11 @@
   Word32 index = 0;
   Word32 i;
   Word32 temp;
-   
+
   for (i=0;i<8;i++) {
-    temp = L_sub( parcor, tnsCoeff3Borders[i]);                                                     
+    temp = L_sub( parcor, tnsCoeff3Borders[i]);
     if (temp > 0)
-      index=i;                                                                                      
+      index=i;
   }
   return extract_l(index - 4);
 }
@@ -788,12 +788,12 @@
   Word32 index = 0;
   Word32 i;
   Word32 temp;
-   
+
 
   for (i=0;i<16;i++) {
-    temp = L_sub(parcor, tnsCoeff4Borders[i]);                                                      
+    temp = L_sub(parcor, tnsCoeff4Borders[i]);
     if (temp > 0)
-      index=i;                                                                                      
+      index=i;
   }
   return extract_l(index - 8);
 }
@@ -814,12 +814,12 @@
   Word32 temp;
 
   for(i=0; i<order; i++) {
-    temp = bitsPerCoeff - 3;                                                                    
+    temp = bitsPerCoeff - 3;
     if (temp == 0) {
-      index[i] = Search3(parcor[i]);                                                                
-    } 
+      index[i] = Search3(parcor[i]);
+    }
     else {
-      index[i] = Search4(parcor[i]);                                                                
+      index[i] = Search4(parcor[i]);
     }
   }
 }
@@ -839,12 +839,12 @@
   Word32 temp;
 
   for (i=0; i<order; i++) {
-    temp = bitsPerCoeff - 4;                                                                     
+    temp = bitsPerCoeff - 4;
     if ( temp == 0 ) {
-        parcor[i] = tnsCoeff4[index[i] + 8];                                                     
+        parcor[i] = tnsCoeff4[index[i] + 8];
     }
     else {
-        parcor[i] = tnsCoeff3[index[i] + 4];                                                  
+        parcor[i] = tnsCoeff3[index[i] + 4];
     }
   }
 }
@@ -865,20 +865,20 @@
    Word32 accu,tmp,tmpSave;
 
    x = x >> 1;
-   tmpSave = x;                                                                                     
+   tmpSave = x;
 
    for (i=0; i<(order - 1); i++) {
 
      tmp = L_add(fixmul(coef_par[i], x), state_par[i]);
      x   = L_add(fixmul(coef_par[i], state_par[i]), x);
 
-     state_par[i] = tmpSave;                                                                        
-     tmpSave = tmp;                                                                                 
+     state_par[i] = tmpSave;
+     tmpSave = tmp;
   }
 
   /* last stage: only need half operations */
   accu = fixmul(state_par[order - 1], coef_par[(order - 1)]);
-  state_par[(order - 1)] = tmpSave;                                                                
+  state_par[(order - 1)] = tmpSave;
 
   x = L_add(accu, x);
   x = L_add(x, x);
@@ -903,11 +903,11 @@
   Word32 j;
 
   for ( j=0; j<TNS_MAX_ORDER; j++ ) {
-    state_par[j] = 0;                                                                               
+    state_par[j] = 0;
   }
 
   for(j=0; j<numOfLines; j++) {
-    output[j] = FIRLattice(order,signal[j],state_par,parCoeff);                                     
+    output[j] = FIRLattice(order,signal[j],state_par,parCoeff);
   }
 }
 
@@ -922,11 +922,11 @@
                                TNS_SUBBLOCK_INFO subInfo, /*!< TNS subblock info */
                                Word32 *thresholds)        /*!< thresholds (modified) */
 {
-  Word32 i;                                                                                         
+  Word32 i;
   if (subInfo.tnsActive) {
     for(i=startCb; i<stopCb; i++) {
       /* thresholds[i] * 0.25 */
-      thresholds[i] = (thresholds[i] >> 2);                                                      
+      thresholds[i] = (thresholds[i] >> 2);
     }
   }
 }
diff --git a/media/libstagefright/codecs/aacenc/src/transform.c b/media/libstagefright/codecs/aacenc/src/transform.c
index af17b5a..a154a2f 100644
--- a/media/libstagefright/codecs/aacenc/src/transform.c
+++ b/media/libstagefright/codecs/aacenc/src/transform.c
@@ -1,37 +1,37 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		transform.c

-

-	Content:	MDCT Transform functionss

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		transform.c
+
+	Content:	MDCT Transform functionss
+
 *******************************************************************************/
 
-#include "basic_op.h"

+#include "basic_op.h"
 #include "psy_const.h"
 #include "transform.h"
 #include "aac_rom.h"
-

-

-#define LS_TRANS ((FRAME_LEN_LONG-FRAME_LEN_SHORT)/2) /* 448 */

-#define SQRT1_2 0x5a82799a	/* sqrt(1/2) in Q31 */

-#define swap2(p0,p1) \

-	t = p0; t1 = *(&(p0)+1);	\

-	p0 = p1; *(&(p0)+1) = *(&(p1)+1);	\

-	p1 = t; *(&(p1)+1) = t1	

+
+
+#define LS_TRANS ((FRAME_LEN_LONG-FRAME_LEN_SHORT)/2) /* 448 */
+#define SQRT1_2 0x5a82799a	/* sqrt(1/2) in Q31 */
+#define swap2(p0,p1) \
+	t = p0; t1 = *(&(p0)+1);	\
+	p0 = p1; *(&(p0)+1) = *(&(p1)+1);	\
+	p1 = t; *(&(p1)+1) = t1
 
 /*********************************************************************************
 *
@@ -39,350 +39,350 @@
 * description:  Shuffle points prepared function for fft
 *
 **********************************************************************************/
-static void Shuffle(int *buf, int num, const unsigned char* bitTab)

-{

-    int *part0, *part1;

-	int i, j;

-	int t, t1;

-

-	part0 = buf;

-    part1 = buf + num;

-	

-	while ((i = *bitTab++) != 0) {

-        j = *bitTab++;

-

-        swap2(part0[4*i+0], part0[4*j+0]);	

-        swap2(part0[4*i+2], part1[4*j+0]);	

-        swap2(part1[4*i+0], part0[4*j+2]);	

-        swap2(part1[4*i+2], part1[4*j+2]);	

-    }

-

-    do {

-        swap2(part0[4*i+2], part1[4*i+0]);	

-    } while ((i = *bitTab++) != 0);

-}

-

-#if !defined(ARMV5E) && !defined(ARMV7Neon)

+static void Shuffle(int *buf, int num, const unsigned char* bitTab)
+{
+    int *part0, *part1;
+	int i, j;
+	int t, t1;
+
+	part0 = buf;
+    part1 = buf + num;
+
+	while ((i = *bitTab++) != 0) {
+        j = *bitTab++;
+
+        swap2(part0[4*i+0], part0[4*j+0]);
+        swap2(part0[4*i+2], part1[4*j+0]);
+        swap2(part1[4*i+0], part0[4*j+2]);
+        swap2(part1[4*i+2], part1[4*j+2]);
+    }
+
+    do {
+        swap2(part0[4*i+2], part1[4*i+0]);
+    } while ((i = *bitTab++) != 0);
+}
+
+#if !defined(ARMV5E) && !defined(ARMV7Neon)
 
 /*****************************************************************************
 *
 * function name: Radix4First
 * description:  Radix 4 point prepared function for fft
 *
-**********************************************************************************/

-static void Radix4First(int *buf, int num)

-{

-    int r0, r1, r2, r3;

-	int r4, r5, r6, r7;

-	

-	for (; num != 0; num--) 

-	{

-		r0 = buf[0] + buf[2];

-		r1 = buf[1] + buf[3];

-		r2 = buf[0] - buf[2];

-		r3 = buf[1] - buf[3];

-		r4 = buf[4] + buf[6];

-		r5 = buf[5] + buf[7];

-		r6 = buf[4] - buf[6];

-		r7 = buf[5] - buf[7];

-

-		buf[0] = r0 + r4;

-		buf[1] = r1 + r5;

-		buf[4] = r0 - r4;

-		buf[5] = r1 - r5;

-		buf[2] = r2 + r7;

-		buf[3] = r3 - r6;

-		buf[6] = r2 - r7;

-		buf[7] = r3 + r6;

-

-		buf += 8;

-	}

-}

-

+**********************************************************************************/
+static void Radix4First(int *buf, int num)
+{
+    int r0, r1, r2, r3;
+	int r4, r5, r6, r7;
+
+	for (; num != 0; num--)
+	{
+		r0 = buf[0] + buf[2];
+		r1 = buf[1] + buf[3];
+		r2 = buf[0] - buf[2];
+		r3 = buf[1] - buf[3];
+		r4 = buf[4] + buf[6];
+		r5 = buf[5] + buf[7];
+		r6 = buf[4] - buf[6];
+		r7 = buf[5] - buf[7];
+
+		buf[0] = r0 + r4;
+		buf[1] = r1 + r5;
+		buf[4] = r0 - r4;
+		buf[5] = r1 - r5;
+		buf[2] = r2 + r7;
+		buf[3] = r3 - r6;
+		buf[6] = r2 - r7;
+		buf[7] = r3 + r6;
+
+		buf += 8;
+	}
+}
+
 /*****************************************************************************
 *
 * function name: Radix8First
 * description:  Radix 8 point prepared function for fft
 *
-**********************************************************************************/

-static void Radix8First(int *buf, int num)

-{

-   int r0, r1, r2, r3;

-   int i0, i1, i2, i3;

-   int r4, r5, r6, r7;

-   int i4, i5, i6, i7;

-   int t0, t1, t2, t3;

-

-	for ( ; num != 0; num--) 

-	{

-		r0 = buf[0] + buf[2];

-		i0 = buf[1] + buf[3];

-		r1 = buf[0] - buf[2];

-		i1 = buf[1] - buf[3];

-		r2 = buf[4] + buf[6];

-		i2 = buf[5] + buf[7];

-		r3 = buf[4] - buf[6];

-		i3 = buf[5] - buf[7];

-

-		r4 = (r0 + r2) >> 1;

-		i4 = (i0 + i2) >> 1;

-		r5 = (r0 - r2) >> 1;

-		i5 = (i0 - i2) >> 1;

-		r6 = (r1 - i3) >> 1;

-		i6 = (i1 + r3) >> 1;

-		r7 = (r1 + i3) >> 1;

-		i7 = (i1 - r3) >> 1;

-

-		r0 = buf[ 8] + buf[10];

-		i0 = buf[ 9] + buf[11];

-		r1 = buf[ 8] - buf[10];

-		i1 = buf[ 9] - buf[11];

-		r2 = buf[12] + buf[14];

-		i2 = buf[13] + buf[15];

-		r3 = buf[12] - buf[14];

-		i3 = buf[13] - buf[15];

-

-		t0 = (r0 + r2) >> 1;

-		t1 = (i0 + i2) >> 1;

-		t2 = (r0 - r2) >> 1;

-		t3 = (i0 - i2) >> 1;

-

-		buf[ 0] = r4 + t0;

-		buf[ 1] = i4 + t1;

-		buf[ 8] = r4 - t0;

-		buf[ 9] = i4 - t1;

-		buf[ 4] = r5 + t3;

-		buf[ 5] = i5 - t2;

-		buf[12] = r5 - t3;

-		buf[13] = i5 + t2;

-

-		r0 = r1 - i3;

-		i0 = i1 + r3;

-		r2 = r1 + i3;

-		i2 = i1 - r3;

-

-		t0 = MULHIGH(SQRT1_2, r0 - i0);

-		t1 = MULHIGH(SQRT1_2, r0 + i0);

-		t2 = MULHIGH(SQRT1_2, r2 - i2);

-		t3 = MULHIGH(SQRT1_2, r2 + i2);

-

-		buf[ 6] = r6 - t0;

-		buf[ 7] = i6 - t1;

-		buf[14] = r6 + t0;

-		buf[15] = i6 + t1;

-		buf[ 2] = r7 + t3;

-		buf[ 3] = i7 - t2;

-		buf[10] = r7 - t3;

-		buf[11] = i7 + t2;

-

-		buf += 16;

-	}

-}

-

+**********************************************************************************/
+static void Radix8First(int *buf, int num)
+{
+   int r0, r1, r2, r3;
+   int i0, i1, i2, i3;
+   int r4, r5, r6, r7;
+   int i4, i5, i6, i7;
+   int t0, t1, t2, t3;
+
+	for ( ; num != 0; num--)
+	{
+		r0 = buf[0] + buf[2];
+		i0 = buf[1] + buf[3];
+		r1 = buf[0] - buf[2];
+		i1 = buf[1] - buf[3];
+		r2 = buf[4] + buf[6];
+		i2 = buf[5] + buf[7];
+		r3 = buf[4] - buf[6];
+		i3 = buf[5] - buf[7];
+
+		r4 = (r0 + r2) >> 1;
+		i4 = (i0 + i2) >> 1;
+		r5 = (r0 - r2) >> 1;
+		i5 = (i0 - i2) >> 1;
+		r6 = (r1 - i3) >> 1;
+		i6 = (i1 + r3) >> 1;
+		r7 = (r1 + i3) >> 1;
+		i7 = (i1 - r3) >> 1;
+
+		r0 = buf[ 8] + buf[10];
+		i0 = buf[ 9] + buf[11];
+		r1 = buf[ 8] - buf[10];
+		i1 = buf[ 9] - buf[11];
+		r2 = buf[12] + buf[14];
+		i2 = buf[13] + buf[15];
+		r3 = buf[12] - buf[14];
+		i3 = buf[13] - buf[15];
+
+		t0 = (r0 + r2) >> 1;
+		t1 = (i0 + i2) >> 1;
+		t2 = (r0 - r2) >> 1;
+		t3 = (i0 - i2) >> 1;
+
+		buf[ 0] = r4 + t0;
+		buf[ 1] = i4 + t1;
+		buf[ 8] = r4 - t0;
+		buf[ 9] = i4 - t1;
+		buf[ 4] = r5 + t3;
+		buf[ 5] = i5 - t2;
+		buf[12] = r5 - t3;
+		buf[13] = i5 + t2;
+
+		r0 = r1 - i3;
+		i0 = i1 + r3;
+		r2 = r1 + i3;
+		i2 = i1 - r3;
+
+		t0 = MULHIGH(SQRT1_2, r0 - i0);
+		t1 = MULHIGH(SQRT1_2, r0 + i0);
+		t2 = MULHIGH(SQRT1_2, r2 - i2);
+		t3 = MULHIGH(SQRT1_2, r2 + i2);
+
+		buf[ 6] = r6 - t0;
+		buf[ 7] = i6 - t1;
+		buf[14] = r6 + t0;
+		buf[15] = i6 + t1;
+		buf[ 2] = r7 + t3;
+		buf[ 3] = i7 - t2;
+		buf[10] = r7 - t3;
+		buf[11] = i7 + t2;
+
+		buf += 16;
+	}
+}
+
 /*****************************************************************************
 *
 * function name: Radix4FFT
 * description:  Radix 4 point fft core function
 *
-**********************************************************************************/

-static void Radix4FFT(int *buf, int num, int bgn, int *twidTab)

-{

-	int r0, r1, r2, r3;

-	int r4, r5, r6, r7;

-	int t0, t1;

-	int sinx, cosx;

-	int i, j, step;

-	int *xptr, *csptr;

-

-	for (num >>= 2; num != 0; num >>= 2) 

-	{

-		step = 2*bgn;

-		xptr = buf;

-

-    	for (i = num; i != 0; i--) 

-		{

-			csptr = twidTab;

-

-			for (j = bgn; j != 0; j--) 

-			{

-				r0 = xptr[0];

-				r1 = xptr[1];

-				xptr += step;

-				

-				t0 = xptr[0];

-				t1 = xptr[1];				

-				cosx = csptr[0];

-				sinx = csptr[1];

-				r2 = MULHIGH(cosx, t0) + MULHIGH(sinx, t1);		/* cos*br + sin*bi */

-				r3 = MULHIGH(cosx, t1) - MULHIGH(sinx, t0);		/* cos*bi - sin*br */

-				xptr += step;

-

-				t0 = r0 >> 2;

-				t1 = r1 >> 2;

-				r0 = t0 - r2;

-				r1 = t1 - r3;

-				r2 = t0 + r2;

-				r3 = t1 + r3;

-				

-				t0 = xptr[0];

-				t1 = xptr[1];

-				cosx = csptr[2];

-				sinx = csptr[3];

-				r4 = MULHIGH(cosx, t0) + MULHIGH(sinx, t1);		/* cos*cr + sin*ci */

-				r5 = MULHIGH(cosx, t1) - MULHIGH(sinx, t0);		/* cos*ci - sin*cr */

-				xptr += step;

-				

-				t0 = xptr[0];

-				t1 = xptr[1];

-				cosx = csptr[4];

-				sinx = csptr[5];

-				r6 = MULHIGH(cosx, t0) + MULHIGH(sinx, t1);		/* cos*cr + sin*ci */

-				r7 = MULHIGH(cosx, t1) - MULHIGH(sinx, t0);		/* cos*ci - sin*cr */

-				csptr += 6;

-

-				t0 = r4;

-				t1 = r5;

-				r4 = t0 + r6;

-				r5 = r7 - t1;

-				r6 = t0 - r6;

-				r7 = r7 + t1;

-

-				xptr[0] = r0 + r5;

-				xptr[1] = r1 + r6;

-				xptr -= step;

-

-				xptr[0] = r2 - r4;

-				xptr[1] = r3 - r7;

-				xptr -= step;

-

-				xptr[0] = r0 - r5;

-				xptr[1] = r1 - r6;

-				xptr -= step;

-

-				xptr[0] = r2 + r4;

-				xptr[1] = r3 + r7;

-				xptr += 2;

-			}

-			xptr += 3*step;

-		}

-		twidTab += 3*step;

-		bgn <<= 2;

-	}

-}

-

+**********************************************************************************/
+static void Radix4FFT(int *buf, int num, int bgn, int *twidTab)
+{
+	int r0, r1, r2, r3;
+	int r4, r5, r6, r7;
+	int t0, t1;
+	int sinx, cosx;
+	int i, j, step;
+	int *xptr, *csptr;
+
+	for (num >>= 2; num != 0; num >>= 2)
+	{
+		step = 2*bgn;
+		xptr = buf;
+
+    	for (i = num; i != 0; i--)
+		{
+			csptr = twidTab;
+
+			for (j = bgn; j != 0; j--)
+			{
+				r0 = xptr[0];
+				r1 = xptr[1];
+				xptr += step;
+
+				t0 = xptr[0];
+				t1 = xptr[1];
+				cosx = csptr[0];
+				sinx = csptr[1];
+				r2 = MULHIGH(cosx, t0) + MULHIGH(sinx, t1);		/* cos*br + sin*bi */
+				r3 = MULHIGH(cosx, t1) - MULHIGH(sinx, t0);		/* cos*bi - sin*br */
+				xptr += step;
+
+				t0 = r0 >> 2;
+				t1 = r1 >> 2;
+				r0 = t0 - r2;
+				r1 = t1 - r3;
+				r2 = t0 + r2;
+				r3 = t1 + r3;
+
+				t0 = xptr[0];
+				t1 = xptr[1];
+				cosx = csptr[2];
+				sinx = csptr[3];
+				r4 = MULHIGH(cosx, t0) + MULHIGH(sinx, t1);		/* cos*cr + sin*ci */
+				r5 = MULHIGH(cosx, t1) - MULHIGH(sinx, t0);		/* cos*ci - sin*cr */
+				xptr += step;
+
+				t0 = xptr[0];
+				t1 = xptr[1];
+				cosx = csptr[4];
+				sinx = csptr[5];
+				r6 = MULHIGH(cosx, t0) + MULHIGH(sinx, t1);		/* cos*cr + sin*ci */
+				r7 = MULHIGH(cosx, t1) - MULHIGH(sinx, t0);		/* cos*ci - sin*cr */
+				csptr += 6;
+
+				t0 = r4;
+				t1 = r5;
+				r4 = t0 + r6;
+				r5 = r7 - t1;
+				r6 = t0 - r6;
+				r7 = r7 + t1;
+
+				xptr[0] = r0 + r5;
+				xptr[1] = r1 + r6;
+				xptr -= step;
+
+				xptr[0] = r2 - r4;
+				xptr[1] = r3 - r7;
+				xptr -= step;
+
+				xptr[0] = r0 - r5;
+				xptr[1] = r1 - r6;
+				xptr -= step;
+
+				xptr[0] = r2 + r4;
+				xptr[1] = r3 + r7;
+				xptr += 2;
+			}
+			xptr += 3*step;
+		}
+		twidTab += 3*step;
+		bgn <<= 2;
+	}
+}
+
 /*********************************************************************************
 *
 * function name: PreMDCT
 * description:  prepare MDCT process for next FFT compute
 *
-**********************************************************************************/

-static void PreMDCT(int *buf0, int num, const int *csptr)

-{

-	int i;

-	int tr1, ti1, tr2, ti2;

-	int cosa, sina, cosb, sinb;

-	int *buf1;

-	

-	buf1 = buf0 + num - 1;

-

-	for(i = num >> 2; i != 0; i--)

-	{

-		cosa = *csptr++;	

-		sina = *csptr++;	

-		cosb = *csptr++;	

-		sinb = *csptr++;		

-

-		tr1 = *(buf0 + 0);

-		ti2 = *(buf0 + 1);

-		tr2 = *(buf1 - 1);

-		ti1 = *(buf1 + 0);

-		

-		*buf0++ = MULHIGH(cosa, tr1) + MULHIGH(sina, ti1);

-		*buf0++ = MULHIGH(cosa, ti1) - MULHIGH(sina, tr1);		

-		

-		*buf1-- = MULHIGH(cosb, ti2) - MULHIGH(sinb, tr2);		

-		*buf1-- = MULHIGH(cosb, tr2) + MULHIGH(sinb, ti2);

-	}

-}

-

+**********************************************************************************/
+static void PreMDCT(int *buf0, int num, const int *csptr)
+{
+	int i;
+	int tr1, ti1, tr2, ti2;
+	int cosa, sina, cosb, sinb;
+	int *buf1;
+
+	buf1 = buf0 + num - 1;
+
+	for(i = num >> 2; i != 0; i--)
+	{
+		cosa = *csptr++;
+		sina = *csptr++;
+		cosb = *csptr++;
+		sinb = *csptr++;
+
+		tr1 = *(buf0 + 0);
+		ti2 = *(buf0 + 1);
+		tr2 = *(buf1 - 1);
+		ti1 = *(buf1 + 0);
+
+		*buf0++ = MULHIGH(cosa, tr1) + MULHIGH(sina, ti1);
+		*buf0++ = MULHIGH(cosa, ti1) - MULHIGH(sina, tr1);
+
+		*buf1-- = MULHIGH(cosb, ti2) - MULHIGH(sinb, tr2);
+		*buf1-- = MULHIGH(cosb, tr2) + MULHIGH(sinb, ti2);
+	}
+}
+
 /*********************************************************************************
 *
 * function name: PostMDCT
 * description:   post MDCT process after next FFT for MDCT
 *
-**********************************************************************************/

-static void PostMDCT(int *buf0, int num, const int *csptr)

-{

-	int i;

-	int tr1, ti1, tr2, ti2;

-	int cosa, sina, cosb, sinb;

-	int *buf1;

-

-	buf1 = buf0 + num - 1;

-	

-	for(i = num >> 2; i != 0; i--)

-	{

-		cosa = *csptr++;	

-		sina = *csptr++;	

-		cosb = *csptr++;	

-		sinb = *csptr++;

-

-		tr1 = *(buf0 + 0);

-		ti1 = *(buf0 + 1);

-		ti2 = *(buf1 + 0);

-		tr2 = *(buf1 - 1);

-

-		*buf0++ = MULHIGH(cosa, tr1) + MULHIGH(sina, ti1);

-		*buf1-- = MULHIGH(sina, tr1) - MULHIGH(cosa, ti1);		

-		

-		*buf0++ = MULHIGH(sinb, tr2) - MULHIGH(cosb, ti2);

-		*buf1-- = MULHIGH(cosb, tr2) + MULHIGH(sinb, ti2);	

-	}

-}

-#endif

-

-

+**********************************************************************************/
+static void PostMDCT(int *buf0, int num, const int *csptr)
+{
+	int i;
+	int tr1, ti1, tr2, ti2;
+	int cosa, sina, cosb, sinb;
+	int *buf1;
+
+	buf1 = buf0 + num - 1;
+
+	for(i = num >> 2; i != 0; i--)
+	{
+		cosa = *csptr++;
+		sina = *csptr++;
+		cosb = *csptr++;
+		sinb = *csptr++;
+
+		tr1 = *(buf0 + 0);
+		ti1 = *(buf0 + 1);
+		ti2 = *(buf1 + 0);
+		tr2 = *(buf1 - 1);
+
+		*buf0++ = MULHIGH(cosa, tr1) + MULHIGH(sina, ti1);
+		*buf1-- = MULHIGH(sina, tr1) - MULHIGH(cosa, ti1);
+
+		*buf0++ = MULHIGH(sinb, tr2) - MULHIGH(cosb, ti2);
+		*buf1-- = MULHIGH(cosb, tr2) + MULHIGH(sinb, ti2);
+	}
+}
+#endif
+
+
 /**********************************************************************************
 *
 * function name: Mdct_Long
 * description:  the long block mdct, include long_start block, end_long block
 *
-**********************************************************************************/

-void Mdct_Long(int *buf)

-{

-	PreMDCT(buf, 1024, cossintab + 128);

-

-	Shuffle(buf, 512, bitrevTab + 17);

-	Radix8First(buf, 512 >> 3);						

-	Radix4FFT(buf, 512 >> 3, 8, (int *)twidTab512);

-

-	PostMDCT(buf, 1024, cossintab + 128);	

-}

-

-

+**********************************************************************************/
+void Mdct_Long(int *buf)
+{
+	PreMDCT(buf, 1024, cossintab + 128);
+
+	Shuffle(buf, 512, bitrevTab + 17);
+	Radix8First(buf, 512 >> 3);
+	Radix4FFT(buf, 512 >> 3, 8, (int *)twidTab512);
+
+	PostMDCT(buf, 1024, cossintab + 128);
+}
+
+
 /**********************************************************************************
 *
 * function name: Mdct_Short
-* description:  the short block mdct 
+* description:  the short block mdct
 *
-**********************************************************************************/

-void Mdct_Short(int *buf)

-{

-	PreMDCT(buf, 128, cossintab);

-

-	Shuffle(buf, 64, bitrevTab);

-	Radix4First(buf, 64 >> 2);						

-	Radix4FFT(buf, 64 >> 2, 4, (int *)twidTab64);	

-

-	PostMDCT(buf, 128, cossintab);	

-}

+**********************************************************************************/
+void Mdct_Short(int *buf)
+{
+	PreMDCT(buf, 128, cossintab);
+
+	Shuffle(buf, 64, bitrevTab);
+	Radix4First(buf, 64 >> 2);
+	Radix4FFT(buf, 64 >> 2, 4, (int *)twidTab64);
+
+	PostMDCT(buf, 128, cossintab);
+}
 
 
 /*****************************************************************************
 *
 * function name: shiftMdctDelayBuffer
 * description:    the mdct delay buffer has a size of 1600,
-*  so the calculation of LONG,STOP must be  spilt in two 
+*  so the calculation of LONG,STOP must be  spilt in two
 *  passes with 1024 samples and a mid shift,
 *  the SHORT transforms can be completed in the delay buffer,
 *  and afterwards a shift
@@ -409,7 +409,7 @@
 	dsBuf = timeSignal;
 
 	for(i=0; i<FRAME_LEN_LONG; i+=8)
-	{   
+	{
 		*srBuf++ = *dsBuf; dsBuf += chIncrement;
 		*srBuf++ = *dsBuf; dsBuf += chIncrement;
 		*srBuf++ = *dsBuf; dsBuf += chIncrement;
@@ -419,31 +419,31 @@
 		*srBuf++ = *dsBuf; dsBuf += chIncrement;
 		*srBuf++ = *dsBuf; dsBuf += chIncrement;
 	}
-}

-

-

+}
+
+
 /*****************************************************************************
 *
 * function name: getScalefactorOfShortVectorStride
 * description:  Calculate max possible scale factor for input vector of shorts
 * returns:      Maximum scale factor
 *
-**********************************************************************************/

-static Word16 getScalefactorOfShortVectorStride(const Word16 *vector, /*!< Pointer to input vector */

-												Word16 len,           /*!< Length of input vector */

-												Word16 stride)        /*!< Stride of input vector */

-{

-	Word16 maxVal = 0;

-	Word16 absVal;

-	Word16 i;

-

-	for(i=0; i<len; i++){

-		absVal = abs_s(vector[i*stride]);

-		maxVal |= absVal;

-	}

-

-	return( maxVal ? norm_s(maxVal) : 15);

-}

+**********************************************************************************/
+static Word16 getScalefactorOfShortVectorStride(const Word16 *vector, /*!< Pointer to input vector */
+												Word16 len,           /*!< Length of input vector */
+												Word16 stride)        /*!< Stride of input vector */
+{
+	Word16 maxVal = 0;
+	Word16 absVal;
+	Word16 i;
+
+	for(i=0; i<len; i++){
+		absVal = abs_s(vector[i*stride]);
+		maxVal |= absVal;
+	}
+
+	return( maxVal ? norm_s(maxVal) : 15);
+}
 
 
 /*****************************************************************************
@@ -464,16 +464,16 @@
 	Word32 i,w;
 	Word32 timeSignalSample;
 	Word32 ws1,ws2;
-	Word16 *dctIn0, *dctIn1;

-	Word32 *outData0, *outData1;

+	Word16 *dctIn0, *dctIn1;
+	Word32 *outData0, *outData1;
 	Word32 *winPtr;
 
 	Word32 delayBufferSf,timeSignalSf,minSf;
 	Word32 headRoom=0;
-	
+
 	switch(blockType){
-		
-		
+
+
 	case LONG_WINDOW:
 		/*
 		we access BLOCK_SWITCHING_OFFSET (1600 ) delay buffer samples + 448 new timeSignal samples
@@ -483,15 +483,15 @@
 		timeSignalSf  = getScalefactorOfShortVectorStride(timeSignal,2*FRAME_LEN_LONG-BLOCK_SWITCHING_OFFSET,chIncrement);
 		minSf = min(delayBufferSf,timeSignalSf);
 		minSf = min(minSf,14);
-		
+
 		dctIn0 = mdctDelayBuffer;
 		dctIn1 = mdctDelayBuffer + FRAME_LEN_LONG - 1;
 		outData0 = realOut + FRAME_LEN_LONG/2;
-		
+
 		/* add windows and pre add for mdct to last buffer*/
 		winPtr = (int *)LongWindowKBD;
 		for(i=0;i<FRAME_LEN_LONG/2;i++){
-			timeSignalSample = (*dctIn0++) << minSf; 
+			timeSignalSample = (*dctIn0++) << minSf;
 			ws1 = timeSignalSample * (*winPtr >> 16);
 			timeSignalSample = (*dctIn1--) << minSf;
 			ws2 = timeSignalSample * (*winPtr & 0xffff);
@@ -499,30 +499,30 @@
 			/* shift 2 to avoid overflow next */
 			*outData0++ = (ws1 >> 2) - (ws2 >> 2);
 		}
-		
+
 		shiftMdctDelayBuffer(mdctDelayBuffer,timeSignal,chIncrement);
-		
+
 		/* add windows and pre add for mdct to new buffer*/
 		dctIn0 = mdctDelayBuffer;
 		dctIn1 = mdctDelayBuffer + FRAME_LEN_LONG - 1;
-		outData0 = realOut + FRAME_LEN_LONG/2 - 1; 
+		outData0 = realOut + FRAME_LEN_LONG/2 - 1;
 		winPtr = (int *)LongWindowKBD;
-		for(i=0;i<FRAME_LEN_LONG/2;i++){    
+		for(i=0;i<FRAME_LEN_LONG/2;i++){
 			timeSignalSample = (*dctIn0++) << minSf;
 			ws1 = timeSignalSample * (*winPtr & 0xffff);
 			timeSignalSample = (*dctIn1--) << minSf;
 			ws2 = timeSignalSample * (*winPtr >> 16);
 			winPtr++;
 			/* shift 2 to avoid overflow next */
-			*outData0-- = -((ws1 >> 2) + (ws2 >> 2)); 
+			*outData0-- = -((ws1 >> 2) + (ws2 >> 2));
 		}
 
-		Mdct_Long(realOut);

-		/* update scale factor */

+		Mdct_Long(realOut);
+		/* update scale factor */
 		minSf = 14 - minSf;
-		*mdctScale=minSf; 
+		*mdctScale=minSf;
 		break;
-		
+
 	case START_WINDOW:
 		/*
 		we access BLOCK_SWITCHING_OFFSET (1600 ) delay buffer samples + no timeSignal samples
@@ -533,7 +533,7 @@
 
 		dctIn0 = mdctDelayBuffer;
 		dctIn1 = mdctDelayBuffer + FRAME_LEN_LONG - 1;
-		outData0 = realOut + FRAME_LEN_LONG/2; 		
+		outData0 = realOut + FRAME_LEN_LONG/2;
 		winPtr = (int *)LongWindowKBD;
 
 		/* add windows and pre add for mdct to last buffer*/
@@ -543,20 +543,20 @@
 			timeSignalSample = (*dctIn1--) << minSf;
 			ws2 = timeSignalSample * (*winPtr & 0xffff);
 			winPtr ++;
-			*outData0++ = (ws1 >> 2) - (ws2 >> 2);  /* shift 2 to avoid overflow next */

+			*outData0++ = (ws1 >> 2) - (ws2 >> 2);  /* shift 2 to avoid overflow next */
 		}
-		
+
 		shiftMdctDelayBuffer(mdctDelayBuffer,timeSignal,chIncrement);
-		
-		outData0 = realOut + FRAME_LEN_LONG/2 - 1; 
+
+		outData0 = realOut + FRAME_LEN_LONG/2 - 1;
 		for(i=0;i<LS_TRANS;i++){
-			*outData0-- = -mdctDelayBuffer[i] << (15 - 2 + minSf);  
+			*outData0-- = -mdctDelayBuffer[i] << (15 - 2 + minSf);
 		}
-		
+
 		/* add windows and pre add for mdct to new buffer*/
 		dctIn0 = mdctDelayBuffer + LS_TRANS;
 		dctIn1 = mdctDelayBuffer + FRAME_LEN_LONG - 1 - LS_TRANS;
-		outData0 = realOut + FRAME_LEN_LONG/2 - 1 -LS_TRANS; 
+		outData0 = realOut + FRAME_LEN_LONG/2 - 1 -LS_TRANS;
 		winPtr = (int *)ShortWindowSine;
 		for(i=0;i<FRAME_LEN_SHORT/2;i++){
 			timeSignalSample= (*dctIn0++) << minSf;
@@ -564,7 +564,7 @@
 			timeSignalSample= (*dctIn1--) << minSf;
 			ws2 = timeSignalSample * (*winPtr >> 16);
 			winPtr++;
-			*outData0-- =  -((ws1 >> 2) + (ws2 >> 2));  /* shift 2 to avoid overflow next */

+			*outData0-- =  -((ws1 >> 2) + (ws2 >> 2));  /* shift 2 to avoid overflow next */
 		}
 
 		Mdct_Long(realOut);
@@ -572,7 +572,7 @@
 		minSf = 14 - minSf;
 		*mdctScale= minSf;
 		break;
-		
+
 	case STOP_WINDOW:
 		/*
 		we access BLOCK_SWITCHING_OFFSET-LS_TRANS (1600-448 ) delay buffer samples + 448 new timeSignal samples
@@ -580,19 +580,19 @@
 		*/
 		delayBufferSf = getScalefactorOfShortVectorStride(mdctDelayBuffer+LS_TRANS,BLOCK_SWITCHING_OFFSET-LS_TRANS,1);
 		timeSignalSf  = getScalefactorOfShortVectorStride(timeSignal,2*FRAME_LEN_LONG-BLOCK_SWITCHING_OFFSET,chIncrement);
-		minSf = min(delayBufferSf,timeSignalSf);    
+		minSf = min(delayBufferSf,timeSignalSf);
 		minSf = min(minSf,13);
-		
+
 		outData0 = realOut + FRAME_LEN_LONG/2;
 		dctIn1 = mdctDelayBuffer + FRAME_LEN_LONG - 1;
 		for(i=0;i<LS_TRANS;i++){
-			*outData0++ = -(*dctIn1--) << (15 - 2 + minSf);    
+			*outData0++ = -(*dctIn1--) << (15 - 2 + minSf);
 		}
-		
+
 		/* add windows and pre add for mdct to last buffer*/
 		dctIn0 = mdctDelayBuffer + LS_TRANS;
 		dctIn1 = mdctDelayBuffer + FRAME_LEN_LONG - 1 - LS_TRANS;
-		outData0 = realOut + FRAME_LEN_LONG/2 + LS_TRANS; 
+		outData0 = realOut + FRAME_LEN_LONG/2 + LS_TRANS;
 		winPtr = (int *)ShortWindowSine;
 		for(i=0;i<FRAME_LEN_SHORT/2;i++){
 			timeSignalSample = (*dctIn0++) << minSf;
@@ -600,44 +600,44 @@
 			timeSignalSample= (*dctIn1--) << minSf;
 			ws2 = timeSignalSample * (*winPtr & 0xffff);
 			winPtr++;
-			*outData0++ = (ws1 >> 2) - (ws2 >> 2);  /* shift 2 to avoid overflow next */

+			*outData0++ = (ws1 >> 2) - (ws2 >> 2);  /* shift 2 to avoid overflow next */
 		}
-		
+
 		shiftMdctDelayBuffer(mdctDelayBuffer,timeSignal,chIncrement);
-		
+
 		/* add windows and pre add for mdct to new buffer*/
 		dctIn0 = mdctDelayBuffer;
 		dctIn1 = mdctDelayBuffer + FRAME_LEN_LONG - 1;
-		outData0 = realOut + FRAME_LEN_LONG/2 - 1; 
+		outData0 = realOut + FRAME_LEN_LONG/2 - 1;
 		winPtr = (int *)LongWindowKBD;
 		for(i=0;i<FRAME_LEN_LONG/2;i++){
 			timeSignalSample= (*dctIn0++) << minSf;
 			ws1 = timeSignalSample *(*winPtr & 0xffff);
 			timeSignalSample= (*dctIn1--) << minSf;
 			ws2 = timeSignalSample * (*winPtr >> 16);
-			*outData0-- =  -((ws1 >> 2) + (ws2 >> 2));  /* shift 2 to avoid overflow next */

-			winPtr++;

+			*outData0-- =  -((ws1 >> 2) + (ws2 >> 2));  /* shift 2 to avoid overflow next */
+			winPtr++;
 		}
-		
+
 		Mdct_Long(realOut);
 		minSf = 14 - minSf;
 		*mdctScale= minSf; /* update scale factor */
 		break;
-		
+
 	case SHORT_WINDOW:
 		/*
 		we access BLOCK_SWITCHING_OFFSET (1600 ) delay buffer samples + no new timeSignal samples
 		and get the biggest scale factor for next calculate more precise
-		*/		
+		*/
 		minSf = getScalefactorOfShortVectorStride(mdctDelayBuffer+TRANSFORM_OFFSET_SHORT,9*FRAME_LEN_SHORT,1);
 		minSf = min(minSf,10);
-		
-		
+
+
 		for(w=0;w<TRANS_FAC;w++){
 			dctIn0 = mdctDelayBuffer+w*FRAME_LEN_SHORT+TRANSFORM_OFFSET_SHORT;
 			dctIn1 = mdctDelayBuffer+w*FRAME_LEN_SHORT+TRANSFORM_OFFSET_SHORT + FRAME_LEN_SHORT-1;
-			outData0 = realOut + FRAME_LEN_SHORT/2; 
-			outData1 = realOut + FRAME_LEN_SHORT/2 - 1; 
+			outData0 = realOut + FRAME_LEN_SHORT/2;
+			outData1 = realOut + FRAME_LEN_SHORT/2 - 1;
 
 			winPtr = (int *)ShortWindowSine;
 			for(i=0;i<FRAME_LEN_SHORT/2;i++){
@@ -645,26 +645,26 @@
 				ws1 = timeSignalSample * (*winPtr >> 16);
 				timeSignalSample= *dctIn1 << minSf;
 				ws2 = timeSignalSample * (*winPtr & 0xffff);
-				*outData0++ = (ws1 >> 2) - (ws2 >> 2);  /* shift 2 to avoid overflow next */

-				
+				*outData0++ = (ws1 >> 2) - (ws2 >> 2);  /* shift 2 to avoid overflow next */
+
 				timeSignalSample= *(dctIn0 + FRAME_LEN_SHORT) << minSf;
 				ws1 = timeSignalSample * (*winPtr & 0xffff);
 				timeSignalSample= *(dctIn1 + FRAME_LEN_SHORT) << minSf;
 				ws2 = timeSignalSample * (*winPtr >> 16);
-				*outData1-- =  -((ws1 >> 2) + (ws2 >> 2));  /* shift 2 to avoid overflow next */

-

-				winPtr++;

-				dctIn0++;

-				dctIn1--;

+				*outData1-- =  -((ws1 >> 2) + (ws2 >> 2));  /* shift 2 to avoid overflow next */
+
+				winPtr++;
+				dctIn0++;
+				dctIn1--;
 			}
 
 			Mdct_Short(realOut);
 			realOut += FRAME_LEN_SHORT;
 		}
-		

+
 		minSf = 11 - minSf;
 		*mdctScale = minSf; /* update scale factor */
-		
+
 		shiftMdctDelayBuffer(mdctDelayBuffer,timeSignal,chIncrement);
 		break;
   }
diff --git a/media/libstagefright/codecs/amrwbenc/Android.mk b/media/libstagefright/codecs/amrwbenc/Android.mk
index 4293287..7141cbaa 100644
--- a/media/libstagefright/codecs/amrwbenc/Android.mk
+++ b/media/libstagefright/codecs/amrwbenc/Android.mk
@@ -3,7 +3,7 @@
 include frameworks/base/media/libstagefright/codecs/common/Config.mk
 
 LOCAL_PRELINK_MODULE := false
- 	
+
 LOCAL_SRC_FILES := \
 	AMRWBEncoder.cpp \
 	src/autocorr.c \
@@ -91,7 +91,7 @@
 
 LOCAL_ARM_MODE := arm
 
-LOCAL_STATIC_LIBRARIES := 
+LOCAL_STATIC_LIBRARIES :=
 
 LOCAL_SHARED_LIBRARIES :=
 
diff --git a/media/libstagefright/codecs/amrwbenc/SampleCode/AMRWB_E_SAMPLE.c b/media/libstagefright/codecs/amrwbenc/SampleCode/AMRWB_E_SAMPLE.c
index 792d3cc..c094d41 100644
--- a/media/libstagefright/codecs/amrwbenc/SampleCode/AMRWB_E_SAMPLE.c
+++ b/media/libstagefright/codecs/amrwbenc/SampleCode/AMRWB_E_SAMPLE.c
@@ -1,364 +1,364 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-#ifdef LINUX

-#include <dlfcn.h>

-#endif

-

-#include      <stdio.h>

-#include      <stdlib.h>

-#include      <time.h>

-#include      "voAMRWB.h"

-#include      "cmnMemory.h"

-

-#define VOAMRWB_RFC3267_HEADER_INFO "#!AMR-WB\n"

-

-#define  INPUT_SIZE   640

-#define  OUTPUT_SIZE  1024

-unsigned char  InputBuf[INPUT_SIZE];

-unsigned char  OutputBuf[OUTPUT_SIZE];

-

-void usage (void) {

-	printf ("AMR_WB Encoder HELP   Displays this text\n");

-	printf ("\n");

-	printf ("Usage:\n");

-	printf ("AMRWBEnc [options] Input_file output_file \n");

-	printf ("\n");

-	printf ("Options +M* +F* +DTX \n");

-	printf ("Support \n");

-	printf ("Options +M* for seting compression bitrate mode, default is 23.85kbps\n");

-	printf (" +M0 = 6.6kbps \n");

-	printf (" +M1 = 8.85kbps \n");

-	printf (" +M2 = 12.65kbps \n");

-	printf (" +M3 = 14.25kbps \n");

-	printf (" +M4 = 15.58kbps \n");

-	printf (" +M5 = 18.25kbps \n");

-	printf (" +M6 = 19.85kbps \n");

-	printf (" +M7 = 23.05kbps \n");

-	printf (" +M8 = 23.85kbps \n");

-	printf ("\n");

-	printf ("Options +F* for setting output frame Type, default is RFC3267 \n");

-	printf ("+F0 for AMR_WB Defualt bit extern short data frame type \n");

-	printf ("+F1 for AMR_WB_ITU bit extern short data frame type \n");

-	printf ("+F2 for RFC3267\n ");

-	printf ("\n");

-	printf ("Options +DTX enable DTX mode, default is disable.\n");

-	printf ("File names, input raw PCM data, and output is AMR_WB bit-stream file.\n");

-	printf ("\n");

-}

-

-int  GetNextBuf(FILE* inFile,unsigned char* dst,int size)

-{

-	int size2 = (int)fread(dst, sizeof(signed char), size,inFile);

-	return size2;

-}

-

-typedef int (VO_API * VOGETAUDIOENCAPI) (VO_AUDIO_CODECAPI * pEncHandle);

-

-int encode(

-		   int mode, 

-		   short   allow_dtx,

-		   VOAMRWBFRAMETYPE frameType,

-		   const char* srcfile, 

-		   const char* dstfile

-		   )

-{

-	int			ret = 0;

-	int         returnCode;

-	FILE		*fsrc = NULL;

-	FILE		*fdst = NULL;

-	int         framenum = 0;

-	int         eofFile = 0;

-	int         size1 = 0;

-	int         Relens;

-

-	VO_AUDIO_CODECAPI       AudioAPI;

-	VO_MEM_OPERATOR         moper;

-	VO_CODEC_INIT_USERDATA  useData;

-	VO_HANDLE               hCodec;

-	VO_CODECBUFFER          inData;

-	VO_CODECBUFFER          outData;

-	VO_AUDIO_OUTPUTINFO     outFormat;

-

-	unsigned char *inBuf = InputBuf;

-	unsigned char *outBuf = OutputBuf;

-

-

-#ifdef LINUX

-	void  *handle = NULL;

-	void  *pfunc;

-	VOGETAUDIOENCAPI pGetAPI;

-#endif

-

-	clock_t   start, finish;

-	double    duration = 0.0;

-

-	if ((fsrc = fopen (srcfile, "rb")) == NULL)

-	{

-		ret = -1;

-		goto safe_exit;

-	}

-

-	if ((fdst = fopen (dstfile, "wb")) == NULL)

-	{

-		ret = -1;

-		goto safe_exit;

-	}

-

-	moper.Alloc = cmnMemAlloc;

-	moper.Copy = cmnMemCopy;

-	moper.Free = cmnMemFree;

-	moper.Set = cmnMemSet;

-	moper.Check = cmnMemCheck;

-

-	useData.memflag = VO_IMF_USERMEMOPERATOR;

-	useData.memData = (VO_PTR)(&moper);

-

-#ifdef LINUX

-	handle = dlopen("/data/local/tmp/voAMRWBEnc.so", RTLD_NOW);

-	if(handle == 0)

-	{

-		printf("open dll error......");

-		return -1;

-	}

-

-	pfunc = dlsym(handle, "voGetAMRWBEncAPI");	

-	if(pfunc == 0)

-	{

-		printf("open function error......");

-		return -1;

-	}

-

-	pGetAPI = (VOGETAUDIOENCAPI)pfunc;

-

-	returnCode  = pGetAPI(&AudioAPI);

-	if(returnCode)

-	{

-		printf("get APIs error......");

-		return -1;

-	}

-#else

-	ret = voGetAMRWBEncAPI(&AudioAPI);

-	if(ret)

-	{

-		ret = -1;

-		printf("get APIs error......");

-		goto safe_exit;

-	}

-#endif 

-

-	//#######################################   Init Encoding Section   #########################################

-	ret = AudioAPI.Init(&hCodec, VO_AUDIO_CodingAMRWB, &useData);

-

-	if(ret)

-	{

-		ret = -1;

-		printf("APIs init error......");

-		goto safe_exit;

-	}

-

-	Relens = GetNextBuf(fsrc,InputBuf,INPUT_SIZE);

-	if(Relens!=INPUT_SIZE && !feof(fsrc))

-	{

-		ret = -1; //Invalid magic number

-		printf("get next buffer error......");

-		goto safe_exit;

-	}

-

-	//###################################### set encode Mode ##################################################

-	ret = AudioAPI.SetParam(hCodec, VO_PID_AMRWB_FRAMETYPE, &frameType);

-	ret = AudioAPI.SetParam(hCodec, VO_PID_AMRWB_MODE, &mode);

-	ret = AudioAPI.SetParam(hCodec, VO_PID_AMRWB_DTX, &allow_dtx);

-

-	if(frameType == VOAMRWB_RFC3267)

-	{

-		/* write RFC3267 Header info to indicate single channel AMR file storage format */

-		size1 = (int)strlen(VOAMRWB_RFC3267_HEADER_INFO);

-		memcpy(outBuf, VOAMRWB_RFC3267_HEADER_INFO, size1);

-		outBuf += size1;

-	}

-

-	//#######################################   Encoding Section   #########################################

-	printf(" \n ---------------- Running -------------------------\n ");

-

-	do{

-		inData.Buffer = (unsigned char *)inBuf;

-		inData.Length = Relens;

-		outData.Buffer = outBuf;

-

-		start = clock();

-

-		/* decode one amr block */

-		returnCode = AudioAPI.SetInputData(hCodec,&inData);

-

-		do {

-			returnCode = AudioAPI.GetOutputData(hCodec,&outData, &outFormat);

-			if(returnCode == 0)

-			{

-				framenum++;

-				printf(" Frames processed: %hd\r", framenum);

-				if(framenum == 1)

-				{

-					fwrite(OutputBuf, 1, outData.Length + size1, fdst);

-					fflush(fdst);	

-				}

-				else

-				{

-					fwrite(outData.Buffer, 1, outData.Length, fdst);

-					fflush(fdst);

-				}

-			}

-			else if(returnCode == VO_ERR_LICENSE_ERROR)

-			{

-		        printf("Encoder time reach upper limit......");

-		        goto safe_exit;

-			}

-		} while(returnCode != VO_ERR_INPUT_BUFFER_SMALL);

-

-		finish = clock();

-		duration += finish - start;

-

-		if (!eofFile) {

-			Relens = GetNextBuf(fsrc, InputBuf, INPUT_SIZE);

-			inBuf = InputBuf;

-			if (feof(fsrc) && Relens == 0)

-				eofFile = 1;

-		}

-	} while (!eofFile && returnCode);

-	//#######################################   End Encoding Section   #########################################

-

-safe_exit:

-	returnCode = AudioAPI.Uninit(hCodec);

-

-	printf( "\n%2.5f seconds\n", (double)duration/CLOCKS_PER_SEC);

-

-	if (fsrc)

-		fclose(fsrc);

-	if (fdst)

-		fclose(fdst);

-

-#ifdef LINUX

-	dlclose(handle);

-#endif

-

-	return ret;

-}

-

-int main(int argc, char **argv)  // for gcc compiler;

-{

-	int     mode, r;

-	int     arg, filename=0;

-	char    *inFileName = NULL;

-	char    *outFileName = NULL;

-	short   allow_dtx;

-	VOAMRWBFRAMETYPE frameType;

-

-	printf("\n");

-	printf("************************Adaptive Multi-Rate Wide Band Encoder (AMR-WB)*******************************\n");

-	printf("***********************************DEFINITIONS:*******************************************************\n");

-	printf("AMR-WB encoder scheme is based on the principle of Algebraic Code Excited Linear Prediction algorithm\n");

-	printf("The AMR-WB encoder compression MONO liner PCM speech input data at 16kHz sampling rate\n");

-	printf("to one of nine data rate modes-6.60, 8.85, 12.65, 14.25, 15.85, 18.25, 19.25, 23.05 and 23.85kbps.\n");

-	printf("The encoder supports output format AMRWB ITU, AMRWB RFC3267.\n");

-	printf("\n");

-

-	/*Encoder Default setting */

-	mode = VOAMRWB_MD2385;

-	allow_dtx = 0;

-	frameType = VOAMRWB_RFC3267;

-

-	if(argc < 3){

-		usage();

-		return 0;

-	}else{

-		for (arg = 1; arg < argc; arg++) {

-			if (argv [arg] [0] == '+') {

-				if(argv[arg][1] == 'M')

-				{

-					switch(argv[arg][2])

-					{

-					case '0': mode = VOAMRWB_MD66;

-						break;

-					case '1': mode = VOAMRWB_MD885;

-						break;

-					case '2': mode = VOAMRWB_MD1265;

-						break;

-					case '3': mode = VOAMRWB_MD1425;

-						break;

-					case '4': mode = VOAMRWB_MD1585;

-						break;

-					case '5': mode = VOAMRWB_MD1825;

-						break;

-					case '6': mode = VOAMRWB_MD1985;

-						break;

-					case '7': mode = VOAMRWB_MD2305;

-						break;

-					case '8': mode = VOAMRWB_MD2385;

-						break;

-					default:

-						usage();

-						printf ("Invalid parameter '%s'.\n", argv [arg]);

-						break;

-					}

-				}else if(argv[arg][1] == 'F')

-				{

-					switch(argv[arg][2])

-					{

-					case '0': frameType = VOAMRWB_DEFAULT;

-						break;

-					case '1': frameType = VOAMRWB_ITU;

-						break;

-					case '2': frameType = VOAMRWB_RFC3267 ;

-						break; 

-					default:

-						usage();

-						printf ("Invalid parameter '%s'.\n", argv [arg]);

-						break;

-

-

-					}

-				}else if(strcmp (argv[arg], "+DTX") == 0)

-				{

-					allow_dtx = 1;

-				}

-

-			} else {

-				switch (filename) {

-						case 0: 

-							inFileName  = argv[arg];

-							break;

-						case 1: 

-							outFileName = argv[arg]; 

-							break;

-						default:

-							usage ();

-							fprintf (stderr, "Invalid parameter '%s'.\n", argv [arg]);

-							return 0;

-				}

-				filename++;

-			}

-		}

-	}

-

-	r = encode(mode, allow_dtx, frameType, inFileName, outFileName);

-	if(r)

-	{

-		fprintf(stderr, "error: %d\n", r);

-	}

-	return r;

-}

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+#ifdef LINUX
+#include <dlfcn.h>
+#endif
+
+#include      <stdio.h>
+#include      <stdlib.h>
+#include      <time.h>
+#include      "voAMRWB.h"
+#include      "cmnMemory.h"
+
+#define VOAMRWB_RFC3267_HEADER_INFO "#!AMR-WB\n"
+
+#define  INPUT_SIZE   640
+#define  OUTPUT_SIZE  1024
+unsigned char  InputBuf[INPUT_SIZE];
+unsigned char  OutputBuf[OUTPUT_SIZE];
+
+void usage (void) {
+	printf ("AMR_WB Encoder HELP   Displays this text\n");
+	printf ("\n");
+	printf ("Usage:\n");
+	printf ("AMRWBEnc [options] Input_file output_file \n");
+	printf ("\n");
+	printf ("Options +M* +F* +DTX \n");
+	printf ("Support \n");
+	printf ("Options +M* for seting compression bitrate mode, default is 23.85kbps\n");
+	printf (" +M0 = 6.6kbps \n");
+	printf (" +M1 = 8.85kbps \n");
+	printf (" +M2 = 12.65kbps \n");
+	printf (" +M3 = 14.25kbps \n");
+	printf (" +M4 = 15.58kbps \n");
+	printf (" +M5 = 18.25kbps \n");
+	printf (" +M6 = 19.85kbps \n");
+	printf (" +M7 = 23.05kbps \n");
+	printf (" +M8 = 23.85kbps \n");
+	printf ("\n");
+	printf ("Options +F* for setting output frame Type, default is RFC3267 \n");
+	printf ("+F0 for AMR_WB Defualt bit extern short data frame type \n");
+	printf ("+F1 for AMR_WB_ITU bit extern short data frame type \n");
+	printf ("+F2 for RFC3267\n ");
+	printf ("\n");
+	printf ("Options +DTX enable DTX mode, default is disable.\n");
+	printf ("File names, input raw PCM data, and output is AMR_WB bit-stream file.\n");
+	printf ("\n");
+}
+
+int  GetNextBuf(FILE* inFile,unsigned char* dst,int size)
+{
+	int size2 = (int)fread(dst, sizeof(signed char), size,inFile);
+	return size2;
+}
+
+typedef int (VO_API * VOGETAUDIOENCAPI) (VO_AUDIO_CODECAPI * pEncHandle);
+
+int encode(
+		   int mode,
+		   short   allow_dtx,
+		   VOAMRWBFRAMETYPE frameType,
+		   const char* srcfile,
+		   const char* dstfile
+		   )
+{
+	int			ret = 0;
+	int         returnCode;
+	FILE		*fsrc = NULL;
+	FILE		*fdst = NULL;
+	int         framenum = 0;
+	int         eofFile = 0;
+	int         size1 = 0;
+	int         Relens;
+
+	VO_AUDIO_CODECAPI       AudioAPI;
+	VO_MEM_OPERATOR         moper;
+	VO_CODEC_INIT_USERDATA  useData;
+	VO_HANDLE               hCodec;
+	VO_CODECBUFFER          inData;
+	VO_CODECBUFFER          outData;
+	VO_AUDIO_OUTPUTINFO     outFormat;
+
+	unsigned char *inBuf = InputBuf;
+	unsigned char *outBuf = OutputBuf;
+
+
+#ifdef LINUX
+	void  *handle = NULL;
+	void  *pfunc;
+	VOGETAUDIOENCAPI pGetAPI;
+#endif
+
+	clock_t   start, finish;
+	double    duration = 0.0;
+
+	if ((fsrc = fopen (srcfile, "rb")) == NULL)
+	{
+		ret = -1;
+		goto safe_exit;
+	}
+
+	if ((fdst = fopen (dstfile, "wb")) == NULL)
+	{
+		ret = -1;
+		goto safe_exit;
+	}
+
+	moper.Alloc = cmnMemAlloc;
+	moper.Copy = cmnMemCopy;
+	moper.Free = cmnMemFree;
+	moper.Set = cmnMemSet;
+	moper.Check = cmnMemCheck;
+
+	useData.memflag = VO_IMF_USERMEMOPERATOR;
+	useData.memData = (VO_PTR)(&moper);
+
+#ifdef LINUX
+	handle = dlopen("/data/local/tmp/voAMRWBEnc.so", RTLD_NOW);
+	if(handle == 0)
+	{
+		printf("open dll error......");
+		return -1;
+	}
+
+	pfunc = dlsym(handle, "voGetAMRWBEncAPI");
+	if(pfunc == 0)
+	{
+		printf("open function error......");
+		return -1;
+	}
+
+	pGetAPI = (VOGETAUDIOENCAPI)pfunc;
+
+	returnCode  = pGetAPI(&AudioAPI);
+	if(returnCode)
+	{
+		printf("get APIs error......");
+		return -1;
+	}
+#else
+	ret = voGetAMRWBEncAPI(&AudioAPI);
+	if(ret)
+	{
+		ret = -1;
+		printf("get APIs error......");
+		goto safe_exit;
+	}
+#endif
+
+	//#######################################   Init Encoding Section   #########################################
+	ret = AudioAPI.Init(&hCodec, VO_AUDIO_CodingAMRWB, &useData);
+
+	if(ret)
+	{
+		ret = -1;
+		printf("APIs init error......");
+		goto safe_exit;
+	}
+
+	Relens = GetNextBuf(fsrc,InputBuf,INPUT_SIZE);
+	if(Relens!=INPUT_SIZE && !feof(fsrc))
+	{
+		ret = -1; //Invalid magic number
+		printf("get next buffer error......");
+		goto safe_exit;
+	}
+
+	//###################################### set encode Mode ##################################################
+	ret = AudioAPI.SetParam(hCodec, VO_PID_AMRWB_FRAMETYPE, &frameType);
+	ret = AudioAPI.SetParam(hCodec, VO_PID_AMRWB_MODE, &mode);
+	ret = AudioAPI.SetParam(hCodec, VO_PID_AMRWB_DTX, &allow_dtx);
+
+	if(frameType == VOAMRWB_RFC3267)
+	{
+		/* write RFC3267 Header info to indicate single channel AMR file storage format */
+		size1 = (int)strlen(VOAMRWB_RFC3267_HEADER_INFO);
+		memcpy(outBuf, VOAMRWB_RFC3267_HEADER_INFO, size1);
+		outBuf += size1;
+	}
+
+	//#######################################   Encoding Section   #########################################
+	printf(" \n ---------------- Running -------------------------\n ");
+
+	do{
+		inData.Buffer = (unsigned char *)inBuf;
+		inData.Length = Relens;
+		outData.Buffer = outBuf;
+
+		start = clock();
+
+		/* decode one amr block */
+		returnCode = AudioAPI.SetInputData(hCodec,&inData);
+
+		do {
+			returnCode = AudioAPI.GetOutputData(hCodec,&outData, &outFormat);
+			if(returnCode == 0)
+			{
+				framenum++;
+				printf(" Frames processed: %hd\r", framenum);
+				if(framenum == 1)
+				{
+					fwrite(OutputBuf, 1, outData.Length + size1, fdst);
+					fflush(fdst);
+				}
+				else
+				{
+					fwrite(outData.Buffer, 1, outData.Length, fdst);
+					fflush(fdst);
+				}
+			}
+			else if(returnCode == VO_ERR_LICENSE_ERROR)
+			{
+		        printf("Encoder time reach upper limit......");
+		        goto safe_exit;
+			}
+		} while(returnCode != VO_ERR_INPUT_BUFFER_SMALL);
+
+		finish = clock();
+		duration += finish - start;
+
+		if (!eofFile) {
+			Relens = GetNextBuf(fsrc, InputBuf, INPUT_SIZE);
+			inBuf = InputBuf;
+			if (feof(fsrc) && Relens == 0)
+				eofFile = 1;
+		}
+	} while (!eofFile && returnCode);
+	//#######################################   End Encoding Section   #########################################
+
+safe_exit:
+	returnCode = AudioAPI.Uninit(hCodec);
+
+	printf( "\n%2.5f seconds\n", (double)duration/CLOCKS_PER_SEC);
+
+	if (fsrc)
+		fclose(fsrc);
+	if (fdst)
+		fclose(fdst);
+
+#ifdef LINUX
+	dlclose(handle);
+#endif
+
+	return ret;
+}
+
+int main(int argc, char **argv)  // for gcc compiler;
+{
+	int     mode, r;
+	int     arg, filename=0;
+	char    *inFileName = NULL;
+	char    *outFileName = NULL;
+	short   allow_dtx;
+	VOAMRWBFRAMETYPE frameType;
+
+	printf("\n");
+	printf("************************Adaptive Multi-Rate Wide Band Encoder (AMR-WB)*******************************\n");
+	printf("***********************************DEFINITIONS:*******************************************************\n");
+	printf("AMR-WB encoder scheme is based on the principle of Algebraic Code Excited Linear Prediction algorithm\n");
+	printf("The AMR-WB encoder compression MONO liner PCM speech input data at 16kHz sampling rate\n");
+	printf("to one of nine data rate modes-6.60, 8.85, 12.65, 14.25, 15.85, 18.25, 19.25, 23.05 and 23.85kbps.\n");
+	printf("The encoder supports output format AMRWB ITU, AMRWB RFC3267.\n");
+	printf("\n");
+
+	/*Encoder Default setting */
+	mode = VOAMRWB_MD2385;
+	allow_dtx = 0;
+	frameType = VOAMRWB_RFC3267;
+
+	if(argc < 3){
+		usage();
+		return 0;
+	}else{
+		for (arg = 1; arg < argc; arg++) {
+			if (argv [arg] [0] == '+') {
+				if(argv[arg][1] == 'M')
+				{
+					switch(argv[arg][2])
+					{
+					case '0': mode = VOAMRWB_MD66;
+						break;
+					case '1': mode = VOAMRWB_MD885;
+						break;
+					case '2': mode = VOAMRWB_MD1265;
+						break;
+					case '3': mode = VOAMRWB_MD1425;
+						break;
+					case '4': mode = VOAMRWB_MD1585;
+						break;
+					case '5': mode = VOAMRWB_MD1825;
+						break;
+					case '6': mode = VOAMRWB_MD1985;
+						break;
+					case '7': mode = VOAMRWB_MD2305;
+						break;
+					case '8': mode = VOAMRWB_MD2385;
+						break;
+					default:
+						usage();
+						printf ("Invalid parameter '%s'.\n", argv [arg]);
+						break;
+					}
+				}else if(argv[arg][1] == 'F')
+				{
+					switch(argv[arg][2])
+					{
+					case '0': frameType = VOAMRWB_DEFAULT;
+						break;
+					case '1': frameType = VOAMRWB_ITU;
+						break;
+					case '2': frameType = VOAMRWB_RFC3267 ;
+						break;
+					default:
+						usage();
+						printf ("Invalid parameter '%s'.\n", argv [arg]);
+						break;
+
+
+					}
+				}else if(strcmp (argv[arg], "+DTX") == 0)
+				{
+					allow_dtx = 1;
+				}
+
+			} else {
+				switch (filename) {
+						case 0:
+							inFileName  = argv[arg];
+							break;
+						case 1:
+							outFileName = argv[arg];
+							break;
+						default:
+							usage ();
+							fprintf (stderr, "Invalid parameter '%s'.\n", argv [arg]);
+							return 0;
+				}
+				filename++;
+			}
+		}
+	}
+
+	r = encode(mode, allow_dtx, frameType, inFileName, outFileName);
+	if(r)
+	{
+		fprintf(stderr, "error: %d\n", r);
+	}
+	return r;
+}
+
diff --git a/media/libstagefright/codecs/amrwbenc/SampleCode/Android.mk b/media/libstagefright/codecs/amrwbenc/SampleCode/Android.mk
index 7edb166..149e591 100644
--- a/media/libstagefright/codecs/amrwbenc/SampleCode/Android.mk
+++ b/media/libstagefright/codecs/amrwbenc/SampleCode/Android.mk
@@ -2,15 +2,15 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES := 	AMRWB_E_SAMPLE.c
-	
+
 LOCAL_SRC_FILES += 	\
-	../../../Common/cmnMemory.c 
+	../../../Common/cmnMemory.c
 
 LOCAL_MODULE := TestvoAMRWBEnc
 
 LOCAL_ARM_MODE := arm
 
-LOCAL_STATIC_LIBRARIES := 
+LOCAL_STATIC_LIBRARIES :=
 
 LOCAL_SHARED_LIBRARIES := libvoAMRWBEnc
 
@@ -20,7 +20,7 @@
 	$(LOCAL_PATH)/../../../Include \
 
 LOCAL_CFLAGS := $(VO_CFLAGS)
-	
+
 include $(BUILD_EXECUTABLE)
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/SampleCode/eclair/Makefile b/media/libstagefright/codecs/amrwbenc/SampleCode/eclair/Makefile
index 55b876a..148b941 100644
--- a/media/libstagefright/codecs/amrwbenc/SampleCode/eclair/Makefile
+++ b/media/libstagefright/codecs/amrwbenc/SampleCode/eclair/Makefile
@@ -1,56 +1,56 @@
-#/*

-# ** Copyright 2003-2010, VisualOn, Inc.

-# **

-# ** Licensed under the Apache License, Version 2.0 (the "License");

-# ** you may not use this file except in compliance with the License.

-# ** You may obtain a copy of the License at

-# **

-# **     http://www.apache.org/licenses/LICENSE-2.0

-# **

-# ** Unless required by applicable law or agreed to in writing, software

-# ** distributed under the License is distributed on an "AS IS" BASIS,

-# ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-# ** See the License for the specific language governing permissions and

-# ** limitations under the License.

-# */

-

-# target6

-# available: pc, v4(armv4), v5(armv5), v5x(armv5 xscale), v6(armv6), v7(cortex-a8 neon)

-VOTT:= v6

-

-

-# module type

-# please specify the type of your module: lib or exe

-VOMT:= exe

-

-

-# module macros

-# please append the additional macro definitions here for your module if necessary. 

-# e.g. -DVISUALON, macro VISUALON defined for your module 

-VOMM:= #ARMV5E

-

-

-

-# please specify the name of your module

-VOTARGET:= voAMRWBEnc_Test

-

-

-# please modify here to be sure to see the g1.mk

-include ../../../../Tools/eclair.mk 

-

-# dependent libraries.

-VODEPLIBS:=-ldl

-

-

-# module source

-# please modify here to be sure to see the ms.mk which specifies all source info of your module

-include ../ms.mk

-

-

-# please specify where is the voRelease on your PC, relative path is suggested

-VORELDIR:=../

-

-

-# please modify here to be sure to see the doit.mk

-include ../../../../Tools/doit.mk 

-

+#/*
+# ** Copyright 2003-2010, VisualOn, Inc.
+# **
+# ** Licensed under the Apache License, Version 2.0 (the "License");
+# ** you may not use this file except in compliance with the License.
+# ** You may obtain a copy of the License at
+# **
+# **     http://www.apache.org/licenses/LICENSE-2.0
+# **
+# ** Unless required by applicable law or agreed to in writing, software
+# ** distributed under the License is distributed on an "AS IS" BASIS,
+# ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# ** See the License for the specific language governing permissions and
+# ** limitations under the License.
+# */
+
+# target6
+# available: pc, v4(armv4), v5(armv5), v5x(armv5 xscale), v6(armv6), v7(cortex-a8 neon)
+VOTT:= v6
+
+
+# module type
+# please specify the type of your module: lib or exe
+VOMT:= exe
+
+
+# module macros
+# please append the additional macro definitions here for your module if necessary.
+# e.g. -DVISUALON, macro VISUALON defined for your module
+VOMM:= #ARMV5E
+
+
+
+# please specify the name of your module
+VOTARGET:= voAMRWBEnc_Test
+
+
+# please modify here to be sure to see the g1.mk
+include ../../../../Tools/eclair.mk
+
+# dependent libraries.
+VODEPLIBS:=-ldl
+
+
+# module source
+# please modify here to be sure to see the ms.mk which specifies all source info of your module
+include ../ms.mk
+
+
+# please specify where is the voRelease on your PC, relative path is suggested
+VORELDIR:=../
+
+
+# please modify here to be sure to see the doit.mk
+include ../../../../Tools/doit.mk
+
diff --git a/media/libstagefright/codecs/amrwbenc/SampleCode/ms.mk b/media/libstagefright/codecs/amrwbenc/SampleCode/ms.mk
index 74e8913..a550cee 100644
--- a/media/libstagefright/codecs/amrwbenc/SampleCode/ms.mk
+++ b/media/libstagefright/codecs/amrwbenc/SampleCode/ms.mk
@@ -1,24 +1,24 @@
-#/*

-# ** Copyright 2003-2010, VisualOn, Inc.

-# **

-# ** Licensed under the Apache License, Version 2.0 (the "License");

-# ** you may not use this file except in compliance with the License.

-# ** You may obtain a copy of the License at

-# **

-# **     http://www.apache.org/licenses/LICENSE-2.0

-# **

-# ** Unless required by applicable law or agreed to in writing, software

-# ** distributed under the License is distributed on an "AS IS" BASIS,

-# ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-# ** See the License for the specific language governing permissions and

-# ** limitations under the License.

-# */

-# please list all objects needed by your target here

-OBJS:=AMRWB_E_SAMPLE.o cmnMemory.o

-			

-# please list all directories that all source files relative with your module(.h .c .cpp) locate 

-VOSRCDIR:=../ \

-          ../../../../Common \

-	  ../../../../Include

-					

-				

+#/*
+# ** Copyright 2003-2010, VisualOn, Inc.
+# **
+# ** Licensed under the Apache License, Version 2.0 (the "License");
+# ** you may not use this file except in compliance with the License.
+# ** You may obtain a copy of the License at
+# **
+# **     http://www.apache.org/licenses/LICENSE-2.0
+# **
+# ** Unless required by applicable law or agreed to in writing, software
+# ** distributed under the License is distributed on an "AS IS" BASIS,
+# ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# ** See the License for the specific language governing permissions and
+# ** limitations under the License.
+# */
+# please list all objects needed by your target here
+OBJS:=AMRWB_E_SAMPLE.o cmnMemory.o
+
+# please list all directories that all source files relative with your module(.h .c .cpp) locate
+VOSRCDIR:=../ \
+          ../../../../Common \
+	  ../../../../Include
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/build/eclair/ARMV5E/Makefile b/media/libstagefright/codecs/amrwbenc/build/eclair/ARMV5E/Makefile
index 58fda29..67ec74e 100644
--- a/media/libstagefright/codecs/amrwbenc/build/eclair/ARMV5E/Makefile
+++ b/media/libstagefright/codecs/amrwbenc/build/eclair/ARMV5E/Makefile
@@ -1,53 +1,53 @@
-#/*

-# ** Copyright 2003-2010, VisualOn, Inc.

-# **

-# ** Licensed under the Apache License, Version 2.0 (the "License");

-# ** you may not use this file except in compliance with the License.

-# ** You may obtain a copy of the License at

-# **

-# **     http://www.apache.org/licenses/LICENSE-2.0

-# **

-# ** Unless required by applicable law or agreed to in writing, software

-# ** distributed under the License is distributed on an "AS IS" BASIS,

-# ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-# ** See the License for the specific language governing permissions and

-# ** limitations under the License.

-# */

-

-# target type

-# available: pc, v4(armv4), v5(armv5), v5x(armv5 xscale), v6(armv6), v7(cortex-a8 neon)

-VOTT:= v5

-

-

-# module type

-# please specify the type of your module: lib or exe

-VOMT:= lib

-

-

-# module macros

-# please append the additional macro definitions here for your module if necessary. 

-ifeq ($(VOTT), v5)

-VOMM:=-DARM -DASM_OPT

-endif

-

-# please specify the name of your module

-VOTARGET:= libvoAMRWBEncv5

-

-

-# please modify here to be sure to see the g1.mk

-include ../../../../../Tools/eclair.mk 

-

-# dependent libraries.

-VODEPLIBS:=-ldl -lstdc++ -lcutils

-

-# module source

-# please modify here to be sure to see the ms.mk which specifies all source info of your module

-include ../ms.mk

-

-

-# please specify where is the voRelease on your PC, relative path is suggested

-VORELDIR:=../../../../../../Release

-

-# please modify here to be sure to see the doit.mk

-include ../../../../../Tools/doit.mk 

-

+#/*
+# ** Copyright 2003-2010, VisualOn, Inc.
+# **
+# ** Licensed under the Apache License, Version 2.0 (the "License");
+# ** you may not use this file except in compliance with the License.
+# ** You may obtain a copy of the License at
+# **
+# **     http://www.apache.org/licenses/LICENSE-2.0
+# **
+# ** Unless required by applicable law or agreed to in writing, software
+# ** distributed under the License is distributed on an "AS IS" BASIS,
+# ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# ** See the License for the specific language governing permissions and
+# ** limitations under the License.
+# */
+
+# target type
+# available: pc, v4(armv4), v5(armv5), v5x(armv5 xscale), v6(armv6), v7(cortex-a8 neon)
+VOTT:= v5
+
+
+# module type
+# please specify the type of your module: lib or exe
+VOMT:= lib
+
+
+# module macros
+# please append the additional macro definitions here for your module if necessary.
+ifeq ($(VOTT), v5)
+VOMM:=-DARM -DASM_OPT
+endif
+
+# please specify the name of your module
+VOTARGET:= libvoAMRWBEncv5
+
+
+# please modify here to be sure to see the g1.mk
+include ../../../../../Tools/eclair.mk
+
+# dependent libraries.
+VODEPLIBS:=-ldl -lstdc++ -lcutils
+
+# module source
+# please modify here to be sure to see the ms.mk which specifies all source info of your module
+include ../ms.mk
+
+
+# please specify where is the voRelease on your PC, relative path is suggested
+VORELDIR:=../../../../../../Release
+
+# please modify here to be sure to see the doit.mk
+include ../../../../../Tools/doit.mk
+
diff --git a/media/libstagefright/codecs/amrwbenc/build/eclair/ARMV7/Makefile b/media/libstagefright/codecs/amrwbenc/build/eclair/ARMV7/Makefile
index 5686411..9a036a5 100644
--- a/media/libstagefright/codecs/amrwbenc/build/eclair/ARMV7/Makefile
+++ b/media/libstagefright/codecs/amrwbenc/build/eclair/ARMV7/Makefile
@@ -1,53 +1,53 @@
-#/*

-# ** Copyright 2003-2010, VisualOn, Inc.

-# **

-# ** Licensed under the Apache License, Version 2.0 (the "License");

-# ** you may not use this file except in compliance with the License.

-# ** You may obtain a copy of the License at

-# **

-# **     http://www.apache.org/licenses/LICENSE-2.0

-# **

-# ** Unless required by applicable law or agreed to in writing, software

-# ** distributed under the License is distributed on an "AS IS" BASIS,

-# ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-# ** See the License for the specific language governing permissions and

-# ** limitations under the License.

-# */

-

-# target type

-# available: pc, v4(armv4), v5(armv5), v5x(armv5 xscale), v6(armv6), v7(cortex-a8 neon)

-VOTT:= v7

-

-

-# module type

-# please specify the type of your module: lib or exe

-VOMT:= lib

-

-

-# module macros

-# please append the additional macro definitions here for your module if necessary. 

-ifeq ($(VOTT), v7)

-VOMM:=-DARM -DARMV7 -DASM_OPT

-endif

-

-# please specify the name of your module

-VOTARGET:= libvoAMRWBEncv7

-

-

-# please modify here to be sure to see the g1.mk

-include ../../../../../Tools/eclair.mk 

-

-# dependent libraries.

-VODEPLIBS:=-ldl -lstdc++ -lcutils

-

-# module source

-# please modify here to be sure to see the ms.mk which specifies all source info of your module

-include ../ms.mk

-

-

-# please specify where is the voRelease on your PC, relative path is suggested

-VORELDIR:=../../../../../../Release

-

-# please modify here to be sure to see the doit.mk

-include ../../../../../Tools/doit.mk 

-

+#/*
+# ** Copyright 2003-2010, VisualOn, Inc.
+# **
+# ** Licensed under the Apache License, Version 2.0 (the "License");
+# ** you may not use this file except in compliance with the License.
+# ** You may obtain a copy of the License at
+# **
+# **     http://www.apache.org/licenses/LICENSE-2.0
+# **
+# ** Unless required by applicable law or agreed to in writing, software
+# ** distributed under the License is distributed on an "AS IS" BASIS,
+# ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# ** See the License for the specific language governing permissions and
+# ** limitations under the License.
+# */
+
+# target type
+# available: pc, v4(armv4), v5(armv5), v5x(armv5 xscale), v6(armv6), v7(cortex-a8 neon)
+VOTT:= v7
+
+
+# module type
+# please specify the type of your module: lib or exe
+VOMT:= lib
+
+
+# module macros
+# please append the additional macro definitions here for your module if necessary.
+ifeq ($(VOTT), v7)
+VOMM:=-DARM -DARMV7 -DASM_OPT
+endif
+
+# please specify the name of your module
+VOTARGET:= libvoAMRWBEncv7
+
+
+# please modify here to be sure to see the g1.mk
+include ../../../../../Tools/eclair.mk
+
+# dependent libraries.
+VODEPLIBS:=-ldl -lstdc++ -lcutils
+
+# module source
+# please modify here to be sure to see the ms.mk which specifies all source info of your module
+include ../ms.mk
+
+
+# please specify where is the voRelease on your PC, relative path is suggested
+VORELDIR:=../../../../../../Release
+
+# please modify here to be sure to see the doit.mk
+include ../../../../../Tools/doit.mk
+
diff --git a/media/libstagefright/codecs/amrwbenc/build/eclair/makefile b/media/libstagefright/codecs/amrwbenc/build/eclair/makefile
index 3473a1a..34981fb 100644
--- a/media/libstagefright/codecs/amrwbenc/build/eclair/makefile
+++ b/media/libstagefright/codecs/amrwbenc/build/eclair/makefile
@@ -15,7 +15,7 @@
 # */
 # Just acting as Father Makefile of Modules
 # please keep the name 'makefile' unchanged
- 
+
 # Module Subdirs
 VOMSD:=$(dir $(shell find . -name 'Makefile'))
 
diff --git a/media/libstagefright/codecs/amrwbenc/build/eclair/ms.mk b/media/libstagefright/codecs/amrwbenc/build/eclair/ms.mk
index bd6620c..942ec9a 100644
--- a/media/libstagefright/codecs/amrwbenc/build/eclair/ms.mk
+++ b/media/libstagefright/codecs/amrwbenc/build/eclair/ms.mk
@@ -1,43 +1,43 @@
-#/*

-# ** Copyright 2003-2010, VisualOn, Inc.

-# **

-# ** Licensed under the Apache License, Version 2.0 (the "License");

-# ** you may not use this file except in compliance with the License.

-# ** You may obtain a copy of the License at

-# **

-# **     http://www.apache.org/licenses/LICENSE-2.0

-# **

-# ** Unless required by applicable law or agreed to in writing, software

-# ** distributed under the License is distributed on an "AS IS" BASIS,

-# ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-# ** See the License for the specific language governing permissions and

-# ** limitations under the License.

-# */

-# please list all directories that all source files relative with your module(.h .c .cpp) locate 

-VOSRCDIR:=../../../inc \

-          ../../../src \

-	  ../../../../../Include 

-

-# please list all objects needed by your target here

-OBJS:= autocorr.o az_isp.o bits.o c2t64fx.o c4t64fx.o convolve.o cor_h_x.o decim54.o \

-       deemph.o dtx.o g_pitch.o gpclip.o homing.o hp400.o hp50.o hp6k.o hp_wsp.o \

-       int_lpc.o isp_az.o isp_isf.o lag_wind.o levinson.o log2.o lp_dec2.o math_op.o mem_align.o \

-       oper_32b.o p_med_ol.o pit_shrp.o pitch_f4.o pred_lt4.o preemph.o q_gain2.o q_pulse.o \

-       qisf_ns.o qpisf_2s.o random.o residu.o scale.o stream.o syn_filt.o updt_tar.o util.o \

-       voAMRWBEnc.o voicefac.o wb_vad.o weight_a.o

-			

-

-ifeq ($(VOTT), v5)

-OBJS += cor_h_vec_opt.o Deemph_32_opt.o Dot_p_opt.o Filt_6k_7k_opt.o residu_asm_opt.o \

-       scale_sig_opt.o Syn_filt_32_opt.o syn_filt_opt.o pred_lt4_1_opt.o convolve_opt.o \

-       Norm_Corr_opt.o

-VOSRCDIR+= ../../../src/asm/ARMV5E

-endif

-

-ifeq ($(VOTT), v7)

-OBJS+= cor_h_vec_neon.o Deemph_32_neon.o Dot_p_neon.o Filt_6k_7k_neon.o residu_asm_neon.o \

-       scale_sig_neon.o Syn_filt_32_neon.o syn_filt_neon.o pred_lt4_1_neon.o convolve_neon.o \

-       Norm_Corr_neon.o

-VOSRCDIR+= ../../../src/asm/ARMV7

-endif

-

+#/*
+# ** Copyright 2003-2010, VisualOn, Inc.
+# **
+# ** Licensed under the Apache License, Version 2.0 (the "License");
+# ** you may not use this file except in compliance with the License.
+# ** You may obtain a copy of the License at
+# **
+# **     http://www.apache.org/licenses/LICENSE-2.0
+# **
+# ** Unless required by applicable law or agreed to in writing, software
+# ** distributed under the License is distributed on an "AS IS" BASIS,
+# ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# ** See the License for the specific language governing permissions and
+# ** limitations under the License.
+# */
+# please list all directories that all source files relative with your module(.h .c .cpp) locate
+VOSRCDIR:=../../../inc \
+          ../../../src \
+	  ../../../../../Include
+
+# please list all objects needed by your target here
+OBJS:= autocorr.o az_isp.o bits.o c2t64fx.o c4t64fx.o convolve.o cor_h_x.o decim54.o \
+       deemph.o dtx.o g_pitch.o gpclip.o homing.o hp400.o hp50.o hp6k.o hp_wsp.o \
+       int_lpc.o isp_az.o isp_isf.o lag_wind.o levinson.o log2.o lp_dec2.o math_op.o mem_align.o \
+       oper_32b.o p_med_ol.o pit_shrp.o pitch_f4.o pred_lt4.o preemph.o q_gain2.o q_pulse.o \
+       qisf_ns.o qpisf_2s.o random.o residu.o scale.o stream.o syn_filt.o updt_tar.o util.o \
+       voAMRWBEnc.o voicefac.o wb_vad.o weight_a.o
+
+
+ifeq ($(VOTT), v5)
+OBJS += cor_h_vec_opt.o Deemph_32_opt.o Dot_p_opt.o Filt_6k_7k_opt.o residu_asm_opt.o \
+       scale_sig_opt.o Syn_filt_32_opt.o syn_filt_opt.o pred_lt4_1_opt.o convolve_opt.o \
+       Norm_Corr_opt.o
+VOSRCDIR+= ../../../src/asm/ARMV5E
+endif
+
+ifeq ($(VOTT), v7)
+OBJS+= cor_h_vec_neon.o Deemph_32_neon.o Dot_p_neon.o Filt_6k_7k_neon.o residu_asm_neon.o \
+       scale_sig_neon.o Syn_filt_32_neon.o syn_filt_neon.o pred_lt4_1_neon.o convolve_neon.o \
+       Norm_Corr_neon.o
+VOSRCDIR+= ../../../src/asm/ARMV7
+endif
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/acelp.h b/media/libstagefright/codecs/amrwbenc/inc/acelp.h
index 4cb38a1..5a1e536 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/acelp.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/acelp.h
@@ -1,521 +1,521 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/*--------------------------------------------------------------------------*

- *                         ACELP.H                                          *

- *--------------------------------------------------------------------------*

- *       Function			 			             *

- *--------------------------------------------------------------------------*/

-#ifndef __ACELP_H__

-#define __ACELP_H__

-

-#include "typedef.h"

-#include "cod_main.h"

-

-/*-----------------------------------------------------------------*

- *                        LPC prototypes                           *

- *-----------------------------------------------------------------*/

-

-Word16 median5(Word16 x[]);

-

-void Autocorr(

-		Word16 x[],                           /* (i)    : Input signal                      */

-		Word16 m,                             /* (i)    : LPC order                         */

-		Word16 r_h[],                         /* (o)    : Autocorrelations  (msb)           */

-		Word16 r_l[]                          /* (o)    : Autocorrelations  (lsb)           */

-	     );

-

-void Lag_window(

-		Word16 r_h[],                         /* (i/o)   : Autocorrelations  (msb)          */

-		Word16 r_l[]                          /* (i/o)   : Autocorrelations  (lsb)          */

-	       );

-

-void Init_Levinson(

-		Word16 * mem                          /* output  :static memory (18 words) */

-		);

-

-void Levinson(

-		Word16 Rh[],                          /* (i)     : Rh[M+1] Vector of autocorrelations (msb) */

-		Word16 Rl[],                          /* (i)     : Rl[M+1] Vector of autocorrelations (lsb) */

-		Word16 A[],                           /* (o) Q12 : A[M]    LPC coefficients  (m = 16)       */

-		Word16 rc[],                          /* (o) Q15 : rc[M]   Reflection coefficients.         */

-		Word16 * mem                          /* (i/o)   :static memory (18 words)                  */

-	     );

-

-void Az_isp(

-		Word16 a[],                           /* (i) Q12 : predictor coefficients                 */

-		Word16 isp[],                         /* (o) Q15 : Immittance spectral pairs              */

-		Word16 old_isp[]                      /* (i)     : old isp[] (in case not found M roots)  */

-	   );

-

-void Isp_Az(

-		Word16 isp[],                         /* (i) Q15 : Immittance spectral pairs            */

-		Word16 a[],                           /* (o) Q12 : predictor coefficients (order = M)   */

-		Word16 m,

-		Word16 adaptive_scaling               /* (i) 0   : adaptive scaling disabled */

-		/*     1   : adaptive scaling enabled  */

-	   );

-

-void Isp_isf(

-		Word16 isp[],                         /* (i) Q15 : isp[m] (range: -1<=val<1)                */

-		Word16 isf[],                         /* (o) Q15 : isf[m] normalized (range: 0.0<=val<=0.5) */

-		Word16 m                              /* (i)     : LPC order                                */

-	    );

-

-void Isf_isp(

-		Word16 isf[],                         /* (i) Q15 : isf[m] normalized (range: 0.0<=val<=0.5) */

-		Word16 isp[],                         /* (o) Q15 : isp[m] (range: -1<=val<1)                */

-		Word16 m                              /* (i)     : LPC order                                */

-	    );

-

-void Int_isp(

-		Word16 isp_old[],                     /* input : isps from past frame              */

-		Word16 isp_new[],                     /* input : isps from present frame           */

-		Word16 frac[],                        /* input : fraction for 3 first subfr (Q15)  */

-		Word16 Az[]                           /* output: LP coefficients in 4 subframes    */

-	    );

-

-void Weight_a(

-		Word16 a[],                           /* (i) Q12 : a[m+1]  LPC coefficients             */

-		Word16 ap[],                          /* (o) Q12 : Spectral expanded LPC coefficients   */

-		Word16 gamma,                         /* (i) Q15 : Spectral expansion factor.           */

-		Word16 m                              /* (i)     : LPC order.                           */

-	     );

-

-

-/*-----------------------------------------------------------------*

- *                        isf quantizers                           *

- *-----------------------------------------------------------------*/

-

-void Qpisf_2s_46b(

-		Word16 * isf1,                        /* (i) Q15 : ISF in the frequency domain (0..0.5) */

-		Word16 * isf_q,                       /* (o) Q15 : quantized ISF               (0..0.5) */

-		Word16 * past_isfq,                   /* (io)Q15 : past ISF quantizer                   */

-		Word16 * indice,                      /* (o)     : quantization indices                 */

-		Word16 nb_surv                        /* (i)     : number of survivor (1, 2, 3 or 4)    */

-		);

-

-void Qpisf_2s_36b(

-		Word16 * isf1,                        /* (i) Q15 : ISF in the frequency domain (0..0.5) */

-		Word16 * isf_q,                       /* (o) Q15 : quantized ISF               (0..0.5) */

-		Word16 * past_isfq,                   /* (io)Q15 : past ISF quantizer                   */

-		Word16 * indice,                      /* (o)     : quantization indices                 */

-		Word16 nb_surv                        /* (i)     : number of survivor (1, 2, 3 or 4)    */

-		);

-

-void Dpisf_2s_46b(

-		Word16 * indice,                      /* input:  quantization indices                       */

-		Word16 * isf_q,                       /* output: quantized ISF in frequency domain (0..0.5) */

-		Word16 * past_isfq,                   /* i/0   : past ISF quantizer                    */

-		Word16 * isfold,                      /* input : past quantized ISF                    */

-		Word16 * isf_buf,                     /* input : isf buffer                                                        */

-		Word16 bfi,                           /* input : Bad frame indicator                   */

-		Word16 enc_dec

-		);

-

-void Dpisf_2s_36b(

-		Word16 * indice,                      /* input:  quantization indices                       */

-		Word16 * isf_q,                       /* output: quantized ISF in frequency domain (0..0.5) */

-		Word16 * past_isfq,                   /* i/0   : past ISF quantizer                    */

-		Word16 * isfold,                      /* input : past quantized ISF                    */

-		Word16 * isf_buf,                     /* input : isf buffer                                                        */

-		Word16 bfi,                           /* input : Bad frame indicator                   */

-		Word16 enc_dec

-		);

-

-void Qisf_ns(

-		Word16 * isf1,                        /* input : ISF in the frequency domain (0..0.5) */

-		Word16 * isf_q,                       /* output: quantized ISF                        */

-		Word16 * indice                       /* output: quantization indices                 */

-	    );

-

-void Disf_ns(

-		Word16 * indice,                      /* input:  quantization indices                  */

-		Word16 * isf_q                        /* input : ISF in the frequency domain (0..0.5)  */

-	    );

-

-Word16 Sub_VQ(                             /* output: return quantization index     */

-		Word16 * x,                           /* input : ISF residual vector           */

-		Word16 * dico,                        /* input : quantization codebook         */

-		Word16 dim,                           /* input : dimention of vector           */

-		Word16 dico_size,                     /* input : size of quantization codebook */

-		Word32 * distance                     /* output: error of quantization         */

-	     );

-

-void Reorder_isf(

-		Word16 * isf,                         /* (i/o) Q15: ISF in the frequency domain (0..0.5) */

-		Word16 min_dist,                      /* (i) Q15  : minimum distance to keep             */

-		Word16 n                              /* (i)      : number of ISF                        */

-		);

-

-/*-----------------------------------------------------------------*

- *                       filter prototypes                         *

- *-----------------------------------------------------------------*/

-

-void Init_Decim_12k8(

-		Word16 mem[]                          /* output: memory (2*NB_COEF_DOWN) set to zeros */

-		);

-void Decim_12k8(

-		Word16 sig16k[],                      /* input:  signal to downsampling  */

-		Word16 lg,                            /* input:  length of input         */

-		Word16 sig12k8[],                     /* output: decimated signal        */

-		Word16 mem[]                          /* in/out: memory (2*NB_COEF_DOWN) */

-	       );

-

-void Init_HP50_12k8(Word16 mem[]);

-void HP50_12k8(

-		Word16 signal[],                      /* input/output signal */

-		Word16 lg,                            /* lenght of signal    */

-		Word16 mem[]                          /* filter memory [6]   */

-	      );

-void Init_HP400_12k8(Word16 mem[]);

-void HP400_12k8(

-		Word16 signal[],                      /* input/output signal */

-		Word16 lg,                            /* lenght of signal    */

-		Word16 mem[]                          /* filter memory [6]   */

-	       );

-

-void Init_Filt_6k_7k(Word16 mem[]);

-void Filt_6k_7k(

-		Word16 signal[],                      /* input:  signal                  */

-		Word16 lg,                            /* input:  length of input         */

-		Word16 mem[]                          /* in/out: memory (size=30)        */

-	       );

-void Filt_6k_7k_asm(

-		Word16 signal[],                      /* input:  signal                  */

-		Word16 lg,                            /* input:  length of input         */

-		Word16 mem[]                          /* in/out: memory (size=30)        */

-	       );

-

-void LP_Decim2(

-		Word16 x[],                           /* in/out: signal to process         */

-		Word16 l,                             /* input : size of filtering         */

-		Word16 mem[]                          /* in/out: memory (size=3)           */

-	      );

-

-void Preemph(

-		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */

-		Word16 mu,                            /* (i) Q15 : preemphasis coefficient                */

-		Word16 lg,                            /* (i)     : lenght of filtering                    */

-		Word16 * mem                          /* (i/o)   : memory (x[-1])                         */

-	    );

-void Preemph2(

-		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */

-		Word16 mu,                            /* (i) Q15 : preemphasis coefficient                */

-		Word16 lg,                            /* (i)     : lenght of filtering                    */

-		Word16 * mem                          /* (i/o)   : memory (x[-1])                         */

-	     );

-void Deemph(

-		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */

-		Word16 mu,                            /* (i) Q15 : deemphasis factor                      */

-		Word16 L,                             /* (i)     : vector size                            */

-		Word16 * mem                          /* (i/o)   : memory (y[-1])                         */

-	   );

-void Deemph2(

-		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */

-		Word16 mu,                            /* (i) Q15 : deemphasis factor                      */

-		Word16 L,                             /* (i)     : vector size                            */

-		Word16 * mem                          /* (i/o)   : memory (y[-1])                         */

-	    );

-void Deemph_32(

-		Word16 x_hi[],                        /* (i)     : input signal (bit31..16) */

-		Word16 x_lo[],                        /* (i)     : input signal (bit15..4)  */

-		Word16 y[],                           /* (o)     : output signal (x16)      */

-		Word16 mu,                            /* (i) Q15 : deemphasis factor        */

-		Word16 L,                             /* (i)     : vector size              */

-		Word16 * mem                          /* (i/o)   : memory (y[-1])           */

-	      );

-

-void Deemph_32_asm(

-		Word16 x_hi[],                        /* (i)     : input signal (bit31..16) */

-		Word16 x_lo[],                        /* (i)     : input signal (bit15..4)  */

-		Word16 y[],                           /* (o)     : output signal (x16)      */

-		Word16 * mem                          /* (i/o)   : memory (y[-1])           */

-	      );

-

-void Convolve(

-		Word16 x[],                           /* (i)     : input vector                              */

-		Word16 h[],                           /* (i) Q15    : impulse response                       */

-		Word16 y[],                           /* (o) 12 bits: output vector                          */

-		Word16 L                              /* (i)     : vector size                               */

-	     );

-

-void Convolve_asm(

-		Word16 x[],                           /* (i)     : input vector                              */

-		Word16 h[],                           /* (i) Q15    : impulse response                       */

-		Word16 y[],                           /* (o) 12 bits: output vector                          */

-		Word16 L                              /* (i)     : vector size                               */

-	     );

-

-void Residu(

-		Word16 a[],                           /* (i) Q12 : prediction coefficients                     */

-		Word16 x[],                           /* (i)     : speech (values x[-m..-1] are needed         */

-		Word16 y[],                           /* (o)     : residual signal                             */

-		Word16 lg                             /* (i)     : size of filtering                           */

-		);

-

-void Residu_opt(

-		Word16 a[],                           /* (i) Q12 : prediction coefficients                     */

-		Word16 x[],                           /* (i)     : speech (values x[-m..-1] are needed         */

-		Word16 y[],                           /* (o)     : residual signal                             */

-		Word16 lg                             /* (i)     : size of filtering                           */

-		);

-

-void Syn_filt(

-	Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients           */

-	Word16 x[],                           /* (i)     : input signal                             */

-	Word16 y[],                           /* (o)     : output signal                            */

-	Word16 lg,                            /* (i)     : size of filtering                        */

-	Word16 mem[],                         /* (i/o)   : memory associated with this filtering.   */

-	Word16 update                         /* (i)     : 0=no update, 1=update of memory.         */

-	);

-

-void Syn_filt_asm(

-	Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients           */

-	Word16 x[],                           /* (i)     : input signal                             */

-	Word16 y[],                           /* (o)     : output signal                            */

-	Word16 mem[]                          /* (i/o)   : memory associated with this filtering.   */

-	);

-

-void Syn_filt_32(

-	Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients */

-	Word16 m,                             /* (i)     : order of LP filter             */

-	Word16 exc[],                         /* (i) Qnew: excitation (exc[i] >> Qnew)    */

-	Word16 Qnew,                          /* (i)     : exc scaling = 0(min) to 8(max) */

-	Word16 sig_hi[],                      /* (o) /16 : synthesis high                 */

-	Word16 sig_lo[],                      /* (o) /16 : synthesis low                  */

-	Word16 lg                             /* (i)     : size of filtering              */

-	);

-

-void Syn_filt_32_asm(

-	Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients */

-	Word16 m,                             /* (i)     : order of LP filter             */

-	Word16 exc[],                         /* (i) Qnew: excitation (exc[i] >> Qnew)    */

-	Word16 Qnew,                          /* (i)     : exc scaling = 0(min) to 8(max) */

-	Word16 sig_hi[],                      /* (o) /16 : synthesis high                 */

-	Word16 sig_lo[],                      /* (o) /16 : synthesis low                  */

-	Word16 lg                             /* (i)     : size of filtering              */

-	);

-/*-----------------------------------------------------------------*

- *                       pitch prototypes                          *

- *-----------------------------------------------------------------*/

-

-Word16 Pitch_ol(                           /* output: open loop pitch lag                        */

-     Word16 signal[],                      /* input : signal used to compute the open loop pitch */

-/* signal[-pit_max] to signal[-1] should be known */

-     Word16 pit_min,                       /* input : minimum pitch lag                          */

-     Word16 pit_max,                       /* input : maximum pitch lag                          */

-     Word16 L_frame                        /* input : length of frame to compute pitch           */

-);

-

-Word16 Pitch_med_ol(                       /* output: open loop pitch lag                        */

-     Word16 wsp[],                         /* input : signal used to compute the open loop pitch */

-                                           /* wsp[-pit_max] to wsp[-1] should be known   */

-     Coder_State *st,                      /* i/o : global codec structure */

-     Word16 L_frame                        /* input : length of frame to compute pitch           */

-);

-

-Word16 Med_olag(                           /* output : median of  5 previous open-loop lags       */

-     Word16 prev_ol_lag,                   /* input  : previous open-loop lag                     */

-     Word16 old_ol_lag[5]

-);

-

-void Init_Hp_wsp(Word16 mem[]);

-void scale_mem_Hp_wsp(Word16 mem[], Word16 exp);

-void Hp_wsp(

-     Word16 wsp[],                         /* i   : wsp[]  signal       */

-     Word16 hp_wsp[],                      /* o   : hypass wsp[]        */

-     Word16 lg,                            /* i   : lenght of signal    */

-     Word16 mem[]                          /* i/o : filter memory [9]   */

-);

-

-Word16 Pitch_fr4(                          /* (o)     : pitch period.                         */

-     Word16 exc[],                         /* (i)     : excitation buffer                     */

-     Word16 xn[],                          /* (i)     : target vector                         */

-     Word16 h[],                           /* (i) Q15 : impulse response of synth/wgt filters */

-     Word16 t0_min,                        /* (i)     : minimum value in the searched range.  */

-     Word16 t0_max,                        /* (i)     : maximum value in the searched range.  */

-     Word16 * pit_frac,                    /* (o)     : chosen fraction (0, 1, 2 or 3).       */

-     Word16 i_subfr,                       /* (i)     : indicator for first subframe.         */

-     Word16 t0_fr2,                        /* (i)     : minimum value for resolution 1/2      */

-     Word16 t0_fr1,                        /* (i)     : minimum value for resolution 1        */

-     Word16 L_subfr                        /* (i)     : Length of subframe                    */

-);

-void Pred_lt4(

-     Word16 exc[],                         /* in/out: excitation buffer */

-     Word16 T0,                            /* input : integer pitch lag */

-     Word16 frac,                          /* input : fraction of lag   */

-     Word16 L_subfr                        /* input : subframe size     */

-);

-

-void pred_lt4_asm(

-     Word16 exc[],                         /* in/out: excitation buffer */

-     Word16 T0,                            /* input : integer pitch lag */

-     Word16 frac,                          /* input : fraction of lag   */

-     Word16 L_subfr                        /* input : subframe size     */

-);

-

-/*-----------------------------------------------------------------*

- *                       gain prototypes                           *

- *-----------------------------------------------------------------*/

-

-Word16 G_pitch(                            /* (o) Q14 : Gain of pitch lag saturated to 1.2   */

-     Word16 xn[],                          /* (i)     : Pitch target.                        */

-     Word16 y1[],                          /* (i)     : filtered adaptive codebook.          */

-     Word16 g_coeff[],                     /* : Correlations need for gain quantization. */

-     Word16 L_subfr                        /* : Length of subframe.                  */

-);

-void Init_Q_gain2(

-     Word16 * mem                          /* output  :static memory (2 words)      */

-);

-Word16 Q_gain2(                            /* Return index of quantization.        */

-     Word16 xn[],                          /* (i) Q_xn:Target vector.               */

-     Word16 y1[],                          /* (i) Q_xn:Adaptive codebook.           */

-     Word16 Q_xn,                          /* (i)     :xn and y1 format             */

-     Word16 y2[],                          /* (i) Q9  :Filtered innovative vector.  */

-     Word16 code[],                        /* (i) Q9  :Innovative vector.           */

-     Word16 g_coeff[],                     /* (i)     :Correlations <xn y1> <y1 y1> */

-/* Compute in G_pitch().        */

-     Word16 L_subfr,                       /* (i)     :Subframe lenght.             */

-     Word16 nbits,                         /* (i)     : number of bits (6 or 7)     */

-     Word16 * gain_pit,                    /* (i/o)Q14:Pitch gain.                  */

-     Word32 * gain_cod,                    /* (o) Q16 :Code gain.                   */

-     Word16 gp_clip,                       /* (i)     : Gp Clipping flag            */

-     Word16 * mem                          /* (i/o)   :static memory (2 words)      */

-);

-

-void Init_D_gain2(

-     Word16 * mem                          /* output  :static memory (4 words)      */

-);

-void D_gain2(

-     Word16 index,                         /* (i)     :index of quantization.       */

-     Word16 nbits,                         /* (i)     : number of bits (6 or 7)     */

-     Word16 code[],                        /* (i) Q9  :Innovative vector.           */

-     Word16 L_subfr,                       /* (i)     :Subframe lenght.             */

-     Word16 * gain_pit,                    /* (o) Q14 :Pitch gain.                  */

-     Word32 * gain_cod,                    /* (o) Q16 :Code gain.                   */

-     Word16 bfi,                           /* (i)     :bad frame indicator          */

-     Word16 prev_bfi,                      /* (i) : Previous BF indicator      */

-     Word16 state,                         /* (i) : State of BFH               */

-     Word16 unusable_frame,                /* (i) : UF indicator            */

-     Word16 vad_hist,                      /* (i)         :number of non-speech frames  */

-     Word16 * mem                          /* (i/o)   :static memory (4 words)      */

-);

-

-/*-----------------------------------------------------------------*

- *                       acelp prototypes                          *

- *-----------------------------------------------------------------*/

-

-void cor_h_x(

-     Word16 h[],                           /* (i) Q12 : impulse response of weighted synthesis filter */

-     Word16 x[],                           /* (i) Q0  : target vector                                 */

-     Word16 dn[]                           /* (o) <12bit : correlation between target and h[]         */

-);

-void ACELP_2t64_fx(

-     Word16 dn[],                          /* (i) <12b : correlation between target x[] and H[]      */

-     Word16 cn[],                          /* (i) <12b : residual after long term prediction         */

-     Word16 H[],                           /* (i) Q12: impulse response of weighted synthesis filter */

-     Word16 code[],                        /* (o) Q9 : algebraic (fixed) codebook excitation         */

-     Word16 y[],                           /* (o) Q9 : filtered fixed codebook excitation            */

-     Word16 * index                        /* (o) : index (12): 5+1+5+1 = 11 bits.                     */

-);

-

-void ACELP_4t64_fx(

-     Word16 dn[],                          /* (i) <12b : correlation between target x[] and H[]      */

-     Word16 cn[],                          /* (i) <12b : residual after long term prediction         */

-     Word16 H[],                           /* (i) Q12: impulse response of weighted synthesis filter */

-     Word16 code[],                        /* (o) Q9 : algebraic (fixed) codebook excitation         */

-     Word16 y[],                           /* (o) Q9 : filtered fixed codebook excitation            */

-     Word16 nbbits,                        /* (i) : 20, 36, 44, 52, 64, 72 or 88 bits                */

-     Word16 ser_size,                      /* (i) : bit rate                                         */

-     Word16 _index[]                       /* (o) : index (20): 5+5+5+5 = 20 bits.                   */

-					   /* (o) : index (36): 9+9+9+9 = 36 bits.                   */

-					   /* (o) : index (44): 13+9+13+9 = 44 bits.                 */

-					   /* (o) : index (52): 13+13+13+13 = 52 bits.               */

-					   /* (o) : index (64): 2+2+2+2+14+14+14+14 = 64 bits.       */

-					   /* (o) : index (72): 10+2+10+2+10+14+10+14 = 72 bits.     */

-					   /* (o) : index (88): 11+11+11+11+11+11+11+11 = 88 bits.   */

-);

-

-void Pit_shrp(

-     Word16 * x,                           /* in/out: impulse response (or algebraic code) */

-     Word16 pit_lag,                       /* input : pitch lag                            */

-     Word16 sharp,                         /* input : pitch sharpening factor (Q15)        */

-     Word16 L_subfr                        /* input : subframe size                        */

-);

-

-

-/*-----------------------------------------------------------------*

- *                        others prototypes                        *

- *-----------------------------------------------------------------*/

-

-void Copy(

-     Word16 x[],                           /* (i)   : input vector   */

-     Word16 y[],                           /* (o)   : output vector  */

-     Word16 L                              /* (i)   : vector length  */

-);

-void Set_zero(

-     Word16 x[],                           /* (o)    : vector to clear     */

-     Word16 L                              /* (i)    : length of vector    */

-);

-void Updt_tar(

-     Word16 * x,                           /* (i) Q0  : old target (for pitch search)     */

-     Word16 * x2,                          /* (o) Q0  : new target (for codebook search)  */

-     Word16 * y,                           /* (i) Q0  : filtered adaptive codebook vector */

-     Word16 gain,                          /* (i) Q14 : adaptive codebook gain            */

-     Word16 L                              /* (i)     : subframe size                     */

-);

-Word16 voice_factor(                       /* (o) Q15 : factor (-1=unvoiced to 1=voiced) */

-     Word16 exc[],                         /* (i) Q_exc: pitch excitation                */

-     Word16 Q_exc,                         /* (i)     : exc format                       */

-     Word16 gain_pit,                      /* (i) Q14 : gain of pitch                    */

-     Word16 code[],                        /* (i) Q9  : Fixed codebook excitation        */

-     Word16 gain_code,                     /* (i) Q0  : gain of code                     */

-     Word16 L_subfr                        /* (i)     : subframe length                  */

-);

-void Scale_sig(

-     Word16 x[],                           /* (i/o) : signal to scale               */

-     Word16 lg,                            /* (i)   : size of x[]                   */

-     Word16 exp                            /* (i)   : exponent: x = round(x << exp) */

-);

-

-void Scale_sig_opt(

-     Word16 x[],                           /* (i/o) : signal to scale               */

-     Word16 lg,                            /* (i)   : size of x[]                   */

-     Word16 exp                            /* (i)   : exponent: x = round(x << exp) */

-);

-

-Word16 Random(Word16 * seed);

-

-void Init_gp_clip(

-     Word16 mem[]                          /* (o) : memory of gain of pitch clipping algorithm */

-);

-Word16 Gp_clip(

-     Word16 mem[]                          /* (i/o) : memory of gain of pitch clipping algorithm */

-);

-void Gp_clip_test_isf(

-     Word16 isf[],                         /* (i)   : isf values (in frequency domain)           */

-     Word16 mem[]                          /* (i/o) : memory of gain of pitch clipping algorithm */

-);

-void Gp_clip_test_gain_pit(

-     Word16 gain_pit,                      /* (i)   : gain of quantized pitch                    */

-     Word16 mem[]                          /* (i/o) : memory of gain of pitch clipping algorithm */

-);

-

-

-#endif   //__ACELP_H__

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/*--------------------------------------------------------------------------*
+ *                         ACELP.H                                          *
+ *--------------------------------------------------------------------------*
+ *       Function			 			             *
+ *--------------------------------------------------------------------------*/
+#ifndef __ACELP_H__
+#define __ACELP_H__
+
+#include "typedef.h"
+#include "cod_main.h"
+
+/*-----------------------------------------------------------------*
+ *                        LPC prototypes                           *
+ *-----------------------------------------------------------------*/
+
+Word16 median5(Word16 x[]);
+
+void Autocorr(
+		Word16 x[],                           /* (i)    : Input signal                      */
+		Word16 m,                             /* (i)    : LPC order                         */
+		Word16 r_h[],                         /* (o)    : Autocorrelations  (msb)           */
+		Word16 r_l[]                          /* (o)    : Autocorrelations  (lsb)           */
+	     );
+
+void Lag_window(
+		Word16 r_h[],                         /* (i/o)   : Autocorrelations  (msb)          */
+		Word16 r_l[]                          /* (i/o)   : Autocorrelations  (lsb)          */
+	       );
+
+void Init_Levinson(
+		Word16 * mem                          /* output  :static memory (18 words) */
+		);
+
+void Levinson(
+		Word16 Rh[],                          /* (i)     : Rh[M+1] Vector of autocorrelations (msb) */
+		Word16 Rl[],                          /* (i)     : Rl[M+1] Vector of autocorrelations (lsb) */
+		Word16 A[],                           /* (o) Q12 : A[M]    LPC coefficients  (m = 16)       */
+		Word16 rc[],                          /* (o) Q15 : rc[M]   Reflection coefficients.         */
+		Word16 * mem                          /* (i/o)   :static memory (18 words)                  */
+	     );
+
+void Az_isp(
+		Word16 a[],                           /* (i) Q12 : predictor coefficients                 */
+		Word16 isp[],                         /* (o) Q15 : Immittance spectral pairs              */
+		Word16 old_isp[]                      /* (i)     : old isp[] (in case not found M roots)  */
+	   );
+
+void Isp_Az(
+		Word16 isp[],                         /* (i) Q15 : Immittance spectral pairs            */
+		Word16 a[],                           /* (o) Q12 : predictor coefficients (order = M)   */
+		Word16 m,
+		Word16 adaptive_scaling               /* (i) 0   : adaptive scaling disabled */
+		/*     1   : adaptive scaling enabled  */
+	   );
+
+void Isp_isf(
+		Word16 isp[],                         /* (i) Q15 : isp[m] (range: -1<=val<1)                */
+		Word16 isf[],                         /* (o) Q15 : isf[m] normalized (range: 0.0<=val<=0.5) */
+		Word16 m                              /* (i)     : LPC order                                */
+	    );
+
+void Isf_isp(
+		Word16 isf[],                         /* (i) Q15 : isf[m] normalized (range: 0.0<=val<=0.5) */
+		Word16 isp[],                         /* (o) Q15 : isp[m] (range: -1<=val<1)                */
+		Word16 m                              /* (i)     : LPC order                                */
+	    );
+
+void Int_isp(
+		Word16 isp_old[],                     /* input : isps from past frame              */
+		Word16 isp_new[],                     /* input : isps from present frame           */
+		Word16 frac[],                        /* input : fraction for 3 first subfr (Q15)  */
+		Word16 Az[]                           /* output: LP coefficients in 4 subframes    */
+	    );
+
+void Weight_a(
+		Word16 a[],                           /* (i) Q12 : a[m+1]  LPC coefficients             */
+		Word16 ap[],                          /* (o) Q12 : Spectral expanded LPC coefficients   */
+		Word16 gamma,                         /* (i) Q15 : Spectral expansion factor.           */
+		Word16 m                              /* (i)     : LPC order.                           */
+	     );
+
+
+/*-----------------------------------------------------------------*
+ *                        isf quantizers                           *
+ *-----------------------------------------------------------------*/
+
+void Qpisf_2s_46b(
+		Word16 * isf1,                        /* (i) Q15 : ISF in the frequency domain (0..0.5) */
+		Word16 * isf_q,                       /* (o) Q15 : quantized ISF               (0..0.5) */
+		Word16 * past_isfq,                   /* (io)Q15 : past ISF quantizer                   */
+		Word16 * indice,                      /* (o)     : quantization indices                 */
+		Word16 nb_surv                        /* (i)     : number of survivor (1, 2, 3 or 4)    */
+		);
+
+void Qpisf_2s_36b(
+		Word16 * isf1,                        /* (i) Q15 : ISF in the frequency domain (0..0.5) */
+		Word16 * isf_q,                       /* (o) Q15 : quantized ISF               (0..0.5) */
+		Word16 * past_isfq,                   /* (io)Q15 : past ISF quantizer                   */
+		Word16 * indice,                      /* (o)     : quantization indices                 */
+		Word16 nb_surv                        /* (i)     : number of survivor (1, 2, 3 or 4)    */
+		);
+
+void Dpisf_2s_46b(
+		Word16 * indice,                      /* input:  quantization indices                       */
+		Word16 * isf_q,                       /* output: quantized ISF in frequency domain (0..0.5) */
+		Word16 * past_isfq,                   /* i/0   : past ISF quantizer                    */
+		Word16 * isfold,                      /* input : past quantized ISF                    */
+		Word16 * isf_buf,                     /* input : isf buffer                                                        */
+		Word16 bfi,                           /* input : Bad frame indicator                   */
+		Word16 enc_dec
+		);
+
+void Dpisf_2s_36b(
+		Word16 * indice,                      /* input:  quantization indices                       */
+		Word16 * isf_q,                       /* output: quantized ISF in frequency domain (0..0.5) */
+		Word16 * past_isfq,                   /* i/0   : past ISF quantizer                    */
+		Word16 * isfold,                      /* input : past quantized ISF                    */
+		Word16 * isf_buf,                     /* input : isf buffer                                                        */
+		Word16 bfi,                           /* input : Bad frame indicator                   */
+		Word16 enc_dec
+		);
+
+void Qisf_ns(
+		Word16 * isf1,                        /* input : ISF in the frequency domain (0..0.5) */
+		Word16 * isf_q,                       /* output: quantized ISF                        */
+		Word16 * indice                       /* output: quantization indices                 */
+	    );
+
+void Disf_ns(
+		Word16 * indice,                      /* input:  quantization indices                  */
+		Word16 * isf_q                        /* input : ISF in the frequency domain (0..0.5)  */
+	    );
+
+Word16 Sub_VQ(                             /* output: return quantization index     */
+		Word16 * x,                           /* input : ISF residual vector           */
+		Word16 * dico,                        /* input : quantization codebook         */
+		Word16 dim,                           /* input : dimention of vector           */
+		Word16 dico_size,                     /* input : size of quantization codebook */
+		Word32 * distance                     /* output: error of quantization         */
+	     );
+
+void Reorder_isf(
+		Word16 * isf,                         /* (i/o) Q15: ISF in the frequency domain (0..0.5) */
+		Word16 min_dist,                      /* (i) Q15  : minimum distance to keep             */
+		Word16 n                              /* (i)      : number of ISF                        */
+		);
+
+/*-----------------------------------------------------------------*
+ *                       filter prototypes                         *
+ *-----------------------------------------------------------------*/
+
+void Init_Decim_12k8(
+		Word16 mem[]                          /* output: memory (2*NB_COEF_DOWN) set to zeros */
+		);
+void Decim_12k8(
+		Word16 sig16k[],                      /* input:  signal to downsampling  */
+		Word16 lg,                            /* input:  length of input         */
+		Word16 sig12k8[],                     /* output: decimated signal        */
+		Word16 mem[]                          /* in/out: memory (2*NB_COEF_DOWN) */
+	       );
+
+void Init_HP50_12k8(Word16 mem[]);
+void HP50_12k8(
+		Word16 signal[],                      /* input/output signal */
+		Word16 lg,                            /* lenght of signal    */
+		Word16 mem[]                          /* filter memory [6]   */
+	      );
+void Init_HP400_12k8(Word16 mem[]);
+void HP400_12k8(
+		Word16 signal[],                      /* input/output signal */
+		Word16 lg,                            /* lenght of signal    */
+		Word16 mem[]                          /* filter memory [6]   */
+	       );
+
+void Init_Filt_6k_7k(Word16 mem[]);
+void Filt_6k_7k(
+		Word16 signal[],                      /* input:  signal                  */
+		Word16 lg,                            /* input:  length of input         */
+		Word16 mem[]                          /* in/out: memory (size=30)        */
+	       );
+void Filt_6k_7k_asm(
+		Word16 signal[],                      /* input:  signal                  */
+		Word16 lg,                            /* input:  length of input         */
+		Word16 mem[]                          /* in/out: memory (size=30)        */
+	       );
+
+void LP_Decim2(
+		Word16 x[],                           /* in/out: signal to process         */
+		Word16 l,                             /* input : size of filtering         */
+		Word16 mem[]                          /* in/out: memory (size=3)           */
+	      );
+
+void Preemph(
+		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
+		Word16 mu,                            /* (i) Q15 : preemphasis coefficient                */
+		Word16 lg,                            /* (i)     : lenght of filtering                    */
+		Word16 * mem                          /* (i/o)   : memory (x[-1])                         */
+	    );
+void Preemph2(
+		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
+		Word16 mu,                            /* (i) Q15 : preemphasis coefficient                */
+		Word16 lg,                            /* (i)     : lenght of filtering                    */
+		Word16 * mem                          /* (i/o)   : memory (x[-1])                         */
+	     );
+void Deemph(
+		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
+		Word16 mu,                            /* (i) Q15 : deemphasis factor                      */
+		Word16 L,                             /* (i)     : vector size                            */
+		Word16 * mem                          /* (i/o)   : memory (y[-1])                         */
+	   );
+void Deemph2(
+		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
+		Word16 mu,                            /* (i) Q15 : deemphasis factor                      */
+		Word16 L,                             /* (i)     : vector size                            */
+		Word16 * mem                          /* (i/o)   : memory (y[-1])                         */
+	    );
+void Deemph_32(
+		Word16 x_hi[],                        /* (i)     : input signal (bit31..16) */
+		Word16 x_lo[],                        /* (i)     : input signal (bit15..4)  */
+		Word16 y[],                           /* (o)     : output signal (x16)      */
+		Word16 mu,                            /* (i) Q15 : deemphasis factor        */
+		Word16 L,                             /* (i)     : vector size              */
+		Word16 * mem                          /* (i/o)   : memory (y[-1])           */
+	      );
+
+void Deemph_32_asm(
+		Word16 x_hi[],                        /* (i)     : input signal (bit31..16) */
+		Word16 x_lo[],                        /* (i)     : input signal (bit15..4)  */
+		Word16 y[],                           /* (o)     : output signal (x16)      */
+		Word16 * mem                          /* (i/o)   : memory (y[-1])           */
+	      );
+
+void Convolve(
+		Word16 x[],                           /* (i)     : input vector                              */
+		Word16 h[],                           /* (i) Q15    : impulse response                       */
+		Word16 y[],                           /* (o) 12 bits: output vector                          */
+		Word16 L                              /* (i)     : vector size                               */
+	     );
+
+void Convolve_asm(
+		Word16 x[],                           /* (i)     : input vector                              */
+		Word16 h[],                           /* (i) Q15    : impulse response                       */
+		Word16 y[],                           /* (o) 12 bits: output vector                          */
+		Word16 L                              /* (i)     : vector size                               */
+	     );
+
+void Residu(
+		Word16 a[],                           /* (i) Q12 : prediction coefficients                     */
+		Word16 x[],                           /* (i)     : speech (values x[-m..-1] are needed         */
+		Word16 y[],                           /* (o)     : residual signal                             */
+		Word16 lg                             /* (i)     : size of filtering                           */
+		);
+
+void Residu_opt(
+		Word16 a[],                           /* (i) Q12 : prediction coefficients                     */
+		Word16 x[],                           /* (i)     : speech (values x[-m..-1] are needed         */
+		Word16 y[],                           /* (o)     : residual signal                             */
+		Word16 lg                             /* (i)     : size of filtering                           */
+		);
+
+void Syn_filt(
+	Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients           */
+	Word16 x[],                           /* (i)     : input signal                             */
+	Word16 y[],                           /* (o)     : output signal                            */
+	Word16 lg,                            /* (i)     : size of filtering                        */
+	Word16 mem[],                         /* (i/o)   : memory associated with this filtering.   */
+	Word16 update                         /* (i)     : 0=no update, 1=update of memory.         */
+	);
+
+void Syn_filt_asm(
+	Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients           */
+	Word16 x[],                           /* (i)     : input signal                             */
+	Word16 y[],                           /* (o)     : output signal                            */
+	Word16 mem[]                          /* (i/o)   : memory associated with this filtering.   */
+	);
+
+void Syn_filt_32(
+	Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients */
+	Word16 m,                             /* (i)     : order of LP filter             */
+	Word16 exc[],                         /* (i) Qnew: excitation (exc[i] >> Qnew)    */
+	Word16 Qnew,                          /* (i)     : exc scaling = 0(min) to 8(max) */
+	Word16 sig_hi[],                      /* (o) /16 : synthesis high                 */
+	Word16 sig_lo[],                      /* (o) /16 : synthesis low                  */
+	Word16 lg                             /* (i)     : size of filtering              */
+	);
+
+void Syn_filt_32_asm(
+	Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients */
+	Word16 m,                             /* (i)     : order of LP filter             */
+	Word16 exc[],                         /* (i) Qnew: excitation (exc[i] >> Qnew)    */
+	Word16 Qnew,                          /* (i)     : exc scaling = 0(min) to 8(max) */
+	Word16 sig_hi[],                      /* (o) /16 : synthesis high                 */
+	Word16 sig_lo[],                      /* (o) /16 : synthesis low                  */
+	Word16 lg                             /* (i)     : size of filtering              */
+	);
+/*-----------------------------------------------------------------*
+ *                       pitch prototypes                          *
+ *-----------------------------------------------------------------*/
+
+Word16 Pitch_ol(                           /* output: open loop pitch lag                        */
+     Word16 signal[],                      /* input : signal used to compute the open loop pitch */
+/* signal[-pit_max] to signal[-1] should be known */
+     Word16 pit_min,                       /* input : minimum pitch lag                          */
+     Word16 pit_max,                       /* input : maximum pitch lag                          */
+     Word16 L_frame                        /* input : length of frame to compute pitch           */
+);
+
+Word16 Pitch_med_ol(                       /* output: open loop pitch lag                        */
+     Word16 wsp[],                         /* input : signal used to compute the open loop pitch */
+                                           /* wsp[-pit_max] to wsp[-1] should be known   */
+     Coder_State *st,                      /* i/o : global codec structure */
+     Word16 L_frame                        /* input : length of frame to compute pitch           */
+);
+
+Word16 Med_olag(                           /* output : median of  5 previous open-loop lags       */
+     Word16 prev_ol_lag,                   /* input  : previous open-loop lag                     */
+     Word16 old_ol_lag[5]
+);
+
+void Init_Hp_wsp(Word16 mem[]);
+void scale_mem_Hp_wsp(Word16 mem[], Word16 exp);
+void Hp_wsp(
+     Word16 wsp[],                         /* i   : wsp[]  signal       */
+     Word16 hp_wsp[],                      /* o   : hypass wsp[]        */
+     Word16 lg,                            /* i   : lenght of signal    */
+     Word16 mem[]                          /* i/o : filter memory [9]   */
+);
+
+Word16 Pitch_fr4(                          /* (o)     : pitch period.                         */
+     Word16 exc[],                         /* (i)     : excitation buffer                     */
+     Word16 xn[],                          /* (i)     : target vector                         */
+     Word16 h[],                           /* (i) Q15 : impulse response of synth/wgt filters */
+     Word16 t0_min,                        /* (i)     : minimum value in the searched range.  */
+     Word16 t0_max,                        /* (i)     : maximum value in the searched range.  */
+     Word16 * pit_frac,                    /* (o)     : chosen fraction (0, 1, 2 or 3).       */
+     Word16 i_subfr,                       /* (i)     : indicator for first subframe.         */
+     Word16 t0_fr2,                        /* (i)     : minimum value for resolution 1/2      */
+     Word16 t0_fr1,                        /* (i)     : minimum value for resolution 1        */
+     Word16 L_subfr                        /* (i)     : Length of subframe                    */
+);
+void Pred_lt4(
+     Word16 exc[],                         /* in/out: excitation buffer */
+     Word16 T0,                            /* input : integer pitch lag */
+     Word16 frac,                          /* input : fraction of lag   */
+     Word16 L_subfr                        /* input : subframe size     */
+);
+
+void pred_lt4_asm(
+     Word16 exc[],                         /* in/out: excitation buffer */
+     Word16 T0,                            /* input : integer pitch lag */
+     Word16 frac,                          /* input : fraction of lag   */
+     Word16 L_subfr                        /* input : subframe size     */
+);
+
+/*-----------------------------------------------------------------*
+ *                       gain prototypes                           *
+ *-----------------------------------------------------------------*/
+
+Word16 G_pitch(                            /* (o) Q14 : Gain of pitch lag saturated to 1.2   */
+     Word16 xn[],                          /* (i)     : Pitch target.                        */
+     Word16 y1[],                          /* (i)     : filtered adaptive codebook.          */
+     Word16 g_coeff[],                     /* : Correlations need for gain quantization. */
+     Word16 L_subfr                        /* : Length of subframe.                  */
+);
+void Init_Q_gain2(
+     Word16 * mem                          /* output  :static memory (2 words)      */
+);
+Word16 Q_gain2(                            /* Return index of quantization.        */
+     Word16 xn[],                          /* (i) Q_xn:Target vector.               */
+     Word16 y1[],                          /* (i) Q_xn:Adaptive codebook.           */
+     Word16 Q_xn,                          /* (i)     :xn and y1 format             */
+     Word16 y2[],                          /* (i) Q9  :Filtered innovative vector.  */
+     Word16 code[],                        /* (i) Q9  :Innovative vector.           */
+     Word16 g_coeff[],                     /* (i)     :Correlations <xn y1> <y1 y1> */
+/* Compute in G_pitch().        */
+     Word16 L_subfr,                       /* (i)     :Subframe lenght.             */
+     Word16 nbits,                         /* (i)     : number of bits (6 or 7)     */
+     Word16 * gain_pit,                    /* (i/o)Q14:Pitch gain.                  */
+     Word32 * gain_cod,                    /* (o) Q16 :Code gain.                   */
+     Word16 gp_clip,                       /* (i)     : Gp Clipping flag            */
+     Word16 * mem                          /* (i/o)   :static memory (2 words)      */
+);
+
+void Init_D_gain2(
+     Word16 * mem                          /* output  :static memory (4 words)      */
+);
+void D_gain2(
+     Word16 index,                         /* (i)     :index of quantization.       */
+     Word16 nbits,                         /* (i)     : number of bits (6 or 7)     */
+     Word16 code[],                        /* (i) Q9  :Innovative vector.           */
+     Word16 L_subfr,                       /* (i)     :Subframe lenght.             */
+     Word16 * gain_pit,                    /* (o) Q14 :Pitch gain.                  */
+     Word32 * gain_cod,                    /* (o) Q16 :Code gain.                   */
+     Word16 bfi,                           /* (i)     :bad frame indicator          */
+     Word16 prev_bfi,                      /* (i) : Previous BF indicator      */
+     Word16 state,                         /* (i) : State of BFH               */
+     Word16 unusable_frame,                /* (i) : UF indicator            */
+     Word16 vad_hist,                      /* (i)         :number of non-speech frames  */
+     Word16 * mem                          /* (i/o)   :static memory (4 words)      */
+);
+
+/*-----------------------------------------------------------------*
+ *                       acelp prototypes                          *
+ *-----------------------------------------------------------------*/
+
+void cor_h_x(
+     Word16 h[],                           /* (i) Q12 : impulse response of weighted synthesis filter */
+     Word16 x[],                           /* (i) Q0  : target vector                                 */
+     Word16 dn[]                           /* (o) <12bit : correlation between target and h[]         */
+);
+void ACELP_2t64_fx(
+     Word16 dn[],                          /* (i) <12b : correlation between target x[] and H[]      */
+     Word16 cn[],                          /* (i) <12b : residual after long term prediction         */
+     Word16 H[],                           /* (i) Q12: impulse response of weighted synthesis filter */
+     Word16 code[],                        /* (o) Q9 : algebraic (fixed) codebook excitation         */
+     Word16 y[],                           /* (o) Q9 : filtered fixed codebook excitation            */
+     Word16 * index                        /* (o) : index (12): 5+1+5+1 = 11 bits.                     */
+);
+
+void ACELP_4t64_fx(
+     Word16 dn[],                          /* (i) <12b : correlation between target x[] and H[]      */
+     Word16 cn[],                          /* (i) <12b : residual after long term prediction         */
+     Word16 H[],                           /* (i) Q12: impulse response of weighted synthesis filter */
+     Word16 code[],                        /* (o) Q9 : algebraic (fixed) codebook excitation         */
+     Word16 y[],                           /* (o) Q9 : filtered fixed codebook excitation            */
+     Word16 nbbits,                        /* (i) : 20, 36, 44, 52, 64, 72 or 88 bits                */
+     Word16 ser_size,                      /* (i) : bit rate                                         */
+     Word16 _index[]                       /* (o) : index (20): 5+5+5+5 = 20 bits.                   */
+					   /* (o) : index (36): 9+9+9+9 = 36 bits.                   */
+					   /* (o) : index (44): 13+9+13+9 = 44 bits.                 */
+					   /* (o) : index (52): 13+13+13+13 = 52 bits.               */
+					   /* (o) : index (64): 2+2+2+2+14+14+14+14 = 64 bits.       */
+					   /* (o) : index (72): 10+2+10+2+10+14+10+14 = 72 bits.     */
+					   /* (o) : index (88): 11+11+11+11+11+11+11+11 = 88 bits.   */
+);
+
+void Pit_shrp(
+     Word16 * x,                           /* in/out: impulse response (or algebraic code) */
+     Word16 pit_lag,                       /* input : pitch lag                            */
+     Word16 sharp,                         /* input : pitch sharpening factor (Q15)        */
+     Word16 L_subfr                        /* input : subframe size                        */
+);
+
+
+/*-----------------------------------------------------------------*
+ *                        others prototypes                        *
+ *-----------------------------------------------------------------*/
+
+void Copy(
+     Word16 x[],                           /* (i)   : input vector   */
+     Word16 y[],                           /* (o)   : output vector  */
+     Word16 L                              /* (i)   : vector length  */
+);
+void Set_zero(
+     Word16 x[],                           /* (o)    : vector to clear     */
+     Word16 L                              /* (i)    : length of vector    */
+);
+void Updt_tar(
+     Word16 * x,                           /* (i) Q0  : old target (for pitch search)     */
+     Word16 * x2,                          /* (o) Q0  : new target (for codebook search)  */
+     Word16 * y,                           /* (i) Q0  : filtered adaptive codebook vector */
+     Word16 gain,                          /* (i) Q14 : adaptive codebook gain            */
+     Word16 L                              /* (i)     : subframe size                     */
+);
+Word16 voice_factor(                       /* (o) Q15 : factor (-1=unvoiced to 1=voiced) */
+     Word16 exc[],                         /* (i) Q_exc: pitch excitation                */
+     Word16 Q_exc,                         /* (i)     : exc format                       */
+     Word16 gain_pit,                      /* (i) Q14 : gain of pitch                    */
+     Word16 code[],                        /* (i) Q9  : Fixed codebook excitation        */
+     Word16 gain_code,                     /* (i) Q0  : gain of code                     */
+     Word16 L_subfr                        /* (i)     : subframe length                  */
+);
+void Scale_sig(
+     Word16 x[],                           /* (i/o) : signal to scale               */
+     Word16 lg,                            /* (i)   : size of x[]                   */
+     Word16 exp                            /* (i)   : exponent: x = round(x << exp) */
+);
+
+void Scale_sig_opt(
+     Word16 x[],                           /* (i/o) : signal to scale               */
+     Word16 lg,                            /* (i)   : size of x[]                   */
+     Word16 exp                            /* (i)   : exponent: x = round(x << exp) */
+);
+
+Word16 Random(Word16 * seed);
+
+void Init_gp_clip(
+     Word16 mem[]                          /* (o) : memory of gain of pitch clipping algorithm */
+);
+Word16 Gp_clip(
+     Word16 mem[]                          /* (i/o) : memory of gain of pitch clipping algorithm */
+);
+void Gp_clip_test_isf(
+     Word16 isf[],                         /* (i)   : isf values (in frequency domain)           */
+     Word16 mem[]                          /* (i/o) : memory of gain of pitch clipping algorithm */
+);
+void Gp_clip_test_gain_pit(
+     Word16 gain_pit,                      /* (i)   : gain of quantized pitch                    */
+     Word16 mem[]                          /* (i/o) : memory of gain of pitch clipping algorithm */
+);
+
+
+#endif   //__ACELP_H__
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/basic_op.h b/media/libstagefright/codecs/amrwbenc/inc/basic_op.h
index 6a2f8605..c23dce6 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/basic_op.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/basic_op.h
@@ -1,1094 +1,1094 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT 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 __BASIC_OP_H__

-#define __BASIC_OP_H__

-

-#include <stdio.h>

-#include <stdlib.h>

-#include "typedef.h"

-

-#define MAX_32 (Word32)0x7fffffffL

-#define MIN_32 (Word32)0x80000000L

-

-#define MAX_16 (Word16)+32767	/* 0x7fff */

-#define MIN_16 (Word16)-32768	/* 0x8000 */

-

-

-#ifdef LINUX

-#define  static_vo  static __inline__

-#else

-#define  static_vo  static __inline

-#endif 

-

-#define saturate(L_var1) (((L_var1) > 0X00007fffL) ? (MAX_16): (((L_var1) < (Word32) 0xffff8000L) ? (MIN_16): ((L_var1) & 0xffff)))

-

-#define abs_s(x)       ((Word16)(((x) != MIN_16) ? (((x) >= 0) ? (x) : (-(x))) : MAX_16))  /* Short abs,           1   */

-#define L_deposit_h(x) (((Word32)(x)) << 16)                                               /* 16 bit var1 -> MSB,     2 */

-#define L_deposit_l(x) ((Word32)(x))                                                       /* 16 bit var1 -> LSB,     2 */

-#define L_abs(x) (((x) != MIN_32) ? (((x) >= 0) ? (x) : (-(x))) : MAX_32)                  /* Long abs,              3*/

-#define negate(var1) ((Word16)(((var1) == MIN_16) ? MAX_16 : (-(var1))))                   /* Short negate,        1*/

-#define L_negate(L_var1) (((L_var1) == (MIN_32)) ? (MAX_32) : (-(L_var1)))                 /* Long negate,     2*/

-

-

-#define extract_h(a)			((Word16)(a >> 16))

-#define extract_l(x)            	(Word16)((x))

-#define add1(a,b)			(a + b)

-#define vo_L_msu(a,b,c)			( a - (( b * c ) << 1) )

-#define vo_mult32(a, b)         ((a) * (b))

-#define vo_mult(a,b)			(( a * b ) >> 15 )

-#define	vo_L_mult(a,b)	    		(((a) * (b)) << 1)

-#define vo_shr_r(var1, var2)   		((var1+((Word16)(1L<<(var2-1))))>>var2)

-#define vo_sub(a,b)			(a - b)

-#define vo_L_deposit_h(a)		((Word32)((a) << 16))

-#define vo_round(a)			((a + 0x00008000) >> 16)

-#define vo_extract_l(a)			((Word16)(a))

-#define vo_L_add(a,b)			(a + b)

-#define vo_L_sub(a,b)			(a - b)

-#define vo_mult_r(a,b)			((( a * b ) + 0x4000 ) >> 15 )

-#define vo_negate(a)		        (-a)

-#define vo_L_shr_r(L_var1, var2)        ((L_var1+((Word32)(1L<<(var2-1))))>>var2)

-

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Prototypes for basic arithmetic operators                               |

-|___________________________________________________________________________|

-*/

-static_vo Word16 add (Word16 var1, Word16 var2);				/* Short add,1 */

-static_vo Word16 sub (Word16 var1, Word16 var2);				/* Short sub,1 */

-static_vo Word16 shl (Word16 var1, Word16 var2);                                /* Short shift left,    1   */

-static_vo Word16 shr (Word16 var1, Word16 var2);                                /* Short shift right,   1   */

-static_vo Word16 mult (Word16 var1, Word16 var2);                               /* Short mult,          1   */

-static_vo Word32 L_mult (Word16 var1, Word16 var2);                             /* Long mult,           1   */

-static_vo Word16 voround (Word32 L_var1);                                       /* Round,               1   */

-static_vo Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2);            	/* Mac,  1  */

-static_vo Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2);   		/* Msu,  1  */

-static_vo Word32 L_add (Word32 L_var1, Word32 L_var2);   		 	/* Long add,        2 */

-static_vo Word32 L_sub (Word32 L_var1, Word32 L_var2);   			/* Long sub,        2 */

-static_vo Word16 mult_r (Word16 var1, Word16 var2);      		 	/* Mult with round, 2 */

-static_vo Word32 L_shl2(Word32 L_var1, Word16 var2);             		/* var2 > 0*/

-static_vo Word32 L_shl (Word32 L_var1, Word16 var2);    	 	 	/* Long shift left, 2 */

-static_vo Word32 L_shr (Word32 L_var1, Word16 var2);    	 	 	/* Long shift right, 2*/

-static_vo Word32 L_shr_r (Word32 L_var1, Word16 var2); 				/* Long shift right with round,  3   */

-static_vo Word16 norm_s (Word16 var1);             				/* Short norm,           15  */

-static_vo Word16 div_s (Word16 var1, Word16 var2); 				/* Short division,       18  */

-static_vo Word16 norm_l (Word32 L_var1);           				/* Long norm,            30  */   

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Functions                                                               |

-|___________________________________________________________________________|

-*/

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : add                                                     |

-|                                                                           |

-|   Purpose :                                                               |

-|                                                                           |

-|    Performs the addition (var1+var2) with overflow control and saturation;|

-|    the 16 bit result is set at +32767 when overflow occurs or at -32768   |

-|    when underflow occurs.                                                 |

-|                                                                           |

-|   Complexity weight : 1                                                   |

-|                                                                           |

-|   Inputs :                                                                |

-|                                                                           |

-|    var1                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|    var2                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|   Outputs :                                                               |

-|                                                                           |

-|    none                                                                   |

-|                                                                           |

-|   Return Value :                                                          |

-|                                                                           |

-|    var_out                                                                |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |

-|___________________________________________________________________________|

-*/

-static_vo Word16 add (Word16 var1, Word16 var2)

-{

-	Word16 var_out;

-	Word32 L_sum;

-	L_sum = (Word32) var1 + var2;

-	var_out = saturate (L_sum);

-	return (var_out);

-}

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : sub                                                     |

-|                                                                           |

-|   Purpose :                                                               |

-|                                                                           |

-|    Performs the subtraction (var1+var2) with overflow control and satu-   |

-|    ration; the 16 bit result is set at +32767 when overflow occurs or at  |

-|    -32768 when underflow occurs.                                          |

-|                                                                           |

-|   Complexity weight : 1                                                   |

-|                                                                           |

-|   Inputs :                                                                |

-|                                                                           |

-|    var1                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|    var2                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|   Outputs :                                                               |

-|                                                                           |

-|    none                                                                   |

-|                                                                           |

-|   Return Value :                                                          |

-|                                                                           |

-|    var_out                                                                |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |

-|___________________________________________________________________________|

-*/

-

-static_vo Word16 sub (Word16 var1, Word16 var2)

-{

-	Word16 var_out;

-	Word32 L_diff;

-	L_diff = (Word32) var1 - var2;

-	var_out = saturate (L_diff);

-	return (var_out);

-}

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : shl                                                     |

-|                                                                           |

-|   Purpose :                                                               |

-|                                                                           |

-|   Arithmetically shift the 16 bit input var1 left var2 positions.Zero fill|

-|   the var2 LSB of the result. If var2 is negative, arithmetically shift   |

-|   var1 right by -var2 with sign extension. Saturate the result in case of |

-|   underflows or overflows.                                                |

-|                                                                           |

-|   Complexity weight : 1                                                   |

-|                                                                           |

-|   Inputs :                                                                |

-|                                                                           |

-|    var1                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|    var2                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|   Outputs :                                                               |

-|                                                                           |

-|    none                                                                   |

-|                                                                           |

-|   Return Value :                                                          |

-|                                                                           |

-|    var_out                                                                |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |

-|___________________________________________________________________________|

-*/

-

-static_vo Word16 shl (Word16 var1, Word16 var2)

-{

-	Word16 var_out;

-	Word32 result;

-	if (var2 < 0)

-	{

-		if (var2 < -16)

-			var2 = -16;

-		var_out = var1 >> ((Word16)-var2);

-	}

-	else

-	{

-		result = (Word32) var1 *((Word32) 1 << var2);

-		if ((var2 > 15 && var1 != 0) || (result != (Word32) ((Word16) result)))

-		{

-			var_out = (Word16)((var1 > 0) ? MAX_16 : MIN_16);

-		}

-		else

-		{

-			var_out = extract_l (result);

-		}

-	}

-	return (var_out);

-}

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : shr                                                     |

-|                                                                           |

-|   Purpose :                                                               |

-|                                                                           |

-|   Arithmetically shift the 16 bit input var1 right var2 positions with    |

-|   sign extension. If var2 is negative, arithmetically shift var1 left by  |

-|   -var2 with sign extension. Saturate the result in case of underflows or |

-|   overflows.                                                              |

-|                                                                           |

-|   Complexity weight : 1                                                   |

-|                                                                           |

-|   Inputs :                                                                |

-|                                                                           |

-|    var1                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|    var2                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|   Outputs :                                                               |

-|                                                                           |

-|    none                                                                   |

-|                                                                           |

-|   Return Value :                                                          |

-|                                                                           |

-|    var_out                                                                |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |

-|___________________________________________________________________________|

-*/

-

-static_vo Word16 shr (Word16 var1, Word16 var2)

-{

-	Word16 var_out;

-	if (var2 < 0)

-	{

-		if (var2 < -16)

-			var2 = -16;

-		var_out = shl(var1, (Word16)-var2);

-	}

-	else

-	{

-		if (var2 >= 15)

-		{

-			var_out = (Word16)((var1 < 0) ? -1 : 0);

-		}

-		else

-		{

-			if (var1 < 0)

-			{

-				var_out = (Word16)(~((~var1) >> var2));

-			}

-			else

-			{

-				var_out = (Word16)(var1 >> var2);

-			}

-		}

-	}

-	return (var_out);

-}

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : mult                                                    |

-|                                                                           |

-|   Purpose :                                                               |

-|                                                                           |

-|    Performs the multiplication of var1 by var2 and gives a 16 bit result  |

-|    which is scaled i.e.:                                                  |

-|             mult(var1,var2) = extract_l(L_shr((var1 times var2),15)) and  |

-|             mult(-32768,-32768) = 32767.                                  |

-|                                                                           |

-|   Complexity weight : 1                                                   |

-|                                                                           |

-|   Inputs :                                                                |

-|                                                                           |

-|    var1                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|    var2                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|   Outputs :                                                               |

-|                                                                           |

-|    none                                                                   |

-|                                                                           |

-|   Return Value :                                                          |

-|                                                                           |

-|    var_out                                                                |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |

-|___________________________________________________________________________|

-*/

-

-static_vo Word16 mult (Word16 var1, Word16 var2)

-{

-	Word16 var_out;

-	Word32 L_product;

-	L_product = (Word32) var1 *(Word32) var2;

-	L_product = (L_product & (Word32) 0xffff8000L) >> 15;

-	if (L_product & (Word32) 0x00010000L)

-		L_product = L_product | (Word32) 0xffff0000L;

-	var_out = saturate (L_product);

-	return (var_out);

-}

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : L_mult                                                  |

-|                                                                           |

-|   Purpose :                                                               |

-|                                                                           |

-|   L_mult is the 32 bit result of the multiplication of var1 times var2    |

-|   with one shift left i.e.:                                               |

-|        L_mult(var1,var2) = L_shl((var1 times var2),1) and                   |

-|        L_mult(-32768,-32768) = 2147483647.                                |

-|                                                                           |

-|   Complexity weight : 1                                                   |

-|                                                                           |

-|   Inputs :                                                                |

-|                                                                           |

-|    var1                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|    var2                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|   Outputs :                                                               |

-|                                                                           |

-|    none                                                                   |

-|                                                                           |

-|   Return Value :                                                          |

-|                                                                           |

-|    L_var_out                                                              |

-|             32 bit long signed integer (Word32) whose value falls in the  |

-|             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |

-|___________________________________________________________________________|

-*/

-

-static_vo Word32 L_mult (Word16 var1, Word16 var2)

-{

-	Word32 L_var_out;

-	L_var_out = (Word32) var1 *(Word32) var2;

-	if (L_var_out != (Word32) 0x40000000L)

-	{

-		L_var_out *= 2;

-	}

-	else

-	{

-		L_var_out = MAX_32;

-	}

-	return (L_var_out);

-}

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : round                                                   |

-|                                                                           |

-|   Purpose :                                                               |

-|                                                                           |

-|   Round the lower 16 bits of the 32 bit input number into the MS 16 bits  |

-|   with saturation. Shift the resulting bits right by 16 and return the 16 |

-|   bit number:                                                             |

-|               round(L_var1) = extract_h(L_add(L_var1,32768))              |

-|                                                                           |

-|   Complexity weight : 1                                                   |

-|                                                                           |

-|   Inputs :                                                                |

-|                                                                           |

-|    L_var1                                                                 |

-|             32 bit long signed integer (Word32 ) whose value falls in the |

-|             range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.                 |

-|                                                                           |

-|   Outputs :                                                               |

-|                                                                           |

-|    none                                                                   |

-|                                                                           |

-|   Return Value :                                                          |

-|                                                                           |

-|    var_out                                                                |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |

-|___________________________________________________________________________|

-*/

-

-static_vo Word16 voround (Word32 L_var1)

-{

-	Word16 var_out;

-	Word32 L_rounded;

-	L_rounded = L_add (L_var1, (Word32) 0x00008000L);

-	var_out = extract_h (L_rounded);

-	return (var_out);

-}

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : L_mac                                                   |

-|                                                                           |

-|   Purpose :                                                               |

-|                                                                           |

-|   Multiply var1 by var2 and shift the result left by 1. Add the 32 bit    |

-|   result to L_var3 with saturation, return a 32 bit result:               |

-|        L_mac(L_var3,var1,var2) = L_add(L_var3,L_mult(var1,var2)).         |

-|                                                                           |

-|   Complexity weight : 1                                                   |

-|                                                                           |

-|   Inputs :                                                                |

-|                                                                           |

-|    L_var3   32 bit long signed integer (Word32) whose value falls in the  |

-|             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |

-|                                                                           |

-|    var1                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|    var2                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|   Outputs :                                                               |

-|                                                                           |

-|    none                                                                   |

-|                                                                           |

-|   Return Value :                                                          |

-|                                                                           |

-|    L_var_out                                                              |

-|             32 bit long signed integer (Word32) whose value falls in the  |

-|             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |

-|___________________________________________________________________________|

-*/

-

-static_vo Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2)

-{

-	Word32 L_var_out;

-	Word32 L_product;

-	L_product = ((var1 * var2) << 1);

-	L_var_out = L_add (L_var3, L_product);

-	return (L_var_out);

-}

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : L_msu                                                   |

-|                                                                           |

-|   Purpose :                                                               |

-|                                                                           |

-|   Multiply var1 by var2 and shift the result left by 1. Subtract the 32   |

-|   bit result to L_var3 with saturation, return a 32 bit result:           |

-|        L_msu(L_var3,var1,var2) = L_sub(L_var3,L_mult(var1,var2)).         |

-|                                                                           |

-|   Complexity weight : 1                                                   |

-|                                                                           |

-|   Inputs :                                                                |

-|                                                                           |

-|    L_var3   32 bit long signed integer (Word32) whose value falls in the  |

-|             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |

-|                                                                           |

-|    var1                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|    var2                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|   Outputs :                                                               |

-|                                                                           |

-|    none                                                                   |

-|                                                                           |

-|   Return Value :                                                          |

-|                                                                           |

-|    L_var_out                                                              |

-|             32 bit long signed integer (Word32) whose value falls in the  |

-|             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |

-|___________________________________________________________________________|

-*/

-

-static_vo Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2)

-{

-	Word32 L_var_out;

-	Word32 L_product;

-	L_product = (var1 * var2)<<1;

-	L_var_out = L_sub (L_var3, L_product);

-	return (L_var_out);

-}

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : L_add                                                   |

-|                                                                           |

-|   Purpose :                                                               |

-|                                                                           |

-|   32 bits addition of the two 32 bits variables (L_var1+L_var2) with      |

-|   overflow control and saturation; the result is set at +2147483647 when  |

-|   overflow occurs or at -2147483648 when underflow occurs.                |

-|                                                                           |

-|   Complexity weight : 2                                                   |

-|                                                                           |

-|   Inputs :                                                                |

-|                                                                           |

-|    L_var1   32 bit long signed integer (Word32) whose value falls in the  |

-|             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |

-|                                                                           |

-|    L_var2   32 bit long signed integer (Word32) whose value falls in the  |

-|             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |

-|                                                                           |

-|   Outputs :                                                               |

-|                                                                           |

-|    none                                                                   |

-|                                                                           |

-|   Return Value :                                                          |

-|                                                                           |

-|    L_var_out                                                              |

-|             32 bit long signed integer (Word32) whose value falls in the  |

-|             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |

-|___________________________________________________________________________|

-*/

-

-static_vo Word32 L_add (Word32 L_var1, Word32 L_var2)

-{

-	Word32 L_var_out;

-	L_var_out = L_var1 + L_var2;

-	if (((L_var1 ^ L_var2) & MIN_32) == 0)

-	{

-		if ((L_var_out ^ L_var1) & MIN_32)

-		{

-			L_var_out = (L_var1 < 0) ? MIN_32 : MAX_32;

-		}

-	}

-	return (L_var_out);

-}

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : L_sub                                                   |

-|                                                                           |

-|   Purpose :                                                               |

-|                                                                           |

-|   32 bits subtraction of the two 32 bits variables (L_var1-L_var2) with   |

-|   overflow control and saturation; the result is set at +2147483647 when  |

-|   overflow occurs or at -2147483648 when underflow occurs.                |

-|                                                                           |

-|   Complexity weight : 2                                                   |

-|                                                                           |

-|   Inputs :                                                                |

-|                                                                           |

-|    L_var1   32 bit long signed integer (Word32) whose value falls in the  |

-|             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |

-|                                                                           |

-|    L_var2   32 bit long signed integer (Word32) whose value falls in the  |

-|             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |

-|                                                                           |

-|   Outputs :                                                               |

-|                                                                           |

-|    none                                                                   |

-|                                                                           |

-|   Return Value :                                                          |

-|                                                                           |

-|    L_var_out                                                              |

-|             32 bit long signed integer (Word32) whose value falls in the  |

-|             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |

-|___________________________________________________________________________|

-*/

-

-static_vo Word32 L_sub (Word32 L_var1, Word32 L_var2)

-{

-	Word32 L_var_out;

-	L_var_out = L_var1 - L_var2;

-	if (((L_var1 ^ L_var2) & MIN_32) != 0)

-	{

-		if ((L_var_out ^ L_var1) & MIN_32)

-		{

-			L_var_out = (L_var1 < 0L) ? MIN_32 : MAX_32;

-		}

-	}

-	return (L_var_out);

-}

-

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : mult_r                                                  |

-|                                                                           |

-|   Purpose :                                                               |

-|                                                                           |

-|   Same as mult with rounding, i.e.:                                       |

-|     mult_r(var1,var2) = extract_l(L_shr(((var1 * var2) + 16384),15)) and  |

-|     mult_r(-32768,-32768) = 32767.                                        |

-|                                                                           |

-|   Complexity weight : 2                                                   |

-|                                                                           |

-|   Inputs :                                                                |

-|                                                                           |

-|    var1                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|    var2                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|   Outputs :                                                               |

-|                                                                           |

-|    none                                                                   |

-|                                                                           |

-|   Return Value :                                                          |

-|                                                                           |

-|    var_out                                                                |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |

-|___________________________________________________________________________|

-*/

-

-static_vo Word16 mult_r (Word16 var1, Word16 var2)

-{

-	Word16 var_out;

-	Word32 L_product_arr;

-	L_product_arr = (Word32) var1 *(Word32) var2;       /* product */

-	L_product_arr += (Word32) 0x00004000L;      /* round */

-	L_product_arr &= (Word32) 0xffff8000L;

-	L_product_arr >>= 15;       /* shift */

-	if (L_product_arr & (Word32) 0x00010000L)   /* sign extend when necessary */

-	{

-		L_product_arr |= (Word32) 0xffff0000L;

-	}

-	var_out = saturate (L_product_arr);

-	return (var_out);

-}

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : L_shl                                                   |

-|                                                                           |

-|   Purpose :                                                               |

-|                                                                           |

-|   Arithmetically shift the 32 bit input L_var1 left var2 positions. Zero  |

-|   fill the var2 LSB of the result. If var2 is negative, arithmetically    |

-|   shift L_var1 right by -var2 with sign extension. Saturate the result in |

-|   case of underflows or overflows.                                        |

-|                                                                           |

-|   Complexity weight : 2                                                   |

-|                                                                           |

-|   Inputs :                                                                |

-|                                                                           |

-|    L_var1   32 bit long signed integer (Word32) whose value falls in the  |

-|             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |

-|                                                                           |

-|    var2                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|   Outputs :                                                               |

-|                                                                           |

-|    none                                                                   |

-|                                                                           |

-|   Return Value :                                                          |

-|                                                                           |

-|    L_var_out                                                              |

-|             32 bit long signed integer (Word32) whose value falls in the  |

-|             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |

-|___________________________________________________________________________|

-*/

-

-static_vo Word32 L_shl (Word32 L_var1, Word16 var2)

-{

-	Word32 L_var_out = 0L;

-	if (var2 <= 0)

-	{

-		if (var2 < -32)

-			var2 = -32;

-		L_var_out = (L_var1 >> (Word16)-var2);

-	}

-	else

-	{

-		for (; var2 > 0; var2--)

-		{

-			if (L_var1 > (Word32) 0X3fffffffL)

-			{

-				L_var_out = MAX_32;

-				break;

-			}

-			else

-			{

-				if (L_var1 < (Word32) 0xc0000000L)

-				{

-					//Overflow = 1;

-					L_var_out = MIN_32;

-					break;

-				}

-			}

-			L_var1 *= 2;

-			L_var_out = L_var1;

-		}

-	}

-	return (L_var_out);

-}

-

-static_vo Word32 L_shl2(Word32 L_var1, Word16 var2)

-{

-	Word32 L_var_out = 0L;

-

-	for (; var2 > 0; var2--)

-	{

-		if (L_var1 > (Word32) 0X3fffffffL)

-		{

-			L_var_out = MAX_32;

-			break;

-		}

-		else

-		{

-			if (L_var1 < (Word32) 0xc0000000L)

-			{

-				L_var_out = MIN_32;

-				break;

-			}

-		}

-		L_var1 <<=1 ;

-		L_var_out = L_var1;

-	}

-	return (L_var_out);

-}

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : L_shr                                                   |

-|                                                                           |

-|   Purpose :                                                               |

-|                                                                           |

-|   Arithmetically shift the 32 bit input L_var1 right var2 positions with  |

-|   sign extension. If var2 is negative, arithmetically shift L_var1 left   |

-|   by -var2 and zero fill the -var2 LSB of the result. Saturate the result |

-|   in case of underflows or overflows.                                     |

-|                                                                           |

-|   Complexity weight : 2                                                   |

-|                                                                           |

-|   Inputs :                                                                |

-|                                                                           |

-|    L_var1   32 bit long signed integer (Word32) whose value falls in the  |

-|             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |

-|                                                                           |

-|    var2                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|   Outputs :                                                               |

-|                                                                           |

-|    none                                                                   |

-|                                                                           |

-|   Return Value :                                                          |

-|                                                                           |

-|    L_var_out                                                              |

-|             32 bit long signed integer (Word32) whose value falls in the  |

-|             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |

-|___________________________________________________________________________|

-*/

-

-static_vo Word32 L_shr (Word32 L_var1, Word16 var2)

-{

-	Word32 L_var_out;

-	if (var2 < 0)

-	{

-		if (var2 < -32)

-			var2 = -32;

-		L_var_out = L_shl2(L_var1, (Word16)-var2);

-	}

-	else

-	{

-		if (var2 >= 31)

-		{

-			L_var_out = (L_var1 < 0L) ? -1 : 0;

-		}

-		else

-		{

-			if (L_var1 < 0)

-			{

-				L_var_out = ~((~L_var1) >> var2);

-			}

-			else

-			{

-				L_var_out = L_var1 >> var2;

-			}

-		}

-	}

-	return (L_var_out);

-}

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : L_shr_r                                                 |

-|                                                                           |

-|   Purpose :                                                               |

-|                                                                           |

-|   Same as L_shr(L_var1,var2) but with rounding. Saturate the result in    |

-|   case of underflows or overflows :                                       |

-|    - If var2 is greater than zero :                                       |

-|          if (L_sub(L_shl(L_shr(L_var1,var2),1),L_shr(L_var1,sub(var2,1))))|

-|          is equal to zero                                                 |

-|                     then                                                  |

-|                     L_shr_r(L_var1,var2) = L_shr(L_var1,var2)             |

-|                     else                                                  |

-|                     L_shr_r(L_var1,var2) = L_add(L_shr(L_var1,var2),1)    |

-|    - If var2 is less than or equal to zero :                              |

-|                     L_shr_r(L_var1,var2) = L_shr(L_var1,var2).            |

-|                                                                           |

-|   Complexity weight : 3                                                   |

-|                                                                           |

-|   Inputs :                                                                |

-|                                                                           |

-|    L_var1                                                                 |

-|             32 bit long signed integer (Word32) whose value falls in the  |

-|             range : 0x8000 0000 <= var1 <= 0x7fff ffff.                   |

-|                                                                           |

-|    var2                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|   Outputs :                                                               |

-|                                                                           |

-|    none                                                                   |

-|                                                                           |

-|   Return Value :                                                          |

-|                                                                           |

-|    L_var_out                                                              |

-|             32 bit long signed integer (Word32) whose value falls in the  |

-|             range : 0x8000 0000 <= var_out <= 0x7fff ffff.                |

-|___________________________________________________________________________|

-*/

-

-static_vo Word32 L_shr_r (Word32 L_var1, Word16 var2)

-{

-	Word32 L_var_out;

-	if (var2 > 31)

-	{

-		L_var_out = 0;

-	}

-	else

-	{

-		L_var_out = L_shr (L_var1, var2);

-		if (var2 > 0)

-		{

-			if ((L_var1 & ((Word32) 1 << (var2 - 1))) != 0)

-			{

-				L_var_out++;

-			}

-		}

-	}

-	return (L_var_out);

-}

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : norm_s                                                  |

-|                                                                           |

-|   Purpose :                                                               |

-|                                                                           |

-|   Produces the number of left shift needed to normalize the 16 bit varia- |

-|   ble var1 for positive values on the interval with minimum of 16384 and  |

-|   maximum of 32767, and for negative values on the interval with minimum  |

-|   of -32768 and maximum of -16384; in order to normalize the result, the  |

-|   following operation must be done :                                      |

-|                    norm_var1 = shl(var1,norm_s(var1)).                    |

-|                                                                           |

-|   Complexity weight : 15                                                  |

-|                                                                           |

-|   Inputs :                                                                |

-|                                                                           |

-|    var1                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |

-|                                                                           |

-|   Outputs :                                                               |

-|                                                                           |

-|    none                                                                   |

-|                                                                           |

-|   Return Value :                                                          |

-|                                                                           |

-|    var_out                                                                |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0x0000 0000 <= var_out <= 0x0000 000f.                |

-|___________________________________________________________________________|

-*/

-

-static_vo Word16 norm_s (Word16 var1)

-{

-	Word16 var_out = 0;

-	if (var1 == 0)

-	{

-		var_out = 0;

-	}

-	else

-	{

-		if (var1 == -1)

-		{

-			var_out = 15;

-		}

-		else

-		{

-			if (var1 < 0)

-			{

-				var1 = (Word16)~var1;

-			}

-			for (var_out = 0; var1 < 0x4000; var_out++)

-			{

-				var1 <<= 1;

-			}

-		}

-	}

-	return (var_out);

-}

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : div_s                                                   |

-|                                                                           |

-|   Purpose :                                                               |

-|                                                                           |

-|   Produces a result which is the fractional integer division of var1  by  |

-|   var2; var1 and var2 must be positive and var2 must be greater or equal  |

-|   to var1; the result is positive (leading bit equal to 0) and truncated  |

-|   to 16 bits.                                                             |

-|   If var1 = var2 then div(var1,var2) = 32767.                             |

-|                                                                           |

-|   Complexity weight : 18                                                  |

-|                                                                           |

-|   Inputs :                                                                |

-|                                                                           |

-|    var1                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0x0000 0000 <= var1 <= var2 and var2 != 0.            |

-|                                                                           |

-|    var2                                                                   |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : var1 <= var2 <= 0x0000 7fff and var2 != 0.            |

-|                                                                           |

-|   Outputs :                                                               |

-|                                                                           |

-|    none                                                                   |

-|                                                                           |

-|   Return Value :                                                          |

-|                                                                           |

-|    var_out                                                                |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0x0000 0000 <= var_out <= 0x0000 7fff.                |

-|             It's a Q15 value (point between b15 and b14).                 |

-|___________________________________________________________________________|

-*/

-

-static_vo Word16 div_s (Word16 var1, Word16 var2)

-{

-	Word16 var_out = 0;

-	Word16 iteration;

-	Word32 L_num;

-	Word32 L_denom;

-	if ((var1 < 0) || (var2 < 0))

-	{

-		var_out = MAX_16;

-		return var_out;

-	}

-	if (var2 == 0)

-	{

-		var_out = MAX_16;

-		return var_out;

-	}

-	if (var1 == 0)

-	{

-		var_out = 0;

-	}

-	else

-	{

-		if (var1 == var2)

-		{

-			var_out = MAX_16;

-		}

-		else

-		{

-			L_num = L_deposit_l (var1);

-			L_denom = L_deposit_l(var2);

-			for (iteration = 0; iteration < 15; iteration++)

-			{

-				var_out <<= 1;

-				L_num <<= 1;

-				if (L_num >= L_denom)

-				{

-					L_num -= L_denom;      

-					var_out += 1;          

-				}

-			}

-		}

-	}

-	return (var_out);

-}

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : norm_l                                                  |

-|                                                                           |

-|   Purpose :                                                               |

-|                                                                           |

-|   Produces the number of left shifts needed to normalize the 32 bit varia-|

-|   ble L_var1 for positive values on the interval with minimum of          |

-|   1073741824 and maximum of 2147483647, and for negative values on the in-|

-|   terval with minimum of -2147483648 and maximum of -1073741824; in order |

-|   to normalize the result, the following operation must be done :         |

-|                   norm_L_var1 = L_shl(L_var1,norm_l(L_var1)).             |

-|                                                                           |

-|   Complexity weight : 30                                                  |

-|                                                                           |

-|   Inputs :                                                                |

-|                                                                           |

-|    L_var1                                                                 |

-|             32 bit long signed integer (Word32) whose value falls in the  |

-|             range : 0x8000 0000 <= var1 <= 0x7fff ffff.                   |

-|                                                                           |

-|   Outputs :                                                               |

-|                                                                           |

-|    none                                                                   |

-|                                                                           |

-|   Return Value :                                                          |

-|                                                                           |

-|    var_out                                                                |

-|             16 bit short signed integer (Word16) whose value falls in the |

-|             range : 0x0000 0000 <= var_out <= 0x0000 001f.                |

-|___________________________________________________________________________|

-*/

-

-static_vo Word16 norm_l (Word32 L_var1)

-{

-	Word16 var_out = 0;

-	if (L_var1 != 0)

-	{

-		var_out = 31;

-		if (L_var1 != (Word32) 0xffffffffL)

-		{

-			L_var1 ^= (L_var1 >>31);

-			for (var_out = 0; L_var1 < (Word32) 0x40000000L; var_out++)

-			{

-				L_var1 <<= 1;

-			}

-		}

-	}

-	return (var_out);

-}

-

-#endif //__BASIC_OP_H__

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT 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 __BASIC_OP_H__
+#define __BASIC_OP_H__
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "typedef.h"
+
+#define MAX_32 (Word32)0x7fffffffL
+#define MIN_32 (Word32)0x80000000L
+
+#define MAX_16 (Word16)+32767	/* 0x7fff */
+#define MIN_16 (Word16)-32768	/* 0x8000 */
+
+
+#ifdef LINUX
+#define  static_vo  static __inline__
+#else
+#define  static_vo  static __inline
+#endif
+
+#define saturate(L_var1) (((L_var1) > 0X00007fffL) ? (MAX_16): (((L_var1) < (Word32) 0xffff8000L) ? (MIN_16): ((L_var1) & 0xffff)))
+
+#define abs_s(x)       ((Word16)(((x) != MIN_16) ? (((x) >= 0) ? (x) : (-(x))) : MAX_16))  /* Short abs,           1   */
+#define L_deposit_h(x) (((Word32)(x)) << 16)                                               /* 16 bit var1 -> MSB,     2 */
+#define L_deposit_l(x) ((Word32)(x))                                                       /* 16 bit var1 -> LSB,     2 */
+#define L_abs(x) (((x) != MIN_32) ? (((x) >= 0) ? (x) : (-(x))) : MAX_32)                  /* Long abs,              3*/
+#define negate(var1) ((Word16)(((var1) == MIN_16) ? MAX_16 : (-(var1))))                   /* Short negate,        1*/
+#define L_negate(L_var1) (((L_var1) == (MIN_32)) ? (MAX_32) : (-(L_var1)))                 /* Long negate,     2*/
+
+
+#define extract_h(a)			((Word16)(a >> 16))
+#define extract_l(x)            	(Word16)((x))
+#define add1(a,b)			(a + b)
+#define vo_L_msu(a,b,c)			( a - (( b * c ) << 1) )
+#define vo_mult32(a, b)         ((a) * (b))
+#define vo_mult(a,b)			(( a * b ) >> 15 )
+#define	vo_L_mult(a,b)	    		(((a) * (b)) << 1)
+#define vo_shr_r(var1, var2)   		((var1+((Word16)(1L<<(var2-1))))>>var2)
+#define vo_sub(a,b)			(a - b)
+#define vo_L_deposit_h(a)		((Word32)((a) << 16))
+#define vo_round(a)			((a + 0x00008000) >> 16)
+#define vo_extract_l(a)			((Word16)(a))
+#define vo_L_add(a,b)			(a + b)
+#define vo_L_sub(a,b)			(a - b)
+#define vo_mult_r(a,b)			((( a * b ) + 0x4000 ) >> 15 )
+#define vo_negate(a)		        (-a)
+#define vo_L_shr_r(L_var1, var2)        ((L_var1+((Word32)(1L<<(var2-1))))>>var2)
+
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Prototypes for basic arithmetic operators                               |
+|___________________________________________________________________________|
+*/
+static_vo Word16 add (Word16 var1, Word16 var2);				/* Short add,1 */
+static_vo Word16 sub (Word16 var1, Word16 var2);				/* Short sub,1 */
+static_vo Word16 shl (Word16 var1, Word16 var2);                                /* Short shift left,    1   */
+static_vo Word16 shr (Word16 var1, Word16 var2);                                /* Short shift right,   1   */
+static_vo Word16 mult (Word16 var1, Word16 var2);                               /* Short mult,          1   */
+static_vo Word32 L_mult (Word16 var1, Word16 var2);                             /* Long mult,           1   */
+static_vo Word16 voround (Word32 L_var1);                                       /* Round,               1   */
+static_vo Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2);            	/* Mac,  1  */
+static_vo Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2);   		/* Msu,  1  */
+static_vo Word32 L_add (Word32 L_var1, Word32 L_var2);   		 	/* Long add,        2 */
+static_vo Word32 L_sub (Word32 L_var1, Word32 L_var2);   			/* Long sub,        2 */
+static_vo Word16 mult_r (Word16 var1, Word16 var2);      		 	/* Mult with round, 2 */
+static_vo Word32 L_shl2(Word32 L_var1, Word16 var2);             		/* var2 > 0*/
+static_vo Word32 L_shl (Word32 L_var1, Word16 var2);    	 	 	/* Long shift left, 2 */
+static_vo Word32 L_shr (Word32 L_var1, Word16 var2);    	 	 	/* Long shift right, 2*/
+static_vo Word32 L_shr_r (Word32 L_var1, Word16 var2); 				/* Long shift right with round,  3   */
+static_vo Word16 norm_s (Word16 var1);             				/* Short norm,           15  */
+static_vo Word16 div_s (Word16 var1, Word16 var2); 				/* Short division,       18  */
+static_vo Word16 norm_l (Word32 L_var1);           				/* Long norm,            30  */
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Functions                                                               |
+|___________________________________________________________________________|
+*/
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : add                                                     |
+|                                                                           |
+|   Purpose :                                                               |
+|                                                                           |
+|    Performs the addition (var1+var2) with overflow control and saturation;|
+|    the 16 bit result is set at +32767 when overflow occurs or at -32768   |
+|    when underflow occurs.                                                 |
+|                                                                           |
+|   Complexity weight : 1                                                   |
+|                                                                           |
+|   Inputs :                                                                |
+|                                                                           |
+|    var1                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|    var2                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|   Outputs :                                                               |
+|                                                                           |
+|    none                                                                   |
+|                                                                           |
+|   Return Value :                                                          |
+|                                                                           |
+|    var_out                                                                |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
+|___________________________________________________________________________|
+*/
+static_vo Word16 add (Word16 var1, Word16 var2)
+{
+	Word16 var_out;
+	Word32 L_sum;
+	L_sum = (Word32) var1 + var2;
+	var_out = saturate (L_sum);
+	return (var_out);
+}
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : sub                                                     |
+|                                                                           |
+|   Purpose :                                                               |
+|                                                                           |
+|    Performs the subtraction (var1+var2) with overflow control and satu-   |
+|    ration; the 16 bit result is set at +32767 when overflow occurs or at  |
+|    -32768 when underflow occurs.                                          |
+|                                                                           |
+|   Complexity weight : 1                                                   |
+|                                                                           |
+|   Inputs :                                                                |
+|                                                                           |
+|    var1                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|    var2                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|   Outputs :                                                               |
+|                                                                           |
+|    none                                                                   |
+|                                                                           |
+|   Return Value :                                                          |
+|                                                                           |
+|    var_out                                                                |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
+|___________________________________________________________________________|
+*/
+
+static_vo Word16 sub (Word16 var1, Word16 var2)
+{
+	Word16 var_out;
+	Word32 L_diff;
+	L_diff = (Word32) var1 - var2;
+	var_out = saturate (L_diff);
+	return (var_out);
+}
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : shl                                                     |
+|                                                                           |
+|   Purpose :                                                               |
+|                                                                           |
+|   Arithmetically shift the 16 bit input var1 left var2 positions.Zero fill|
+|   the var2 LSB of the result. If var2 is negative, arithmetically shift   |
+|   var1 right by -var2 with sign extension. Saturate the result in case of |
+|   underflows or overflows.                                                |
+|                                                                           |
+|   Complexity weight : 1                                                   |
+|                                                                           |
+|   Inputs :                                                                |
+|                                                                           |
+|    var1                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|    var2                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|   Outputs :                                                               |
+|                                                                           |
+|    none                                                                   |
+|                                                                           |
+|   Return Value :                                                          |
+|                                                                           |
+|    var_out                                                                |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
+|___________________________________________________________________________|
+*/
+
+static_vo Word16 shl (Word16 var1, Word16 var2)
+{
+	Word16 var_out;
+	Word32 result;
+	if (var2 < 0)
+	{
+		if (var2 < -16)
+			var2 = -16;
+		var_out = var1 >> ((Word16)-var2);
+	}
+	else
+	{
+		result = (Word32) var1 *((Word32) 1 << var2);
+		if ((var2 > 15 && var1 != 0) || (result != (Word32) ((Word16) result)))
+		{
+			var_out = (Word16)((var1 > 0) ? MAX_16 : MIN_16);
+		}
+		else
+		{
+			var_out = extract_l (result);
+		}
+	}
+	return (var_out);
+}
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : shr                                                     |
+|                                                                           |
+|   Purpose :                                                               |
+|                                                                           |
+|   Arithmetically shift the 16 bit input var1 right var2 positions with    |
+|   sign extension. If var2 is negative, arithmetically shift var1 left by  |
+|   -var2 with sign extension. Saturate the result in case of underflows or |
+|   overflows.                                                              |
+|                                                                           |
+|   Complexity weight : 1                                                   |
+|                                                                           |
+|   Inputs :                                                                |
+|                                                                           |
+|    var1                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|    var2                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|   Outputs :                                                               |
+|                                                                           |
+|    none                                                                   |
+|                                                                           |
+|   Return Value :                                                          |
+|                                                                           |
+|    var_out                                                                |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
+|___________________________________________________________________________|
+*/
+
+static_vo Word16 shr (Word16 var1, Word16 var2)
+{
+	Word16 var_out;
+	if (var2 < 0)
+	{
+		if (var2 < -16)
+			var2 = -16;
+		var_out = shl(var1, (Word16)-var2);
+	}
+	else
+	{
+		if (var2 >= 15)
+		{
+			var_out = (Word16)((var1 < 0) ? -1 : 0);
+		}
+		else
+		{
+			if (var1 < 0)
+			{
+				var_out = (Word16)(~((~var1) >> var2));
+			}
+			else
+			{
+				var_out = (Word16)(var1 >> var2);
+			}
+		}
+	}
+	return (var_out);
+}
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : mult                                                    |
+|                                                                           |
+|   Purpose :                                                               |
+|                                                                           |
+|    Performs the multiplication of var1 by var2 and gives a 16 bit result  |
+|    which is scaled i.e.:                                                  |
+|             mult(var1,var2) = extract_l(L_shr((var1 times var2),15)) and  |
+|             mult(-32768,-32768) = 32767.                                  |
+|                                                                           |
+|   Complexity weight : 1                                                   |
+|                                                                           |
+|   Inputs :                                                                |
+|                                                                           |
+|    var1                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|    var2                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|   Outputs :                                                               |
+|                                                                           |
+|    none                                                                   |
+|                                                                           |
+|   Return Value :                                                          |
+|                                                                           |
+|    var_out                                                                |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
+|___________________________________________________________________________|
+*/
+
+static_vo Word16 mult (Word16 var1, Word16 var2)
+{
+	Word16 var_out;
+	Word32 L_product;
+	L_product = (Word32) var1 *(Word32) var2;
+	L_product = (L_product & (Word32) 0xffff8000L) >> 15;
+	if (L_product & (Word32) 0x00010000L)
+		L_product = L_product | (Word32) 0xffff0000L;
+	var_out = saturate (L_product);
+	return (var_out);
+}
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : L_mult                                                  |
+|                                                                           |
+|   Purpose :                                                               |
+|                                                                           |
+|   L_mult is the 32 bit result of the multiplication of var1 times var2    |
+|   with one shift left i.e.:                                               |
+|        L_mult(var1,var2) = L_shl((var1 times var2),1) and                   |
+|        L_mult(-32768,-32768) = 2147483647.                                |
+|                                                                           |
+|   Complexity weight : 1                                                   |
+|                                                                           |
+|   Inputs :                                                                |
+|                                                                           |
+|    var1                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|    var2                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|   Outputs :                                                               |
+|                                                                           |
+|    none                                                                   |
+|                                                                           |
+|   Return Value :                                                          |
+|                                                                           |
+|    L_var_out                                                              |
+|             32 bit long signed integer (Word32) whose value falls in the  |
+|             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
+|___________________________________________________________________________|
+*/
+
+static_vo Word32 L_mult (Word16 var1, Word16 var2)
+{
+	Word32 L_var_out;
+	L_var_out = (Word32) var1 *(Word32) var2;
+	if (L_var_out != (Word32) 0x40000000L)
+	{
+		L_var_out *= 2;
+	}
+	else
+	{
+		L_var_out = MAX_32;
+	}
+	return (L_var_out);
+}
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : round                                                   |
+|                                                                           |
+|   Purpose :                                                               |
+|                                                                           |
+|   Round the lower 16 bits of the 32 bit input number into the MS 16 bits  |
+|   with saturation. Shift the resulting bits right by 16 and return the 16 |
+|   bit number:                                                             |
+|               round(L_var1) = extract_h(L_add(L_var1,32768))              |
+|                                                                           |
+|   Complexity weight : 1                                                   |
+|                                                                           |
+|   Inputs :                                                                |
+|                                                                           |
+|    L_var1                                                                 |
+|             32 bit long signed integer (Word32 ) whose value falls in the |
+|             range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.                 |
+|                                                                           |
+|   Outputs :                                                               |
+|                                                                           |
+|    none                                                                   |
+|                                                                           |
+|   Return Value :                                                          |
+|                                                                           |
+|    var_out                                                                |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
+|___________________________________________________________________________|
+*/
+
+static_vo Word16 voround (Word32 L_var1)
+{
+	Word16 var_out;
+	Word32 L_rounded;
+	L_rounded = L_add (L_var1, (Word32) 0x00008000L);
+	var_out = extract_h (L_rounded);
+	return (var_out);
+}
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : L_mac                                                   |
+|                                                                           |
+|   Purpose :                                                               |
+|                                                                           |
+|   Multiply var1 by var2 and shift the result left by 1. Add the 32 bit    |
+|   result to L_var3 with saturation, return a 32 bit result:               |
+|        L_mac(L_var3,var1,var2) = L_add(L_var3,L_mult(var1,var2)).         |
+|                                                                           |
+|   Complexity weight : 1                                                   |
+|                                                                           |
+|   Inputs :                                                                |
+|                                                                           |
+|    L_var3   32 bit long signed integer (Word32) whose value falls in the  |
+|             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
+|                                                                           |
+|    var1                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|    var2                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|   Outputs :                                                               |
+|                                                                           |
+|    none                                                                   |
+|                                                                           |
+|   Return Value :                                                          |
+|                                                                           |
+|    L_var_out                                                              |
+|             32 bit long signed integer (Word32) whose value falls in the  |
+|             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
+|___________________________________________________________________________|
+*/
+
+static_vo Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2)
+{
+	Word32 L_var_out;
+	Word32 L_product;
+	L_product = ((var1 * var2) << 1);
+	L_var_out = L_add (L_var3, L_product);
+	return (L_var_out);
+}
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : L_msu                                                   |
+|                                                                           |
+|   Purpose :                                                               |
+|                                                                           |
+|   Multiply var1 by var2 and shift the result left by 1. Subtract the 32   |
+|   bit result to L_var3 with saturation, return a 32 bit result:           |
+|        L_msu(L_var3,var1,var2) = L_sub(L_var3,L_mult(var1,var2)).         |
+|                                                                           |
+|   Complexity weight : 1                                                   |
+|                                                                           |
+|   Inputs :                                                                |
+|                                                                           |
+|    L_var3   32 bit long signed integer (Word32) whose value falls in the  |
+|             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
+|                                                                           |
+|    var1                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|    var2                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|   Outputs :                                                               |
+|                                                                           |
+|    none                                                                   |
+|                                                                           |
+|   Return Value :                                                          |
+|                                                                           |
+|    L_var_out                                                              |
+|             32 bit long signed integer (Word32) whose value falls in the  |
+|             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
+|___________________________________________________________________________|
+*/
+
+static_vo Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2)
+{
+	Word32 L_var_out;
+	Word32 L_product;
+	L_product = (var1 * var2)<<1;
+	L_var_out = L_sub (L_var3, L_product);
+	return (L_var_out);
+}
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : L_add                                                   |
+|                                                                           |
+|   Purpose :                                                               |
+|                                                                           |
+|   32 bits addition of the two 32 bits variables (L_var1+L_var2) with      |
+|   overflow control and saturation; the result is set at +2147483647 when  |
+|   overflow occurs or at -2147483648 when underflow occurs.                |
+|                                                                           |
+|   Complexity weight : 2                                                   |
+|                                                                           |
+|   Inputs :                                                                |
+|                                                                           |
+|    L_var1   32 bit long signed integer (Word32) whose value falls in the  |
+|             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
+|                                                                           |
+|    L_var2   32 bit long signed integer (Word32) whose value falls in the  |
+|             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
+|                                                                           |
+|   Outputs :                                                               |
+|                                                                           |
+|    none                                                                   |
+|                                                                           |
+|   Return Value :                                                          |
+|                                                                           |
+|    L_var_out                                                              |
+|             32 bit long signed integer (Word32) whose value falls in the  |
+|             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
+|___________________________________________________________________________|
+*/
+
+static_vo Word32 L_add (Word32 L_var1, Word32 L_var2)
+{
+	Word32 L_var_out;
+	L_var_out = L_var1 + L_var2;
+	if (((L_var1 ^ L_var2) & MIN_32) == 0)
+	{
+		if ((L_var_out ^ L_var1) & MIN_32)
+		{
+			L_var_out = (L_var1 < 0) ? MIN_32 : MAX_32;
+		}
+	}
+	return (L_var_out);
+}
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : L_sub                                                   |
+|                                                                           |
+|   Purpose :                                                               |
+|                                                                           |
+|   32 bits subtraction of the two 32 bits variables (L_var1-L_var2) with   |
+|   overflow control and saturation; the result is set at +2147483647 when  |
+|   overflow occurs or at -2147483648 when underflow occurs.                |
+|                                                                           |
+|   Complexity weight : 2                                                   |
+|                                                                           |
+|   Inputs :                                                                |
+|                                                                           |
+|    L_var1   32 bit long signed integer (Word32) whose value falls in the  |
+|             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
+|                                                                           |
+|    L_var2   32 bit long signed integer (Word32) whose value falls in the  |
+|             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
+|                                                                           |
+|   Outputs :                                                               |
+|                                                                           |
+|    none                                                                   |
+|                                                                           |
+|   Return Value :                                                          |
+|                                                                           |
+|    L_var_out                                                              |
+|             32 bit long signed integer (Word32) whose value falls in the  |
+|             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
+|___________________________________________________________________________|
+*/
+
+static_vo Word32 L_sub (Word32 L_var1, Word32 L_var2)
+{
+	Word32 L_var_out;
+	L_var_out = L_var1 - L_var2;
+	if (((L_var1 ^ L_var2) & MIN_32) != 0)
+	{
+		if ((L_var_out ^ L_var1) & MIN_32)
+		{
+			L_var_out = (L_var1 < 0L) ? MIN_32 : MAX_32;
+		}
+	}
+	return (L_var_out);
+}
+
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : mult_r                                                  |
+|                                                                           |
+|   Purpose :                                                               |
+|                                                                           |
+|   Same as mult with rounding, i.e.:                                       |
+|     mult_r(var1,var2) = extract_l(L_shr(((var1 * var2) + 16384),15)) and  |
+|     mult_r(-32768,-32768) = 32767.                                        |
+|                                                                           |
+|   Complexity weight : 2                                                   |
+|                                                                           |
+|   Inputs :                                                                |
+|                                                                           |
+|    var1                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|    var2                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|   Outputs :                                                               |
+|                                                                           |
+|    none                                                                   |
+|                                                                           |
+|   Return Value :                                                          |
+|                                                                           |
+|    var_out                                                                |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
+|___________________________________________________________________________|
+*/
+
+static_vo Word16 mult_r (Word16 var1, Word16 var2)
+{
+	Word16 var_out;
+	Word32 L_product_arr;
+	L_product_arr = (Word32) var1 *(Word32) var2;       /* product */
+	L_product_arr += (Word32) 0x00004000L;      /* round */
+	L_product_arr &= (Word32) 0xffff8000L;
+	L_product_arr >>= 15;       /* shift */
+	if (L_product_arr & (Word32) 0x00010000L)   /* sign extend when necessary */
+	{
+		L_product_arr |= (Word32) 0xffff0000L;
+	}
+	var_out = saturate (L_product_arr);
+	return (var_out);
+}
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : L_shl                                                   |
+|                                                                           |
+|   Purpose :                                                               |
+|                                                                           |
+|   Arithmetically shift the 32 bit input L_var1 left var2 positions. Zero  |
+|   fill the var2 LSB of the result. If var2 is negative, arithmetically    |
+|   shift L_var1 right by -var2 with sign extension. Saturate the result in |
+|   case of underflows or overflows.                                        |
+|                                                                           |
+|   Complexity weight : 2                                                   |
+|                                                                           |
+|   Inputs :                                                                |
+|                                                                           |
+|    L_var1   32 bit long signed integer (Word32) whose value falls in the  |
+|             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
+|                                                                           |
+|    var2                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|   Outputs :                                                               |
+|                                                                           |
+|    none                                                                   |
+|                                                                           |
+|   Return Value :                                                          |
+|                                                                           |
+|    L_var_out                                                              |
+|             32 bit long signed integer (Word32) whose value falls in the  |
+|             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
+|___________________________________________________________________________|
+*/
+
+static_vo Word32 L_shl (Word32 L_var1, Word16 var2)
+{
+	Word32 L_var_out = 0L;
+	if (var2 <= 0)
+	{
+		if (var2 < -32)
+			var2 = -32;
+		L_var_out = (L_var1 >> (Word16)-var2);
+	}
+	else
+	{
+		for (; var2 > 0; var2--)
+		{
+			if (L_var1 > (Word32) 0X3fffffffL)
+			{
+				L_var_out = MAX_32;
+				break;
+			}
+			else
+			{
+				if (L_var1 < (Word32) 0xc0000000L)
+				{
+					//Overflow = 1;
+					L_var_out = MIN_32;
+					break;
+				}
+			}
+			L_var1 *= 2;
+			L_var_out = L_var1;
+		}
+	}
+	return (L_var_out);
+}
+
+static_vo Word32 L_shl2(Word32 L_var1, Word16 var2)
+{
+	Word32 L_var_out = 0L;
+
+	for (; var2 > 0; var2--)
+	{
+		if (L_var1 > (Word32) 0X3fffffffL)
+		{
+			L_var_out = MAX_32;
+			break;
+		}
+		else
+		{
+			if (L_var1 < (Word32) 0xc0000000L)
+			{
+				L_var_out = MIN_32;
+				break;
+			}
+		}
+		L_var1 <<=1 ;
+		L_var_out = L_var1;
+	}
+	return (L_var_out);
+}
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : L_shr                                                   |
+|                                                                           |
+|   Purpose :                                                               |
+|                                                                           |
+|   Arithmetically shift the 32 bit input L_var1 right var2 positions with  |
+|   sign extension. If var2 is negative, arithmetically shift L_var1 left   |
+|   by -var2 and zero fill the -var2 LSB of the result. Saturate the result |
+|   in case of underflows or overflows.                                     |
+|                                                                           |
+|   Complexity weight : 2                                                   |
+|                                                                           |
+|   Inputs :                                                                |
+|                                                                           |
+|    L_var1   32 bit long signed integer (Word32) whose value falls in the  |
+|             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
+|                                                                           |
+|    var2                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|   Outputs :                                                               |
+|                                                                           |
+|    none                                                                   |
+|                                                                           |
+|   Return Value :                                                          |
+|                                                                           |
+|    L_var_out                                                              |
+|             32 bit long signed integer (Word32) whose value falls in the  |
+|             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
+|___________________________________________________________________________|
+*/
+
+static_vo Word32 L_shr (Word32 L_var1, Word16 var2)
+{
+	Word32 L_var_out;
+	if (var2 < 0)
+	{
+		if (var2 < -32)
+			var2 = -32;
+		L_var_out = L_shl2(L_var1, (Word16)-var2);
+	}
+	else
+	{
+		if (var2 >= 31)
+		{
+			L_var_out = (L_var1 < 0L) ? -1 : 0;
+		}
+		else
+		{
+			if (L_var1 < 0)
+			{
+				L_var_out = ~((~L_var1) >> var2);
+			}
+			else
+			{
+				L_var_out = L_var1 >> var2;
+			}
+		}
+	}
+	return (L_var_out);
+}
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : L_shr_r                                                 |
+|                                                                           |
+|   Purpose :                                                               |
+|                                                                           |
+|   Same as L_shr(L_var1,var2) but with rounding. Saturate the result in    |
+|   case of underflows or overflows :                                       |
+|    - If var2 is greater than zero :                                       |
+|          if (L_sub(L_shl(L_shr(L_var1,var2),1),L_shr(L_var1,sub(var2,1))))|
+|          is equal to zero                                                 |
+|                     then                                                  |
+|                     L_shr_r(L_var1,var2) = L_shr(L_var1,var2)             |
+|                     else                                                  |
+|                     L_shr_r(L_var1,var2) = L_add(L_shr(L_var1,var2),1)    |
+|    - If var2 is less than or equal to zero :                              |
+|                     L_shr_r(L_var1,var2) = L_shr(L_var1,var2).            |
+|                                                                           |
+|   Complexity weight : 3                                                   |
+|                                                                           |
+|   Inputs :                                                                |
+|                                                                           |
+|    L_var1                                                                 |
+|             32 bit long signed integer (Word32) whose value falls in the  |
+|             range : 0x8000 0000 <= var1 <= 0x7fff ffff.                   |
+|                                                                           |
+|    var2                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|   Outputs :                                                               |
+|                                                                           |
+|    none                                                                   |
+|                                                                           |
+|   Return Value :                                                          |
+|                                                                           |
+|    L_var_out                                                              |
+|             32 bit long signed integer (Word32) whose value falls in the  |
+|             range : 0x8000 0000 <= var_out <= 0x7fff ffff.                |
+|___________________________________________________________________________|
+*/
+
+static_vo Word32 L_shr_r (Word32 L_var1, Word16 var2)
+{
+	Word32 L_var_out;
+	if (var2 > 31)
+	{
+		L_var_out = 0;
+	}
+	else
+	{
+		L_var_out = L_shr (L_var1, var2);
+		if (var2 > 0)
+		{
+			if ((L_var1 & ((Word32) 1 << (var2 - 1))) != 0)
+			{
+				L_var_out++;
+			}
+		}
+	}
+	return (L_var_out);
+}
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : norm_s                                                  |
+|                                                                           |
+|   Purpose :                                                               |
+|                                                                           |
+|   Produces the number of left shift needed to normalize the 16 bit varia- |
+|   ble var1 for positive values on the interval with minimum of 16384 and  |
+|   maximum of 32767, and for negative values on the interval with minimum  |
+|   of -32768 and maximum of -16384; in order to normalize the result, the  |
+|   following operation must be done :                                      |
+|                    norm_var1 = shl(var1,norm_s(var1)).                    |
+|                                                                           |
+|   Complexity weight : 15                                                  |
+|                                                                           |
+|   Inputs :                                                                |
+|                                                                           |
+|    var1                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
+|                                                                           |
+|   Outputs :                                                               |
+|                                                                           |
+|    none                                                                   |
+|                                                                           |
+|   Return Value :                                                          |
+|                                                                           |
+|    var_out                                                                |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0x0000 0000 <= var_out <= 0x0000 000f.                |
+|___________________________________________________________________________|
+*/
+
+static_vo Word16 norm_s (Word16 var1)
+{
+	Word16 var_out = 0;
+	if (var1 == 0)
+	{
+		var_out = 0;
+	}
+	else
+	{
+		if (var1 == -1)
+		{
+			var_out = 15;
+		}
+		else
+		{
+			if (var1 < 0)
+			{
+				var1 = (Word16)~var1;
+			}
+			for (var_out = 0; var1 < 0x4000; var_out++)
+			{
+				var1 <<= 1;
+			}
+		}
+	}
+	return (var_out);
+}
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : div_s                                                   |
+|                                                                           |
+|   Purpose :                                                               |
+|                                                                           |
+|   Produces a result which is the fractional integer division of var1  by  |
+|   var2; var1 and var2 must be positive and var2 must be greater or equal  |
+|   to var1; the result is positive (leading bit equal to 0) and truncated  |
+|   to 16 bits.                                                             |
+|   If var1 = var2 then div(var1,var2) = 32767.                             |
+|                                                                           |
+|   Complexity weight : 18                                                  |
+|                                                                           |
+|   Inputs :                                                                |
+|                                                                           |
+|    var1                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0x0000 0000 <= var1 <= var2 and var2 != 0.            |
+|                                                                           |
+|    var2                                                                   |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : var1 <= var2 <= 0x0000 7fff and var2 != 0.            |
+|                                                                           |
+|   Outputs :                                                               |
+|                                                                           |
+|    none                                                                   |
+|                                                                           |
+|   Return Value :                                                          |
+|                                                                           |
+|    var_out                                                                |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0x0000 0000 <= var_out <= 0x0000 7fff.                |
+|             It's a Q15 value (point between b15 and b14).                 |
+|___________________________________________________________________________|
+*/
+
+static_vo Word16 div_s (Word16 var1, Word16 var2)
+{
+	Word16 var_out = 0;
+	Word16 iteration;
+	Word32 L_num;
+	Word32 L_denom;
+	if ((var1 < 0) || (var2 < 0))
+	{
+		var_out = MAX_16;
+		return var_out;
+	}
+	if (var2 == 0)
+	{
+		var_out = MAX_16;
+		return var_out;
+	}
+	if (var1 == 0)
+	{
+		var_out = 0;
+	}
+	else
+	{
+		if (var1 == var2)
+		{
+			var_out = MAX_16;
+		}
+		else
+		{
+			L_num = L_deposit_l (var1);
+			L_denom = L_deposit_l(var2);
+			for (iteration = 0; iteration < 15; iteration++)
+			{
+				var_out <<= 1;
+				L_num <<= 1;
+				if (L_num >= L_denom)
+				{
+					L_num -= L_denom;
+					var_out += 1;
+				}
+			}
+		}
+	}
+	return (var_out);
+}
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : norm_l                                                  |
+|                                                                           |
+|   Purpose :                                                               |
+|                                                                           |
+|   Produces the number of left shifts needed to normalize the 32 bit varia-|
+|   ble L_var1 for positive values on the interval with minimum of          |
+|   1073741824 and maximum of 2147483647, and for negative values on the in-|
+|   terval with minimum of -2147483648 and maximum of -1073741824; in order |
+|   to normalize the result, the following operation must be done :         |
+|                   norm_L_var1 = L_shl(L_var1,norm_l(L_var1)).             |
+|                                                                           |
+|   Complexity weight : 30                                                  |
+|                                                                           |
+|   Inputs :                                                                |
+|                                                                           |
+|    L_var1                                                                 |
+|             32 bit long signed integer (Word32) whose value falls in the  |
+|             range : 0x8000 0000 <= var1 <= 0x7fff ffff.                   |
+|                                                                           |
+|   Outputs :                                                               |
+|                                                                           |
+|    none                                                                   |
+|                                                                           |
+|   Return Value :                                                          |
+|                                                                           |
+|    var_out                                                                |
+|             16 bit short signed integer (Word16) whose value falls in the |
+|             range : 0x0000 0000 <= var_out <= 0x0000 001f.                |
+|___________________________________________________________________________|
+*/
+
+static_vo Word16 norm_l (Word32 L_var1)
+{
+	Word16 var_out = 0;
+	if (L_var1 != 0)
+	{
+		var_out = 31;
+		if (L_var1 != (Word32) 0xffffffffL)
+		{
+			L_var1 ^= (L_var1 >>31);
+			for (var_out = 0; L_var1 < (Word32) 0x40000000L; var_out++)
+			{
+				L_var1 <<= 1;
+			}
+		}
+	}
+	return (var_out);
+}
+
+#endif //__BASIC_OP_H__
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/bits.h b/media/libstagefright/codecs/amrwbenc/inc/bits.h
index 77146de..e880684 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/bits.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/bits.h
@@ -1,92 +1,92 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/*--------------------------------------------------------------------------*

-*                         BITS.H                                           *

-*--------------------------------------------------------------------------*

-*       Number of bits for different modes			           *

-*--------------------------------------------------------------------------*/

-

-#ifndef __BITS_H__

-#define __BITS_H__

-

-#include <stdio.h>

-#include "typedef.h"

-#include "cnst.h"

-#include "cod_main.h"

-

-#define NBBITS_7k     132                  /* 6.60k  */

-#define NBBITS_9k     177                  /* 8.85k  */

-#define NBBITS_12k    253                  /* 12.65k */

-#define NBBITS_14k    285                  /* 14.25k */

-#define NBBITS_16k    317                  /* 15.85k */

-#define NBBITS_18k    365                  /* 18.25k */

-#define NBBITS_20k    397                  /* 19.85k */

-#define NBBITS_23k    461                  /* 23.05k */

-#define NBBITS_24k    477                  /* 23.85k */

-

-#define NBBITS_SID    35

-#define NB_BITS_MAX   NBBITS_24k

-

-#define BIT_0     (Word16)-127

-#define BIT_1     (Word16)127

-#define BIT_0_ITU (Word16)0x007F

-#define BIT_1_ITU (Word16)0x0081

-

-#define SIZE_MAX1  (3+NB_BITS_MAX)          /* serial size max */

-#define TX_FRAME_TYPE (Word16)0x6b21

-#define RX_FRAME_TYPE (Word16)0x6b20

-

-static const Word16 nb_of_bits[NUM_OF_MODES] = {

-	NBBITS_7k,

-	NBBITS_9k,

-	NBBITS_12k,

-	NBBITS_14k,

-	NBBITS_16k,

-	NBBITS_18k,

-	NBBITS_20k,

-	NBBITS_23k,

-	NBBITS_24k,

-	NBBITS_SID

-};

-

-/*typedef struct

-{

-Word16 sid_update_counter;

-Word16 sid_handover_debt;

-Word16 prev_ft;

-} TX_State;

-*/

-

-//typedef struct

-//{

-//	Word16 prev_ft;

-//	Word16 prev_mode;

-//} RX_State;

-

-int PackBits(Word16 prms[], Word16 coding_mode, Word16 mode, Coder_State *st);

-

-

-void Parm_serial(

-		Word16 value,                         /* input : parameter value */

-		Word16 no_of_bits,                    /* input : number of bits  */

-		Word16 ** prms

-		);

-

-

-#endif  //__BITS_H__

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/*--------------------------------------------------------------------------*
+*                         BITS.H                                           *
+*--------------------------------------------------------------------------*
+*       Number of bits for different modes			           *
+*--------------------------------------------------------------------------*/
+
+#ifndef __BITS_H__
+#define __BITS_H__
+
+#include <stdio.h>
+#include "typedef.h"
+#include "cnst.h"
+#include "cod_main.h"
+
+#define NBBITS_7k     132                  /* 6.60k  */
+#define NBBITS_9k     177                  /* 8.85k  */
+#define NBBITS_12k    253                  /* 12.65k */
+#define NBBITS_14k    285                  /* 14.25k */
+#define NBBITS_16k    317                  /* 15.85k */
+#define NBBITS_18k    365                  /* 18.25k */
+#define NBBITS_20k    397                  /* 19.85k */
+#define NBBITS_23k    461                  /* 23.05k */
+#define NBBITS_24k    477                  /* 23.85k */
+
+#define NBBITS_SID    35
+#define NB_BITS_MAX   NBBITS_24k
+
+#define BIT_0     (Word16)-127
+#define BIT_1     (Word16)127
+#define BIT_0_ITU (Word16)0x007F
+#define BIT_1_ITU (Word16)0x0081
+
+#define SIZE_MAX1  (3+NB_BITS_MAX)          /* serial size max */
+#define TX_FRAME_TYPE (Word16)0x6b21
+#define RX_FRAME_TYPE (Word16)0x6b20
+
+static const Word16 nb_of_bits[NUM_OF_MODES] = {
+	NBBITS_7k,
+	NBBITS_9k,
+	NBBITS_12k,
+	NBBITS_14k,
+	NBBITS_16k,
+	NBBITS_18k,
+	NBBITS_20k,
+	NBBITS_23k,
+	NBBITS_24k,
+	NBBITS_SID
+};
+
+/*typedef struct
+{
+Word16 sid_update_counter;
+Word16 sid_handover_debt;
+Word16 prev_ft;
+} TX_State;
+*/
+
+//typedef struct
+//{
+//	Word16 prev_ft;
+//	Word16 prev_mode;
+//} RX_State;
+
+int PackBits(Word16 prms[], Word16 coding_mode, Word16 mode, Coder_State *st);
+
+
+void Parm_serial(
+		Word16 value,                         /* input : parameter value */
+		Word16 no_of_bits,                    /* input : number of bits  */
+		Word16 ** prms
+		);
+
+
+#endif  //__BITS_H__
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/cnst.h b/media/libstagefright/codecs/amrwbenc/inc/cnst.h
index ffdbd88..5395d2d 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/cnst.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/cnst.h
@@ -1,81 +1,81 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/*--------------------------------------------------------------------------*

- *                         CNST.H                                           *

- *--------------------------------------------------------------------------*

- *       Codec constant parameters (coder and decoder)                      *

- *--------------------------------------------------------------------------*/

-

-#ifndef __CNST_H__

-#define __CNST_H__

-

-#define L_FRAME16k   320                   /* Frame size at 16kHz                        */

-#define L_FRAME      256                   /* Frame size                                 */

-#define L_SUBFR16k   80                    /* Subframe size at 16kHz                     */

-

-#define L_SUBFR      64                    /* Subframe size                              */

-#define NB_SUBFR     4                     /* Number of subframe per frame               */

-

-#define L_NEXT       64                    /* Overhead in LP analysis                    */

-#define L_WINDOW     384                   /* window size in LP analysis                 */

-#define L_TOTAL      384                   /* Total size of speech buffer.               */

-#define M            16                    /* Order of LP filter                         */

-#define M16k         20

-

-#define L_FILT16k    15                    /* Delay of down-sampling filter              */

-#define L_FILT       12                    /* Delay of up-sampling filter                */

-

-#define GP_CLIP      15565                 /* Pitch gain clipping = 0.95 Q14             */

-#define PIT_SHARP    27853                 /* pitch sharpening factor = 0.85 Q15         */

-

-#define PIT_MIN      34                    /* Minimum pitch lag with resolution 1/4      */

-#define PIT_FR2      128                   /* Minimum pitch lag with resolution 1/2      */

-#define PIT_FR1_9b   160                   /* Minimum pitch lag with resolution 1        */

-#define PIT_FR1_8b   92                    /* Minimum pitch lag with resolution 1        */

-#define PIT_MAX      231                   /* Maximum pitch lag                          */

-#define L_INTERPOL   (16+1)                /* Length of filter for interpolation         */

-

-#define OPL_DECIM    2                     /* Decimation in open-loop pitch analysis     */

-

-#define PREEMPH_FAC  22282                 /* preemphasis factor (0.68 in Q15)           */

-#define GAMMA1       30147                 /* Weighting factor (numerator) (0.92 in Q15) */

-#define TILT_FAC     22282                 /* tilt factor (denominator) (0.68 in Q15)    */

-

-#define Q_MAX        8                     /* scaling max for signal (see syn_filt_32)   */

-

-#define RANDOM_INITSEED  21845             /* own random init value                      */

-

-#define L_MEANBUF        3

-#define ONE_PER_MEANBUF 10923

-

-#define MODE_7k       0

-#define MODE_9k       1

-#define MODE_12k      2

-#define MODE_14k      3

-#define MODE_16k      4

-#define MODE_18k      5

-#define MODE_20k      6

-#define MODE_23k      7

-#define MODE_24k      8

-#define MRDTX         9

-#define NUM_OF_MODES  10                   /* see bits.h for bits definition             */

-

-#define EHF_MASK (Word16)0x0008            /* homing frame pattern                       */

-

-#endif //__CNST_H__

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/*--------------------------------------------------------------------------*
+ *                         CNST.H                                           *
+ *--------------------------------------------------------------------------*
+ *       Codec constant parameters (coder and decoder)                      *
+ *--------------------------------------------------------------------------*/
+
+#ifndef __CNST_H__
+#define __CNST_H__
+
+#define L_FRAME16k   320                   /* Frame size at 16kHz                        */
+#define L_FRAME      256                   /* Frame size                                 */
+#define L_SUBFR16k   80                    /* Subframe size at 16kHz                     */
+
+#define L_SUBFR      64                    /* Subframe size                              */
+#define NB_SUBFR     4                     /* Number of subframe per frame               */
+
+#define L_NEXT       64                    /* Overhead in LP analysis                    */
+#define L_WINDOW     384                   /* window size in LP analysis                 */
+#define L_TOTAL      384                   /* Total size of speech buffer.               */
+#define M            16                    /* Order of LP filter                         */
+#define M16k         20
+
+#define L_FILT16k    15                    /* Delay of down-sampling filter              */
+#define L_FILT       12                    /* Delay of up-sampling filter                */
+
+#define GP_CLIP      15565                 /* Pitch gain clipping = 0.95 Q14             */
+#define PIT_SHARP    27853                 /* pitch sharpening factor = 0.85 Q15         */
+
+#define PIT_MIN      34                    /* Minimum pitch lag with resolution 1/4      */
+#define PIT_FR2      128                   /* Minimum pitch lag with resolution 1/2      */
+#define PIT_FR1_9b   160                   /* Minimum pitch lag with resolution 1        */
+#define PIT_FR1_8b   92                    /* Minimum pitch lag with resolution 1        */
+#define PIT_MAX      231                   /* Maximum pitch lag                          */
+#define L_INTERPOL   (16+1)                /* Length of filter for interpolation         */
+
+#define OPL_DECIM    2                     /* Decimation in open-loop pitch analysis     */
+
+#define PREEMPH_FAC  22282                 /* preemphasis factor (0.68 in Q15)           */
+#define GAMMA1       30147                 /* Weighting factor (numerator) (0.92 in Q15) */
+#define TILT_FAC     22282                 /* tilt factor (denominator) (0.68 in Q15)    */
+
+#define Q_MAX        8                     /* scaling max for signal (see syn_filt_32)   */
+
+#define RANDOM_INITSEED  21845             /* own random init value                      */
+
+#define L_MEANBUF        3
+#define ONE_PER_MEANBUF 10923
+
+#define MODE_7k       0
+#define MODE_9k       1
+#define MODE_12k      2
+#define MODE_14k      3
+#define MODE_16k      4
+#define MODE_18k      5
+#define MODE_20k      6
+#define MODE_23k      7
+#define MODE_24k      8
+#define MRDTX         9
+#define NUM_OF_MODES  10                   /* see bits.h for bits definition             */
+
+#define EHF_MASK (Word16)0x0008            /* homing frame pattern                       */
+
+#endif //__CNST_H__
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/cod_main.h b/media/libstagefright/codecs/amrwbenc/inc/cod_main.h
index 1fd5787..53ca55e 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/cod_main.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/cod_main.h
@@ -1,103 +1,103 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/*--------------------------------------------------------------------------*

- *                         COD_MAIN.H                                       *

- *--------------------------------------------------------------------------*

- *       Static memory in the encoder				            *

- *--------------------------------------------------------------------------*/

-#ifndef __COD_MAIN_H__

-#define __COD_MAIN_H__

-

-#include "cnst.h"                          /* coder constant parameters */

-

-#include "wb_vad.h"

-#include "dtx.h"

-#include "stream.h"

-#include "voAMRWB.h"

-

-typedef struct

-{

-    Word16 mem_decim[2 * L_FILT16k];       /* speech decimated filter memory */

-    Word16 mem_sig_in[6];                  /* hp50 filter memory */

-    Word16 mem_preemph;                    /* speech preemph filter memory */

-    Word16 old_speech[L_TOTAL - L_FRAME];  /* old speech vector at 12.8kHz */

-    Word16 old_wsp[PIT_MAX / OPL_DECIM];   /* old decimated weighted speech vector */

-    Word16 old_exc[PIT_MAX + L_INTERPOL];  /* old excitation vector */

-    Word16 mem_levinson[M + 2];            /* levinson routine memory */

-    Word16 ispold[M];                      /* old isp (immittance spectral pairs) */

-    Word16 ispold_q[M];                    /* quantized old isp */

-    Word16 past_isfq[M];                   /* past isf quantizer */

-    Word16 mem_wsp;                        /* wsp vector memory */

-    Word16 mem_decim2[3];                  /* wsp decimation filter memory */

-    Word16 mem_w0;                         /* target vector memory */

-    Word16 mem_syn[M];                     /* synthesis memory */

-    Word16 tilt_code;                      /* tilt of code */

-    Word16 old_wsp_max;                    /* old wsp maximum value */

-    Word16 old_wsp_shift;                  /* old wsp shift */

-    Word16 Q_old;                          /* old scaling factor */

-    Word16 Q_max[2];                       /* old maximum scaling factor */

-    Word16 gp_clip[2];                     /* gain of pitch clipping memory */

-    Word16 qua_gain[4];                    /* gain quantizer memory */

-

-    Word16 old_T0_med;

-    Word16 ol_gain;

-    Word16 ada_w;

-    Word16 ol_wght_flg;

-    Word16 old_ol_lag[5];

-    Word16 hp_wsp_mem[9];

-    Word16 old_hp_wsp[L_FRAME / OPL_DECIM + (PIT_MAX / OPL_DECIM)];

-    VadVars *vadSt;

-    dtx_encState *dtx_encSt;

-    Word16 first_frame;

-    Word16 isfold[M];                      /* old isf (frequency domain) */

-    Word32 L_gc_thres;                     /* threshold for noise enhancer */

-    Word16 mem_syn_hi[M];                  /* modified synthesis memory (MSB) */

-    Word16 mem_syn_lo[M];                  /* modified synthesis memory (LSB) */

-    Word16 mem_deemph;                     /* speech deemph filter memory */

-    Word16 mem_sig_out[6];                 /* hp50 filter memory for synthesis */

-    Word16 mem_hp400[6];                   /* hp400 filter memory for synthesis */

-    Word16 mem_oversamp[2 * L_FILT];       /* synthesis oversampled filter memory */

-    Word16 mem_syn_hf[M];                  /* HF synthesis memory */

-    Word16 mem_hf[2 * L_FILT16k];          /* HF band-pass filter memory */

-    Word16 mem_hf2[2 * L_FILT16k];         /* HF band-pass filter memory */

-    Word16 seed2;                          /* random memory for HF generation */

-    Word16 vad_hist;

-    Word16 gain_alpha;

-    /*  TX_State structure  */

-	Word16 sid_update_counter;

-    Word16 sid_handover_debt;

-    Word16 prev_ft;

-	Word16 allow_dtx;

-	/*some input/output buffer parameters */

-	unsigned char       *inputStream;

-	int			        inputSize;

-	VOAMRWBMODE  		mode;

-	VOAMRWBFRAMETYPE	frameType;

-	unsigned short      *outputStream;

-	int			        outputSize;

-	FrameStream         *stream;

-	VO_MEM_OPERATOR     *pvoMemop;

-	VO_MEM_OPERATOR     voMemoprator;

-	VO_PTR              hCheck;

-} Coder_State;

-

-typedef void* HAMRENC;

-

-#endif  //__COD_MAIN_H__

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/*--------------------------------------------------------------------------*
+ *                         COD_MAIN.H                                       *
+ *--------------------------------------------------------------------------*
+ *       Static memory in the encoder				            *
+ *--------------------------------------------------------------------------*/
+#ifndef __COD_MAIN_H__
+#define __COD_MAIN_H__
+
+#include "cnst.h"                          /* coder constant parameters */
+
+#include "wb_vad.h"
+#include "dtx.h"
+#include "stream.h"
+#include "voAMRWB.h"
+
+typedef struct
+{
+    Word16 mem_decim[2 * L_FILT16k];       /* speech decimated filter memory */
+    Word16 mem_sig_in[6];                  /* hp50 filter memory */
+    Word16 mem_preemph;                    /* speech preemph filter memory */
+    Word16 old_speech[L_TOTAL - L_FRAME];  /* old speech vector at 12.8kHz */
+    Word16 old_wsp[PIT_MAX / OPL_DECIM];   /* old decimated weighted speech vector */
+    Word16 old_exc[PIT_MAX + L_INTERPOL];  /* old excitation vector */
+    Word16 mem_levinson[M + 2];            /* levinson routine memory */
+    Word16 ispold[M];                      /* old isp (immittance spectral pairs) */
+    Word16 ispold_q[M];                    /* quantized old isp */
+    Word16 past_isfq[M];                   /* past isf quantizer */
+    Word16 mem_wsp;                        /* wsp vector memory */
+    Word16 mem_decim2[3];                  /* wsp decimation filter memory */
+    Word16 mem_w0;                         /* target vector memory */
+    Word16 mem_syn[M];                     /* synthesis memory */
+    Word16 tilt_code;                      /* tilt of code */
+    Word16 old_wsp_max;                    /* old wsp maximum value */
+    Word16 old_wsp_shift;                  /* old wsp shift */
+    Word16 Q_old;                          /* old scaling factor */
+    Word16 Q_max[2];                       /* old maximum scaling factor */
+    Word16 gp_clip[2];                     /* gain of pitch clipping memory */
+    Word16 qua_gain[4];                    /* gain quantizer memory */
+
+    Word16 old_T0_med;
+    Word16 ol_gain;
+    Word16 ada_w;
+    Word16 ol_wght_flg;
+    Word16 old_ol_lag[5];
+    Word16 hp_wsp_mem[9];
+    Word16 old_hp_wsp[L_FRAME / OPL_DECIM + (PIT_MAX / OPL_DECIM)];
+    VadVars *vadSt;
+    dtx_encState *dtx_encSt;
+    Word16 first_frame;
+    Word16 isfold[M];                      /* old isf (frequency domain) */
+    Word32 L_gc_thres;                     /* threshold for noise enhancer */
+    Word16 mem_syn_hi[M];                  /* modified synthesis memory (MSB) */
+    Word16 mem_syn_lo[M];                  /* modified synthesis memory (LSB) */
+    Word16 mem_deemph;                     /* speech deemph filter memory */
+    Word16 mem_sig_out[6];                 /* hp50 filter memory for synthesis */
+    Word16 mem_hp400[6];                   /* hp400 filter memory for synthesis */
+    Word16 mem_oversamp[2 * L_FILT];       /* synthesis oversampled filter memory */
+    Word16 mem_syn_hf[M];                  /* HF synthesis memory */
+    Word16 mem_hf[2 * L_FILT16k];          /* HF band-pass filter memory */
+    Word16 mem_hf2[2 * L_FILT16k];         /* HF band-pass filter memory */
+    Word16 seed2;                          /* random memory for HF generation */
+    Word16 vad_hist;
+    Word16 gain_alpha;
+    /*  TX_State structure  */
+	Word16 sid_update_counter;
+    Word16 sid_handover_debt;
+    Word16 prev_ft;
+	Word16 allow_dtx;
+	/*some input/output buffer parameters */
+	unsigned char       *inputStream;
+	int			        inputSize;
+	VOAMRWBMODE  		mode;
+	VOAMRWBFRAMETYPE	frameType;
+	unsigned short      *outputStream;
+	int			        outputSize;
+	FrameStream         *stream;
+	VO_MEM_OPERATOR     *pvoMemop;
+	VO_MEM_OPERATOR     voMemoprator;
+	VO_PTR              hCheck;
+} Coder_State;
+
+typedef void* HAMRENC;
+
+#endif  //__COD_MAIN_H__
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/dtx.h b/media/libstagefright/codecs/amrwbenc/inc/dtx.h
index e52c2d0..0bdda67 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/dtx.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/dtx.h
@@ -1,115 +1,115 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/*--------------------------------------------------------------------------*

- *                         DTX.H					    *

- *--------------------------------------------------------------------------*

- *       Static memory, constants and frametypes for the DTX 		    *

- *--------------------------------------------------------------------------*/

-

-#ifndef __DTX_H__

-#define __DTX_H__

-

-#define DTX_MAX_EMPTY_THRESH 50

-#define DTX_HIST_SIZE 8

-#define DTX_HIST_SIZE_MIN_ONE 7

-#define DTX_ELAPSED_FRAMES_THRESH (24 + 7 -1)

-#define DTX_HANG_CONST 7                   /* yields eight frames of SP HANGOVER  */

-#define INV_MED_THRESH 14564

-#define ISF_GAP  128                       /* 50 */

-#define ONE_MINUS_ISF_GAP 16384 - ISF_GAP

-#define ISF_GAP   128

-#define ISF_DITH_GAP   448

-#define ISF_FACTOR_LOW 256

-#define ISF_FACTOR_STEP 2

-#define GAIN_THR 180

-#define GAIN_FACTOR 75

-

-typedef struct

-{

-    Word16 isf_hist[M * DTX_HIST_SIZE];

-    Word16 log_en_hist[DTX_HIST_SIZE];

-    Word16 hist_ptr;

-    Word16 log_en_index;

-    Word16 cng_seed;

-    /* DTX handler stuff */

-    Word16 dtxHangoverCount;

-    Word16 decAnaElapsedCount;

-    Word32 D[28];

-    Word32 sumD[DTX_HIST_SIZE];

-} dtx_encState;

-

-#define SPEECH 0

-#define DTX 1

-#define DTX_MUTE 2

-

-#define TX_SPEECH 0

-#define TX_SID_FIRST 1

-#define TX_SID_UPDATE 2

-#define TX_NO_DATA 3

-

-#define RX_SPEECH_GOOD 0

-#define RX_SPEECH_PROBABLY_DEGRADED 1

-#define RX_SPEECH_LOST 2

-#define RX_SPEECH_BAD 3

-#define RX_SID_FIRST 4

-#define RX_SID_UPDATE 5

-#define RX_SID_BAD 6

-#define RX_NO_DATA 7

-

-/*****************************************************************************

- *

- * DEFINITION OF DATA TYPES

- *****************************************************************************/

-

-Word16 dtx_enc_init(dtx_encState ** st, Word16 isf_init[], VO_MEM_OPERATOR *pMemOP);

-Word16 dtx_enc_reset(dtx_encState * st, Word16 isf_init[]);

-void dtx_enc_exit(dtx_encState ** st, VO_MEM_OPERATOR *pMemOP);

-

-Word16 dtx_enc(

-     dtx_encState * st,                    /* i/o : State struct                                         */

-     Word16 isf[M],                        /* o   : CN ISF vector                                        */

-     Word16 * exc2,                        /* o   : CN excitation                                        */

-     Word16 ** prms

-);

-

-Word16 dtx_buffer(

-     dtx_encState * st,                    /* i/o : State struct                    */

-     Word16 isf_new[],                     /* i   : isf vector                      */

-     Word32 enr,                           /* i   : residual energy (in L_FRAME)    */

-     Word16 codec_mode

-);

-

-void tx_dtx_handler(dtx_encState * st,     /* i/o : State struct           */

-     Word16 vad_flag,                      /* i   : vad decision           */

-     Word16 * usedMode                     /* i/o : mode changed or not    */

-);

-

-void Qisf_ns(

-     Word16 * isf1,                        /* input : ISF in the frequency domain (0..0.5) */

-     Word16 * isf_q,                       /* output: quantized ISF                        */

-     Word16 * indice                       /* output: quantization indices                 */

-);

-

-

-void Disf_ns(

-     Word16 * indice,                      /* input:  quantization indices                  */

-     Word16 * isf_q                        /* input : ISF in the frequency domain (0..0.5)  */

-);

-

-#endif  //__DTX_H__

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/*--------------------------------------------------------------------------*
+ *                         DTX.H					    *
+ *--------------------------------------------------------------------------*
+ *       Static memory, constants and frametypes for the DTX 		    *
+ *--------------------------------------------------------------------------*/
+
+#ifndef __DTX_H__
+#define __DTX_H__
+
+#define DTX_MAX_EMPTY_THRESH 50
+#define DTX_HIST_SIZE 8
+#define DTX_HIST_SIZE_MIN_ONE 7
+#define DTX_ELAPSED_FRAMES_THRESH (24 + 7 -1)
+#define DTX_HANG_CONST 7                   /* yields eight frames of SP HANGOVER  */
+#define INV_MED_THRESH 14564
+#define ISF_GAP  128                       /* 50 */
+#define ONE_MINUS_ISF_GAP 16384 - ISF_GAP
+#define ISF_GAP   128
+#define ISF_DITH_GAP   448
+#define ISF_FACTOR_LOW 256
+#define ISF_FACTOR_STEP 2
+#define GAIN_THR 180
+#define GAIN_FACTOR 75
+
+typedef struct
+{
+    Word16 isf_hist[M * DTX_HIST_SIZE];
+    Word16 log_en_hist[DTX_HIST_SIZE];
+    Word16 hist_ptr;
+    Word16 log_en_index;
+    Word16 cng_seed;
+    /* DTX handler stuff */
+    Word16 dtxHangoverCount;
+    Word16 decAnaElapsedCount;
+    Word32 D[28];
+    Word32 sumD[DTX_HIST_SIZE];
+} dtx_encState;
+
+#define SPEECH 0
+#define DTX 1
+#define DTX_MUTE 2
+
+#define TX_SPEECH 0
+#define TX_SID_FIRST 1
+#define TX_SID_UPDATE 2
+#define TX_NO_DATA 3
+
+#define RX_SPEECH_GOOD 0
+#define RX_SPEECH_PROBABLY_DEGRADED 1
+#define RX_SPEECH_LOST 2
+#define RX_SPEECH_BAD 3
+#define RX_SID_FIRST 4
+#define RX_SID_UPDATE 5
+#define RX_SID_BAD 6
+#define RX_NO_DATA 7
+
+/*****************************************************************************
+ *
+ * DEFINITION OF DATA TYPES
+ *****************************************************************************/
+
+Word16 dtx_enc_init(dtx_encState ** st, Word16 isf_init[], VO_MEM_OPERATOR *pMemOP);
+Word16 dtx_enc_reset(dtx_encState * st, Word16 isf_init[]);
+void dtx_enc_exit(dtx_encState ** st, VO_MEM_OPERATOR *pMemOP);
+
+Word16 dtx_enc(
+     dtx_encState * st,                    /* i/o : State struct                                         */
+     Word16 isf[M],                        /* o   : CN ISF vector                                        */
+     Word16 * exc2,                        /* o   : CN excitation                                        */
+     Word16 ** prms
+);
+
+Word16 dtx_buffer(
+     dtx_encState * st,                    /* i/o : State struct                    */
+     Word16 isf_new[],                     /* i   : isf vector                      */
+     Word32 enr,                           /* i   : residual energy (in L_FRAME)    */
+     Word16 codec_mode
+);
+
+void tx_dtx_handler(dtx_encState * st,     /* i/o : State struct           */
+     Word16 vad_flag,                      /* i   : vad decision           */
+     Word16 * usedMode                     /* i/o : mode changed or not    */
+);
+
+void Qisf_ns(
+     Word16 * isf1,                        /* input : ISF in the frequency domain (0..0.5) */
+     Word16 * isf_q,                       /* output: quantized ISF                        */
+     Word16 * indice                       /* output: quantization indices                 */
+);
+
+
+void Disf_ns(
+     Word16 * indice,                      /* input:  quantization indices                  */
+     Word16 * isf_q                        /* input : ISF in the frequency domain (0..0.5)  */
+);
+
+#endif  //__DTX_H__
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/grid100.tab b/media/libstagefright/codecs/amrwbenc/inc/grid100.tab
index efee18d..658d28d 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/grid100.tab
+++ b/media/libstagefright/codecs/amrwbenc/inc/grid100.tab
@@ -1,53 +1,53 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-

-/*-------------------------------------------------------------*

- *  Table for az_isp()                                         *

- *                                                             *

- * Vector grid[] is in Q15                                     *

- *                                                             *

- * grid[0] = 1.0;                                              *

- * grid[grid_points+1] = -1.0;                                 *

- * for (i = 1; i < grid_points; i++)                           *

- *   grid[i] = cos((6.283185307*i)/(2.0*grid_points));         *

- *                                                             *

- *-------------------------------------------------------------*/

-

-/* Version 101 points */

-

-#define   GRID_POINTS     100

-

-const Word16 vogrid[GRID_POINTS+1] ={

-    32767,     32751,     32703,     32622,     32509,     32364,

-    32187,     31978,     31738,     31466,     31164,     30830,

-    30466,     30072,     29649,     29196,     28714,     28204,

-    27666,     27101,     26509,     25891,     25248,     24579,

-    23886,     23170,     22431,     21669,     20887,     20083,

-    19260,     18418,     17557,     16680,     15786,     14876,

-    13951,     13013,     12062,     11099,     10125,      9141,

-     8149,      7148,      6140,      5126,      4106,      3083,

-     2057,      1029,         0,     -1029,     -2057,     -3083,

-    -4106,     -5126,     -6140,     -7148,     -8149,     -9141,

-   -10125,    -11099,    -12062,    -13013,    -13951,    -14876,

-   -15786,    -16680,    -17557,    -18418,    -19260,    -20083,

-   -20887,    -21669,    -22431,    -23170,    -23886,    -24579,

-   -25248,    -25891,    -26509,    -27101,    -27666,    -28204,

-   -28714,    -29196,    -29649,    -30072,    -30466,    -30830,

-   -31164,    -31466,    -31738,    -31978,    -32187,    -32364,

-   -32509,    -32622,    -32703,    -32751,    -32760};

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+
+/*-------------------------------------------------------------*
+ *  Table for az_isp()                                         *
+ *                                                             *
+ * Vector grid[] is in Q15                                     *
+ *                                                             *
+ * grid[0] = 1.0;                                              *
+ * grid[grid_points+1] = -1.0;                                 *
+ * for (i = 1; i < grid_points; i++)                           *
+ *   grid[i] = cos((6.283185307*i)/(2.0*grid_points));         *
+ *                                                             *
+ *-------------------------------------------------------------*/
+
+/* Version 101 points */
+
+#define   GRID_POINTS     100
+
+const Word16 vogrid[GRID_POINTS+1] ={
+    32767,     32751,     32703,     32622,     32509,     32364,
+    32187,     31978,     31738,     31466,     31164,     30830,
+    30466,     30072,     29649,     29196,     28714,     28204,
+    27666,     27101,     26509,     25891,     25248,     24579,
+    23886,     23170,     22431,     21669,     20887,     20083,
+    19260,     18418,     17557,     16680,     15786,     14876,
+    13951,     13013,     12062,     11099,     10125,      9141,
+     8149,      7148,      6140,      5126,      4106,      3083,
+     2057,      1029,         0,     -1029,     -2057,     -3083,
+    -4106,     -5126,     -6140,     -7148,     -8149,     -9141,
+   -10125,    -11099,    -12062,    -13013,    -13951,    -14876,
+   -15786,    -16680,    -17557,    -18418,    -19260,    -20083,
+   -20887,    -21669,    -22431,    -23170,    -23886,    -24579,
+   -25248,    -25891,    -26509,    -27101,    -27666,    -28204,
+   -28714,    -29196,    -29649,    -30072,    -30466,    -30830,
+   -31164,    -31466,    -31738,    -31978,    -32187,    -32364,
+   -32509,    -32622,    -32703,    -32751,    -32760};
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/ham_wind.tab b/media/libstagefright/codecs/amrwbenc/inc/ham_wind.tab
index 91f8690..560a9973 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/ham_wind.tab
+++ b/media/libstagefright/codecs/amrwbenc/inc/ham_wind.tab
@@ -1,73 +1,73 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/* Hamming_cos window for LPC analysis.                 */

-/*   Create with function hamm_cos(window,384-128,128)  */

-

-#define L_WINDOW 384

-

-const Word16 vo_window[L_WINDOW] = {

-    2621,    2622,    2626,    2632,    2640,    2650,    2662,    2677,

-    2694,    2714,    2735,    2759,    2785,    2814,    2844,    2877,

-    2912,    2949,    2989,    3031,    3075,    3121,    3169,    3220,

-    3273,    3328,    3385,    3444,    3506,    3569,    3635,    3703,

-    3773,    3845,    3919,    3996,    4074,    4155,    4237,    4321,

-    4408,    4496,    4587,    4680,    4774,    4870,    4969,    5069,

-    5171,    5275,    5381,    5489,    5599,    5710,    5824,    5939,

-    6056,    6174,    6295,    6417,    6541,    6666,    6793,    6922,

-    7052,    7185,    7318,    7453,    7590,    7728,    7868,    8009,

-    8152,    8296,    8442,    8589,    8737,    8887,    9038,    9191,

-    9344,    9499,    9655,    9813,    9971,   10131,   10292,   10454,

-   10617,   10781,   10946,   11113,   11280,   11448,   11617,   11787,

-   11958,   12130,   12303,   12476,   12650,   12825,   13001,   13178,

-   13355,   13533,   13711,   13890,   14070,   14250,   14431,   14612,

-   14793,   14975,   15158,   15341,   15524,   15708,   15891,   16076,

-   16260,   16445,   16629,   16814,   16999,   17185,   17370,   17555,

-   17740,   17926,   18111,   18296,   18481,   18666,   18851,   19036,

-   19221,   19405,   19589,   19773,   19956,   20139,   20322,   20504,

-   20686,   20867,   21048,   21229,   21408,   21588,   21767,   21945,

-   22122,   22299,   22475,   22651,   22825,   22999,   23172,   23344,

-   23516,   23686,   23856,   24025,   24192,   24359,   24525,   24689,

-   24853,   25016,   25177,   25337,   25496,   25654,   25811,   25967,

-   26121,   26274,   26426,   26576,   26725,   26873,   27019,   27164,

-   27308,   27450,   27590,   27729,   27867,   28003,   28137,   28270,

-   28401,   28531,   28659,   28785,   28910,   29033,   29154,   29274,

-   29391,   29507,   29622,   29734,   29845,   29953,   30060,   30165,

-   30268,   30370,   30469,   30566,   30662,   30755,   30847,   30936,

-   31024,   31109,   31193,   31274,   31354,   31431,   31506,   31579,

-   31651,   31719,   31786,   31851,   31914,   31974,   32032,   32088,

-   32142,   32194,   32243,   32291,   32336,   32379,   32419,   32458,

-   32494,   32528,   32560,   32589,   32617,   32642,   32664,   32685,

-   32703,   32719,   32733,   32744,   32753,   32760,   32764,   32767,

-   32767,   32765,   32757,   32745,   32727,   32705,   32678,   32646,

-   32609,   32567,   32520,   32468,   32411,   32349,   32283,   32211,

-   32135,   32054,   31968,   31877,   31781,   31681,   31575,   31465,

-   31351,   31231,   31107,   30978,   30844,   30706,   30563,   30415,

-   30263,   30106,   29945,   29779,   29609,   29434,   29255,   29071,

-   28883,   28691,   28494,   28293,   28087,   27878,   27664,   27446,

-   27224,   26997,   26767,   26533,   26294,   26052,   25806,   25555,

-   25301,   25043,   24782,   24516,   24247,   23974,   23698,   23418,

-   23134,   22847,   22557,   22263,   21965,   21665,   21361,   21054,

-   20743,   20430,   20113,   19794,   19471,   19146,   18817,   18486,

-   18152,   17815,   17476,   17134,   16789,   16442,   16092,   15740,

-   15385,   15028,   14669,   14308,   13944,   13579,   13211,   12841,

-   12470,   12096,   11721,   11344,   10965,   10584,   10202,    9819,

-    9433,    9047,    8659,    8270,    7879,    7488,    7095,    6701,

-    6306,    5910,    5514,    5116,    4718,    4319,    3919,    3519,

-    3118,    2716,    2315,    1913,    1510,    1108,     705,     302};

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/* Hamming_cos window for LPC analysis.                 */
+/*   Create with function hamm_cos(window,384-128,128)  */
+
+#define L_WINDOW 384
+
+const Word16 vo_window[L_WINDOW] = {
+    2621,    2622,    2626,    2632,    2640,    2650,    2662,    2677,
+    2694,    2714,    2735,    2759,    2785,    2814,    2844,    2877,
+    2912,    2949,    2989,    3031,    3075,    3121,    3169,    3220,
+    3273,    3328,    3385,    3444,    3506,    3569,    3635,    3703,
+    3773,    3845,    3919,    3996,    4074,    4155,    4237,    4321,
+    4408,    4496,    4587,    4680,    4774,    4870,    4969,    5069,
+    5171,    5275,    5381,    5489,    5599,    5710,    5824,    5939,
+    6056,    6174,    6295,    6417,    6541,    6666,    6793,    6922,
+    7052,    7185,    7318,    7453,    7590,    7728,    7868,    8009,
+    8152,    8296,    8442,    8589,    8737,    8887,    9038,    9191,
+    9344,    9499,    9655,    9813,    9971,   10131,   10292,   10454,
+   10617,   10781,   10946,   11113,   11280,   11448,   11617,   11787,
+   11958,   12130,   12303,   12476,   12650,   12825,   13001,   13178,
+   13355,   13533,   13711,   13890,   14070,   14250,   14431,   14612,
+   14793,   14975,   15158,   15341,   15524,   15708,   15891,   16076,
+   16260,   16445,   16629,   16814,   16999,   17185,   17370,   17555,
+   17740,   17926,   18111,   18296,   18481,   18666,   18851,   19036,
+   19221,   19405,   19589,   19773,   19956,   20139,   20322,   20504,
+   20686,   20867,   21048,   21229,   21408,   21588,   21767,   21945,
+   22122,   22299,   22475,   22651,   22825,   22999,   23172,   23344,
+   23516,   23686,   23856,   24025,   24192,   24359,   24525,   24689,
+   24853,   25016,   25177,   25337,   25496,   25654,   25811,   25967,
+   26121,   26274,   26426,   26576,   26725,   26873,   27019,   27164,
+   27308,   27450,   27590,   27729,   27867,   28003,   28137,   28270,
+   28401,   28531,   28659,   28785,   28910,   29033,   29154,   29274,
+   29391,   29507,   29622,   29734,   29845,   29953,   30060,   30165,
+   30268,   30370,   30469,   30566,   30662,   30755,   30847,   30936,
+   31024,   31109,   31193,   31274,   31354,   31431,   31506,   31579,
+   31651,   31719,   31786,   31851,   31914,   31974,   32032,   32088,
+   32142,   32194,   32243,   32291,   32336,   32379,   32419,   32458,
+   32494,   32528,   32560,   32589,   32617,   32642,   32664,   32685,
+   32703,   32719,   32733,   32744,   32753,   32760,   32764,   32767,
+   32767,   32765,   32757,   32745,   32727,   32705,   32678,   32646,
+   32609,   32567,   32520,   32468,   32411,   32349,   32283,   32211,
+   32135,   32054,   31968,   31877,   31781,   31681,   31575,   31465,
+   31351,   31231,   31107,   30978,   30844,   30706,   30563,   30415,
+   30263,   30106,   29945,   29779,   29609,   29434,   29255,   29071,
+   28883,   28691,   28494,   28293,   28087,   27878,   27664,   27446,
+   27224,   26997,   26767,   26533,   26294,   26052,   25806,   25555,
+   25301,   25043,   24782,   24516,   24247,   23974,   23698,   23418,
+   23134,   22847,   22557,   22263,   21965,   21665,   21361,   21054,
+   20743,   20430,   20113,   19794,   19471,   19146,   18817,   18486,
+   18152,   17815,   17476,   17134,   16789,   16442,   16092,   15740,
+   15385,   15028,   14669,   14308,   13944,   13579,   13211,   12841,
+   12470,   12096,   11721,   11344,   10965,   10584,   10202,    9819,
+    9433,    9047,    8659,    8270,    7879,    7488,    7095,    6701,
+    6306,    5910,    5514,    5116,    4718,    4319,    3919,    3519,
+    3118,    2716,    2315,    1913,    1510,    1108,     705,     302};
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/homing.tab b/media/libstagefright/codecs/amrwbenc/inc/homing.tab
index 2963da7a..e399fb8 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/homing.tab
+++ b/media/libstagefright/codecs/amrwbenc/inc/homing.tab
@@ -1,123 +1,123 @@
-

-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT 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 DHF_PARMS_MAX 32               /* homing frame pattern  */

-#define NUM_OF_SPMODES 9

-

-#define PRML 15

-#define PRMN_7k NBBITS_7k/PRML + 1

-#define PRMN_9k NBBITS_9k/PRML + 1

-#define PRMN_12k NBBITS_12k/PRML + 1

-#define PRMN_14k NBBITS_14k/PRML + 1

-#define PRMN_16k NBBITS_16k/PRML + 1

-#define PRMN_18k NBBITS_18k/PRML + 1

-#define PRMN_20k NBBITS_20k/PRML + 1

-#define PRMN_23k NBBITS_23k/PRML + 1

-#define PRMN_24k NBBITS_24k/PRML + 1

-

-static const Word16 dfh_M7k[PRMN_7k] =

-{

-  3168, 29954, 29213, 16121, 

-	64, 13440, 30624, 16430, 

- 19008

-};

-

-static const Word16 dfh_M9k[PRMN_9k] =

-{

-   3168, 31665,  9943, 9123, 

-  15599,  4358, 20248, 2048, 

-  17040, 27787, 16816, 13888

-};

-

-static const Word16 dfh_M12k[PRMN_12k] =

-{

-  3168, 31665,  9943,  9128, 

-  3647,  8129, 30930, 27926, 

- 18880, 12319,   496,  1042, 

-  4061, 20446, 25629, 28069, 

- 13948

-};

-

-static const Word16 dfh_M14k[PRMN_14k] =

-{

-    3168, 31665,  9943,  9131, 

-   24815,   655, 26616, 26764, 

-    7238, 19136,  6144,    88, 

-	4158, 25733, 30567, 30494, 

-	221, 20321, 17823

-};

-

-static const Word16 dfh_M16k[PRMN_16k] =

-{

-    3168, 31665,  9943,  9131, 

-   24815,   700,  3824,  7271, 

-   26400,  9528,  6594, 26112, 

-     108,  2068, 12867, 16317, 

-   23035, 24632,  7528,  1752, 

-    6759, 24576

-};

-

-static const Word16 dfh_M18k[PRMN_18k] =

-{

-     3168, 31665,  9943,  9135, 

-	14787, 14423, 30477, 24927, 

-	25345, 30154,   916,  5728, 

-	18978,  2048,   528, 16449, 

-	 2436,  3581, 23527, 29479, 

-	 8237, 16810, 27091, 19052, 

-	    0

-};

-

-static const Word16 dfh_M20k[PRMN_20k] =

-{

-     3168, 31665,  9943,  9129, 

-	 8637, 31807, 24646,   736, 

-	28643,  2977,  2566, 25564, 

-	12930, 13960,  2048,   834, 

-	 3270,  4100, 26920, 16237, 

-	31227, 17667, 15059, 20589, 

-	30249, 29123, 0

-};

-

-static const Word16 dfh_M23k[PRMN_23k] =

-{

-	 3168, 31665,  9943,  9132, 

-	16748,  3202, 28179, 16317, 

-	30590, 15857, 19960,  8818, 

-	21711, 21538,  4260, 16690, 

-	20224,  3666,  4194,  9497, 

-	16320, 15388,  5755, 31551, 

-	14080,  3574, 15932,    50, 

-	23392, 26053, 31216

-};

-

-static const Word16 dfh_M24k[PRMN_24k] =

-{

-	 3168, 31665,  9943,  9134, 

-	24776,  5857, 18475, 28535, 

-	29662, 14321, 16725,  4396, 

-	29353, 10003, 17068, 20504, 

-	  720,     0,  8465, 12581, 

-	28863, 24774,  9709, 26043, 

-	 7941, 27649, 13965, 15236, 

-	18026, 22047, 16681,  3968

-};

-

-

-

+
+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT 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 DHF_PARMS_MAX 32               /* homing frame pattern  */
+#define NUM_OF_SPMODES 9
+
+#define PRML 15
+#define PRMN_7k NBBITS_7k/PRML + 1
+#define PRMN_9k NBBITS_9k/PRML + 1
+#define PRMN_12k NBBITS_12k/PRML + 1
+#define PRMN_14k NBBITS_14k/PRML + 1
+#define PRMN_16k NBBITS_16k/PRML + 1
+#define PRMN_18k NBBITS_18k/PRML + 1
+#define PRMN_20k NBBITS_20k/PRML + 1
+#define PRMN_23k NBBITS_23k/PRML + 1
+#define PRMN_24k NBBITS_24k/PRML + 1
+
+static const Word16 dfh_M7k[PRMN_7k] =
+{
+  3168, 29954, 29213, 16121,
+	64, 13440, 30624, 16430,
+ 19008
+};
+
+static const Word16 dfh_M9k[PRMN_9k] =
+{
+   3168, 31665,  9943, 9123,
+  15599,  4358, 20248, 2048,
+  17040, 27787, 16816, 13888
+};
+
+static const Word16 dfh_M12k[PRMN_12k] =
+{
+  3168, 31665,  9943,  9128,
+  3647,  8129, 30930, 27926,
+ 18880, 12319,   496,  1042,
+  4061, 20446, 25629, 28069,
+ 13948
+};
+
+static const Word16 dfh_M14k[PRMN_14k] =
+{
+    3168, 31665,  9943,  9131,
+   24815,   655, 26616, 26764,
+    7238, 19136,  6144,    88,
+	4158, 25733, 30567, 30494,
+	221, 20321, 17823
+};
+
+static const Word16 dfh_M16k[PRMN_16k] =
+{
+    3168, 31665,  9943,  9131,
+   24815,   700,  3824,  7271,
+   26400,  9528,  6594, 26112,
+     108,  2068, 12867, 16317,
+   23035, 24632,  7528,  1752,
+    6759, 24576
+};
+
+static const Word16 dfh_M18k[PRMN_18k] =
+{
+     3168, 31665,  9943,  9135,
+	14787, 14423, 30477, 24927,
+	25345, 30154,   916,  5728,
+	18978,  2048,   528, 16449,
+	 2436,  3581, 23527, 29479,
+	 8237, 16810, 27091, 19052,
+	    0
+};
+
+static const Word16 dfh_M20k[PRMN_20k] =
+{
+     3168, 31665,  9943,  9129,
+	 8637, 31807, 24646,   736,
+	28643,  2977,  2566, 25564,
+	12930, 13960,  2048,   834,
+	 3270,  4100, 26920, 16237,
+	31227, 17667, 15059, 20589,
+	30249, 29123, 0
+};
+
+static const Word16 dfh_M23k[PRMN_23k] =
+{
+	 3168, 31665,  9943,  9132,
+	16748,  3202, 28179, 16317,
+	30590, 15857, 19960,  8818,
+	21711, 21538,  4260, 16690,
+	20224,  3666,  4194,  9497,
+	16320, 15388,  5755, 31551,
+	14080,  3574, 15932,    50,
+	23392, 26053, 31216
+};
+
+static const Word16 dfh_M24k[PRMN_24k] =
+{
+	 3168, 31665,  9943,  9134,
+	24776,  5857, 18475, 28535,
+	29662, 14321, 16725,  4396,
+	29353, 10003, 17068, 20504,
+	  720,     0,  8465, 12581,
+	28863, 24774,  9709, 26043,
+	 7941, 27649, 13965, 15236,
+	18026, 22047, 16681,  3968
+};
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/isp_isf.tab b/media/libstagefright/codecs/amrwbenc/inc/isp_isf.tab
index ff20e38..97c3b68 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/isp_isf.tab
+++ b/media/libstagefright/codecs/amrwbenc/inc/isp_isf.tab
@@ -1,62 +1,62 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/*-----------------------------------------------------*

- | Tables for function Isf_isp() and Isp_isf()         |

- *-----------------------------------------------------*/

-

-/* table of cos(x) in Q15 */

-

-const static Word16 table[129] = {

-  32767,

-  32758,  32729,  32679,  32610,  32522,  32413,  32286,  32138,

-  31972,  31786,  31581,  31357,  31114,  30853,  30572,  30274,

-  29957,  29622,  29269,  28899,  28511,  28106,  27684,  27246,

-  26791,  26320,  25833,  25330,  24812,  24279,  23732,  23170,

-  22595,  22006,  21403,  20788,  20160,  19520,  18868,  18205,

-  17531,  16846,  16151,  15447,  14733,  14010,  13279,  12540,

-  11793,  11039,  10279,   9512,   8740,   7962,   7180,   6393,

-   5602,   4808,   4011,   3212,   2411,   1608,    804,      0,

-   -804,  -1608,  -2411,  -3212,  -4011,  -4808,  -5602,  -6393,

-  -7180,  -7962,  -8740,  -9512, -10279, -11039, -11793, -12540,

- -13279, -14010, -14733, -15447, -16151, -16846, -17531, -18205,

- -18868, -19520, -20160, -20788, -21403, -22006, -22595, -23170,

- -23732, -24279, -24812, -25330, -25833, -26320, -26791, -27246,

- -27684, -28106, -28511, -28899, -29269, -29622, -29957, -30274,

- -30572, -30853, -31114, -31357, -31581, -31786, -31972, -32138,

- -32286, -32413, -32522, -32610, -32679, -32729, -32758, -32768};

-

-/* slope in Q11 used to compute y = acos(x) */

-

-const static Word16 slope[128] = { 

- -26214, -9039, -5243, -3799, -2979, -2405, -2064, -1771,

- -1579, -1409, -1279, -1170, -1079, -1004, -933, -880,

- -827, -783, -743, -708, -676, -647, -621, -599,

- -576, -557, -538, -521, -506, -492, -479, -466,

- -456, -445, -435, -426, -417, -410, -402, -395,

- -389, -383, -377, -372, -367, -363, -359, -355,

- -351, -348, -345, -342, -340, -337, -335, -333,

- -331, -330, -329, -328, -327, -326, -326, -326,

- -326, -326, -326, -327, -328, -329, -330, -331,

- -333, -335, -337, -340, -342, -345, -348, -351,

- -355, -359, -363, -367, -372, -377, -383, -389,

- -395, -402, -410, -417, -426, -435, -445, -456,

- -466, -479, -492, -506, -521, -538, -557, -576,

- -599, -621, -647, -676, -708, -743, -783, -827,

- -880, -933, -1004, -1079, -1170, -1279, -1409, -1579,

- -1771, -2064, -2405, -2979, -3799, -5243, -9039, -26214};

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/*-----------------------------------------------------*
+ | Tables for function Isf_isp() and Isp_isf()         |
+ *-----------------------------------------------------*/
+
+/* table of cos(x) in Q15 */
+
+const static Word16 table[129] = {
+  32767,
+  32758,  32729,  32679,  32610,  32522,  32413,  32286,  32138,
+  31972,  31786,  31581,  31357,  31114,  30853,  30572,  30274,
+  29957,  29622,  29269,  28899,  28511,  28106,  27684,  27246,
+  26791,  26320,  25833,  25330,  24812,  24279,  23732,  23170,
+  22595,  22006,  21403,  20788,  20160,  19520,  18868,  18205,
+  17531,  16846,  16151,  15447,  14733,  14010,  13279,  12540,
+  11793,  11039,  10279,   9512,   8740,   7962,   7180,   6393,
+   5602,   4808,   4011,   3212,   2411,   1608,    804,      0,
+   -804,  -1608,  -2411,  -3212,  -4011,  -4808,  -5602,  -6393,
+  -7180,  -7962,  -8740,  -9512, -10279, -11039, -11793, -12540,
+ -13279, -14010, -14733, -15447, -16151, -16846, -17531, -18205,
+ -18868, -19520, -20160, -20788, -21403, -22006, -22595, -23170,
+ -23732, -24279, -24812, -25330, -25833, -26320, -26791, -27246,
+ -27684, -28106, -28511, -28899, -29269, -29622, -29957, -30274,
+ -30572, -30853, -31114, -31357, -31581, -31786, -31972, -32138,
+ -32286, -32413, -32522, -32610, -32679, -32729, -32758, -32768};
+
+/* slope in Q11 used to compute y = acos(x) */
+
+const static Word16 slope[128] = {
+ -26214, -9039, -5243, -3799, -2979, -2405, -2064, -1771,
+ -1579, -1409, -1279, -1170, -1079, -1004, -933, -880,
+ -827, -783, -743, -708, -676, -647, -621, -599,
+ -576, -557, -538, -521, -506, -492, -479, -466,
+ -456, -445, -435, -426, -417, -410, -402, -395,
+ -389, -383, -377, -372, -367, -363, -359, -355,
+ -351, -348, -345, -342, -340, -337, -335, -333,
+ -331, -330, -329, -328, -327, -326, -326, -326,
+ -326, -326, -326, -327, -328, -329, -330, -331,
+ -333, -335, -337, -340, -342, -345, -348, -351,
+ -355, -359, -363, -367, -372, -377, -383, -389,
+ -395, -402, -410, -417, -426, -435, -445, -456,
+ -466, -479, -492, -506, -521, -538, -557, -576,
+ -599, -621, -647, -676, -708, -743, -783, -827,
+ -880, -933, -1004, -1079, -1170, -1279, -1409, -1579,
+ -1771, -2064, -2405, -2979, -3799, -5243, -9039, -26214};
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/lag_wind.tab b/media/libstagefright/codecs/amrwbenc/inc/lag_wind.tab
index 4175d66..9c73357 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/lag_wind.tab
+++ b/media/libstagefright/codecs/amrwbenc/inc/lag_wind.tab
@@ -1,81 +1,81 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/*-----------------------------------------------------*

- | Table of lag_window for autocorrelation.            |

- | noise floor = 1.0001   = (0.9999  on r[1] ..r[16])  |

- | Bandwidth expansion = 60 Hz                         |

- | Sampling frequency  = 12800 Hz                      |

- |                                                     |

- | Special double precision format. See "math_op.c"    |

- |                                                     |

- | lag_wind[0] =  1.00000000    (not stored)           |

- | lag_wind[1] =  0.99946642                           |

- | lag_wind[2] =  0.99816680                           |

- | lag_wind[3] =  0.99600452                           |

- | lag_wind[4] =  0.99298513                           |

- | lag_wind[5] =  0.98911655                           |

- | lag_wind[6] =  0.98440880                           |

- | lag_wind[7] =  0.97887397                           |

- | lag_wind[8] =  0.97252619                           |

- | lag_wind[9] =  0.96538186                           |

- | lag_wind[10]=  0.95745903                           |

- | lag_wind[11]=  0.94877797                           |

- | lag_wind[12]=  0.93936038                           |

- | lag_wind[13]=  0.92922986                           |

- | lag_wind[14]=  0.91841155                           |

- | lag_wind[15]=  0.90693212                           |

- | lag_wind[16]=  0.89481968                           |

- ------------------------------------------------------*/

-

-#define M 16

-

-static Word16 volag_h[M] = {

-      32750,

-      32707,

-      32637,

-      32538,

-      32411,

-      32257,

-      32075,

-      31867,

-      31633,

-      31374,

-      31089,

-      30780,

-      30449,

-      30094,

-      29718,

-      29321};

-

-static Word16 volag_l[M] = {

-      16896,

-      30464,

-       2496,

-       4480,

-      12160,

-       3520,

-      24320,

-      24192,

-      20736,

-        576,

-      18240,

-      31488,

-        128,

-      16704,

-      11520,

-      14784};

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/*-----------------------------------------------------*
+ | Table of lag_window for autocorrelation.            |
+ | noise floor = 1.0001   = (0.9999  on r[1] ..r[16])  |
+ | Bandwidth expansion = 60 Hz                         |
+ | Sampling frequency  = 12800 Hz                      |
+ |                                                     |
+ | Special double precision format. See "math_op.c"    |
+ |                                                     |
+ | lag_wind[0] =  1.00000000    (not stored)           |
+ | lag_wind[1] =  0.99946642                           |
+ | lag_wind[2] =  0.99816680                           |
+ | lag_wind[3] =  0.99600452                           |
+ | lag_wind[4] =  0.99298513                           |
+ | lag_wind[5] =  0.98911655                           |
+ | lag_wind[6] =  0.98440880                           |
+ | lag_wind[7] =  0.97887397                           |
+ | lag_wind[8] =  0.97252619                           |
+ | lag_wind[9] =  0.96538186                           |
+ | lag_wind[10]=  0.95745903                           |
+ | lag_wind[11]=  0.94877797                           |
+ | lag_wind[12]=  0.93936038                           |
+ | lag_wind[13]=  0.92922986                           |
+ | lag_wind[14]=  0.91841155                           |
+ | lag_wind[15]=  0.90693212                           |
+ | lag_wind[16]=  0.89481968                           |
+ ------------------------------------------------------*/
+
+#define M 16
+
+static Word16 volag_h[M] = {
+      32750,
+      32707,
+      32637,
+      32538,
+      32411,
+      32257,
+      32075,
+      31867,
+      31633,
+      31374,
+      31089,
+      30780,
+      30449,
+      30094,
+      29718,
+      29321};
+
+static Word16 volag_l[M] = {
+      16896,
+      30464,
+       2496,
+       4480,
+      12160,
+       3520,
+      24320,
+      24192,
+      20736,
+        576,
+      18240,
+      31488,
+        128,
+      16704,
+      11520,
+      14784};
diff --git a/media/libstagefright/codecs/amrwbenc/inc/log2.h b/media/libstagefright/codecs/amrwbenc/inc/log2.h
index 91bdbec..b065eb4 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/log2.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/log2.h
@@ -1,62 +1,62 @@
-

-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/********************************************************************************

-*

-*      File             : log2.h

-*      Purpose          : Computes log2(L_x)

-*

-********************************************************************************

-*/

-#ifndef __LOG2_H__

-#define __LOG2_H__

- 

-/*

-********************************************************************************

-*                         INCLUDE FILES

-********************************************************************************

-*/

-#include "typedef.h"

- 

-/*

-********************************************************************************

-*                         DEFINITION OF DATA TYPES

-********************************************************************************

-*/

- 

-/*

-********************************************************************************

-*                         DECLARATION OF PROTOTYPES

-********************************************************************************

-*/

-void Log2 (

-		Word32 L_x,        /* (i) : input value                                 */

-		Word16 *exponent,  /* (o) : Integer part of Log2.   (range: 0<=val<=30) */

-		Word16 *fraction   /* (o) : Fractional part of Log2. (range: 0<=val<1)*/

-	  );

-

-void Log2_norm (

-		Word32 L_x,         /* (i) : input value (normalized)                    */

-		Word16 exp,         /* (i) : norm_l (L_x)                                */

-		Word16 *exponent,   /* (o) : Integer part of Log2.   (range: 0<=val<=30) */

-		Word16 *fraction    /* (o) : Fractional part of Log2. (range: 0<=val<1)  */

-	       );

-

-#endif  //__LOG2_H__

-

-

+
+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/********************************************************************************
+*
+*      File             : log2.h
+*      Purpose          : Computes log2(L_x)
+*
+********************************************************************************
+*/
+#ifndef __LOG2_H__
+#define __LOG2_H__
+
+/*
+********************************************************************************
+*                         INCLUDE FILES
+********************************************************************************
+*/
+#include "typedef.h"
+
+/*
+********************************************************************************
+*                         DEFINITION OF DATA TYPES
+********************************************************************************
+*/
+
+/*
+********************************************************************************
+*                         DECLARATION OF PROTOTYPES
+********************************************************************************
+*/
+void Log2 (
+		Word32 L_x,        /* (i) : input value                                 */
+		Word16 *exponent,  /* (o) : Integer part of Log2.   (range: 0<=val<=30) */
+		Word16 *fraction   /* (o) : Fractional part of Log2. (range: 0<=val<1)*/
+	  );
+
+void Log2_norm (
+		Word32 L_x,         /* (i) : input value (normalized)                    */
+		Word16 exp,         /* (i) : norm_l (L_x)                                */
+		Word16 *exponent,   /* (o) : Integer part of Log2.   (range: 0<=val<=30) */
+		Word16 *fraction    /* (o) : Fractional part of Log2. (range: 0<=val<1)  */
+	       );
+
+#endif  //__LOG2_H__
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/log2_tab.h b/media/libstagefright/codecs/amrwbenc/inc/log2_tab.h
index 7761ae6..85fa73c 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/log2_tab.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/log2_tab.h
@@ -1,35 +1,35 @@
-

-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-

-/*******************************************************************************

-*

-*      File             : log2.tab

-*      Purpose          : Table for routine Log2().

-*      $Id $

-*

-********************************************************************************

-*/

-static const Word16 table[33] =

-{

-    0, 1455, 2866, 4236, 5568, 6863, 8124, 9352, 10549, 11716,

-    12855, 13967, 15054, 16117, 17156, 18172, 19167, 20142, 21097, 22033,

-    22951, 23852, 24735, 25603, 26455, 27291, 28113, 28922, 29716, 30497,

-    31266, 32023, 32767

-};

-

+
+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+
+/*******************************************************************************
+*
+*      File             : log2.tab
+*      Purpose          : Table for routine Log2().
+*      $Id $
+*
+********************************************************************************
+*/
+static const Word16 table[33] =
+{
+    0, 1455, 2866, 4236, 5568, 6863, 8124, 9352, 10549, 11716,
+    12855, 13967, 15054, 16117, 17156, 18172, 19167, 20142, 21097, 22033,
+    22951, 23852, 24735, 25603, 26455, 27291, 28113, 28922, 29716, 30497,
+    31266, 32023, 32767
+};
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/main.h b/media/libstagefright/codecs/amrwbenc/inc/main.h
index d7e7c67..3a6f963 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/main.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/main.h
@@ -1,45 +1,45 @@
-

-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/*--------------------------------------------------------------------------*

- *                         MAIN.H	                                    *

- *--------------------------------------------------------------------------*

- *       Main functions							    *

- *--------------------------------------------------------------------------*/

-

-#ifndef __MAIN_H__

-#define __MAIN_H__

-

-void coder(

-     Word16 * mode,                        /* input :  used mode                             */

-     Word16 speech16k[],                   /* input :  320 new speech samples (at 16 kHz)    */

-     Word16 prms[],                        /* output:  output parameters           */

-     Word16 * ser_size,                    /* output:  bit rate of the used mode   */

-     void *spe_state,                      /* i/o   :  State structure                       */

-     Word16 allow_dtx                      /* input :  DTX ON/OFF                            */

-);

-

-

-

-void Reset_encoder(void *st, Word16 reset_all);

-

-

-Word16 encoder_homing_frame_test(Word16 input_frame[]);

-

-#endif //__MAIN_H__

-

+
+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/*--------------------------------------------------------------------------*
+ *                         MAIN.H	                                    *
+ *--------------------------------------------------------------------------*
+ *       Main functions							    *
+ *--------------------------------------------------------------------------*/
+
+#ifndef __MAIN_H__
+#define __MAIN_H__
+
+void coder(
+     Word16 * mode,                        /* input :  used mode                             */
+     Word16 speech16k[],                   /* input :  320 new speech samples (at 16 kHz)    */
+     Word16 prms[],                        /* output:  output parameters           */
+     Word16 * ser_size,                    /* output:  bit rate of the used mode   */
+     void *spe_state,                      /* i/o   :  State structure                       */
+     Word16 allow_dtx                      /* input :  DTX ON/OFF                            */
+);
+
+
+
+void Reset_encoder(void *st, Word16 reset_all);
+
+
+Word16 encoder_homing_frame_test(Word16 input_frame[]);
+
+#endif //__MAIN_H__
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/math_op.h b/media/libstagefright/codecs/amrwbenc/inc/math_op.h
index 25e29f7..7b6196b 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/math_op.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/math_op.h
@@ -1,55 +1,55 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/*--------------------------------------------------------------------------*

- *                         MATH_OP.H	                                    *

- *--------------------------------------------------------------------------*

- *       Mathematical operations					    *

- *--------------------------------------------------------------------------*/

-

-#ifndef __MATH_OP_H__

-#define __MATH_OP_H__

-

-Word32 Isqrt(                              /* (o) Q31 : output value (range: 0<=val<1)         */

-		Word32 L_x                            /* (i) Q0  : input value  (range: 0<=val<=7fffffff) */

-	    );

-

-void Isqrt_n(

-		Word32 * frac,                        /* (i/o) Q31: normalized value (1.0 < frac <= 0.5) */

-		Word16 * exp                          /* (i/o)    : exponent (value = frac x 2^exponent) */

-	    );

-

-Word32 Pow2(                               /* (o) Q0  : result       (range: 0<=val<=0x7fffffff) */

-		Word16 exponant,                      /* (i) Q0  : Integer part.      (range: 0<=val<=30)   */

-		Word16 fraction                       /* (i) Q15 : Fractionnal part.  (range: 0.0<=val<1.0) */

-	   );

-

-Word32 Dot_product12(                      /* (o) Q31: normalized result (1 < val <= -1) */

-		Word16 x[],                           /* (i) 12bits: x vector                       */

-		Word16 y[],                           /* (i) 12bits: y vector                       */

-		Word16 lg,                            /* (i)    : vector length                     */

-		Word16 * exp                          /* (o)    : exponent of result (0..+30)       */

-		);

-

-Word32 Dot_product12_asm(                      /* (o) Q31: normalized result (1 < val <= -1) */

-		Word16 x[],                           /* (i) 12bits: x vector                       */

-		Word16 y[],                           /* (i) 12bits: y vector                       */

-		Word16 lg,                            /* (i)    : vector length                     */

-		Word16 * exp                          /* (o)    : exponent of result (0..+30)       */

-		);

-#endif //__MATH_OP_H__

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/*--------------------------------------------------------------------------*
+ *                         MATH_OP.H	                                    *
+ *--------------------------------------------------------------------------*
+ *       Mathematical operations					    *
+ *--------------------------------------------------------------------------*/
+
+#ifndef __MATH_OP_H__
+#define __MATH_OP_H__
+
+Word32 Isqrt(                              /* (o) Q31 : output value (range: 0<=val<1)         */
+		Word32 L_x                            /* (i) Q0  : input value  (range: 0<=val<=7fffffff) */
+	    );
+
+void Isqrt_n(
+		Word32 * frac,                        /* (i/o) Q31: normalized value (1.0 < frac <= 0.5) */
+		Word16 * exp                          /* (i/o)    : exponent (value = frac x 2^exponent) */
+	    );
+
+Word32 Pow2(                               /* (o) Q0  : result       (range: 0<=val<=0x7fffffff) */
+		Word16 exponant,                      /* (i) Q0  : Integer part.      (range: 0<=val<=30)   */
+		Word16 fraction                       /* (i) Q15 : Fractionnal part.  (range: 0.0<=val<1.0) */
+	   );
+
+Word32 Dot_product12(                      /* (o) Q31: normalized result (1 < val <= -1) */
+		Word16 x[],                           /* (i) 12bits: x vector                       */
+		Word16 y[],                           /* (i) 12bits: y vector                       */
+		Word16 lg,                            /* (i)    : vector length                     */
+		Word16 * exp                          /* (o)    : exponent of result (0..+30)       */
+		);
+
+Word32 Dot_product12_asm(                      /* (o) Q31: normalized result (1 < val <= -1) */
+		Word16 x[],                           /* (i) 12bits: x vector                       */
+		Word16 y[],                           /* (i) 12bits: y vector                       */
+		Word16 lg,                            /* (i)    : vector length                     */
+		Word16 * exp                          /* (o)    : exponent of result (0..+30)       */
+		);
+#endif //__MATH_OP_H__
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/mem_align.h b/media/libstagefright/codecs/amrwbenc/inc/mem_align.h
index d6ddec3..442786a1 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/mem_align.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/mem_align.h
@@ -1,35 +1,35 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		mem_align.h

-

-	Content:	Memory alloc alignments functions

-

-*******************************************************************************/

-

-#ifndef __VO_MEM_ALIGN_H__

-#define __VO_MEM_ALIGN_H__

-

-#include "voMem.h"

-#include "typedef.h"

-

-extern void *mem_malloc(VO_MEM_OPERATOR *pMemop, unsigned int size, unsigned char alignment, unsigned int CodecID);

-extern void mem_free(VO_MEM_OPERATOR *pMemop, void *mem_ptr, unsigned int CodecID);

-

-#endif	/* __VO_MEM_ALIGN_H__ */

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		mem_align.h
+
+	Content:	Memory alloc alignments functions
+
+*******************************************************************************/
+
+#ifndef __VO_MEM_ALIGN_H__
+#define __VO_MEM_ALIGN_H__
+
+#include "voMem.h"
+#include "typedef.h"
+
+extern void *mem_malloc(VO_MEM_OPERATOR *pMemop, unsigned int size, unsigned char alignment, unsigned int CodecID);
+extern void mem_free(VO_MEM_OPERATOR *pMemop, void *mem_ptr, unsigned int CodecID);
+
+#endif	/* __VO_MEM_ALIGN_H__ */
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/mime_io.tab b/media/libstagefright/codecs/amrwbenc/inc/mime_io.tab
index ffc86a1..7b485ea 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/mime_io.tab
+++ b/media/libstagefright/codecs/amrwbenc/inc/mime_io.tab
@@ -1,368 +1,368 @@
-

-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT 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 "typedef.h"

-

-static UWord8 toc_byte[16] = {0x04, 0x0C, 0x14, 0x1C, 0x24, 0x2C, 0x34, 0x3C,

-                              0x44, 0x4C, 0x54, 0x5C, 0x64, 0x6C, 0x74, 0x7C};

-

-/* number of speech bits for all modes */

-static Word16 unpacked_size[16] = {132,  177, 253, 285, 317, 365, 397, 461,

-                                   477,   35,   0,   0,   0,   0,   0,   0};

-

-/* size of packed frame for each mode, excluding TOC byte */

-static Word16 packed_size[16] = {17, 23, 32, 36, 40, 46, 50, 58,

-                                 60,  5,  0,  0,  0,  0,  0,  0};

-

-/* number of unused speech bits in packed format for each mode */

-static Word16 unused_size[16] = {4, 7, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0};

-

-/* sorting tables for all modes */

-

-static Word16 sort_660[132] = {

-     0,   5,   6,   7,  61,  84, 107, 130,  62,  85,

-     8,   4,  37,  38,  39,  40,  58,  81, 104, 127,

-    60,  83, 106, 129, 108, 131, 128,  41,  42,  80,

-   126,   1,   3,  57, 103,  82, 105,  59,   2,  63,

-   109, 110,  86,  19,  22,  23,  64,  87,  18,  20,

-    21,  17,  13,  88,  43,  89,  65, 111,  14,  24,

-    25,  26,  27,  28,  15,  16,  44,  90,  66, 112,

-     9,  11,  10,  12,  67, 113,  29,  30,  31,  32,

-    34,  33,  35,  36,  45,  51,  68,  74,  91,  97,

-   114, 120,  46,  69,  92, 115,  52,  75,  98, 121,

-    47,  70,  93, 116,  53,  76,  99, 122,  48,  71,

-    94, 117,  54,  77, 100, 123,  49,  72,  95, 118,

-    55,  78, 101, 124,  50,  73,  96, 119,  56,  79,

-   102, 125

-};

-

-static Word16 sort_885[177] = {

-     0,   4,   6,   7,   5,   3,  47,  48,  49, 112,

-   113, 114,  75, 106, 140, 171,  80, 111, 145, 176,

-    77, 108, 142, 173,  78, 109, 143, 174,  79, 110,

-   144, 175,  76, 107, 141, 172,  50, 115,  51,   2,

-     1,  81, 116, 146,  19,  21,  12,  17,  18,  20,

-    16,  25,  13,  10,  14,  24,  23,  22,  26,   8,

-    15,  52, 117,  31,  82, 147,   9,  33,  11,  83,

-   148,  53, 118,  28,  27,  84, 149,  34,  35,  29,

-    46,  32,  30,  54, 119,  37,  36,  39,  38,  40,

-    85, 150,  41,  42,  43,  44,  45,  55,  60,  65,

-    70,  86,  91,  96, 101, 120, 125, 130, 135, 151,

-   156, 161, 166,  56,  87, 121, 152,  61,  92, 126,

-   157,  66,  97, 131, 162,  71, 102, 136, 167,  57,

-    88, 122, 153,  62,  93, 127, 158,  67,  98, 132,

-   163,  72, 103, 137, 168,  58,  89, 123, 154,  63,

-    94, 128, 159,  68,  99, 133, 164,  73, 104, 138,

-   169,  59,  90, 124, 155,  64,  95, 129, 160,  69,

-   100, 134, 165,  74, 105, 139, 170

-};

-

-static Word16 sort_1265[253] = {

-     0,   4,   6,  93, 143, 196, 246,   7,   5,   3,

-    47,  48,  49,  50,  51, 150, 151, 152, 153, 154,

-    94, 144, 197, 247,  99, 149, 202, 252,  96, 146,

-   199, 249,  97, 147, 200, 250, 100, 203,  98, 148,

-   201, 251,  95, 145, 198, 248,  52,   2,   1, 101,

-   204, 155,  19,  21,  12,  17,  18,  20,  16,  25,

-    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,

-   156,  31, 102, 205,   9,  33,  11, 103, 206,  54,

-   157,  28,  27, 104, 207,  34,  35,  29,  46,  32,

-    30,  55, 158,  37,  36,  39,  38,  40, 105, 208,

-    41,  42,  43,  44,  45,  56, 106, 159, 209,  57,

-    66,  75,  84, 107, 116, 125, 134, 160, 169, 178,

-   187, 210, 219, 228, 237,  58, 108, 161, 211,  62,

-   112, 165, 215,  67, 117, 170, 220,  71, 121, 174,

-   224,  76, 126, 179, 229,  80, 130, 183, 233,  85,

-   135, 188, 238,  89, 139, 192, 242,  59, 109, 162,

-   212,  63, 113, 166, 216,  68, 118, 171, 221,  72,

-   122, 175, 225,  77, 127, 180, 230,  81, 131, 184,

-   234,  86, 136, 189, 239,  90, 140, 193, 243,  60,

-   110, 163, 213,  64, 114, 167, 217,  69, 119, 172,

-   222,  73, 123, 176, 226,  78, 128, 181, 231,  82,

-   132, 185, 235,  87, 137, 190, 240,  91, 141, 194,

-   244,  61, 111, 164, 214,  65, 115, 168, 218,  70,

-   120, 173, 223,  74, 124, 177, 227,  79, 129, 182,

-   232,  83, 133, 186, 236,  88, 138, 191, 241,  92,

-   142, 195, 245                         

-};

-

-static Word16 sort_1425[285] = {

-     0,   4,   6, 101, 159, 220, 278,   7,   5,   3,

-    47,  48,  49,  50,  51, 166, 167, 168, 169, 170,

-   102, 160, 221, 279, 107, 165, 226, 284, 104, 162,

-   223, 281, 105, 163, 224, 282, 108, 227, 106, 164,

-   225, 283, 103, 161, 222, 280,  52,   2,   1, 109,

-   228, 171,  19,  21,  12,  17,  18,  20,  16,  25,

-    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,

-   172,  31, 110, 229,   9,  33,  11, 111, 230,  54,

-   173,  28,  27, 112, 231,  34,  35,  29,  46,  32,

-    30,  55, 174,  37,  36,  39,  38,  40, 113, 232,

-    41,  42,  43,  44,  45,  56, 114, 175, 233,  62,

-   120, 181, 239,  75, 133, 194, 252,  57, 115, 176,

-   234,  63, 121, 182, 240,  70, 128, 189, 247,  76,

-   134, 195, 253,  83, 141, 202, 260,  92, 150, 211,

-   269,  84, 142, 203, 261,  93, 151, 212, 270,  85,

-   143, 204, 262,  94, 152, 213, 271,  86, 144, 205,

-   263,  95, 153, 214, 272,  64, 122, 183, 241,  77,

-   135, 196, 254,  65, 123, 184, 242,  78, 136, 197,

-   255,  87, 145, 206, 264,  96, 154, 215, 273,  58,

-   116, 177, 235,  66, 124, 185, 243,  71, 129, 190,

-   248,  79, 137, 198, 256,  88, 146, 207, 265,  97,

-   155, 216, 274,  59, 117, 178, 236,  67, 125, 186,

-   244,  72, 130, 191, 249,  80, 138, 199, 257,  89,

-   147, 208, 266,  98, 156, 217, 275,  60, 118, 179,

-   237,  68, 126, 187, 245,  73, 131, 192, 250,  81,

-   139, 200, 258,  90, 148, 209, 267,  99, 157, 218,

-   276,  61, 119, 180, 238,  69, 127, 188, 246,  74,

-   132, 193, 251,  82, 140, 201, 259,  91, 149, 210,

-   268, 100, 158, 219, 277

-};

-

-static Word16 sort_1585[317] = {

-     0,   4,   6, 109, 175, 244, 310,   7,   5,   3,

-    47,  48,  49,  50,  51, 182, 183, 184, 185, 186,

-   110, 176, 245, 311, 115, 181, 250, 316, 112, 178,

-   247, 313, 113, 179, 248, 314, 116, 251, 114, 180,

-   249, 315, 111, 177, 246, 312,  52,   2,   1, 117,

-   252, 187,  19,  21,  12,  17,  18,  20,  16,  25,

-    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,

-   188,  31, 118, 253,   9,  33,  11, 119, 254,  54,

-   189,  28,  27, 120, 255,  34,  35,  29,  46,  32,

-    30,  55, 190,  37,  36,  39,  38,  40, 121, 256,

-    41,  42,  43,  44,  45,  56, 122, 191, 257,  63,

-   129, 198, 264,  76, 142, 211, 277,  89, 155, 224,

-   290, 102, 168, 237, 303,  57, 123, 192, 258,  70,

-   136, 205, 271,  83, 149, 218, 284,  96, 162, 231,

-   297,  62, 128, 197, 263,  75, 141, 210, 276,  88,

-   154, 223, 289, 101, 167, 236, 302,  58, 124, 193,

-   259,  71, 137, 206, 272,  84, 150, 219, 285,  97,

-   163, 232, 298,  59, 125, 194, 260,  64, 130, 199,

-   265,  67, 133, 202, 268,  72, 138, 207, 273,  77,

-   143, 212, 278,  80, 146, 215, 281,  85, 151, 220,

-   286,  90, 156, 225, 291,  93, 159, 228, 294,  98,

-   164, 233, 299, 103, 169, 238, 304, 106, 172, 241,

-   307,  60, 126, 195, 261,  65, 131, 200, 266,  68,

-   134, 203, 269,  73, 139, 208, 274,  78, 144, 213,

-   279,  81, 147, 216, 282,  86, 152, 221, 287,  91,

-   157, 226, 292,  94, 160, 229, 295,  99, 165, 234,

-   300, 104, 170, 239, 305, 107, 173, 242, 308,  61,

-   127, 196, 262,  66, 132, 201, 267,  69, 135, 204,

-   270,  74, 140, 209, 275,  79, 145, 214, 280,  82,

-   148, 217, 283,  87, 153, 222, 288,  92, 158, 227,

-   293,  95, 161, 230, 296, 100, 166, 235, 301, 105,

-   171, 240, 306, 108, 174, 243, 309

-};

-

-static Word16 sort_1825[365] = {

-     0,   4,   6, 121, 199, 280, 358,   7,   5,   3,

-    47,  48,  49,  50,  51, 206, 207, 208, 209, 210,

-   122, 200, 281, 359, 127, 205, 286, 364, 124, 202,

-   283, 361, 125, 203, 284, 362, 128, 287, 126, 204,

-   285, 363, 123, 201, 282, 360,  52,   2,   1, 129,

-   288, 211,  19,  21,  12,  17,  18,  20,  16,  25,

-    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,

-   212,  31, 130, 289,   9,  33,  11, 131, 290,  54,

-   213,  28,  27, 132, 291,  34,  35,  29,  46,  32,

-    30,  55, 214,  37,  36,  39,  38,  40, 133, 292,

-    41,  42,  43,  44,  45,  56, 134, 215, 293, 198,

-   299, 136, 120, 138,  60, 279,  58,  62, 357, 139,

-   140, 295, 156,  57, 219, 297,  63, 217, 137, 170,

-   300, 222,  64, 106,  61,  78, 294,  92, 142, 141,

-   135, 221, 296, 301, 343,  59, 298, 184, 329, 315,

-   220, 216, 265, 251, 218, 237, 352, 223, 157,  86,

-   171,  87, 164, 351, 111, 302,  65, 178, 115, 323,

-    72, 192, 101, 179,  93,  73, 193, 151, 337, 309,

-   143, 274,  69, 324, 165, 150,  97, 338, 110, 310,

-   330, 273,  68, 107, 175, 245, 114,  79, 113, 189,

-   246, 259, 174,  71, 185,  96, 344, 100, 322,  83,

-   334, 316, 333, 252, 161, 348, 147,  82, 269, 232,

-   260, 308, 353, 347, 163, 231, 306, 320, 188, 270,

-   146, 177, 266, 350, 256,  85, 149, 116, 191, 160,

-   238, 258, 336, 305, 255,  88, 224,  99, 339, 230,

-   228, 227, 272, 242, 241, 319, 233, 311, 102,  74,

-   180, 275,  66, 194, 152, 325, 172, 247, 244, 261,

-   117, 158, 166, 354,  75, 144, 108, 312,  94, 186,

-   303,  80, 234,  89, 195, 112, 340, 181, 345, 317,

-   326, 276, 239, 167, 118, 313,  70, 355, 327, 253,

-   190, 176, 271, 104,  98, 153, 103,  90,  76, 267,

-   277, 248, 225, 262, 182,  84, 154, 235, 335, 168,

-   331, 196, 341, 249, 162, 307, 148, 349, 263, 321,

-   257, 243, 229, 356, 159, 119,  67, 187, 173, 145,

-   240,  77, 304, 332, 314, 342, 109, 254,  81, 278,

-   105,  91, 346, 318, 183, 250, 197, 328,  95, 155,

-   169, 268, 226, 236, 264                 

-};

-

-static Word16 sort_1985[397] = {

-     0,   4,   6, 129, 215, 304, 390,   7,   5,   3,

-    47,  48,  49,  50,  51, 222, 223, 224, 225, 226,

-   130, 216, 305, 391, 135, 221, 310, 396, 132, 218,

-   307, 393, 133, 219, 308, 394, 136, 311, 134, 220,

-   309, 395, 131, 217, 306, 392,  52,   2,   1, 137,

-   312, 227,  19,  21,  12,  17,  18,  20,  16,  25,

-    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,

-   228,  31, 138, 313,   9,  33,  11, 139, 314,  54,

-   229,  28,  27, 140, 315,  34,  35,  29,  46,  32,

-    30,  55, 230,  37,  36,  39,  38,  40, 141, 316,

-    41,  42,  43,  44,  45,  56, 142, 231, 317,  63,

-    73,  92, 340,  82, 324, 149, 353, 159, 334, 165,

-   338, 178, 163, 254,  77, 168, 257, 153, 343,  57,

-   248, 238,  79, 252, 166,  67,  80, 201, 101, 267,

-   143, 164, 341, 255, 339, 187, 376, 318,  78, 328,

-   362, 115, 232, 242, 253, 290, 276,  62,  58, 158,

-    68,  93, 179, 319, 148, 169, 154,  72, 385, 329,

-   333, 344, 102,  83, 144, 233, 323, 124, 243, 192,

-   354, 237,  64, 247, 202, 209, 150, 116, 335, 268,

-   239, 299, 188, 196, 298,  94, 195, 258, 123, 363,

-   384, 109, 325, 371, 170, 370,  84, 110, 295, 180,

-    74, 210, 191, 106, 291, 205, 367, 381, 377, 206,

-   355, 122, 119, 120, 383, 160, 105, 108, 277, 380,

-   294, 284, 285, 345, 208, 269, 249, 366, 386, 300,

-   297, 259, 125, 369, 197,  97, 194, 286, 211, 281,

-   280, 183, 372,  87, 155, 283,  59, 348, 327, 184,

-    76, 111, 330, 203, 349,  69,  98, 152, 145, 189,

-    66, 320, 337, 173, 358, 251, 198, 174, 263, 262,

-   126, 241, 193,  88, 388, 117,  95, 387, 112, 359,

-   287, 244, 103, 272, 301, 171, 162, 234, 273, 127,

-   373, 181, 292,  85, 378, 302, 121, 107, 364, 346,

-   356, 212, 278, 213,  65, 382, 288, 207, 113, 175,

-    99, 296, 374, 368, 199, 260, 185, 336, 331, 161,

-   270, 264, 250, 240,  75, 350, 151,  60,  89, 321,

-   156, 274, 360, 326,  70, 282, 167, 146, 352,  81,

-    91, 389, 266, 245, 177, 235, 190, 256, 204, 342,

-   128, 118, 303, 104, 379, 182, 114, 375, 200,  96,

-   293, 172, 214, 365, 279,  86, 289, 351, 347, 357,

-   261, 186, 176, 271,  90, 100, 147, 322, 275, 361,

-    71, 332,  61, 265, 157, 246, 236         

-};

-

-static Word16 sort_2305[461] = {

-     0,   4,   6, 145, 247, 352, 454,   7,   5,   3,

-    47,  48,  49,  50,  51, 254, 255, 256, 257, 258,

-   146, 248, 353, 455, 151, 253, 358, 460, 148, 250,

-   355, 457, 149, 251, 356, 458, 152, 359, 150, 252,

-   357, 459, 147, 249, 354, 456,  52,   2,   1, 153,

-   360, 259,  19,  21,  12,  17,  18,  20,  16,  25,

-    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,

-   260,  31, 154, 361,   9,  33,  11, 155, 362,  54,

-   261,  28,  27, 156, 363,  34,  35,  29,  46,  32,

-    30,  55, 262,  37,  36,  39,  38,  40, 157, 364,

-    41,  42,  43,  44,  45,  56, 158, 263, 365, 181,

-   192, 170,  79,  57, 399,  90, 159, 297, 377, 366,

-   275,  68, 183, 388, 286, 194, 299, 92 ,  70, 182,

-   401, 172,  59,  91,  58, 400, 368, 161,  81, 160,

-   264, 171,  80, 389, 390, 378, 379, 193, 298,  69,

-   266, 265, 367, 277, 288, 276, 287, 184,  60, 195,

-    82,  93,  71, 369, 402, 173, 162, 444, 300, 391,

-    98,  76, 278,  61, 267, 374, 135, 411, 167, 102,

-   380, 200,  87, 178,  65,  94, 204, 124,  72, 342,

-   189, 305, 381, 396, 433, 301, 226, 407, 289, 237,

-   113, 215, 185, 128, 309, 403, 116, 320, 196, 331,

-   370, 422, 174,  64, 392,  83, 425, 219, 134, 188,

-   432, 112, 427, 139, 279, 163, 436, 208, 447, 218,

-   236, 229,  97, 294, 385, 230, 166, 268, 177, 443,

-   225, 426, 101, 272, 138, 127, 290, 117, 347, 199,

-   414,  95, 140, 240, 410, 395, 209, 129, 283, 346,

-   105, 241, 437,  86, 308, 448, 203, 345, 186, 107,

-   220, 415, 334, 319, 106, 313, 118, 123,  73, 207,

-   421, 214, 384, 373, 438,  62, 371, 341,  75, 449,

-   168, 323, 164, 242, 416, 324, 304, 197, 335, 404,

-   271,  63, 191, 325,  96, 169, 231, 280, 312, 187,

-   406,  84, 201, 100,  67, 382, 175, 336, 202, 330,

-   269, 393, 376, 383, 293, 307, 409, 179, 285, 314,

-   302, 372, 398, 190, 180,  89,  99, 103, 232,  78,

-    88,  77, 136, 387, 165, 198, 394, 125, 176, 428,

-    74, 375, 238, 227,  66, 273, 282, 141, 306, 412,

-   114,  85, 130, 348, 119, 291, 296, 386, 233, 397,

-   303, 405, 284, 445, 423, 221, 210, 205, 450, 108,

-   274, 434, 216, 343, 337, 142, 243, 321, 408, 451,

-   310, 292, 120, 109, 281, 439, 270, 429, 332, 295,

-   418, 211, 315, 222, 326, 131, 430, 244, 327, 349,

-   417, 316, 143, 338, 440, 234, 110, 212, 452, 245,

-   121, 419, 350, 223, 132, 441, 328, 413, 317, 339,

-   126, 104, 137, 446, 344, 239, 435, 115, 333, 206,

-   322, 217, 228, 424, 453, 311, 351, 111, 442, 224,

-   213, 122, 431, 340, 235, 246, 133, 144, 420, 329,

-   318

-};

-

-static Word16 sort_2385[477] = {

-     0,   4,   6, 145, 251, 360, 466,   7,   5,   3,

-    47,  48,  49,  50,  51, 262, 263, 264, 265, 266,

-   146, 252, 361, 467, 151, 257, 366, 472, 148, 254,

-   363, 469, 149, 255, 364, 470, 156, 371, 150, 256,

-   365, 471, 147, 253, 362, 468,  52,   2,   1, 157,

-   372, 267,  19,  21,  12,  17,  18,  20,  16,  25,

-    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,

-   268,  31, 152, 153, 154, 155, 258, 259, 260, 261,

-   367, 368, 369, 370, 473, 474, 475, 476, 158, 373,

-     9,  33,  11, 159, 374,  54, 269,  28,  27, 160,

-   375,  34,  35,  29,  46,  32,  30,  55, 270, 37,

-    36,  39,  38,  40, 161, 376,  41,  42,  43,  44,

-    45,  56, 162, 271, 377, 185, 196, 174,  79,  57,

-   411,  90, 163, 305, 389, 378, 283,  68, 187, 400,

-   294, 198, 307,  92,  70, 186, 413, 176,  59,  91,

-    58, 412, 380, 165,  81, 164, 272, 175,  80, 401,

-   402, 390, 391, 197, 306,  69, 274, 273, 379, 285,

-   296, 284, 295, 188,  60, 199,  82,  93,  71, 381,

-   414, 177, 166, 456, 308, 403,  98,  76, 286,  61,

-   275, 386, 135, 423, 171, 102, 392, 204,  87, 182,

-    65,  94, 208, 124,  72, 350, 193, 313, 393, 408,

-   445, 309, 230, 419, 297, 241, 113, 219, 189, 128,

-   317, 415, 116, 328, 200, 339, 382, 434, 178,  64,

-   404,  83, 437, 223, 134, 192, 444, 112, 439, 139,

-   287, 167, 448, 212, 459, 222, 240, 233,  97, 302,

-   397, 234, 170, 276, 181, 455, 229, 438, 101, 280,

-   138, 127, 298, 117, 355, 203, 426,  95, 140, 244,

-   422, 407, 213, 129, 291, 354, 105, 245, 449,  86,

-   316, 460, 207, 353, 190, 107, 224, 427, 342, 327,

-   106, 321, 118, 123,  73, 211, 433, 218, 396, 385,

-   450,  62, 383, 349,  75, 461, 172, 331, 168, 246,

-   428, 332, 312, 201, 343, 416, 279,  63, 195, 333,

-    96, 173, 235, 288, 320, 191, 418,  84, 205, 100,

-    67, 394, 179, 344, 206, 338, 277, 405, 388, 395,

-   301, 315, 421, 183, 293, 322, 310, 384, 410, 194,

-   184,  89,  99, 103, 236,  78,  88,  77, 136, 399,

-   169, 202, 406, 125, 180, 440,  74, 387, 242, 231,

-    66, 281, 290, 141, 314, 424, 114,  85, 130, 356,

-   119, 299, 304, 398, 237, 409, 311, 417, 292, 457,

-   435, 225, 214, 209, 462, 108, 282, 446, 220, 351,

-   345, 142, 247, 329, 420, 463, 318, 300, 120, 109,

-   289, 451, 278, 441, 340, 303, 430, 215, 323, 226,

-   334, 131, 442, 248, 335, 357, 429, 324, 143, 346,

-   452, 238, 110, 216, 464, 249, 121, 431, 358, 227,

-   132, 453, 336, 425, 325, 347, 126, 104, 137, 458,

-   352, 243, 447, 115, 341, 210, 330, 221, 232, 436,

-   465, 319, 359, 111, 454, 228, 217, 122, 443, 348,

-   239, 250, 133, 144, 432, 337, 326         

-};

-

-static Word16 sort_SID[35] = {

-    0,  1,  2,  3,  4,  5,  6,  7,  8,  9,

-   10, 11, 12, 13, 14, 15, 16, 17, 18, 19,

-   20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

-   30, 31, 32, 33, 34

-};

-

-/* pointer table for bit sorting tables */

-static Word16 *sort_ptr[16] = { sort_660, sort_885, sort_1265, sort_1425, sort_1585, sort_1825, sort_1985, sort_2305,

-                               sort_2385, sort_SID,      NULL,      NULL,      NULL,      NULL,      NULL,      NULL};

-

-

-

-

+
+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT 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 "typedef.h"
+
+static UWord8 toc_byte[16] = {0x04, 0x0C, 0x14, 0x1C, 0x24, 0x2C, 0x34, 0x3C,
+                              0x44, 0x4C, 0x54, 0x5C, 0x64, 0x6C, 0x74, 0x7C};
+
+/* number of speech bits for all modes */
+static Word16 unpacked_size[16] = {132,  177, 253, 285, 317, 365, 397, 461,
+                                   477,   35,   0,   0,   0,   0,   0,   0};
+
+/* size of packed frame for each mode, excluding TOC byte */
+static Word16 packed_size[16] = {17, 23, 32, 36, 40, 46, 50, 58,
+                                 60,  5,  0,  0,  0,  0,  0,  0};
+
+/* number of unused speech bits in packed format for each mode */
+static Word16 unused_size[16] = {4, 7, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0};
+
+/* sorting tables for all modes */
+
+static Word16 sort_660[132] = {
+     0,   5,   6,   7,  61,  84, 107, 130,  62,  85,
+     8,   4,  37,  38,  39,  40,  58,  81, 104, 127,
+    60,  83, 106, 129, 108, 131, 128,  41,  42,  80,
+   126,   1,   3,  57, 103,  82, 105,  59,   2,  63,
+   109, 110,  86,  19,  22,  23,  64,  87,  18,  20,
+    21,  17,  13,  88,  43,  89,  65, 111,  14,  24,
+    25,  26,  27,  28,  15,  16,  44,  90,  66, 112,
+     9,  11,  10,  12,  67, 113,  29,  30,  31,  32,
+    34,  33,  35,  36,  45,  51,  68,  74,  91,  97,
+   114, 120,  46,  69,  92, 115,  52,  75,  98, 121,
+    47,  70,  93, 116,  53,  76,  99, 122,  48,  71,
+    94, 117,  54,  77, 100, 123,  49,  72,  95, 118,
+    55,  78, 101, 124,  50,  73,  96, 119,  56,  79,
+   102, 125
+};
+
+static Word16 sort_885[177] = {
+     0,   4,   6,   7,   5,   3,  47,  48,  49, 112,
+   113, 114,  75, 106, 140, 171,  80, 111, 145, 176,
+    77, 108, 142, 173,  78, 109, 143, 174,  79, 110,
+   144, 175,  76, 107, 141, 172,  50, 115,  51,   2,
+     1,  81, 116, 146,  19,  21,  12,  17,  18,  20,
+    16,  25,  13,  10,  14,  24,  23,  22,  26,   8,
+    15,  52, 117,  31,  82, 147,   9,  33,  11,  83,
+   148,  53, 118,  28,  27,  84, 149,  34,  35,  29,
+    46,  32,  30,  54, 119,  37,  36,  39,  38,  40,
+    85, 150,  41,  42,  43,  44,  45,  55,  60,  65,
+    70,  86,  91,  96, 101, 120, 125, 130, 135, 151,
+   156, 161, 166,  56,  87, 121, 152,  61,  92, 126,
+   157,  66,  97, 131, 162,  71, 102, 136, 167,  57,
+    88, 122, 153,  62,  93, 127, 158,  67,  98, 132,
+   163,  72, 103, 137, 168,  58,  89, 123, 154,  63,
+    94, 128, 159,  68,  99, 133, 164,  73, 104, 138,
+   169,  59,  90, 124, 155,  64,  95, 129, 160,  69,
+   100, 134, 165,  74, 105, 139, 170
+};
+
+static Word16 sort_1265[253] = {
+     0,   4,   6,  93, 143, 196, 246,   7,   5,   3,
+    47,  48,  49,  50,  51, 150, 151, 152, 153, 154,
+    94, 144, 197, 247,  99, 149, 202, 252,  96, 146,
+   199, 249,  97, 147, 200, 250, 100, 203,  98, 148,
+   201, 251,  95, 145, 198, 248,  52,   2,   1, 101,
+   204, 155,  19,  21,  12,  17,  18,  20,  16,  25,
+    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,
+   156,  31, 102, 205,   9,  33,  11, 103, 206,  54,
+   157,  28,  27, 104, 207,  34,  35,  29,  46,  32,
+    30,  55, 158,  37,  36,  39,  38,  40, 105, 208,
+    41,  42,  43,  44,  45,  56, 106, 159, 209,  57,
+    66,  75,  84, 107, 116, 125, 134, 160, 169, 178,
+   187, 210, 219, 228, 237,  58, 108, 161, 211,  62,
+   112, 165, 215,  67, 117, 170, 220,  71, 121, 174,
+   224,  76, 126, 179, 229,  80, 130, 183, 233,  85,
+   135, 188, 238,  89, 139, 192, 242,  59, 109, 162,
+   212,  63, 113, 166, 216,  68, 118, 171, 221,  72,
+   122, 175, 225,  77, 127, 180, 230,  81, 131, 184,
+   234,  86, 136, 189, 239,  90, 140, 193, 243,  60,
+   110, 163, 213,  64, 114, 167, 217,  69, 119, 172,
+   222,  73, 123, 176, 226,  78, 128, 181, 231,  82,
+   132, 185, 235,  87, 137, 190, 240,  91, 141, 194,
+   244,  61, 111, 164, 214,  65, 115, 168, 218,  70,
+   120, 173, 223,  74, 124, 177, 227,  79, 129, 182,
+   232,  83, 133, 186, 236,  88, 138, 191, 241,  92,
+   142, 195, 245
+};
+
+static Word16 sort_1425[285] = {
+     0,   4,   6, 101, 159, 220, 278,   7,   5,   3,
+    47,  48,  49,  50,  51, 166, 167, 168, 169, 170,
+   102, 160, 221, 279, 107, 165, 226, 284, 104, 162,
+   223, 281, 105, 163, 224, 282, 108, 227, 106, 164,
+   225, 283, 103, 161, 222, 280,  52,   2,   1, 109,
+   228, 171,  19,  21,  12,  17,  18,  20,  16,  25,
+    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,
+   172,  31, 110, 229,   9,  33,  11, 111, 230,  54,
+   173,  28,  27, 112, 231,  34,  35,  29,  46,  32,
+    30,  55, 174,  37,  36,  39,  38,  40, 113, 232,
+    41,  42,  43,  44,  45,  56, 114, 175, 233,  62,
+   120, 181, 239,  75, 133, 194, 252,  57, 115, 176,
+   234,  63, 121, 182, 240,  70, 128, 189, 247,  76,
+   134, 195, 253,  83, 141, 202, 260,  92, 150, 211,
+   269,  84, 142, 203, 261,  93, 151, 212, 270,  85,
+   143, 204, 262,  94, 152, 213, 271,  86, 144, 205,
+   263,  95, 153, 214, 272,  64, 122, 183, 241,  77,
+   135, 196, 254,  65, 123, 184, 242,  78, 136, 197,
+   255,  87, 145, 206, 264,  96, 154, 215, 273,  58,
+   116, 177, 235,  66, 124, 185, 243,  71, 129, 190,
+   248,  79, 137, 198, 256,  88, 146, 207, 265,  97,
+   155, 216, 274,  59, 117, 178, 236,  67, 125, 186,
+   244,  72, 130, 191, 249,  80, 138, 199, 257,  89,
+   147, 208, 266,  98, 156, 217, 275,  60, 118, 179,
+   237,  68, 126, 187, 245,  73, 131, 192, 250,  81,
+   139, 200, 258,  90, 148, 209, 267,  99, 157, 218,
+   276,  61, 119, 180, 238,  69, 127, 188, 246,  74,
+   132, 193, 251,  82, 140, 201, 259,  91, 149, 210,
+   268, 100, 158, 219, 277
+};
+
+static Word16 sort_1585[317] = {
+     0,   4,   6, 109, 175, 244, 310,   7,   5,   3,
+    47,  48,  49,  50,  51, 182, 183, 184, 185, 186,
+   110, 176, 245, 311, 115, 181, 250, 316, 112, 178,
+   247, 313, 113, 179, 248, 314, 116, 251, 114, 180,
+   249, 315, 111, 177, 246, 312,  52,   2,   1, 117,
+   252, 187,  19,  21,  12,  17,  18,  20,  16,  25,
+    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,
+   188,  31, 118, 253,   9,  33,  11, 119, 254,  54,
+   189,  28,  27, 120, 255,  34,  35,  29,  46,  32,
+    30,  55, 190,  37,  36,  39,  38,  40, 121, 256,
+    41,  42,  43,  44,  45,  56, 122, 191, 257,  63,
+   129, 198, 264,  76, 142, 211, 277,  89, 155, 224,
+   290, 102, 168, 237, 303,  57, 123, 192, 258,  70,
+   136, 205, 271,  83, 149, 218, 284,  96, 162, 231,
+   297,  62, 128, 197, 263,  75, 141, 210, 276,  88,
+   154, 223, 289, 101, 167, 236, 302,  58, 124, 193,
+   259,  71, 137, 206, 272,  84, 150, 219, 285,  97,
+   163, 232, 298,  59, 125, 194, 260,  64, 130, 199,
+   265,  67, 133, 202, 268,  72, 138, 207, 273,  77,
+   143, 212, 278,  80, 146, 215, 281,  85, 151, 220,
+   286,  90, 156, 225, 291,  93, 159, 228, 294,  98,
+   164, 233, 299, 103, 169, 238, 304, 106, 172, 241,
+   307,  60, 126, 195, 261,  65, 131, 200, 266,  68,
+   134, 203, 269,  73, 139, 208, 274,  78, 144, 213,
+   279,  81, 147, 216, 282,  86, 152, 221, 287,  91,
+   157, 226, 292,  94, 160, 229, 295,  99, 165, 234,
+   300, 104, 170, 239, 305, 107, 173, 242, 308,  61,
+   127, 196, 262,  66, 132, 201, 267,  69, 135, 204,
+   270,  74, 140, 209, 275,  79, 145, 214, 280,  82,
+   148, 217, 283,  87, 153, 222, 288,  92, 158, 227,
+   293,  95, 161, 230, 296, 100, 166, 235, 301, 105,
+   171, 240, 306, 108, 174, 243, 309
+};
+
+static Word16 sort_1825[365] = {
+     0,   4,   6, 121, 199, 280, 358,   7,   5,   3,
+    47,  48,  49,  50,  51, 206, 207, 208, 209, 210,
+   122, 200, 281, 359, 127, 205, 286, 364, 124, 202,
+   283, 361, 125, 203, 284, 362, 128, 287, 126, 204,
+   285, 363, 123, 201, 282, 360,  52,   2,   1, 129,
+   288, 211,  19,  21,  12,  17,  18,  20,  16,  25,
+    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,
+   212,  31, 130, 289,   9,  33,  11, 131, 290,  54,
+   213,  28,  27, 132, 291,  34,  35,  29,  46,  32,
+    30,  55, 214,  37,  36,  39,  38,  40, 133, 292,
+    41,  42,  43,  44,  45,  56, 134, 215, 293, 198,
+   299, 136, 120, 138,  60, 279,  58,  62, 357, 139,
+   140, 295, 156,  57, 219, 297,  63, 217, 137, 170,
+   300, 222,  64, 106,  61,  78, 294,  92, 142, 141,
+   135, 221, 296, 301, 343,  59, 298, 184, 329, 315,
+   220, 216, 265, 251, 218, 237, 352, 223, 157,  86,
+   171,  87, 164, 351, 111, 302,  65, 178, 115, 323,
+    72, 192, 101, 179,  93,  73, 193, 151, 337, 309,
+   143, 274,  69, 324, 165, 150,  97, 338, 110, 310,
+   330, 273,  68, 107, 175, 245, 114,  79, 113, 189,
+   246, 259, 174,  71, 185,  96, 344, 100, 322,  83,
+   334, 316, 333, 252, 161, 348, 147,  82, 269, 232,
+   260, 308, 353, 347, 163, 231, 306, 320, 188, 270,
+   146, 177, 266, 350, 256,  85, 149, 116, 191, 160,
+   238, 258, 336, 305, 255,  88, 224,  99, 339, 230,
+   228, 227, 272, 242, 241, 319, 233, 311, 102,  74,
+   180, 275,  66, 194, 152, 325, 172, 247, 244, 261,
+   117, 158, 166, 354,  75, 144, 108, 312,  94, 186,
+   303,  80, 234,  89, 195, 112, 340, 181, 345, 317,
+   326, 276, 239, 167, 118, 313,  70, 355, 327, 253,
+   190, 176, 271, 104,  98, 153, 103,  90,  76, 267,
+   277, 248, 225, 262, 182,  84, 154, 235, 335, 168,
+   331, 196, 341, 249, 162, 307, 148, 349, 263, 321,
+   257, 243, 229, 356, 159, 119,  67, 187, 173, 145,
+   240,  77, 304, 332, 314, 342, 109, 254,  81, 278,
+   105,  91, 346, 318, 183, 250, 197, 328,  95, 155,
+   169, 268, 226, 236, 264
+};
+
+static Word16 sort_1985[397] = {
+     0,   4,   6, 129, 215, 304, 390,   7,   5,   3,
+    47,  48,  49,  50,  51, 222, 223, 224, 225, 226,
+   130, 216, 305, 391, 135, 221, 310, 396, 132, 218,
+   307, 393, 133, 219, 308, 394, 136, 311, 134, 220,
+   309, 395, 131, 217, 306, 392,  52,   2,   1, 137,
+   312, 227,  19,  21,  12,  17,  18,  20,  16,  25,
+    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,
+   228,  31, 138, 313,   9,  33,  11, 139, 314,  54,
+   229,  28,  27, 140, 315,  34,  35,  29,  46,  32,
+    30,  55, 230,  37,  36,  39,  38,  40, 141, 316,
+    41,  42,  43,  44,  45,  56, 142, 231, 317,  63,
+    73,  92, 340,  82, 324, 149, 353, 159, 334, 165,
+   338, 178, 163, 254,  77, 168, 257, 153, 343,  57,
+   248, 238,  79, 252, 166,  67,  80, 201, 101, 267,
+   143, 164, 341, 255, 339, 187, 376, 318,  78, 328,
+   362, 115, 232, 242, 253, 290, 276,  62,  58, 158,
+    68,  93, 179, 319, 148, 169, 154,  72, 385, 329,
+   333, 344, 102,  83, 144, 233, 323, 124, 243, 192,
+   354, 237,  64, 247, 202, 209, 150, 116, 335, 268,
+   239, 299, 188, 196, 298,  94, 195, 258, 123, 363,
+   384, 109, 325, 371, 170, 370,  84, 110, 295, 180,
+    74, 210, 191, 106, 291, 205, 367, 381, 377, 206,
+   355, 122, 119, 120, 383, 160, 105, 108, 277, 380,
+   294, 284, 285, 345, 208, 269, 249, 366, 386, 300,
+   297, 259, 125, 369, 197,  97, 194, 286, 211, 281,
+   280, 183, 372,  87, 155, 283,  59, 348, 327, 184,
+    76, 111, 330, 203, 349,  69,  98, 152, 145, 189,
+    66, 320, 337, 173, 358, 251, 198, 174, 263, 262,
+   126, 241, 193,  88, 388, 117,  95, 387, 112, 359,
+   287, 244, 103, 272, 301, 171, 162, 234, 273, 127,
+   373, 181, 292,  85, 378, 302, 121, 107, 364, 346,
+   356, 212, 278, 213,  65, 382, 288, 207, 113, 175,
+    99, 296, 374, 368, 199, 260, 185, 336, 331, 161,
+   270, 264, 250, 240,  75, 350, 151,  60,  89, 321,
+   156, 274, 360, 326,  70, 282, 167, 146, 352,  81,
+    91, 389, 266, 245, 177, 235, 190, 256, 204, 342,
+   128, 118, 303, 104, 379, 182, 114, 375, 200,  96,
+   293, 172, 214, 365, 279,  86, 289, 351, 347, 357,
+   261, 186, 176, 271,  90, 100, 147, 322, 275, 361,
+    71, 332,  61, 265, 157, 246, 236
+};
+
+static Word16 sort_2305[461] = {
+     0,   4,   6, 145, 247, 352, 454,   7,   5,   3,
+    47,  48,  49,  50,  51, 254, 255, 256, 257, 258,
+   146, 248, 353, 455, 151, 253, 358, 460, 148, 250,
+   355, 457, 149, 251, 356, 458, 152, 359, 150, 252,
+   357, 459, 147, 249, 354, 456,  52,   2,   1, 153,
+   360, 259,  19,  21,  12,  17,  18,  20,  16,  25,
+    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,
+   260,  31, 154, 361,   9,  33,  11, 155, 362,  54,
+   261,  28,  27, 156, 363,  34,  35,  29,  46,  32,
+    30,  55, 262,  37,  36,  39,  38,  40, 157, 364,
+    41,  42,  43,  44,  45,  56, 158, 263, 365, 181,
+   192, 170,  79,  57, 399,  90, 159, 297, 377, 366,
+   275,  68, 183, 388, 286, 194, 299, 92 ,  70, 182,
+   401, 172,  59,  91,  58, 400, 368, 161,  81, 160,
+   264, 171,  80, 389, 390, 378, 379, 193, 298,  69,
+   266, 265, 367, 277, 288, 276, 287, 184,  60, 195,
+    82,  93,  71, 369, 402, 173, 162, 444, 300, 391,
+    98,  76, 278,  61, 267, 374, 135, 411, 167, 102,
+   380, 200,  87, 178,  65,  94, 204, 124,  72, 342,
+   189, 305, 381, 396, 433, 301, 226, 407, 289, 237,
+   113, 215, 185, 128, 309, 403, 116, 320, 196, 331,
+   370, 422, 174,  64, 392,  83, 425, 219, 134, 188,
+   432, 112, 427, 139, 279, 163, 436, 208, 447, 218,
+   236, 229,  97, 294, 385, 230, 166, 268, 177, 443,
+   225, 426, 101, 272, 138, 127, 290, 117, 347, 199,
+   414,  95, 140, 240, 410, 395, 209, 129, 283, 346,
+   105, 241, 437,  86, 308, 448, 203, 345, 186, 107,
+   220, 415, 334, 319, 106, 313, 118, 123,  73, 207,
+   421, 214, 384, 373, 438,  62, 371, 341,  75, 449,
+   168, 323, 164, 242, 416, 324, 304, 197, 335, 404,
+   271,  63, 191, 325,  96, 169, 231, 280, 312, 187,
+   406,  84, 201, 100,  67, 382, 175, 336, 202, 330,
+   269, 393, 376, 383, 293, 307, 409, 179, 285, 314,
+   302, 372, 398, 190, 180,  89,  99, 103, 232,  78,
+    88,  77, 136, 387, 165, 198, 394, 125, 176, 428,
+    74, 375, 238, 227,  66, 273, 282, 141, 306, 412,
+   114,  85, 130, 348, 119, 291, 296, 386, 233, 397,
+   303, 405, 284, 445, 423, 221, 210, 205, 450, 108,
+   274, 434, 216, 343, 337, 142, 243, 321, 408, 451,
+   310, 292, 120, 109, 281, 439, 270, 429, 332, 295,
+   418, 211, 315, 222, 326, 131, 430, 244, 327, 349,
+   417, 316, 143, 338, 440, 234, 110, 212, 452, 245,
+   121, 419, 350, 223, 132, 441, 328, 413, 317, 339,
+   126, 104, 137, 446, 344, 239, 435, 115, 333, 206,
+   322, 217, 228, 424, 453, 311, 351, 111, 442, 224,
+   213, 122, 431, 340, 235, 246, 133, 144, 420, 329,
+   318
+};
+
+static Word16 sort_2385[477] = {
+     0,   4,   6, 145, 251, 360, 466,   7,   5,   3,
+    47,  48,  49,  50,  51, 262, 263, 264, 265, 266,
+   146, 252, 361, 467, 151, 257, 366, 472, 148, 254,
+   363, 469, 149, 255, 364, 470, 156, 371, 150, 256,
+   365, 471, 147, 253, 362, 468,  52,   2,   1, 157,
+   372, 267,  19,  21,  12,  17,  18,  20,  16,  25,
+    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,
+   268,  31, 152, 153, 154, 155, 258, 259, 260, 261,
+   367, 368, 369, 370, 473, 474, 475, 476, 158, 373,
+     9,  33,  11, 159, 374,  54, 269,  28,  27, 160,
+   375,  34,  35,  29,  46,  32,  30,  55, 270, 37,
+    36,  39,  38,  40, 161, 376,  41,  42,  43,  44,
+    45,  56, 162, 271, 377, 185, 196, 174,  79,  57,
+   411,  90, 163, 305, 389, 378, 283,  68, 187, 400,
+   294, 198, 307,  92,  70, 186, 413, 176,  59,  91,
+    58, 412, 380, 165,  81, 164, 272, 175,  80, 401,
+   402, 390, 391, 197, 306,  69, 274, 273, 379, 285,
+   296, 284, 295, 188,  60, 199,  82,  93,  71, 381,
+   414, 177, 166, 456, 308, 403,  98,  76, 286,  61,
+   275, 386, 135, 423, 171, 102, 392, 204,  87, 182,
+    65,  94, 208, 124,  72, 350, 193, 313, 393, 408,
+   445, 309, 230, 419, 297, 241, 113, 219, 189, 128,
+   317, 415, 116, 328, 200, 339, 382, 434, 178,  64,
+   404,  83, 437, 223, 134, 192, 444, 112, 439, 139,
+   287, 167, 448, 212, 459, 222, 240, 233,  97, 302,
+   397, 234, 170, 276, 181, 455, 229, 438, 101, 280,
+   138, 127, 298, 117, 355, 203, 426,  95, 140, 244,
+   422, 407, 213, 129, 291, 354, 105, 245, 449,  86,
+   316, 460, 207, 353, 190, 107, 224, 427, 342, 327,
+   106, 321, 118, 123,  73, 211, 433, 218, 396, 385,
+   450,  62, 383, 349,  75, 461, 172, 331, 168, 246,
+   428, 332, 312, 201, 343, 416, 279,  63, 195, 333,
+    96, 173, 235, 288, 320, 191, 418,  84, 205, 100,
+    67, 394, 179, 344, 206, 338, 277, 405, 388, 395,
+   301, 315, 421, 183, 293, 322, 310, 384, 410, 194,
+   184,  89,  99, 103, 236,  78,  88,  77, 136, 399,
+   169, 202, 406, 125, 180, 440,  74, 387, 242, 231,
+    66, 281, 290, 141, 314, 424, 114,  85, 130, 356,
+   119, 299, 304, 398, 237, 409, 311, 417, 292, 457,
+   435, 225, 214, 209, 462, 108, 282, 446, 220, 351,
+   345, 142, 247, 329, 420, 463, 318, 300, 120, 109,
+   289, 451, 278, 441, 340, 303, 430, 215, 323, 226,
+   334, 131, 442, 248, 335, 357, 429, 324, 143, 346,
+   452, 238, 110, 216, 464, 249, 121, 431, 358, 227,
+   132, 453, 336, 425, 325, 347, 126, 104, 137, 458,
+   352, 243, 447, 115, 341, 210, 330, 221, 232, 436,
+   465, 319, 359, 111, 454, 228, 217, 122, 443, 348,
+   239, 250, 133, 144, 432, 337, 326
+};
+
+static Word16 sort_SID[35] = {
+    0,  1,  2,  3,  4,  5,  6,  7,  8,  9,
+   10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
+   20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
+   30, 31, 32, 33, 34
+};
+
+/* pointer table for bit sorting tables */
+static Word16 *sort_ptr[16] = { sort_660, sort_885, sort_1265, sort_1425, sort_1585, sort_1825, sort_1985, sort_2305,
+                               sort_2385, sort_SID,      NULL,      NULL,      NULL,      NULL,      NULL,      NULL};
+
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/oper_32b.h b/media/libstagefright/codecs/amrwbenc/inc/oper_32b.h
index 4159d84..7a0f564 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/oper_32b.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/oper_32b.h
@@ -1,31 +1,31 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/* Double precision operations */

-/* $Id$ */

-

-#ifndef __OPER_32B_H__

-#define __OPER_32B_H__

-

-void VO_L_Extract (Word32 L_32, Word16 *hi, Word16 *lo);

-Word32 L_Comp (Word16 hi, Word16 lo);

-Word32 Mpy_32 (Word16 hi1, Word16 lo1, Word16 hi2, Word16 lo2);

-Word32 Mpy_32_16 (Word16 hi, Word16 lo, Word16 n);

-Word32 Div_32 (Word32 L_num, Word16 denom_hi, Word16 denom_lo);

-

-#endif //__OPER_32B_H__

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/* Double precision operations */
+/* $Id$ */
+
+#ifndef __OPER_32B_H__
+#define __OPER_32B_H__
+
+void VO_L_Extract (Word32 L_32, Word16 *hi, Word16 *lo);
+Word32 L_Comp (Word16 hi, Word16 lo);
+Word32 Mpy_32 (Word16 hi1, Word16 lo1, Word16 hi2, Word16 lo2);
+Word32 Mpy_32_16 (Word16 hi, Word16 lo, Word16 n);
+Word32 Div_32 (Word32 L_num, Word16 denom_hi, Word16 denom_lo);
+
+#endif //__OPER_32B_H__
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/p_med_o.h b/media/libstagefright/codecs/amrwbenc/inc/p_med_o.h
index 27c4c7e..4a13f16 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/p_med_o.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/p_med_o.h
@@ -1,52 +1,52 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/*--------------------------------------------------------------------------*

- *                         P_MED_O.H                                        *

- *--------------------------------------------------------------------------*

- *       Median open-loop lag search				            *

- *--------------------------------------------------------------------------*/

-

-#ifndef __P_MED_O_H__

-#define __P_MED_O_H__

-

-Word16 Pitch_med_ol(                       /* output: open loop pitch lag                        */

-		Word16 wsp[],                         /* input : signal used to compute the open loop pitch */

-		/* wsp[-pit_max] to wsp[-1] should be known   */

-		Word16 L_min,                         /* input : minimum pitch lag                          */

-		Word16 L_max,                         /* input : maximum pitch lag                          */

-		Word16 L_frame,                       /* input : length of frame to compute pitch           */

-		Word16 L_0,                           /* input : old_ open-loop pitch                       */

-		Word16 * gain,                        /* output: normalize correlation of hp_wsp for the Lag */

-		Word16 * hp_wsp_mem,                  /* i:o   : memory of the hypass filter for hp_wsp[] (lg=9)   */

-		Word16 * old_hp_wsp,                  /* i:o   : hypass wsp[]                               */

-		Word16 wght_flg                       /* input : is weighting function used                 */

-		);

-

-Word16 Med_olag(                           /* output : median of  5 previous open-loop lags       */

-		Word16 prev_ol_lag,                   /* input  : previous open-loop lag                     */

-		Word16 old_ol_lag[5]

-	       );

-

-void Hp_wsp(

-		Word16 wsp[],                         /* i   : wsp[]  signal       */

-		Word16 hp_wsp[],                      /* o   : hypass wsp[]        */

-		Word16 lg,                            /* i   : lenght of signal    */

-		Word16 mem[]                          /* i/o : filter memory [9]   */

-	   );

-

-#endif  //__P_MED_O_H__

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/*--------------------------------------------------------------------------*
+ *                         P_MED_O.H                                        *
+ *--------------------------------------------------------------------------*
+ *       Median open-loop lag search				            *
+ *--------------------------------------------------------------------------*/
+
+#ifndef __P_MED_O_H__
+#define __P_MED_O_H__
+
+Word16 Pitch_med_ol(                       /* output: open loop pitch lag                        */
+		Word16 wsp[],                         /* input : signal used to compute the open loop pitch */
+		/* wsp[-pit_max] to wsp[-1] should be known   */
+		Word16 L_min,                         /* input : minimum pitch lag                          */
+		Word16 L_max,                         /* input : maximum pitch lag                          */
+		Word16 L_frame,                       /* input : length of frame to compute pitch           */
+		Word16 L_0,                           /* input : old_ open-loop pitch                       */
+		Word16 * gain,                        /* output: normalize correlation of hp_wsp for the Lag */
+		Word16 * hp_wsp_mem,                  /* i:o   : memory of the hypass filter for hp_wsp[] (lg=9)   */
+		Word16 * old_hp_wsp,                  /* i:o   : hypass wsp[]                               */
+		Word16 wght_flg                       /* input : is weighting function used                 */
+		);
+
+Word16 Med_olag(                           /* output : median of  5 previous open-loop lags       */
+		Word16 prev_ol_lag,                   /* input  : previous open-loop lag                     */
+		Word16 old_ol_lag[5]
+	       );
+
+void Hp_wsp(
+		Word16 wsp[],                         /* i   : wsp[]  signal       */
+		Word16 hp_wsp[],                      /* o   : hypass wsp[]        */
+		Word16 lg,                            /* i   : lenght of signal    */
+		Word16 mem[]                          /* i/o : filter memory [9]   */
+	   );
+
+#endif  //__P_MED_O_H__
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/p_med_ol.tab b/media/libstagefright/codecs/amrwbenc/inc/p_med_ol.tab
index 14bd1d5..d74ec8e 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/p_med_ol.tab
+++ b/media/libstagefright/codecs/amrwbenc/inc/p_med_ol.tab
@@ -1,47 +1,47 @@
-

-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/*-----------------------------------------------------*

- | Table for function Pitch_med_ol()				   |

- *-----------------------------------------------------*/

-

- static Word16 corrweight[199]= {

-

- 10772, 10794, 10816, 10839, 10862, 10885, 10908, 10932, 10955, 10980,

- 11004, 11029, 11054, 11079, 11105, 11131, 11157, 11183, 11210, 11238,

- 11265, 11293, 11322, 11350, 11379, 11409, 11439, 11469, 11500, 11531,

- 11563, 11595, 11628, 11661, 11694, 11728, 11763, 11798, 11834, 11870,

- 11907, 11945, 11983, 12022, 12061, 12101, 12142, 12184, 12226, 12270,

- 12314, 12358, 12404, 12451, 12498, 12547, 12596, 12647, 12699, 12751,

- 12805, 12861, 12917, 12975, 13034, 13095, 13157, 13221, 13286, 13353,

- 13422, 13493, 13566, 13641, 13719, 13798, 13880, 13965, 14053, 14143,

- 14237, 14334, 14435, 14539, 14648, 14761, 14879, 15002, 15130, 15265,

- 15406, 15554, 15710, 15874, 16056, 16384, 16384, 16384, 16384, 16384,

- 16384, 16384, 16056, 15874, 15710, 15554, 15406, 15265, 15130, 15002,

- 14879, 14761, 14648, 14539, 14435, 14334, 14237, 14143, 14053, 13965,

- 13880, 13798, 13719, 13641, 13566, 13493, 13422, 13353, 13286, 13221,

- 13157, 13095, 13034, 12975, 12917, 12861, 12805, 12751, 12699, 12647,

- 12596, 12547, 12498, 12451, 12404, 12358, 12314, 12270, 12226, 12184,

- 12142, 12101, 12061, 12022, 11983, 11945, 11907, 11870, 11834, 11798,

- 11763, 11728, 11694, 11661, 11628, 11595, 11563, 11531, 11500, 11469,

- 11439, 11409, 11379, 11350, 11322, 11293, 11265, 11238, 11210, 11183,

- 11157, 11131, 11105, 11079, 11054, 11029, 11004, 10980, 10955, 10932,

- 10908, 10885, 10862, 10839, 10816, 10794, 10772, 10750, 10728};

-

-

-

+
+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/*-----------------------------------------------------*
+ | Table for function Pitch_med_ol()				   |
+ *-----------------------------------------------------*/
+
+ static Word16 corrweight[199]= {
+
+ 10772, 10794, 10816, 10839, 10862, 10885, 10908, 10932, 10955, 10980,
+ 11004, 11029, 11054, 11079, 11105, 11131, 11157, 11183, 11210, 11238,
+ 11265, 11293, 11322, 11350, 11379, 11409, 11439, 11469, 11500, 11531,
+ 11563, 11595, 11628, 11661, 11694, 11728, 11763, 11798, 11834, 11870,
+ 11907, 11945, 11983, 12022, 12061, 12101, 12142, 12184, 12226, 12270,
+ 12314, 12358, 12404, 12451, 12498, 12547, 12596, 12647, 12699, 12751,
+ 12805, 12861, 12917, 12975, 13034, 13095, 13157, 13221, 13286, 13353,
+ 13422, 13493, 13566, 13641, 13719, 13798, 13880, 13965, 14053, 14143,
+ 14237, 14334, 14435, 14539, 14648, 14761, 14879, 15002, 15130, 15265,
+ 15406, 15554, 15710, 15874, 16056, 16384, 16384, 16384, 16384, 16384,
+ 16384, 16384, 16056, 15874, 15710, 15554, 15406, 15265, 15130, 15002,
+ 14879, 14761, 14648, 14539, 14435, 14334, 14237, 14143, 14053, 13965,
+ 13880, 13798, 13719, 13641, 13566, 13493, 13422, 13353, 13286, 13221,
+ 13157, 13095, 13034, 12975, 12917, 12861, 12805, 12751, 12699, 12647,
+ 12596, 12547, 12498, 12451, 12404, 12358, 12314, 12270, 12226, 12184,
+ 12142, 12101, 12061, 12022, 11983, 11945, 11907, 11870, 11834, 11798,
+ 11763, 11728, 11694, 11661, 11628, 11595, 11563, 11531, 11500, 11469,
+ 11439, 11409, 11379, 11350, 11322, 11293, 11265, 11238, 11210, 11183,
+ 11157, 11131, 11105, 11079, 11054, 11029, 11004, 10980, 10955, 10932,
+ 10908, 10885, 10862, 10839, 10816, 10794, 10772, 10750, 10728};
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/q_gain2.tab b/media/libstagefright/codecs/amrwbenc/inc/q_gain2.tab
index 1a0deee..bc36489 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/q_gain2.tab
+++ b/media/libstagefright/codecs/amrwbenc/inc/q_gain2.tab
@@ -1,228 +1,228 @@
-

-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/*------------------------------------------------------*

- * Tables for function q_gain2()                        *

- *                                                      *

- *  g_pitch(Q14),  g_code(Q11)                          *

- *                                                      *

- * pitch gain are ordered in table to reduce complexity *

- * during quantization of gains.                        *

- *------------------------------------------------------*/

-

-#define nb_qua_gain6b  64     /* Number of quantization level */

-#define nb_qua_gain7b  128    /* Number of quantization level */

-

-

-static Word16 t_qua_gain6b[64*2] = {

-   1566,  1332,

-   1577,  3557,

-   3071,  6490,

-   4193, 10163,

-   4496,  2534,

-   5019,  4488,

-   5586, 15614,

-   5725,  1422,

-   6453,   580,

-   6724,  6831,

-   7657,  3527,

-   8072,  2099,

-   8232,  5319,

-   8827,  8775,

-   9740,  2868,

-   9856,  1465,

-  10087, 12488,

-  10241,  4453,

-  10859,  6618,

-  11321,  3587,

-  11417,  1800,

-  11643,  2428,

-  11718,   988,

-  12312,  5093,

-  12523,  8413,

-  12574, 26214,

-  12601,  3396,

-  13172,  1623,

-  13285,  2423,

-  13418,  6087,

-  13459, 12810,

-  13656,  3607,

-  14111,  4521,

-  14144,  1229,

-  14425,  1871,

-  14431,  7234,

-  14445,  2834,

-  14628, 10036,

-  14860, 17496,

-  15161,  3629,

-  15209,  5819,

-  15299,  2256,

-  15518,  4722,

-  15663,  1060,

-  15759,  7972,

-  15939, 11964,

-  16020,  2996,

-  16086,  1707,

-  16521,  4254,

-  16576,  6224,

-  16894,  2380,

-  16906,   681,

-  17213,  8406,

-  17610,  3418,

-  17895,  5269,

-  18168, 11748,

-  18230,  1575,

-  18607, 32767,

-  18728, 21684,

-  19137,  2543,

-  19422,  6577,

-  19446,  4097,

-  19450,  9056,

-  20371, 14885};

-

-static Word16 t_qua_gain7b[128*2] = {

-    204,   441,

-    464,  1977,

-    869,  1077,

-   1072,  3062,

-   1281,  4759,

-   1647,  1539,

-   1845,  7020,

-   1853,   634,

-   1995,  2336,

-   2351, 15400,

-   2661,  1165,

-   2702,  3900,

-   2710, 10133,

-   3195,  1752,

-   3498,  2624,

-   3663,   849,

-   3984,  5697,

-   4214,  3399,

-   4415,  1304,

-   4695,  2056,

-   5376,  4558,

-   5386,   676,

-   5518, 23554,

-   5567,  7794,

-   5644,  3061,

-   5672,  1513,

-   5957,  2338,

-   6533,  1060,

-   6804,  5998,

-   6820,  1767,

-   6937,  3837,

-   7277,   414,

-   7305,  2665,

-   7466, 11304,

-   7942,   794,

-   8007,  1982,

-   8007,  1366,

-   8326,  3105,

-   8336,  4810,

-   8708,  7954,

-   8989,  2279,

-   9031,  1055,

-   9247,  3568,

-   9283,  1631,

-   9654,  6311,

-   9811,  2605,

-  10120,   683,

-  10143,  4179,

-  10245,  1946,

-  10335,  1218,

-  10468,  9960,

-  10651,  3000,

-  10951,  1530,

-  10969,  5290,

-  11203,  2305,

-  11325,  3562,

-  11771,  6754,

-  11839,  1849,

-  11941,  4495,

-  11954,  1298,

-  11975, 15223,

-  11977,   883,

-  11986,  2842,

-  12438,  2141,

-  12593,  3665,

-  12636,  8367,

-  12658,  1594,

-  12886,  2628,

-  12984,  4942,

-  13146,  1115,

-  13224,   524,

-  13341,  3163,

-  13399,  1923,

-  13549,  5961,

-  13606,  1401,

-  13655,  2399,

-  13782,  3909,

-  13868, 10923,

-  14226,  1723,

-  14232,  2939,

-  14278,  7528,

-  14439,  4598,

-  14451,   984,

-  14458,  2265,

-  14792,  1403,

-  14818,  3445,

-  14899,  5709,

-  15017, 15362,

-  15048,  1946,

-  15069,  2655,

-  15405,  9591,

-  15405,  4079,

-  15570,  7183,

-  15687,  2286,

-  15691,  1624,

-  15699,  3068,

-  15772,  5149,

-  15868,  1205,

-  15970,   696,

-  16249,  3584,

-  16338,  1917,

-  16424,  2560,

-  16483,  4438,

-  16529,  6410,

-  16620, 11966,

-  16839,  8780,

-  17030,  3050,

-  17033, 18325,

-  17092,  1568,

-  17123,  5197,

-  17351,  2113,

-  17374,   980,

-  17566, 26214,

-  17609,  3912,

-  17639, 32767,

-  18151,  7871,

-  18197,  2516,

-  18202,  5649,

-  18679,  3283,

-  18930,  1370,

-  19271, 13757,

-  19317,  4120,

-  19460,  1973,

-  19654, 10018,

-  19764,  6792,

-  19912,  5135,

-  20040,  2841,

-  21234, 19833};

-

-

+
+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/*------------------------------------------------------*
+ * Tables for function q_gain2()                        *
+ *                                                      *
+ *  g_pitch(Q14),  g_code(Q11)                          *
+ *                                                      *
+ * pitch gain are ordered in table to reduce complexity *
+ * during quantization of gains.                        *
+ *------------------------------------------------------*/
+
+#define nb_qua_gain6b  64     /* Number of quantization level */
+#define nb_qua_gain7b  128    /* Number of quantization level */
+
+
+static Word16 t_qua_gain6b[64*2] = {
+   1566,  1332,
+   1577,  3557,
+   3071,  6490,
+   4193, 10163,
+   4496,  2534,
+   5019,  4488,
+   5586, 15614,
+   5725,  1422,
+   6453,   580,
+   6724,  6831,
+   7657,  3527,
+   8072,  2099,
+   8232,  5319,
+   8827,  8775,
+   9740,  2868,
+   9856,  1465,
+  10087, 12488,
+  10241,  4453,
+  10859,  6618,
+  11321,  3587,
+  11417,  1800,
+  11643,  2428,
+  11718,   988,
+  12312,  5093,
+  12523,  8413,
+  12574, 26214,
+  12601,  3396,
+  13172,  1623,
+  13285,  2423,
+  13418,  6087,
+  13459, 12810,
+  13656,  3607,
+  14111,  4521,
+  14144,  1229,
+  14425,  1871,
+  14431,  7234,
+  14445,  2834,
+  14628, 10036,
+  14860, 17496,
+  15161,  3629,
+  15209,  5819,
+  15299,  2256,
+  15518,  4722,
+  15663,  1060,
+  15759,  7972,
+  15939, 11964,
+  16020,  2996,
+  16086,  1707,
+  16521,  4254,
+  16576,  6224,
+  16894,  2380,
+  16906,   681,
+  17213,  8406,
+  17610,  3418,
+  17895,  5269,
+  18168, 11748,
+  18230,  1575,
+  18607, 32767,
+  18728, 21684,
+  19137,  2543,
+  19422,  6577,
+  19446,  4097,
+  19450,  9056,
+  20371, 14885};
+
+static Word16 t_qua_gain7b[128*2] = {
+    204,   441,
+    464,  1977,
+    869,  1077,
+   1072,  3062,
+   1281,  4759,
+   1647,  1539,
+   1845,  7020,
+   1853,   634,
+   1995,  2336,
+   2351, 15400,
+   2661,  1165,
+   2702,  3900,
+   2710, 10133,
+   3195,  1752,
+   3498,  2624,
+   3663,   849,
+   3984,  5697,
+   4214,  3399,
+   4415,  1304,
+   4695,  2056,
+   5376,  4558,
+   5386,   676,
+   5518, 23554,
+   5567,  7794,
+   5644,  3061,
+   5672,  1513,
+   5957,  2338,
+   6533,  1060,
+   6804,  5998,
+   6820,  1767,
+   6937,  3837,
+   7277,   414,
+   7305,  2665,
+   7466, 11304,
+   7942,   794,
+   8007,  1982,
+   8007,  1366,
+   8326,  3105,
+   8336,  4810,
+   8708,  7954,
+   8989,  2279,
+   9031,  1055,
+   9247,  3568,
+   9283,  1631,
+   9654,  6311,
+   9811,  2605,
+  10120,   683,
+  10143,  4179,
+  10245,  1946,
+  10335,  1218,
+  10468,  9960,
+  10651,  3000,
+  10951,  1530,
+  10969,  5290,
+  11203,  2305,
+  11325,  3562,
+  11771,  6754,
+  11839,  1849,
+  11941,  4495,
+  11954,  1298,
+  11975, 15223,
+  11977,   883,
+  11986,  2842,
+  12438,  2141,
+  12593,  3665,
+  12636,  8367,
+  12658,  1594,
+  12886,  2628,
+  12984,  4942,
+  13146,  1115,
+  13224,   524,
+  13341,  3163,
+  13399,  1923,
+  13549,  5961,
+  13606,  1401,
+  13655,  2399,
+  13782,  3909,
+  13868, 10923,
+  14226,  1723,
+  14232,  2939,
+  14278,  7528,
+  14439,  4598,
+  14451,   984,
+  14458,  2265,
+  14792,  1403,
+  14818,  3445,
+  14899,  5709,
+  15017, 15362,
+  15048,  1946,
+  15069,  2655,
+  15405,  9591,
+  15405,  4079,
+  15570,  7183,
+  15687,  2286,
+  15691,  1624,
+  15699,  3068,
+  15772,  5149,
+  15868,  1205,
+  15970,   696,
+  16249,  3584,
+  16338,  1917,
+  16424,  2560,
+  16483,  4438,
+  16529,  6410,
+  16620, 11966,
+  16839,  8780,
+  17030,  3050,
+  17033, 18325,
+  17092,  1568,
+  17123,  5197,
+  17351,  2113,
+  17374,   980,
+  17566, 26214,
+  17609,  3912,
+  17639, 32767,
+  18151,  7871,
+  18197,  2516,
+  18202,  5649,
+  18679,  3283,
+  18930,  1370,
+  19271, 13757,
+  19317,  4120,
+  19460,  1973,
+  19654, 10018,
+  19764,  6792,
+  19912,  5135,
+  20040,  2841,
+  21234, 19833};
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/q_pulse.h b/media/libstagefright/codecs/amrwbenc/inc/q_pulse.h
index baf5525..b5d5280 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/q_pulse.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/q_pulse.h
@@ -1,66 +1,66 @@
-

-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/*--------------------------------------------------------------------------*

- *                         Q_PULSE.H                                        *

- *--------------------------------------------------------------------------*

- * Coding and decoding of algebraic codebook			            *

- *--------------------------------------------------------------------------*/

-

-#ifndef  __Q_PULSE_H__

-#define  __Q_PULSE_H__

-

-#include "typedef.h"

-

-Word32 quant_1p_N1(                        /* (o) return (N+1) bits           */

-		Word16 pos,                           /* (i) position of the pulse       */

-		Word16 N);                            /* (i) number of bits for position */

-

-Word32 quant_2p_2N1(                       /* (o) return (2*N)+1 bits         */

-		Word16 pos1,                          /* (i) position of the pulse 1     */

-		Word16 pos2,                          /* (i) position of the pulse 2     */

-		Word16 N);                            /* (i) number of bits for position */

-

-Word32 quant_3p_3N1(                       /* (o) return (3*N)+1 bits         */

-		Word16 pos1,                          /* (i) position of the pulse 1     */

-		Word16 pos2,                          /* (i) position of the pulse 2     */

-		Word16 pos3,                          /* (i) position of the pulse 3     */

-		Word16 N);                            /* (i) number of bits for position */

-

-Word32 quant_4p_4N1(                       /* (o) return (4*N)+1 bits         */

-		Word16 pos1,                          /* (i) position of the pulse 1     */

-		Word16 pos2,                          /* (i) position of the pulse 2     */

-		Word16 pos3,                          /* (i) position of the pulse 3     */

-		Word16 pos4,                          /* (i) position of the pulse 4     */

-		Word16 N);                            /* (i) number of bits for position */

-

-Word32 quant_4p_4N(                        /* (o) return 4*N bits             */

-		Word16 pos[],                         /* (i) position of the pulse 1..4  */

-		Word16 N);                            /* (i) number of bits for position */

-

-Word32 quant_5p_5N(                        /* (o) return 5*N bits             */

-		Word16 pos[],                         /* (i) position of the pulse 1..5  */

-		Word16 N);                            /* (i) number of bits for position */

-

-Word32 quant_6p_6N_2(                      /* (o) return (6*N)-2 bits         */

-		Word16 pos[],                         /* (i) position of the pulse 1..6  */

-		Word16 N);                            /* (i) number of bits for position */

-

-

-#endif //__Q_PULSE_H__

-

+
+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/*--------------------------------------------------------------------------*
+ *                         Q_PULSE.H                                        *
+ *--------------------------------------------------------------------------*
+ * Coding and decoding of algebraic codebook			            *
+ *--------------------------------------------------------------------------*/
+
+#ifndef  __Q_PULSE_H__
+#define  __Q_PULSE_H__
+
+#include "typedef.h"
+
+Word32 quant_1p_N1(                        /* (o) return (N+1) bits           */
+		Word16 pos,                           /* (i) position of the pulse       */
+		Word16 N);                            /* (i) number of bits for position */
+
+Word32 quant_2p_2N1(                       /* (o) return (2*N)+1 bits         */
+		Word16 pos1,                          /* (i) position of the pulse 1     */
+		Word16 pos2,                          /* (i) position of the pulse 2     */
+		Word16 N);                            /* (i) number of bits for position */
+
+Word32 quant_3p_3N1(                       /* (o) return (3*N)+1 bits         */
+		Word16 pos1,                          /* (i) position of the pulse 1     */
+		Word16 pos2,                          /* (i) position of the pulse 2     */
+		Word16 pos3,                          /* (i) position of the pulse 3     */
+		Word16 N);                            /* (i) number of bits for position */
+
+Word32 quant_4p_4N1(                       /* (o) return (4*N)+1 bits         */
+		Word16 pos1,                          /* (i) position of the pulse 1     */
+		Word16 pos2,                          /* (i) position of the pulse 2     */
+		Word16 pos3,                          /* (i) position of the pulse 3     */
+		Word16 pos4,                          /* (i) position of the pulse 4     */
+		Word16 N);                            /* (i) number of bits for position */
+
+Word32 quant_4p_4N(                        /* (o) return 4*N bits             */
+		Word16 pos[],                         /* (i) position of the pulse 1..4  */
+		Word16 N);                            /* (i) number of bits for position */
+
+Word32 quant_5p_5N(                        /* (o) return 5*N bits             */
+		Word16 pos[],                         /* (i) position of the pulse 1..5  */
+		Word16 N);                            /* (i) number of bits for position */
+
+Word32 quant_6p_6N_2(                      /* (o) return (6*N)-2 bits         */
+		Word16 pos[],                         /* (i) position of the pulse 1..6  */
+		Word16 N);                            /* (i) number of bits for position */
+
+
+#endif //__Q_PULSE_H__
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/qisf_ns.tab b/media/libstagefright/codecs/amrwbenc/inc/qisf_ns.tab
index 52f0daf..43c47e9 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/qisf_ns.tab
+++ b/media/libstagefright/codecs/amrwbenc/inc/qisf_ns.tab
@@ -1,347 +1,347 @@
-

-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/*-------------------------------------------------------------------*

- *                         qisf_ns.h

- *-------------------------------------------------------------------*

- * Quantization tables for split by 5 VQ of ISFs for a background noise database

- * Version whith no prediction

- *-------------------------------------------------------------------*/

-

-#define ORDER   16            /* order of linear prediction filter */

-#define ISF_GAP 128

-

-#define SIZE_BK_NOISE1  64

-#define SIZE_BK_NOISE2  64

-#define SIZE_BK_NOISE3  64

-#define SIZE_BK_NOISE4  32

-#define SIZE_BK_NOISE5  32

-

-

-/* means of ISFs */

- static Word16 mean_isf_noise[ORDER] = {

-

-   478,  1100,  2213,  3267,  4219,  5222,  6198,  7240,

-  8229,  9153, 10098, 11108, 12144, 13184, 14165,  3803};

-

-

-/* 28 bits */

-/*-------------------------------------------------------------------*

- *  isf codebooks:  split-by-5 VQ                                    *

- *                                                                   *

- *  codebook   vector dimension    number of vectors                 *

- *  ~~~~~~~~   ~~~~~~~~~~~~~~~~    ~~~~~~~~~~~~~~~~~                 *

- *     1            2                  64                            *

- *     2            3                  64                            *

- *     3            3                  64                            *

- *     4            4                  32                            *

- *     5            4                  32                            *

- *-------------------------------------------------------------------*/

-

-/*------------------------------------------------*

- * 1st split:   isf0 to isf1

- *------------------------------------------------*/

-

-

- static Word16 dico1_isf_noise[SIZE_BK_NOISE1*2] = {

-

-  -269,  -673,

-  -222,  -537,

-  -233,  -430,

-  -138,  -451,

-  -212,  -331,

-  -192,  -241,

-   -87,  -231,

-  -191,  -128,

-   -70,  -106,

-  -164,    -6,

-    74,  -179,

-    27,   -33,

-  -102,    74,

-  -162,   115,

-   -94,   172,

-    -6,   130,

-  -143,   234,

-    14,   218,

-   -65,   270,

-    88,   182,

-  -124,   341,

-   -44,   381,

-    38,   335,

-   117,   274,

-  -112,   454,

-    74,   431,

-    -5,   488,

-   175,   384,

-   -83,   561,

-   122,   529,

-    21,   601,

-   229,   481,

-   231,   303,

-   226,   608,

-   300,   372,

-   210,   187,

-   306,   265,

-   328,   473,

-   382,   331,

-   371,   132,

-   139,    58,

-   365,    21,

-   250,   -82,

-   443,   218,

-   483,   110,

-   426,   415,

-   579,   222,

-   518,   333,

-   573,   448,

-   455,   529,

-   685,   329,

-   332,   580,

-   595,   593,

-   468,   645,

-   762,   517,

-   326,   709,

-   485,   793,

-   130,   684,

-   671,   737,

-   354,   876,

-    88,   806,

-   -65,   706,

-   -35,  1016,

-   266,  1123};

-

-

-/*------------------------------------------------*

- * 2nd split:   isf2 to isf4

- *------------------------------------------------*/

-

- static Word16 dico2_isf_noise[SIZE_BK_NOISE2*3] = {

-

-  -824,  -884,  -949,

-  -805,  -456,  -418,

-  -442,  -438,  -541,

-  -217,  -578,  -793,

-  -168,  -444,  -582,

-  -287,  -492,  -274,

-  -552,  -297,  -300,

-  -163,  -333,  -358,

-  -370,  -232,  -232,

-  -175,  -358,  -159,

-  -381,   -21,  -357,

-  -184,  -159,  -162,

-   -53,  -191,  -280,

-    18,  -267,  -215,

-  -138,    61,  -283,

-    71,   -95,  -294,

-    13,  -156,  -546,

-     0,   -83,   -79,

-    44,    97,  -316,

-   178,   -52,  -213,

-   222,  -261,  -422,

-   237,  -118,   -44,

-   141,   145,  -132,

-   363,    81,  -287,

-   213,    65,    34,

-  -107,    94,    -5,

-    91,   -29,   126,

-  -355,    51,   -41,

-  -219,   -76,   145,

-   -63,   100,   244,

-  -719,    44,    27,

-  -572,  -124,   155,

-  -423,   133,   315,

-  -917,    71,   224,

-  -268,   318,   131,

-   -93,  -190,   420,

-   -97,   122,   491,

-   -79,   317,   355,

-   130,   100,   325,

-    86,  -293,   210,

-   133,   258,   161,

-   176,   -73,   465,

-   195,   300,   384,

-   348,    22,   221,

-   376,   183,   409,

-   377,   286,   202,

-   242,   213,   659,

-   257,   565,   248,

-   344,   408,   -76,

-   405,   440,   509,

-   612,   385,   379,

-   536,   607,   216,

-   -56,   582,   192,

-   100,   517,   567,

-  -365,   448,   445,

-   728,   347,    10,

-   505,   357,   759,

-   636,   582,   658,

-   335,   517,   852,

-   378,   809,   572,

-  -195,   878,   829,

-   529,   707,   987,

-   918,   726,   392,

-  1250,   997,  1063};

-

-/*------------------------------------------------*

- * 3rd split:   isf5 to isf7

- *------------------------------------------------*/

-

- static Word16 dico3_isf_noise[SIZE_BK_NOISE3*3] = {

-

-  -805,  -838,  -774,

-  -522,  -627,  -828,

-  -477,  -486,  -603,

-  -295,  -481,  -634,

-  -366,  -384,  -393,

-  -186,  -414,  -396,

-  -237,  -394,  -106,

-  -252,  -202,  -275,

-   -61,  -177,  -442,

-   -84,  -198,  -199,

-  -179,  -125,   -31,

-   -72,   -47,  -163,

-  -298,  -220,   215,

-   -64,  -168,   251,

-  -133,   156,   -59,

-   -30,    -2,   127,

-    54,    66,   -61,

-  -233,    21,   251,

-   209,   -50,    32,

-    33,   194,   136,

-  -117,   -18,   475,

-   202,    46,   309,

-   256,   185,    53,

-    35,   200,   390,

-   200,   263,   242,

-  -216,   302,   294,

-   128,   358,     0,

-    19,   431,   287,

-   224,   447,   280,

-   367,   165,   213,

-   397,   314,   319,

-   383,   379,    75,

-   277,   325,   462,

-   394,   505,   334,

-   251,    98,  -213,

-   450,   153,   448,

-   565,   226,    76,

-   470,   383,   502,

-   635,   390,   278,

-   237,   135,   620,

-   342,   401,   649,

-   331,   551,   518,

-   130,   418,   592,

-   531,   306,   737,

-   729,   389,   580,

-   497,   557,   699,

-   296,   383,   874,

-   283,   624,   759,

-   126,   622,   476,

-   559,   595,   472,

-   382,   770,   616,

-   719,   613,   745,

-   540,   639,   928,

-   517,   826,   801,

-   684,   811,   604,

-   752,   786,   857,

-   933,   661,   350,

-   694,   450,  1061,

-   562,   911,  1051,

-   824,   813,  1104,

-   758,  1047,   882,

-  1140,   917,   889,

-  1039,  1246,  1426,

-  1483,  1666,  1876};

-

-/*------------------------------------------------*

- * 4th split:   isf8 to isf11

- *------------------------------------------------*/

-

- static Word16 dico4_isf_noise[SIZE_BK_NOISE4*4] = {

-

-  -776,  -854,  -891,  -920,

-  -552,  -610,  -663,  -741,

-  -321,  -370,  -476,  -565,

-   274,  -160,  -456,   201,

-   265,    67,  -160,  -306,

-    -8,  -210,    79,   272,

-   163,   236,   307,   308,

-   578,   317,    64,   298,

-    -9,   197,   342,   620,

-   343,   232,   314,   622,

-   173,   149,   548,   527,

-   356,   370,   481,   376,

-   135,   444,   488,   556,

-   391,   471,   487,   653,

-   228,   424,   576,   835,

-   422,   372,   722,   682,

-   295,   673,   693,   635,

-   539,   596,   590,   449,

-   475,   618,   659,   818,

-   735,   517,   491,   673,

-   602,   346,   257,   877,

-   625,   635,   849,   720,

-   727,   818,   698,   595,

-   653,   481,   690,  1139,

-   814,   762,   704,   908,

-   507,   747,   898,   936,

-   848,   855,   924,   785,

-   646,  1037,   882,   795,

-   772,   845,  1024,  1151,

-  1133,   983,   818,   921,

-   940,  1068,  1252,  1302,

-  1588,  1767,  1718,  1513};

-

-/*------------------------------------------------*

- * 5th split:   isf12 to isf15

- *------------------------------------------------*/

-

- static Word16 dico5_isf_noise[SIZE_BK_NOISE5*4] = {

-  -810,  -879,  -945,  -254,

-   248,   184,   671,   128,

-   288,   703,   918,    99,

-   658,   558,   662,   219,

-   552,   585,   910,   208,

-   559,   804,   759,   119,

-   606,   774,   921,  -139,

-   782,   761,   748,   208,

-   756,   708,   983,    56,

-   544,   864,  1010,   152,

-   737,   698,   987,   299,

-   771,   924,   879,   103,

-   536,   785,   961,   405,

-   667,   916,   801,   328,

-   738,   705,   773,   439,

-   823,   871,   992,   355,

-   640,  1004,  1052,   369,

-   724,   822,   949,   597,

-   415,   655,   729,   482,

-  1009,   896,   793,   363,

-   908,   803,   687,   -25,

-  1016,   838,  1011,   189,

-   947,  1112,   942,   222,

-   914,  1049,   981,   527,

-   956,   987,  1011,  -120,

-   781,  1049,  1121,    92,

-  1178,  1053,   884,    47,

-  1123,  1059,  1182,   118,

-   933,   972,  1277,   357,

-  1109,   918,  1101,   503,

-  1039,  1286,  1220,   317,

-  1351,  1207,  1010,   326};

-

+
+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/*-------------------------------------------------------------------*
+ *                         qisf_ns.h
+ *-------------------------------------------------------------------*
+ * Quantization tables for split by 5 VQ of ISFs for a background noise database
+ * Version whith no prediction
+ *-------------------------------------------------------------------*/
+
+#define ORDER   16            /* order of linear prediction filter */
+#define ISF_GAP 128
+
+#define SIZE_BK_NOISE1  64
+#define SIZE_BK_NOISE2  64
+#define SIZE_BK_NOISE3  64
+#define SIZE_BK_NOISE4  32
+#define SIZE_BK_NOISE5  32
+
+
+/* means of ISFs */
+ static Word16 mean_isf_noise[ORDER] = {
+
+   478,  1100,  2213,  3267,  4219,  5222,  6198,  7240,
+  8229,  9153, 10098, 11108, 12144, 13184, 14165,  3803};
+
+
+/* 28 bits */
+/*-------------------------------------------------------------------*
+ *  isf codebooks:  split-by-5 VQ                                    *
+ *                                                                   *
+ *  codebook   vector dimension    number of vectors                 *
+ *  ~~~~~~~~   ~~~~~~~~~~~~~~~~    ~~~~~~~~~~~~~~~~~                 *
+ *     1            2                  64                            *
+ *     2            3                  64                            *
+ *     3            3                  64                            *
+ *     4            4                  32                            *
+ *     5            4                  32                            *
+ *-------------------------------------------------------------------*/
+
+/*------------------------------------------------*
+ * 1st split:   isf0 to isf1
+ *------------------------------------------------*/
+
+
+ static Word16 dico1_isf_noise[SIZE_BK_NOISE1*2] = {
+
+  -269,  -673,
+  -222,  -537,
+  -233,  -430,
+  -138,  -451,
+  -212,  -331,
+  -192,  -241,
+   -87,  -231,
+  -191,  -128,
+   -70,  -106,
+  -164,    -6,
+    74,  -179,
+    27,   -33,
+  -102,    74,
+  -162,   115,
+   -94,   172,
+    -6,   130,
+  -143,   234,
+    14,   218,
+   -65,   270,
+    88,   182,
+  -124,   341,
+   -44,   381,
+    38,   335,
+   117,   274,
+  -112,   454,
+    74,   431,
+    -5,   488,
+   175,   384,
+   -83,   561,
+   122,   529,
+    21,   601,
+   229,   481,
+   231,   303,
+   226,   608,
+   300,   372,
+   210,   187,
+   306,   265,
+   328,   473,
+   382,   331,
+   371,   132,
+   139,    58,
+   365,    21,
+   250,   -82,
+   443,   218,
+   483,   110,
+   426,   415,
+   579,   222,
+   518,   333,
+   573,   448,
+   455,   529,
+   685,   329,
+   332,   580,
+   595,   593,
+   468,   645,
+   762,   517,
+   326,   709,
+   485,   793,
+   130,   684,
+   671,   737,
+   354,   876,
+    88,   806,
+   -65,   706,
+   -35,  1016,
+   266,  1123};
+
+
+/*------------------------------------------------*
+ * 2nd split:   isf2 to isf4
+ *------------------------------------------------*/
+
+ static Word16 dico2_isf_noise[SIZE_BK_NOISE2*3] = {
+
+  -824,  -884,  -949,
+  -805,  -456,  -418,
+  -442,  -438,  -541,
+  -217,  -578,  -793,
+  -168,  -444,  -582,
+  -287,  -492,  -274,
+  -552,  -297,  -300,
+  -163,  -333,  -358,
+  -370,  -232,  -232,
+  -175,  -358,  -159,
+  -381,   -21,  -357,
+  -184,  -159,  -162,
+   -53,  -191,  -280,
+    18,  -267,  -215,
+  -138,    61,  -283,
+    71,   -95,  -294,
+    13,  -156,  -546,
+     0,   -83,   -79,
+    44,    97,  -316,
+   178,   -52,  -213,
+   222,  -261,  -422,
+   237,  -118,   -44,
+   141,   145,  -132,
+   363,    81,  -287,
+   213,    65,    34,
+  -107,    94,    -5,
+    91,   -29,   126,
+  -355,    51,   -41,
+  -219,   -76,   145,
+   -63,   100,   244,
+  -719,    44,    27,
+  -572,  -124,   155,
+  -423,   133,   315,
+  -917,    71,   224,
+  -268,   318,   131,
+   -93,  -190,   420,
+   -97,   122,   491,
+   -79,   317,   355,
+   130,   100,   325,
+    86,  -293,   210,
+   133,   258,   161,
+   176,   -73,   465,
+   195,   300,   384,
+   348,    22,   221,
+   376,   183,   409,
+   377,   286,   202,
+   242,   213,   659,
+   257,   565,   248,
+   344,   408,   -76,
+   405,   440,   509,
+   612,   385,   379,
+   536,   607,   216,
+   -56,   582,   192,
+   100,   517,   567,
+  -365,   448,   445,
+   728,   347,    10,
+   505,   357,   759,
+   636,   582,   658,
+   335,   517,   852,
+   378,   809,   572,
+  -195,   878,   829,
+   529,   707,   987,
+   918,   726,   392,
+  1250,   997,  1063};
+
+/*------------------------------------------------*
+ * 3rd split:   isf5 to isf7
+ *------------------------------------------------*/
+
+ static Word16 dico3_isf_noise[SIZE_BK_NOISE3*3] = {
+
+  -805,  -838,  -774,
+  -522,  -627,  -828,
+  -477,  -486,  -603,
+  -295,  -481,  -634,
+  -366,  -384,  -393,
+  -186,  -414,  -396,
+  -237,  -394,  -106,
+  -252,  -202,  -275,
+   -61,  -177,  -442,
+   -84,  -198,  -199,
+  -179,  -125,   -31,
+   -72,   -47,  -163,
+  -298,  -220,   215,
+   -64,  -168,   251,
+  -133,   156,   -59,
+   -30,    -2,   127,
+    54,    66,   -61,
+  -233,    21,   251,
+   209,   -50,    32,
+    33,   194,   136,
+  -117,   -18,   475,
+   202,    46,   309,
+   256,   185,    53,
+    35,   200,   390,
+   200,   263,   242,
+  -216,   302,   294,
+   128,   358,     0,
+    19,   431,   287,
+   224,   447,   280,
+   367,   165,   213,
+   397,   314,   319,
+   383,   379,    75,
+   277,   325,   462,
+   394,   505,   334,
+   251,    98,  -213,
+   450,   153,   448,
+   565,   226,    76,
+   470,   383,   502,
+   635,   390,   278,
+   237,   135,   620,
+   342,   401,   649,
+   331,   551,   518,
+   130,   418,   592,
+   531,   306,   737,
+   729,   389,   580,
+   497,   557,   699,
+   296,   383,   874,
+   283,   624,   759,
+   126,   622,   476,
+   559,   595,   472,
+   382,   770,   616,
+   719,   613,   745,
+   540,   639,   928,
+   517,   826,   801,
+   684,   811,   604,
+   752,   786,   857,
+   933,   661,   350,
+   694,   450,  1061,
+   562,   911,  1051,
+   824,   813,  1104,
+   758,  1047,   882,
+  1140,   917,   889,
+  1039,  1246,  1426,
+  1483,  1666,  1876};
+
+/*------------------------------------------------*
+ * 4th split:   isf8 to isf11
+ *------------------------------------------------*/
+
+ static Word16 dico4_isf_noise[SIZE_BK_NOISE4*4] = {
+
+  -776,  -854,  -891,  -920,
+  -552,  -610,  -663,  -741,
+  -321,  -370,  -476,  -565,
+   274,  -160,  -456,   201,
+   265,    67,  -160,  -306,
+    -8,  -210,    79,   272,
+   163,   236,   307,   308,
+   578,   317,    64,   298,
+    -9,   197,   342,   620,
+   343,   232,   314,   622,
+   173,   149,   548,   527,
+   356,   370,   481,   376,
+   135,   444,   488,   556,
+   391,   471,   487,   653,
+   228,   424,   576,   835,
+   422,   372,   722,   682,
+   295,   673,   693,   635,
+   539,   596,   590,   449,
+   475,   618,   659,   818,
+   735,   517,   491,   673,
+   602,   346,   257,   877,
+   625,   635,   849,   720,
+   727,   818,   698,   595,
+   653,   481,   690,  1139,
+   814,   762,   704,   908,
+   507,   747,   898,   936,
+   848,   855,   924,   785,
+   646,  1037,   882,   795,
+   772,   845,  1024,  1151,
+  1133,   983,   818,   921,
+   940,  1068,  1252,  1302,
+  1588,  1767,  1718,  1513};
+
+/*------------------------------------------------*
+ * 5th split:   isf12 to isf15
+ *------------------------------------------------*/
+
+ static Word16 dico5_isf_noise[SIZE_BK_NOISE5*4] = {
+  -810,  -879,  -945,  -254,
+   248,   184,   671,   128,
+   288,   703,   918,    99,
+   658,   558,   662,   219,
+   552,   585,   910,   208,
+   559,   804,   759,   119,
+   606,   774,   921,  -139,
+   782,   761,   748,   208,
+   756,   708,   983,    56,
+   544,   864,  1010,   152,
+   737,   698,   987,   299,
+   771,   924,   879,   103,
+   536,   785,   961,   405,
+   667,   916,   801,   328,
+   738,   705,   773,   439,
+   823,   871,   992,   355,
+   640,  1004,  1052,   369,
+   724,   822,   949,   597,
+   415,   655,   729,   482,
+  1009,   896,   793,   363,
+   908,   803,   687,   -25,
+  1016,   838,  1011,   189,
+   947,  1112,   942,   222,
+   914,  1049,   981,   527,
+   956,   987,  1011,  -120,
+   781,  1049,  1121,    92,
+  1178,  1053,   884,    47,
+  1123,  1059,  1182,   118,
+   933,   972,  1277,   357,
+  1109,   918,  1101,   503,
+  1039,  1286,  1220,   317,
+  1351,  1207,  1010,   326};
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/qpisf_2s.tab b/media/libstagefright/codecs/amrwbenc/inc/qpisf_2s.tab
index 4d869a4..b6b4e81 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/qpisf_2s.tab
+++ b/media/libstagefright/codecs/amrwbenc/inc/qpisf_2s.tab
@@ -1,1360 +1,1360 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/*-------------------------------------------------------------------*

- *                         qpisf_2s.h

- *-------------------------------------------------------------------*

- * Quantization tables for two-stage of ISFs (split by 2 in 1st stage)

- * Version whith prediction MU = 0.25

- *-------------------------------------------------------------------*/

-

-#define ORDER   16            /* order of linear prediction filter */

-#define ISF_GAP 128           /* 50 Hz */

-#define N_SURV  4

-

-#define SIZE_BK1  256

-#define SIZE_BK2  256

-#define SIZE_BK21 64

-#define SIZE_BK22 128

-#define SIZE_BK23 128

-#define SIZE_BK24 32

-#define SIZE_BK25 32

-

-#define SIZE_BK21_36b 128

-#define SIZE_BK22_36b 128

-#define SIZE_BK23_36b 64

-

-/* means of ISFs */

-static Word16 mean_isf[ORDER] = {

-

-   738,  1326,  2336,  3578,  4596,  5662,  6711,  7730,

-  8750,  9753, 10705, 11728, 12833, 13971, 15043,  4037};

-

-/* 46 bits */

-/*-------------------------------------------------------------------*

- *  isf codebooks:  two-stage VQ with split-by-5 in 2nd stage        *

- *                                                                   *

- *  codebook   vector dimension    number of vectors                 *

- *  ~~~~~~~~   ~~~~~~~~~~~~~~~~    ~~~~~~~~~~~~~~~~~                 *

- *     1_1            9                  256                         *

- *     1_2            7                  256                         *

- *     2_1            3                  64                          *

- *     2_2            3                  128                         *

- *     2_3            3                  128                         *

- *     2_4            3                  32                          *

- *     2_5            4                  32                          *

- *-------------------------------------------------------------------*/

-

-/*------------------------------------------------*

- * 1st stage codebook; 1st split:   isf0 to isf8

- *------------------------------------------------*/

-

-static Word16 dico1_isf[SIZE_BK1*9] = {

-

-   579,  1081,  1035,   390,     3,  -263,  -198,   -82,    38,

-    18,   -68,   -12,   313,   761,   405,   249,   111,   -76,

-   740,  1263,  1292,  1006,   997,  1019,  1017,   976,   923,

-   -91,   827,   948,   648,   613,   535,   522,   490,   421,

-    41,   -44,  -281,  -472,   652,   534,   193,   135,   -90,

-    41,  -121,  -356,   -60,   663,   307,    61,   -48,  -344,

-   557,   946,  1049,   867,   846,   990,  1112,  1262,  1241,

-  -118,  -204,   328,   512,   870,   793,   610,   402,   186,

-   156,   293,    74,  -338,  -475,  -897,  -594,  -161,  -497,

-   226,   131,  -138,   307,   169,  -271,  -164,  -387,  -624,

-    62,   -32,   -61,  -252,  -541,  -828, -1027,  -523,  -662,

-   102,   -61,   141,   112,  -270,  -251,  -541,    25,  -150,

-     6,  -132,  -356,  -686,   -96,  -322,  -522,   -31,  -326,

-   -36,  -209,  -521,  -229,   307,  -132,    -5,   -99,  -384,

-    60,   -51,  -237,  -668,  -973,  -407,  -708,   -75,  -172,

-    26,  -138,  -266,   111,  -302,    43,  -278,  -356,  -359,

-   570,   822,   496,  -154,  -312,   -92,   137,   279,   371,

-  -146,   368,   409,    68,     6,    77,   167,   202,   162,

-   633,   898,   996,   756,   662,   683,   783,   909,   996,

-  -103,   294,   607,   415,   483,   462,   480,   431,   408,

-  -120,  -338,  -612,  -524,   584,   331,    92,   433,   276,

-  -178,  -293,  -154,   -41,   269,   100,    -9,   213,   160,

-   830,   736,   278,   820,  1254,   686,   712,  1039,   473,

-  -218,  -304,   463,   454,   397,   273,   202,   286,   273,

-  -232,     7,     6,  -388,  -472,  -427,  -378,  -167,  -100,

-  -294,  -183,   134,   -47,   101,   -88,   -84,  -117,    -3,

-    57,    17,  -202,  -634,  -989, -1119,  -533,   176,   -36,

-   120,   -28,    23,   111,  -319,   318,   -22,   -77,   266,

-  -271,  -464,  -434,  -658,  -640,  -385,  -385,   -99,   -69,

-  -198,  -259,  -266,   -44,   -39,  -139,  -137,   171,    66,

-     9,  -145,  -377,  -846, -1000,  -111,  -325,   342,   135,

-   -81,  -286,  -380,   192,   -57,   307,    76,   -24,  -140,

-   677,   702,   247,    56,   249,   141,  -105,  -236,   -99,

-    36,   -39,   -69,   348,   198,   -93,   322,    91,   -72,

-   503,   885,  1508,  1307,  1282,  1172,  1119,  1209,  1061,

-   416,   719,   989,  1227,  1001,  1052,   954,   741,  1044,

-  -127,  -376,  -657,   139,   623,   223,   501,   306,   220,

-  -113,  -384,  -796,   504,   438,    85,   213,   -83,  -194,

-   585,  1132,  1233,  1091,  1247,  1433,  1512,  1448,  1314,

-  -174,  -422,     7,  1155,  1089,  1182,  1003,   945,   806,

-     8,  -126,  -317,  -103,  -351,  -695,   -98,  -268,  -537,

-    33,  -103,  -290,   167,   -39,  -407,    44,  -208,  -375,

-   104,   -23,   -64,  -291,  -637,  -851, -1084,   -61,  -112,

-   -75,  -306,  -434,   218,  -148,  -354,  -680,  -133,  -216,

-  -121,  -377,  -718,   -97,  -130,  -361,  -156,  -379,  -599,

-   -56,  -254,  -586,   235,   157,  -214,    11,  -260,  -149,

-  -124,  -267,  -397,  -580,  -593,  -527,  -805,  -385,   346,

-  -193,  -440,  -708,  -351,  -141,  -255,  -499,  -147,  -185,

-   448,   660,   494,   208,   509,   461,   338,   291,   149,

-  -223,    88,   335,   159,   212,   191,   286,   308,   205,

-   -31,   469,   803,   659,   619,   658,   843,   987,  1113,

-  -171,  -242,   514,   362,   295,   524,   552,   694,   585,

-   -64,  -308,  -448,   -21,   284,   786,   446,   289,    92,

-  -218,  -390,    -7,   169,   206,   330,   352,   408,   358,

-   -36,   702,   959,   859,   861,  1115,  1269,  1357,  1305,

-  -133,  -341,   -65,   678,   417,   440,   486,   518,   780,

-    33,   -44,  -191,  -344,  -461,  -755,  -201,   217,   -31,

-  -353,  -547,   -44,   123,   -61,   -68,   -79,    29,    60,

-    73,   -57,  -406,  -766, -1243, -1203,   240,   400,   165,

-   -73,  -282,  -601,  -213,  -171,  -375,   332,    35,  -103,

-   -29,  -207,  -553,  -476,  -638,  -908,   172,   -22,  -135,

-  -192,  -239,  -164,  -103,  -111,   -47,   153,   125,   110,

-    -1,  -203,  -570, -1030, -1424,  -535,   155,     1,   147,

-  -333,  -653,  -865,  -197,  -158,   -21,   -44,    95,   108,

-   389,   588,   490,    33,  -237,  -524,  -628,  -136,  -260,

-    40,  -177,  -462,   453,   862,   380,   131,  -130,  -405,

-   842,  1678,  1841,  1549,  1474,  1256,  1082,   905,   742,

-   370,  1216,  1768,  1633,  1212,   636,    22,  -330,    71,

-   -76,  -281,  -741,  -742,   898,   619,   277,    71,  -222,

-   -32,  -265,  -556,   -25,   994,   682,   305,   126,  -165,

-    73,   738,   893,   968,   993,  1768,  2273,  1840,  1391,

-   -69,  -349,  -585,   234,  1158,   903,   626,   510,   251,

-    -1,   -99,  -272,  -210,  -603,  -351,  -540,  -811,  -383,

-   -16,  -230,  -504,   410,   149,  -205,  -343,  -651,  -639,

-   103,    -9,  -227,  -205,  -562,  -781, -1079, -1208,  -156,

-   143,    63,  -135,   -67,  -317,  -602,  -784, -1154,  -640,

-  -144,  -391,  -674,  -622,  -200,  -254,  -660,  -947,  -395,

-   -40,  -250,  -625,    27,   543,    94,  -131,  -386,  -673,

-  -123,  -371,  -757,  -451,  -564,  -614,  -415,  -711,   -35,

-  -116,  -309,  -593,  -268,   239,   -33,  -338,  -650,  -135,

-    94,   251,   554,    57,  -312,  -423,  -154,   -57,   235,

-  -268,   -71,   381,   114,   -44,   -87,   125,   173,   133,

-  1513,  1714,  1238,   534,   276,   315,   461,   459,   508,

-  -131,   -19,  1149,   670,   486,   356,   309,   369,   296,

-  -223,  -501,  -899,  -722,   -70,     6,   131,   310,   394,

-   -99,  -303,  -517,   249,    64,   -53,   135,   -11,   453,

-  -147,  -399,  -730,  -401,   817,   738,   802,   749,   575,

-  -154,  -435,  -739,   800,   593,   366,   529,   318,   326,

-  -224,    45,   -39,  -387,  -515,  -518,  -608,  -384,  -321,

-  -315,  -377,   143,  -101,  -113,  -377,  -177,  -144,   -12,

-   117,    40,  -239,  -651, -1051,  -581,  -737,  -990,  -328,

-    26,   -50,  -157,   -23,  -453,  -283,  -531,  -546,   192,

-  -252,  -501,  -743,  -589,  -627,  -499,  -328,  -118,   -72,

-  -324,  -494,  -244,  -306,  -144,  -177,  -262,  -135,   -78,

-   -36,  -234,  -519,  -961, -1290,  -314,  -479,  -371,   -45,

-   -95,  -292,  -535,    -8,  -300,   112,  -164,  -277,   198,

-   -99,  -128,   880,   836,   579,   351,    23,   -95,  -217,

-   -27,  -258,   124,  1011,   597,   425,   144,     7,   -73,

-   421,  1293,  1640,  1623,  1742,  1617,  1499,  1284,  1006,

-   -95,   752,  1680,  1569,  1618,  1436,  1200,   980,   712,

-   -69,  -300,  -683,  -435,  1132,   899,   504,   332,   109,

-   -74,  -323,  -637,   563,  1074,   608,   371,   105,   -49,

-   -78,   831,  1194,  1110,  1378,  1481,  1492,  1365,  1217,

-  -259,  -121,  1440,  1334,  1628,  1490,  1438,  1223,   933,

-   -82,  -306,  -613,  -222,  -378,  -675,  -545,  -671,  -845,

-    53,  -124,  -347,   422,    52,  -125,  -270,  -529,     9,

-    79,   -89,  -320,  -662,  -999, -1199, -1243,  -676,  -297,

-   -68,  -273,  -611,   137,  -146,  -397,  -627,  -845,  -220,

-  -112,  -346,  -797,  -826,   234,  -132,  -188,  -278,  -522,

-  -159,  -405,  -734,  -419,   293,    74,  -167,  -167,   184,

-  -153,  -437,  -833, -1080,  -336,  -472,  -561,  -340,  -253,

-  -169,  -423,  -820,  -904,  -131,   -19,  -346,  -604,    31,

-    33,   -31,   312,    62,  -148,    49,   -59,   564,   486,

-  -306,  -333,   194,   -44,    67,    72,   147,   205,   243,

-  -207,   -49,  1360,   983,   969,   991,  1014,  1110,   973,

-  -211,  -172,   883,   627,   711,   674,   705,   798,   746,

-   -88,  -325,  -763,  -974,   687,   908,   514,   382,   172,

-  -292,  -612,  -805,    63,   131,   270,   259,   352,   348,

-  -235,   -84,   955,   818,  1120,  1289,  1559,  1480,  1285,

-  -180,  -461,  -614,   657,   691,   745,   854,   783,   713,

-   -97,  -309,  -477,  -614,  -777,  -734,  -768,  -526,  -472,

-  -344,  -476,   -35,  -169,    49,   -77,  -150,  -240,  -141,

-   -52,  -268,  -639,  -919, -1278, -1113,  -342,  -333,  -151,

-   -68,  -242,  -585,   -73,  -209,  -478,  -159,  -429,   133,

-  -197,  -499, -1005, -1268,  -272,  -224,  -105,   -67,    17,

-  -363,  -618,  -414,  -116,   -62,    20,    10,   116,   108,

-  -195,  -475,  -906, -1260,  -891,  -441,  -277,  -142,   -28,

-  -226,  -519,  -950,  -700,  -275,  -266,  -116,  -105,    82,

-   404,   511,   520,   327,    17,  -194,  -333,  -536,  -586,

-  -114,  -130,   276,   237,   204,   342,   135,   -16,  -111,

-   670,  1208,  1168,   860,   742,   601,   528,   403,   309,

-   397,   621,   966,   752,   579,   398,   400,   329,   252,

-   191,   180,  -137,  -467,   272,   106,   -95,    17,  -192,

-   -80,  -290,  -626,   194,   598,   196,    21,  -281,    77,

-   510,   864,  1108,   807,   939,   902,   925,   717,   481,

-   137,   367,   534,   764,   670,   382,   296,   153,    84,

-   303,   497,   144,   -85,  -125,  -539,  -482,  -464,  -764,

-   233,   347,    68,  -147,   169,  -210,  -242,  -226,  -482,

-   307,   422,   154,  -175,  -386,  -722,  -724,  -904, -1015,

-   309,   308,   160,   -60,  -470,  -420,  -598,  -791,  -219,

-    68,   121,  -137,  -560,  -146,  -446,  -515,  -494,  -729,

-   130,    53,  -227,    46,   474,    32,  -161,  -192,  -490,

-   213,   164,   -71,  -465,  -876,  -161,  -456,  -587,   -48,

-   218,   117,    39,   177,  -194,   -88,  -226,  -418,    50,

-   210,   547,   569,   279,   121,   -44,   -50,    10,   -84,

-    58,   140,   182,    -5,   267,   117,   106,   211,   198,

-   539,   835,   913,   719,   617,   544,   591,   565,   642,

-   153,   559,   872,   460,   222,   108,   188,   180,   183,

-   158,   119,   284,  -153,  -271,   229,    87,   110,   -57,

-  -183,    82,   118,    21,    13,    40,   118,   191,   185,

-   162,   889,   654,   108,   -34,   244,   488,   561,   532,

-   163,    56,   609,   341,    50,   329,    68,   266,   218,

-   100,   206,    18,  -304,  -107,  -436,  -487,   -65,  -306,

-   -86,   154,   134,   -30,   -45,   -73,  -104,   -80,   -96,

-   245,   330,    10,  -440,  -849, -1082,    79,    40,  -265,

-   196,   372,   272,  -181,  -493,  -389,   275,    80,   -59,

-     2,   -12,  -246,  -505,  -100,  -436,    21,  -187,  -431,

-  -221,   -48,    36,  -271,  -186,  -147,  -109,    26,    71,

-   213,   140,    72,  -351,  -620,   -84,  -363,    69,    46,

-    91,   167,    -3,   -95,   -99,  -105,   -48,   114,   147,

-   259,   249,   172,   607,   406,    52,    59,  -189,  -320,

-   115,   -85,   -54,   574,   128,   226,   -59,  -253,   130,

-   -62,  1033,  1308,  1035,  1127,  1098,  1029,   961,   823,

-    39,   364,   757,   940,   728,   660,   659,   583,   770,

-  -115,  -338,  -760,  -471,   394,    37,   441,   178,     6,

-   -57,  -305,  -525,   796,   453,   188,    -4,  -114,   248,

-    71,   444,   797,   731,  1096,  1157,  1222,  1029,   811,

-   135,   359,   551,   425,   749,   815,   874,   704,   502,

-   132,   247,     0,  -206,  -449,  -750,  -258,  -514,  -633,

-   248,   249,    91,   121,  -195,  -499,   -90,  -282,  -435,

-    78,    20,  -277,  -623,  -983, -1224,  -415,  -458,  -639,

-   347,   509,   208,  -179,  -464,  -728,   -76,  -237,  -486,

-  -103,  -343,  -756,  -713,  -265,  -609,  -191,  -398,  -636,

-  -121,  -383,  -749,   567,   252,   -36,  -354,  -417,   -50,

-   204,   100,  -149,  -650, -1081,   -47,    -7,  -263,   111,

-   -46,  -180,  -267,  -324,  -562,  -394,  -692,   398,   292,

-   482,   670,   683,   624,   442,   165,   116,    36,  -149,

-   108,   247,   291,   247,   355,   122,   109,   224,   296,

-   -14,   945,   990,   801,   755,   815,   847,   913,   892,

-   292,   349,   725,   482,   388,   329,   429,   620,   667,

-   -34,   197,   213,  -127,    84,   494,   620,   575,   375,

-   126,   207,   172,   167,   362,   202,   296,   395,   455,

-    -6,   250,   539,   467,   636,   801,  1149,  1287,  1118,

-    27,   240,   369,   280,   440,   411,   634,   892,   953,

-   159,   170,   -58,  -395,  -797,  -690,    77,  -211,  -334,

-    -5,   -28,   -13,   -74,  -335,  -603,   300,    88,  -205,

-    82,   -33,  -364,  -698, -1203, -1153,   110,  -146,  -289,

-   113,     1,  -243,  -588,  -994,  -496,   414,   160,    42,

-   -56,  -247,  -440,  -693,  -996,  -479,    11,  -178,  -357,

-  -151,  -353,  -327,  -211,  -340,   141,    65,   425,   453,

-    34,  -169,  -455,  -932, -1215,   138,   499,   256,   324,

-    68,   139,   -15,  -547,  -478,    17,   306,   502,   481,

-   -32,  -134,   445,   129,  -143,  -244,  -503,  -507,  -599,

-    61,  -140,  -345,   496,   458,    -2,    20,  -227,  -514,

-   394,  1765,  1666,  1339,  1117,   806,   642,   479,   380,

-   215,   519,   920,  1053,  1090,   791,   528,   290,   155,

-   -54,  -233,  -647,  -602,   639,   294,    -2,  -167,  -442,

-   -78,  -315,  -791,  -113,   820,   403,   158,  -116,  -356,

-   529,  1851,  2003,  1228,   622,   -41,  -416,   344,   819,

-  -105,  -379,  -236,  1224,   893,   749,   568,   356,   214,

-   -17,  -199,  -144,    50,  -283,  -247,  -578,  -846, -1087,

-    69,   -11,  -381,  -206,   209,  -284,  -387,  -416,  -716,

-    39,    -5,  -145,  -374,  -682,  -909, -1074, -1169, -1066,

-   287,   226,    67,  -221,  -662,  -171,  -421,  -642,  -707,

-  -132,  -348,  -538,  -448,   -20,    -4,  -354,  -748,  -933,

-     4,   -75,  -289,  -598,   317,    52,  -208,  -297,  -559,

-   -88,  -264,  -358,  -589,  -631,  -248,  -523,  -822, -1071,

-    70,    -8,    54,  -314,  -515,    92,  -146,  -274,  -493,

-   199,    62,   391,   158,  -141,    71,  -219,  -203,  -207,

-   152,    40,   329,   162,   -29,    48,  -149,   108,   127,

-   635,  1058,   883,   492,   372,   312,   317,   274,   241,

-   267,   722,  1256,   882,   625,   248,     8,   -81,   -60,

-   -58,  -138,  -291,  -600,   -12,    -2,   -39,   147,   117,

-  -107,  -345,  -513,   459,    76,    92,  -272,   388,   262,

-   362,   516,   203,  -409,  -716,  -831,  -331,   185,   209,

-  -117,  -391,  -298,   671,   292,   538,   257,   166,   -38,

-  -102,  -319,  -194,  -283,  -573,  -262,  -579,  -219,  -444,

-  -235,    78,    11,  -168,  -101,  -229,  -263,  -321,  -123,

-    70,    50,  -170,  -599,  -996,  -588,  -263,  -516,  -455,

-   394,   363,   229,  -136,  -538,    21,  -183,  -348,  -201,

-  -124,  -368,  -640,  -879,  -847,  -209,  -409,  -494,  -515,

-  -127,  -341,  -541,  -425,  -510,   -10,  -252,  -473,  -291,

-    84,   -69,  -201,  -676,  -868,   103,  -311,  -132,  -320,

-     5,  -173,  -188,  -297,  -628,   197,   -57,     7,   -11,

-    49,  -160,    56,   558,   111,    33,  -311,  -440,  -463,

-    -1,  -246,  -307,   862,   453,   139,  -170,  -355,  -232,

-   279,   966,  1642,  1478,  1463,  1123,   795,   525,   339,

-  -197,   -38,  1702,  1331,  1252,   950,   692,   504,   426,

-  -108,  -344,  -861, -1172,   444,   354,    88,   -46,  -220,

-   -53,  -321,  -494,  1113,   744,   364,   198,   -34,   -75,

-   457,   955,  1177,  1214,  1427,  1457,  1345,   917,   539,

-   -69,   199,   897,  1140,  1343,  1183,   977,   742,   522,

-   122,    44,  -269,    27,  -155,  -562,  -307,  -590,  -773,

-   154,    42,  -160,   252,  -129,  -305,  -471,  -733,  -371,

-   135,   185,   -82,  -416,  -722,  -913,  -504,  -743,  -880,

-   149,   214,   -84,  -329,  -680,  -835,  -426,  -661,   -81,

-  -128,  -380,  -735,  -998,  -337,    17,  -182,  -467,  -697,

-   -84,  -290,  -510,  -592,    13,   440,   154,   -38,  -279,

-    70,   -61,  -246,  -727, -1047,   -80,  -381,  -535,  -704,

-   178,    -2,  -146,  -670,  -938,   482,   138,    63,    65,

-   -11,    15,   772,   443,   142,   -20,  -209,  -126,  -161,

-   -32,  -249,    95,   552,   124,    30,  -343,    82,   -86,

-   148,   751,  1515,  1105,   867,   606,   474,   448,   399,

-  -163,  -257,   899,  1097,   906,   751,   502,   390,   294,

-   -51,  -258,  -447,  -806,  -368,   763,   464,   364,   183,

-  -166,  -374,  -367,    87,    35,   399,   418,   856,   833,

-  -205,  -310,   588,   778,   785,  1065,  1118,  1245,  1157,

-  -173,  -312,   107,   345,   400,   790,   870,  1113,  1001,

-    -7,  -120,  -387,  -410,  -614,  -943,  -226,  -384,  -491,

-  -203,  -288,   -51,  -331,   -90,  -178,  -408,  -573,  -338,

-    56,   -29,  -273,  -627, -1041,  -798,  -247,  -467,   148,

-    66,    -2,  -205,  -205,  -575,  -349,   -57,  -352,   -58,

-   -45,  -225,  -471,  -924,  -497,    77,   -32,    44,  -135,

-  -277,  -491,  -497,  -502,  -424,  -202,  -137,    77,    96,

-    26,  -179,  -469, -1008, -1260,   262,   -35,  -132,  -259,

-   -66,  -232,  -447,  -533,  -789,  -191,  -100,  -267,   364};

-

-/*------------------------------------------------*

- * 1st stage codebook; 2nd split:   isf9 to isf15

- *------------------------------------------------*/

-

-static Word16 dico2_isf[SIZE_BK2*7] = {

-

-  1357,  1313,  1136,   784,   438,   181,   145,

-   636,   648,   667,   568,   442,   217,   362,

-   427,   440,   674,   524,   332,   117,  -417,

-   121,   295,   468,   465,   230,    44,  -221,

-  -147,  -240,   149,    80,   390,   278,   106,

-  -418,  -556,   552,   511,   235,   144,   -95,

-    43,   193,   274,   150,    67,    34,  -273,

-   -43,  -126,   171,   416,   282,    63,  -354,

-  -372,   -86,  -344,  -108,   -94,  -182,   -89,

-  -600,  -840,  -200,   465,   258,   -11,  -253,

-   -48,   329,    97,  -290,  -543,  -795,  -354,

-  -570,  -117,   187,    10,  -133,  -416,   -76,

-  -618,  -129,  -247,  -371,    45,   -76,   277,

- -1022, -1079,   126,   474,   254,   127,    52,

-  -281,    76,  -167,  -361,  -283,  -551,  -283,

-  -119,   -52,    -1,   134,   -32,  -204,  -415,

-  1064,   827,   637,   684,   464,   209,    12,

-   482,   416,   449,   371,   335,   294,   194,

-   719,   576,   365,   135,   113,    91,  -199,

-   298,   176,   493,   366,   194,   163,    36,

-   -35,  -236,  -259,   -36,    -4,    99,   152,

-   -98,  -306,   -27,   228,    90,   111,   -86,

-    91,    13,  -211,  -258,  -106,    86,   -64,

-    73,   -35,   -57,   -31,   162,    35,  -192,

-  -109,  -335,  -629,   -66,   -61,  -128,   322,

-  -495,  -669,  -728,   193,    31,  -220,   122,

-   324,    95,   -89,   -91,  -409,  -710,  -154,

-     0,  -234,    92,    33,  -343,  -609,  -220,

-  -343,  -408,  -476,  -655,  -153,    82,   222,

-  -490,  -745,  -255,    49,   -48,   135,  -127,

-   119,   -67,  -328,  -390,  -272,  -545,   -56,

-   -57,  -130,   -10,    -7,  -164,   -47,   -22,

-   984,  1064,   961,   568,   210,   -27,    16,

-   811,   691,   754,   514,   224,   -35,   166,

-   662,   704,   618,   386,    57,  -211,  -257,

-   510,   359,   418,   393,    91,  -144,   -18,

-  -193,   -31,   -27,   223,    89,  -143,    24,

-  -112,   -98,   471,   319,   185,     3,   175,

-   252,   146,   -47,   272,    48,  -211,  -234,

-   146,    69,   203,   364,    68,   -52,    51,

-  -259,  -478,  -697,  -349,  -758,  -501,    63,

-  -501,  -769,  -289,    79,  -311,  -497,  -106,

-   251,    53,  -235,  -469,  -895,  -884,   145,

-  -416,  -551,   140,  -133,  -523,  -775,    44,

-  -326,  -423,  -713,  -497,   -86,  -431,    99,

-  -757,  -772,  -160,   -76,   -46,   -32,   379,

-    85,   -35,  -200,  -401,  -663, -1040,  -247,

-  -180,  -330,   -92,  -376,    27,  -183,  -110,

-  1279,  1086,   781,   502,   324,   164,   157,

-   682,   466,   449,   277,   146,    28,   409,

-   635,   472,   390,   107,  -232,  -538,  -139,

-   196,   396,   332,   213,   209,   -29,   -81,

-   150,   -95,  -312,    76,   -77,  -320,   -50,

-    46,     9,    47,   175,   139,    30,   384,

-   218,   206,   -24,  -250,   -96,  -276,  -183,

-    26,   119,    38,    14,    -4,  -133,   -52,

-  -477,  -614,  -987,  -715,  -631,  -813,   200,

-  -744, -1009, -1065,  -745,  -631,  -171,    18,

-  -137,  -251,  -483,  -613,  -980, -1203,    12,

-  -605,  -767,  -562,  -686, -1088,  -515,    58,

-  -202,  -428,  -782, -1072,   -96,  -234,  -179,

-  -480,  -709, -1070,  -897,  -131,   -92,   321,

-  -145,  -193,  -512,  -729,  -572,  -765,  -210,

-  -331,  -585,  -525,  -631,  -281,  -208,  -303,

-  1165,  1104,   939,   828,   716,   426,   155,

-     6,  -109,   820,   778,   415,   113,   -27,

-   381,   339,   314,   265,   121,    -9,  -474,

-  -373,    47,   584,   442,    99,  -231,  -113,

-  -496,   -38,  -285,   262,   305,   170,     4,

-  -587,  -556,    69,    66,   471,   354,    13,

-  -138,    70,   -18,   106,    67,   167,  -302,

-  -445,  -141,   185,   191,   151,    83,  -133,

-  -257,  -521,  -720,  -198,   134,   -46,  -182,

-  -819, -1168,  -777,   512,   359,    95,  -113,

-   137,    -2,   -74,  -138,  -401,  -114,  -371,

-  -242,  -466,   204,   223,   -31,  -212,  -192,

-  -532,  -637,  -466,  -686,   256,   277,  -139,

- -1141, -1244,  -381,   -75,   -54,    14,    88,

-  -311,   115,  -143,  -499,  -343,   124,  -416,

-  -616,  -147,  -135,    43,    -4,   121,  -369,

-   835,   783,   641,   390,   355,   350,    64,

-    72,   194,   443,   467,   436,   219,   372,

-   464,   369,   192,     4,  -156,   -72,  -226,

-    57,   206,   303,   205,   188,   101,   265,

-   -40,  -205,  -488,  -184,   276,    64,   -26,

-  -217,  -433,  -297,   137,   328,   308,  -289,

-   378,    81,  -308,  -465,    57,   -37,   227,

-  -100,    24,   -36,  -151,   199,     8,   143,

-  -426,  -697, -1059,  -133,   388,   161,   321,

-  -644, -1023, -1271,    39,    66,  -123,    70,

-   372,   177,  -173,  -556,  -553,  -304,  -189,

-  -117,  -369,  -425,  -122,  -462,  -152,   -73,

-  -649,  -850, -1189,  -767,   497,   360,   222,

-  -798, -1139, -1455,  -190,   430,   234,   179,

-    42,   -94,  -405,  -692,    38,  -202,  -246,

-  -169,  -366,  -290,   -88,   -64,    32,  -292,

-  1010,   923,   938,   710,   465,   230,   342,

-   217,   300,  1054,   675,    68,  -458,  -179,

-    78,   453,   316,    18,  -237,  -496,  -243,

-   167,    21,   424,   215,   -91,  -303,  -170,

-  -290,   -81,   -70,   -67,    40,    54,   -59,

-  -353,  -427,   -90,    53,    94,     9,    54,

-   -28,   318,   283,    15,  -240,   -58,    79,

-   -75,  -121,   229,    35,    58,     6,  -133,

-  -351,  -514,  -744,  -834,  -705,  -137,   164,

- -1124, -1388, -1055,  -230,   -73,    40,    36,

-  -163,  -233,  -532,  -785, -1170,  -697,    96,

-  -788,  -959,  -246,  -430,  -624,  -165,    -8,

-  -856,  -540,  -630,  -907,  -337,   -70,    76,

-  -937, -1042,  -659,  -733,  -208,   199,   -26,

-  -523,    78,   -98,  -501,  -869,  -890,   -81,

-  -624,  -703,   -45,  -348,   -25,    87,  -186,

-  1005,   823,   546,   249,    90,   -22,   207,

-   298,   397,   381,   319,   200,    62,   303,

-   473,   379,   133,  -247,  -632,  -441,    75,

-   284,   208,   391,   115,   -25,    44,    95,

-   -72,    79,   -95,   -63,  -129,  -293,   203,

-  -164,  -349,   115,   122,    69,    -1,   378,

-   348,   170,    99,    58,  -179,  -302,   188,

-  -190,    -2,   150,    23,   -51,   -11,   216,

-  -615,  -863, -1090, -1427,  -802,   -48,    -6,

-  -961, -1276, -1548,  -727,   -58,    56,   223,

-  -124,  -255,  -561,  -988, -1277,  -148,   -82,

-  -480,  -660,  -891, -1191, -1339,  -325,    20,

-  -621,  -917, -1296, -1350,   264,   289,    50,

-  -844, -1022, -1345, -1329,  -293,    46,   278,

-  -260,  -468,  -829, -1176,  -533,  -560,   -78,

-  -215,  -484,  -822, -1233,  -791,    15,  -138,

-  1301,  1317,  1262,  1048,   716,   357,   -64,

-   578,   824,   925,   802,   630,   362,   102,

-   470,   925,   767,   514,   327,   190,  -112,

-   225,   492,   495,   437,   598,   384,   -45,

-    43,    82,   -42,   175,   519,   342,   -64,

-  -304,  -154,   159,   576,   403,   221,   327,

-   214,   244,   122,   -62,   312,    92,  -160,

-   218,   208,   310,   268,   306,   323,  -199,

-  -285,  -269,   -79,  -124,  -143,  -153,   236,

-  -205,  -384,  -426,   344,    59,  -185,  -184,

-  -272,   247,   126,  -210,  -518,  -468,    78,

-   -99,  -120,   502,   160,  -280,  -557,   304,

-  -423,   -17,  -283,  -443,   215,   212,  -140,

-  -564,  -684,  -228,   510,   361,   130,   323,

-  -428,   335,    98,   -65,    36,  -215,  -246,

-  -362,    51,   364,   -16,  -234,   150,  -165,

-   914,   883,   751,   653,   676,   464,  -153,

-   631,   545,   535,   720,   596,   360,   -81,

-   783,   712,   512,   439,   341,   251,  -391,

-   497,   417,   249,   372,   295,   173,  -193,

-   128,  -110,  -385,    93,    39,   173,  -231,

-   216,   -59,  -253,   462,   389,   154,    69,

-   455,   270,    -4,  -337,   -49,   233,  -322,

-   307,   143,    53,   218,   128,   236,  -156,

-   -37,  -186,  -240,  -411,  -110,     9,   399,

-  -140,  -365,  -628,   258,   380,   214,   277,

-   131,   454,   177,  -285,  -520,   108,  -214,

-    77,  -141,   201,  -123,  -490,  -131,    60,

-   -14,  -194,  -521,  -741,   273,   362,   -33,

-  -362,  -566,  -287,  -228,   161,   237,   317,

-  -269,   195,   -75,  -375,  -204,    11,    77,

-  -128,  -264,  -156,  -223,  -475,   265,    27,

-  1238,  1147,   916,   689,   432,   210,  -280,

-   800,   664,   879,   726,   411,   160,  -164,

-   454,   686,   536,   275,   147,    46,   111,

-   303,   486,   512,   355,   241,   181,   -69,

-    79,    92,    29,   147,   233,    52,    17,

-  -171,   289,   131,   439,   271,     3,   -10,

-   413,   241,   144,   174,   155,    -2,    14,

-    58,   217,   247,   219,   149,   175,   -18,

-   228,    -8,  -240,  -206,  -513,  -191,   202,

-   -96,  -272,  -454,    33,  -300,  -575,    46,

-   -10,  -108,  -246,  -347,  -770,  -535,     9,

-  -326,  -430,   -61,  -321,  -704,  -299,   201,

-    -1,  -280,  -603,  -419,  -185,    18,   -36,

-  -516,  -522,  -379,  -291,  -181,   -97,    27,

-  -159,  -313,  -525,  -224,  -510,  -831,  -197,

-  -292,  -459,   -59,  -310,  -562,  -143,  -351,

-  1066,   912,   631,   389,   207,    86,  -224,

-   596,   512,   596,   505,   314,   122,   -48,

-   787,   861,   441,   -93,  -303,    33,  -190,

-   257,   469,   337,    51,    15,   298,   -93,

-   295,    73,  -119,    25,    36,    23,   108,

-   -28,    -3,   -32,   114,    21,   185,   107,

-   482,   305,    15,  -279,  -319,    52,    96,

-   226,    46,   115,    72,  -136,   133,  -125,

-    18,  -207,  -559,  -590,  -503,  -482,   321,

-  -571,  -789,  -951,  -172,  -441,  -538,   113,

-   181,    14,  -310,  -641, -1001,  -202,   159,

-  -136,  -393,  -433,  -513,  -911,  -144,   -22,

-    72,  -265,  -706,  -954,  -159,    53,   332,

-  -338,  -591,  -852,  -383,  -395,    56,    44,

-    43,  -158,  -464,  -897,  -631,  -157,  -294,

-  -161,  -128,  -328,  -573,  -483,  -125,    11,

-  1017,   906,  1051,  1005,   679,   341,  -102,

-   359,   334,  1567,  1314,   723,   105,    10,

-   -65,   726,   529,   301,   220,    43,  -273,

-  -510,   436,   719,   566,   358,   179,   114,

-  -560,   298,   133,  -120,   342,   225,    14,

-  -899,  -101,   217,   617,   400,   146,   -58,

-   -41,   352,    82,  -196,    39,   121,  -167,

-  -212,    59,   447,   284,   423,   250,  -169,

-  -371,  -484,  -596,    30,   -41,   249,    22,

-  -372,  -650,  -794,   477,   445,   216,   -79,

-  -352,   275,    17,  -443,  -929,    92,    19,

-  -699,  -696,   431,   264,   -49,  -310,   182,

-  -978,  -217,  -430,  -400,   101,   261,    72,

-  -929,  -889,  -357,   -13,   463,   378,   236,

-  -826,    56,    30,  -299,  -360,  -128,   -51,

-  -878,  -299,  -111,    75,    65,    36,     3,

-   817,   368,   -25,   354,   697,   591,  -173,

-   309,   212,   222,   751,   484,   140,   -56,

-   593,   379,    70,    -8,   258,   180,   110,

-   165,   -46,   255,   297,   219,   273,   105,

-   160,   -70,  -358,  -181,   379,   330,   319,

-  -238,  -369,  -198,   740,   580,   319,  -143,

-   201,   109,  -202,  -456,   328,   276,  -141,

-   203,   170,   111,    42,   207,   360,   188,

-  -345,  -399,  -513,  -233,   650,   422,    81,

-  -635,  -961, -1220,   463,   539,   204,   209,

-   202,   -25,  -194,  -498,  -787,   193,  -143,

-  -449,  -538,   195,  -106,  -331,    68,    62,

-  -228,  -477,  -840,  -576,   317,   128,   283,

-  -671,  -937,  -807,  -114,   391,   335,   -62,

-   246,     2,  -314,  -679,  -303,   180,   -88,

-  -107,  -272,    90,  -198,   -28,   290,  -112,

-   885,  1149,  1021,   712,   496,   281,   -83,

-   269,   492,   787,   643,   347,    70,   124,

-   336,   636,   499,    92,  -229,  -179,   191,

-    26,   402,   564,   340,   149,   -11,   135,

-  -440,   561,   470,   204,   -72,  -186,   140,

-  -720,    14,   355,   229,    68,  -133,   465,

-   110,   310,   103,    12,   106,    29,   158,

-  -178,   113,   161,   142,   121,   115,    27,

-  -651,  -414,  -645,  -152,  -164,   -13,  -429,

-  -639,  -944,  -681,  -104,   -81,    52,  -189,

-  -663,  -164,  -316,  -683,  -954,  -205,   -83,

-  -609,  -669,  -172,  -517,  -694,   283,   -80,

-  -646,  -152,  -383,  -678,  -246,   -40,  -143,

-  -747,  -796,  -745,  -390,   -98,    43,   275,

-  -599,  -199,  -398,  -433,  -436,  -538,    31,

- -1107,  -568,  -376,  -265,  -126,   -21,     1,

-   847,   573,   308,   392,   305,   101,    55,

-   273,   293,   201,   267,   346,   201,   123,

-   727,   480,   226,     2,   -65,  -138,   164,

-   273,   208,   173,   292,    12,   253,   174,

-   340,   207,   180,    88,   116,    46,   475,

-  -460,  -166,   -30,    13,   110,   173,   396,

-   137,    88,    43,  -137,   -94,    34,   284,

-    96,   -14,   226,    40,    63,    70,   130,

-  -467,  -735, -1012, -1174,  -307,   305,   -67,

-  -612,  -920, -1146,  -567,    -8,    92,   -25,

-  -182,  -271,  -492,  -754,  -857,   287,   -75,

-  -494,  -787,  -689,  -683,  -709,   137,  -326,

-  -288,  -550,  -903, -1105,   334,   321,   -62,

-  -354,  -653,  -834,  -445,     1,   377,  -152,

-  -162,  -306,  -608,  -937,  -297,   247,  -192,

-  -234,  -477,  -244,  -488,  -266,   342,  -332};

-

-/*---------------------------------------------------*

- * 2nd stage codebook; 1st split:   isf2_0 to isf2_2

- *---------------------------------------------------*/

-

-

-static Word16 dico21_isf[SIZE_BK21*3] = {

-

-   329,   409,   249,

-   -33,   505,   160,

-   -29,   -14,   582,

-  -262,   127,   354,

-   145,   237,   175,

-  -152,   245,   122,

-    27,    42,   340,

-   -84,   -93,   311,

-   285,   222,  -156,

-    47,   -43,  -504,

-   234,   121,   385,

-   104,  -317,    45,

-   176,   195,     8,

-   104,   -59,   -94,

-   177,    53,   192,

-   -34,  -127,   152,

-   570,   277,   -34,

-   -67,  -329,  -639,

-  -157,  -272,   462,

-  -177,  -462,   198,

-   322,   179,   115,

-  -386,   171,    19,

-    19,   -12,   195,

-  -120,  -252,   201,

-   304,    36,  -336,

-  -128,  -221,  -380,

-   171,  -185,   296,

-  -242,  -312,    23,

-   198,    39,    16,

-    -3,  -177,  -111,

-   111,   -93,    76,

-   -92,  -223,     4,

-   177,   406,   -44,

-  -168,   380,  -149,

-    -4,   273,   331,

-  -420,   513,   277,

-    21,   247,    47,

-   -58,   131,    -2,

-    -3,   134,   180,

-  -145,    40,   175,

-   189,    74,  -145,

-   -27,   -45,  -325,

-   370,  -114,   -21,

-   -83,  -415,  -173,

-    77,    95,   -51,

-   -40,   -30,   -67,

-    71,    88,    86,

-   -35,   -98,    14,

-    69,   197,  -334,

-  -196,    79,  -231,

-  -348,  -137,   218,

-  -352,   -89,   -85,

-    47,   201,  -130,

-  -165,    37,   -15,

-   -43,     3,    86,

-  -161,  -108,    79,

-    83,    21,  -237,

-   -81,  -149,  -238,

-   150,  -186,  -251,

-  -186,  -249,  -162,

-   -19,    66,  -139,

-   -26,   -50,  -181,

-    24,    11,     0,

-  -130,  -105,   -98};

-

-

-

-/*---------------------------------------------------*

- * 2nd stage codebook; 2nd split:   isf2_3 to isf2_5

- *---------------------------------------------------*/

-

-

-static Word16 dico22_isf[SIZE_BK22*3] = {

-

-  -127,   310,    42,

-  -242,   197,     5,

-  -151,    84,   -17,

-  -214,   127,  -149,

-  -247,  -131,   159,

-  -268,  -267,   -95,

-  -217,     1,   -79,

-  -271,   -80,  -185,

-   -45,   436,   159,

-   165,   199,   391,

-   -33,    81,   187,

-   -66,   -42,   355,

-  -298,   -57,   343,

-  -108,  -537,   226,

-  -144,   -23,   193,

-   176,  -402,    87,

-    53,   296,    25,

-   -84,   253,  -104,

-   -58,   105,  -126,

-  -169,   174,  -314,

-   -48,    44,  -294,

-  -164,  -417,  -242,

-  -139,     3,  -194,

-  -155,  -207,  -211,

-   119,   322,   213,

-   333,    50,   380,

-   237,   247,    -2,

-   466,   -16,   201,

-   238,  -255,  -107,

-    67,  -440,  -149,

-   122,   -88,  -139,

-    88,  -247,   -73,

-   -41,   231,   167,

-   -62,   155,    16,

-   -65,    16,    77,

-   -68,    -2,   -63,

-  -151,  -300,   160,

-   -18,  -333,    54,

-   -56,   -94,     5,

-     2,  -190,    14,

-    92,   148,   209,

-   108,     9,   272,

-   108,    35,   110,

-   142,   -85,   145,

-    47,  -157,   279,

-     3,  -320,   246,

-    43,   -72,    68,

-    86,  -217,   135,

-    36,   140,    79,

-    56,   175,   -49,

-    26,    45,     3,

-    73,    55,  -101,

-   109,  -183,  -242,

-    -4,  -283,  -242,

-    48,   -68,   -48,

-    -6,  -153,  -122,

-   161,   196,    96,

-   232,    80,   190,

-   165,    97,    11,

-   258,   -31,    71,

-   267,   -77,   -91,

-   311,  -209,    87,

-   152,   -14,   -22,

-   150,  -149,     9,

-  -324,   557,   187,

-  -384,   307,    46,

-  -251,    27,    77,

-  -365,    77,   -52,

-  -482,   -84,   160,

-  -424,  -515,   -64,

-  -294,  -120,    -4,

-  -476,  -116,  -109,

-   -97,   318,   365,

-   106,   627,   445,

-  -190,   120,   287,

-  -146,    65,   619,

-  -427,   242,   363,

-  -361,  -371,   432,

-  -347,   102,   168,

-  -629,   195,   -14,

-   -65,   476,   -47,

-  -297,   320,  -168,

-   -55,   356,  -264,

-  -391,    82,  -286,

-   -51,   -31,  -556,

-  -178,  -399,  -586,

-  -205,   -49,  -360,

-  -343,  -238,  -337,

-   220,   457,    58,

-   561,   467,   259,

-   340,   270,  -168,

-   450,    77,  -280,

-    60,   167,  -413,

-   133,  -252,  -492,

-   216,   157,  -290,

-   282,     0,  -495,

-  -226,   293,   183,

-  -157,   135,   122,

-  -158,   -59,    39,

-  -133,  -118,   -97,

-  -332,  -309,   113,

-  -160,  -425,    -6,

-  -149,  -211,    24,

-   -80,  -277,   -90,

-   -11,   125,   338,

-   130,   -71,   465,

-     5,   -45,   184,

-   237,   -95,   253,

-  -139,  -197,   297,

-   -19,  -300,   511,

-   -63,  -152,   139,

-   250,  -289,   336,

-   124,   339,  -150,

-    34,   176,  -208,

-   171,   166,  -116,

-    94,    38,  -229,

-    75,   -65,  -339,

-   -78,  -205,  -385,

-     0,   -30,  -163,

-   -56,  -110,  -242,

-   321,   244,   194,

-   505,   238,    -1,

-   317,   116,    65,

-   309,    88,   -74,

-   452,   -51,   -50,

-   334,  -217,  -290,

-   211,    41,  -152,

-   238,   -55,  -260};

-

-

-/*---------------------------------------------------*

- * 2nd stage codebook; 3rd split:   isf2_6 to isf2_8

- *---------------------------------------------------*/

-

-

-static Word16 dico23_isf[SIZE_BK23*3] = {

-

-   -10,   151,   359,

-   136,   298,   223,

-   255,  -104,   290,

-   423,     6,   183,

-  -270,  -269,   -98,

-   -52,   -82,    13,

-   -82,  -274,   -97,

-    90,  -246,   -72,

-  -299,   -70,   421,

-   -88,   365,   430,

-   187,  -318,   381,

-   380,    37,   488,

-  -373,  -316,    79,

-  -308,  -101,     5,

-  -135,  -451,     8,

-    72,  -421,  -154,

-   180,   170,  -121,

-    62,   177,   -40,

-   326,    80,  -105,

-   248,   263,    -5,

-  -168,  -181,  -221,

-    -2,   -23,  -158,

-   -14,  -149,  -121,

-   119,   -91,  -147,

-   119,   332,  -153,

-    49,   303,    34,

-   442,   -55,   -69,

-   217,   454,    58,

-  -359,  -187,  -375,

-   -42,    50,  -274,

-    -8,  -267,  -249,

-    85,   -86,  -346,

-   -77,   -40,   345,

-    89,   134,   219,

-   156,   -80,   160,

-   108,    40,   116,

-  -158,  -206,    29,

-     5,   -32,   175,

-   -65,  -158,   146,

-    55,   -78,    73,

-  -114,  -222,   353,

-   -47,    81,   211,

-    49,  -151,   268,

-   105,     4,   302,

-  -263,  -132,   183,

-  -151,   -28,   201,

-  -177,  -307,   166,

-   101,  -221,   130,

-    74,    58,   -98,

-    32,    44,    13,

-   194,    30,  -142,

-   170,    96,     8,

-  -136,  -119,   -91,

-   -65,     8,   -55,

-     3,  -188,    12,

-    45,   -63,   -49,

-   149,   -21,   -19,

-    24,   144,    95,

-   254,   -22,    60,

-   161,   196,    96,

-  -158,   -61,    48,

-   -70,    33,    82,

-   -23,  -321,    58,

-   155,  -147,     5,

-  -364,   328,    77,

-   -21,   453,   173,

-  -108,    82,   630,

-   367,   263,   208,

-  -300,   -62,  -176,

-  -205,   143,  -158,

-  -169,  -410,  -264,

-   257,  -269,  -100,

-  -636,   289,    -2,

-  -292,   627,   173,

-  -382,  -363,   387,

-   248,   524,   447,

-  -521,  -111,  -107,

-  -395,   118,  -274,

-  -343,  -680,  -125,

-  -172,  -447,  -663,

-    75,   148,  -367,

-   -79,   263,   -94,

-   249,   148,  -286,

-   380,   271,  -162,

-  -142,    -4,  -186,

-   -57,   111,  -125,

-   -35,  -108,  -254,

-   100,    29,  -242,

-   -80,   303,  -264,

-   -78,   464,   -57,

-   248,   -22,  -494,

-   661,   662,    44,

-  -193,   -40,  -330,

-  -178,   145,  -337,

-   -90,  -199,  -400,

-   -40,   -23,  -498,

-  -192,   114,   315,

-   -41,   244,   190,

-    88,   -97,   485,

-   241,    80,   212,

-  -246,    40,    87,

-  -156,   147,   134,

-    -2,  -334,   239,

-   308,  -203,   110,

-  -459,   251,   422,

-  -218,   310,   228,

-   -86,  -346,   654,

-   184,   175,   425,

-  -481,   -63,   169,

-  -349,   117,   188,

-  -125,  -560,   310,

-   158,  -416,    94,

-    46,   171,  -192,

-   -63,   157,    14,

-   256,   -35,  -271,

-   322,   123,    53,

-  -214,     4,   -76,

-  -156,    86,   -18,

-   128,  -197,  -232,

-   265,   -90,   -98,

-  -308,   332,  -145,

-  -131,   308,    58,

-   509,    59,  -339,

-   562,   196,   -14,

-  -378,   100,   -47,

-  -234,   202,     1,

-   104,  -270,  -493,

-   319,  -210,  -325};

-

-

-/*---------------------------------------------------*

- * 2nd stage codebook; 4th split:   isf2_9 to isf2_11

- *---------------------------------------------------*/

-

-static Word16 dico24_isf[SIZE_BK24*3] = {

-

-   -79,   -89,    -4,

-  -171,    77,  -211,

-   160,  -193,    98,

-   120,  -103,   323,

-    32,   -22,  -129,

-    72,    78,  -268,

-   182,   -76,   -66,

-   309,    99,  -145,

-  -229,  -157,   -84,

-  -383,    98,   -71,

-   -90,  -352,    12,

-  -284,  -178,   178,

-   -65,  -125,  -166,

-   -87,  -175,  -351,

-    42,  -198,   -48,

-   154,  -140,  -243,

-   -77,    18,   108,

-   -39,   355,    91,

-    87,     8,   155,

-    -4,   158,   239,

-   128,    95,   -54,

-     7,   246,  -124,

-   258,    15,    89,

-   206,   216,    98,

-  -201,     9,    18,

-  -312,   233,   204,

-   -39,  -174,   155,

-  -144,    -9,   284,

-   -57,    70,   -69,

-  -157,   187,    18,

-    54,   -30,    23,

-    24,   135,    55};

-

-

-/*---------------------------------------------------*

- * 2nd stage codebook; 5th split:   isf2_12 to isf2_15

- *---------------------------------------------------*/

-

-static Word16 dico25_isf[SIZE_BK25*4] = {

-

-   169,   142,  -119,   115,

-   206,   -20,    94,   226,

-  -106,   313,   -21,    16,

-   -62,   161,    71,   255,

-   -89,   101,  -185,   125,

-    72,   -30,  -201,   344,

-  -258,    33,    -8,    81,

-  -104,  -154,    72,   296,

-   144,   -68,  -268,   -25,

-    81,   -78,   -87,   106,

-    22,   155,  -186,  -119,

-   -46,   -28,    27,    91,

-  -114,   -37,  -175,   -33,

-   -94,  -222,  -189,   122,

-  -132,  -119,  -191,  -270,

-  -172,  -173,    18,   -43,

-   279,   135,   -42,  -128,

-   187,   -86,   229,  -138,

-   159,   240,   140,    46,

-    69,    25,   227,    77,

-    21,   115,    13,     8,

-    68,  -248,   126,    81,

-  -150,   137,   207,    -9,

-  -154,  -133,   289,    67,

-   143,   -37,   -86,  -326,

-   180,   -32,    19,   -23,

-    26,   168,   116,  -233,

-   -32,   -26,   118,   -78,

-     3,    -8,   -45,  -115,

-    57,  -215,   -54,   -83,

-  -209,   112,   -22,  -167,

-   -91,  -151,   168,  -262};

-

-

-

-       /* 36 bit */

-/*-------------------------------------------------------------------*

- *  isf codebooks:  two-stage VQ with split-by-3 in 2nd stage        *

- *                1st stage is kept the same as the 46 bit quantizer *

- *                                                                   *

- *  codebook   vector dimension    number of vectors                 *

- *  ~~~~~~~~   ~~~~~~~~~~~~~~~~    ~~~~~~~~~~~~~~~~~                 *

- *     1_1            9                  256                         *

- *     1_2            7                  256                         *

- *     2_1            5                  128                         *

- *     2_2            4                  128                         *

- *     2_3            7                  64                          *

- *-------------------------------------------------------------------*/

-

-static Word16 dico21_isf_36b[SIZE_BK21_36b*5] = {

-

-   -52,   -96,   212,   315,   -73,

-    82,  -204,   363,   136,  -197,

-  -126,  -331,   183,   218,   143,

-   -49,   -41,   557,   230,    72,

-     2,   -73,   163,   377,   221,

-   133,   111,   278,   215,  -110,

-  -102,   -20,   284,   113,   273,

-    84,   319,   290,    18,    85,

-   -25,    -5,   125,   132,  -204,

-   -38,    -5,   286,    -9,  -356,

-  -140,  -256,    92,   117,  -189,

-  -144,   191,   313,    51,   -98,

-   167,   -10,    44,   247,    36,

-   381,   197,   238,    74,     6,

-    38,  -408,    29,    -3,   -85,

-    92,   266,   157,   -25,  -200,

-   161,  -121,    70,    84,  -140,

-   -16,   -86,   112,   -94,  -189,

-  -269,  -270,   351,   107,   -24,

-   -68,   -67,   492,  -103,  -155,

-   -53,  -131,    62,   122,    10,

-   135,    84,   283,   -55,  -120,

-   -12,  -219,   331,   -81,   167,

-   220,  -136,   147,  -172,   -42,

-   140,   -95,  -109,   -88,  -194,

-     0,    -2,    -4,   -33,  -381,

-   -66,  -217,   152,  -186,  -402,

-   244,   108,   156,  -140,  -395,

-   113,  -136,  -196,   110,   -24,

-   214,   118,    11,   -64,  -131,

-  -110,  -286,    -6,  -332,    16,

-    94,    97,    79,  -291,  -205,

-    -5,   -39,   -20,   252,   -96,

-    76,   174,   101,   163,    61,

-   -69,  -239,   -55,   399,     6,

-  -115,   319,   164,   275,   196,

-   -15,    36,   -47,   331,   121,

-   226,   209,   271,   325,   184,

-    13,   -80,  -218,   471,   353,

-   288,   378,    16,   -51,   251,

-   174,   116,    52,   149,  -279,

-   235,   276,    39,   120,   -48,

-     0,  -108,  -108,   241,  -339,

-   -93,   534,    45,    33,   -87,

-   194,   149,   -71,   405,   -44,

-   409,   370,    81,  -186,  -154,

-    25,  -102,  -448,   124,  -173,

-    22,   408,  -110,  -310,  -214,

-   -26,    23,   -83,   114,    14,

-  -110,   164,    52,   223,   -82,

-    37,   -25,  -263,   306,   -15,

-  -466,   415,   292,   165,   -18,

-    29,   -19,  -171,   155,   182,

-   179,   144,   -27,   231,   258,

-  -103,  -247,  -396,   238,   113,

-   375,  -154,  -109,    -4,   156,

-    98,    85,  -292,    -5,  -124,

-   116,   139,  -116,   -98,  -294,

-   -14,   -83,  -278,  -117,  -378,

-   106,    33,  -106,  -344,  -484,

-   119,    17,  -412,   138,   166,

-   384,   101,  -204,    88,  -156,

-  -121,  -284,  -300,    -1,  -166,

-   280,    33,  -152,  -313,   -81,

-   -37,    22,   229,   153,    37,

-   -60,   -83,   236,    -8,   -41,

-  -169,  -228,   126,   -20,   363,

-  -235,    17,   364,  -156,   156,

-   -25,   -30,    72,   144,   156,

-   153,   -26,   256,    97,   144,

-   -21,   -37,    48,   -65,   250,

-    63,    77,   273,  -128,   124,

-  -129,   -26,    40,     9,  -115,

-    -6,    82,    38,   -90,  -182,

-  -336,   -13,    28,   158,    91,

-   -30,   241,   137,  -170,   -17,

-   146,    14,   -11,    33,    61,

-   192,   197,    54,   -84,    85,

-    23,  -200,   -78,   -29,   140,

-   122,   237,   106,  -341,   136,

-   -57,  -142,   -85,   -16,   -74,

-   -59,   -90,    -8,  -187,   -20,

-  -211,  -267,   216,  -179,  -110,

-   -50,    -7,   220,  -267,   -70,

-   -57,   -42,   -17,   -15,    71,

-    32,    21,    63,  -137,    33,

-  -137,  -175,   104,   -68,    97,

-   -67,   -43,   133,  -301,   221,

-  -116,  -200,   -81,   -92,  -272,

-   -64,   -41,   -54,  -244,  -220,

-  -287,  -242,   -50,   -87,   -89,

-  -245,   236,   102,  -166,  -295,

-    66,    24,  -162,   -71,    95,

-    66,   136,   -90,  -220,   -36,

-   -98,  -161,  -222,  -188,    29,

-   -18,    18,   -19,  -415,     9,

-    49,    61,   100,    39,   -56,

-  -111,    82,   135,   -31,    52,

-   -90,  -153,   -93,   189,   182,

-  -214,   295,   119,   -74,   284,

-     2,   137,    37,    47,   182,

-    92,   117,   184,   -53,   373,

-   -21,   -14,   -35,   136,   391,

-   146,   129,  -164,   -28,   333,

-    92,    80,   -84,   100,  -134,

-    -8,   217,   -32,     3,   -47,

-  -151,   251,  -215,   142,    92,

-  -224,   310,  -172,  -275,    98,

-   159,   155,  -177,   112,    53,

-   205,    27,     8,  -240,   192,

-   169,   120,  -319,  -201,   106,

-    11,    36,   -86,  -237,   455,

-  -109,  -154,  -163,   174,   -55,

-   -38,    32,  -101,   -78,   -59,

-  -205,  -321,   -97,    69,    79,

-  -310,    44,    18,  -185,    34,

-  -115,   -20,  -148,   -39,   203,

-   -29,   154,   -30,  -158,   166,

-   -45,  -131,  -317,   -24,   363,

-  -165,  -205,  -112,  -222,   265,

-   -32,   -44,  -150,    54,  -193,

-    -6,   -38,  -255,  -169,  -115,

-  -266,    87,  -189,   -36,  -169,

-   -60,   -87,  -266,  -436,  -170,

-   -68,   -81,  -278,    24,    38,

-   -23,   -19,  -155,  -256,   141,

-   -61,  -226,  -565,  -175,    71,

-     9,   -29,  -237,  -515,   263};

-

-static Word16 dico22_isf_36b[SIZE_BK22_36b*4] = {

-

-  -298,    -6,    95,    31,

-  -213,   -87,  -122,   261,

-     4,   -49,   208,    14,

-  -129,  -110,    30,   118,

-  -214,   258,   110,  -235,

-   -41,   -18,  -126,   120,

-   103,    65,   127,   -37,

-   126,   -36,   -24,    25,

-  -138,   -67,  -278,  -186,

-  -164,  -194,  -201,    78,

-  -211,   -87,   -51,  -221,

-  -174,   -79,   -94,   -39,

-    23,    -6,  -157,  -240,

-    22,  -110,  -153,   -68,

-   148,    -5,    -2,  -149,

-    -1,  -135,   -39,  -179,

-    68,   360,  -117,   -15,

-   137,    47,  -278,   146,

-   136,   260,   135,    65,

-    61,   116,   -45,    97,

-   231,   379,    87,  -120,

-   338,   177,  -272,     3,

-   266,   156,    28,   -69,

-   260,    84,   -85,    86,

-  -266,   154,  -256,  -182,

-   -17,   -65,  -304,    -6,

-   -40,   175,  -151,  -180,

-   -27,    27,   -87,   -63,

-   121,   114,  -166,  -469,

-   159,   -66,  -323,  -231,

-   214,   152,  -141,  -212,

-   137,    36,  -184,   -51,

-  -282,  -237,    40,    10,

-   -48,  -235,   -37,   251,

-   -54,  -323,   136,    29,

-   -88,  -174,   213,   198,

-  -390,    99,   -63,  -375,

-   107,  -169,  -164,   424,

-    69,  -111,   141,  -167,

-    74,  -129,    65,   144,

-  -353,  -207,  -205,  -109,

-  -160,  -386,  -355,    98,

-  -176,  -493,   -20,  -143,

-  -252,  -432,    -2,   216,

-   -90,  -174,  -168,  -411,

-    13,  -284,  -229,  -160,

-   -87,  -279,    34,  -251,

-   -75,  -263,   -58,   -42,

-   420,    53,  -211,  -358,

-   384,   -35,  -374,   396,

-    68,  -228,   323,    -2,

-   167,  -307,   192,   194,

-   459,   329,    -5,  -332,

-   375,    79,    -7,   313,

-   282,  -124,   200,   -92,

-   271,  -162,   -70,   180,

-  -157,  -298,  -514,  -309,

-    58,  -163,  -546,    18,

-   124,  -364,   167,  -238,

-    83,  -411,  -117,    96,

-   140,  -112,  -388,  -624,

-   259,  -133,  -317,    41,

-   163,  -130,   -64,  -334,

-   226,  -165,  -124,  -110,

-  -466,   -61,     6,   229,

-  -153,   205,  -145,   242,

-  -159,    48,   195,   148,

-   -58,    28,    31,   279,

-  -303,   185,   279,    -4,

-   -61,   197,    59,    86,

-  -114,   123,   168,   -52,

-    35,    36,   100,   126,

-  -407,   102,   -77,   -40,

-  -338,    -1,  -342,   156,

-  -179,   105,   -34,   -97,

-  -185,    84,   -35,   108,

-  -133,   107,   -91,  -357,

-  -180,    54,  -229,    24,

-   -44,    47,    47,  -182,

-   -66,    13,    45,     4,

-  -339,   251,    64,   226,

-   -42,   101,  -350,   275,

-   -99,   398,   142,   121,

-   111,    12,  -102,   260,

-     0,   505,   260,   -94,

-   161,   285,   -96,   224,

-    -4,   206,   314,    33,

-   167,   139,    88,   204,

-  -235,   316,   -60,   -25,

-    -8,  -150,  -312,   201,

-   -36,   292,    61,  -104,

-   -40,   174,  -162,    42,

-   -21,   402,   -29,  -351,

-    21,   152,  -360,   -93,

-    57,   191,   212,  -196,

-    76,   158,   -21,   -69,

-  -328,  -185,   331,   119,

-   -53,   285,    56,   337,

-  -107,   -24,   405,    29,

-   -18,   137,   272,   277,

-  -255,    22,   173,  -191,

-   295,   322,   325,   302,

-    21,   -27,   332,  -178,

-   119,    13,   271,   129,

-  -455,  -180,   116,  -191,

-  -227,    62,  -148,   524,

-  -176,  -287,   282,  -157,

-  -243,    13,   199,   430,

-   -59,   -49,   115,  -365,

-    72,  -172,  -137,    93,

-  -138,  -126,   141,   -84,

-     5,  -124,    38,   -20,

-  -258,   311,   601,   213,

-    94,   130,   -61,   502,

-    -1,  -157,   485,   313,

-   146,   -74,   158,   345,

-   276,   135,   280,   -57,

-   490,   252,    99,    43,

-   267,   -74,   429,   105,

-   278,   -23,   119,    94,

-  -542,   488,   257,  -115,

-   -84,  -244,  -438,   478,

-  -113,  -545,   387,   101,

-   -95,  -306,   111,   498,

-    95,   166,    22,  -301,

-   420,   -15,   -58,   -78,

-   270,    29,   122,  -282,

-   160,  -240,    50,   -38};

-

-static Word16 dico23_isf_36b[SIZE_BK23_36b*7] = {

-

-    81,   -18,    68,   -27,  -122,  -280,    -4,

-    45,  -177,   209,   -30,  -136,   -74,   131,

-   -44,   101,   -75,   -88,   -48,  -137,   -54,

-  -245,   -28,    63,   -18,  -112,  -103,    58,

-   -79,    -6,   220,   -65,   114,   -35,   -50,

-   109,   -65,   143,  -114,   129,    76,   125,

-   166,    90,   -61,  -242,   186,   -74,   -43,

-   -46,   -92,    49,  -227,    24,  -155,    39,

-    67,    85,    99,   -42,    53,  -184,  -281,

-   142,  -122,     0,    21,  -142,   -15,   -17,

-   223,    92,   -21,   -48,   -82,   -14,  -167,

-    51,   -37,  -243,   -30,   -90,    18,   -56,

-    54,   105,    74,    86,    69,    13,  -101,

-   196,    72,   -89,    43,    65,    19,    39,

-   121,    34,   131,   -82,    25,   213,  -156,

-   101,  -102,  -136,   -21,    57,   214,    22,

-    36,  -124,   205,   204,    58,  -156,   -83,

-    83,  -117,   137,   137,    85,   116,    44,

-   -92,  -148,   -68,    11,  -102,  -197,  -220,

-   -76,  -185,   -58,   132,   -26,  -183,    85,

-    -7,   -31,    -2,    23,   205,  -151,    10,

-   -27,   -37,    -5,   -18,   292,   131,     1,

-   117,  -168,     9,   -93,    80,   -59,  -125,

-  -182,  -244,    98,   -24,   135,   -22,    94,

-   221,    97,   106,    42,    43,  -160,    83,

-    25,   -64,   -21,     6,    14,   -15,   154,

-   126,    15,  -140,   150,   -10,  -207,  -114,

-    79,   -63,  -211,   -70,   -28,  -217,   165,

-    46,    38,   -22,   281,   132,   -62,   109,

-   112,    54,  -112,   -93,   208,    27,   296,

-   115,    10,  -147,    41,   216,    42,  -276,

-    50,  -115,  -254,   167,   117,    -2,    61,

-    17,   144,    34,   -72,  -186,  -150,   272,

-   -29,   -66,   -89,   -95,  -149,   129,   251,

-   122,     0,   -50,  -234,   -91,    36,    26,

-  -105,  -102,   -88,  -121,  -236,    -7,   -11,

-  -204,   109,     5,  -191,   105,   -15,   163,

-   -80,    32,   -24,  -209,    41,   294,    70,

-  -106,   -94,  -204,  -118,   120,   -50,   -37,

-   -82,  -241,    46,  -131,   -29,   150,   -55,

-    33,   155,   120,   -89,    -8,     7,    62,

-   213,    82,    61,    18,  -161,   144,   152,

-    30,   131,    65,   -87,  -255,   -17,  -107,

-    -8,    85,   -64,    51,  -162,   223,   -53,

-  -134,   261,    69,   -56,   218,    72,  -111,

-     2,   155,  -113,   -87,    49,    85,   -28,

-  -163,    42,    -1,  -196,     7,    39,  -245,

-    14,  -137,   -79,    11,  -160,   202,  -293,

-   -94,    33,   208,   100,    56,   -44,   326,

-   -78,   -41,   232,    13,  -142,   227,    80,

-   -16,   -87,   201,    33,  -133,    15,  -183,

-   -58,  -192,   -47,   184,  -128,   133,    99,

-  -205,    11,  -155,    78,    52,    72,   141,

-  -246,    26,    99,   151,    59,   115,   -64,

-   -79,   -47,   -16,   -14,     6,    47,   -43,

-   -72,  -178,   -27,   162,   112,    43,  -174,

-  -175,   238,   186,    71,   -54,  -188,   -76,

-  -225,   233,    39,   -39,  -158,   122,    44,

-   -26,    43,    84,   130,   -93,   -51,    22,

-     3,    92,  -150,   136,  -182,   -57,    97,

-  -131,   179,   -78,    80,    91,  -165,    90,

-    -2,   148,    15,   130,    65,   175,   117,

-  -138,   114,  -137,   132,     3,   -10,  -186,

-   140,    -4,   -37,   254,   -62,    92,  -109};

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/*-------------------------------------------------------------------*
+ *                         qpisf_2s.h
+ *-------------------------------------------------------------------*
+ * Quantization tables for two-stage of ISFs (split by 2 in 1st stage)
+ * Version whith prediction MU = 0.25
+ *-------------------------------------------------------------------*/
+
+#define ORDER   16            /* order of linear prediction filter */
+#define ISF_GAP 128           /* 50 Hz */
+#define N_SURV  4
+
+#define SIZE_BK1  256
+#define SIZE_BK2  256
+#define SIZE_BK21 64
+#define SIZE_BK22 128
+#define SIZE_BK23 128
+#define SIZE_BK24 32
+#define SIZE_BK25 32
+
+#define SIZE_BK21_36b 128
+#define SIZE_BK22_36b 128
+#define SIZE_BK23_36b 64
+
+/* means of ISFs */
+static Word16 mean_isf[ORDER] = {
+
+   738,  1326,  2336,  3578,  4596,  5662,  6711,  7730,
+  8750,  9753, 10705, 11728, 12833, 13971, 15043,  4037};
+
+/* 46 bits */
+/*-------------------------------------------------------------------*
+ *  isf codebooks:  two-stage VQ with split-by-5 in 2nd stage        *
+ *                                                                   *
+ *  codebook   vector dimension    number of vectors                 *
+ *  ~~~~~~~~   ~~~~~~~~~~~~~~~~    ~~~~~~~~~~~~~~~~~                 *
+ *     1_1            9                  256                         *
+ *     1_2            7                  256                         *
+ *     2_1            3                  64                          *
+ *     2_2            3                  128                         *
+ *     2_3            3                  128                         *
+ *     2_4            3                  32                          *
+ *     2_5            4                  32                          *
+ *-------------------------------------------------------------------*/
+
+/*------------------------------------------------*
+ * 1st stage codebook; 1st split:   isf0 to isf8
+ *------------------------------------------------*/
+
+static Word16 dico1_isf[SIZE_BK1*9] = {
+
+   579,  1081,  1035,   390,     3,  -263,  -198,   -82,    38,
+    18,   -68,   -12,   313,   761,   405,   249,   111,   -76,
+   740,  1263,  1292,  1006,   997,  1019,  1017,   976,   923,
+   -91,   827,   948,   648,   613,   535,   522,   490,   421,
+    41,   -44,  -281,  -472,   652,   534,   193,   135,   -90,
+    41,  -121,  -356,   -60,   663,   307,    61,   -48,  -344,
+   557,   946,  1049,   867,   846,   990,  1112,  1262,  1241,
+  -118,  -204,   328,   512,   870,   793,   610,   402,   186,
+   156,   293,    74,  -338,  -475,  -897,  -594,  -161,  -497,
+   226,   131,  -138,   307,   169,  -271,  -164,  -387,  -624,
+    62,   -32,   -61,  -252,  -541,  -828, -1027,  -523,  -662,
+   102,   -61,   141,   112,  -270,  -251,  -541,    25,  -150,
+     6,  -132,  -356,  -686,   -96,  -322,  -522,   -31,  -326,
+   -36,  -209,  -521,  -229,   307,  -132,    -5,   -99,  -384,
+    60,   -51,  -237,  -668,  -973,  -407,  -708,   -75,  -172,
+    26,  -138,  -266,   111,  -302,    43,  -278,  -356,  -359,
+   570,   822,   496,  -154,  -312,   -92,   137,   279,   371,
+  -146,   368,   409,    68,     6,    77,   167,   202,   162,
+   633,   898,   996,   756,   662,   683,   783,   909,   996,
+  -103,   294,   607,   415,   483,   462,   480,   431,   408,
+  -120,  -338,  -612,  -524,   584,   331,    92,   433,   276,
+  -178,  -293,  -154,   -41,   269,   100,    -9,   213,   160,
+   830,   736,   278,   820,  1254,   686,   712,  1039,   473,
+  -218,  -304,   463,   454,   397,   273,   202,   286,   273,
+  -232,     7,     6,  -388,  -472,  -427,  -378,  -167,  -100,
+  -294,  -183,   134,   -47,   101,   -88,   -84,  -117,    -3,
+    57,    17,  -202,  -634,  -989, -1119,  -533,   176,   -36,
+   120,   -28,    23,   111,  -319,   318,   -22,   -77,   266,
+  -271,  -464,  -434,  -658,  -640,  -385,  -385,   -99,   -69,
+  -198,  -259,  -266,   -44,   -39,  -139,  -137,   171,    66,
+     9,  -145,  -377,  -846, -1000,  -111,  -325,   342,   135,
+   -81,  -286,  -380,   192,   -57,   307,    76,   -24,  -140,
+   677,   702,   247,    56,   249,   141,  -105,  -236,   -99,
+    36,   -39,   -69,   348,   198,   -93,   322,    91,   -72,
+   503,   885,  1508,  1307,  1282,  1172,  1119,  1209,  1061,
+   416,   719,   989,  1227,  1001,  1052,   954,   741,  1044,
+  -127,  -376,  -657,   139,   623,   223,   501,   306,   220,
+  -113,  -384,  -796,   504,   438,    85,   213,   -83,  -194,
+   585,  1132,  1233,  1091,  1247,  1433,  1512,  1448,  1314,
+  -174,  -422,     7,  1155,  1089,  1182,  1003,   945,   806,
+     8,  -126,  -317,  -103,  -351,  -695,   -98,  -268,  -537,
+    33,  -103,  -290,   167,   -39,  -407,    44,  -208,  -375,
+   104,   -23,   -64,  -291,  -637,  -851, -1084,   -61,  -112,
+   -75,  -306,  -434,   218,  -148,  -354,  -680,  -133,  -216,
+  -121,  -377,  -718,   -97,  -130,  -361,  -156,  -379,  -599,
+   -56,  -254,  -586,   235,   157,  -214,    11,  -260,  -149,
+  -124,  -267,  -397,  -580,  -593,  -527,  -805,  -385,   346,
+  -193,  -440,  -708,  -351,  -141,  -255,  -499,  -147,  -185,
+   448,   660,   494,   208,   509,   461,   338,   291,   149,
+  -223,    88,   335,   159,   212,   191,   286,   308,   205,
+   -31,   469,   803,   659,   619,   658,   843,   987,  1113,
+  -171,  -242,   514,   362,   295,   524,   552,   694,   585,
+   -64,  -308,  -448,   -21,   284,   786,   446,   289,    92,
+  -218,  -390,    -7,   169,   206,   330,   352,   408,   358,
+   -36,   702,   959,   859,   861,  1115,  1269,  1357,  1305,
+  -133,  -341,   -65,   678,   417,   440,   486,   518,   780,
+    33,   -44,  -191,  -344,  -461,  -755,  -201,   217,   -31,
+  -353,  -547,   -44,   123,   -61,   -68,   -79,    29,    60,
+    73,   -57,  -406,  -766, -1243, -1203,   240,   400,   165,
+   -73,  -282,  -601,  -213,  -171,  -375,   332,    35,  -103,
+   -29,  -207,  -553,  -476,  -638,  -908,   172,   -22,  -135,
+  -192,  -239,  -164,  -103,  -111,   -47,   153,   125,   110,
+    -1,  -203,  -570, -1030, -1424,  -535,   155,     1,   147,
+  -333,  -653,  -865,  -197,  -158,   -21,   -44,    95,   108,
+   389,   588,   490,    33,  -237,  -524,  -628,  -136,  -260,
+    40,  -177,  -462,   453,   862,   380,   131,  -130,  -405,
+   842,  1678,  1841,  1549,  1474,  1256,  1082,   905,   742,
+   370,  1216,  1768,  1633,  1212,   636,    22,  -330,    71,
+   -76,  -281,  -741,  -742,   898,   619,   277,    71,  -222,
+   -32,  -265,  -556,   -25,   994,   682,   305,   126,  -165,
+    73,   738,   893,   968,   993,  1768,  2273,  1840,  1391,
+   -69,  -349,  -585,   234,  1158,   903,   626,   510,   251,
+    -1,   -99,  -272,  -210,  -603,  -351,  -540,  -811,  -383,
+   -16,  -230,  -504,   410,   149,  -205,  -343,  -651,  -639,
+   103,    -9,  -227,  -205,  -562,  -781, -1079, -1208,  -156,
+   143,    63,  -135,   -67,  -317,  -602,  -784, -1154,  -640,
+  -144,  -391,  -674,  -622,  -200,  -254,  -660,  -947,  -395,
+   -40,  -250,  -625,    27,   543,    94,  -131,  -386,  -673,
+  -123,  -371,  -757,  -451,  -564,  -614,  -415,  -711,   -35,
+  -116,  -309,  -593,  -268,   239,   -33,  -338,  -650,  -135,
+    94,   251,   554,    57,  -312,  -423,  -154,   -57,   235,
+  -268,   -71,   381,   114,   -44,   -87,   125,   173,   133,
+  1513,  1714,  1238,   534,   276,   315,   461,   459,   508,
+  -131,   -19,  1149,   670,   486,   356,   309,   369,   296,
+  -223,  -501,  -899,  -722,   -70,     6,   131,   310,   394,
+   -99,  -303,  -517,   249,    64,   -53,   135,   -11,   453,
+  -147,  -399,  -730,  -401,   817,   738,   802,   749,   575,
+  -154,  -435,  -739,   800,   593,   366,   529,   318,   326,
+  -224,    45,   -39,  -387,  -515,  -518,  -608,  -384,  -321,
+  -315,  -377,   143,  -101,  -113,  -377,  -177,  -144,   -12,
+   117,    40,  -239,  -651, -1051,  -581,  -737,  -990,  -328,
+    26,   -50,  -157,   -23,  -453,  -283,  -531,  -546,   192,
+  -252,  -501,  -743,  -589,  -627,  -499,  -328,  -118,   -72,
+  -324,  -494,  -244,  -306,  -144,  -177,  -262,  -135,   -78,
+   -36,  -234,  -519,  -961, -1290,  -314,  -479,  -371,   -45,
+   -95,  -292,  -535,    -8,  -300,   112,  -164,  -277,   198,
+   -99,  -128,   880,   836,   579,   351,    23,   -95,  -217,
+   -27,  -258,   124,  1011,   597,   425,   144,     7,   -73,
+   421,  1293,  1640,  1623,  1742,  1617,  1499,  1284,  1006,
+   -95,   752,  1680,  1569,  1618,  1436,  1200,   980,   712,
+   -69,  -300,  -683,  -435,  1132,   899,   504,   332,   109,
+   -74,  -323,  -637,   563,  1074,   608,   371,   105,   -49,
+   -78,   831,  1194,  1110,  1378,  1481,  1492,  1365,  1217,
+  -259,  -121,  1440,  1334,  1628,  1490,  1438,  1223,   933,
+   -82,  -306,  -613,  -222,  -378,  -675,  -545,  -671,  -845,
+    53,  -124,  -347,   422,    52,  -125,  -270,  -529,     9,
+    79,   -89,  -320,  -662,  -999, -1199, -1243,  -676,  -297,
+   -68,  -273,  -611,   137,  -146,  -397,  -627,  -845,  -220,
+  -112,  -346,  -797,  -826,   234,  -132,  -188,  -278,  -522,
+  -159,  -405,  -734,  -419,   293,    74,  -167,  -167,   184,
+  -153,  -437,  -833, -1080,  -336,  -472,  -561,  -340,  -253,
+  -169,  -423,  -820,  -904,  -131,   -19,  -346,  -604,    31,
+    33,   -31,   312,    62,  -148,    49,   -59,   564,   486,
+  -306,  -333,   194,   -44,    67,    72,   147,   205,   243,
+  -207,   -49,  1360,   983,   969,   991,  1014,  1110,   973,
+  -211,  -172,   883,   627,   711,   674,   705,   798,   746,
+   -88,  -325,  -763,  -974,   687,   908,   514,   382,   172,
+  -292,  -612,  -805,    63,   131,   270,   259,   352,   348,
+  -235,   -84,   955,   818,  1120,  1289,  1559,  1480,  1285,
+  -180,  -461,  -614,   657,   691,   745,   854,   783,   713,
+   -97,  -309,  -477,  -614,  -777,  -734,  -768,  -526,  -472,
+  -344,  -476,   -35,  -169,    49,   -77,  -150,  -240,  -141,
+   -52,  -268,  -639,  -919, -1278, -1113,  -342,  -333,  -151,
+   -68,  -242,  -585,   -73,  -209,  -478,  -159,  -429,   133,
+  -197,  -499, -1005, -1268,  -272,  -224,  -105,   -67,    17,
+  -363,  -618,  -414,  -116,   -62,    20,    10,   116,   108,
+  -195,  -475,  -906, -1260,  -891,  -441,  -277,  -142,   -28,
+  -226,  -519,  -950,  -700,  -275,  -266,  -116,  -105,    82,
+   404,   511,   520,   327,    17,  -194,  -333,  -536,  -586,
+  -114,  -130,   276,   237,   204,   342,   135,   -16,  -111,
+   670,  1208,  1168,   860,   742,   601,   528,   403,   309,
+   397,   621,   966,   752,   579,   398,   400,   329,   252,
+   191,   180,  -137,  -467,   272,   106,   -95,    17,  -192,
+   -80,  -290,  -626,   194,   598,   196,    21,  -281,    77,
+   510,   864,  1108,   807,   939,   902,   925,   717,   481,
+   137,   367,   534,   764,   670,   382,   296,   153,    84,
+   303,   497,   144,   -85,  -125,  -539,  -482,  -464,  -764,
+   233,   347,    68,  -147,   169,  -210,  -242,  -226,  -482,
+   307,   422,   154,  -175,  -386,  -722,  -724,  -904, -1015,
+   309,   308,   160,   -60,  -470,  -420,  -598,  -791,  -219,
+    68,   121,  -137,  -560,  -146,  -446,  -515,  -494,  -729,
+   130,    53,  -227,    46,   474,    32,  -161,  -192,  -490,
+   213,   164,   -71,  -465,  -876,  -161,  -456,  -587,   -48,
+   218,   117,    39,   177,  -194,   -88,  -226,  -418,    50,
+   210,   547,   569,   279,   121,   -44,   -50,    10,   -84,
+    58,   140,   182,    -5,   267,   117,   106,   211,   198,
+   539,   835,   913,   719,   617,   544,   591,   565,   642,
+   153,   559,   872,   460,   222,   108,   188,   180,   183,
+   158,   119,   284,  -153,  -271,   229,    87,   110,   -57,
+  -183,    82,   118,    21,    13,    40,   118,   191,   185,
+   162,   889,   654,   108,   -34,   244,   488,   561,   532,
+   163,    56,   609,   341,    50,   329,    68,   266,   218,
+   100,   206,    18,  -304,  -107,  -436,  -487,   -65,  -306,
+   -86,   154,   134,   -30,   -45,   -73,  -104,   -80,   -96,
+   245,   330,    10,  -440,  -849, -1082,    79,    40,  -265,
+   196,   372,   272,  -181,  -493,  -389,   275,    80,   -59,
+     2,   -12,  -246,  -505,  -100,  -436,    21,  -187,  -431,
+  -221,   -48,    36,  -271,  -186,  -147,  -109,    26,    71,
+   213,   140,    72,  -351,  -620,   -84,  -363,    69,    46,
+    91,   167,    -3,   -95,   -99,  -105,   -48,   114,   147,
+   259,   249,   172,   607,   406,    52,    59,  -189,  -320,
+   115,   -85,   -54,   574,   128,   226,   -59,  -253,   130,
+   -62,  1033,  1308,  1035,  1127,  1098,  1029,   961,   823,
+    39,   364,   757,   940,   728,   660,   659,   583,   770,
+  -115,  -338,  -760,  -471,   394,    37,   441,   178,     6,
+   -57,  -305,  -525,   796,   453,   188,    -4,  -114,   248,
+    71,   444,   797,   731,  1096,  1157,  1222,  1029,   811,
+   135,   359,   551,   425,   749,   815,   874,   704,   502,
+   132,   247,     0,  -206,  -449,  -750,  -258,  -514,  -633,
+   248,   249,    91,   121,  -195,  -499,   -90,  -282,  -435,
+    78,    20,  -277,  -623,  -983, -1224,  -415,  -458,  -639,
+   347,   509,   208,  -179,  -464,  -728,   -76,  -237,  -486,
+  -103,  -343,  -756,  -713,  -265,  -609,  -191,  -398,  -636,
+  -121,  -383,  -749,   567,   252,   -36,  -354,  -417,   -50,
+   204,   100,  -149,  -650, -1081,   -47,    -7,  -263,   111,
+   -46,  -180,  -267,  -324,  -562,  -394,  -692,   398,   292,
+   482,   670,   683,   624,   442,   165,   116,    36,  -149,
+   108,   247,   291,   247,   355,   122,   109,   224,   296,
+   -14,   945,   990,   801,   755,   815,   847,   913,   892,
+   292,   349,   725,   482,   388,   329,   429,   620,   667,
+   -34,   197,   213,  -127,    84,   494,   620,   575,   375,
+   126,   207,   172,   167,   362,   202,   296,   395,   455,
+    -6,   250,   539,   467,   636,   801,  1149,  1287,  1118,
+    27,   240,   369,   280,   440,   411,   634,   892,   953,
+   159,   170,   -58,  -395,  -797,  -690,    77,  -211,  -334,
+    -5,   -28,   -13,   -74,  -335,  -603,   300,    88,  -205,
+    82,   -33,  -364,  -698, -1203, -1153,   110,  -146,  -289,
+   113,     1,  -243,  -588,  -994,  -496,   414,   160,    42,
+   -56,  -247,  -440,  -693,  -996,  -479,    11,  -178,  -357,
+  -151,  -353,  -327,  -211,  -340,   141,    65,   425,   453,
+    34,  -169,  -455,  -932, -1215,   138,   499,   256,   324,
+    68,   139,   -15,  -547,  -478,    17,   306,   502,   481,
+   -32,  -134,   445,   129,  -143,  -244,  -503,  -507,  -599,
+    61,  -140,  -345,   496,   458,    -2,    20,  -227,  -514,
+   394,  1765,  1666,  1339,  1117,   806,   642,   479,   380,
+   215,   519,   920,  1053,  1090,   791,   528,   290,   155,
+   -54,  -233,  -647,  -602,   639,   294,    -2,  -167,  -442,
+   -78,  -315,  -791,  -113,   820,   403,   158,  -116,  -356,
+   529,  1851,  2003,  1228,   622,   -41,  -416,   344,   819,
+  -105,  -379,  -236,  1224,   893,   749,   568,   356,   214,
+   -17,  -199,  -144,    50,  -283,  -247,  -578,  -846, -1087,
+    69,   -11,  -381,  -206,   209,  -284,  -387,  -416,  -716,
+    39,    -5,  -145,  -374,  -682,  -909, -1074, -1169, -1066,
+   287,   226,    67,  -221,  -662,  -171,  -421,  -642,  -707,
+  -132,  -348,  -538,  -448,   -20,    -4,  -354,  -748,  -933,
+     4,   -75,  -289,  -598,   317,    52,  -208,  -297,  -559,
+   -88,  -264,  -358,  -589,  -631,  -248,  -523,  -822, -1071,
+    70,    -8,    54,  -314,  -515,    92,  -146,  -274,  -493,
+   199,    62,   391,   158,  -141,    71,  -219,  -203,  -207,
+   152,    40,   329,   162,   -29,    48,  -149,   108,   127,
+   635,  1058,   883,   492,   372,   312,   317,   274,   241,
+   267,   722,  1256,   882,   625,   248,     8,   -81,   -60,
+   -58,  -138,  -291,  -600,   -12,    -2,   -39,   147,   117,
+  -107,  -345,  -513,   459,    76,    92,  -272,   388,   262,
+   362,   516,   203,  -409,  -716,  -831,  -331,   185,   209,
+  -117,  -391,  -298,   671,   292,   538,   257,   166,   -38,
+  -102,  -319,  -194,  -283,  -573,  -262,  -579,  -219,  -444,
+  -235,    78,    11,  -168,  -101,  -229,  -263,  -321,  -123,
+    70,    50,  -170,  -599,  -996,  -588,  -263,  -516,  -455,
+   394,   363,   229,  -136,  -538,    21,  -183,  -348,  -201,
+  -124,  -368,  -640,  -879,  -847,  -209,  -409,  -494,  -515,
+  -127,  -341,  -541,  -425,  -510,   -10,  -252,  -473,  -291,
+    84,   -69,  -201,  -676,  -868,   103,  -311,  -132,  -320,
+     5,  -173,  -188,  -297,  -628,   197,   -57,     7,   -11,
+    49,  -160,    56,   558,   111,    33,  -311,  -440,  -463,
+    -1,  -246,  -307,   862,   453,   139,  -170,  -355,  -232,
+   279,   966,  1642,  1478,  1463,  1123,   795,   525,   339,
+  -197,   -38,  1702,  1331,  1252,   950,   692,   504,   426,
+  -108,  -344,  -861, -1172,   444,   354,    88,   -46,  -220,
+   -53,  -321,  -494,  1113,   744,   364,   198,   -34,   -75,
+   457,   955,  1177,  1214,  1427,  1457,  1345,   917,   539,
+   -69,   199,   897,  1140,  1343,  1183,   977,   742,   522,
+   122,    44,  -269,    27,  -155,  -562,  -307,  -590,  -773,
+   154,    42,  -160,   252,  -129,  -305,  -471,  -733,  -371,
+   135,   185,   -82,  -416,  -722,  -913,  -504,  -743,  -880,
+   149,   214,   -84,  -329,  -680,  -835,  -426,  -661,   -81,
+  -128,  -380,  -735,  -998,  -337,    17,  -182,  -467,  -697,
+   -84,  -290,  -510,  -592,    13,   440,   154,   -38,  -279,
+    70,   -61,  -246,  -727, -1047,   -80,  -381,  -535,  -704,
+   178,    -2,  -146,  -670,  -938,   482,   138,    63,    65,
+   -11,    15,   772,   443,   142,   -20,  -209,  -126,  -161,
+   -32,  -249,    95,   552,   124,    30,  -343,    82,   -86,
+   148,   751,  1515,  1105,   867,   606,   474,   448,   399,
+  -163,  -257,   899,  1097,   906,   751,   502,   390,   294,
+   -51,  -258,  -447,  -806,  -368,   763,   464,   364,   183,
+  -166,  -374,  -367,    87,    35,   399,   418,   856,   833,
+  -205,  -310,   588,   778,   785,  1065,  1118,  1245,  1157,
+  -173,  -312,   107,   345,   400,   790,   870,  1113,  1001,
+    -7,  -120,  -387,  -410,  -614,  -943,  -226,  -384,  -491,
+  -203,  -288,   -51,  -331,   -90,  -178,  -408,  -573,  -338,
+    56,   -29,  -273,  -627, -1041,  -798,  -247,  -467,   148,
+    66,    -2,  -205,  -205,  -575,  -349,   -57,  -352,   -58,
+   -45,  -225,  -471,  -924,  -497,    77,   -32,    44,  -135,
+  -277,  -491,  -497,  -502,  -424,  -202,  -137,    77,    96,
+    26,  -179,  -469, -1008, -1260,   262,   -35,  -132,  -259,
+   -66,  -232,  -447,  -533,  -789,  -191,  -100,  -267,   364};
+
+/*------------------------------------------------*
+ * 1st stage codebook; 2nd split:   isf9 to isf15
+ *------------------------------------------------*/
+
+static Word16 dico2_isf[SIZE_BK2*7] = {
+
+  1357,  1313,  1136,   784,   438,   181,   145,
+   636,   648,   667,   568,   442,   217,   362,
+   427,   440,   674,   524,   332,   117,  -417,
+   121,   295,   468,   465,   230,    44,  -221,
+  -147,  -240,   149,    80,   390,   278,   106,
+  -418,  -556,   552,   511,   235,   144,   -95,
+    43,   193,   274,   150,    67,    34,  -273,
+   -43,  -126,   171,   416,   282,    63,  -354,
+  -372,   -86,  -344,  -108,   -94,  -182,   -89,
+  -600,  -840,  -200,   465,   258,   -11,  -253,
+   -48,   329,    97,  -290,  -543,  -795,  -354,
+  -570,  -117,   187,    10,  -133,  -416,   -76,
+  -618,  -129,  -247,  -371,    45,   -76,   277,
+ -1022, -1079,   126,   474,   254,   127,    52,
+  -281,    76,  -167,  -361,  -283,  -551,  -283,
+  -119,   -52,    -1,   134,   -32,  -204,  -415,
+  1064,   827,   637,   684,   464,   209,    12,
+   482,   416,   449,   371,   335,   294,   194,
+   719,   576,   365,   135,   113,    91,  -199,
+   298,   176,   493,   366,   194,   163,    36,
+   -35,  -236,  -259,   -36,    -4,    99,   152,
+   -98,  -306,   -27,   228,    90,   111,   -86,
+    91,    13,  -211,  -258,  -106,    86,   -64,
+    73,   -35,   -57,   -31,   162,    35,  -192,
+  -109,  -335,  -629,   -66,   -61,  -128,   322,
+  -495,  -669,  -728,   193,    31,  -220,   122,
+   324,    95,   -89,   -91,  -409,  -710,  -154,
+     0,  -234,    92,    33,  -343,  -609,  -220,
+  -343,  -408,  -476,  -655,  -153,    82,   222,
+  -490,  -745,  -255,    49,   -48,   135,  -127,
+   119,   -67,  -328,  -390,  -272,  -545,   -56,
+   -57,  -130,   -10,    -7,  -164,   -47,   -22,
+   984,  1064,   961,   568,   210,   -27,    16,
+   811,   691,   754,   514,   224,   -35,   166,
+   662,   704,   618,   386,    57,  -211,  -257,
+   510,   359,   418,   393,    91,  -144,   -18,
+  -193,   -31,   -27,   223,    89,  -143,    24,
+  -112,   -98,   471,   319,   185,     3,   175,
+   252,   146,   -47,   272,    48,  -211,  -234,
+   146,    69,   203,   364,    68,   -52,    51,
+  -259,  -478,  -697,  -349,  -758,  -501,    63,
+  -501,  -769,  -289,    79,  -311,  -497,  -106,
+   251,    53,  -235,  -469,  -895,  -884,   145,
+  -416,  -551,   140,  -133,  -523,  -775,    44,
+  -326,  -423,  -713,  -497,   -86,  -431,    99,
+  -757,  -772,  -160,   -76,   -46,   -32,   379,
+    85,   -35,  -200,  -401,  -663, -1040,  -247,
+  -180,  -330,   -92,  -376,    27,  -183,  -110,
+  1279,  1086,   781,   502,   324,   164,   157,
+   682,   466,   449,   277,   146,    28,   409,
+   635,   472,   390,   107,  -232,  -538,  -139,
+   196,   396,   332,   213,   209,   -29,   -81,
+   150,   -95,  -312,    76,   -77,  -320,   -50,
+    46,     9,    47,   175,   139,    30,   384,
+   218,   206,   -24,  -250,   -96,  -276,  -183,
+    26,   119,    38,    14,    -4,  -133,   -52,
+  -477,  -614,  -987,  -715,  -631,  -813,   200,
+  -744, -1009, -1065,  -745,  -631,  -171,    18,
+  -137,  -251,  -483,  -613,  -980, -1203,    12,
+  -605,  -767,  -562,  -686, -1088,  -515,    58,
+  -202,  -428,  -782, -1072,   -96,  -234,  -179,
+  -480,  -709, -1070,  -897,  -131,   -92,   321,
+  -145,  -193,  -512,  -729,  -572,  -765,  -210,
+  -331,  -585,  -525,  -631,  -281,  -208,  -303,
+  1165,  1104,   939,   828,   716,   426,   155,
+     6,  -109,   820,   778,   415,   113,   -27,
+   381,   339,   314,   265,   121,    -9,  -474,
+  -373,    47,   584,   442,    99,  -231,  -113,
+  -496,   -38,  -285,   262,   305,   170,     4,
+  -587,  -556,    69,    66,   471,   354,    13,
+  -138,    70,   -18,   106,    67,   167,  -302,
+  -445,  -141,   185,   191,   151,    83,  -133,
+  -257,  -521,  -720,  -198,   134,   -46,  -182,
+  -819, -1168,  -777,   512,   359,    95,  -113,
+   137,    -2,   -74,  -138,  -401,  -114,  -371,
+  -242,  -466,   204,   223,   -31,  -212,  -192,
+  -532,  -637,  -466,  -686,   256,   277,  -139,
+ -1141, -1244,  -381,   -75,   -54,    14,    88,
+  -311,   115,  -143,  -499,  -343,   124,  -416,
+  -616,  -147,  -135,    43,    -4,   121,  -369,
+   835,   783,   641,   390,   355,   350,    64,
+    72,   194,   443,   467,   436,   219,   372,
+   464,   369,   192,     4,  -156,   -72,  -226,
+    57,   206,   303,   205,   188,   101,   265,
+   -40,  -205,  -488,  -184,   276,    64,   -26,
+  -217,  -433,  -297,   137,   328,   308,  -289,
+   378,    81,  -308,  -465,    57,   -37,   227,
+  -100,    24,   -36,  -151,   199,     8,   143,
+  -426,  -697, -1059,  -133,   388,   161,   321,
+  -644, -1023, -1271,    39,    66,  -123,    70,
+   372,   177,  -173,  -556,  -553,  -304,  -189,
+  -117,  -369,  -425,  -122,  -462,  -152,   -73,
+  -649,  -850, -1189,  -767,   497,   360,   222,
+  -798, -1139, -1455,  -190,   430,   234,   179,
+    42,   -94,  -405,  -692,    38,  -202,  -246,
+  -169,  -366,  -290,   -88,   -64,    32,  -292,
+  1010,   923,   938,   710,   465,   230,   342,
+   217,   300,  1054,   675,    68,  -458,  -179,
+    78,   453,   316,    18,  -237,  -496,  -243,
+   167,    21,   424,   215,   -91,  -303,  -170,
+  -290,   -81,   -70,   -67,    40,    54,   -59,
+  -353,  -427,   -90,    53,    94,     9,    54,
+   -28,   318,   283,    15,  -240,   -58,    79,
+   -75,  -121,   229,    35,    58,     6,  -133,
+  -351,  -514,  -744,  -834,  -705,  -137,   164,
+ -1124, -1388, -1055,  -230,   -73,    40,    36,
+  -163,  -233,  -532,  -785, -1170,  -697,    96,
+  -788,  -959,  -246,  -430,  -624,  -165,    -8,
+  -856,  -540,  -630,  -907,  -337,   -70,    76,
+  -937, -1042,  -659,  -733,  -208,   199,   -26,
+  -523,    78,   -98,  -501,  -869,  -890,   -81,
+  -624,  -703,   -45,  -348,   -25,    87,  -186,
+  1005,   823,   546,   249,    90,   -22,   207,
+   298,   397,   381,   319,   200,    62,   303,
+   473,   379,   133,  -247,  -632,  -441,    75,
+   284,   208,   391,   115,   -25,    44,    95,
+   -72,    79,   -95,   -63,  -129,  -293,   203,
+  -164,  -349,   115,   122,    69,    -1,   378,
+   348,   170,    99,    58,  -179,  -302,   188,
+  -190,    -2,   150,    23,   -51,   -11,   216,
+  -615,  -863, -1090, -1427,  -802,   -48,    -6,
+  -961, -1276, -1548,  -727,   -58,    56,   223,
+  -124,  -255,  -561,  -988, -1277,  -148,   -82,
+  -480,  -660,  -891, -1191, -1339,  -325,    20,
+  -621,  -917, -1296, -1350,   264,   289,    50,
+  -844, -1022, -1345, -1329,  -293,    46,   278,
+  -260,  -468,  -829, -1176,  -533,  -560,   -78,
+  -215,  -484,  -822, -1233,  -791,    15,  -138,
+  1301,  1317,  1262,  1048,   716,   357,   -64,
+   578,   824,   925,   802,   630,   362,   102,
+   470,   925,   767,   514,   327,   190,  -112,
+   225,   492,   495,   437,   598,   384,   -45,
+    43,    82,   -42,   175,   519,   342,   -64,
+  -304,  -154,   159,   576,   403,   221,   327,
+   214,   244,   122,   -62,   312,    92,  -160,
+   218,   208,   310,   268,   306,   323,  -199,
+  -285,  -269,   -79,  -124,  -143,  -153,   236,
+  -205,  -384,  -426,   344,    59,  -185,  -184,
+  -272,   247,   126,  -210,  -518,  -468,    78,
+   -99,  -120,   502,   160,  -280,  -557,   304,
+  -423,   -17,  -283,  -443,   215,   212,  -140,
+  -564,  -684,  -228,   510,   361,   130,   323,
+  -428,   335,    98,   -65,    36,  -215,  -246,
+  -362,    51,   364,   -16,  -234,   150,  -165,
+   914,   883,   751,   653,   676,   464,  -153,
+   631,   545,   535,   720,   596,   360,   -81,
+   783,   712,   512,   439,   341,   251,  -391,
+   497,   417,   249,   372,   295,   173,  -193,
+   128,  -110,  -385,    93,    39,   173,  -231,
+   216,   -59,  -253,   462,   389,   154,    69,
+   455,   270,    -4,  -337,   -49,   233,  -322,
+   307,   143,    53,   218,   128,   236,  -156,
+   -37,  -186,  -240,  -411,  -110,     9,   399,
+  -140,  -365,  -628,   258,   380,   214,   277,
+   131,   454,   177,  -285,  -520,   108,  -214,
+    77,  -141,   201,  -123,  -490,  -131,    60,
+   -14,  -194,  -521,  -741,   273,   362,   -33,
+  -362,  -566,  -287,  -228,   161,   237,   317,
+  -269,   195,   -75,  -375,  -204,    11,    77,
+  -128,  -264,  -156,  -223,  -475,   265,    27,
+  1238,  1147,   916,   689,   432,   210,  -280,
+   800,   664,   879,   726,   411,   160,  -164,
+   454,   686,   536,   275,   147,    46,   111,
+   303,   486,   512,   355,   241,   181,   -69,
+    79,    92,    29,   147,   233,    52,    17,
+  -171,   289,   131,   439,   271,     3,   -10,
+   413,   241,   144,   174,   155,    -2,    14,
+    58,   217,   247,   219,   149,   175,   -18,
+   228,    -8,  -240,  -206,  -513,  -191,   202,
+   -96,  -272,  -454,    33,  -300,  -575,    46,
+   -10,  -108,  -246,  -347,  -770,  -535,     9,
+  -326,  -430,   -61,  -321,  -704,  -299,   201,
+    -1,  -280,  -603,  -419,  -185,    18,   -36,
+  -516,  -522,  -379,  -291,  -181,   -97,    27,
+  -159,  -313,  -525,  -224,  -510,  -831,  -197,
+  -292,  -459,   -59,  -310,  -562,  -143,  -351,
+  1066,   912,   631,   389,   207,    86,  -224,
+   596,   512,   596,   505,   314,   122,   -48,
+   787,   861,   441,   -93,  -303,    33,  -190,
+   257,   469,   337,    51,    15,   298,   -93,
+   295,    73,  -119,    25,    36,    23,   108,
+   -28,    -3,   -32,   114,    21,   185,   107,
+   482,   305,    15,  -279,  -319,    52,    96,
+   226,    46,   115,    72,  -136,   133,  -125,
+    18,  -207,  -559,  -590,  -503,  -482,   321,
+  -571,  -789,  -951,  -172,  -441,  -538,   113,
+   181,    14,  -310,  -641, -1001,  -202,   159,
+  -136,  -393,  -433,  -513,  -911,  -144,   -22,
+    72,  -265,  -706,  -954,  -159,    53,   332,
+  -338,  -591,  -852,  -383,  -395,    56,    44,
+    43,  -158,  -464,  -897,  -631,  -157,  -294,
+  -161,  -128,  -328,  -573,  -483,  -125,    11,
+  1017,   906,  1051,  1005,   679,   341,  -102,
+   359,   334,  1567,  1314,   723,   105,    10,
+   -65,   726,   529,   301,   220,    43,  -273,
+  -510,   436,   719,   566,   358,   179,   114,
+  -560,   298,   133,  -120,   342,   225,    14,
+  -899,  -101,   217,   617,   400,   146,   -58,
+   -41,   352,    82,  -196,    39,   121,  -167,
+  -212,    59,   447,   284,   423,   250,  -169,
+  -371,  -484,  -596,    30,   -41,   249,    22,
+  -372,  -650,  -794,   477,   445,   216,   -79,
+  -352,   275,    17,  -443,  -929,    92,    19,
+  -699,  -696,   431,   264,   -49,  -310,   182,
+  -978,  -217,  -430,  -400,   101,   261,    72,
+  -929,  -889,  -357,   -13,   463,   378,   236,
+  -826,    56,    30,  -299,  -360,  -128,   -51,
+  -878,  -299,  -111,    75,    65,    36,     3,
+   817,   368,   -25,   354,   697,   591,  -173,
+   309,   212,   222,   751,   484,   140,   -56,
+   593,   379,    70,    -8,   258,   180,   110,
+   165,   -46,   255,   297,   219,   273,   105,
+   160,   -70,  -358,  -181,   379,   330,   319,
+  -238,  -369,  -198,   740,   580,   319,  -143,
+   201,   109,  -202,  -456,   328,   276,  -141,
+   203,   170,   111,    42,   207,   360,   188,
+  -345,  -399,  -513,  -233,   650,   422,    81,
+  -635,  -961, -1220,   463,   539,   204,   209,
+   202,   -25,  -194,  -498,  -787,   193,  -143,
+  -449,  -538,   195,  -106,  -331,    68,    62,
+  -228,  -477,  -840,  -576,   317,   128,   283,
+  -671,  -937,  -807,  -114,   391,   335,   -62,
+   246,     2,  -314,  -679,  -303,   180,   -88,
+  -107,  -272,    90,  -198,   -28,   290,  -112,
+   885,  1149,  1021,   712,   496,   281,   -83,
+   269,   492,   787,   643,   347,    70,   124,
+   336,   636,   499,    92,  -229,  -179,   191,
+    26,   402,   564,   340,   149,   -11,   135,
+  -440,   561,   470,   204,   -72,  -186,   140,
+  -720,    14,   355,   229,    68,  -133,   465,
+   110,   310,   103,    12,   106,    29,   158,
+  -178,   113,   161,   142,   121,   115,    27,
+  -651,  -414,  -645,  -152,  -164,   -13,  -429,
+  -639,  -944,  -681,  -104,   -81,    52,  -189,
+  -663,  -164,  -316,  -683,  -954,  -205,   -83,
+  -609,  -669,  -172,  -517,  -694,   283,   -80,
+  -646,  -152,  -383,  -678,  -246,   -40,  -143,
+  -747,  -796,  -745,  -390,   -98,    43,   275,
+  -599,  -199,  -398,  -433,  -436,  -538,    31,
+ -1107,  -568,  -376,  -265,  -126,   -21,     1,
+   847,   573,   308,   392,   305,   101,    55,
+   273,   293,   201,   267,   346,   201,   123,
+   727,   480,   226,     2,   -65,  -138,   164,
+   273,   208,   173,   292,    12,   253,   174,
+   340,   207,   180,    88,   116,    46,   475,
+  -460,  -166,   -30,    13,   110,   173,   396,
+   137,    88,    43,  -137,   -94,    34,   284,
+    96,   -14,   226,    40,    63,    70,   130,
+  -467,  -735, -1012, -1174,  -307,   305,   -67,
+  -612,  -920, -1146,  -567,    -8,    92,   -25,
+  -182,  -271,  -492,  -754,  -857,   287,   -75,
+  -494,  -787,  -689,  -683,  -709,   137,  -326,
+  -288,  -550,  -903, -1105,   334,   321,   -62,
+  -354,  -653,  -834,  -445,     1,   377,  -152,
+  -162,  -306,  -608,  -937,  -297,   247,  -192,
+  -234,  -477,  -244,  -488,  -266,   342,  -332};
+
+/*---------------------------------------------------*
+ * 2nd stage codebook; 1st split:   isf2_0 to isf2_2
+ *---------------------------------------------------*/
+
+
+static Word16 dico21_isf[SIZE_BK21*3] = {
+
+   329,   409,   249,
+   -33,   505,   160,
+   -29,   -14,   582,
+  -262,   127,   354,
+   145,   237,   175,
+  -152,   245,   122,
+    27,    42,   340,
+   -84,   -93,   311,
+   285,   222,  -156,
+    47,   -43,  -504,
+   234,   121,   385,
+   104,  -317,    45,
+   176,   195,     8,
+   104,   -59,   -94,
+   177,    53,   192,
+   -34,  -127,   152,
+   570,   277,   -34,
+   -67,  -329,  -639,
+  -157,  -272,   462,
+  -177,  -462,   198,
+   322,   179,   115,
+  -386,   171,    19,
+    19,   -12,   195,
+  -120,  -252,   201,
+   304,    36,  -336,
+  -128,  -221,  -380,
+   171,  -185,   296,
+  -242,  -312,    23,
+   198,    39,    16,
+    -3,  -177,  -111,
+   111,   -93,    76,
+   -92,  -223,     4,
+   177,   406,   -44,
+  -168,   380,  -149,
+    -4,   273,   331,
+  -420,   513,   277,
+    21,   247,    47,
+   -58,   131,    -2,
+    -3,   134,   180,
+  -145,    40,   175,
+   189,    74,  -145,
+   -27,   -45,  -325,
+   370,  -114,   -21,
+   -83,  -415,  -173,
+    77,    95,   -51,
+   -40,   -30,   -67,
+    71,    88,    86,
+   -35,   -98,    14,
+    69,   197,  -334,
+  -196,    79,  -231,
+  -348,  -137,   218,
+  -352,   -89,   -85,
+    47,   201,  -130,
+  -165,    37,   -15,
+   -43,     3,    86,
+  -161,  -108,    79,
+    83,    21,  -237,
+   -81,  -149,  -238,
+   150,  -186,  -251,
+  -186,  -249,  -162,
+   -19,    66,  -139,
+   -26,   -50,  -181,
+    24,    11,     0,
+  -130,  -105,   -98};
+
+
+
+/*---------------------------------------------------*
+ * 2nd stage codebook; 2nd split:   isf2_3 to isf2_5
+ *---------------------------------------------------*/
+
+
+static Word16 dico22_isf[SIZE_BK22*3] = {
+
+  -127,   310,    42,
+  -242,   197,     5,
+  -151,    84,   -17,
+  -214,   127,  -149,
+  -247,  -131,   159,
+  -268,  -267,   -95,
+  -217,     1,   -79,
+  -271,   -80,  -185,
+   -45,   436,   159,
+   165,   199,   391,
+   -33,    81,   187,
+   -66,   -42,   355,
+  -298,   -57,   343,
+  -108,  -537,   226,
+  -144,   -23,   193,
+   176,  -402,    87,
+    53,   296,    25,
+   -84,   253,  -104,
+   -58,   105,  -126,
+  -169,   174,  -314,
+   -48,    44,  -294,
+  -164,  -417,  -242,
+  -139,     3,  -194,
+  -155,  -207,  -211,
+   119,   322,   213,
+   333,    50,   380,
+   237,   247,    -2,
+   466,   -16,   201,
+   238,  -255,  -107,
+    67,  -440,  -149,
+   122,   -88,  -139,
+    88,  -247,   -73,
+   -41,   231,   167,
+   -62,   155,    16,
+   -65,    16,    77,
+   -68,    -2,   -63,
+  -151,  -300,   160,
+   -18,  -333,    54,
+   -56,   -94,     5,
+     2,  -190,    14,
+    92,   148,   209,
+   108,     9,   272,
+   108,    35,   110,
+   142,   -85,   145,
+    47,  -157,   279,
+     3,  -320,   246,
+    43,   -72,    68,
+    86,  -217,   135,
+    36,   140,    79,
+    56,   175,   -49,
+    26,    45,     3,
+    73,    55,  -101,
+   109,  -183,  -242,
+    -4,  -283,  -242,
+    48,   -68,   -48,
+    -6,  -153,  -122,
+   161,   196,    96,
+   232,    80,   190,
+   165,    97,    11,
+   258,   -31,    71,
+   267,   -77,   -91,
+   311,  -209,    87,
+   152,   -14,   -22,
+   150,  -149,     9,
+  -324,   557,   187,
+  -384,   307,    46,
+  -251,    27,    77,
+  -365,    77,   -52,
+  -482,   -84,   160,
+  -424,  -515,   -64,
+  -294,  -120,    -4,
+  -476,  -116,  -109,
+   -97,   318,   365,
+   106,   627,   445,
+  -190,   120,   287,
+  -146,    65,   619,
+  -427,   242,   363,
+  -361,  -371,   432,
+  -347,   102,   168,
+  -629,   195,   -14,
+   -65,   476,   -47,
+  -297,   320,  -168,
+   -55,   356,  -264,
+  -391,    82,  -286,
+   -51,   -31,  -556,
+  -178,  -399,  -586,
+  -205,   -49,  -360,
+  -343,  -238,  -337,
+   220,   457,    58,
+   561,   467,   259,
+   340,   270,  -168,
+   450,    77,  -280,
+    60,   167,  -413,
+   133,  -252,  -492,
+   216,   157,  -290,
+   282,     0,  -495,
+  -226,   293,   183,
+  -157,   135,   122,
+  -158,   -59,    39,
+  -133,  -118,   -97,
+  -332,  -309,   113,
+  -160,  -425,    -6,
+  -149,  -211,    24,
+   -80,  -277,   -90,
+   -11,   125,   338,
+   130,   -71,   465,
+     5,   -45,   184,
+   237,   -95,   253,
+  -139,  -197,   297,
+   -19,  -300,   511,
+   -63,  -152,   139,
+   250,  -289,   336,
+   124,   339,  -150,
+    34,   176,  -208,
+   171,   166,  -116,
+    94,    38,  -229,
+    75,   -65,  -339,
+   -78,  -205,  -385,
+     0,   -30,  -163,
+   -56,  -110,  -242,
+   321,   244,   194,
+   505,   238,    -1,
+   317,   116,    65,
+   309,    88,   -74,
+   452,   -51,   -50,
+   334,  -217,  -290,
+   211,    41,  -152,
+   238,   -55,  -260};
+
+
+/*---------------------------------------------------*
+ * 2nd stage codebook; 3rd split:   isf2_6 to isf2_8
+ *---------------------------------------------------*/
+
+
+static Word16 dico23_isf[SIZE_BK23*3] = {
+
+   -10,   151,   359,
+   136,   298,   223,
+   255,  -104,   290,
+   423,     6,   183,
+  -270,  -269,   -98,
+   -52,   -82,    13,
+   -82,  -274,   -97,
+    90,  -246,   -72,
+  -299,   -70,   421,
+   -88,   365,   430,
+   187,  -318,   381,
+   380,    37,   488,
+  -373,  -316,    79,
+  -308,  -101,     5,
+  -135,  -451,     8,
+    72,  -421,  -154,
+   180,   170,  -121,
+    62,   177,   -40,
+   326,    80,  -105,
+   248,   263,    -5,
+  -168,  -181,  -221,
+    -2,   -23,  -158,
+   -14,  -149,  -121,
+   119,   -91,  -147,
+   119,   332,  -153,
+    49,   303,    34,
+   442,   -55,   -69,
+   217,   454,    58,
+  -359,  -187,  -375,
+   -42,    50,  -274,
+    -8,  -267,  -249,
+    85,   -86,  -346,
+   -77,   -40,   345,
+    89,   134,   219,
+   156,   -80,   160,
+   108,    40,   116,
+  -158,  -206,    29,
+     5,   -32,   175,
+   -65,  -158,   146,
+    55,   -78,    73,
+  -114,  -222,   353,
+   -47,    81,   211,
+    49,  -151,   268,
+   105,     4,   302,
+  -263,  -132,   183,
+  -151,   -28,   201,
+  -177,  -307,   166,
+   101,  -221,   130,
+    74,    58,   -98,
+    32,    44,    13,
+   194,    30,  -142,
+   170,    96,     8,
+  -136,  -119,   -91,
+   -65,     8,   -55,
+     3,  -188,    12,
+    45,   -63,   -49,
+   149,   -21,   -19,
+    24,   144,    95,
+   254,   -22,    60,
+   161,   196,    96,
+  -158,   -61,    48,
+   -70,    33,    82,
+   -23,  -321,    58,
+   155,  -147,     5,
+  -364,   328,    77,
+   -21,   453,   173,
+  -108,    82,   630,
+   367,   263,   208,
+  -300,   -62,  -176,
+  -205,   143,  -158,
+  -169,  -410,  -264,
+   257,  -269,  -100,
+  -636,   289,    -2,
+  -292,   627,   173,
+  -382,  -363,   387,
+   248,   524,   447,
+  -521,  -111,  -107,
+  -395,   118,  -274,
+  -343,  -680,  -125,
+  -172,  -447,  -663,
+    75,   148,  -367,
+   -79,   263,   -94,
+   249,   148,  -286,
+   380,   271,  -162,
+  -142,    -4,  -186,
+   -57,   111,  -125,
+   -35,  -108,  -254,
+   100,    29,  -242,
+   -80,   303,  -264,
+   -78,   464,   -57,
+   248,   -22,  -494,
+   661,   662,    44,
+  -193,   -40,  -330,
+  -178,   145,  -337,
+   -90,  -199,  -400,
+   -40,   -23,  -498,
+  -192,   114,   315,
+   -41,   244,   190,
+    88,   -97,   485,
+   241,    80,   212,
+  -246,    40,    87,
+  -156,   147,   134,
+    -2,  -334,   239,
+   308,  -203,   110,
+  -459,   251,   422,
+  -218,   310,   228,
+   -86,  -346,   654,
+   184,   175,   425,
+  -481,   -63,   169,
+  -349,   117,   188,
+  -125,  -560,   310,
+   158,  -416,    94,
+    46,   171,  -192,
+   -63,   157,    14,
+   256,   -35,  -271,
+   322,   123,    53,
+  -214,     4,   -76,
+  -156,    86,   -18,
+   128,  -197,  -232,
+   265,   -90,   -98,
+  -308,   332,  -145,
+  -131,   308,    58,
+   509,    59,  -339,
+   562,   196,   -14,
+  -378,   100,   -47,
+  -234,   202,     1,
+   104,  -270,  -493,
+   319,  -210,  -325};
+
+
+/*---------------------------------------------------*
+ * 2nd stage codebook; 4th split:   isf2_9 to isf2_11
+ *---------------------------------------------------*/
+
+static Word16 dico24_isf[SIZE_BK24*3] = {
+
+   -79,   -89,    -4,
+  -171,    77,  -211,
+   160,  -193,    98,
+   120,  -103,   323,
+    32,   -22,  -129,
+    72,    78,  -268,
+   182,   -76,   -66,
+   309,    99,  -145,
+  -229,  -157,   -84,
+  -383,    98,   -71,
+   -90,  -352,    12,
+  -284,  -178,   178,
+   -65,  -125,  -166,
+   -87,  -175,  -351,
+    42,  -198,   -48,
+   154,  -140,  -243,
+   -77,    18,   108,
+   -39,   355,    91,
+    87,     8,   155,
+    -4,   158,   239,
+   128,    95,   -54,
+     7,   246,  -124,
+   258,    15,    89,
+   206,   216,    98,
+  -201,     9,    18,
+  -312,   233,   204,
+   -39,  -174,   155,
+  -144,    -9,   284,
+   -57,    70,   -69,
+  -157,   187,    18,
+    54,   -30,    23,
+    24,   135,    55};
+
+
+/*---------------------------------------------------*
+ * 2nd stage codebook; 5th split:   isf2_12 to isf2_15
+ *---------------------------------------------------*/
+
+static Word16 dico25_isf[SIZE_BK25*4] = {
+
+   169,   142,  -119,   115,
+   206,   -20,    94,   226,
+  -106,   313,   -21,    16,
+   -62,   161,    71,   255,
+   -89,   101,  -185,   125,
+    72,   -30,  -201,   344,
+  -258,    33,    -8,    81,
+  -104,  -154,    72,   296,
+   144,   -68,  -268,   -25,
+    81,   -78,   -87,   106,
+    22,   155,  -186,  -119,
+   -46,   -28,    27,    91,
+  -114,   -37,  -175,   -33,
+   -94,  -222,  -189,   122,
+  -132,  -119,  -191,  -270,
+  -172,  -173,    18,   -43,
+   279,   135,   -42,  -128,
+   187,   -86,   229,  -138,
+   159,   240,   140,    46,
+    69,    25,   227,    77,
+    21,   115,    13,     8,
+    68,  -248,   126,    81,
+  -150,   137,   207,    -9,
+  -154,  -133,   289,    67,
+   143,   -37,   -86,  -326,
+   180,   -32,    19,   -23,
+    26,   168,   116,  -233,
+   -32,   -26,   118,   -78,
+     3,    -8,   -45,  -115,
+    57,  -215,   -54,   -83,
+  -209,   112,   -22,  -167,
+   -91,  -151,   168,  -262};
+
+
+
+       /* 36 bit */
+/*-------------------------------------------------------------------*
+ *  isf codebooks:  two-stage VQ with split-by-3 in 2nd stage        *
+ *                1st stage is kept the same as the 46 bit quantizer *
+ *                                                                   *
+ *  codebook   vector dimension    number of vectors                 *
+ *  ~~~~~~~~   ~~~~~~~~~~~~~~~~    ~~~~~~~~~~~~~~~~~                 *
+ *     1_1            9                  256                         *
+ *     1_2            7                  256                         *
+ *     2_1            5                  128                         *
+ *     2_2            4                  128                         *
+ *     2_3            7                  64                          *
+ *-------------------------------------------------------------------*/
+
+static Word16 dico21_isf_36b[SIZE_BK21_36b*5] = {
+
+   -52,   -96,   212,   315,   -73,
+    82,  -204,   363,   136,  -197,
+  -126,  -331,   183,   218,   143,
+   -49,   -41,   557,   230,    72,
+     2,   -73,   163,   377,   221,
+   133,   111,   278,   215,  -110,
+  -102,   -20,   284,   113,   273,
+    84,   319,   290,    18,    85,
+   -25,    -5,   125,   132,  -204,
+   -38,    -5,   286,    -9,  -356,
+  -140,  -256,    92,   117,  -189,
+  -144,   191,   313,    51,   -98,
+   167,   -10,    44,   247,    36,
+   381,   197,   238,    74,     6,
+    38,  -408,    29,    -3,   -85,
+    92,   266,   157,   -25,  -200,
+   161,  -121,    70,    84,  -140,
+   -16,   -86,   112,   -94,  -189,
+  -269,  -270,   351,   107,   -24,
+   -68,   -67,   492,  -103,  -155,
+   -53,  -131,    62,   122,    10,
+   135,    84,   283,   -55,  -120,
+   -12,  -219,   331,   -81,   167,
+   220,  -136,   147,  -172,   -42,
+   140,   -95,  -109,   -88,  -194,
+     0,    -2,    -4,   -33,  -381,
+   -66,  -217,   152,  -186,  -402,
+   244,   108,   156,  -140,  -395,
+   113,  -136,  -196,   110,   -24,
+   214,   118,    11,   -64,  -131,
+  -110,  -286,    -6,  -332,    16,
+    94,    97,    79,  -291,  -205,
+    -5,   -39,   -20,   252,   -96,
+    76,   174,   101,   163,    61,
+   -69,  -239,   -55,   399,     6,
+  -115,   319,   164,   275,   196,
+   -15,    36,   -47,   331,   121,
+   226,   209,   271,   325,   184,
+    13,   -80,  -218,   471,   353,
+   288,   378,    16,   -51,   251,
+   174,   116,    52,   149,  -279,
+   235,   276,    39,   120,   -48,
+     0,  -108,  -108,   241,  -339,
+   -93,   534,    45,    33,   -87,
+   194,   149,   -71,   405,   -44,
+   409,   370,    81,  -186,  -154,
+    25,  -102,  -448,   124,  -173,
+    22,   408,  -110,  -310,  -214,
+   -26,    23,   -83,   114,    14,
+  -110,   164,    52,   223,   -82,
+    37,   -25,  -263,   306,   -15,
+  -466,   415,   292,   165,   -18,
+    29,   -19,  -171,   155,   182,
+   179,   144,   -27,   231,   258,
+  -103,  -247,  -396,   238,   113,
+   375,  -154,  -109,    -4,   156,
+    98,    85,  -292,    -5,  -124,
+   116,   139,  -116,   -98,  -294,
+   -14,   -83,  -278,  -117,  -378,
+   106,    33,  -106,  -344,  -484,
+   119,    17,  -412,   138,   166,
+   384,   101,  -204,    88,  -156,
+  -121,  -284,  -300,    -1,  -166,
+   280,    33,  -152,  -313,   -81,
+   -37,    22,   229,   153,    37,
+   -60,   -83,   236,    -8,   -41,
+  -169,  -228,   126,   -20,   363,
+  -235,    17,   364,  -156,   156,
+   -25,   -30,    72,   144,   156,
+   153,   -26,   256,    97,   144,
+   -21,   -37,    48,   -65,   250,
+    63,    77,   273,  -128,   124,
+  -129,   -26,    40,     9,  -115,
+    -6,    82,    38,   -90,  -182,
+  -336,   -13,    28,   158,    91,
+   -30,   241,   137,  -170,   -17,
+   146,    14,   -11,    33,    61,
+   192,   197,    54,   -84,    85,
+    23,  -200,   -78,   -29,   140,
+   122,   237,   106,  -341,   136,
+   -57,  -142,   -85,   -16,   -74,
+   -59,   -90,    -8,  -187,   -20,
+  -211,  -267,   216,  -179,  -110,
+   -50,    -7,   220,  -267,   -70,
+   -57,   -42,   -17,   -15,    71,
+    32,    21,    63,  -137,    33,
+  -137,  -175,   104,   -68,    97,
+   -67,   -43,   133,  -301,   221,
+  -116,  -200,   -81,   -92,  -272,
+   -64,   -41,   -54,  -244,  -220,
+  -287,  -242,   -50,   -87,   -89,
+  -245,   236,   102,  -166,  -295,
+    66,    24,  -162,   -71,    95,
+    66,   136,   -90,  -220,   -36,
+   -98,  -161,  -222,  -188,    29,
+   -18,    18,   -19,  -415,     9,
+    49,    61,   100,    39,   -56,
+  -111,    82,   135,   -31,    52,
+   -90,  -153,   -93,   189,   182,
+  -214,   295,   119,   -74,   284,
+     2,   137,    37,    47,   182,
+    92,   117,   184,   -53,   373,
+   -21,   -14,   -35,   136,   391,
+   146,   129,  -164,   -28,   333,
+    92,    80,   -84,   100,  -134,
+    -8,   217,   -32,     3,   -47,
+  -151,   251,  -215,   142,    92,
+  -224,   310,  -172,  -275,    98,
+   159,   155,  -177,   112,    53,
+   205,    27,     8,  -240,   192,
+   169,   120,  -319,  -201,   106,
+    11,    36,   -86,  -237,   455,
+  -109,  -154,  -163,   174,   -55,
+   -38,    32,  -101,   -78,   -59,
+  -205,  -321,   -97,    69,    79,
+  -310,    44,    18,  -185,    34,
+  -115,   -20,  -148,   -39,   203,
+   -29,   154,   -30,  -158,   166,
+   -45,  -131,  -317,   -24,   363,
+  -165,  -205,  -112,  -222,   265,
+   -32,   -44,  -150,    54,  -193,
+    -6,   -38,  -255,  -169,  -115,
+  -266,    87,  -189,   -36,  -169,
+   -60,   -87,  -266,  -436,  -170,
+   -68,   -81,  -278,    24,    38,
+   -23,   -19,  -155,  -256,   141,
+   -61,  -226,  -565,  -175,    71,
+     9,   -29,  -237,  -515,   263};
+
+static Word16 dico22_isf_36b[SIZE_BK22_36b*4] = {
+
+  -298,    -6,    95,    31,
+  -213,   -87,  -122,   261,
+     4,   -49,   208,    14,
+  -129,  -110,    30,   118,
+  -214,   258,   110,  -235,
+   -41,   -18,  -126,   120,
+   103,    65,   127,   -37,
+   126,   -36,   -24,    25,
+  -138,   -67,  -278,  -186,
+  -164,  -194,  -201,    78,
+  -211,   -87,   -51,  -221,
+  -174,   -79,   -94,   -39,
+    23,    -6,  -157,  -240,
+    22,  -110,  -153,   -68,
+   148,    -5,    -2,  -149,
+    -1,  -135,   -39,  -179,
+    68,   360,  -117,   -15,
+   137,    47,  -278,   146,
+   136,   260,   135,    65,
+    61,   116,   -45,    97,
+   231,   379,    87,  -120,
+   338,   177,  -272,     3,
+   266,   156,    28,   -69,
+   260,    84,   -85,    86,
+  -266,   154,  -256,  -182,
+   -17,   -65,  -304,    -6,
+   -40,   175,  -151,  -180,
+   -27,    27,   -87,   -63,
+   121,   114,  -166,  -469,
+   159,   -66,  -323,  -231,
+   214,   152,  -141,  -212,
+   137,    36,  -184,   -51,
+  -282,  -237,    40,    10,
+   -48,  -235,   -37,   251,
+   -54,  -323,   136,    29,
+   -88,  -174,   213,   198,
+  -390,    99,   -63,  -375,
+   107,  -169,  -164,   424,
+    69,  -111,   141,  -167,
+    74,  -129,    65,   144,
+  -353,  -207,  -205,  -109,
+  -160,  -386,  -355,    98,
+  -176,  -493,   -20,  -143,
+  -252,  -432,    -2,   216,
+   -90,  -174,  -168,  -411,
+    13,  -284,  -229,  -160,
+   -87,  -279,    34,  -251,
+   -75,  -263,   -58,   -42,
+   420,    53,  -211,  -358,
+   384,   -35,  -374,   396,
+    68,  -228,   323,    -2,
+   167,  -307,   192,   194,
+   459,   329,    -5,  -332,
+   375,    79,    -7,   313,
+   282,  -124,   200,   -92,
+   271,  -162,   -70,   180,
+  -157,  -298,  -514,  -309,
+    58,  -163,  -546,    18,
+   124,  -364,   167,  -238,
+    83,  -411,  -117,    96,
+   140,  -112,  -388,  -624,
+   259,  -133,  -317,    41,
+   163,  -130,   -64,  -334,
+   226,  -165,  -124,  -110,
+  -466,   -61,     6,   229,
+  -153,   205,  -145,   242,
+  -159,    48,   195,   148,
+   -58,    28,    31,   279,
+  -303,   185,   279,    -4,
+   -61,   197,    59,    86,
+  -114,   123,   168,   -52,
+    35,    36,   100,   126,
+  -407,   102,   -77,   -40,
+  -338,    -1,  -342,   156,
+  -179,   105,   -34,   -97,
+  -185,    84,   -35,   108,
+  -133,   107,   -91,  -357,
+  -180,    54,  -229,    24,
+   -44,    47,    47,  -182,
+   -66,    13,    45,     4,
+  -339,   251,    64,   226,
+   -42,   101,  -350,   275,
+   -99,   398,   142,   121,
+   111,    12,  -102,   260,
+     0,   505,   260,   -94,
+   161,   285,   -96,   224,
+    -4,   206,   314,    33,
+   167,   139,    88,   204,
+  -235,   316,   -60,   -25,
+    -8,  -150,  -312,   201,
+   -36,   292,    61,  -104,
+   -40,   174,  -162,    42,
+   -21,   402,   -29,  -351,
+    21,   152,  -360,   -93,
+    57,   191,   212,  -196,
+    76,   158,   -21,   -69,
+  -328,  -185,   331,   119,
+   -53,   285,    56,   337,
+  -107,   -24,   405,    29,
+   -18,   137,   272,   277,
+  -255,    22,   173,  -191,
+   295,   322,   325,   302,
+    21,   -27,   332,  -178,
+   119,    13,   271,   129,
+  -455,  -180,   116,  -191,
+  -227,    62,  -148,   524,
+  -176,  -287,   282,  -157,
+  -243,    13,   199,   430,
+   -59,   -49,   115,  -365,
+    72,  -172,  -137,    93,
+  -138,  -126,   141,   -84,
+     5,  -124,    38,   -20,
+  -258,   311,   601,   213,
+    94,   130,   -61,   502,
+    -1,  -157,   485,   313,
+   146,   -74,   158,   345,
+   276,   135,   280,   -57,
+   490,   252,    99,    43,
+   267,   -74,   429,   105,
+   278,   -23,   119,    94,
+  -542,   488,   257,  -115,
+   -84,  -244,  -438,   478,
+  -113,  -545,   387,   101,
+   -95,  -306,   111,   498,
+    95,   166,    22,  -301,
+   420,   -15,   -58,   -78,
+   270,    29,   122,  -282,
+   160,  -240,    50,   -38};
+
+static Word16 dico23_isf_36b[SIZE_BK23_36b*7] = {
+
+    81,   -18,    68,   -27,  -122,  -280,    -4,
+    45,  -177,   209,   -30,  -136,   -74,   131,
+   -44,   101,   -75,   -88,   -48,  -137,   -54,
+  -245,   -28,    63,   -18,  -112,  -103,    58,
+   -79,    -6,   220,   -65,   114,   -35,   -50,
+   109,   -65,   143,  -114,   129,    76,   125,
+   166,    90,   -61,  -242,   186,   -74,   -43,
+   -46,   -92,    49,  -227,    24,  -155,    39,
+    67,    85,    99,   -42,    53,  -184,  -281,
+   142,  -122,     0,    21,  -142,   -15,   -17,
+   223,    92,   -21,   -48,   -82,   -14,  -167,
+    51,   -37,  -243,   -30,   -90,    18,   -56,
+    54,   105,    74,    86,    69,    13,  -101,
+   196,    72,   -89,    43,    65,    19,    39,
+   121,    34,   131,   -82,    25,   213,  -156,
+   101,  -102,  -136,   -21,    57,   214,    22,
+    36,  -124,   205,   204,    58,  -156,   -83,
+    83,  -117,   137,   137,    85,   116,    44,
+   -92,  -148,   -68,    11,  -102,  -197,  -220,
+   -76,  -185,   -58,   132,   -26,  -183,    85,
+    -7,   -31,    -2,    23,   205,  -151,    10,
+   -27,   -37,    -5,   -18,   292,   131,     1,
+   117,  -168,     9,   -93,    80,   -59,  -125,
+  -182,  -244,    98,   -24,   135,   -22,    94,
+   221,    97,   106,    42,    43,  -160,    83,
+    25,   -64,   -21,     6,    14,   -15,   154,
+   126,    15,  -140,   150,   -10,  -207,  -114,
+    79,   -63,  -211,   -70,   -28,  -217,   165,
+    46,    38,   -22,   281,   132,   -62,   109,
+   112,    54,  -112,   -93,   208,    27,   296,
+   115,    10,  -147,    41,   216,    42,  -276,
+    50,  -115,  -254,   167,   117,    -2,    61,
+    17,   144,    34,   -72,  -186,  -150,   272,
+   -29,   -66,   -89,   -95,  -149,   129,   251,
+   122,     0,   -50,  -234,   -91,    36,    26,
+  -105,  -102,   -88,  -121,  -236,    -7,   -11,
+  -204,   109,     5,  -191,   105,   -15,   163,
+   -80,    32,   -24,  -209,    41,   294,    70,
+  -106,   -94,  -204,  -118,   120,   -50,   -37,
+   -82,  -241,    46,  -131,   -29,   150,   -55,
+    33,   155,   120,   -89,    -8,     7,    62,
+   213,    82,    61,    18,  -161,   144,   152,
+    30,   131,    65,   -87,  -255,   -17,  -107,
+    -8,    85,   -64,    51,  -162,   223,   -53,
+  -134,   261,    69,   -56,   218,    72,  -111,
+     2,   155,  -113,   -87,    49,    85,   -28,
+  -163,    42,    -1,  -196,     7,    39,  -245,
+    14,  -137,   -79,    11,  -160,   202,  -293,
+   -94,    33,   208,   100,    56,   -44,   326,
+   -78,   -41,   232,    13,  -142,   227,    80,
+   -16,   -87,   201,    33,  -133,    15,  -183,
+   -58,  -192,   -47,   184,  -128,   133,    99,
+  -205,    11,  -155,    78,    52,    72,   141,
+  -246,    26,    99,   151,    59,   115,   -64,
+   -79,   -47,   -16,   -14,     6,    47,   -43,
+   -72,  -178,   -27,   162,   112,    43,  -174,
+  -175,   238,   186,    71,   -54,  -188,   -76,
+  -225,   233,    39,   -39,  -158,   122,    44,
+   -26,    43,    84,   130,   -93,   -51,    22,
+     3,    92,  -150,   136,  -182,   -57,    97,
+  -131,   179,   -78,    80,    91,  -165,    90,
+    -2,   148,    15,   130,    65,   175,   117,
+  -138,   114,  -137,   132,     3,   -10,  -186,
+   140,    -4,   -37,   254,   -62,    92,  -109};
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/stream.h b/media/libstagefright/codecs/amrwbenc/inc/stream.h
index edbc13a..4c1d0f0 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/stream.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/stream.h
@@ -1,47 +1,47 @@
-

-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/***********************************************************************

-File:		stream.h

-

-Contains:       VOME API Buffer Operator Implement Header

-

-************************************************************************/

-#ifndef __STREAM_H__

-#define __STREAM_H__

-

-#include "voMem.h"

-#define Frame_Maxsize  1024 * 2  //Work Buffer 10K 

-#define Frame_MaxByte  640        //AMR_WB Encoder one frame 320 samples = 640 Bytes

-#define MIN(a,b)	 ((a) < (b)? (a) : (b))

-

-typedef struct{

-	unsigned char *set_ptr;

-	unsigned char *frame_ptr;

-	unsigned char *frame_ptr_bk;

-	int  set_len;

-	int  framebuffer_len; 

-	int  frame_storelen;

-	int  used_len;

-}FrameStream;

-

-void voAWB_UpdateFrameBuffer(FrameStream *stream, VO_MEM_OPERATOR *pMemOP);

-void voAWB_InitFrameBuffer(FrameStream *stream);

-void voAWB_FlushFrameBuffer(FrameStream *stream);

-#endif //__STREAM_H__

-

+
+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/***********************************************************************
+File:		stream.h
+
+Contains:       VOME API Buffer Operator Implement Header
+
+************************************************************************/
+#ifndef __STREAM_H__
+#define __STREAM_H__
+
+#include "voMem.h"
+#define Frame_Maxsize  1024 * 2  //Work Buffer 10K
+#define Frame_MaxByte  640        //AMR_WB Encoder one frame 320 samples = 640 Bytes
+#define MIN(a,b)	 ((a) < (b)? (a) : (b))
+
+typedef struct{
+	unsigned char *set_ptr;
+	unsigned char *frame_ptr;
+	unsigned char *frame_ptr_bk;
+	int  set_len;
+	int  framebuffer_len;
+	int  frame_storelen;
+	int  used_len;
+}FrameStream;
+
+void voAWB_UpdateFrameBuffer(FrameStream *stream, VO_MEM_OPERATOR *pMemOP);
+void voAWB_InitFrameBuffer(FrameStream *stream);
+void voAWB_FlushFrameBuffer(FrameStream *stream);
+#endif //__STREAM_H__
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/typedef.h b/media/libstagefright/codecs/amrwbenc/inc/typedef.h
index aa8c098..f08a678 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/typedef.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/typedef.h
@@ -1,65 +1,65 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*

-*      File             : typedef.c

-*      Purpose          : Basic types.

-*

-************************************************************************/

-

-#ifndef __TYPEDEF_H__

-#define __TYPEDEF_H__

-

-#undef ORIGINAL_TYPEDEF_H /* define to get "original" ETSI version

-                             of typedef.h                           */

-

-#ifdef ORIGINAL_TYPEDEF_H

-/*

- * this is the original code from the ETSI file typedef.h

- */

-   

-#if defined(__BORLANDC__) || defined(__WATCOMC__) || defined(_MSC_VER) || defined(__ZTC__)

-typedef signed char Word8;

-typedef short Word16;

-typedef long Word32;

-typedef int Flag;

-

-#elif defined(__sun)

-typedef signed char Word8;

-typedef short Word16;

-typedef long Word32;

-typedef int Flag;

-

-#elif defined(__unix__) || defined(__unix)

-typedef signed char Word8;

-typedef short Word16;

-typedef int Word32;

-typedef int Flag;

-

-#endif

-#else /* not original typedef.h */

-

-/*

- * use (improved) type definition file typdefs.h and add a "Flag" type

- */

-#include "typedefs.h"

-typedef int Flag;

-

-#endif

-

-#endif  //__TYPEDEF_H__

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*
+*      File             : typedef.c
+*      Purpose          : Basic types.
+*
+************************************************************************/
+
+#ifndef __TYPEDEF_H__
+#define __TYPEDEF_H__
+
+#undef ORIGINAL_TYPEDEF_H /* define to get "original" ETSI version
+                             of typedef.h                           */
+
+#ifdef ORIGINAL_TYPEDEF_H
+/*
+ * this is the original code from the ETSI file typedef.h
+ */
+
+#if defined(__BORLANDC__) || defined(__WATCOMC__) || defined(_MSC_VER) || defined(__ZTC__)
+typedef signed char Word8;
+typedef short Word16;
+typedef long Word32;
+typedef int Flag;
+
+#elif defined(__sun)
+typedef signed char Word8;
+typedef short Word16;
+typedef long Word32;
+typedef int Flag;
+
+#elif defined(__unix__) || defined(__unix)
+typedef signed char Word8;
+typedef short Word16;
+typedef int Word32;
+typedef int Flag;
+
+#endif
+#else /* not original typedef.h */
+
+/*
+ * use (improved) type definition file typdefs.h and add a "Flag" type
+ */
+#include "typedefs.h"
+typedef int Flag;
+
+#endif
+
+#endif  //__TYPEDEF_H__
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/typedefs.h b/media/libstagefright/codecs/amrwbenc/inc/typedefs.h
index 28b657e..0062584 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/typedefs.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/typedefs.h
@@ -1,211 +1,211 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/*

-*

-*      File             : typedefs.h

-*      Description      : Definition of platform independent data

-*                         types and constants

-*

-*

-*      The following platform independent data types and corresponding

-*      preprocessor (#define) constants are defined:

-*

-*        defined type  meaning           corresponding constants

-*        ----------------------------------------------------------

-*        Char          character         (none)

-*        Bool          boolean           true, false

-*        Word8         8-bit signed      minWord8,   maxWord8

-*        UWord8        8-bit unsigned    minUWord8,  maxUWord8

-*        Word16        16-bit signed     minWord16,  maxWord16

-*        UWord16       16-bit unsigned   minUWord16, maxUWord16

-*        Word32        32-bit signed     minWord32,  maxWord32

-*        UWord32       32-bit unsigned   minUWord32, maxUWord32

-*        Float         floating point    minFloat,   maxFloat

-*

-*

-*      The following compile switches are #defined:

-*

-*        PLATFORM      string indicating platform progam is compiled on

-*                      possible values: "OSF", "PC", "SUN"

-*

-*        OSF           only defined if the current platform is an Alpha

-*        PC            only defined if the current platform is a PC

-*        SUN           only defined if the current platform is a Sun

-*        

-*        LSBFIRST      is defined if the byte order on this platform is

-*                      "least significant byte first" -> defined on DEC Alpha

-*                      and PC, undefined on Sun

-*

-********************************************************************************

-*/

-

-#ifndef __TYPEDEFS_H__

-#define __TYPEDEFS_H__

-

-/*

-********************************************************************************

-*                         INCLUDE FILES

-********************************************************************************

-*/

-#include <float.h>

-#include <limits.h>

-

-

-

-/*

-********************************************************************************

-*                         DEFINITION OF CONSTANTS 

-********************************************************************************

-*/

-/*

- ********* define char type

- */

-typedef char Char;

-

-/*

- ********* define 8 bit signed/unsigned types & constants

- */

-#if SCHAR_MAX == 127

-typedef signed char Word8;

-#define minWord8  SCHAR_MIN

-#define maxWord8  SCHAR_MAX

-

-typedef unsigned char UWord8;

-#define minUWord8 0

-#define maxUWord8 UCHAR_MAX

-#else

-#error cannot find 8-bit type

-#endif

-

-

-/*

- ********* define 16 bit signed/unsigned types & constants

- */

-#if INT_MAX == 32767

-typedef int Word16;

-#define minWord16     INT_MIN

-#define maxWord16     INT_MAX

-typedef unsigned int UWord16;

-#define minUWord16    0

-#define maxUWord16    UINT_MAX

-#elif SHRT_MAX == 32767

-typedef short Word16;

-#define minWord16     SHRT_MIN

-#define maxWord16     SHRT_MAX

-typedef unsigned short UWord16;

-#define minUWord16    0

-#define maxUWord16    USHRT_MAX

-#else

-#error cannot find 16-bit type

-#endif

-

-

-/*

- ********* define 32 bit signed/unsigned types & constants

- */

-#if INT_MAX == 2147483647

-typedef int Word32;

-#define minWord32     INT_MIN

-#define maxWord32     INT_MAX

-typedef unsigned int UWord32;

-#define minUWord32    0

-#define maxUWord32    UINT_MAX

-#elif LONG_MAX == 2147483647

-typedef long Word32;

-#define minWord32     LONG_MIN

-#define maxWord32     LONG_MAX

-typedef unsigned long UWord32;

-#define minUWord32    0

-#define maxUWord32    ULONG_MAX

-#else

-#error cannot find 32-bit type

-#endif

-

-/*

- ********* define floating point type & constants

- */

-/* use "#if 0" below if Float should be double;

-   use "#if 1" below if Float should be float

- */

-#if 0

-typedef float Float;

-#define maxFloat      FLT_MAX

-#define minFloat      FLT_MIN

-#else

-typedef double Float;

-#define maxFloat      DBL_MAX

-#define minFloat      DBL_MIN

-#endif

-

-/*

- ********* define complex type

- */

-typedef struct {

-  Float r;  /* real      part */

-  Float i;  /* imaginary part */

-} CPX;

-

-/*

- ********* define boolean type

- */

-typedef int Bool;

-#define false 0

-#define true 1

-

-/* ******Avoid function multiple definition****** */

-#define     Autocorr         voAWB_Autocorr

-#define     Convolve         voAWB_Convolve

-#define     cor_h_x          voAWB_cor_h_x

-#define     dtx_enc_init     voAWB_dtx_enc_init

-#define     dtx_enc_reset    voAWB_dtx_enc_reset

-#define     dtx_enc_exit     voAWB_dtx_enc_exit

-#define     dtx_enc          voAWB_dtx_enc

-#define     dtx_buffer       voAWB_dtx_buffer

-#define     tx_dtx_handler   voAWB_tx_dtx_handler

-#define     G_pitch          voAWB_G_pitch

-#define     Isp_Az           voAWB_Isp_Az

-#define     Lag_window       voAWB_Lag_window

-#define     Log2_norm        voAWB_Log2_norm

-#define     Log2             voAWB_Log2

-#define     Pow2             voAWB_Pow2

-#define     L_Comp           voAWB_L_Comp

-#define     Mpy_32           voAWB_Mpy_32

-#define     Mpy_32_16        voAWB_Mpy_32_16

-#define     Div_32           voAWB_Div_32

-#define     Pit_shrp         voAWB_Pit_shrp

-#define     Qisf_ns          voAWB_Qisf_ns

-#define     Disf_ns          voAWB_Disf_ns

-#define     Residu           voAWB_Residu

-#define     Syn_filt         voAWB_Syn_filt

-#define     Set_zero         voAWB_Set_zero

-#define     Copy             voAWB_Copy

-#define     voice_factor     voAWB_voice_factor

-#define     Syn_filt_32      voAWB_Syn_filt_32

-#define     Isf_isp          voAWB_Isf_isp

-#define     Levinson         voAWB_Levinson

-#define     median5          voAWB_median5           

-#define     Pred_lt4         voAWB_Pred_lt4

-#define     Reorder_isf      voAWB_Reorder_isf

-#define     Dpisf_2s_36b     voAWB_Dpisf_2s_36b

-#define     Dpisf_2s_46b     voAWB_Dpisf_2s_46b

-#define     Dot_product12    voAWB_Dot_product12

-#define     mem_malloc       voAWB_mem_malloc

-#define     mem_free         voAWB_mem_free

-/******************************************************/

-

-#endif  //#define __TYPEDEFS_H__

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/*
+*
+*      File             : typedefs.h
+*      Description      : Definition of platform independent data
+*                         types and constants
+*
+*
+*      The following platform independent data types and corresponding
+*      preprocessor (#define) constants are defined:
+*
+*        defined type  meaning           corresponding constants
+*        ----------------------------------------------------------
+*        Char          character         (none)
+*        Bool          boolean           true, false
+*        Word8         8-bit signed      minWord8,   maxWord8
+*        UWord8        8-bit unsigned    minUWord8,  maxUWord8
+*        Word16        16-bit signed     minWord16,  maxWord16
+*        UWord16       16-bit unsigned   minUWord16, maxUWord16
+*        Word32        32-bit signed     minWord32,  maxWord32
+*        UWord32       32-bit unsigned   minUWord32, maxUWord32
+*        Float         floating point    minFloat,   maxFloat
+*
+*
+*      The following compile switches are #defined:
+*
+*        PLATFORM      string indicating platform progam is compiled on
+*                      possible values: "OSF", "PC", "SUN"
+*
+*        OSF           only defined if the current platform is an Alpha
+*        PC            only defined if the current platform is a PC
+*        SUN           only defined if the current platform is a Sun
+*
+*        LSBFIRST      is defined if the byte order on this platform is
+*                      "least significant byte first" -> defined on DEC Alpha
+*                      and PC, undefined on Sun
+*
+********************************************************************************
+*/
+
+#ifndef __TYPEDEFS_H__
+#define __TYPEDEFS_H__
+
+/*
+********************************************************************************
+*                         INCLUDE FILES
+********************************************************************************
+*/
+#include <float.h>
+#include <limits.h>
+
+
+
+/*
+********************************************************************************
+*                         DEFINITION OF CONSTANTS
+********************************************************************************
+*/
+/*
+ ********* define char type
+ */
+typedef char Char;
+
+/*
+ ********* define 8 bit signed/unsigned types & constants
+ */
+#if SCHAR_MAX == 127
+typedef signed char Word8;
+#define minWord8  SCHAR_MIN
+#define maxWord8  SCHAR_MAX
+
+typedef unsigned char UWord8;
+#define minUWord8 0
+#define maxUWord8 UCHAR_MAX
+#else
+#error cannot find 8-bit type
+#endif
+
+
+/*
+ ********* define 16 bit signed/unsigned types & constants
+ */
+#if INT_MAX == 32767
+typedef int Word16;
+#define minWord16     INT_MIN
+#define maxWord16     INT_MAX
+typedef unsigned int UWord16;
+#define minUWord16    0
+#define maxUWord16    UINT_MAX
+#elif SHRT_MAX == 32767
+typedef short Word16;
+#define minWord16     SHRT_MIN
+#define maxWord16     SHRT_MAX
+typedef unsigned short UWord16;
+#define minUWord16    0
+#define maxUWord16    USHRT_MAX
+#else
+#error cannot find 16-bit type
+#endif
+
+
+/*
+ ********* define 32 bit signed/unsigned types & constants
+ */
+#if INT_MAX == 2147483647
+typedef int Word32;
+#define minWord32     INT_MIN
+#define maxWord32     INT_MAX
+typedef unsigned int UWord32;
+#define minUWord32    0
+#define maxUWord32    UINT_MAX
+#elif LONG_MAX == 2147483647
+typedef long Word32;
+#define minWord32     LONG_MIN
+#define maxWord32     LONG_MAX
+typedef unsigned long UWord32;
+#define minUWord32    0
+#define maxUWord32    ULONG_MAX
+#else
+#error cannot find 32-bit type
+#endif
+
+/*
+ ********* define floating point type & constants
+ */
+/* use "#if 0" below if Float should be double;
+   use "#if 1" below if Float should be float
+ */
+#if 0
+typedef float Float;
+#define maxFloat      FLT_MAX
+#define minFloat      FLT_MIN
+#else
+typedef double Float;
+#define maxFloat      DBL_MAX
+#define minFloat      DBL_MIN
+#endif
+
+/*
+ ********* define complex type
+ */
+typedef struct {
+  Float r;  /* real      part */
+  Float i;  /* imaginary part */
+} CPX;
+
+/*
+ ********* define boolean type
+ */
+typedef int Bool;
+#define false 0
+#define true 1
+
+/* ******Avoid function multiple definition****** */
+#define     Autocorr         voAWB_Autocorr
+#define     Convolve         voAWB_Convolve
+#define     cor_h_x          voAWB_cor_h_x
+#define     dtx_enc_init     voAWB_dtx_enc_init
+#define     dtx_enc_reset    voAWB_dtx_enc_reset
+#define     dtx_enc_exit     voAWB_dtx_enc_exit
+#define     dtx_enc          voAWB_dtx_enc
+#define     dtx_buffer       voAWB_dtx_buffer
+#define     tx_dtx_handler   voAWB_tx_dtx_handler
+#define     G_pitch          voAWB_G_pitch
+#define     Isp_Az           voAWB_Isp_Az
+#define     Lag_window       voAWB_Lag_window
+#define     Log2_norm        voAWB_Log2_norm
+#define     Log2             voAWB_Log2
+#define     Pow2             voAWB_Pow2
+#define     L_Comp           voAWB_L_Comp
+#define     Mpy_32           voAWB_Mpy_32
+#define     Mpy_32_16        voAWB_Mpy_32_16
+#define     Div_32           voAWB_Div_32
+#define     Pit_shrp         voAWB_Pit_shrp
+#define     Qisf_ns          voAWB_Qisf_ns
+#define     Disf_ns          voAWB_Disf_ns
+#define     Residu           voAWB_Residu
+#define     Syn_filt         voAWB_Syn_filt
+#define     Set_zero         voAWB_Set_zero
+#define     Copy             voAWB_Copy
+#define     voice_factor     voAWB_voice_factor
+#define     Syn_filt_32      voAWB_Syn_filt_32
+#define     Isf_isp          voAWB_Isf_isp
+#define     Levinson         voAWB_Levinson
+#define     median5          voAWB_median5
+#define     Pred_lt4         voAWB_Pred_lt4
+#define     Reorder_isf      voAWB_Reorder_isf
+#define     Dpisf_2s_36b     voAWB_Dpisf_2s_36b
+#define     Dpisf_2s_46b     voAWB_Dpisf_2s_46b
+#define     Dot_product12    voAWB_Dot_product12
+#define     mem_malloc       voAWB_mem_malloc
+#define     mem_free         voAWB_mem_free
+/******************************************************/
+
+#endif  //#define __TYPEDEFS_H__
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/wb_vad.h b/media/libstagefright/codecs/amrwbenc/inc/wb_vad.h
index b733afe..6822f48 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/wb_vad.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/wb_vad.h
@@ -1,78 +1,78 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/*-------------------------------------------------------------------*

- *                         WB_VAD.H                                  *

- *-------------------------------------------------------------------*

- * Functions and static memory for Voice Activity Detection.         *

- *-------------------------------------------------------------------*/

-

-#ifndef __WB_VAD_H__

-#define __WB_VAD_H__

-

-/******************************************************************************

- *                         INCLUDE FILES

- ******************************************************************************/

-#include "typedef.h"

-#include "wb_vad_c.h"

-#include "voMem.h"

-

-/******************************************************************************

- *                         DEFINITION OF DATA TYPES

- ******************************************************************************/

-

-typedef struct

-{

-	Word16 bckr_est[COMPLEN];              /* background noise estimate                */

-	Word16 ave_level[COMPLEN];             /* averaged input components for stationary */

-	/* estimation                               */

-	Word16 old_level[COMPLEN];             /* input levels of the previous frame       */

-	Word16 sub_level[COMPLEN];             /* input levels calculated at the end of a frame (lookahead)  */

-	Word16 a_data5[F_5TH_CNT][2];          /* memory for the filter bank               */

-	Word16 a_data3[F_3TH_CNT];             /* memory for the filter bank               */

-

-	Word16 burst_count;                    /* counts length of a speech burst          */

-	Word16 hang_count;                     /* hangover counter                         */

-	Word16 stat_count;                     /* stationary counter                       */

-

-	/* Note that each of the following two variables holds 15 flags. Each flag reserves 1 bit of the

-	 * variable. The newest flag is in the bit 15 (assuming that LSB is bit 1 and MSB is bit 16). */

-	Word16 vadreg;                         /* flags for intermediate VAD decisions     */

-	Word16 tone_flag;                      /* tone detection flags                     */

-

-	Word16 sp_est_cnt;                     /* counter for speech level estimation      */

-	Word16 sp_max;                         /* maximum level                            */

-	Word16 sp_max_cnt;                     /* counts frames that contains speech       */

-	Word16 speech_level;                   /* estimated speech level                   */

-	Word32 prev_pow_sum;                   /* power of previous frame                  */

-

-} VadVars;

-

-/********************************************************************************

- *

- * DECLARATION OF PROTOTYPES

- ********************************************************************************/

-

-Word16 wb_vad_init(VadVars ** st, VO_MEM_OPERATOR *pMemOP);

-Word16 wb_vad_reset(VadVars * st);

-void wb_vad_exit(VadVars ** st, VO_MEM_OPERATOR *pMemOP);

-void wb_vad_tone_detection(VadVars * st, Word16 p_gain);

-Word16 wb_vad(VadVars * st, Word16 in_buf[]);

-

-#endif  //__WB_VAD_H__

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/*-------------------------------------------------------------------*
+ *                         WB_VAD.H                                  *
+ *-------------------------------------------------------------------*
+ * Functions and static memory for Voice Activity Detection.         *
+ *-------------------------------------------------------------------*/
+
+#ifndef __WB_VAD_H__
+#define __WB_VAD_H__
+
+/******************************************************************************
+ *                         INCLUDE FILES
+ ******************************************************************************/
+#include "typedef.h"
+#include "wb_vad_c.h"
+#include "voMem.h"
+
+/******************************************************************************
+ *                         DEFINITION OF DATA TYPES
+ ******************************************************************************/
+
+typedef struct
+{
+	Word16 bckr_est[COMPLEN];              /* background noise estimate                */
+	Word16 ave_level[COMPLEN];             /* averaged input components for stationary */
+	/* estimation                               */
+	Word16 old_level[COMPLEN];             /* input levels of the previous frame       */
+	Word16 sub_level[COMPLEN];             /* input levels calculated at the end of a frame (lookahead)  */
+	Word16 a_data5[F_5TH_CNT][2];          /* memory for the filter bank               */
+	Word16 a_data3[F_3TH_CNT];             /* memory for the filter bank               */
+
+	Word16 burst_count;                    /* counts length of a speech burst          */
+	Word16 hang_count;                     /* hangover counter                         */
+	Word16 stat_count;                     /* stationary counter                       */
+
+	/* Note that each of the following two variables holds 15 flags. Each flag reserves 1 bit of the
+	 * variable. The newest flag is in the bit 15 (assuming that LSB is bit 1 and MSB is bit 16). */
+	Word16 vadreg;                         /* flags for intermediate VAD decisions     */
+	Word16 tone_flag;                      /* tone detection flags                     */
+
+	Word16 sp_est_cnt;                     /* counter for speech level estimation      */
+	Word16 sp_max;                         /* maximum level                            */
+	Word16 sp_max_cnt;                     /* counts frames that contains speech       */
+	Word16 speech_level;                   /* estimated speech level                   */
+	Word32 prev_pow_sum;                   /* power of previous frame                  */
+
+} VadVars;
+
+/********************************************************************************
+ *
+ * DECLARATION OF PROTOTYPES
+ ********************************************************************************/
+
+Word16 wb_vad_init(VadVars ** st, VO_MEM_OPERATOR *pMemOP);
+Word16 wb_vad_reset(VadVars * st);
+void wb_vad_exit(VadVars ** st, VO_MEM_OPERATOR *pMemOP);
+void wb_vad_tone_detection(VadVars * st, Word16 p_gain);
+Word16 wb_vad(VadVars * st, Word16 in_buf[]);
+
+#endif  //__WB_VAD_H__
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/inc/wb_vad_c.h b/media/libstagefright/codecs/amrwbenc/inc/wb_vad_c.h
index 39ef506..04fd318 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/wb_vad_c.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/wb_vad_c.h
@@ -1,109 +1,109 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/*-------------------------------------------------------------------*

- *                         WB_VAD_C.H				     *

- *-------------------------------------------------------------------*

- * Constants for Voice Activity Detection.			     *

- *-------------------------------------------------------------------*/

-

-#ifndef __WB_VAD_C_H__

-#define __WB_VAD_C_H__

-

-#define FRAME_LEN 256                      /* Length (samples) of the input frame          */

-#define COMPLEN 12                         /* Number of sub-bands used by VAD              */

-

-#define UNIRSHFT 7                         /* = log2(MAX_16/UNITY), UNITY = 256      */

-#define SCALE 128                          /* (UNITY*UNITY)/512 */

-

-#define TONE_THR (Word16)(0.65*MAX_16)     /* Threshold for tone detection   */

-

-/* constants for speech level estimation */

-#define SP_EST_COUNT 80

-#define SP_ACTIVITY_COUNT 25

-#define ALPHA_SP_UP (Word16)((1.0 - 0.85)*MAX_16)

-#define ALPHA_SP_DOWN (Word16)((1.0 - 0.85)*MAX_16)

-

-#define NOM_LEVEL 2050                     /* about -26 dBov Q15 */

-#define SPEECH_LEVEL_INIT NOM_LEVEL        /* initial speech level */

-#define MIN_SPEECH_LEVEL1  (Word16)(NOM_LEVEL * 0.063)  /* NOM_LEVEL -24 dB */

-#define MIN_SPEECH_LEVEL2  (Word16)(NOM_LEVEL * 0.2)    /* NOM_LEVEL -14 dB */

-#define MIN_SPEECH_SNR 4096                /* 0 dB, lowest SNR estimation, Q12 */

-

-/* Time constants for background spectrum update */

-#define ALPHA_UP1   (Word16)((1.0 - 0.95)*MAX_16)       /* Normal update, upwards:   */

-#define ALPHA_DOWN1 (Word16)((1.0 - 0.936)*MAX_16)      /* Normal update, downwards  */

-#define ALPHA_UP2   (Word16)((1.0 - 0.985)*MAX_16)      /* Forced update, upwards    */

-#define ALPHA_DOWN2 (Word16)((1.0 - 0.943)*MAX_16)      /* Forced update, downwards  */

-#define ALPHA3      (Word16)((1.0 - 0.95)*MAX_16)       /* Update downwards          */

-#define ALPHA4      (Word16)((1.0 - 0.9)*MAX_16)        /* For stationary estimation */

-#define ALPHA5      (Word16)((1.0 - 0.5)*MAX_16)        /* For stationary estimation */

-

-/* Constants for VAD threshold */

-#define THR_MIN  (Word16)(1.6*SCALE)       /* Minimum threshold               */

-#define THR_HIGH (Word16)(6*SCALE)         /* Highest threshold               */

-#define THR_LOW (Word16)(1.7*SCALE)        /* Lowest threshold               */

-#define NO_P1 31744                        /* ilog2(1), Noise level for highest threshold */

-#define NO_P2 19786                        /* ilog2(0.1*MAX_16), Noise level for lowest threshold */

-#define NO_SLOPE (Word16)(MAX_16*(float)(THR_LOW-THR_HIGH)/(float)(NO_P2-NO_P1))

-

-#define SP_CH_MIN (Word16)(-0.75*SCALE)

-#define SP_CH_MAX (Word16)(0.75*SCALE)

-#define SP_P1 22527                        /* ilog2(NOM_LEVEL/4) */

-#define SP_P2 17832                        /* ilog2(NOM_LEVEL*4) */

-#define SP_SLOPE (Word16)(MAX_16*(float)(SP_CH_MAX-SP_CH_MIN)/(float)(SP_P2-SP_P1))

-

-/* Constants for hangover length */

-#define HANG_HIGH  12                      /* longest hangover               */

-#define HANG_LOW  2                        /* shortest hangover               */

-#define HANG_P1 THR_LOW                    /* threshold for longest hangover */

-#define HANG_P2 (Word16)(4*SCALE)          /* threshold for shortest hangover */

-#define HANG_SLOPE (Word16)(MAX_16*(float)(HANG_LOW-HANG_HIGH)/(float)(HANG_P2-HANG_P1))

-

-/* Constants for burst length */

-#define BURST_HIGH 8                       /* longest burst length         */

-#define BURST_LOW 3                        /* shortest burst length        */

-#define BURST_P1 THR_HIGH                  /* threshold for longest burst */

-#define BURST_P2 THR_LOW                   /* threshold for shortest burst */

-#define BURST_SLOPE (Word16)(MAX_16*(float)(BURST_LOW-BURST_HIGH)/(float)(BURST_P2-BURST_P1))

-

-/* Parameters for background spectrum recovery function */

-#define STAT_COUNT 20                      /* threshold of stationary detection counter         */

-

-#define STAT_THR_LEVEL 184                 /* Threshold level for stationarity detection        */

-#define STAT_THR 1000                      /* Threshold for stationarity detection              */

-

-/* Limits for background noise estimate */

-#define NOISE_MIN 40                       /* minimum */

-#define NOISE_MAX 20000                    /* maximum */

-#define NOISE_INIT 150                     /* initial */

-

-/* Thresholds for signal power (now calculated on 2 frames) */

-#define VAD_POW_LOW (Word32)30000L         /* If input power is lower than this, VAD is set to 0 */

-#define POW_TONE_THR (Word32)686080L       /* If input power is lower,tone detection flag is ignored */

-

-/* Constants for the filter bank */

-#define COEFF3   13363                     /* coefficient for the 3rd order filter     */

-#define COEFF5_1 21955                     /* 1st coefficient the for 5th order filter */

-#define COEFF5_2 6390                      /* 2nd coefficient the for 5th order filter */

-#define F_5TH_CNT 5                        /* number of 5th order filters */

-#define F_3TH_CNT 6                        /* number of 3th order filters */

-

-#endif   //__WB_VAD_C_H__

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/*-------------------------------------------------------------------*
+ *                         WB_VAD_C.H				     *
+ *-------------------------------------------------------------------*
+ * Constants for Voice Activity Detection.			     *
+ *-------------------------------------------------------------------*/
+
+#ifndef __WB_VAD_C_H__
+#define __WB_VAD_C_H__
+
+#define FRAME_LEN 256                      /* Length (samples) of the input frame          */
+#define COMPLEN 12                         /* Number of sub-bands used by VAD              */
+
+#define UNIRSHFT 7                         /* = log2(MAX_16/UNITY), UNITY = 256      */
+#define SCALE 128                          /* (UNITY*UNITY)/512 */
+
+#define TONE_THR (Word16)(0.65*MAX_16)     /* Threshold for tone detection   */
+
+/* constants for speech level estimation */
+#define SP_EST_COUNT 80
+#define SP_ACTIVITY_COUNT 25
+#define ALPHA_SP_UP (Word16)((1.0 - 0.85)*MAX_16)
+#define ALPHA_SP_DOWN (Word16)((1.0 - 0.85)*MAX_16)
+
+#define NOM_LEVEL 2050                     /* about -26 dBov Q15 */
+#define SPEECH_LEVEL_INIT NOM_LEVEL        /* initial speech level */
+#define MIN_SPEECH_LEVEL1  (Word16)(NOM_LEVEL * 0.063)  /* NOM_LEVEL -24 dB */
+#define MIN_SPEECH_LEVEL2  (Word16)(NOM_LEVEL * 0.2)    /* NOM_LEVEL -14 dB */
+#define MIN_SPEECH_SNR 4096                /* 0 dB, lowest SNR estimation, Q12 */
+
+/* Time constants for background spectrum update */
+#define ALPHA_UP1   (Word16)((1.0 - 0.95)*MAX_16)       /* Normal update, upwards:   */
+#define ALPHA_DOWN1 (Word16)((1.0 - 0.936)*MAX_16)      /* Normal update, downwards  */
+#define ALPHA_UP2   (Word16)((1.0 - 0.985)*MAX_16)      /* Forced update, upwards    */
+#define ALPHA_DOWN2 (Word16)((1.0 - 0.943)*MAX_16)      /* Forced update, downwards  */
+#define ALPHA3      (Word16)((1.0 - 0.95)*MAX_16)       /* Update downwards          */
+#define ALPHA4      (Word16)((1.0 - 0.9)*MAX_16)        /* For stationary estimation */
+#define ALPHA5      (Word16)((1.0 - 0.5)*MAX_16)        /* For stationary estimation */
+
+/* Constants for VAD threshold */
+#define THR_MIN  (Word16)(1.6*SCALE)       /* Minimum threshold               */
+#define THR_HIGH (Word16)(6*SCALE)         /* Highest threshold               */
+#define THR_LOW (Word16)(1.7*SCALE)        /* Lowest threshold               */
+#define NO_P1 31744                        /* ilog2(1), Noise level for highest threshold */
+#define NO_P2 19786                        /* ilog2(0.1*MAX_16), Noise level for lowest threshold */
+#define NO_SLOPE (Word16)(MAX_16*(float)(THR_LOW-THR_HIGH)/(float)(NO_P2-NO_P1))
+
+#define SP_CH_MIN (Word16)(-0.75*SCALE)
+#define SP_CH_MAX (Word16)(0.75*SCALE)
+#define SP_P1 22527                        /* ilog2(NOM_LEVEL/4) */
+#define SP_P2 17832                        /* ilog2(NOM_LEVEL*4) */
+#define SP_SLOPE (Word16)(MAX_16*(float)(SP_CH_MAX-SP_CH_MIN)/(float)(SP_P2-SP_P1))
+
+/* Constants for hangover length */
+#define HANG_HIGH  12                      /* longest hangover               */
+#define HANG_LOW  2                        /* shortest hangover               */
+#define HANG_P1 THR_LOW                    /* threshold for longest hangover */
+#define HANG_P2 (Word16)(4*SCALE)          /* threshold for shortest hangover */
+#define HANG_SLOPE (Word16)(MAX_16*(float)(HANG_LOW-HANG_HIGH)/(float)(HANG_P2-HANG_P1))
+
+/* Constants for burst length */
+#define BURST_HIGH 8                       /* longest burst length         */
+#define BURST_LOW 3                        /* shortest burst length        */
+#define BURST_P1 THR_HIGH                  /* threshold for longest burst */
+#define BURST_P2 THR_LOW                   /* threshold for shortest burst */
+#define BURST_SLOPE (Word16)(MAX_16*(float)(BURST_LOW-BURST_HIGH)/(float)(BURST_P2-BURST_P1))
+
+/* Parameters for background spectrum recovery function */
+#define STAT_COUNT 20                      /* threshold of stationary detection counter         */
+
+#define STAT_THR_LEVEL 184                 /* Threshold level for stationarity detection        */
+#define STAT_THR 1000                      /* Threshold for stationarity detection              */
+
+/* Limits for background noise estimate */
+#define NOISE_MIN 40                       /* minimum */
+#define NOISE_MAX 20000                    /* maximum */
+#define NOISE_INIT 150                     /* initial */
+
+/* Thresholds for signal power (now calculated on 2 frames) */
+#define VAD_POW_LOW (Word32)30000L         /* If input power is lower than this, VAD is set to 0 */
+#define POW_TONE_THR (Word32)686080L       /* If input power is lower,tone detection flag is ignored */
+
+/* Constants for the filter bank */
+#define COEFF3   13363                     /* coefficient for the 3rd order filter     */
+#define COEFF5_1 21955                     /* 1st coefficient the for 5th order filter */
+#define COEFF5_2 6390                      /* 2nd coefficient the for 5th order filter */
+#define F_5TH_CNT 5                        /* number of 5th order filters */
+#define F_3TH_CNT 6                        /* number of 3th order filters */
+
+#endif   //__WB_VAD_C_H__
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Deemph_32_opt.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Deemph_32_opt.s
index 0eb5e9f..282db92 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Deemph_32_opt.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Deemph_32_opt.s
@@ -1,104 +1,104 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-

-@void Deemph_32(

-@     Word16 x_hi[],                        /* (i)     : input signal (bit31..16) */

-@     Word16 x_lo[],                        /* (i)     : input signal (bit15..4)  */

-@     Word16 y[],                           /* (o)     : output signal (x16)      */

-@     Word16 mu,                            /* (i) Q15 : deemphasis factor        */

-@     Word16 L,                             /* (i)     : vector size              */

-@     Word16 * mem                          /* (i/o)   : memory (y[-1])           */

-@     )

-

-@x_hi     RN      R0

-@x_lo     RN      R1

-@y[]      RN      R2

-@*mem     RN      R3

-

-           .section  .text

-           .global   Deemph_32_asm

-	   

-Deemph_32_asm:

-

-           STMFD   	r13!, {r4 - r12, r14} 

-	   MOV          r4, #2                   @i=0

-	   LDRSH        r6, [r0], #2             @load x_hi[0]

-	   LDRSH        r7, [r1], #2             @load x_lo[0]

-	   LDR          r5, =22282               @r5---mu

-	   MOV          r11, #0x8000

-

-           @y[0]

-	   MOV          r10, r6, LSL #16         @L_tmp = x_hi[0]<<16

-	   MOV          r8,  r5, ASR #1          @fac = mu >> 1

-	   LDR          r5,  [r3]

-	   ADD          r12, r10, r7, LSL #4     @L_tmp += x_lo[0] << 4

-	   MOV          r10, r12, LSL #3         @L_tmp <<= 3

-	   MUL          r9, r5, r8

-	   LDRSH        r6, [r0], #2             @load x_hi[1] 

-	   QDADD        r10, r10, r9

-	   LDRSH        r7, [r1], #2             @load x_lo[1]  

-	   MOV          r12, r10, LSL #1         @L_tmp = L_mac(L_tmp, *mem, fac)

-	   QADD         r10, r12, r11

-	   MOV          r14, r10, ASR #16        @y[0] = round(L_tmp)

-

-

-	   MOV          r10, r6, LSL #16

-	   ADD          r12, r10, r7, LSL #4

-           STRH         r14, [r2], #2            @update y[0]

-	   MOV          r10, r12, LSL #3

-	   MUL          r9, r14, r8

-	   QDADD        r10, r10, r9

-	   MOV          r12, r10, LSL #1

-	   QADD         r10, r12, r11

-	   MOV          r14, r10, ASR #16        @y[1] = round(L_tmp)

-

-LOOP:

-           LDRSH        r6, [r0], #2             @load x_hi[]

-	   LDRSH        r7, [r1], #2

-	   STRH         r14, [r2], #2

-	   MOV          r10, r6, LSL #16

-	   ADD          r12, r10, r7, LSL #4

-	   MUL          r9, r14, r8

-	   MOV          r10, r12, LSL #3

-	   QDADD        r10, r10, r9

-           LDRSH        r6, [r0], #2             @load x_hi[]

-	   MOV          r12, r10, LSL #1

-	   QADD         r10, r12, r11

-	   LDRSH        r7, [r1], #2

-	   MOV          r14, r10, ASR #16

-

-	   MOV          r10, r6, LSL #16

-	   ADD          r12, r10, r7, LSL #4

-	   STRH         r14, [r2], #2

-	   MUL          r9, r14, r8

-	   MOV          r10, r12, LSL #3

-	   QDADD        r10, r10, r9

-           ADD          r4, r4, #2

-	   MOV          r12, r10, LSL #1

-	   QADD         r10, r12, r11

-           CMP          r4, #64

-	   MOV          r14, r10, ASR #16

-

-           BLT          LOOP

-           STR          r14, [r3]

-           STRH         r14, [r2]	   

-

-           LDMFD   	r13!, {r4 - r12, r15} 

-

-	   @ENDP

-	   .END

-

-

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+
+@void Deemph_32(
+@     Word16 x_hi[],                        /* (i)     : input signal (bit31..16) */
+@     Word16 x_lo[],                        /* (i)     : input signal (bit15..4)  */
+@     Word16 y[],                           /* (o)     : output signal (x16)      */
+@     Word16 mu,                            /* (i) Q15 : deemphasis factor        */
+@     Word16 L,                             /* (i)     : vector size              */
+@     Word16 * mem                          /* (i/o)   : memory (y[-1])           */
+@     )
+
+@x_hi     RN      R0
+@x_lo     RN      R1
+@y[]      RN      R2
+@*mem     RN      R3
+
+           .section  .text
+           .global   Deemph_32_asm
+
+Deemph_32_asm:
+
+           STMFD   	r13!, {r4 - r12, r14}
+	   MOV          r4, #2                   @i=0
+	   LDRSH        r6, [r0], #2             @load x_hi[0]
+	   LDRSH        r7, [r1], #2             @load x_lo[0]
+	   LDR          r5, =22282               @r5---mu
+	   MOV          r11, #0x8000
+
+           @y[0]
+	   MOV          r10, r6, LSL #16         @L_tmp = x_hi[0]<<16
+	   MOV          r8,  r5, ASR #1          @fac = mu >> 1
+	   LDR          r5,  [r3]
+	   ADD          r12, r10, r7, LSL #4     @L_tmp += x_lo[0] << 4
+	   MOV          r10, r12, LSL #3         @L_tmp <<= 3
+	   MUL          r9, r5, r8
+	   LDRSH        r6, [r0], #2             @load x_hi[1]
+	   QDADD        r10, r10, r9
+	   LDRSH        r7, [r1], #2             @load x_lo[1]
+	   MOV          r12, r10, LSL #1         @L_tmp = L_mac(L_tmp, *mem, fac)
+	   QADD         r10, r12, r11
+	   MOV          r14, r10, ASR #16        @y[0] = round(L_tmp)
+
+
+	   MOV          r10, r6, LSL #16
+	   ADD          r12, r10, r7, LSL #4
+           STRH         r14, [r2], #2            @update y[0]
+	   MOV          r10, r12, LSL #3
+	   MUL          r9, r14, r8
+	   QDADD        r10, r10, r9
+	   MOV          r12, r10, LSL #1
+	   QADD         r10, r12, r11
+	   MOV          r14, r10, ASR #16        @y[1] = round(L_tmp)
+
+LOOP:
+           LDRSH        r6, [r0], #2             @load x_hi[]
+	   LDRSH        r7, [r1], #2
+	   STRH         r14, [r2], #2
+	   MOV          r10, r6, LSL #16
+	   ADD          r12, r10, r7, LSL #4
+	   MUL          r9, r14, r8
+	   MOV          r10, r12, LSL #3
+	   QDADD        r10, r10, r9
+           LDRSH        r6, [r0], #2             @load x_hi[]
+	   MOV          r12, r10, LSL #1
+	   QADD         r10, r12, r11
+	   LDRSH        r7, [r1], #2
+	   MOV          r14, r10, ASR #16
+
+	   MOV          r10, r6, LSL #16
+	   ADD          r12, r10, r7, LSL #4
+	   STRH         r14, [r2], #2
+	   MUL          r9, r14, r8
+	   MOV          r10, r12, LSL #3
+	   QDADD        r10, r10, r9
+           ADD          r4, r4, #2
+	   MOV          r12, r10, LSL #1
+	   QADD         r10, r12, r11
+           CMP          r4, #64
+	   MOV          r14, r10, ASR #16
+
+           BLT          LOOP
+           STR          r14, [r3]
+           STRH         r14, [r2]
+
+           LDMFD   	r13!, {r4 - r12, r15}
+
+	   @ENDP
+	   .END
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Dot_p_opt.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Dot_p_opt.s
index 0383269..4aa317e 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Dot_p_opt.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Dot_p_opt.s
@@ -1,80 +1,80 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-@

-@Word32 Dot_product12(                      /* (o) Q31: normalized result (1 < val <= -1) */

-@       Word16 x[],                           /* (i) 12bits: x vector                       */

-@       Word16 y[],                           /* (i) 12bits: y vector                       */

-@       Word16 lg,                            /* (i)    : vector length                     */

-@       Word16 * exp                          /* (o)    : exponent of result (0..+30)       */

-@)

-@****************************************************************

-@  x[]   ---  r0

-@  y[]   ---  r1

-@  lg    ---  r2

-@  *exp  ---  r3

-

-          .section  .text

- 	  .global   Dot_product12_asm

-

-Dot_product12_asm:

-

-          STMFD   	    r13!, {r4 - r12, r14} 

-          MOV               r4, #0                                 @ L_sum = 0

-          MOV               r5, #0                                 @ i = 0

-

-LOOP:

-          LDR           r6, [r0], #4

-          LDR           r7, [r1], #4

-          LDR           r8, [r0], #4

-          SMLABB        r4, r6, r7, r4

-          LDR           r9, [r1], #4

-	  SMLATT        r4, r6, r7, r4 

-

-	  LDR           r6, [r0], #4

-	  SMLABB        r4, r8, r9, r4

-

-	  LDR           r7, [r1], #4

-	  SMLATT        r4, r8, r9, r4	  

-	  LDR           r8, [r0], #4

-

-	  SMLABB        r4, r6, r7, r4

-	  LDR           r9, [r1], #4

-	  SMLATT        r4, r6, r7, r4

-	  ADD           r5, r5, #8

-	  SMLABB        r4, r8, r9, r4

-	  CMP           r5, r2

-	  SMLATT        r4, r8, r9, r4

-	  BLT           LOOP

-              

-          MOV           r12, r4, LSL #1

-          ADD           r12, r12, #1                         @ L_sum = (L_sum << 1)  + 1

-	  MOV           r4, r12

-

-          CMP           r12, #0

-	  RSBLT         r4, r12, #0

-          CLZ           r10, r4

-          SUB           r10, r10, #1                         @ sft = norm_l(L_sum)

-          MOV           r0, r12, LSL r10                     @ L_sum = L_sum << sft

-          RSB           r11, r10, #30                        @ *exp = 30 - sft

-          STRH          r11, [r3]                     

-

-Dot_product12_end:

-		     

-          LDMFD   	    r13!, {r4 - r12, r15} 

-          @ENDFUNC

-          .END

- 

-

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+@
+@Word32 Dot_product12(                      /* (o) Q31: normalized result (1 < val <= -1) */
+@       Word16 x[],                           /* (i) 12bits: x vector                       */
+@       Word16 y[],                           /* (i) 12bits: y vector                       */
+@       Word16 lg,                            /* (i)    : vector length                     */
+@       Word16 * exp                          /* (o)    : exponent of result (0..+30)       */
+@)
+@****************************************************************
+@  x[]   ---  r0
+@  y[]   ---  r1
+@  lg    ---  r2
+@  *exp  ---  r3
+
+          .section  .text
+ 	  .global   Dot_product12_asm
+
+Dot_product12_asm:
+
+          STMFD   	    r13!, {r4 - r12, r14}
+          MOV               r4, #0                                 @ L_sum = 0
+          MOV               r5, #0                                 @ i = 0
+
+LOOP:
+          LDR           r6, [r0], #4
+          LDR           r7, [r1], #4
+          LDR           r8, [r0], #4
+          SMLABB        r4, r6, r7, r4
+          LDR           r9, [r1], #4
+	  SMLATT        r4, r6, r7, r4
+
+	  LDR           r6, [r0], #4
+	  SMLABB        r4, r8, r9, r4
+
+	  LDR           r7, [r1], #4
+	  SMLATT        r4, r8, r9, r4
+	  LDR           r8, [r0], #4
+
+	  SMLABB        r4, r6, r7, r4
+	  LDR           r9, [r1], #4
+	  SMLATT        r4, r6, r7, r4
+	  ADD           r5, r5, #8
+	  SMLABB        r4, r8, r9, r4
+	  CMP           r5, r2
+	  SMLATT        r4, r8, r9, r4
+	  BLT           LOOP
+
+          MOV           r12, r4, LSL #1
+          ADD           r12, r12, #1                         @ L_sum = (L_sum << 1)  + 1
+	  MOV           r4, r12
+
+          CMP           r12, #0
+	  RSBLT         r4, r12, #0
+          CLZ           r10, r4
+          SUB           r10, r10, #1                         @ sft = norm_l(L_sum)
+          MOV           r0, r12, LSL r10                     @ L_sum = L_sum << sft
+          RSB           r11, r10, #30                        @ *exp = 30 - sft
+          STRH          r11, [r3]
+
+Dot_product12_end:
+
+          LDMFD   	    r13!, {r4 - r12, r15}
+          @ENDFUNC
+          .END
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Filt_6k_7k_opt.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Filt_6k_7k_opt.s
index e6ebd73..856ada8 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Filt_6k_7k_opt.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Filt_6k_7k_opt.s
@@ -1,185 +1,185 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-

-@**********************************************************************/

-@void Filt_6k_7k(

-@     Word16 signal[],                      /* input:  signal                  */

-@     Word16 lg,                            /* input:  length of input         */

-@     Word16 mem[]                          /* in/out: memory (size=30)        */

-@)

-@******************************************************************

-@ r0    ---  signal[]

-@ r1    ---  lg

-@ r2    ---  mem[] 

-

-          .section  .text

-          .global  Filt_6k_7k_asm

-          .extern  voAWB_Copy

-          .extern  fir_6k_7k

-

-Filt_6k_7k_asm:

-

-          STMFD   		r13!, {r4 - r12, r14} 

-          SUB    		r13, r13, #240              @ x[L_SUBFR16k + (L_FIR - 1)]

-          MOV     		r8, r0                      @ copy signal[] address

-          MOV     		r4, r1                      @ copy lg address

-          MOV     		r5, r2                      @ copy mem[] address

-

-          MOV     		r1, r13

-          MOV     		r0, r2

-          MOV     		r2, #30                     @ L_FIR - 1

-          BL      		voAWB_Copy                   @ memcpy(x, mem, (L_FIR - 1)<<1)

-

-          LDR     		r10, Lable1                 @ get fir_7k address     

-

-          MOV           	r14, #0  

-          MOV                   r3, r8                      @ change myMemCopy to Copy, due to Copy will change r3 content

-          ADD     	    	r6, r13, #60                @ get x[L_FIR - 1] address

-          MOV           	r7, r3                      @ get signal[i]

-LOOP1:

-          LDRSH         	r8,  [r7], #2

-          LDRSH         	r9,  [r7], #2

-          MOV           	r8, r8, ASR #2

-          MOV           	r9, r9, ASR #2

-          LDRSH         	r11, [r7], #2

-          LDRSH         	r12, [r7], #2

-          MOV           	r11, r11, ASR #2

-          MOV           	r12, r12, ASR #2

-          STRH          	r8, [r6], #2

-          STRH          	r9, [r6], #2

-          STRH          	r11, [r6], #2

-          STRH          	r12, [r6], #2

-          LDRSH         	r8,  [r7], #2

-          LDRSH         	r9,  [r7], #2

-          MOV           	r8, r8, ASR #2

-          MOV           	r9, r9, ASR #2

-          LDRSH         	r11, [r7], #2

-          LDRSH         	r12, [r7], #2

-          MOV           	r11, r11, ASR #2

-          MOV           	r12, r12, ASR #2

-          STRH          	r8, [r6], #2

-          STRH          	r9, [r6], #2

-          STRH          	r11, [r6], #2

-          STRH          	r12, [r6], #2

-          ADD           	r14, r14, #8

-          CMP           	r14, #80

-          BLT           	LOOP1          

-

-

-          STR     		r5, [sp, #-4]               @ PUSH  r5 to stack

-

-          @ not use registers: r4, r10, r12, r14, r5

-          MOV     		r4, r13 

-          MOV     		r5, #0                      @ i = 0              

-LOOP2:

-          LDR           	r0, [r10]

-

-          LDRSH  	        r1, [r4]                   @ load x[i]

-          LDRSH   	        r2, [r4, #60]              @ load x[i + 30]

-          LDRSH                 r6, [r4, #2]               @ load x[i + 1]

-          LDRSH                 r7, [r4, #58]              @ load x[i + 29]

-          ADD                   r1, r1, r2                 @ x[i] + x[i + 30]

-          ADD                   r6, r6, r7                 @ x[i + 1] + x[i + 29]

-          LDRSH                 r8, [r4, #4]               @ load x[i + 2]

-          LDRSH                 r9, [r4, #56]              @ load x[i + 28]

-

-          SMULBB                r14, r1, r0                @ (x[i] + x[i + 30]) * fir_7k[0]

-          ADD                   r8, r8, r9                 @ x[i + 2] + x[i + 28]

-          SMLABT                r14, r6, r0, r14           @ (x[i + 1] + x[i + 29]) * fir_7k[1]

-

-          LDR                   r0, [r10, #4]

-          LDRSH                 r1, [r4, #6]               @ load x[i+3]

-          LDRSH                 r2, [r4, #54]              @ load x[i+27]

-          LDRSH                 r6, [r4, #8]               @ load x[i+4]

-          LDRSH                 r7, [r4, #52]              @ load x[i+26]

-          ADD                   r1, r1, r2                 @ x[i+3] + x[i+27]

-          ADD                   r6, r6, r7                 @ x[i+4] + x[i+26]

-          SMLABB                r14, r8, r0, r14           @ (x[i + 2] + x[i + 28]) * fir_7k[2]

-          LDRSH                 r8, [r4, #10]              @ load x[i+5]

-          LDRSH                 r9, [r4, #50]              @ load x[i+25]

-          SMLABT                r14, r1, r0, r14           @ (x[i+3] + x[i+27]) * fir_7k[3]

-          ADD                   r8, r8, r9                 @ x[i+5] + x[i+25] 

- 

-          LDR                   r0, [r10, #8]

-          LDRSH                 r1, [r4, #12]              @ x[i+6]

-          LDRSH                 r2, [r4, #48]              @ x[i+24]

-          SMLABB                r14, r6, r0, r14           @ (x[i+4] + x[i+26]) * fir_7k[4]

-          LDRSH                 r6, [r4, #14]              @ x[i+7] 

-          LDRSH                 r7, [r4, #46]              @ x[i+23]

-          SMLABT                r14, r8, r0, r14           @ (x[i+5] + x[i+25]) * fir_7k[5]

-          LDR                   r0, [r10, #12]

-          ADD                   r1, r1, r2                 @ (x[i+6] + x[i+24])

-          ADD                   r6, r6, r7                 @ (x[i+7] + x[i+23])

-          SMLABB                r14, r1, r0, r14           @ (x[i+6] + x[i+24]) * fir_7k[6]

-          LDRSH                 r8, [r4, #16]              @ x[i+8]

-          LDRSH                 r9, [r4, #44]              @ x[i+22] 

-          SMLABT                r14, r6, r0, r14           @ (x[i+7] + x[i+23]) * fir_7k[7]  

-          LDR                   r0, [r10, #16]

-          LDRSH                 r1, [r4, #18]              @ x[i+9]

-          LDRSH                 r2, [r4, #42]              @ x[i+21]

-          LDRSH                 r6, [r4, #20]              @ x[i+10]

-          LDRSH                 r7, [r4, #40]              @ x[i+20]

-          ADD                   r8, r8, r9                 @ (x[i+8] + x[i+22])

-          ADD                   r1, r1, r2                 @ (x[i+9] + x[i+21])

-          ADD                   r6, r6, r7                 @ (x[i+10] + x[i+20])

-          SMLABB                r14, r8, r0, r14           @ (x[i+8] + x[i+22]) * fir_7k[8]

-          LDRSH                 r8, [r4, #22]              @ x[i+11]

-          LDRSH                 r9, [r4, #38]              @ x[i+19]

-          SMLABT                r14, r1, r0, r14           @ (x[i+9] + x[i+21]) * fir_7k[9]

-          LDR                   r0, [r10, #20]

-          LDRSH                 r1, [r4, #24]              @ x[i+12]

-          LDRSH                 r2, [r4, #36]              @ x[i+18]

-          SMLABB                r14, r6, r0, r14           @ (x[i+10] + x[i+20]) * fir_7k[10]

-          LDRSH                 r6, [r4, #26]              @ x[i+13]

-          ADD                   r8, r8, r9                 @ (x[i+11] + x[i+19])  

-          LDRSH                 r7, [r4, #34]              @ x[i+17]

-          SMLABT                r14, r8, r0, r14           @ (x[i+11] + x[i+19]) * fir_7k[11]

-          LDR                   r0, [r10, #24]

-          ADD                   r1, r1, r2                 @ x[i+12] + x[i+18]

-          LDRSH                 r8, [r4, #28]              @ x[i+14]

-          SMLABB                r14, r1, r0, r14           @ (x[i+12] + x[i+18]) * fir_7k[12]

-          ADD                   r6, r6, r7                 @ (x[i+13] + x[i+17])

-          LDRSH                 r9, [r4, #32]              @ x[i+16] 

-          SMLABT                r14, r6, r0, r14           @ (x[i+13] + x[i+17]) * fir_7k[13]

-          LDR                   r0, [r10, #28]         

-          ADD                   r8, r8, r9                 @ (x[i+14] + x[i+16])

-          LDRSH                 r1, [r4, #30]              @ x[i+15]

-          SMLABB                r14, r8, r0, r14           @ (x[i+14] + x[i+16]) * fir_7k[14]

-          SMLABT                r14, r1, r0, r14           @ x[i+15] * fir_7k[15]                              

-

-          ADD     		r5, r5, #1

-          ADD     		r14, r14, #0x4000

-          ADD     		r4, r4, #2                

-          MOV     		r1, r14, ASR #15

-          CMP     		r5, #80

-          STRH    		r1, [r3], #2               @signal[i] = (L_tmp + 0x4000) >> 15

-          BLT     		LOOP2      

-           

-          LDR     		r1, [sp, #-4]               @mem address

-          ADD     		r0, r13, #160               @x + lg

-          MOV     		r2, #30

-          BL      		voAWB_Copy

-                    

-Filt_6k_7k_end:

-          ADD     		r13, r13, #240  

-          LDMFD   		r13!, {r4 - r12, r15} 

- 

-Lable1:

-          .word   		fir_6k_7k

-          @ENDFUNC

-          .END

-

-

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+
+@**********************************************************************/
+@void Filt_6k_7k(
+@     Word16 signal[],                      /* input:  signal                  */
+@     Word16 lg,                            /* input:  length of input         */
+@     Word16 mem[]                          /* in/out: memory (size=30)        */
+@)
+@******************************************************************
+@ r0    ---  signal[]
+@ r1    ---  lg
+@ r2    ---  mem[]
+
+          .section  .text
+          .global  Filt_6k_7k_asm
+          .extern  voAWB_Copy
+          .extern  fir_6k_7k
+
+Filt_6k_7k_asm:
+
+          STMFD   		r13!, {r4 - r12, r14}
+          SUB    		r13, r13, #240              @ x[L_SUBFR16k + (L_FIR - 1)]
+          MOV     		r8, r0                      @ copy signal[] address
+          MOV     		r4, r1                      @ copy lg address
+          MOV     		r5, r2                      @ copy mem[] address
+
+          MOV     		r1, r13
+          MOV     		r0, r2
+          MOV     		r2, #30                     @ L_FIR - 1
+          BL      		voAWB_Copy                   @ memcpy(x, mem, (L_FIR - 1)<<1)
+
+          LDR     		r10, Lable1                 @ get fir_7k address
+
+          MOV           	r14, #0
+          MOV                   r3, r8                      @ change myMemCopy to Copy, due to Copy will change r3 content
+          ADD     	    	r6, r13, #60                @ get x[L_FIR - 1] address
+          MOV           	r7, r3                      @ get signal[i]
+LOOP1:
+          LDRSH         	r8,  [r7], #2
+          LDRSH         	r9,  [r7], #2
+          MOV           	r8, r8, ASR #2
+          MOV           	r9, r9, ASR #2
+          LDRSH         	r11, [r7], #2
+          LDRSH         	r12, [r7], #2
+          MOV           	r11, r11, ASR #2
+          MOV           	r12, r12, ASR #2
+          STRH          	r8, [r6], #2
+          STRH          	r9, [r6], #2
+          STRH          	r11, [r6], #2
+          STRH          	r12, [r6], #2
+          LDRSH         	r8,  [r7], #2
+          LDRSH         	r9,  [r7], #2
+          MOV           	r8, r8, ASR #2
+          MOV           	r9, r9, ASR #2
+          LDRSH         	r11, [r7], #2
+          LDRSH         	r12, [r7], #2
+          MOV           	r11, r11, ASR #2
+          MOV           	r12, r12, ASR #2
+          STRH          	r8, [r6], #2
+          STRH          	r9, [r6], #2
+          STRH          	r11, [r6], #2
+          STRH          	r12, [r6], #2
+          ADD           	r14, r14, #8
+          CMP           	r14, #80
+          BLT           	LOOP1
+
+
+          STR     		r5, [sp, #-4]               @ PUSH  r5 to stack
+
+          @ not use registers: r4, r10, r12, r14, r5
+          MOV     		r4, r13
+          MOV     		r5, #0                      @ i = 0
+LOOP2:
+          LDR           	r0, [r10]
+
+          LDRSH  	        r1, [r4]                   @ load x[i]
+          LDRSH   	        r2, [r4, #60]              @ load x[i + 30]
+          LDRSH                 r6, [r4, #2]               @ load x[i + 1]
+          LDRSH                 r7, [r4, #58]              @ load x[i + 29]
+          ADD                   r1, r1, r2                 @ x[i] + x[i + 30]
+          ADD                   r6, r6, r7                 @ x[i + 1] + x[i + 29]
+          LDRSH                 r8, [r4, #4]               @ load x[i + 2]
+          LDRSH                 r9, [r4, #56]              @ load x[i + 28]
+
+          SMULBB                r14, r1, r0                @ (x[i] + x[i + 30]) * fir_7k[0]
+          ADD                   r8, r8, r9                 @ x[i + 2] + x[i + 28]
+          SMLABT                r14, r6, r0, r14           @ (x[i + 1] + x[i + 29]) * fir_7k[1]
+
+          LDR                   r0, [r10, #4]
+          LDRSH                 r1, [r4, #6]               @ load x[i+3]
+          LDRSH                 r2, [r4, #54]              @ load x[i+27]
+          LDRSH                 r6, [r4, #8]               @ load x[i+4]
+          LDRSH                 r7, [r4, #52]              @ load x[i+26]
+          ADD                   r1, r1, r2                 @ x[i+3] + x[i+27]
+          ADD                   r6, r6, r7                 @ x[i+4] + x[i+26]
+          SMLABB                r14, r8, r0, r14           @ (x[i + 2] + x[i + 28]) * fir_7k[2]
+          LDRSH                 r8, [r4, #10]              @ load x[i+5]
+          LDRSH                 r9, [r4, #50]              @ load x[i+25]
+          SMLABT                r14, r1, r0, r14           @ (x[i+3] + x[i+27]) * fir_7k[3]
+          ADD                   r8, r8, r9                 @ x[i+5] + x[i+25]
+
+          LDR                   r0, [r10, #8]
+          LDRSH                 r1, [r4, #12]              @ x[i+6]
+          LDRSH                 r2, [r4, #48]              @ x[i+24]
+          SMLABB                r14, r6, r0, r14           @ (x[i+4] + x[i+26]) * fir_7k[4]
+          LDRSH                 r6, [r4, #14]              @ x[i+7]
+          LDRSH                 r7, [r4, #46]              @ x[i+23]
+          SMLABT                r14, r8, r0, r14           @ (x[i+5] + x[i+25]) * fir_7k[5]
+          LDR                   r0, [r10, #12]
+          ADD                   r1, r1, r2                 @ (x[i+6] + x[i+24])
+          ADD                   r6, r6, r7                 @ (x[i+7] + x[i+23])
+          SMLABB                r14, r1, r0, r14           @ (x[i+6] + x[i+24]) * fir_7k[6]
+          LDRSH                 r8, [r4, #16]              @ x[i+8]
+          LDRSH                 r9, [r4, #44]              @ x[i+22]
+          SMLABT                r14, r6, r0, r14           @ (x[i+7] + x[i+23]) * fir_7k[7]
+          LDR                   r0, [r10, #16]
+          LDRSH                 r1, [r4, #18]              @ x[i+9]
+          LDRSH                 r2, [r4, #42]              @ x[i+21]
+          LDRSH                 r6, [r4, #20]              @ x[i+10]
+          LDRSH                 r7, [r4, #40]              @ x[i+20]
+          ADD                   r8, r8, r9                 @ (x[i+8] + x[i+22])
+          ADD                   r1, r1, r2                 @ (x[i+9] + x[i+21])
+          ADD                   r6, r6, r7                 @ (x[i+10] + x[i+20])
+          SMLABB                r14, r8, r0, r14           @ (x[i+8] + x[i+22]) * fir_7k[8]
+          LDRSH                 r8, [r4, #22]              @ x[i+11]
+          LDRSH                 r9, [r4, #38]              @ x[i+19]
+          SMLABT                r14, r1, r0, r14           @ (x[i+9] + x[i+21]) * fir_7k[9]
+          LDR                   r0, [r10, #20]
+          LDRSH                 r1, [r4, #24]              @ x[i+12]
+          LDRSH                 r2, [r4, #36]              @ x[i+18]
+          SMLABB                r14, r6, r0, r14           @ (x[i+10] + x[i+20]) * fir_7k[10]
+          LDRSH                 r6, [r4, #26]              @ x[i+13]
+          ADD                   r8, r8, r9                 @ (x[i+11] + x[i+19])
+          LDRSH                 r7, [r4, #34]              @ x[i+17]
+          SMLABT                r14, r8, r0, r14           @ (x[i+11] + x[i+19]) * fir_7k[11]
+          LDR                   r0, [r10, #24]
+          ADD                   r1, r1, r2                 @ x[i+12] + x[i+18]
+          LDRSH                 r8, [r4, #28]              @ x[i+14]
+          SMLABB                r14, r1, r0, r14           @ (x[i+12] + x[i+18]) * fir_7k[12]
+          ADD                   r6, r6, r7                 @ (x[i+13] + x[i+17])
+          LDRSH                 r9, [r4, #32]              @ x[i+16]
+          SMLABT                r14, r6, r0, r14           @ (x[i+13] + x[i+17]) * fir_7k[13]
+          LDR                   r0, [r10, #28]
+          ADD                   r8, r8, r9                 @ (x[i+14] + x[i+16])
+          LDRSH                 r1, [r4, #30]              @ x[i+15]
+          SMLABB                r14, r8, r0, r14           @ (x[i+14] + x[i+16]) * fir_7k[14]
+          SMLABT                r14, r1, r0, r14           @ x[i+15] * fir_7k[15]
+
+          ADD     		r5, r5, #1
+          ADD     		r14, r14, #0x4000
+          ADD     		r4, r4, #2
+          MOV     		r1, r14, ASR #15
+          CMP     		r5, #80
+          STRH    		r1, [r3], #2               @signal[i] = (L_tmp + 0x4000) >> 15
+          BLT     		LOOP2
+
+          LDR     		r1, [sp, #-4]               @mem address
+          ADD     		r0, r13, #160               @x + lg
+          MOV     		r2, #30
+          BL      		voAWB_Copy
+
+Filt_6k_7k_end:
+          ADD     		r13, r13, #240
+          LDMFD   		r13!, {r4 - r12, r15}
+
+Lable1:
+          .word   		fir_6k_7k
+          @ENDFUNC
+          .END
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Norm_Corr_opt.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Norm_Corr_opt.s
index b440a31..49bdc2b 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Norm_Corr_opt.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Norm_Corr_opt.s
@@ -32,8 +32,8 @@
 @ r6 --- corr_norm[]
 
 
-	.section  .text 
-        .global   Norm_corr_asm 
+	.section  .text
+        .global   Norm_corr_asm
         .extern   Convolve_asm
         .extern   Isqrt_n
 @******************************
@@ -47,17 +47,17 @@
 .equ         T_MIN         ,   212
 .equ         T_MAX         ,   216
 .equ         CORR_NORM     ,   220
-                  
+
 Norm_corr_asm:
 
-        STMFD      r13!, {r4 - r12, r14}  
+        STMFD      r13!, {r4 - r12, r14}
         SUB        r13, r13, #voSTACK
-  
+
         ADD        r8, r13, #20                 @get the excf[L_SUBFR]
         LDR        r4, [r13, #T_MIN]            @get t_min
         RSB        r11, r4, #0                  @k = -t_min
-        ADD        r5, r0, r11, LSL #1          @get the &exc[k]   
-        
+        ADD        r5, r0, r11, LSL #1          @get the &exc[k]
+
         @transfer Convolve function
         STMFD       sp!, {r0 - r3}
         MOV         r0, r5
@@ -68,7 +68,7 @@
 
         @ r8 --- excf[]
 
-	MOV         r14, r1                       @copy xn[] address                      
+	MOV         r14, r1                       @copy xn[] address
         MOV         r5, #64
         MOV         r6, #0                       @L_tmp = 0
         MOV         r7, #1
@@ -93,21 +93,21 @@
 	CLZ         r7, r9
 	SUB         r6, r7, #1                   @exp = norm_l(L_tmp)
         RSB         r7, r6, #32                  @exp = 32 - exp
-	MOV         r6, r7, ASR #1         
+	MOV         r6, r7, ASR #1
 	RSB         r7, r6, #0                   @scale = -(exp >> 1)
-	
+
         @loop for every possible period
 	@for(t = t_min@ t <= t_max@ t++)
 	@r7 --- scale r4 --- t_min r8 --- excf[]
 
-LOOPFOR:	
+LOOPFOR:
         MOV         r5, #0                       @L_tmp  = 0
 	MOV         r6, #0                       @L_tmp1 = 0
-	MOV         r9, #64  
+	MOV         r9, #64
 	MOV         r12, r1                      @copy of xn[]
 	ADD         r14, r13, #20                @copy of excf[]
 	MOV         r8, #0x8000
-        	
+
 LOOPi:
 	LDR         r11, [r14], #4               @load excf[i], excf[i+1]
         LDR         r10, [r12], #4               @load xn[i], xn[i+1]
@@ -128,13 +128,13 @@
 	MOV         r10, #1
 	ADD         r5, r10, r5, LSL #1          @L_tmp = (L_tmp << 1) + 1
 	ADD         r6, r10, r6, LSL #1          @L_tmp1 = (L_tmp1 << 1) + 1
- 
-	CLZ         r10, r5        
+
+	CLZ         r10, r5
 	CMP         r5, #0
 	RSBLT       r11, r5, #0
 	CLZLT       r10, r11
 	SUB         r10, r10, #1                 @exp = norm_l(L_tmp)
-     
+
 	MOV         r5, r5, LSL r10              @L_tmp = (L_tmp << exp)
 	RSB         r10, r10, #30                @exp_corr = 30 - exp
 	MOV         r11, r5, ASR #16             @corr = extract_h(L_tmp)
@@ -150,7 +150,7 @@
 	@Isqrt_n(&L_tmp, &exp_norm)
 
 	MOV         r14, r0
-	MOV         r12, r1 
+	MOV         r12, r1
 
         STMFD       sp!, {r0 - r4, r7 - r12, r14}
 	ADD         r1, sp, #4
@@ -168,7 +168,7 @@
 	MOV         r6, r6, ASR #16              @norm = extract_h(L_tmp)
 	MUL         r12, r6, r11
 	ADD         r12, r12, r12                @L_tmp = vo_L_mult(corr, norm)
-  
+
 	ADD         r6, r10, r5
 	ADD         r6, r6, r7                   @exp_corr + exp_norm + scale
 
@@ -187,9 +187,9 @@
 
 	CMP         r4, r6
 	BEQ         Norm_corr_asm_end
- 
+
 	ADD         r4, r4, #1                   @ t_min ++
-        
+
 	RSB         r5, r4, #0                   @ k
 
 	MOV         r6, #63                      @ i = 63
@@ -216,16 +216,16 @@
 	MUL         r14, r11, r8
         LDR         r6, [r13, #T_MAX]            @ get t_max
 	MOV         r8, r14, ASR #15
-	STRH        r8, [r10]                    
+	STRH        r8, [r10]
 
 	CMP         r4, r6
 	BLE         LOOPFOR
 
-Norm_corr_asm_end: 
-        
-        ADD            r13, r13, #voSTACK      
+Norm_corr_asm_end:
+
+        ADD            r13, r13, #voSTACK
         LDMFD          r13!, {r4 - r12, r15}
-    
+
         .END
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Syn_filt_32_opt.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Syn_filt_32_opt.s
index 6416634..3f4930c 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Syn_filt_32_opt.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Syn_filt_32_opt.s
@@ -1,226 +1,226 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-@

-@void Syn_filt_32(

-@     Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients */

-@     Word16 m,                             /* (i)     : order of LP filter             */

-@     Word16 exc[],                         /* (i) Qnew: excitation (exc[i] >> Qnew)    */

-@     Word16 Qnew,                          /* (i)     : exc scaling = 0(min) to 8(max) */

-@     Word16 sig_hi[],                      /* (o) /16 : synthesis high                 */

-@     Word16 sig_lo[],                      /* (o) /16 : synthesis low                  */

-@     Word16 lg                             /* (i)     : size of filtering              */

-@)

-@***************************************************************

-@

-@ a[]      --- r0

-@ m        --- r1

-@ exc[]    --- r2

-@ Qnew     --- r3

-@ sig_hi[] --- r4

-@ sig_lo[] --- r5

-@ lg       --- r6

-

-          .section  .text

-          .global  Syn_filt_32_asm

-

-Syn_filt_32_asm:

-

-          STMFD   	r13!, {r4 - r12, r14} 

-          LDR           r4,  [r13, #40]                  @ get sig_hi[] address

-          LDR           r5,  [r13, #44]                  @ get sig_lo[] address

-

-          LDRSH         r6,  [r0]                        @ load Aq[0]

-          ADD           r7,  r3, #4                      @ 4 + Q_new

-          MOV           r3, r6, ASR r7                   @ a0 = Aq[0] >> (4 + Q_new)

-

-          LDR           r14, =0xffff

-          LDRSH         r6, [r0, #2]                     @ load Aq[1]

-          LDRSH         r7, [r0, #4]                     @ load Aq[2]

-          LDRSH         r8, [r0, #6]                     @ load Aq[3]

-          LDRSH         r9, [r0, #8]                     @ load Aq[4]

-          AND           r6, r6, r14

-          AND           r8, r8, r14

-          ORR           r10, r6, r7, LSL #16             @ Aq[2] -- Aq[1]

-          ORR           r11, r8, r9, LSL #16             @ Aq[4] -- Aq[3]

-          STR           r10, [r13, #-4]                  

-          STR           r11, [r13, #-8]

-

-          LDRSH         r6, [r0, #10]                    @ load Aq[5]

-          LDRSH         r7, [r0, #12]                    @ load Aq[6]

-          LDRSH         r8, [r0, #14]                    @ load Aq[7]

-          LDRSH         r9, [r0, #16]                    @ load Aq[8]

-          AND           r6, r6, r14

-          AND           r8, r8, r14

-          ORR           r10, r6, r7, LSL #16             @ Aq[6] -- Aq[5]

-          ORR           r11, r8, r9, LSL #16             @ Aq[8] -- Aq[7]

-          STR           r10, [r13, #-12]

-          STR           r11, [r13, #-16]

-

-          LDRSH         r6, [r0, #18]                    @ load Aq[9]

-          LDRSH         r7, [r0, #20]                    @ load Aq[10]

-          LDRSH         r8, [r0, #22]                    @ load Aq[11]

-          LDRSH         r9, [r0, #24]                    @ load Aq[12]

-          AND           r6, r6, r14 

-          AND           r8, r8, r14

-          ORR           r10, r6, r7, LSL #16             @ Aq[10] -- Aq[9]

-          ORR           r11, r8, r9, LSL #16             @ Aq[12] -- Aq[11]

-          STR           r10, [r13, #-20]

-          STR           r11, [r13, #-24]  

-

-          LDRSH         r6, [r0, #26]                    @ load Aq[13]

-          LDRSH         r7, [r0, #28]                    @ load Aq[14]

-          LDRSH         r8, [r0, #30]                    @ load Aq[15]

-          LDRSH         r9, [r0, #32]                    @ load Aq[16]

-          AND           r6, r6, r14

-          AND           r8, r8, r14

-          ORR           r10, r6, r7, LSL #16             @ Aq[14] -- Aq[13]

-          ORR           r11, r8, r9, LSL #16             @ Aq[16] -- Aq[15]

-          STR           r10, [r13, #-28]

-          STR           r11, [r13, #-32]

-          

-          MOV           r8, #0                           @ i = 0

-              

-LOOP:            

-          LDRSH         r6, [r5, #-2]                    @ load sig_lo[i-1]

-          LDRSH         r7, [r5, #-4]                    @ load sig_lo[i-2]

-

-          LDR           r11, [r13, #-4]                  @ Aq[2] -- Aq[1]        

-          LDRSH         r9, [r5, #-6]                    @ load sig_lo[i-3]

-          LDRSH         r10, [r5, #-8]                   @ load sig_lo[i-4]

-

-          SMULBB        r12, r6, r11                     @ sig_lo[i-1] * Aq[1]

-

-          LDRSH         r6, [r5, #-10]                   @ load sig_lo[i-5]

-          SMLABT        r12, r7, r11, r12                @ sig_lo[i-2] * Aq[2]

-          LDR           r11, [r13, #-8]                  @ Aq[4] -- Aq[3]

-          LDRSH         r7, [r5, #-12]                   @ load sig_lo[i-6]

-          SMLABB        r12, r9, r11, r12                @ sig_lo[i-3] * Aq[3]

-          LDRSH         r9, [r5, #-14]                   @ load sig_lo[i-7]

-          SMLABT        r12, r10, r11, r12               @ sig_lo[i-4] * Aq[4]

-          LDR           r11, [r13, #-12]                 @ Aq[6] -- Aq[5]

-          LDRSH         r10, [r5, #-16]                  @ load sig_lo[i-8]

-          SMLABB        r12, r6, r11, r12                @ sig_lo[i-5] * Aq[5]

-          LDRSH         r6,  [r5, #-18]                  @ load sig_lo[i-9]

-          SMLABT        r12, r7, r11, r12                @ sig_lo[i-6] * Aq[6]

-          LDR           r11, [r13, #-16]                 @ Aq[8] -- Aq[7]

-          LDRSH         r7,  [r5, #-20]                  @ load sig_lo[i-10]

-          SMLABB        r12, r9, r11, r12                @ sig_lo[i-7] * Aq[7]

-          LDRSH         r9, [r5, #-22]                   @ load sig_lo[i-11]

-          SMLABT        r12, r10, r11, r12               @ sig_lo[i-8] * Aq[8]

-          LDR           r11, [r13, #-20]                 @ Aq[10] -- Aq[9]

-          LDRSH         r10,[r5, #-24]                   @ load sig_lo[i-12]

-          SMLABB        r12, r6, r11, r12                @ sig_lo[i-9] * Aq[9]

-          LDRSH         r6, [r5, #-26]                   @ load sig_lo[i-13]

-          SMLABT        r12, r7, r11, r12                @ sig_lo[i-10] * Aq[10]

-          LDR           r11, [r13, #-24]                 @ Aq[12] -- Aq[11]

-          LDRSH         r7, [r5, #-28]                   @ load sig_lo[i-14]

-          SMLABB        r12, r9, r11, r12                @ sig_lo[i-11] * Aq[11]

-          LDRSH         r9, [r5, #-30]                   @ load sig_lo[i-15]

-          SMLABT        r12, r10, r11, r12               @ sig_lo[i-12] * Aq[12]

-

-          LDR           r11, [r13, #-28]                 @ Aq[14] -- Aq[13]

-          LDRSH         r10, [r5, #-32]                  @ load sig_lo[i-16]

-          SMLABB        r12, r6, r11, r12                @ sig_lo[i-13] * Aq[13]

-          SMLABT        r12, r7, r11, r12                @ sig_lo[i-14] * Aq[14]

- 

-          LDR           r11, [r13, #-32]                 @ Aq[16] -- Aq[15]

-          LDRSH         r6, [r2],#2                      @ load exc[i] 

-          SMLABB        r12, r9, r11, r12                @ sig_lo[i-15] * Aq[15]

-          SMLABT        r12, r10, r11, r12               @ sig_lo[i-16] * Aq[16]

-          MUL           r7, r6, r3                       @ exc[i] * a0 

-          RSB           r14, r12, #0                     @ L_tmp

-          MOV           r14, r14, ASR #11                @ L_tmp >>= 11

-          ADD           r14, r14, r7, LSL #1             @ L_tmp += (exc[i] * a0) << 1

-

-

-          LDRSH         r6, [r4, #-2]                    @ load sig_hi[i-1]

-          LDRSH         r7, [r4, #-4]                    @ load sig_hi[i-2]

-

-          LDR           r11, [r13, #-4]                  @ Aq[2] -- Aq[1]        

-          LDRSH         r9, [r4, #-6]                    @ load sig_hi[i-3]

-          LDRSH         r10, [r4, #-8]                   @ load sig_hi[i-4]

-          SMULBB        r12, r6, r11                     @ sig_hi[i-1] * Aq[1]

-          LDRSH         r6, [r4, #-10]                   @ load sig_hi[i-5]

-	  SMLABT        r12, r7, r11, r12                @ sig_hi[i-2] * Aq[2]

-

-          LDR           r11, [r13, #-8]                  @ Aq[4] -- Aq[3]

-          LDRSH         r7, [r4, #-12]                   @ load sig_hi[i-6]

-

-          SMLABB        r12, r9, r11, r12                @ sig_hi[i-3] * Aq[3]

-	  LDRSH         r9, [r4, #-14]                   @ load sig_hi[i-7]

-

-	  SMLABT        r12, r10, r11, r12               @ sig_hi[i-4] * Aq[4]

-

-          LDR           r11, [r13, #-12]                 @ Aq[6] -- Aq[5]

-          LDRSH         r10, [r4, #-16]                  @ load sig_hi[i-8]

-

-	  SMLABB        r12, r6, r11, r12                @ sig_hi[i-5] * Aq[5]

-

-	  LDRSH         r6,  [r4, #-18]                  @ load sig_hi[i-9]

-	  SMLABT        r12, r7, r11, r12                @ sig_hi[i-6] * Aq[6]

-

-          LDR           r11, [r13, #-16]                 @ Aq[8] -- Aq[7]

-          LDRSH         r7,  [r4, #-20]                  @ load sig_hi[i-10]

-

-	  SMLABB        r12, r9, r11, r12                @ sig_hi[i-7] * Aq[7]

-

-	  LDRSH         r9, [r4, #-22]                   @ load sig_hi[i-11]

-

-	  SMLABT        r12, r10, r11, r12               @ sig_hi[i-8] * Aq[8]

-

-          LDR           r11, [r13, #-20]                 @ Aq[10] -- Aq[9]

-          LDRSH         r10,[r4, #-24]                   @ load sig_hi[i-12]

-

-	  SMLABB        r12, r6, r11, r12                @ sig_hi[i-9] * Aq[9]

-          LDRSH         r6, [r4, #-26]                   @ load sig_hi[i-13]

-          SMLABT        r12, r7, r11, r12                @ sig_hi[i-10] * Aq[10]

-

-          LDR           r11, [r13, #-24]                 @ Aq[12] -- Aq[11]

-          LDRSH         r7, [r4, #-28]                   @ load sig_hi[i-14]

-          SMLABB        r12, r9, r11, r12                @ sig_hi[i-11] * Aq[11]

-          LDRSH         r9, [r4, #-30]                   @ load sig_hi[i-15]

-          SMLABT        r12, r10, r11, r12               @ sig_hi[i-12] * Aq[12]

-

-          LDR           r11, [r13, #-28]                 @ Aq[14] -- Aq[13]

-          LDRSH         r10, [r4, #-32]                  @ load sig_hi[i-16]

-          SMLABB        r12, r6, r11, r12                @ sig_hi[i-13] * Aq[13]

-          SMLABT        r12, r7, r11, r12                @ sig_hi[i-14] * Aq[14]

- 

-          LDR           r11, [r13, #-32]                 @ Aq[16] -- Aq[15]

-          SMLABB        r12, r9, r11, r12                @ sig_hi[i-15] * Aq[15]

-          SMLABT        r12, r10, r11, r12               @ sig_hi[i-16] * Aq[16]       

-          ADD           r6, r12, r12                     @ r12 << 1

-          SUB           r14, r14, r6                     

-          MOV           r14, r14, LSL #3                 @ L_tmp <<=3

-  

-          MOV           r7, r14, ASR #16                 @ L_tmp >> 16

-

-          MOV           r14, r14, ASR #4                 @ L_tmp >>=4

-          STRH          r7, [r4], #2                         @ sig_hi[i] = L_tmp >> 16

-          SUB           r9, r14, r7, LSL #12             @ sig_lo[i] = L_tmp - (sig_hi[i] << 12)

-

-          ADD           r8, r8, #1

-          STRH          r9, [r5], #2   

-          CMP           r8, #64

-          BLT           LOOP                            

-         

-Syn_filt_32_end:

-		     

-          LDMFD   	    r13!, {r4 - r12, r15} 

-          @ENDFUNC

-          .END

- 

-

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+@
+@void Syn_filt_32(
+@     Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients */
+@     Word16 m,                             /* (i)     : order of LP filter             */
+@     Word16 exc[],                         /* (i) Qnew: excitation (exc[i] >> Qnew)    */
+@     Word16 Qnew,                          /* (i)     : exc scaling = 0(min) to 8(max) */
+@     Word16 sig_hi[],                      /* (o) /16 : synthesis high                 */
+@     Word16 sig_lo[],                      /* (o) /16 : synthesis low                  */
+@     Word16 lg                             /* (i)     : size of filtering              */
+@)
+@***************************************************************
+@
+@ a[]      --- r0
+@ m        --- r1
+@ exc[]    --- r2
+@ Qnew     --- r3
+@ sig_hi[] --- r4
+@ sig_lo[] --- r5
+@ lg       --- r6
+
+          .section  .text
+          .global  Syn_filt_32_asm
+
+Syn_filt_32_asm:
+
+          STMFD   	r13!, {r4 - r12, r14}
+          LDR           r4,  [r13, #40]                  @ get sig_hi[] address
+          LDR           r5,  [r13, #44]                  @ get sig_lo[] address
+
+          LDRSH         r6,  [r0]                        @ load Aq[0]
+          ADD           r7,  r3, #4                      @ 4 + Q_new
+          MOV           r3, r6, ASR r7                   @ a0 = Aq[0] >> (4 + Q_new)
+
+          LDR           r14, =0xffff
+          LDRSH         r6, [r0, #2]                     @ load Aq[1]
+          LDRSH         r7, [r0, #4]                     @ load Aq[2]
+          LDRSH         r8, [r0, #6]                     @ load Aq[3]
+          LDRSH         r9, [r0, #8]                     @ load Aq[4]
+          AND           r6, r6, r14
+          AND           r8, r8, r14
+          ORR           r10, r6, r7, LSL #16             @ Aq[2] -- Aq[1]
+          ORR           r11, r8, r9, LSL #16             @ Aq[4] -- Aq[3]
+          STR           r10, [r13, #-4]
+          STR           r11, [r13, #-8]
+
+          LDRSH         r6, [r0, #10]                    @ load Aq[5]
+          LDRSH         r7, [r0, #12]                    @ load Aq[6]
+          LDRSH         r8, [r0, #14]                    @ load Aq[7]
+          LDRSH         r9, [r0, #16]                    @ load Aq[8]
+          AND           r6, r6, r14
+          AND           r8, r8, r14
+          ORR           r10, r6, r7, LSL #16             @ Aq[6] -- Aq[5]
+          ORR           r11, r8, r9, LSL #16             @ Aq[8] -- Aq[7]
+          STR           r10, [r13, #-12]
+          STR           r11, [r13, #-16]
+
+          LDRSH         r6, [r0, #18]                    @ load Aq[9]
+          LDRSH         r7, [r0, #20]                    @ load Aq[10]
+          LDRSH         r8, [r0, #22]                    @ load Aq[11]
+          LDRSH         r9, [r0, #24]                    @ load Aq[12]
+          AND           r6, r6, r14
+          AND           r8, r8, r14
+          ORR           r10, r6, r7, LSL #16             @ Aq[10] -- Aq[9]
+          ORR           r11, r8, r9, LSL #16             @ Aq[12] -- Aq[11]
+          STR           r10, [r13, #-20]
+          STR           r11, [r13, #-24]
+
+          LDRSH         r6, [r0, #26]                    @ load Aq[13]
+          LDRSH         r7, [r0, #28]                    @ load Aq[14]
+          LDRSH         r8, [r0, #30]                    @ load Aq[15]
+          LDRSH         r9, [r0, #32]                    @ load Aq[16]
+          AND           r6, r6, r14
+          AND           r8, r8, r14
+          ORR           r10, r6, r7, LSL #16             @ Aq[14] -- Aq[13]
+          ORR           r11, r8, r9, LSL #16             @ Aq[16] -- Aq[15]
+          STR           r10, [r13, #-28]
+          STR           r11, [r13, #-32]
+
+          MOV           r8, #0                           @ i = 0
+
+LOOP:
+          LDRSH         r6, [r5, #-2]                    @ load sig_lo[i-1]
+          LDRSH         r7, [r5, #-4]                    @ load sig_lo[i-2]
+
+          LDR           r11, [r13, #-4]                  @ Aq[2] -- Aq[1]
+          LDRSH         r9, [r5, #-6]                    @ load sig_lo[i-3]
+          LDRSH         r10, [r5, #-8]                   @ load sig_lo[i-4]
+
+          SMULBB        r12, r6, r11                     @ sig_lo[i-1] * Aq[1]
+
+          LDRSH         r6, [r5, #-10]                   @ load sig_lo[i-5]
+          SMLABT        r12, r7, r11, r12                @ sig_lo[i-2] * Aq[2]
+          LDR           r11, [r13, #-8]                  @ Aq[4] -- Aq[3]
+          LDRSH         r7, [r5, #-12]                   @ load sig_lo[i-6]
+          SMLABB        r12, r9, r11, r12                @ sig_lo[i-3] * Aq[3]
+          LDRSH         r9, [r5, #-14]                   @ load sig_lo[i-7]
+          SMLABT        r12, r10, r11, r12               @ sig_lo[i-4] * Aq[4]
+          LDR           r11, [r13, #-12]                 @ Aq[6] -- Aq[5]
+          LDRSH         r10, [r5, #-16]                  @ load sig_lo[i-8]
+          SMLABB        r12, r6, r11, r12                @ sig_lo[i-5] * Aq[5]
+          LDRSH         r6,  [r5, #-18]                  @ load sig_lo[i-9]
+          SMLABT        r12, r7, r11, r12                @ sig_lo[i-6] * Aq[6]
+          LDR           r11, [r13, #-16]                 @ Aq[8] -- Aq[7]
+          LDRSH         r7,  [r5, #-20]                  @ load sig_lo[i-10]
+          SMLABB        r12, r9, r11, r12                @ sig_lo[i-7] * Aq[7]
+          LDRSH         r9, [r5, #-22]                   @ load sig_lo[i-11]
+          SMLABT        r12, r10, r11, r12               @ sig_lo[i-8] * Aq[8]
+          LDR           r11, [r13, #-20]                 @ Aq[10] -- Aq[9]
+          LDRSH         r10,[r5, #-24]                   @ load sig_lo[i-12]
+          SMLABB        r12, r6, r11, r12                @ sig_lo[i-9] * Aq[9]
+          LDRSH         r6, [r5, #-26]                   @ load sig_lo[i-13]
+          SMLABT        r12, r7, r11, r12                @ sig_lo[i-10] * Aq[10]
+          LDR           r11, [r13, #-24]                 @ Aq[12] -- Aq[11]
+          LDRSH         r7, [r5, #-28]                   @ load sig_lo[i-14]
+          SMLABB        r12, r9, r11, r12                @ sig_lo[i-11] * Aq[11]
+          LDRSH         r9, [r5, #-30]                   @ load sig_lo[i-15]
+          SMLABT        r12, r10, r11, r12               @ sig_lo[i-12] * Aq[12]
+
+          LDR           r11, [r13, #-28]                 @ Aq[14] -- Aq[13]
+          LDRSH         r10, [r5, #-32]                  @ load sig_lo[i-16]
+          SMLABB        r12, r6, r11, r12                @ sig_lo[i-13] * Aq[13]
+          SMLABT        r12, r7, r11, r12                @ sig_lo[i-14] * Aq[14]
+
+          LDR           r11, [r13, #-32]                 @ Aq[16] -- Aq[15]
+          LDRSH         r6, [r2],#2                      @ load exc[i]
+          SMLABB        r12, r9, r11, r12                @ sig_lo[i-15] * Aq[15]
+          SMLABT        r12, r10, r11, r12               @ sig_lo[i-16] * Aq[16]
+          MUL           r7, r6, r3                       @ exc[i] * a0
+          RSB           r14, r12, #0                     @ L_tmp
+          MOV           r14, r14, ASR #11                @ L_tmp >>= 11
+          ADD           r14, r14, r7, LSL #1             @ L_tmp += (exc[i] * a0) << 1
+
+
+          LDRSH         r6, [r4, #-2]                    @ load sig_hi[i-1]
+          LDRSH         r7, [r4, #-4]                    @ load sig_hi[i-2]
+
+          LDR           r11, [r13, #-4]                  @ Aq[2] -- Aq[1]
+          LDRSH         r9, [r4, #-6]                    @ load sig_hi[i-3]
+          LDRSH         r10, [r4, #-8]                   @ load sig_hi[i-4]
+          SMULBB        r12, r6, r11                     @ sig_hi[i-1] * Aq[1]
+          LDRSH         r6, [r4, #-10]                   @ load sig_hi[i-5]
+	  SMLABT        r12, r7, r11, r12                @ sig_hi[i-2] * Aq[2]
+
+          LDR           r11, [r13, #-8]                  @ Aq[4] -- Aq[3]
+          LDRSH         r7, [r4, #-12]                   @ load sig_hi[i-6]
+
+          SMLABB        r12, r9, r11, r12                @ sig_hi[i-3] * Aq[3]
+	  LDRSH         r9, [r4, #-14]                   @ load sig_hi[i-7]
+
+	  SMLABT        r12, r10, r11, r12               @ sig_hi[i-4] * Aq[4]
+
+          LDR           r11, [r13, #-12]                 @ Aq[6] -- Aq[5]
+          LDRSH         r10, [r4, #-16]                  @ load sig_hi[i-8]
+
+	  SMLABB        r12, r6, r11, r12                @ sig_hi[i-5] * Aq[5]
+
+	  LDRSH         r6,  [r4, #-18]                  @ load sig_hi[i-9]
+	  SMLABT        r12, r7, r11, r12                @ sig_hi[i-6] * Aq[6]
+
+          LDR           r11, [r13, #-16]                 @ Aq[8] -- Aq[7]
+          LDRSH         r7,  [r4, #-20]                  @ load sig_hi[i-10]
+
+	  SMLABB        r12, r9, r11, r12                @ sig_hi[i-7] * Aq[7]
+
+	  LDRSH         r9, [r4, #-22]                   @ load sig_hi[i-11]
+
+	  SMLABT        r12, r10, r11, r12               @ sig_hi[i-8] * Aq[8]
+
+          LDR           r11, [r13, #-20]                 @ Aq[10] -- Aq[9]
+          LDRSH         r10,[r4, #-24]                   @ load sig_hi[i-12]
+
+	  SMLABB        r12, r6, r11, r12                @ sig_hi[i-9] * Aq[9]
+          LDRSH         r6, [r4, #-26]                   @ load sig_hi[i-13]
+          SMLABT        r12, r7, r11, r12                @ sig_hi[i-10] * Aq[10]
+
+          LDR           r11, [r13, #-24]                 @ Aq[12] -- Aq[11]
+          LDRSH         r7, [r4, #-28]                   @ load sig_hi[i-14]
+          SMLABB        r12, r9, r11, r12                @ sig_hi[i-11] * Aq[11]
+          LDRSH         r9, [r4, #-30]                   @ load sig_hi[i-15]
+          SMLABT        r12, r10, r11, r12               @ sig_hi[i-12] * Aq[12]
+
+          LDR           r11, [r13, #-28]                 @ Aq[14] -- Aq[13]
+          LDRSH         r10, [r4, #-32]                  @ load sig_hi[i-16]
+          SMLABB        r12, r6, r11, r12                @ sig_hi[i-13] * Aq[13]
+          SMLABT        r12, r7, r11, r12                @ sig_hi[i-14] * Aq[14]
+
+          LDR           r11, [r13, #-32]                 @ Aq[16] -- Aq[15]
+          SMLABB        r12, r9, r11, r12                @ sig_hi[i-15] * Aq[15]
+          SMLABT        r12, r10, r11, r12               @ sig_hi[i-16] * Aq[16]
+          ADD           r6, r12, r12                     @ r12 << 1
+          SUB           r14, r14, r6
+          MOV           r14, r14, LSL #3                 @ L_tmp <<=3
+
+          MOV           r7, r14, ASR #16                 @ L_tmp >> 16
+
+          MOV           r14, r14, ASR #4                 @ L_tmp >>=4
+          STRH          r7, [r4], #2                         @ sig_hi[i] = L_tmp >> 16
+          SUB           r9, r14, r7, LSL #12             @ sig_lo[i] = L_tmp - (sig_hi[i] << 12)
+
+          ADD           r8, r8, #1
+          STRH          r9, [r5], #2
+          CMP           r8, #64
+          BLT           LOOP
+
+Syn_filt_32_end:
+
+          LDMFD   	    r13!, {r4 - r12, r15}
+          @ENDFUNC
+          .END
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/convolve_opt.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/convolve_opt.s
index 0228bda..71bb532 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/convolve_opt.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/convolve_opt.s
@@ -27,24 +27,24 @@
 @  r3 --- L
 
 	.section  .text
-        .global   Convolve_asm 
+        .global   Convolve_asm
 
 Convolve_asm:
 
-        STMFD          r13!, {r4 - r12, r14}  
+        STMFD          r13!, {r4 - r12, r14}
         MOV            r3,  #0                           @ n
 	MOV            r11, #0x8000
-        
-LOOP: 
+
+LOOP:
         ADD            r4, r1, r3, LSL #1                @ tmpH address
         ADD            r5, r3, #1                        @ i = n + 1
         MOV            r6, r0                            @ tmpX = x
         LDRSH          r9,  [r6], #2                     @ *tmpX++
         LDRSH          r10, [r4], #-2                    @ *tmpH--
         SUB            r5, r5, #1
-        MUL            r8,  r9, r10 
+        MUL            r8,  r9, r10
 
-LOOP1:                    
+LOOP1:
         CMP            r5, #0
         BLE            L1
 	LDRSH          r9,  [r6], #2                     @ *tmpX++
@@ -58,12 +58,12 @@
 	LDRSH          r12, [r6], #2                     @ *tmpX++
 	LDRSH          r14, [r4], #-2                    @ *tmpH--
 	MLA            r8, r9, r10, r8
-        SUBS           r5, r5, #4 
+        SUBS           r5, r5, #4
 	MLA            r8, r12, r14, r8
-    
-        B              LOOP1  
 
-L1:                  
+        B              LOOP1
+
+L1:
 
         ADD            r5, r11, r8, LSL #1
         MOV            r5, r5, LSR #16                   @extract_h(s)
@@ -75,14 +75,14 @@
         ADD            r5, r3, #1
         MOV            r6, r0
         LDRSH          r9,  [r6], #2                     @ *tmpX++
-        LDRSH          r10, [r4], #-2                     
+        LDRSH          r10, [r4], #-2
         LDRSH          r12, [r6], #2
         LDRSH          r14, [r4], #-2
 
         MUL            r8, r9, r10
         SUB            r5, r5, #2
         MLA            r8, r12, r14, r8
-        
+
 LOOP2:
         CMP            r5, #0
         BLE            L2
@@ -97,14 +97,14 @@
 	LDRSH          r12, [r6], #2                     @ *tmpX++
 	LDRSH          r14, [r4], #-2                    @ *tmpH--
 	MLA            r8, r9, r10, r8
-        SUBS           r5, r5, #4 
+        SUBS           r5, r5, #4
 	MLA            r8, r12, r14, r8
         B              LOOP2
 
 L2:
         ADD            r8, r11, r8, LSL #1
         MOV            r8, r8, LSR #16                   @extract_h(s)
-        ADD            r3, r3, #1  
+        ADD            r3, r3, #1
         STRH           r8, [r2], #2                      @y[n]
 
         ADD            r4, r1, r3, LSL #1
@@ -117,7 +117,7 @@
         MUL            r8, r9, r10
         LDRSH          r9,  [r6], #2
         LDRSH          r10, [r4], #-2
-        MLA            r8, r12, r14, r8 
+        MLA            r8, r12, r14, r8
         SUB            r5, r5, #3
         MLA            r8, r9, r10, r8
 
@@ -135,9 +135,9 @@
 	LDRSH          r12, [r6], #2                     @ *tmpX++
 	LDRSH          r14, [r4], #-2                    @ *tmpH--
 	MLA            r8, r9, r10, r8
-        SUBS           r5, r5, #4 
-	MLA            r8, r12, r14, r8 
-        B              LOOP3   
+        SUBS           r5, r5, #4
+	MLA            r8, r12, r14, r8
+        B              LOOP3
 
 L3:
         ADD            r8, r11, r8, LSL #1
@@ -150,7 +150,7 @@
         MOV            r6, r0
         MOV            r8, #0
 
-LOOP4:                    
+LOOP4:
         CMP            r5, #0
         BLE            L4
 	LDRSH          r9,  [r6], #2                     @ *tmpX++
@@ -164,22 +164,22 @@
 	LDRSH          r12, [r6], #2                     @ *tmpX++
 	LDRSH          r14, [r4], #-2                    @ *tmpH--
 	MLA            r8, r9, r10, r8
-        SUBS           r5, r5, #4 
-	MLA            r8, r12, r14, r8        
-        B              LOOP4    
-L4:                  
+        SUBS           r5, r5, #4
+	MLA            r8, r12, r14, r8
+        B              LOOP4
+L4:
         ADD            r5, r11, r8, LSL #1
         MOV            r5, r5, LSR #16                   @extract_h(s)
         ADD            r3, r3, #1
         STRH           r5, [r2], #2                      @y[n]
-        
+
         CMP            r3, #64
         BLT            LOOP
-                
-Convolve_asm_end: 
- 
+
+Convolve_asm_end:
+
         LDMFD      r13!, {r4 - r12, r15}
-    
+
         @ENDFUNC
         .END
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/cor_h_vec_opt.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/cor_h_vec_opt.s
index 441b984..2d4c7cc 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/cor_h_vec_opt.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/cor_h_vec_opt.s
@@ -1,151 +1,151 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-@static void cor_h_vec_012(

-@		Word16 h[],                           /* (i) scaled impulse response                 */

-@		Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */

-@		Word16 track,                         /* (i) track to use                            */

-@		Word16 sign[],                        /* (i) sign vector                             */

-@		Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */

-@		Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */

-@		Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */

-@)

-@r0 ---- h[]

-@r1 ---- vec[]

-@r2 ---- track

-@r3 ---- sign[]

-@r4 ---- rrixix[][NB_POS]

-@r5 ---- cor_1[]

-@r6 ---- cor_2[]

-

-

-          .section  .text

-	  .global  cor_h_vec_012_asm

-

-cor_h_vec_012_asm:

-

-         STMFD         r13!, {r4 - r12, r14}

-	 LDR           r4, [r13, #40]                    @load rrixix[][NB_POS]

-	 ADD           r7, r4, r2, LSL #5                @r7 --- p0 = rrixix[track]

-         MOV           r4, #0                            @i=0

-

-	 @r0 --- h[], r1 --- vec[],  r2 --- pos

-	 @r3 --- sign[], r4 --- i, r7 --- p0

-LOOPi:

-         MOV           r5, #0                            @L_sum1 = 0

-         MOV           r6, #0                            @L_sum2 = 0

-         ADD           r9, r1, r2, LSL #1                @p2 = &vec[pos]

-         MOV           r10, r0                           @p1 = h

-         RSB           r11, r2, #62                      @j=62-pos

-

-LOOPj1:

-	 LDRSH         r12, [r10], #2  

-	 LDRSH         r8,  [r9], #2

-	 LDRSH         r14, [r9]

-	 SUBS          r11, r11, #1

-         MLA           r5, r12, r8, r5

-         MLA           r6, r12, r14, r6	 

-	 BGE           LOOPj1

-

-	 LDRSH         r12, [r10], #2                     @*p1++

-	 MOV           r6, r6, LSL #2                     @L_sum2 = (L_sum2 << 2)

-         MLA           r5, r12, r14, r5

-         MOV           r14, #0x8000

-         MOV           r5, r5, LSL #2                     @L_sum1 = (L_sum1 << 2)

-         ADD           r10, r6, r14         

-         ADD           r9, r5, r14

-         MOV           r5, r9, ASR #16

-         MOV           r6, r10, ASR #16

-         ADD           r9, r3, r2, LSL #1                 @address of sign[pos]

-         ADD           r8, r7, #32

-         LDRSH         r10, [r9], #2                 	  @sign[pos]

-	 LDRSH         r11, [r9]                          @sign[pos + 1]

-	 MUL           r12, r5, r10

-	 MUL           r14, r6, r11

-	 MOV           r5, r12, ASR #15

-	 MOV           r6, r14, ASR #15

-	 LDR           r9,  [r13, #44]                   

-	 LDR           r12, [r13, #48]

-         LDRSH         r10, [r7], #2                      @*p0++

-	 LDRSH         r11, [r8]                          @*p3++

-         ADD           r9, r9, r4, LSL #1

-	 ADD           r12, r12, r4, LSL #1

-	 ADD           r5, r5, r10

-	 ADD           r6, r6, r11

-	 STRH          r5, [r9]

-	 STRH          r6, [r12]

-

-         ADD           r2, r2, #4

- 

-         MOV           r5, #0                            @L_sum1 = 0

-	 MOV           r6, #0                            @L_sum2 = 0

-	 ADD           r9, r1, r2, LSL #1                @p2 = &vec[pos]

-	 MOV           r10, r0                           @p1 = h

-	 RSB           r11, r2, #62                      @j=62-pos

-	 ADD           r4, r4, #1                        @i++

-

-LOOPj2:

-	 LDRSH         r12, [r10], #2  

-	 LDRSH         r8,  [r9], #2

-	 LDRSH         r14, [r9]

-	 SUBS          r11, r11, #1

-         MLA           r5, r12, r8, r5

-         MLA           r6, r12, r14, r6	 

-	 BGE           LOOPj2

-

-	 LDRSH         r12, [r10], #2                     @*p1++

-	 MOV           r6, r6, LSL #2                     @L_sum2 = (L_sum2 << 2)

-         MLA           r5, r12, r14, r5

-         MOV           r14, #0x8000

-         MOV           r5, r5, LSL #2                     @L_sum1 = (L_sum1 << 2)

-         ADD           r10, r6, r14        

-         ADD           r9, r5, r14

-

-         MOV           r5, r9, ASR #16

-         MOV           r6, r10, ASR #16

-         ADD           r9, r3, r2, LSL #1                 @address of sign[pos]

-         ADD           r8, r7, #32

-         LDRSH         r10, [r9], #2                 	  @sign[pos]

-	 LDRSH         r11, [r9]                          @sign[pos + 1]

-	 MUL           r12, r5, r10

-	 MUL           r14, r6, r11

-	 MOV           r5, r12, ASR #15

-	 MOV           r6, r14, ASR #15

-	 LDR           r9,  [r13, #44]                   

-	 LDR           r12, [r13, #48]

-         LDRSH         r10, [r7], #2                      @*p0++

-	 LDRSH         r11, [r8]                          @*p3++

-         ADD           r9, r9, r4, LSL #1

-	 ADD           r12, r12, r4, LSL #1

-	 ADD           r5, r5, r10

-	 ADD           r6, r6, r11

-	 STRH          r5, [r9]

-	 STRH          r6, [r12]

-	 ADD           r4, r4, #1                         @i+1

-	 ADD           r2, r2, #4                         @pos += STEP

-	 CMP           r4, #16

-	 

-	 BLT           LOOPi

-         

-the_end:

-         LDMFD         r13!, {r4 - r12, r15}

-      

-         @ENDFUNC

-         .END	 

-        

-	

-	  

-

-

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+@static void cor_h_vec_012(
+@		Word16 h[],                           /* (i) scaled impulse response                 */
+@		Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */
+@		Word16 track,                         /* (i) track to use                            */
+@		Word16 sign[],                        /* (i) sign vector                             */
+@		Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */
+@		Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */
+@		Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */
+@)
+@r0 ---- h[]
+@r1 ---- vec[]
+@r2 ---- track
+@r3 ---- sign[]
+@r4 ---- rrixix[][NB_POS]
+@r5 ---- cor_1[]
+@r6 ---- cor_2[]
+
+
+          .section  .text
+	  .global  cor_h_vec_012_asm
+
+cor_h_vec_012_asm:
+
+         STMFD         r13!, {r4 - r12, r14}
+	 LDR           r4, [r13, #40]                    @load rrixix[][NB_POS]
+	 ADD           r7, r4, r2, LSL #5                @r7 --- p0 = rrixix[track]
+         MOV           r4, #0                            @i=0
+
+	 @r0 --- h[], r1 --- vec[],  r2 --- pos
+	 @r3 --- sign[], r4 --- i, r7 --- p0
+LOOPi:
+         MOV           r5, #0                            @L_sum1 = 0
+         MOV           r6, #0                            @L_sum2 = 0
+         ADD           r9, r1, r2, LSL #1                @p2 = &vec[pos]
+         MOV           r10, r0                           @p1 = h
+         RSB           r11, r2, #62                      @j=62-pos
+
+LOOPj1:
+	 LDRSH         r12, [r10], #2
+	 LDRSH         r8,  [r9], #2
+	 LDRSH         r14, [r9]
+	 SUBS          r11, r11, #1
+         MLA           r5, r12, r8, r5
+         MLA           r6, r12, r14, r6
+	 BGE           LOOPj1
+
+	 LDRSH         r12, [r10], #2                     @*p1++
+	 MOV           r6, r6, LSL #2                     @L_sum2 = (L_sum2 << 2)
+         MLA           r5, r12, r14, r5
+         MOV           r14, #0x8000
+         MOV           r5, r5, LSL #2                     @L_sum1 = (L_sum1 << 2)
+         ADD           r10, r6, r14
+         ADD           r9, r5, r14
+         MOV           r5, r9, ASR #16
+         MOV           r6, r10, ASR #16
+         ADD           r9, r3, r2, LSL #1                 @address of sign[pos]
+         ADD           r8, r7, #32
+         LDRSH         r10, [r9], #2                 	  @sign[pos]
+	 LDRSH         r11, [r9]                          @sign[pos + 1]
+	 MUL           r12, r5, r10
+	 MUL           r14, r6, r11
+	 MOV           r5, r12, ASR #15
+	 MOV           r6, r14, ASR #15
+	 LDR           r9,  [r13, #44]
+	 LDR           r12, [r13, #48]
+         LDRSH         r10, [r7], #2                      @*p0++
+	 LDRSH         r11, [r8]                          @*p3++
+         ADD           r9, r9, r4, LSL #1
+	 ADD           r12, r12, r4, LSL #1
+	 ADD           r5, r5, r10
+	 ADD           r6, r6, r11
+	 STRH          r5, [r9]
+	 STRH          r6, [r12]
+
+         ADD           r2, r2, #4
+
+         MOV           r5, #0                            @L_sum1 = 0
+	 MOV           r6, #0                            @L_sum2 = 0
+	 ADD           r9, r1, r2, LSL #1                @p2 = &vec[pos]
+	 MOV           r10, r0                           @p1 = h
+	 RSB           r11, r2, #62                      @j=62-pos
+	 ADD           r4, r4, #1                        @i++
+
+LOOPj2:
+	 LDRSH         r12, [r10], #2
+	 LDRSH         r8,  [r9], #2
+	 LDRSH         r14, [r9]
+	 SUBS          r11, r11, #1
+         MLA           r5, r12, r8, r5
+         MLA           r6, r12, r14, r6
+	 BGE           LOOPj2
+
+	 LDRSH         r12, [r10], #2                     @*p1++
+	 MOV           r6, r6, LSL #2                     @L_sum2 = (L_sum2 << 2)
+         MLA           r5, r12, r14, r5
+         MOV           r14, #0x8000
+         MOV           r5, r5, LSL #2                     @L_sum1 = (L_sum1 << 2)
+         ADD           r10, r6, r14
+         ADD           r9, r5, r14
+
+         MOV           r5, r9, ASR #16
+         MOV           r6, r10, ASR #16
+         ADD           r9, r3, r2, LSL #1                 @address of sign[pos]
+         ADD           r8, r7, #32
+         LDRSH         r10, [r9], #2                 	  @sign[pos]
+	 LDRSH         r11, [r9]                          @sign[pos + 1]
+	 MUL           r12, r5, r10
+	 MUL           r14, r6, r11
+	 MOV           r5, r12, ASR #15
+	 MOV           r6, r14, ASR #15
+	 LDR           r9,  [r13, #44]
+	 LDR           r12, [r13, #48]
+         LDRSH         r10, [r7], #2                      @*p0++
+	 LDRSH         r11, [r8]                          @*p3++
+         ADD           r9, r9, r4, LSL #1
+	 ADD           r12, r12, r4, LSL #1
+	 ADD           r5, r5, r10
+	 ADD           r6, r6, r11
+	 STRH          r5, [r9]
+	 STRH          r6, [r12]
+	 ADD           r4, r4, #1                         @i+1
+	 ADD           r2, r2, #4                         @pos += STEP
+	 CMP           r4, #16
+
+	 BLT           LOOPi
+
+the_end:
+         LDMFD         r13!, {r4 - r12, r15}
+
+         @ENDFUNC
+         .END
+
+
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/pred_lt4_1_opt.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/pred_lt4_1_opt.s
index d5dd8f0..e0b338d 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/pred_lt4_1_opt.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/pred_lt4_1_opt.s
@@ -1,460 +1,460 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-@

-@void Pred_lt4(

-@		  Word16 exc[],                         /* in/out: excitation buffer */

-@		  Word16 T0,                            /* input : integer pitch lag */

-@		  Word16 frac,                          /* input : fraction of lag   */

-@		  Word16 L_subfr                        /* input : subframe size     */

-@	      )

-

-@******************************

-@       ARM Register

-@******************************

-@ r0  ---  exc[]

-@ r1  ---  T0

-@ r2  ---  frac

-@ r3  ---  L_subfr

-

-         .section  .text

-	 .global   pred_lt4_asm

-	 .extern   inter4_2

-

-pred_lt4_asm:

-

-         STMFD     r13!, {r4 - r12, r14} 

-         RSB       r4, r1, #0                         @-T0

-         RSB       r2, r2, #0                         @frac = -frac

-         ADD       r5, r0, r4, LSL #1                 @x = exc - T0

-         CMP       r2, #0

-         ADDLT     r2, r2, #4                         @frac += UP_SAMP

-         SUBLT     r5, r5, #2                         @x--

-         SUB       r5, r5, #30                        @x -= 15

-         RSB       r4, r2, #3                         @k = 3 - frac

-         LDR       r6, Table

-	 MOV       r8, r4, LSL #6                    

-         @MOV       r7, #0                             @j = 0

-         ADD       r8, r6, r8                         @ptr2 = &(inter4_2[k][0])

-

-	 MOV       r1, r5

-	 MOV       r5, #0x8000

-	 MOV       r14, #21

-@ used register

-         @r0 --- exc[]  r1 --- x  r7 --- j  r8 --- ptr2  r5 --- 0x8000

-THREE_LOOP:

-

-         @MOV       r1, r5                             @ptr1 = x

-	 MOV       r2, r8                             @ptr = ptr2

-         LDR       r3, [r2], #4                       @h[0], h[1]

-	 LDRSH     r4, [r1], #2                       @x[0]

-	 LDRSH     r6, [r1], #2                       @x[1]

-	 LDRSH     r9, [r1], #2                       @x[2]

-

-	 SMULBB    r10, r4, r3                        @x[0] * h[0]                  

-	 SMULBB    r11, r6, r3                        @x[1] * h[0]

-	 SMULBB    r12, r9, r3                        @x[2] * h[0]

-

-         LDRSH     r4, [r1], #2                       @x[3]

-	 SMLABT    r10, r6, r3, r10                   @x[1] * h[1]

-         SMLABT    r11, r9, r3, r11                   @x[2] * h[1]

-	 SMLABT    r12, r4, r3, r12                   @x[3] * h[1]

-

-	 LDR       r3, [r2], #4                       @h[2], h[3]

-	 LDRSH     r6, [r1], #2                       @x[4]

-	 SMLABB    r10, r9, r3, r10                   @x[2] * h[2]

-         SMLABB    r11, r4, r3, r11                   @x[3] * h[2]

-         SMLABB    r12, r6, r3, r12                   @x[4] * h[2]

-

-         LDRSH     r9, [r1], #2                       @x[5]

-         SMLABT    r10, r4, r3, r10                   @x[3] * h[3]

-         SMLABT    r11, r6, r3, r11                   @x[4] * h[3]

-         SMLABT    r12, r9, r3, r12                   @x[5] * h[3]

-

-         LDR       r3, [r2], #4                       @h[4], h[5]

-         LDRSH     r4, [r1], #2                       @x[6]

-         SMLABB    r10, r6, r3, r10                   @x[4] * h[4]

-         SMLABB    r11, r9, r3, r11                   @x[5] * h[4]

-         SMLABB    r12, r4, r3, r12                   @x[6] * h[4]

-

-	 LDRSH     r6, [r1], #2                       @x[7]

-	 SMLABT    r10, r9, r3, r10                   @x[5] * h[5]

-	 SMLABT    r11, r4, r3, r11                   @x[6] * h[5]

-	 SMLABT    r12, r6, r3, r12                   @x[7] * h[5]

-

-         LDR       r3, [r2], #4                       @h[6], h[7]

-	 LDRSH     r9, [r1], #2                       @x[8]

-	 SMLABB    r10, r4, r3, r10                   @x[6] * h[6]

-	 SMLABB    r11, r6, r3, r11                   @x[7] * h[6]

-	 SMLABB    r12, r9, r3, r12                   @x[8] * h[6]

-

-	 LDRSH     r4, [r1], #2                       @x[9]

-	 SMLABT    r10, r6, r3, r10                   @x[7] * h[7]

-	 SMLABT    r11, r9, r3, r11                   @x[8] * h[7]

-	 SMLABT    r12, r4, r3, r12                   @x[9] * h[7]

-

-	 LDR       r3, [r2], #4                       @h[8], h[9]

-	 LDRSH     r6, [r1], #2                       @x[10]

-	 SMLABB    r10, r9, r3, r10                   @x[8] * h[8]

-	 SMLABB    r11, r4, r3, r11                   @x[9] * h[8]

-	 SMLABB    r12, r6, r3, r12                   @x[10] * h[8]

-

-	 LDRSH     r9, [r1], #2                       @x[11]

-	 SMLABT    r10, r4, r3, r10                   @x[9] * h[9]

-	 SMLABT    r11, r6, r3, r11                   @x[10] * h[9]

-	 SMLABT    r12, r9, r3, r12                   @x[11] * h[9]

-

-         LDR       r3, [r2], #4                       @h[10], h[11]

-	 LDRSH     r4, [r1], #2                       @x[12]

-         SMLABB    r10, r6, r3, r10                   @x[10] * h[10]

-	 SMLABB    r11, r9, r3, r11                   @x[11] * h[10]

-	 SMLABB    r12, r4, r3, r12                   @x[12] * h[10]

-

-	 LDRSH     r6, [r1], #2                       @x[13]

-	 SMLABT    r10, r9, r3, r10                   @x[11] * h[11]

-	 SMLABT    r11, r4, r3, r11                   @x[12] * h[11]

-	 SMLABT    r12, r6, r3, r12                   @x[13] * h[11]

-

-	 LDR       r3, [r2], #4                       @h[12], h[13]

-	 LDRSH     r9, [r1], #2                       @x[14]

-	 SMLABB    r10, r4, r3, r10                   @x[12] * h[12]

-	 SMLABB    r11, r6, r3, r11                   @x[13] * h[12]

-	 SMLABB    r12, r9, r3, r12                   @x[14] * h[12]

-

-	 LDRSH     r4, [r1], #2                       @x[15]

-	 SMLABT    r10, r6, r3, r10                   @x[13] * h[13]

-	 SMLABT    r11, r9, r3, r11                   @x[14] * h[13]

-	 SMLABT    r12, r4, r3, r12                   @x[15] * h[13]

-

-	 LDR       r3, [r2], #4                       @h[14], h[15]

-	 LDRSH     r6, [r1], #2                       @x[16]

-	 SMLABB    r10, r9, r3, r10                   @x[14] * h[14]

-	 SMLABB    r11, r4, r3, r11                   @x[15] * h[14]

-	 SMLABB    r12, r6, r3, r12                   @x[16] * h[14]

-

-	 LDRSH     r9, [r1], #2                       @x[17]

-         SMLABT    r10, r4, r3, r10                   @x[15] * h[15]

-	 SMLABT    r11, r6, r3, r11                   @x[16] * h[15]

-	 SMLABT    r12, r9, r3, r12                   @x[17] * h[15]

-

-	 LDR       r3, [r2], #4                       @h[16], h[17]

-	 LDRSH     r4, [r1], #2                       @x[18]

-	 SMLABB    r10, r6, r3, r10                   @x[16] * h[16]

-	 SMLABB    r11, r9, r3, r11                   @x[17] * h[16]

-	 SMLABB    r12, r4, r3, r12                   @x[18] * h[16]

-

-         LDRSH     r6, [r1], #2                       @x[19]

-	 SMLABT    r10, r9, r3, r10                   @x[17] * h[17]

-	 SMLABT    r11, r4, r3, r11                   @x[18] * h[17]

-	 SMLABT    r12, r6, r3, r12                   @x[19] * h[17]

-

-	 LDR       r3, [r2], #4                       @h[18], h[19]

-         LDRSH     r9, [r1], #2                       @x[20]

-	 SMLABB    r10, r4, r3, r10                   @x[18] * h[18]

-	 SMLABB    r11, r6, r3, r11                   @x[19] * h[18]

-	 SMLABB    r12, r9, r3, r12                   @x[20] * h[18]

-

-	 LDRSH     r4, [r1], #2                       @x[21]

-	 SMLABT    r10, r6, r3, r10                   @x[19] * h[19]

-	 SMLABT    r11, r9, r3, r11                   @x[20] * h[19]

-	 SMLABT    r12, r4, r3, r12                   @x[21] * h[19]

-

-	 LDR       r3, [r2], #4                       @h[20], h[21]

-	 LDRSH     r6, [r1], #2                       @x[22]

-	 SMLABB    r10, r9, r3, r10                   @x[20] * h[20]

-	 SMLABB    r11, r4, r3, r11                   @x[21] * h[20]

-	 SMLABB    r12, r6, r3, r12                   @x[22] * h[20]

-

-	 LDRSH     r9, [r1], #2                       @x[23]

-	 SMLABT    r10, r4, r3, r10                   @x[21] * h[21]

-	 SMLABT    r11, r6, r3, r11                   @x[22] * h[21]

-	 SMLABT    r12, r9, r3, r12                   @x[23] * h[21]

-

-	 LDR       r3, [r2], #4                       @h[22], h[23]

-	 LDRSH     r4, [r1], #2                       @x[24]

-	 SMLABB    r10, r6, r3, r10                   @x[22] * h[22]

-	 SMLABB    r11, r9, r3, r11                   @x[23] * h[22]

-	 SMLABB    r12, r4, r3, r12                   @x[24] * h[22]

-

-         LDRSH     r6, [r1], #2                       @x[25]

-	 SMLABT    r10, r9, r3, r10                   @x[23] * h[23]

-	 SMLABT    r11, r4, r3, r11                   @x[24] * h[23]

-	 SMLABT    r12, r6, r3, r12                   @x[25] * h[23]

-

-	 LDR       r3, [r2], #4                       @h[24], h[25]

-         LDRSH     r9, [r1], #2                       @x[26]

-	 SMLABB    r10, r4, r3, r10                   @x[24] * h[24]

-	 SMLABB    r11, r6, r3, r11                   @x[25] * h[24]

-	 SMLABB    r12, r9, r3, r12                   @x[26] * h[24]

-

-	 LDRSH     r4, [r1], #2                       @x[27]

-	 SMLABT    r10, r6, r3, r10                   @x[25] * h[25]

-	 SMLABT    r11, r9, r3, r11                   @x[26] * h[25]

-	 SMLABT    r12, r4, r3, r12                   @x[27] * h[25]

-

-	 LDR       r3, [r2], #4                       @h[26], h[27]

-	 LDRSH     r6, [r1], #2                       @x[28]

-	 SMLABB    r10, r9, r3, r10                   @x[26] * h[26]

-	 SMLABB    r11, r4, r3, r11                   @x[27] * h[26]

-	 SMLABB    r12, r6, r3, r12                   @x[28] * h[26]

-

-	 LDRSH     r9, [r1], #2                       @x[29]

-	 SMLABT    r10, r4, r3, r10                   @x[27] * h[27]

-	 SMLABT    r11, r6, r3, r11                   @x[28] * h[27]

-	 SMLABT    r12, r9, r3, r12                   @x[29] * h[27]

-

-	 LDR       r3, [r2], #4                       @h[28], h[29]

-	 LDRSH     r4, [r1], #2                       @x[30]

-	 SMLABB    r10, r6, r3, r10                   @x[28] * h[28]

-	 SMLABB    r11, r9, r3, r11                   @x[29] * h[28]

-	 SMLABB    r12, r4, r3, r12                   @x[30] * h[28]

-

-         LDRSH     r6, [r1], #2                       @x[31]

-	 SMLABT    r10, r9, r3, r10                   @x[29] * h[29]

-	 SMLABT    r11, r4, r3, r11                   @x[30] * h[29]

-	 SMLABT    r12, r6, r3, r12                   @x[31] * h[29]

-

-	 LDR       r3, [r2], #4                       @h[30], h[31]

-         LDRSH     r9, [r1], #2                       @x[32]

-	 SMLABB    r10, r4, r3, r10                   @x[30] * h[30]

-	 SMLABB    r11, r6, r3, r11                   @x[31] * h[30]

-	 SMLABB    r12, r9, r3, r12                   @x[32] * h[30]

-

-	 LDRSH     r4, [r1], #-60                     @x[33]

-	 SMLABT    r10, r6, r3, r10                   @x[31] * h[31]

-	 SMLABT    r11, r9, r3, r11                   @x[32] * h[31]

-	 SMLABT    r12, r4, r3, r12                   @x[33] * h[31]

-

-	 @SSAT      r10, #32, r10, LSL #2

-	 @SSAT      r11, #32, r11, LSL #2

-	 @SSAT      r12, #32, r12, LSL #2

-

-	 MOV       r10, r10, LSL #1

-	 MOV       r11, r11, LSL #1

-	 MOV       r12, r12, LSL #1

-

-	 QADD      r10, r10, r10

-	 QADD      r11, r11, r11

-	 QADD      r12, r12, r12

-

-	 QADD      r10, r10, r5

-	 QADD      r11, r11, r5

-	 QADD      r12, r12, r5

-

-	 SUBS      r14, r14, #1

-

-	 MOV       r10, r10, ASR #16

-	 MOV       r11, r11, ASR #16

-	 MOV       r12, r12, ASR #16

-

-	 STRH      r10, [r0], #2

-	 STRH      r11, [r0], #2

-	 STRH      r12, [r0], #2

-	 BNE       THREE_LOOP

-

-	 MOV       r2, r8                             @ptr = ptr2

-

-Last2LOOP:

-

-         LDR       r3, [r2], #4                       @h[0], h[1]

-	 LDRSH     r4, [r1], #2                       @x[0]

-	 LDRSH     r6, [r1], #2                       @x[1]

-	 LDRSH     r9, [r1], #2                       @x[2]

-

-	 SMULBB    r10, r4, r3                        @x[0] * h[0]

-	 SMULBB    r11, r6, r3                        @x[1] * h[0]

-

-	 SMLABT    r10, r6, r3, r10                   @x[1] * h[1]

-	 SMLABT    r11, r9, r3, r11                   @x[2] * h[1]

-

-	 LDR       r3, [r2], #4                       @h[2], h[3]

-	 LDRSH     r4, [r1], #2                       @x[3]

-         LDRSH     r6, [r1], #2                       @x[4]

-

-	 SMLABB    r10, r9, r3, r10                   @x[2] * h[2]

-         SMLABB    r11, r4, r3, r11                   @x[3] * h[2]

-      

-	 SMLABT    r10, r4, r3, r10                   @x[3] * h[3]

-	 SMLABT    r11, r6, r3, r11                   @x[4] * h[3]

-

-	 LDR       r3, [r2], #4                       @h[4], h[5]

-	 LDRSH     r9, [r1], #2                       @x[5]

-	 LDRSH     r4, [r1], #2                       @x[6]

-

-	 SMLABB    r10, r6, r3, r10                   @x[4] * h[4]

-	 SMLABB    r11, r9, r3, r11                   @x[5] * h[4]

-

-	 SMLABT    r10, r9, r3, r10                   @x[5] * h[5]

-	 SMLABT    r11, r4, r3, r11                   @x[6] * h[5]

-

-	 LDR       r3, [r2], #4                       @h[6], h[7]

-	 LDRSH     r6, [r1], #2                       @x[7]

-	 LDRSH     r9, [r1], #2                       @x[8]

-

-	 SMLABB    r10, r4, r3, r10                   @x[6] * h[6]

-	 SMLABB    r11, r6, r3, r11                   @x[7] * h[6]

-

-	 SMLABT    r10, r6, r3, r10                   @x[7] * h[7]

-	 SMLABT    r11, r9, r3, r11                   @x[8] * h[7]

-

-	 LDR       r3, [r2], #4                       @h[8], h[9]

-	 LDRSH     r4, [r1], #2                       @x[9]

-	 LDRSH     r6, [r1], #2                       @x[10]

-

-	 SMLABB    r10, r9, r3, r10                   @x[8] * h[8]

-	 SMLABB    r11, r4, r3, r11                   @x[9] * h[8]

-

-	 SMLABT    r10, r4, r3, r10                   @x[9] * h[9]

-	 SMLABT    r11, r6, r3, r11                   @x[10] * h[9]

-

-	 LDR       r3, [r2], #4                       @h[10], h[11]

-	 LDRSH     r9, [r1], #2                       @x[11]

-	 LDRSH     r4, [r1], #2                       @x[12]

-

-	 SMLABB    r10, r6, r3, r10                   @x[10] * h[10]

-	 SMLABB    r11, r9, r3, r11                   @x[11] * h[10]

-

-	 SMLABT    r10, r9, r3, r10                   @x[11] * h[11]

-	 SMLABT    r11, r4, r3, r11                   @x[12] * h[11]

-

-	 LDR       r3, [r2], #4                       @h[12], h[13]

-	 LDRSH     r6, [r1], #2                       @x[13]

-	 LDRSH     r9, [r1], #2                       @x[14]

-

-	 SMLABB    r10, r4, r3, r10                   @x[12] * h[12]

-	 SMLABB    r11, r6, r3, r11                   @x[13] * h[12]

-

-	 SMLABT    r10, r6, r3, r10                   @x[13] * h[13]

-	 SMLABT    r11, r9, r3, r11                   @x[14] * h[13]

-

-	 LDR       r3, [r2], #4                       @h[14], h[15]

-	 LDRSH     r4, [r1], #2                       @x[15]

-	 LDRSH     r6, [r1], #2                       @x[16]

-

-	 SMLABB    r10, r9, r3, r10                   @x[14] * h[14]

-	 SMLABB    r11, r4, r3, r11                   @x[15] * h[14]

-

-	 SMLABT    r10, r4, r3, r10                   @x[15] * h[15]

-	 SMLABT    r11, r6, r3, r11                   @x[16] * h[15]

-

-	 LDR       r3, [r2], #4                       @h[16], h[17]

-	 LDRSH     r9, [r1], #2                       @x[17]

-	 LDRSH     r4, [r1], #2                       @x[18]

-

-	 SMLABB    r10, r6, r3, r10                   @x[16] * h[16]

-	 SMLABB    r11, r9, r3, r11                   @x[17] * h[16]

-

-	 SMLABT    r10, r9, r3, r10                   @x[17] * h[17]

-	 SMLABT    r11, r4, r3, r11                   @x[18] * h[17]

-

-	 LDR       r3, [r2], #4                       @h[18], h[19]

-	 LDRSH     r6, [r1], #2                       @x[19]

-	 LDRSH     r9, [r1], #2                       @x[20]

-

-	 SMLABB    r10, r4, r3, r10                   @x[18] * h[18]

-	 SMLABB    r11, r6, r3, r11                   @x[19] * h[18]

-

-	 SMLABT    r10, r6, r3, r10                   @x[19] * h[19]

-	 SMLABT    r11, r9, r3, r11                   @x[20] * h[19]

-

-	 LDR       r3, [r2], #4                       @h[20], h[21]

-	 LDRSH     r4, [r1], #2                       @x[21]

-	 LDRSH     r6, [r1], #2                       @x[22]

-

-	 SMLABB    r10, r9, r3, r10                   @x[20] * h[20]

-	 SMLABB    r11, r4, r3, r11                   @x[21] * h[20]

-

-	 SMLABT    r10, r4, r3, r10                   @x[21] * h[21]

-	 SMLABT    r11, r6, r3, r11                   @x[22] * h[21]

-

-	 LDR       r3, [r2], #4                       @h[22], h[23]

-	 LDRSH     r9, [r1], #2                       @x[23]

-	 LDRSH     r4, [r1], #2                       @x[24]

-

-	 SMLABB    r10, r6, r3, r10                   @x[22] * h[22]

-	 SMLABB    r11, r9, r3, r11                   @x[23] * h[22]

-

-	 SMLABT    r10, r9, r3, r10                   @x[23] * h[23]

-	 SMLABT    r11, r4, r3, r11                   @x[24] * h[23]

-

-	 LDR       r3, [r2], #4                       @h[24], h[25]

-	 LDRSH     r6, [r1], #2                       @x[25]

-	 LDRSH     r9, [r1], #2                       @x[26]

-

-	 SMLABB    r10, r4, r3, r10                   @x[24] * h[24]

-	 SMLABB    r11, r6, r3, r11                   @x[25] * h[24]

-

-	 SMLABT    r10, r6, r3, r10                   @x[25] * h[25]

-	 SMLABT    r11, r9, r3, r11                   @x[26] * h[25]

-

-	 LDR       r3, [r2], #4                       @h[26], h[27]

-	 LDRSH     r4, [r1], #2                       @x[27]

-	 LDRSH     r6, [r1], #2                       @x[28]

-

-	 SMLABB    r10, r9, r3, r10                   @x[26] * h[26]

-	 SMLABB    r11, r4, r3, r11                   @x[27] * h[26]

-

-	 SMLABT    r10, r4, r3, r10                   @x[27] * h[27]

-	 SMLABT    r11, r6, r3, r11                   @x[28] * h[27]

-

-	 LDR       r3, [r2], #4                       @h[28], h[29]

-	 LDRSH     r9, [r1], #2                       @x[29]

-	 LDRSH     r4, [r1], #2                       @x[30]

-

-	 SMLABB    r10, r6, r3, r10                   @x[28] * h[28]

-	 SMLABB    r11, r9, r3, r11                   @x[29] * h[28]

-

-	 SMLABT    r10, r9, r3, r10                   @x[29] * h[29]

-	 SMLABT    r11, r4, r3, r11                   @x[30] * h[29]

-

-	 LDR       r3, [r2], #4                       @h[30], h[31]

-	 LDRSH     r6, [r1], #2                       @x[31]

-	 LDRSH     r9, [r1], #2                       @x[32]

-

-	 SMLABB    r10, r4, r3, r10                   @x[30] * h[30]

-	 SMLABB    r11, r6, r3, r11                   @x[31] * h[30]

-

-	 SMLABT    r10, r6, r3, r10                   @x[31] * h[31]

-	 SMLABT    r11, r9, r3, r11                   @x[32] * h[31]

-

-	 @SSAT      r10, #32, r10, LSL #2

-	 @SSAT      r11, #32, r11, LSL #2

-	 MOV       r10, r10, LSL #1

-	 MOV       r11, r11, LSL #1

-

-	 QADD      r10, r10, r10

-	 QADD      r11, r11, r11 

-

-	 QADD      r10, r10, r5

-	 QADD      r11, r11, r5

-

-	 MOV       r10, r10, ASR #16

-	 MOV       r11, r11, ASR #16

-

-	 STRH      r10, [r0], #2

-	 STRH      r11, [r0], #2

-

-

-pred_lt4_end:

-         LDMFD     r13!, {r4 - r12, r15}

-

-Table:

-         .word       inter4_2

-	 @ENDFUNC

-	 .END

-

-

-

-

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+@
+@void Pred_lt4(
+@		  Word16 exc[],                         /* in/out: excitation buffer */
+@		  Word16 T0,                            /* input : integer pitch lag */
+@		  Word16 frac,                          /* input : fraction of lag   */
+@		  Word16 L_subfr                        /* input : subframe size     */
+@	      )
+
+@******************************
+@       ARM Register
+@******************************
+@ r0  ---  exc[]
+@ r1  ---  T0
+@ r2  ---  frac
+@ r3  ---  L_subfr
+
+         .section  .text
+	 .global   pred_lt4_asm
+	 .extern   inter4_2
+
+pred_lt4_asm:
+
+         STMFD     r13!, {r4 - r12, r14}
+         RSB       r4, r1, #0                         @-T0
+         RSB       r2, r2, #0                         @frac = -frac
+         ADD       r5, r0, r4, LSL #1                 @x = exc - T0
+         CMP       r2, #0
+         ADDLT     r2, r2, #4                         @frac += UP_SAMP
+         SUBLT     r5, r5, #2                         @x--
+         SUB       r5, r5, #30                        @x -= 15
+         RSB       r4, r2, #3                         @k = 3 - frac
+         LDR       r6, Table
+	 MOV       r8, r4, LSL #6
+         @MOV       r7, #0                             @j = 0
+         ADD       r8, r6, r8                         @ptr2 = &(inter4_2[k][0])
+
+	 MOV       r1, r5
+	 MOV       r5, #0x8000
+	 MOV       r14, #21
+@ used register
+         @r0 --- exc[]  r1 --- x  r7 --- j  r8 --- ptr2  r5 --- 0x8000
+THREE_LOOP:
+
+         @MOV       r1, r5                             @ptr1 = x
+	 MOV       r2, r8                             @ptr = ptr2
+         LDR       r3, [r2], #4                       @h[0], h[1]
+	 LDRSH     r4, [r1], #2                       @x[0]
+	 LDRSH     r6, [r1], #2                       @x[1]
+	 LDRSH     r9, [r1], #2                       @x[2]
+
+	 SMULBB    r10, r4, r3                        @x[0] * h[0]
+	 SMULBB    r11, r6, r3                        @x[1] * h[0]
+	 SMULBB    r12, r9, r3                        @x[2] * h[0]
+
+         LDRSH     r4, [r1], #2                       @x[3]
+	 SMLABT    r10, r6, r3, r10                   @x[1] * h[1]
+         SMLABT    r11, r9, r3, r11                   @x[2] * h[1]
+	 SMLABT    r12, r4, r3, r12                   @x[3] * h[1]
+
+	 LDR       r3, [r2], #4                       @h[2], h[3]
+	 LDRSH     r6, [r1], #2                       @x[4]
+	 SMLABB    r10, r9, r3, r10                   @x[2] * h[2]
+         SMLABB    r11, r4, r3, r11                   @x[3] * h[2]
+         SMLABB    r12, r6, r3, r12                   @x[4] * h[2]
+
+         LDRSH     r9, [r1], #2                       @x[5]
+         SMLABT    r10, r4, r3, r10                   @x[3] * h[3]
+         SMLABT    r11, r6, r3, r11                   @x[4] * h[3]
+         SMLABT    r12, r9, r3, r12                   @x[5] * h[3]
+
+         LDR       r3, [r2], #4                       @h[4], h[5]
+         LDRSH     r4, [r1], #2                       @x[6]
+         SMLABB    r10, r6, r3, r10                   @x[4] * h[4]
+         SMLABB    r11, r9, r3, r11                   @x[5] * h[4]
+         SMLABB    r12, r4, r3, r12                   @x[6] * h[4]
+
+	 LDRSH     r6, [r1], #2                       @x[7]
+	 SMLABT    r10, r9, r3, r10                   @x[5] * h[5]
+	 SMLABT    r11, r4, r3, r11                   @x[6] * h[5]
+	 SMLABT    r12, r6, r3, r12                   @x[7] * h[5]
+
+         LDR       r3, [r2], #4                       @h[6], h[7]
+	 LDRSH     r9, [r1], #2                       @x[8]
+	 SMLABB    r10, r4, r3, r10                   @x[6] * h[6]
+	 SMLABB    r11, r6, r3, r11                   @x[7] * h[6]
+	 SMLABB    r12, r9, r3, r12                   @x[8] * h[6]
+
+	 LDRSH     r4, [r1], #2                       @x[9]
+	 SMLABT    r10, r6, r3, r10                   @x[7] * h[7]
+	 SMLABT    r11, r9, r3, r11                   @x[8] * h[7]
+	 SMLABT    r12, r4, r3, r12                   @x[9] * h[7]
+
+	 LDR       r3, [r2], #4                       @h[8], h[9]
+	 LDRSH     r6, [r1], #2                       @x[10]
+	 SMLABB    r10, r9, r3, r10                   @x[8] * h[8]
+	 SMLABB    r11, r4, r3, r11                   @x[9] * h[8]
+	 SMLABB    r12, r6, r3, r12                   @x[10] * h[8]
+
+	 LDRSH     r9, [r1], #2                       @x[11]
+	 SMLABT    r10, r4, r3, r10                   @x[9] * h[9]
+	 SMLABT    r11, r6, r3, r11                   @x[10] * h[9]
+	 SMLABT    r12, r9, r3, r12                   @x[11] * h[9]
+
+         LDR       r3, [r2], #4                       @h[10], h[11]
+	 LDRSH     r4, [r1], #2                       @x[12]
+         SMLABB    r10, r6, r3, r10                   @x[10] * h[10]
+	 SMLABB    r11, r9, r3, r11                   @x[11] * h[10]
+	 SMLABB    r12, r4, r3, r12                   @x[12] * h[10]
+
+	 LDRSH     r6, [r1], #2                       @x[13]
+	 SMLABT    r10, r9, r3, r10                   @x[11] * h[11]
+	 SMLABT    r11, r4, r3, r11                   @x[12] * h[11]
+	 SMLABT    r12, r6, r3, r12                   @x[13] * h[11]
+
+	 LDR       r3, [r2], #4                       @h[12], h[13]
+	 LDRSH     r9, [r1], #2                       @x[14]
+	 SMLABB    r10, r4, r3, r10                   @x[12] * h[12]
+	 SMLABB    r11, r6, r3, r11                   @x[13] * h[12]
+	 SMLABB    r12, r9, r3, r12                   @x[14] * h[12]
+
+	 LDRSH     r4, [r1], #2                       @x[15]
+	 SMLABT    r10, r6, r3, r10                   @x[13] * h[13]
+	 SMLABT    r11, r9, r3, r11                   @x[14] * h[13]
+	 SMLABT    r12, r4, r3, r12                   @x[15] * h[13]
+
+	 LDR       r3, [r2], #4                       @h[14], h[15]
+	 LDRSH     r6, [r1], #2                       @x[16]
+	 SMLABB    r10, r9, r3, r10                   @x[14] * h[14]
+	 SMLABB    r11, r4, r3, r11                   @x[15] * h[14]
+	 SMLABB    r12, r6, r3, r12                   @x[16] * h[14]
+
+	 LDRSH     r9, [r1], #2                       @x[17]
+         SMLABT    r10, r4, r3, r10                   @x[15] * h[15]
+	 SMLABT    r11, r6, r3, r11                   @x[16] * h[15]
+	 SMLABT    r12, r9, r3, r12                   @x[17] * h[15]
+
+	 LDR       r3, [r2], #4                       @h[16], h[17]
+	 LDRSH     r4, [r1], #2                       @x[18]
+	 SMLABB    r10, r6, r3, r10                   @x[16] * h[16]
+	 SMLABB    r11, r9, r3, r11                   @x[17] * h[16]
+	 SMLABB    r12, r4, r3, r12                   @x[18] * h[16]
+
+         LDRSH     r6, [r1], #2                       @x[19]
+	 SMLABT    r10, r9, r3, r10                   @x[17] * h[17]
+	 SMLABT    r11, r4, r3, r11                   @x[18] * h[17]
+	 SMLABT    r12, r6, r3, r12                   @x[19] * h[17]
+
+	 LDR       r3, [r2], #4                       @h[18], h[19]
+         LDRSH     r9, [r1], #2                       @x[20]
+	 SMLABB    r10, r4, r3, r10                   @x[18] * h[18]
+	 SMLABB    r11, r6, r3, r11                   @x[19] * h[18]
+	 SMLABB    r12, r9, r3, r12                   @x[20] * h[18]
+
+	 LDRSH     r4, [r1], #2                       @x[21]
+	 SMLABT    r10, r6, r3, r10                   @x[19] * h[19]
+	 SMLABT    r11, r9, r3, r11                   @x[20] * h[19]
+	 SMLABT    r12, r4, r3, r12                   @x[21] * h[19]
+
+	 LDR       r3, [r2], #4                       @h[20], h[21]
+	 LDRSH     r6, [r1], #2                       @x[22]
+	 SMLABB    r10, r9, r3, r10                   @x[20] * h[20]
+	 SMLABB    r11, r4, r3, r11                   @x[21] * h[20]
+	 SMLABB    r12, r6, r3, r12                   @x[22] * h[20]
+
+	 LDRSH     r9, [r1], #2                       @x[23]
+	 SMLABT    r10, r4, r3, r10                   @x[21] * h[21]
+	 SMLABT    r11, r6, r3, r11                   @x[22] * h[21]
+	 SMLABT    r12, r9, r3, r12                   @x[23] * h[21]
+
+	 LDR       r3, [r2], #4                       @h[22], h[23]
+	 LDRSH     r4, [r1], #2                       @x[24]
+	 SMLABB    r10, r6, r3, r10                   @x[22] * h[22]
+	 SMLABB    r11, r9, r3, r11                   @x[23] * h[22]
+	 SMLABB    r12, r4, r3, r12                   @x[24] * h[22]
+
+         LDRSH     r6, [r1], #2                       @x[25]
+	 SMLABT    r10, r9, r3, r10                   @x[23] * h[23]
+	 SMLABT    r11, r4, r3, r11                   @x[24] * h[23]
+	 SMLABT    r12, r6, r3, r12                   @x[25] * h[23]
+
+	 LDR       r3, [r2], #4                       @h[24], h[25]
+         LDRSH     r9, [r1], #2                       @x[26]
+	 SMLABB    r10, r4, r3, r10                   @x[24] * h[24]
+	 SMLABB    r11, r6, r3, r11                   @x[25] * h[24]
+	 SMLABB    r12, r9, r3, r12                   @x[26] * h[24]
+
+	 LDRSH     r4, [r1], #2                       @x[27]
+	 SMLABT    r10, r6, r3, r10                   @x[25] * h[25]
+	 SMLABT    r11, r9, r3, r11                   @x[26] * h[25]
+	 SMLABT    r12, r4, r3, r12                   @x[27] * h[25]
+
+	 LDR       r3, [r2], #4                       @h[26], h[27]
+	 LDRSH     r6, [r1], #2                       @x[28]
+	 SMLABB    r10, r9, r3, r10                   @x[26] * h[26]
+	 SMLABB    r11, r4, r3, r11                   @x[27] * h[26]
+	 SMLABB    r12, r6, r3, r12                   @x[28] * h[26]
+
+	 LDRSH     r9, [r1], #2                       @x[29]
+	 SMLABT    r10, r4, r3, r10                   @x[27] * h[27]
+	 SMLABT    r11, r6, r3, r11                   @x[28] * h[27]
+	 SMLABT    r12, r9, r3, r12                   @x[29] * h[27]
+
+	 LDR       r3, [r2], #4                       @h[28], h[29]
+	 LDRSH     r4, [r1], #2                       @x[30]
+	 SMLABB    r10, r6, r3, r10                   @x[28] * h[28]
+	 SMLABB    r11, r9, r3, r11                   @x[29] * h[28]
+	 SMLABB    r12, r4, r3, r12                   @x[30] * h[28]
+
+         LDRSH     r6, [r1], #2                       @x[31]
+	 SMLABT    r10, r9, r3, r10                   @x[29] * h[29]
+	 SMLABT    r11, r4, r3, r11                   @x[30] * h[29]
+	 SMLABT    r12, r6, r3, r12                   @x[31] * h[29]
+
+	 LDR       r3, [r2], #4                       @h[30], h[31]
+         LDRSH     r9, [r1], #2                       @x[32]
+	 SMLABB    r10, r4, r3, r10                   @x[30] * h[30]
+	 SMLABB    r11, r6, r3, r11                   @x[31] * h[30]
+	 SMLABB    r12, r9, r3, r12                   @x[32] * h[30]
+
+	 LDRSH     r4, [r1], #-60                     @x[33]
+	 SMLABT    r10, r6, r3, r10                   @x[31] * h[31]
+	 SMLABT    r11, r9, r3, r11                   @x[32] * h[31]
+	 SMLABT    r12, r4, r3, r12                   @x[33] * h[31]
+
+	 @SSAT      r10, #32, r10, LSL #2
+	 @SSAT      r11, #32, r11, LSL #2
+	 @SSAT      r12, #32, r12, LSL #2
+
+	 MOV       r10, r10, LSL #1
+	 MOV       r11, r11, LSL #1
+	 MOV       r12, r12, LSL #1
+
+	 QADD      r10, r10, r10
+	 QADD      r11, r11, r11
+	 QADD      r12, r12, r12
+
+	 QADD      r10, r10, r5
+	 QADD      r11, r11, r5
+	 QADD      r12, r12, r5
+
+	 SUBS      r14, r14, #1
+
+	 MOV       r10, r10, ASR #16
+	 MOV       r11, r11, ASR #16
+	 MOV       r12, r12, ASR #16
+
+	 STRH      r10, [r0], #2
+	 STRH      r11, [r0], #2
+	 STRH      r12, [r0], #2
+	 BNE       THREE_LOOP
+
+	 MOV       r2, r8                             @ptr = ptr2
+
+Last2LOOP:
+
+         LDR       r3, [r2], #4                       @h[0], h[1]
+	 LDRSH     r4, [r1], #2                       @x[0]
+	 LDRSH     r6, [r1], #2                       @x[1]
+	 LDRSH     r9, [r1], #2                       @x[2]
+
+	 SMULBB    r10, r4, r3                        @x[0] * h[0]
+	 SMULBB    r11, r6, r3                        @x[1] * h[0]
+
+	 SMLABT    r10, r6, r3, r10                   @x[1] * h[1]
+	 SMLABT    r11, r9, r3, r11                   @x[2] * h[1]
+
+	 LDR       r3, [r2], #4                       @h[2], h[3]
+	 LDRSH     r4, [r1], #2                       @x[3]
+         LDRSH     r6, [r1], #2                       @x[4]
+
+	 SMLABB    r10, r9, r3, r10                   @x[2] * h[2]
+         SMLABB    r11, r4, r3, r11                   @x[3] * h[2]
+
+	 SMLABT    r10, r4, r3, r10                   @x[3] * h[3]
+	 SMLABT    r11, r6, r3, r11                   @x[4] * h[3]
+
+	 LDR       r3, [r2], #4                       @h[4], h[5]
+	 LDRSH     r9, [r1], #2                       @x[5]
+	 LDRSH     r4, [r1], #2                       @x[6]
+
+	 SMLABB    r10, r6, r3, r10                   @x[4] * h[4]
+	 SMLABB    r11, r9, r3, r11                   @x[5] * h[4]
+
+	 SMLABT    r10, r9, r3, r10                   @x[5] * h[5]
+	 SMLABT    r11, r4, r3, r11                   @x[6] * h[5]
+
+	 LDR       r3, [r2], #4                       @h[6], h[7]
+	 LDRSH     r6, [r1], #2                       @x[7]
+	 LDRSH     r9, [r1], #2                       @x[8]
+
+	 SMLABB    r10, r4, r3, r10                   @x[6] * h[6]
+	 SMLABB    r11, r6, r3, r11                   @x[7] * h[6]
+
+	 SMLABT    r10, r6, r3, r10                   @x[7] * h[7]
+	 SMLABT    r11, r9, r3, r11                   @x[8] * h[7]
+
+	 LDR       r3, [r2], #4                       @h[8], h[9]
+	 LDRSH     r4, [r1], #2                       @x[9]
+	 LDRSH     r6, [r1], #2                       @x[10]
+
+	 SMLABB    r10, r9, r3, r10                   @x[8] * h[8]
+	 SMLABB    r11, r4, r3, r11                   @x[9] * h[8]
+
+	 SMLABT    r10, r4, r3, r10                   @x[9] * h[9]
+	 SMLABT    r11, r6, r3, r11                   @x[10] * h[9]
+
+	 LDR       r3, [r2], #4                       @h[10], h[11]
+	 LDRSH     r9, [r1], #2                       @x[11]
+	 LDRSH     r4, [r1], #2                       @x[12]
+
+	 SMLABB    r10, r6, r3, r10                   @x[10] * h[10]
+	 SMLABB    r11, r9, r3, r11                   @x[11] * h[10]
+
+	 SMLABT    r10, r9, r3, r10                   @x[11] * h[11]
+	 SMLABT    r11, r4, r3, r11                   @x[12] * h[11]
+
+	 LDR       r3, [r2], #4                       @h[12], h[13]
+	 LDRSH     r6, [r1], #2                       @x[13]
+	 LDRSH     r9, [r1], #2                       @x[14]
+
+	 SMLABB    r10, r4, r3, r10                   @x[12] * h[12]
+	 SMLABB    r11, r6, r3, r11                   @x[13] * h[12]
+
+	 SMLABT    r10, r6, r3, r10                   @x[13] * h[13]
+	 SMLABT    r11, r9, r3, r11                   @x[14] * h[13]
+
+	 LDR       r3, [r2], #4                       @h[14], h[15]
+	 LDRSH     r4, [r1], #2                       @x[15]
+	 LDRSH     r6, [r1], #2                       @x[16]
+
+	 SMLABB    r10, r9, r3, r10                   @x[14] * h[14]
+	 SMLABB    r11, r4, r3, r11                   @x[15] * h[14]
+
+	 SMLABT    r10, r4, r3, r10                   @x[15] * h[15]
+	 SMLABT    r11, r6, r3, r11                   @x[16] * h[15]
+
+	 LDR       r3, [r2], #4                       @h[16], h[17]
+	 LDRSH     r9, [r1], #2                       @x[17]
+	 LDRSH     r4, [r1], #2                       @x[18]
+
+	 SMLABB    r10, r6, r3, r10                   @x[16] * h[16]
+	 SMLABB    r11, r9, r3, r11                   @x[17] * h[16]
+
+	 SMLABT    r10, r9, r3, r10                   @x[17] * h[17]
+	 SMLABT    r11, r4, r3, r11                   @x[18] * h[17]
+
+	 LDR       r3, [r2], #4                       @h[18], h[19]
+	 LDRSH     r6, [r1], #2                       @x[19]
+	 LDRSH     r9, [r1], #2                       @x[20]
+
+	 SMLABB    r10, r4, r3, r10                   @x[18] * h[18]
+	 SMLABB    r11, r6, r3, r11                   @x[19] * h[18]
+
+	 SMLABT    r10, r6, r3, r10                   @x[19] * h[19]
+	 SMLABT    r11, r9, r3, r11                   @x[20] * h[19]
+
+	 LDR       r3, [r2], #4                       @h[20], h[21]
+	 LDRSH     r4, [r1], #2                       @x[21]
+	 LDRSH     r6, [r1], #2                       @x[22]
+
+	 SMLABB    r10, r9, r3, r10                   @x[20] * h[20]
+	 SMLABB    r11, r4, r3, r11                   @x[21] * h[20]
+
+	 SMLABT    r10, r4, r3, r10                   @x[21] * h[21]
+	 SMLABT    r11, r6, r3, r11                   @x[22] * h[21]
+
+	 LDR       r3, [r2], #4                       @h[22], h[23]
+	 LDRSH     r9, [r1], #2                       @x[23]
+	 LDRSH     r4, [r1], #2                       @x[24]
+
+	 SMLABB    r10, r6, r3, r10                   @x[22] * h[22]
+	 SMLABB    r11, r9, r3, r11                   @x[23] * h[22]
+
+	 SMLABT    r10, r9, r3, r10                   @x[23] * h[23]
+	 SMLABT    r11, r4, r3, r11                   @x[24] * h[23]
+
+	 LDR       r3, [r2], #4                       @h[24], h[25]
+	 LDRSH     r6, [r1], #2                       @x[25]
+	 LDRSH     r9, [r1], #2                       @x[26]
+
+	 SMLABB    r10, r4, r3, r10                   @x[24] * h[24]
+	 SMLABB    r11, r6, r3, r11                   @x[25] * h[24]
+
+	 SMLABT    r10, r6, r3, r10                   @x[25] * h[25]
+	 SMLABT    r11, r9, r3, r11                   @x[26] * h[25]
+
+	 LDR       r3, [r2], #4                       @h[26], h[27]
+	 LDRSH     r4, [r1], #2                       @x[27]
+	 LDRSH     r6, [r1], #2                       @x[28]
+
+	 SMLABB    r10, r9, r3, r10                   @x[26] * h[26]
+	 SMLABB    r11, r4, r3, r11                   @x[27] * h[26]
+
+	 SMLABT    r10, r4, r3, r10                   @x[27] * h[27]
+	 SMLABT    r11, r6, r3, r11                   @x[28] * h[27]
+
+	 LDR       r3, [r2], #4                       @h[28], h[29]
+	 LDRSH     r9, [r1], #2                       @x[29]
+	 LDRSH     r4, [r1], #2                       @x[30]
+
+	 SMLABB    r10, r6, r3, r10                   @x[28] * h[28]
+	 SMLABB    r11, r9, r3, r11                   @x[29] * h[28]
+
+	 SMLABT    r10, r9, r3, r10                   @x[29] * h[29]
+	 SMLABT    r11, r4, r3, r11                   @x[30] * h[29]
+
+	 LDR       r3, [r2], #4                       @h[30], h[31]
+	 LDRSH     r6, [r1], #2                       @x[31]
+	 LDRSH     r9, [r1], #2                       @x[32]
+
+	 SMLABB    r10, r4, r3, r10                   @x[30] * h[30]
+	 SMLABB    r11, r6, r3, r11                   @x[31] * h[30]
+
+	 SMLABT    r10, r6, r3, r10                   @x[31] * h[31]
+	 SMLABT    r11, r9, r3, r11                   @x[32] * h[31]
+
+	 @SSAT      r10, #32, r10, LSL #2
+	 @SSAT      r11, #32, r11, LSL #2
+	 MOV       r10, r10, LSL #1
+	 MOV       r11, r11, LSL #1
+
+	 QADD      r10, r10, r10
+	 QADD      r11, r11, r11
+
+	 QADD      r10, r10, r5
+	 QADD      r11, r11, r5
+
+	 MOV       r10, r10, ASR #16
+	 MOV       r11, r11, ASR #16
+
+	 STRH      r10, [r0], #2
+	 STRH      r11, [r0], #2
+
+
+pred_lt4_end:
+         LDMFD     r13!, {r4 - r12, r15}
+
+Table:
+         .word       inter4_2
+	 @ENDFUNC
+	 .END
+
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/residu_asm_opt.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/residu_asm_opt.s
index 060d9c7..5ff0964 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/residu_asm_opt.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/residu_asm_opt.s
@@ -1,228 +1,228 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-@

-@void Residu(

-@	    Word16 a[],                           /* (i) Q12 : prediction coefficients */

-@	    Word16 x[],                           /* (i)     : speech (values x[-m..-1] are needed */

-@	    Word16 y[],                           /* (o) x2  : residual signal       */

-@	    Word16 lg                             /* (i)     : size of filtering     */

-@	   )

-@a[] --- r0

-@x[] --- r1

-@y[] --- r2

-@lg  --- r3

-

-        .section  .text

-	.global   Residu_opt

-

-Residu_opt:

-

-        STMFD   r13!, {r4 - r12, r14}

-

-        LDRH    r5, [r0], #2

-        LDRH    r6, [r0], #2

-        ORR     r5, r6, r5, LSL #16                  @r5 --- a0, a1	

-

-        LDRH    r6, [r0], #2

-	LDRH    r7, [r0], #2

-	ORR     r6, r7, r6, LSL #16                  @r6 --- a2, a3

-	

-        LDRH    r7, [r0], #2

-	LDRH    r8, [r0], #2

-	ORR     r7, r8, r7, LSL #16                  @r7 --- a4, a5

-

-	LDRH    r8, [r0], #2

-	LDRH    r9, [r0], #2

-	ORR     r8, r9, r8, LSL #16                  @r8 --- a6, a7

-

-	LDRH    r9, [r0], #2

-	LDRH    r10, [r0], #2

-	ORR     r9, r10, r9, LSL #16                 @r9 --- a8, a9

-

-	LDRH    r10, [r0], #2

-	LDRH    r11, [r0], #2

-	ORR     r10, r11, r10, LSL #16               @r10 --- a10, a11

-

-        LDRH    r11, [r0], #2

-	LDRH    r12, [r0], #2

-	ORR     r11, r12, r11, LSL #16               @r11 --- a12, a13

-	

-	LDRH    r12, [r0], #2

-	LDRH    r4, [r0], #2

-	ORR     r12, r4, r12, LSL #16                @r12 --- a14, a15

-	

-

-	STMFD   r13!, {r8 - r12}                     @store r8-r12 

-	LDRH    r4, [r0], #2                         @load a16

-        MOV     r14, r3, ASR #2                      @one loop get 4 outputs

-	ADD     r1, r1, #4

-	MOV     r0, r2

-	ORR     r14, r4, r14, LSL #16                @r14 --- loopnum, a16

-

-residu_loop:

-

-        LDR     r10, [r1], #-4                       @r10  --- x[3], x[2]

-	LDR     r2,  [r1], #-4                       @r2   --- x[1], x[0]

-

-	SMULTB  r3, r5, r2                           @i1(0)  --- r3 = x[0] * a0

-        SMULTT  r4, r5, r2                           @i2(0)  --- r4 = x[1] * a0	

-	SMULTB  r11, r5, r10                         @i3(0)  --- r11 = x[2] * a0

-	SMULTT  r12, r5, r10                         @i4(0)  --- r12 = x[3] * a0

-

-        SMLABB  r4, r5, r2, r4                       @i2(1)  --- r4 += x[0] * a1

-        SMLABT  r11, r5, r2, r11                     @i3(1)  --- r11 += x[1] * a0

-        SMLABB  r12, r5, r10, r12                    @i4(1)  --- r12 += x[2] * a1

-

-	SMLATB  r11, r6, r2, r11                     @i3(2)  --- r11 += x[0] * a2

-	SMLATT  r12, r6, r2, r12                     @i4(2)  --- r12 += x[1] * a2

-	SMLABB  r12, r6, r2, r12                     @i4(3)  --- r12 += x[0] * a3                 

-	

-	LDR     r2, [r1], #-4                        @r2 ---- x[-1], x[-2]

-

-	SMLABT  r3, r5, r2, r3                       @i1(1) --- r3 += x[-1] * a1

-	SMLATT  r4, r6, r2, r4                       @i2(2) --- r4 += x[-1] * a2

-	SMLABT  r11, r6, r2, r11                     @i3(3) --- r11 += x[-1] * a3

-	SMLATT  r12, r7, r2, r12                     @i4(4) --- r12 += x[-1] * a4

-        SMLATB  r3, r6, r2, r3                       @i1(2) --- r3 += x[-2] * a2	

-

-	SMLABB	r4, r6, r2, r4				@ i2	(3)

-	SMLATB  r11,r7, r2, r11				@ i3	(4)

-	SMLABB	r12,r7, r2, r12				@ i4	(5)

-	

-	LDR	r2,[r1],#-4

-	SMLABT	r3, r6, r2, r3				@ i1	(3)

-	SMLATT	r4, r7, r2, r4				@ i2	(4)

-	SMLABT	r11,r7, r2, r11				@ i3	(5)

-	SMLATT	r12,r8, r2, r12				@ i4	(6)

-	SMLATB	r3, r7, r2, r3				@ i1	(4)

-	SMLABB	r4, r7, r2, r4				@ i2	(5)

-	SMLATB	r11,r8, r2, r11				@ i3	(6)

-	SMLABB	r12,r8, r2, r12				@ i4	(7)

-		

-	LDR	r2,[r1],#-4

-	SMLABT	r3, r7, r2, r3				@ i1	(5)

-	SMLATT	r4, r8, r2, r4				@ i2	(6)

-	SMLABT	r11,r8, r2, r11				@ i3	(7)

-	SMLATT	r12,r9, r2, r12				@ i4	(8)

-	SMLATB	r3, r8, r2, r3				@ i1	(6)

-	SMLABB	r4, r8, r2, r4				@ i2	(7)

-	SMLATB	r11,r9, r2, r11				@ i3	(8)

-	SMLABB	r12,r9, r2, r12				@ i4	(9)

-	LDR	r10, [r13, #8]				@ [ a10 | a11]

-	

-	LDR	r2,[r1],#-4

-	SMLABT	r3, r8, r2, r3				@ i1	(7)

-	SMLATT	r4, r9, r2, r4				@ i2	(8)

-	SMLABT	r11,r9, r2, r11				@ i3	(9)

-	SMLATT	r12,r10, r2, r12			@ i4	(10)

-	SMLATB	r3, r9, r2, r3				@ i1	(8)

-	SMLABB	r4, r9, r2, r4				@ i2	(9)

-	SMLATB	r11,r10, r2, r11			@ i3	(10)

-	SMLABB	r12,r10, r2, r12			@ i4	(11)

-	LDR	r8, [r13, #12]				@ [ a12 | a13 ]

-		

-	LDR	r2,[r1],#-4

-	SMLABT	r3, r9, r2, r3				@ i1	(9)

-	SMLATT	r4, r10, r2, r4				@ i2	(10)

-	SMLABT	r11,r10, r2, r11			@ i3	(11)

-	SMLATT	r12,r8, r2, r12				@ i4	(12)

-	SMLATB	r3, r10, r2, r3				@ i1	(10)

-	SMLABB	r4, r10, r2, r4				@ i2	(11)

-	SMLATB	r11,r8, r2, r11				@ i3	(12)

-	SMLABB	r12,r8, r2, r12				@ i4	(13)

-	LDR	r9, [r13, #16]				@ [ a14 | a15 ]

-	

-	LDR	r2,[r1],#-4

-	SMLABT	r3, r10, r2, r3				@ i1	(11)

-	SMLATT	r4, r8, r2, r4				@ i2	(12)

-	SMLABT	r11,r8, r2, r11				@ i3	(13)

-	SMLATT	r12,r9, r2, r12				@ i4	(14)

-	SMLATB	r3, r8, r2, r3				@ i1	(12)

-	SMLABB	r4, r8, r2, r4				@ i2	(13)

-	SMLATB	r11,r9, r2, r11				@ i3	(14)

-	SMLABB	r12,r9, r2, r12				@ i4	(15)

-	

-

-	LDR	r2,[r1],#-4

-	SMLABT	r3, r8, r2, r3				@ i1	(13)

-	SMLATT	r4, r9, r2, r4				@ i2	(14)

-	SMLABT	r11,r9, r2, r11				@ i3	(15)

-	SMLABT	r12,r14, r2, r12			@ i4	(16)

-	SMLATB	r3, r9, r2, r3				@ i1	(14)

-	SMLABB	r4, r9, r2, r4				@ i2	(15)

-	SMLABB	r11,r14, r2, r11			@ i3	(16)

-	LDR		r8, [r13]					@ [ a6 | a7 ]

-			

-        LDR     r2,[r1],#44         		@ Change

-	SMLABT	r3, r9, r2, r3

-	SMLABB	r3, r14, r2, r3

-	SMLABT	r4, r14, r2, r4

-	LDR		r9, [r13, #4]				@ [ a8 | a9 ]

-	

-

-	QADD	r3,r3,r3					

-	QADD	r4,r4,r4					

-	QADD	r11,r11,r11					

-	QADD	r12,r12,r12					

-		

-	QADD	r3,r3,r3					

-	QADD	r4,r4,r4					

-	QADD	r11,r11,r11					

-	QADD	r12,r12,r12					

-	

-	QADD	r3,r3,r3					

-	QADD	r4,r4,r4					

-	QADD	r11,r11,r11					

-	QADD	r12,r12,r12					

-	

-	QADD	r3,r3,r3					

-	QADD	r4,r4,r4					

-	QADD	r11,r11,r11					

-	QADD	r12,r12,r12					

-	

-	MOV	r2,#32768	

-	

-	QDADD	r3,r2,r3					

-	QDADD	r4,r2,r4					

-	QDADD	r11,r2,r11					

-	QDADD	r12,r2,r12					

-		

-	

-	MOV	r3,r3,asr #16

-	MOV	r4,r4,asr #16

-	MOV	r11,r11,asr #16

-	MOV	r12,r12,asr #16

-	

-	STRH	r3,[r0],#2

-	STRH	r4,[r0],#2

-	STRH	r11,[r0],#2

-	STRH	r12,[r0],#2

-	

-	MOV	r2,r14,asr #16

-	SUB	r14, r14, #0x10000

-	SUBS	r2,r2,#1

-	BNE	residu_loop	

-end:

-	LDMFD	r13!, {r8 -r12}	

-	LDMFD	r13!, {r4 -r12,pc}

-

-        @ENDFUNC

-        .END	 

-        

-	

-	  

-

-

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+@
+@void Residu(
+@	    Word16 a[],                           /* (i) Q12 : prediction coefficients */
+@	    Word16 x[],                           /* (i)     : speech (values x[-m..-1] are needed */
+@	    Word16 y[],                           /* (o) x2  : residual signal       */
+@	    Word16 lg                             /* (i)     : size of filtering     */
+@	   )
+@a[] --- r0
+@x[] --- r1
+@y[] --- r2
+@lg  --- r3
+
+        .section  .text
+	.global   Residu_opt
+
+Residu_opt:
+
+        STMFD   r13!, {r4 - r12, r14}
+
+        LDRH    r5, [r0], #2
+        LDRH    r6, [r0], #2
+        ORR     r5, r6, r5, LSL #16                  @r5 --- a0, a1
+
+        LDRH    r6, [r0], #2
+	LDRH    r7, [r0], #2
+	ORR     r6, r7, r6, LSL #16                  @r6 --- a2, a3
+
+        LDRH    r7, [r0], #2
+	LDRH    r8, [r0], #2
+	ORR     r7, r8, r7, LSL #16                  @r7 --- a4, a5
+
+	LDRH    r8, [r0], #2
+	LDRH    r9, [r0], #2
+	ORR     r8, r9, r8, LSL #16                  @r8 --- a6, a7
+
+	LDRH    r9, [r0], #2
+	LDRH    r10, [r0], #2
+	ORR     r9, r10, r9, LSL #16                 @r9 --- a8, a9
+
+	LDRH    r10, [r0], #2
+	LDRH    r11, [r0], #2
+	ORR     r10, r11, r10, LSL #16               @r10 --- a10, a11
+
+        LDRH    r11, [r0], #2
+	LDRH    r12, [r0], #2
+	ORR     r11, r12, r11, LSL #16               @r11 --- a12, a13
+
+	LDRH    r12, [r0], #2
+	LDRH    r4, [r0], #2
+	ORR     r12, r4, r12, LSL #16                @r12 --- a14, a15
+
+
+	STMFD   r13!, {r8 - r12}                     @store r8-r12
+	LDRH    r4, [r0], #2                         @load a16
+        MOV     r14, r3, ASR #2                      @one loop get 4 outputs
+	ADD     r1, r1, #4
+	MOV     r0, r2
+	ORR     r14, r4, r14, LSL #16                @r14 --- loopnum, a16
+
+residu_loop:
+
+        LDR     r10, [r1], #-4                       @r10  --- x[3], x[2]
+	LDR     r2,  [r1], #-4                       @r2   --- x[1], x[0]
+
+	SMULTB  r3, r5, r2                           @i1(0)  --- r3 = x[0] * a0
+        SMULTT  r4, r5, r2                           @i2(0)  --- r4 = x[1] * a0
+	SMULTB  r11, r5, r10                         @i3(0)  --- r11 = x[2] * a0
+	SMULTT  r12, r5, r10                         @i4(0)  --- r12 = x[3] * a0
+
+        SMLABB  r4, r5, r2, r4                       @i2(1)  --- r4 += x[0] * a1
+        SMLABT  r11, r5, r2, r11                     @i3(1)  --- r11 += x[1] * a0
+        SMLABB  r12, r5, r10, r12                    @i4(1)  --- r12 += x[2] * a1
+
+	SMLATB  r11, r6, r2, r11                     @i3(2)  --- r11 += x[0] * a2
+	SMLATT  r12, r6, r2, r12                     @i4(2)  --- r12 += x[1] * a2
+	SMLABB  r12, r6, r2, r12                     @i4(3)  --- r12 += x[0] * a3
+
+	LDR     r2, [r1], #-4                        @r2 ---- x[-1], x[-2]
+
+	SMLABT  r3, r5, r2, r3                       @i1(1) --- r3 += x[-1] * a1
+	SMLATT  r4, r6, r2, r4                       @i2(2) --- r4 += x[-1] * a2
+	SMLABT  r11, r6, r2, r11                     @i3(3) --- r11 += x[-1] * a3
+	SMLATT  r12, r7, r2, r12                     @i4(4) --- r12 += x[-1] * a4
+        SMLATB  r3, r6, r2, r3                       @i1(2) --- r3 += x[-2] * a2
+
+	SMLABB	r4, r6, r2, r4				@ i2	(3)
+	SMLATB  r11,r7, r2, r11				@ i3	(4)
+	SMLABB	r12,r7, r2, r12				@ i4	(5)
+
+	LDR	r2,[r1],#-4
+	SMLABT	r3, r6, r2, r3				@ i1	(3)
+	SMLATT	r4, r7, r2, r4				@ i2	(4)
+	SMLABT	r11,r7, r2, r11				@ i3	(5)
+	SMLATT	r12,r8, r2, r12				@ i4	(6)
+	SMLATB	r3, r7, r2, r3				@ i1	(4)
+	SMLABB	r4, r7, r2, r4				@ i2	(5)
+	SMLATB	r11,r8, r2, r11				@ i3	(6)
+	SMLABB	r12,r8, r2, r12				@ i4	(7)
+
+	LDR	r2,[r1],#-4
+	SMLABT	r3, r7, r2, r3				@ i1	(5)
+	SMLATT	r4, r8, r2, r4				@ i2	(6)
+	SMLABT	r11,r8, r2, r11				@ i3	(7)
+	SMLATT	r12,r9, r2, r12				@ i4	(8)
+	SMLATB	r3, r8, r2, r3				@ i1	(6)
+	SMLABB	r4, r8, r2, r4				@ i2	(7)
+	SMLATB	r11,r9, r2, r11				@ i3	(8)
+	SMLABB	r12,r9, r2, r12				@ i4	(9)
+	LDR	r10, [r13, #8]				@ [ a10 | a11]
+
+	LDR	r2,[r1],#-4
+	SMLABT	r3, r8, r2, r3				@ i1	(7)
+	SMLATT	r4, r9, r2, r4				@ i2	(8)
+	SMLABT	r11,r9, r2, r11				@ i3	(9)
+	SMLATT	r12,r10, r2, r12			@ i4	(10)
+	SMLATB	r3, r9, r2, r3				@ i1	(8)
+	SMLABB	r4, r9, r2, r4				@ i2	(9)
+	SMLATB	r11,r10, r2, r11			@ i3	(10)
+	SMLABB	r12,r10, r2, r12			@ i4	(11)
+	LDR	r8, [r13, #12]				@ [ a12 | a13 ]
+
+	LDR	r2,[r1],#-4
+	SMLABT	r3, r9, r2, r3				@ i1	(9)
+	SMLATT	r4, r10, r2, r4				@ i2	(10)
+	SMLABT	r11,r10, r2, r11			@ i3	(11)
+	SMLATT	r12,r8, r2, r12				@ i4	(12)
+	SMLATB	r3, r10, r2, r3				@ i1	(10)
+	SMLABB	r4, r10, r2, r4				@ i2	(11)
+	SMLATB	r11,r8, r2, r11				@ i3	(12)
+	SMLABB	r12,r8, r2, r12				@ i4	(13)
+	LDR	r9, [r13, #16]				@ [ a14 | a15 ]
+
+	LDR	r2,[r1],#-4
+	SMLABT	r3, r10, r2, r3				@ i1	(11)
+	SMLATT	r4, r8, r2, r4				@ i2	(12)
+	SMLABT	r11,r8, r2, r11				@ i3	(13)
+	SMLATT	r12,r9, r2, r12				@ i4	(14)
+	SMLATB	r3, r8, r2, r3				@ i1	(12)
+	SMLABB	r4, r8, r2, r4				@ i2	(13)
+	SMLATB	r11,r9, r2, r11				@ i3	(14)
+	SMLABB	r12,r9, r2, r12				@ i4	(15)
+
+
+	LDR	r2,[r1],#-4
+	SMLABT	r3, r8, r2, r3				@ i1	(13)
+	SMLATT	r4, r9, r2, r4				@ i2	(14)
+	SMLABT	r11,r9, r2, r11				@ i3	(15)
+	SMLABT	r12,r14, r2, r12			@ i4	(16)
+	SMLATB	r3, r9, r2, r3				@ i1	(14)
+	SMLABB	r4, r9, r2, r4				@ i2	(15)
+	SMLABB	r11,r14, r2, r11			@ i3	(16)
+	LDR		r8, [r13]					@ [ a6 | a7 ]
+
+        LDR     r2,[r1],#44         		@ Change
+	SMLABT	r3, r9, r2, r3
+	SMLABB	r3, r14, r2, r3
+	SMLABT	r4, r14, r2, r4
+	LDR		r9, [r13, #4]				@ [ a8 | a9 ]
+
+
+	QADD	r3,r3,r3
+	QADD	r4,r4,r4
+	QADD	r11,r11,r11
+	QADD	r12,r12,r12
+
+	QADD	r3,r3,r3
+	QADD	r4,r4,r4
+	QADD	r11,r11,r11
+	QADD	r12,r12,r12
+
+	QADD	r3,r3,r3
+	QADD	r4,r4,r4
+	QADD	r11,r11,r11
+	QADD	r12,r12,r12
+
+	QADD	r3,r3,r3
+	QADD	r4,r4,r4
+	QADD	r11,r11,r11
+	QADD	r12,r12,r12
+
+	MOV	r2,#32768
+
+	QDADD	r3,r2,r3
+	QDADD	r4,r2,r4
+	QDADD	r11,r2,r11
+	QDADD	r12,r2,r12
+
+
+	MOV	r3,r3,asr #16
+	MOV	r4,r4,asr #16
+	MOV	r11,r11,asr #16
+	MOV	r12,r12,asr #16
+
+	STRH	r3,[r0],#2
+	STRH	r4,[r0],#2
+	STRH	r11,[r0],#2
+	STRH	r12,[r0],#2
+
+	MOV	r2,r14,asr #16
+	SUB	r14, r14, #0x10000
+	SUBS	r2,r2,#1
+	BNE	residu_loop
+end:
+	LDMFD	r13!, {r8 -r12}
+	LDMFD	r13!, {r4 -r12,pc}
+
+        @ENDFUNC
+        .END
+
+
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/scale_sig_opt.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/scale_sig_opt.s
index aa9f464..b300224 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/scale_sig_opt.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/scale_sig_opt.s
@@ -1,75 +1,75 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-@

-@void Scale_sig(

-@	       Word16 x[],                           /* (i/o) : signal to scale               */

-@	       Word16 lg,                            /* (i)   : size of x[]                   */

-@	       Word16 exp                            /* (i)   : exponent: x = round(x << exp) */

-@	       )

-@

-@r0 --- x[]

-@r1 --- lg

-@r2 --- exp

-

-          .section  .text

-	  .global   Scale_sig_opt

-

-Scale_sig_opt:

-

-         STMFD         r13!, {r4 - r12, r14}

-	 SUB           r3, r1, #1                  @i = lg - 1

-         CMP           r2, #0                      @Compare exp and 0

-	 RSB           r7, r2, #0                  @exp = -exp

-	 ADD           r10, r2, #16                @16 + exp

-         ADD           r4, r0, r3, LSL #1          @x[i] address

-	 MOV           r8, #0x7fffffff

-	 MOV           r9, #0x8000

-	 BLE           LOOP2

-	 

-LOOP1:

-

-         LDRSH          r5, [r4]                    @load x[i]

-         MOV           r12, r5, LSL r10

-	 TEQ           r5, r12, ASR r10

-	 EORNE         r12, r8, r5, ASR #31

-	 SUBS          r3, r3, #1

-	 QADD          r11, r12, r9

-	 MOV           r12, r11, ASR #16

-	 STRH          r12, [r4], #-2

-	 BGE           LOOP1

-         BL            The_end

-

-LOOP2:

-

-         LDRSH          r5, [r4]                   @load x[i]

-	 MOV           r6, r5, LSL #16            @L_tmp = x[i] << 16

-	 MOV           r5, r6, ASR r7             @L_tmp >>= exp

-	 QADD          r11, r5, r9

-	 MOV           r12, r11, ASR #16

-	 SUBS          r3, r3, #1

-	 STRH          r12, [r4], #-2

-	 BGE           LOOP2

-

-The_end:

-         LDMFD         r13!, {r4 - r12, r15}

-     

-         @ENDFUNC

-         .END	 

-        

-	

-	  

-

-

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+@
+@void Scale_sig(
+@	       Word16 x[],                           /* (i/o) : signal to scale               */
+@	       Word16 lg,                            /* (i)   : size of x[]                   */
+@	       Word16 exp                            /* (i)   : exponent: x = round(x << exp) */
+@	       )
+@
+@r0 --- x[]
+@r1 --- lg
+@r2 --- exp
+
+          .section  .text
+	  .global   Scale_sig_opt
+
+Scale_sig_opt:
+
+         STMFD         r13!, {r4 - r12, r14}
+	 SUB           r3, r1, #1                  @i = lg - 1
+         CMP           r2, #0                      @Compare exp and 0
+	 RSB           r7, r2, #0                  @exp = -exp
+	 ADD           r10, r2, #16                @16 + exp
+         ADD           r4, r0, r3, LSL #1          @x[i] address
+	 MOV           r8, #0x7fffffff
+	 MOV           r9, #0x8000
+	 BLE           LOOP2
+
+LOOP1:
+
+         LDRSH          r5, [r4]                    @load x[i]
+         MOV           r12, r5, LSL r10
+	 TEQ           r5, r12, ASR r10
+	 EORNE         r12, r8, r5, ASR #31
+	 SUBS          r3, r3, #1
+	 QADD          r11, r12, r9
+	 MOV           r12, r11, ASR #16
+	 STRH          r12, [r4], #-2
+	 BGE           LOOP1
+         BL            The_end
+
+LOOP2:
+
+         LDRSH          r5, [r4]                   @load x[i]
+	 MOV           r6, r5, LSL #16            @L_tmp = x[i] << 16
+	 MOV           r5, r6, ASR r7             @L_tmp >>= exp
+	 QADD          r11, r5, r9
+	 MOV           r12, r11, ASR #16
+	 SUBS          r3, r3, #1
+	 STRH          r12, [r4], #-2
+	 BGE           LOOP2
+
+The_end:
+         LDMFD         r13!, {r4 - r12, r15}
+
+         @ENDFUNC
+         .END
+
+
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/syn_filt_opt.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/syn_filt_opt.s
index e05e9e0..0c287a4 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/syn_filt_opt.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/syn_filt_opt.s
@@ -1,238 +1,238 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-@**********************************************************************/

-@void Syn_filt(

-@     Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients           */

-@     Word16 x[],                           /* (i)     : input signal                             */

-@     Word16 y[],                           /* (o)     : output signal                            */

-@     Word16 mem[],                         /* (i/o)   : memory associated with this filtering.   */

-@)

-@***********************************************************************

-@ a[]    ---   r0

-@ x[]    ---   r1

-@ y[]    ---   r2

-@ mem[]  ---   r3

-@ m ---  16  lg --- 80  update --- 1

-

-          .section  .text

-	  .global   Syn_filt_asm

-          .extern   voAWB_Copy

-

-Syn_filt_asm:

-

-          STMFD   	r13!, {r4 - r12, r14} 

-          SUB           r13, r13, #700                   @ y_buf[L_FRAME16k + M16k]

-   

-          MOV           r4, r3                           @ copy mem[] address

-          MOV           r5, r13                          @ copy yy = y_buf address

-

-          @ for(i = 0@ i < m@ i++)

-          @{

-          @    *yy++ = mem[i]@

-          @} 

-

-          LDRH          r6,  [r4], #2          

-          LDRH          r7,  [r4], #2

-          LDRH          r8,  [r4], #2

-          LDRH          r9,  [r4], #2

-          LDRH          r10, [r4], #2

-          LDRH          r11, [r4], #2

-          LDRH          r12, [r4], #2

-          LDRH          r14, [r4], #2

-

-          STRH          r6,  [r5], #2

-          STRH          r7,  [r5], #2

-          STRH          r8,  [r5], #2

-          STRH          r9,  [r5], #2

-          STRH          r10, [r5], #2

-          STRH          r11, [r5], #2

-          STRH          r12, [r5], #2

-          STRH          r14, [r5], #2

-

-          LDRH          r6,  [r4], #2          

-          LDRH          r7,  [r4], #2

-          LDRH          r8,  [r4], #2

-          LDRH          r9,  [r4], #2

-          LDRH          r10, [r4], #2

-          LDRH          r11, [r4], #2

-          LDRH          r12, [r4], #2

-          LDRH          r14, [r4], #2

-

-          STRH          r6,  [r5], #2

-          STRH          r7,  [r5], #2

-          STRH          r8,  [r5], #2

-          STRH          r9,  [r5], #2

-          STRH          r10, [r5], #2

-          STRH          r11, [r5], #2

-          STRH          r12, [r5], #2

-          STRH          r14, [r5], #2

-

-          LDRSH         r5, [r0]                         @ load a[0]

-          MOV           r8, #0                           @ i = 0

-          MOV           r5, r5, ASR #1                   @ a0 = a[0] >> 1

-          @MOV           r4, r13

-          @ load all a[]

-

-          LDR           r14, =0xffff

-          LDRSH         r6, [r0, #2]                     @ load a[1]

-          LDRSH         r7, [r0, #4]                     @ load a[2]

-          LDRSH         r9, [r0, #6]                     @ load a[3]

-          LDRSH         r11,[r0, #8]                     @ load a[4]

-          AND           r6, r6, r14

-          AND           r9, r9, r14          

-          ORR           r10, r6, r7, LSL #16             @ -a[2] -- -a[1]

-          ORR           r12, r9, r11, LSL #16            @ -a[4] -- -a[3]

-          STR           r10, [r13, #-4]

-          STR           r12, [r13, #-8]

-          

-          LDRSH         r6, [r0, #10]                    @ load a[5]

-          LDRSH         r7, [r0, #12]                    @ load a[6]

-          LDRSH         r9, [r0, #14]                    @ load a[7]

-          LDRSH         r11,[r0, #16]                    @ load a[8]

-          AND           r6, r6, r14

-          AND           r9, r9, r14          

-          ORR           r10, r6, r7, LSL #16             @ -a[6] -- -a[5]

-          ORR           r12, r9, r11, LSL #16            @ -a[8] -- -a[7]

-          STR           r10, [r13, #-12]

-          STR           r12, [r13, #-16]          

-           

-          LDRSH         r6, [r0, #18]                    @ load a[9]

-          LDRSH         r7, [r0, #20]                    @ load a[10]

-          LDRSH         r9, [r0, #22]                    @ load a[11]

-          LDRSH         r11,[r0, #24]                    @ load a[12]

-          AND           r6, r6, r14

-          AND           r9, r9, r14          

-          ORR           r10, r6, r7, LSL #16             @ -a[10] -- -a[9]

-          ORR           r12, r9, r11, LSL #16            @ -a[12] -- -a[11]

-          STR           r10, [r13, #-20]

-          STR           r12, [r13, #-24]    

-

-          LDRSH         r6, [r0, #26]                    @ load a[13]

-          LDRSH         r7, [r0, #28]                    @ load a[14]

-          LDRSH         r9, [r0, #30]                    @ load a[15]

-          LDRSH         r11,[r0, #32]                    @ load a[16]

-          AND           r6, r6, r14

-          AND           r9, r9, r14          

-          ORR           r10, r6, r7, LSL #16             @ -a[14] -- -a[13]

-          ORR           r12, r9, r11, LSL #16            @ -a[16] -- -a[15]

-          STR           r10, [r13, #-28]

-          STR           r12, [r13, #-32]                

-                     

-          ADD           r4, r13, #32

-LOOP:

-          LDRSH         r6,  [r1], #2                    @ load x[i]

-          ADD           r10, r4, r8, LSL #1              @ temp_p = yy + i

-

-          MUL           r0, r5, r6                      @ L_tmp = x[i] * a0

-          @ for(j = 1@ j <= m, j+=8)

-          LDR           r7,  [r13, #-4]                  @ -a[2]  -a[1]

-          LDRSH         r9,  [r10, #-2]                  @ *(temp_p - 1)

-          LDRSH         r12, [r10, #-4]                  @ *(temp_p - 2)

-

-

-          SMULBB        r14, r9, r7                      @ -a[1] * (*(temp_p -1))

-

-          LDRSH         r6,  [r10, #-6]                  @ *(temp_p - 3)

-

-          SMLABT        r14, r12, r7, r14                @ -a[2] * (*(temp_p - 2))

-

-          LDR           r7,  [r13, #-8]                  @ -a[4] -a[3]

-          LDRSH         r11, [r10, #-8]                  @ *(temp_p - 4)

-

-          SMLABB        r14, r6, r7, r14                 @ -a[3] * (*(temp_p -3))

-

-          LDRSH         r9,  [r10, #-10]                 @ *(temp_p - 5)

-   

-          SMLABT        r14, r11, r7, r14                @ -a[4] * (*(temp_p -4))        

-

-          LDR           r7,  [r13, #-12]                 @ -a[6]  -a[5]

-          LDRSH         r12, [r10, #-12]                 @ *(temp_p - 6)

-

-          SMLABB        r14, r9, r7, r14                 @ -a[5] * (*(temp_p -5))

-

-          LDRSH         r6,  [r10, #-14]                 @ *(temp_p - 7)

-

-          SMLABT        r14, r12, r7, r14                @ -a[6] * (*(temp_p - 6))

-

-          LDR           r7,  [r13, #-16]                 @ -a[8] -a[7]

-          LDRSH         r11, [r10, #-16]                 @ *(temp_p - 8)

-         

-          SMLABB        r14, r6, r7, r14                 @ -a[7] * (*(temp_p -7))

-

-          LDRSH         r9,  [r10, #-18]                 @ *(temp_p - 9)

-

-          SMLABT        r14, r11, r7, r14                @ -a[8] * (*(temp_p -8))          

- 

-          LDR           r7,  [r13, #-20]                 @ -a[10]  -a[9]

-          LDRSH         r12, [r10, #-20]                 @ *(temp_p - 10)

-

-          SMLABB        r14, r9, r7, r14                 @ -a[9] * (*(temp_p -9))

-

-          LDRSH         r6,  [r10, #-22]                 @ *(temp_p - 11)

-

-          SMLABT        r14, r12, r7, r14                @ -a[10] * (*(temp_p - 10))

-

-          LDR           r7,  [r13, #-24]                 @ -a[12] -a[11]

-          LDRSH         r11, [r10, #-24]                 @ *(temp_p - 12)

-

-          SMLABB        r14, r6, r7, r14                 @ -a[11] * (*(temp_p -11))

-

-          LDRSH         r9,  [r10, #-26]                 @ *(temp_p - 13)

-

-          SMLABT        r14, r11, r7, r14                @ -a[12] * (*(temp_p -12))           

-

-          LDR           r7,  [r13, #-28]                 @ -a[14] -a[13]

-          LDRSH         r12, [r10, #-28]                 @ *(temp_p - 14)

- 

-          SMLABB        r14, r9, r7, r14                 @ -a[13] * (*(temp_p -13))

-

-          LDRSH         r6,  [r10, #-30]                 @ *(temp_p - 15)

-

-          SMLABT        r14, r12, r7, r14                @ -a[14] * (*(temp_p - 14))

-

-          LDR           r7,  [r13, #-32]                 @ -a[16] -a[15]

-          LDRSH         r11, [r10, #-32]                 @ *(temp_p - 16)

-

-          SMLABB        r14, r6, r7, r14                 @ -a[15] * (*(temp_p -15))

-

-          SMLABT        r14, r11, r7, r14                @ -a[16] * (*(temp_p -16))

-

-          RSB           r14, r14, r0

-                                  

-          MOV           r7, r14, LSL #4                  @ L_tmp <<=4

-          ADD           r8, r8, #1

-          ADD           r14, r7, #0x8000                 

-          MOV           r7, r14, ASR #16                 @ (L_tmp + 0x8000) >> 16

-          CMP           r8, #80

-          STRH          r7, [r10]                        @ yy[i]

-          STRH          r7, [r2], #2                     @ y[i]

-          BLT           LOOP

- 

-          @ update mem[]

-          ADD           r5, r13, #160                    @ yy[64] address

-          MOV           r1, r3

-          MOV           r0, r5

-          MOV           r2, #16

-          BL            voAWB_Copy          

-

-Syn_filt_asm_end:

- 

-          ADD           r13, r13, #700		     

-          LDMFD   	r13!, {r4 - r12, r15} 

-          @ENDFUNC

-          .END

- 

-

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+@**********************************************************************/
+@void Syn_filt(
+@     Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients           */
+@     Word16 x[],                           /* (i)     : input signal                             */
+@     Word16 y[],                           /* (o)     : output signal                            */
+@     Word16 mem[],                         /* (i/o)   : memory associated with this filtering.   */
+@)
+@***********************************************************************
+@ a[]    ---   r0
+@ x[]    ---   r1
+@ y[]    ---   r2
+@ mem[]  ---   r3
+@ m ---  16  lg --- 80  update --- 1
+
+          .section  .text
+	  .global   Syn_filt_asm
+          .extern   voAWB_Copy
+
+Syn_filt_asm:
+
+          STMFD   	r13!, {r4 - r12, r14}
+          SUB           r13, r13, #700                   @ y_buf[L_FRAME16k + M16k]
+
+          MOV           r4, r3                           @ copy mem[] address
+          MOV           r5, r13                          @ copy yy = y_buf address
+
+          @ for(i = 0@ i < m@ i++)
+          @{
+          @    *yy++ = mem[i]@
+          @}
+
+          LDRH          r6,  [r4], #2
+          LDRH          r7,  [r4], #2
+          LDRH          r8,  [r4], #2
+          LDRH          r9,  [r4], #2
+          LDRH          r10, [r4], #2
+          LDRH          r11, [r4], #2
+          LDRH          r12, [r4], #2
+          LDRH          r14, [r4], #2
+
+          STRH          r6,  [r5], #2
+          STRH          r7,  [r5], #2
+          STRH          r8,  [r5], #2
+          STRH          r9,  [r5], #2
+          STRH          r10, [r5], #2
+          STRH          r11, [r5], #2
+          STRH          r12, [r5], #2
+          STRH          r14, [r5], #2
+
+          LDRH          r6,  [r4], #2
+          LDRH          r7,  [r4], #2
+          LDRH          r8,  [r4], #2
+          LDRH          r9,  [r4], #2
+          LDRH          r10, [r4], #2
+          LDRH          r11, [r4], #2
+          LDRH          r12, [r4], #2
+          LDRH          r14, [r4], #2
+
+          STRH          r6,  [r5], #2
+          STRH          r7,  [r5], #2
+          STRH          r8,  [r5], #2
+          STRH          r9,  [r5], #2
+          STRH          r10, [r5], #2
+          STRH          r11, [r5], #2
+          STRH          r12, [r5], #2
+          STRH          r14, [r5], #2
+
+          LDRSH         r5, [r0]                         @ load a[0]
+          MOV           r8, #0                           @ i = 0
+          MOV           r5, r5, ASR #1                   @ a0 = a[0] >> 1
+          @MOV           r4, r13
+          @ load all a[]
+
+          LDR           r14, =0xffff
+          LDRSH         r6, [r0, #2]                     @ load a[1]
+          LDRSH         r7, [r0, #4]                     @ load a[2]
+          LDRSH         r9, [r0, #6]                     @ load a[3]
+          LDRSH         r11,[r0, #8]                     @ load a[4]
+          AND           r6, r6, r14
+          AND           r9, r9, r14
+          ORR           r10, r6, r7, LSL #16             @ -a[2] -- -a[1]
+          ORR           r12, r9, r11, LSL #16            @ -a[4] -- -a[3]
+          STR           r10, [r13, #-4]
+          STR           r12, [r13, #-8]
+
+          LDRSH         r6, [r0, #10]                    @ load a[5]
+          LDRSH         r7, [r0, #12]                    @ load a[6]
+          LDRSH         r9, [r0, #14]                    @ load a[7]
+          LDRSH         r11,[r0, #16]                    @ load a[8]
+          AND           r6, r6, r14
+          AND           r9, r9, r14
+          ORR           r10, r6, r7, LSL #16             @ -a[6] -- -a[5]
+          ORR           r12, r9, r11, LSL #16            @ -a[8] -- -a[7]
+          STR           r10, [r13, #-12]
+          STR           r12, [r13, #-16]
+
+          LDRSH         r6, [r0, #18]                    @ load a[9]
+          LDRSH         r7, [r0, #20]                    @ load a[10]
+          LDRSH         r9, [r0, #22]                    @ load a[11]
+          LDRSH         r11,[r0, #24]                    @ load a[12]
+          AND           r6, r6, r14
+          AND           r9, r9, r14
+          ORR           r10, r6, r7, LSL #16             @ -a[10] -- -a[9]
+          ORR           r12, r9, r11, LSL #16            @ -a[12] -- -a[11]
+          STR           r10, [r13, #-20]
+          STR           r12, [r13, #-24]
+
+          LDRSH         r6, [r0, #26]                    @ load a[13]
+          LDRSH         r7, [r0, #28]                    @ load a[14]
+          LDRSH         r9, [r0, #30]                    @ load a[15]
+          LDRSH         r11,[r0, #32]                    @ load a[16]
+          AND           r6, r6, r14
+          AND           r9, r9, r14
+          ORR           r10, r6, r7, LSL #16             @ -a[14] -- -a[13]
+          ORR           r12, r9, r11, LSL #16            @ -a[16] -- -a[15]
+          STR           r10, [r13, #-28]
+          STR           r12, [r13, #-32]
+
+          ADD           r4, r13, #32
+LOOP:
+          LDRSH         r6,  [r1], #2                    @ load x[i]
+          ADD           r10, r4, r8, LSL #1              @ temp_p = yy + i
+
+          MUL           r0, r5, r6                      @ L_tmp = x[i] * a0
+          @ for(j = 1@ j <= m, j+=8)
+          LDR           r7,  [r13, #-4]                  @ -a[2]  -a[1]
+          LDRSH         r9,  [r10, #-2]                  @ *(temp_p - 1)
+          LDRSH         r12, [r10, #-4]                  @ *(temp_p - 2)
+
+
+          SMULBB        r14, r9, r7                      @ -a[1] * (*(temp_p -1))
+
+          LDRSH         r6,  [r10, #-6]                  @ *(temp_p - 3)
+
+          SMLABT        r14, r12, r7, r14                @ -a[2] * (*(temp_p - 2))
+
+          LDR           r7,  [r13, #-8]                  @ -a[4] -a[3]
+          LDRSH         r11, [r10, #-8]                  @ *(temp_p - 4)
+
+          SMLABB        r14, r6, r7, r14                 @ -a[3] * (*(temp_p -3))
+
+          LDRSH         r9,  [r10, #-10]                 @ *(temp_p - 5)
+
+          SMLABT        r14, r11, r7, r14                @ -a[4] * (*(temp_p -4))
+
+          LDR           r7,  [r13, #-12]                 @ -a[6]  -a[5]
+          LDRSH         r12, [r10, #-12]                 @ *(temp_p - 6)
+
+          SMLABB        r14, r9, r7, r14                 @ -a[5] * (*(temp_p -5))
+
+          LDRSH         r6,  [r10, #-14]                 @ *(temp_p - 7)
+
+          SMLABT        r14, r12, r7, r14                @ -a[6] * (*(temp_p - 6))
+
+          LDR           r7,  [r13, #-16]                 @ -a[8] -a[7]
+          LDRSH         r11, [r10, #-16]                 @ *(temp_p - 8)
+
+          SMLABB        r14, r6, r7, r14                 @ -a[7] * (*(temp_p -7))
+
+          LDRSH         r9,  [r10, #-18]                 @ *(temp_p - 9)
+
+          SMLABT        r14, r11, r7, r14                @ -a[8] * (*(temp_p -8))
+
+          LDR           r7,  [r13, #-20]                 @ -a[10]  -a[9]
+          LDRSH         r12, [r10, #-20]                 @ *(temp_p - 10)
+
+          SMLABB        r14, r9, r7, r14                 @ -a[9] * (*(temp_p -9))
+
+          LDRSH         r6,  [r10, #-22]                 @ *(temp_p - 11)
+
+          SMLABT        r14, r12, r7, r14                @ -a[10] * (*(temp_p - 10))
+
+          LDR           r7,  [r13, #-24]                 @ -a[12] -a[11]
+          LDRSH         r11, [r10, #-24]                 @ *(temp_p - 12)
+
+          SMLABB        r14, r6, r7, r14                 @ -a[11] * (*(temp_p -11))
+
+          LDRSH         r9,  [r10, #-26]                 @ *(temp_p - 13)
+
+          SMLABT        r14, r11, r7, r14                @ -a[12] * (*(temp_p -12))
+
+          LDR           r7,  [r13, #-28]                 @ -a[14] -a[13]
+          LDRSH         r12, [r10, #-28]                 @ *(temp_p - 14)
+
+          SMLABB        r14, r9, r7, r14                 @ -a[13] * (*(temp_p -13))
+
+          LDRSH         r6,  [r10, #-30]                 @ *(temp_p - 15)
+
+          SMLABT        r14, r12, r7, r14                @ -a[14] * (*(temp_p - 14))
+
+          LDR           r7,  [r13, #-32]                 @ -a[16] -a[15]
+          LDRSH         r11, [r10, #-32]                 @ *(temp_p - 16)
+
+          SMLABB        r14, r6, r7, r14                 @ -a[15] * (*(temp_p -15))
+
+          SMLABT        r14, r11, r7, r14                @ -a[16] * (*(temp_p -16))
+
+          RSB           r14, r14, r0
+
+          MOV           r7, r14, LSL #4                  @ L_tmp <<=4
+          ADD           r8, r8, #1
+          ADD           r14, r7, #0x8000
+          MOV           r7, r14, ASR #16                 @ (L_tmp + 0x8000) >> 16
+          CMP           r8, #80
+          STRH          r7, [r10]                        @ yy[i]
+          STRH          r7, [r2], #2                     @ y[i]
+          BLT           LOOP
+
+          @ update mem[]
+          ADD           r5, r13, #160                    @ yy[64] address
+          MOV           r1, r3
+          MOV           r0, r5
+          MOV           r2, #16
+          BL            voAWB_Copy
+
+Syn_filt_asm_end:
+
+          ADD           r13, r13, #700
+          LDMFD   	r13!, {r4 - r12, r15}
+          @ENDFUNC
+          .END
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Deemph_32_neon.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Deemph_32_neon.s
index acb60c3..1d5893f 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Deemph_32_neon.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Deemph_32_neon.s
@@ -1,102 +1,102 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-@

-@void Deemph_32(

-@     Word16 x_hi[],                        /* (i)     : input signal (bit31..16) */

-@     Word16 x_lo[],                        /* (i)     : input signal (bit15..4)  */

-@     Word16 y[],                           /* (o)     : output signal (x16)      */

-@     Word16 mu,                            /* (i) Q15 : deemphasis factor        */

-@     Word16 L,                             /* (i)     : vector size              */

-@     Word16 * mem                          /* (i/o)   : memory (y[-1])           */

-@     )

-

-@x_hi     RN      R0

-@x_lo     RN      R1

-@y[]      RN      R2

-@*mem     RN      R3

-

-           .section  .text

-           .global   Deemph_32_asm

-	   

-Deemph_32_asm:

-

-           STMFD   	r13!, {r4 - r12, r14} 

-	   MOV          r4, #2                   @i=0

-	   LDRSH        r6, [r0], #2             @load x_hi[0]

-	   LDRSH        r7, [r1], #2             @load x_lo[0]

-	   LDR          r5, =22282               @r5---mu

-	   MOV          r11, #0x8000

-

-           @y[0]

-	   MOV          r10, r6, LSL #16         @L_tmp = x_hi[0]<<16

-	   MOV          r8,  r5, ASR #1          @fac = mu >> 1

-	   LDR          r5,  [r3]

-	   ADD          r12, r10, r7, LSL #4     @L_tmp += x_lo[0] << 4

-	   MOV          r10, r12, LSL #3         @L_tmp <<= 3

-	   MUL          r9, r5, r8

-	   LDRSH        r6, [r0], #2             @load x_hi[1] 

-	   QDADD        r10, r10, r9

-	   LDRSH        r7, [r1], #2             @load x_lo[1]  

-	   MOV          r12, r10, LSL #1         @L_tmp = L_mac(L_tmp, *mem, fac)

-	   QADD         r10, r12, r11

-	   MOV          r14, r10, ASR #16        @y[0] = round(L_tmp)

-

-

-	   MOV          r10, r6, LSL #16

-	   ADD          r12, r10, r7, LSL #4

-           STRH         r14, [r2], #2            @update y[0]

-	   MOV          r10, r12, LSL #3

-	   MUL          r9, r14, r8

-	   QDADD        r10, r10, r9

-	   MOV          r12, r10, LSL #1

-	   QADD         r10, r12, r11

-	   MOV          r14, r10, ASR #16        @y[1] = round(L_tmp)

-

-LOOP:

-           LDRSH        r6, [r0], #2             @load x_hi[]

-	   LDRSH        r7, [r1], #2

-	   STRH         r14, [r2], #2

-	   MOV          r10, r6, LSL #16

-	   ADD          r12, r10, r7, LSL #4

-	   MUL          r9, r14, r8

-	   MOV          r10, r12, LSL #3

-	   QDADD        r10, r10, r9

-           LDRSH        r6, [r0], #2             @load x_hi[]

-	   MOV          r12, r10, LSL #1

-	   QADD         r10, r12, r11

-	   LDRSH        r7, [r1], #2

-	   MOV          r14, r10, ASR #16

-

-	   MOV          r10, r6, LSL #16

-	   ADD          r12, r10, r7, LSL #4

-	   STRH         r14, [r2], #2

-	   MUL          r9, r14, r8

-	   MOV          r10, r12, LSL #3

-	   QDADD        r10, r10, r9

-           ADD          r4, r4, #2

-	   MOV          r12, r10, LSL #1

-	   QADD         r10, r12, r11

-           CMP          r4, #64

-	   MOV          r14, r10, ASR #16

-

-           BLT          LOOP

-           STR          r14, [r3]

-           STRH         r14, [r2]	   

-

-           LDMFD   	r13!, {r4 - r12, r15} 

-

-	   .END

-

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+@
+@void Deemph_32(
+@     Word16 x_hi[],                        /* (i)     : input signal (bit31..16) */
+@     Word16 x_lo[],                        /* (i)     : input signal (bit15..4)  */
+@     Word16 y[],                           /* (o)     : output signal (x16)      */
+@     Word16 mu,                            /* (i) Q15 : deemphasis factor        */
+@     Word16 L,                             /* (i)     : vector size              */
+@     Word16 * mem                          /* (i/o)   : memory (y[-1])           */
+@     )
+
+@x_hi     RN      R0
+@x_lo     RN      R1
+@y[]      RN      R2
+@*mem     RN      R3
+
+           .section  .text
+           .global   Deemph_32_asm
+
+Deemph_32_asm:
+
+           STMFD   	r13!, {r4 - r12, r14}
+	   MOV          r4, #2                   @i=0
+	   LDRSH        r6, [r0], #2             @load x_hi[0]
+	   LDRSH        r7, [r1], #2             @load x_lo[0]
+	   LDR          r5, =22282               @r5---mu
+	   MOV          r11, #0x8000
+
+           @y[0]
+	   MOV          r10, r6, LSL #16         @L_tmp = x_hi[0]<<16
+	   MOV          r8,  r5, ASR #1          @fac = mu >> 1
+	   LDR          r5,  [r3]
+	   ADD          r12, r10, r7, LSL #4     @L_tmp += x_lo[0] << 4
+	   MOV          r10, r12, LSL #3         @L_tmp <<= 3
+	   MUL          r9, r5, r8
+	   LDRSH        r6, [r0], #2             @load x_hi[1]
+	   QDADD        r10, r10, r9
+	   LDRSH        r7, [r1], #2             @load x_lo[1]
+	   MOV          r12, r10, LSL #1         @L_tmp = L_mac(L_tmp, *mem, fac)
+	   QADD         r10, r12, r11
+	   MOV          r14, r10, ASR #16        @y[0] = round(L_tmp)
+
+
+	   MOV          r10, r6, LSL #16
+	   ADD          r12, r10, r7, LSL #4
+           STRH         r14, [r2], #2            @update y[0]
+	   MOV          r10, r12, LSL #3
+	   MUL          r9, r14, r8
+	   QDADD        r10, r10, r9
+	   MOV          r12, r10, LSL #1
+	   QADD         r10, r12, r11
+	   MOV          r14, r10, ASR #16        @y[1] = round(L_tmp)
+
+LOOP:
+           LDRSH        r6, [r0], #2             @load x_hi[]
+	   LDRSH        r7, [r1], #2
+	   STRH         r14, [r2], #2
+	   MOV          r10, r6, LSL #16
+	   ADD          r12, r10, r7, LSL #4
+	   MUL          r9, r14, r8
+	   MOV          r10, r12, LSL #3
+	   QDADD        r10, r10, r9
+           LDRSH        r6, [r0], #2             @load x_hi[]
+	   MOV          r12, r10, LSL #1
+	   QADD         r10, r12, r11
+	   LDRSH        r7, [r1], #2
+	   MOV          r14, r10, ASR #16
+
+	   MOV          r10, r6, LSL #16
+	   ADD          r12, r10, r7, LSL #4
+	   STRH         r14, [r2], #2
+	   MUL          r9, r14, r8
+	   MOV          r10, r12, LSL #3
+	   QDADD        r10, r10, r9
+           ADD          r4, r4, #2
+	   MOV          r12, r10, LSL #1
+	   QADD         r10, r12, r11
+           CMP          r4, #64
+	   MOV          r14, r10, ASR #16
+
+           BLT          LOOP
+           STR          r14, [r3]
+           STRH         r14, [r2]
+
+           LDMFD   	r13!, {r4 - r12, r15}
+
+	   .END
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Dot_p_neon.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Dot_p_neon.s
index 07ca344..8230944d 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Dot_p_neon.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Dot_p_neon.s
@@ -1,127 +1,127 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-@

-@**********************************************************************/

-@Word32 Dot_product12(                      /* (o) Q31: normalized result (1 < val <= -1) */

-@       Word16 x[],                           /* (i) 12bits: x vector                       */

-@       Word16 y[],                           /* (i) 12bits: y vector                       */

-@       Word16 lg,                            /* (i)    : vector length                     */

-@       Word16 * exp                          /* (o)    : exponent of result (0..+30)       */

-@)

-@************************************************************************

-@  x[]   ---  r0

-@  y[]   ---  r1

-@  lg    ---  r2

-@  *exp  ---  r3

-

-          .section   .text

-          .global    Dot_product12_asm

-

-Dot_product12_asm:

-

-          STMFD   	    r13!, {r4 - r12, r14}

-	  CMP               r0, r1

-	  BEQ               LOOP_EQ

-

-          VLD1.S16          {Q0, Q1}, [r0]!               @load 16 Word16 x[]

-          VLD1.S16          {Q2, Q3}, [r0]!               @load 16 Word16 x[]

-          VLD1.S16          {Q4, Q5}, [r0]!               @load 16 Word16 x[]

-          VLD1.S16          {Q6, Q7}, [r0]!               @load 16 Word16 x[]

-	  VLD1.S16          {Q8, Q9}, [r1]!               @load 16 Word16 y[]

-	  VLD1.S16          {Q10, Q11}, [r1]!             @load 16 Word16 y[]

-	  VLD1.S16          {Q12, Q13}, [r1]!             @load 16 Word16 y[]

-

-          VMULL.S16         Q15, D16, D0

-          VMLAL.S16         Q15, D17, D1               

-          VMLAL.S16         Q15, D18, D2

-          VMLAL.S16         Q15, D19, D3

-	  VLD1.S16          {Q0, Q1}, [r1]!               @load 16 Word16 y[]   

-          VMLAL.S16         Q15, D20, D4       

-          VMLAL.S16         Q15, D21, D5

-          VMLAL.S16         Q15, D22, D6

-          VMLAL.S16         Q15, D23, D7                                       

-          VMLAL.S16         Q15, D24, D8

-          VMLAL.S16         Q15, D25, D9

-          VMLAL.S16         Q15, D26, D10

-          VMLAL.S16         Q15, D27, D11

-          VMLAL.S16         Q15, D0, D12

-          VMLAL.S16         Q15, D1, D13

-          VMLAL.S16         Q15, D2, D14

-          VMLAL.S16         Q15, D3, D15

-

-          CMP               r2, #64

-          BEQ               Lable1

-          VLD1.S16          {Q0, Q1}, [r0]!               @load 16 Word16 x[]  

-	  VLD1.S16          {Q2, Q3}, [r1]! 

-          VMLAL.S16         Q15, D4, D0             

-          VMLAL.S16         Q15, D5, D1

-          VMLAL.S16         Q15, D6, D2

-          VMLAL.S16         Q15, D7, D3

-	  BL                Lable1

-

-LOOP_EQ:

-          VLD1.S16          {Q0, Q1}, [r0]!

-	  VLD1.S16          {Q2, Q3}, [r0]!

-	  VLD1.S16          {Q4, Q5}, [r0]!

-	  VLD1.S16          {Q6, Q7}, [r0]!

-	  VMULL.S16         Q15, D0, D0

-	  VMLAL.S16         Q15, D1, D1

-	  VMLAL.S16         Q15, D2, D2

-	  VMLAL.S16         Q15, D3, D3

-	  VMLAL.S16         Q15, D4, D4

-	  VMLAL.S16         Q15, D5, D5

-	  VMLAL.S16         Q15, D6, D6

-	  VMLAL.S16         Q15, D7, D7

-	  VMLAL.S16         Q15, D8, D8

-	  VMLAL.S16         Q15, D9, D9

-	  VMLAL.S16         Q15, D10, D10

-	  VMLAL.S16         Q15, D11, D11

-	  VMLAL.S16         Q15, D12, D12

-	  VMLAL.S16         Q15, D13, D13

-	  VMLAL.S16         Q15, D14, D14

-	  VMLAL.S16         Q15, D15, D15

-

-	  CMP               r2, #64

-	  BEQ               Lable1

-	  VLD1.S16          {Q0, Q1}, [r0]!

-	  VMLAL.S16         Q15, D0, D0

-	  VMLAL.S16         Q15, D1, D1

-	  VMLAL.S16         Q15, D2, D2

-	  VMLAL.S16         Q15, D3, D3

-

-Lable1: 

-

-          VQADD.S32         D30, D30, D31

-          VPADD.S32         D30, D30, D30

-          VMOV.S32          r12, D30[0]        

-

-	  ADD               r12, r12, r12

-          ADD               r12, r12, #1                         @ L_sum = (L_sum << 1)  + 1

-	  MOV               r4, r12

-	  CMP               r12, #0

-	  RSBLT             r4, r12, #0

-          CLZ               r10, r4

-          SUB               r10, r10, #1                         @ sft = norm_l(L_sum)

-          MOV               r0, r12, LSL r10                     @ L_sum = L_sum << sft

-          RSB               r11, r10, #30                        @ *exp = 30 - sft

-          STRH              r11, [r3]                     

-

-Dot_product12_end:

-		     

-          LDMFD   	    r13!, {r4 - r12, r15} 

-

-          .END

-

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+@
+@**********************************************************************/
+@Word32 Dot_product12(                      /* (o) Q31: normalized result (1 < val <= -1) */
+@       Word16 x[],                           /* (i) 12bits: x vector                       */
+@       Word16 y[],                           /* (i) 12bits: y vector                       */
+@       Word16 lg,                            /* (i)    : vector length                     */
+@       Word16 * exp                          /* (o)    : exponent of result (0..+30)       */
+@)
+@************************************************************************
+@  x[]   ---  r0
+@  y[]   ---  r1
+@  lg    ---  r2
+@  *exp  ---  r3
+
+          .section   .text
+          .global    Dot_product12_asm
+
+Dot_product12_asm:
+
+          STMFD   	    r13!, {r4 - r12, r14}
+	  CMP               r0, r1
+	  BEQ               LOOP_EQ
+
+          VLD1.S16          {Q0, Q1}, [r0]!               @load 16 Word16 x[]
+          VLD1.S16          {Q2, Q3}, [r0]!               @load 16 Word16 x[]
+          VLD1.S16          {Q4, Q5}, [r0]!               @load 16 Word16 x[]
+          VLD1.S16          {Q6, Q7}, [r0]!               @load 16 Word16 x[]
+	  VLD1.S16          {Q8, Q9}, [r1]!               @load 16 Word16 y[]
+	  VLD1.S16          {Q10, Q11}, [r1]!             @load 16 Word16 y[]
+	  VLD1.S16          {Q12, Q13}, [r1]!             @load 16 Word16 y[]
+
+          VMULL.S16         Q15, D16, D0
+          VMLAL.S16         Q15, D17, D1
+          VMLAL.S16         Q15, D18, D2
+          VMLAL.S16         Q15, D19, D3
+	  VLD1.S16          {Q0, Q1}, [r1]!               @load 16 Word16 y[]
+          VMLAL.S16         Q15, D20, D4
+          VMLAL.S16         Q15, D21, D5
+          VMLAL.S16         Q15, D22, D6
+          VMLAL.S16         Q15, D23, D7
+          VMLAL.S16         Q15, D24, D8
+          VMLAL.S16         Q15, D25, D9
+          VMLAL.S16         Q15, D26, D10
+          VMLAL.S16         Q15, D27, D11
+          VMLAL.S16         Q15, D0, D12
+          VMLAL.S16         Q15, D1, D13
+          VMLAL.S16         Q15, D2, D14
+          VMLAL.S16         Q15, D3, D15
+
+          CMP               r2, #64
+          BEQ               Lable1
+          VLD1.S16          {Q0, Q1}, [r0]!               @load 16 Word16 x[]
+	  VLD1.S16          {Q2, Q3}, [r1]!
+          VMLAL.S16         Q15, D4, D0
+          VMLAL.S16         Q15, D5, D1
+          VMLAL.S16         Q15, D6, D2
+          VMLAL.S16         Q15, D7, D3
+	  BL                Lable1
+
+LOOP_EQ:
+          VLD1.S16          {Q0, Q1}, [r0]!
+	  VLD1.S16          {Q2, Q3}, [r0]!
+	  VLD1.S16          {Q4, Q5}, [r0]!
+	  VLD1.S16          {Q6, Q7}, [r0]!
+	  VMULL.S16         Q15, D0, D0
+	  VMLAL.S16         Q15, D1, D1
+	  VMLAL.S16         Q15, D2, D2
+	  VMLAL.S16         Q15, D3, D3
+	  VMLAL.S16         Q15, D4, D4
+	  VMLAL.S16         Q15, D5, D5
+	  VMLAL.S16         Q15, D6, D6
+	  VMLAL.S16         Q15, D7, D7
+	  VMLAL.S16         Q15, D8, D8
+	  VMLAL.S16         Q15, D9, D9
+	  VMLAL.S16         Q15, D10, D10
+	  VMLAL.S16         Q15, D11, D11
+	  VMLAL.S16         Q15, D12, D12
+	  VMLAL.S16         Q15, D13, D13
+	  VMLAL.S16         Q15, D14, D14
+	  VMLAL.S16         Q15, D15, D15
+
+	  CMP               r2, #64
+	  BEQ               Lable1
+	  VLD1.S16          {Q0, Q1}, [r0]!
+	  VMLAL.S16         Q15, D0, D0
+	  VMLAL.S16         Q15, D1, D1
+	  VMLAL.S16         Q15, D2, D2
+	  VMLAL.S16         Q15, D3, D3
+
+Lable1:
+
+          VQADD.S32         D30, D30, D31
+          VPADD.S32         D30, D30, D30
+          VMOV.S32          r12, D30[0]
+
+	  ADD               r12, r12, r12
+          ADD               r12, r12, #1                         @ L_sum = (L_sum << 1)  + 1
+	  MOV               r4, r12
+	  CMP               r12, #0
+	  RSBLT             r4, r12, #0
+          CLZ               r10, r4
+          SUB               r10, r10, #1                         @ sft = norm_l(L_sum)
+          MOV               r0, r12, LSL r10                     @ L_sum = L_sum << sft
+          RSB               r11, r10, #30                        @ *exp = 30 - sft
+          STRH              r11, [r3]
+
+Dot_product12_end:
+
+          LDMFD   	    r13!, {r4 - r12, r15}
+
+          .END
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Filt_6k_7k_neon.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Filt_6k_7k_neon.s
index 1880024..14ba828 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Filt_6k_7k_neon.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Filt_6k_7k_neon.s
@@ -1,228 +1,228 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-@                             

-@**********************************************************************/

-@void Filt_6k_7k(

-@     Word16 signal[],                      /* input:  signal                  */

-@     Word16 lg,                            /* input:  length of input         */

-@     Word16 mem[]                          /* in/out: memory (size=30)        */

-@)

-@***********************************************************************

-@ r0    ---  signal[]

-@ r1    ---  lg

-@ r2    ---  mem[] 

-

-          .section  .text

-          .global   Filt_6k_7k_asm

-          .extern   fir_6k_7k

-

-Filt_6k_7k_asm:

-

-          STMFD   		r13!, {r0 - r12, r14} 

-          SUB    		r13, r13, #240              @ x[L_SUBFR16k + (L_FIR - 1)]

-          MOV     		r8, r0                      @ copy signal[] address

-          MOV     		r5, r2                      @ copy mem[] address

-

-          MOV     		r0, r2

-          MOV     		r1, r13

-

-	  VLD1.S16              {D0, D1, D2, D3}, [r0]!

-	  VLD1.S16              {D4, D5, D6, D7}, [r0]!

-

-	  VST1.S16              {D0, D1, D2, D3}, [r1]!

-	  VST1.S16              {D4, D5, D6}, [r1]!

-	  VST1.S16              D7[0], [r1]!

-	  VST1.S16              D7[1], [r1]!

-

-

-

-          LDR     		r10, Lable1                 @ get fir_7k address     

-          MOV                   r3, r8                      @ change myMemCopy to Copy, due to Copy will change r3 content

-          ADD     	    	r6, r13, #60                @ get x[L_FIR - 1] address

-          MOV           	r7, r3                      @ get signal[i]

-          @for (i = lg - 1@ i >= 0@ i--)

-          @{

-          @     x[i + L_FIR - 1] = signal[i] >> 2@

-          @}

-	  VLD1.S16              {Q0, Q1}, [r7]!		    @ signal[0]  ~ signal[15]

-	  VLD1.S16              {Q2, Q3}, [r7]!             @ signal[16] ~ signal[31]

-          VLD1.S16              {Q4, Q5}, [r7]!             @ signal[32] ~ signal[47]

-	  VLD1.S16              {Q6, Q7}, [r7]!             @ signal[48] ~ signal[63]

-	  VLD1.S16              {Q8, Q9}, [r7]!             @ signal[64] ~ signal[79]

-	  VSHR.S16              Q10, Q0, #2

-          VSHR.S16              Q11, Q1, #2

-          VSHR.S16              Q12, Q2, #2

-	  VSHR.S16              Q13, Q3, #2

-	  VST1.S16              {Q10, Q11}, [r6]!

-	  VSHR.S16              Q0,  Q4, #2

-	  VSHR.S16              Q1,  Q5, #2

-	  VSHR.S16              Q10, Q6, #2

-	  VSHR.S16              Q11, Q7, #2

-	  VSHR.S16              Q2,  Q8, #2

-	  VSHR.S16              Q3,  Q9, #2

-	  VST1.S16              {Q12, Q13}, [r6]!

-	  VST1.S16              {Q0, Q1}, [r6]!

-	  VST1.S16              {Q10, Q11}, [r6]!

-	  VST1.S16              {Q2, Q3}, [r6]!

-

-	  MOV                   r12, r5

-          @STR     		r5, [sp, #-4]               @ PUSH  r5 to stack

-          @ not use registers: r4, r10, r12, r14, r5

-          MOV     		r4, r13 

-          MOV     		r5, #0                      @ i = 0    

-         

-          @ r4 --- x[i], r10 ---- fir_6k_7k

-          VLD1.S16              {Q0, Q1}, [r10]!           @fir_6k_7k[0]  ~ fir_6k_7k[15]

-	  VLD1.S16              {Q2, Q3}, [r10]!           @fir_6k_7k[16] ~ fir_6k_7k[31]

-          VMOV.S16              D7[3], r5                        @set fir_6k_7K = 0

-

-	  VLD1.S16              {Q4, Q5}, [r4]!            @x[0]  ~ x[15]

-	  VLD1.S16              {Q6, Q7}, [r4]!            @x[16] ~ X[31]

-	  VLD1.S16              {Q8}, [r4]! 

-          VMOV.S16              Q15, #0	  

-          

-LOOP_6K7K:

-

-          VMULL.S16             Q9,D8,D0[0]                 

-          VMULL.S16             Q10,D9,D1[0] 

-          VMULL.S16             Q11,D9,D0[0]                 

-          VMULL.S16             Q12,D10,D1[0]

-          VEXT.8                Q4,Q4,Q5,#2

-          VMLAL.S16             Q9,D10,D2[0]

-          VMLAL.S16             Q10,D11,D3[0]

-          VMLAL.S16             Q11,D11,D2[0]

-          VMLAL.S16             Q12,D12,D3[0]    

-          VEXT.8                Q5,Q5,Q6,#2

-          VMLAL.S16             Q9,D12,D4[0]

-          VMLAL.S16             Q10,D13,D5[0]

-          VMLAL.S16             Q11,D13,D4[0]

-          VMLAL.S16             Q12,D14,D5[0]

-          VEXT.8                Q6,Q6,Q7,#2

-          VMLAL.S16             Q9,D14,D6[0]

-          VMLAL.S16             Q10,D15,D7[0]

-          VMLAL.S16             Q11,D15,D6[0]

-	  VMLAL.S16             Q12,D16,D7[0]

-	  VEXT.8  		Q7,Q7,Q8,#2 

-

-	  VMLAL.S16 		Q9,D8,D0[1]                

-	  VMLAL.S16     	Q10,D9,D1[1]

-	  VEXT.8 		Q8,Q8,Q15,#2 

-	  VMLAL.S16 		Q11,D9,D0[1]                

-	  VMLAL.S16 		Q12,D10,D1[1]

-	  VEXT.8  		Q4,Q4,Q5,#2

-	  VMLAL.S16 		Q9,D10,D2[1]

-	  VMLAL.S16 		Q10,D11,D3[1]

-	  VMLAL.S16 		Q11,D11,D2[1]

-	  VMLAL.S16 		Q12,D12,D3[1]    

-	  VEXT.8  		Q5,Q5,Q6,#2

-	  VMLAL.S16 		Q9,D12,D4[1]

-	  VMLAL.S16 		Q10,D13,D5[1]

-	  VMLAL.S16 		Q11,D13,D4[1]

-	  VMLAL.S16 		Q12,D14,D5[1]

-	  VEXT.8  		Q6,Q6,Q7,#2

-	  VMLAL.S16 		Q9,D14,D6[1]

-	  VMLAL.S16 		Q10,D15,D7[1]

-	  VMLAL.S16 		Q11,D15,D6[1]

-	  VMLAL.S16 		Q12,D16,D7[1]

-	  VEXT.8  		Q7,Q7,Q8,#2 

-

-	  VMLAL.S16 		Q9,D8,D0[2]           

-	  VMLAL.S16 		Q10,D9,D1[2]

-	  VEXT.8 		Q8,Q8,Q15,#2 

-	  VMLAL.S16 		Q11,D9,D0[2]           

-	  VMLAL.S16 		Q12,D10,D1[2]

-	  VEXT.8  		Q4,Q4,Q5,#2

-	  VMLAL.S16 		Q9,D10,D2[2]

-	  VMLAL.S16 		Q10,D11,D3[2]

-	  VMLAL.S16 		Q11,D11,D2[2]

-	  VMLAL.S16 		Q12,D12,D3[2]    

-	  VEXT.8  		Q5,Q5,Q6,#2

-	  VMLAL.S16 		Q9,D12,D4[2]

-	  VMLAL.S16 		Q10,D13,D5[2]

-	  VMLAL.S16 		Q11,D13,D4[2]

-	  VMLAL.S16 		Q12,D14,D5[2]

-	  VEXT.8  		Q6,Q6,Q7,#2

-	  VMLAL.S16 		Q9,D14,D6[2]

-	  VMLAL.S16 		Q10,D15,D7[2]

-	  VMLAL.S16 		Q11,D15,D6[2]

-	  VMLAL.S16 		Q12,D16,D7[2]

-	  VEXT.8  		Q7,Q7,Q8,#2 

-

-	  VMLAL.S16 		Q9,D8,D0[3]              

-	  VMLAL.S16 		Q10,D9,D1[3]

-	  VEXT.8 		Q8,Q8,Q15,#2 

-	  VMLAL.S16 		Q11,D9,D0[3]              

-	  VMLAL.S16 		Q12,D10,D1[3]

-	  VEXT.8  		Q4,Q4,Q5,#2

-	  VMLAL.S16 		Q9,D10,D2[3]

-	  VMLAL.S16 		Q10,D11,D3[3]

-	  VMLAL.S16 		Q11,D11,D2[3]

-	  VMLAL.S16 		Q12,D12,D3[3]    

-	  VEXT.8  		Q5,Q5,Q6,#2

-	  VMLAL.S16 		Q9,D12,D4[3]

-	  VMLAL.S16 		Q10,D13,D5[3]

-	  VMLAL.S16 		Q11,D13,D4[3]

-	  VMLAL.S16 		Q12,D14,D5[3]

-	  VEXT.8  		Q6,Q6,Q7,#2

-	  VMLAL.S16 		Q9,D14,D6[3]

-	  VMLAL.S16 		Q10,D15,D7[3]

-	  VMLAL.S16 		Q11,D15,D6[3]

-	  VMLAL.S16 		Q12,D16,D7[3]

-	  VEXT.8 		Q7,Q7,Q8,#2     

-

-	  VMOV.S16  		D8,D9

-	  VEXT.8 		Q8,Q8,Q15,#2 

-	  VMOV.S16  		D9,D10

-	  VADD.S32  		Q9,Q9,Q10

-	  VMOV.S16  		D10,D11

-	  VMOV.S16  		D11,D12

-	  VADD.S32  		Q11,Q11,Q12

-	  VMOV.S16  		D12,D13

-	  VQRSHRN.S32 		D28,Q9,#15

-	  VMOV.S16  		D13,D14

-	  VMOV.S16  		D14,D15

-	  VQRSHRN.S32 		D29,Q11,#15

-	  VMOV.S16  		D15,D16

-

-	  VLD1.S16  		{Q8},[r4]!

-	  ADD                   r5, r5, #8

-	  CMP   		r5, #80

-	  VST1.S16  		{D28,D29},[r3]!

-	  BLT     		LOOP_6K7K

-

-          ADD     		r0, r13, #160               @x + lg

-	  MOV                   r1, r12

-	  @LDR     		r1, [sp, #-4]               @mem address

-

-	  VLD1.S16              {D0, D1, D2, D3}, [r0]!

-	  VLD1.S16              {D4, D5, D6, D7}, [r0]!

-

-	  VST1.S16              {D0, D1, D2, D3}, [r1]!

-	  VST1.S16              {D4, D5, D6}, [r1]!

-	  VST1.S16              D7[0], [r1]!

-	  VST1.S16              D7[1], [r1]!

-                    

-Filt_6k_7k_end:

-

-          ADD     		r13, r13, #240  

-          LDMFD   		r13!, {r0 - r12, r15} 

- 

-Lable1:

-          .word   		fir_6k_7k

-          @ENDFUNC

-          .END

-

-

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+@
+@**********************************************************************/
+@void Filt_6k_7k(
+@     Word16 signal[],                      /* input:  signal                  */
+@     Word16 lg,                            /* input:  length of input         */
+@     Word16 mem[]                          /* in/out: memory (size=30)        */
+@)
+@***********************************************************************
+@ r0    ---  signal[]
+@ r1    ---  lg
+@ r2    ---  mem[]
+
+          .section  .text
+          .global   Filt_6k_7k_asm
+          .extern   fir_6k_7k
+
+Filt_6k_7k_asm:
+
+          STMFD   		r13!, {r0 - r12, r14}
+          SUB    		r13, r13, #240              @ x[L_SUBFR16k + (L_FIR - 1)]
+          MOV     		r8, r0                      @ copy signal[] address
+          MOV     		r5, r2                      @ copy mem[] address
+
+          MOV     		r0, r2
+          MOV     		r1, r13
+
+	  VLD1.S16              {D0, D1, D2, D3}, [r0]!
+	  VLD1.S16              {D4, D5, D6, D7}, [r0]!
+
+	  VST1.S16              {D0, D1, D2, D3}, [r1]!
+	  VST1.S16              {D4, D5, D6}, [r1]!
+	  VST1.S16              D7[0], [r1]!
+	  VST1.S16              D7[1], [r1]!
+
+
+
+          LDR     		r10, Lable1                 @ get fir_7k address
+          MOV                   r3, r8                      @ change myMemCopy to Copy, due to Copy will change r3 content
+          ADD     	    	r6, r13, #60                @ get x[L_FIR - 1] address
+          MOV           	r7, r3                      @ get signal[i]
+          @for (i = lg - 1@ i >= 0@ i--)
+          @{
+          @     x[i + L_FIR - 1] = signal[i] >> 2@
+          @}
+	  VLD1.S16              {Q0, Q1}, [r7]!		    @ signal[0]  ~ signal[15]
+	  VLD1.S16              {Q2, Q3}, [r7]!             @ signal[16] ~ signal[31]
+          VLD1.S16              {Q4, Q5}, [r7]!             @ signal[32] ~ signal[47]
+	  VLD1.S16              {Q6, Q7}, [r7]!             @ signal[48] ~ signal[63]
+	  VLD1.S16              {Q8, Q9}, [r7]!             @ signal[64] ~ signal[79]
+	  VSHR.S16              Q10, Q0, #2
+          VSHR.S16              Q11, Q1, #2
+          VSHR.S16              Q12, Q2, #2
+	  VSHR.S16              Q13, Q3, #2
+	  VST1.S16              {Q10, Q11}, [r6]!
+	  VSHR.S16              Q0,  Q4, #2
+	  VSHR.S16              Q1,  Q5, #2
+	  VSHR.S16              Q10, Q6, #2
+	  VSHR.S16              Q11, Q7, #2
+	  VSHR.S16              Q2,  Q8, #2
+	  VSHR.S16              Q3,  Q9, #2
+	  VST1.S16              {Q12, Q13}, [r6]!
+	  VST1.S16              {Q0, Q1}, [r6]!
+	  VST1.S16              {Q10, Q11}, [r6]!
+	  VST1.S16              {Q2, Q3}, [r6]!
+
+	  MOV                   r12, r5
+          @STR     		r5, [sp, #-4]               @ PUSH  r5 to stack
+          @ not use registers: r4, r10, r12, r14, r5
+          MOV     		r4, r13
+          MOV     		r5, #0                      @ i = 0
+
+          @ r4 --- x[i], r10 ---- fir_6k_7k
+          VLD1.S16              {Q0, Q1}, [r10]!           @fir_6k_7k[0]  ~ fir_6k_7k[15]
+	  VLD1.S16              {Q2, Q3}, [r10]!           @fir_6k_7k[16] ~ fir_6k_7k[31]
+          VMOV.S16              D7[3], r5                        @set fir_6k_7K = 0
+
+	  VLD1.S16              {Q4, Q5}, [r4]!            @x[0]  ~ x[15]
+	  VLD1.S16              {Q6, Q7}, [r4]!            @x[16] ~ X[31]
+	  VLD1.S16              {Q8}, [r4]!
+          VMOV.S16              Q15, #0
+
+LOOP_6K7K:
+
+          VMULL.S16             Q9,D8,D0[0]
+          VMULL.S16             Q10,D9,D1[0]
+          VMULL.S16             Q11,D9,D0[0]
+          VMULL.S16             Q12,D10,D1[0]
+          VEXT.8                Q4,Q4,Q5,#2
+          VMLAL.S16             Q9,D10,D2[0]
+          VMLAL.S16             Q10,D11,D3[0]
+          VMLAL.S16             Q11,D11,D2[0]
+          VMLAL.S16             Q12,D12,D3[0]
+          VEXT.8                Q5,Q5,Q6,#2
+          VMLAL.S16             Q9,D12,D4[0]
+          VMLAL.S16             Q10,D13,D5[0]
+          VMLAL.S16             Q11,D13,D4[0]
+          VMLAL.S16             Q12,D14,D5[0]
+          VEXT.8                Q6,Q6,Q7,#2
+          VMLAL.S16             Q9,D14,D6[0]
+          VMLAL.S16             Q10,D15,D7[0]
+          VMLAL.S16             Q11,D15,D6[0]
+	  VMLAL.S16             Q12,D16,D7[0]
+	  VEXT.8  		Q7,Q7,Q8,#2
+
+	  VMLAL.S16 		Q9,D8,D0[1]
+	  VMLAL.S16     	Q10,D9,D1[1]
+	  VEXT.8 		Q8,Q8,Q15,#2
+	  VMLAL.S16 		Q11,D9,D0[1]
+	  VMLAL.S16 		Q12,D10,D1[1]
+	  VEXT.8  		Q4,Q4,Q5,#2
+	  VMLAL.S16 		Q9,D10,D2[1]
+	  VMLAL.S16 		Q10,D11,D3[1]
+	  VMLAL.S16 		Q11,D11,D2[1]
+	  VMLAL.S16 		Q12,D12,D3[1]
+	  VEXT.8  		Q5,Q5,Q6,#2
+	  VMLAL.S16 		Q9,D12,D4[1]
+	  VMLAL.S16 		Q10,D13,D5[1]
+	  VMLAL.S16 		Q11,D13,D4[1]
+	  VMLAL.S16 		Q12,D14,D5[1]
+	  VEXT.8  		Q6,Q6,Q7,#2
+	  VMLAL.S16 		Q9,D14,D6[1]
+	  VMLAL.S16 		Q10,D15,D7[1]
+	  VMLAL.S16 		Q11,D15,D6[1]
+	  VMLAL.S16 		Q12,D16,D7[1]
+	  VEXT.8  		Q7,Q7,Q8,#2
+
+	  VMLAL.S16 		Q9,D8,D0[2]
+	  VMLAL.S16 		Q10,D9,D1[2]
+	  VEXT.8 		Q8,Q8,Q15,#2
+	  VMLAL.S16 		Q11,D9,D0[2]
+	  VMLAL.S16 		Q12,D10,D1[2]
+	  VEXT.8  		Q4,Q4,Q5,#2
+	  VMLAL.S16 		Q9,D10,D2[2]
+	  VMLAL.S16 		Q10,D11,D3[2]
+	  VMLAL.S16 		Q11,D11,D2[2]
+	  VMLAL.S16 		Q12,D12,D3[2]
+	  VEXT.8  		Q5,Q5,Q6,#2
+	  VMLAL.S16 		Q9,D12,D4[2]
+	  VMLAL.S16 		Q10,D13,D5[2]
+	  VMLAL.S16 		Q11,D13,D4[2]
+	  VMLAL.S16 		Q12,D14,D5[2]
+	  VEXT.8  		Q6,Q6,Q7,#2
+	  VMLAL.S16 		Q9,D14,D6[2]
+	  VMLAL.S16 		Q10,D15,D7[2]
+	  VMLAL.S16 		Q11,D15,D6[2]
+	  VMLAL.S16 		Q12,D16,D7[2]
+	  VEXT.8  		Q7,Q7,Q8,#2
+
+	  VMLAL.S16 		Q9,D8,D0[3]
+	  VMLAL.S16 		Q10,D9,D1[3]
+	  VEXT.8 		Q8,Q8,Q15,#2
+	  VMLAL.S16 		Q11,D9,D0[3]
+	  VMLAL.S16 		Q12,D10,D1[3]
+	  VEXT.8  		Q4,Q4,Q5,#2
+	  VMLAL.S16 		Q9,D10,D2[3]
+	  VMLAL.S16 		Q10,D11,D3[3]
+	  VMLAL.S16 		Q11,D11,D2[3]
+	  VMLAL.S16 		Q12,D12,D3[3]
+	  VEXT.8  		Q5,Q5,Q6,#2
+	  VMLAL.S16 		Q9,D12,D4[3]
+	  VMLAL.S16 		Q10,D13,D5[3]
+	  VMLAL.S16 		Q11,D13,D4[3]
+	  VMLAL.S16 		Q12,D14,D5[3]
+	  VEXT.8  		Q6,Q6,Q7,#2
+	  VMLAL.S16 		Q9,D14,D6[3]
+	  VMLAL.S16 		Q10,D15,D7[3]
+	  VMLAL.S16 		Q11,D15,D6[3]
+	  VMLAL.S16 		Q12,D16,D7[3]
+	  VEXT.8 		Q7,Q7,Q8,#2
+
+	  VMOV.S16  		D8,D9
+	  VEXT.8 		Q8,Q8,Q15,#2
+	  VMOV.S16  		D9,D10
+	  VADD.S32  		Q9,Q9,Q10
+	  VMOV.S16  		D10,D11
+	  VMOV.S16  		D11,D12
+	  VADD.S32  		Q11,Q11,Q12
+	  VMOV.S16  		D12,D13
+	  VQRSHRN.S32 		D28,Q9,#15
+	  VMOV.S16  		D13,D14
+	  VMOV.S16  		D14,D15
+	  VQRSHRN.S32 		D29,Q11,#15
+	  VMOV.S16  		D15,D16
+
+	  VLD1.S16  		{Q8},[r4]!
+	  ADD                   r5, r5, #8
+	  CMP   		r5, #80
+	  VST1.S16  		{D28,D29},[r3]!
+	  BLT     		LOOP_6K7K
+
+          ADD     		r0, r13, #160               @x + lg
+	  MOV                   r1, r12
+	  @LDR     		r1, [sp, #-4]               @mem address
+
+	  VLD1.S16              {D0, D1, D2, D3}, [r0]!
+	  VLD1.S16              {D4, D5, D6, D7}, [r0]!
+
+	  VST1.S16              {D0, D1, D2, D3}, [r1]!
+	  VST1.S16              {D4, D5, D6}, [r1]!
+	  VST1.S16              D7[0], [r1]!
+	  VST1.S16              D7[1], [r1]!
+
+Filt_6k_7k_end:
+
+          ADD     		r13, r13, #240
+          LDMFD   		r13!, {r0 - r12, r15}
+
+Lable1:
+          .word   		fir_6k_7k
+          @ENDFUNC
+          .END
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Norm_Corr_neon.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Norm_Corr_neon.s
index 60e9ade..4263cd4 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Norm_Corr_neon.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Norm_Corr_neon.s
@@ -33,7 +33,7 @@
 
 
 	.section  .text
-        .global    Norm_corr_asm 
+        .global    Norm_corr_asm
         .extern    Convolve_asm
         .extern    Isqrt_n
 @******************************
@@ -47,17 +47,17 @@
 .equ    T_MIN             , 212
 .equ    T_MAX             , 216
 .equ    CORR_NORM         , 220
-                  
+
 Norm_corr_asm:
 
-        STMFD          r13!, {r4 - r12, r14}  
+        STMFD          r13!, {r4 - r12, r14}
         SUB            r13, r13, #voSTACK
-  
+
         ADD            r8, r13, #20                 @get the excf[L_SUBFR]
         LDR            r4, [r13, #T_MIN]            @get t_min
         RSB            r11, r4, #0                  @k = -t_min
-        ADD            r5, r0, r11, LSL #1          @get the &exc[k]   
-        
+        ADD            r5, r0, r11, LSL #1          @get the &exc[k]
+
         @transfer Convolve function
         STMFD          sp!, {r0 - r3}
         MOV            r0, r5
@@ -68,7 +68,7 @@
 
         @ r8 --- excf[]
 
-	MOV            r14, r1                       @copy xn[] address                      
+	MOV            r14, r1                       @copy xn[] address
         MOV            r7, #1
 	VLD1.S16       {Q0, Q1}, [r14]!
 	VLD1.S16       {Q2, Q3}, [r14]!
@@ -95,34 +95,34 @@
         VQADD.S32      D20, D20, D21
         VMOV.S32       r9,  D20[0]
         VMOV.S32       r10, D20[1]
-        QADD           r6, r9, r10 
+        QADD           r6, r9, r10
 	QADD           r6, r6, r6
         QADD           r9, r6, r7                   @L_tmp = (L_tmp << 1) + 1;
 	CLZ            r7, r9
 	SUB            r6, r7, #1                   @exp = norm_l(L_tmp)
         RSB            r7, r6, #32                  @exp = 32 - exp
-	MOV            r6, r7, ASR #1         
+	MOV            r6, r7, ASR #1
 	RSB            r7, r6, #0                   @scale = -(exp >> 1)
-	
+
         @loop for every possible period
 	@for(t = t_min@ t <= t_max@ t++)
 	@r7 --- scale r4 --- t_min r8 --- excf[]
 
-LOOPFOR:	
+LOOPFOR:
 	ADD            r14, r13, #20                @copy of excf[]
 	MOV            r12, r1                      @copy of xn[]
 	MOV            r8, #0x8000
 
         VLD1.S16       {Q0, Q1}, [r14]!                 @ load 16 excf[]
-        VLD1.S16       {Q2, Q3}, [r14]!                 @ load 16 excf[]       
+        VLD1.S16       {Q2, Q3}, [r14]!                 @ load 16 excf[]
         VLD1.S16       {Q4, Q5}, [r12]!                 @ load 16 x[]
 	VLD1.S16       {Q6, Q7}, [r12]!                 @ load 16 x[]
         VMULL.S16    Q10, D0, D0                      @L_tmp1 += excf[] * excf[]
-        VMULL.S16    Q11, D0, D8                      @L_tmp  += x[] * excf[]                   
+        VMULL.S16    Q11, D0, D8                      @L_tmp  += x[] * excf[]
         VMLAL.S16    Q10, D1, D1
         VMLAL.S16    Q11, D1, D9
         VMLAL.S16    Q10, D2, D2
-        VMLAL.S16    Q11, D2, D10        
+        VMLAL.S16    Q11, D2, D10
         VMLAL.S16    Q10, D3, D3
         VMLAL.S16    Q11, D3, D11
         VMLAL.S16    Q10, D4, D4
@@ -143,7 +143,7 @@
         VMLAL.S16    Q10, D1, D1
         VMLAL.S16    Q11, D1, D9
         VMLAL.S16    Q10, D2, D2
-        VMLAL.S16    Q11, D2, D10        
+        VMLAL.S16    Q11, D2, D10
         VMLAL.S16    Q10, D3, D3
         VMLAL.S16    Q11, D3, D11
         VMLAL.S16    Q10, D4, D4
@@ -162,19 +162,19 @@
 	VPADD.S32      D22, D22, D22                   @D22[0] --- L_tmp << 1
 
 	VMOV.S32       r6, D20[0]
-        VMOV.S32       r5, D22[0]	
+        VMOV.S32       r5, D22[0]
 
 	@r5 --- L_tmp, r6 --- L_tmp1
 	MOV            r10, #1
 	ADD            r5, r10, r5, LSL #1                     @L_tmp = (L_tmp << 1) + 1
 	ADD            r6, r10, r6, LSL #1                     @L_tmp1 = (L_tmp1 << 1) + 1
- 
-	CLZ            r10, r5        
+
+	CLZ            r10, r5
 	CMP            r5, #0
 	RSBLT          r11, r5, #0
 	CLZLT          r10, r11
 	SUB            r10, r10, #1                 @exp = norm_l(L_tmp)
-     
+
 	MOV            r5, r5, LSL r10              @L_tmp = (L_tmp << exp)
 	RSB            r10, r10, #30                @exp_corr = 30 - exp
 	MOV            r11, r5, ASR #16             @corr = extract_h(L_tmp)
@@ -190,7 +190,7 @@
 	@Isqrt_n(&L_tmp, &exp_norm)
 
 	MOV            r14, r0
-	MOV            r12, r1 
+	MOV            r12, r1
 
         STMFD          sp!, {r0 - r4, r7 - r12, r14}
 	ADD            r1, sp, #4
@@ -208,7 +208,7 @@
 	MOV            r6, r6, ASR #16              @norm = extract_h(L_tmp)
 	MUL            r12, r6, r11
 	ADD            r12, r12, r12                @L_tmp = vo_L_mult(corr, norm)
-  
+
 	ADD            r6, r10, r5
 	ADD            r6, r6, r7                   @exp_corr + exp_norm + scale
 
@@ -227,8 +227,8 @@
 
 	CMP            r4, r6
 	BEQ            Norm_corr_asm_end
- 
-	ADD            r4, r4, #1                   @ t_min ++ 
+
+	ADD            r4, r4, #1                   @ t_min ++
 	RSB            r5, r4, #0                   @ k
 
 	MOV            r6, #63                      @ i = 63
@@ -255,16 +255,16 @@
 	MUL            r14, r11, r8
         LDR            r6, [r13, #T_MAX]            @ get t_max
 	MOV            r8, r14, ASR #15
-	STRH           r8, [r10]                    
+	STRH           r8, [r10]
 
 	CMP            r4, r6
 	BLE            LOOPFOR
 
-Norm_corr_asm_end: 
-        
-        ADD            r13, r13, #voSTACK      
+Norm_corr_asm_end:
+
+        ADD            r13, r13, #voSTACK
         LDMFD          r13!, {r4 - r12, r15}
-    
+
         .END
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Syn_filt_32_neon.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Syn_filt_32_neon.s
index cb1764f..e786dde 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Syn_filt_32_neon.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Syn_filt_32_neon.s
@@ -1,133 +1,133 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-@

-@**********************************************************************/

-@void Syn_filt_32(

-@     Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients */

-@     Word16 m,                             /* (i)     : order of LP filter             */

-@     Word16 exc[],                         /* (i) Qnew: excitation (exc[i] >> Qnew)    */

-@     Word16 Qnew,                          /* (i)     : exc scaling = 0(min) to 8(max) */

-@     Word16 sig_hi[],                      /* (o) /16 : synthesis high                 */

-@     Word16 sig_lo[],                      /* (o) /16 : synthesis low                  */

-@     Word16 lg                             /* (i)     : size of filtering              */

-@)

-@***********************************************************************

-@ a[]      --- r0

-@ m        --- r1

-@ exc[]    --- r2

-@ Qnew     --- r3

-@ sig_hi[] --- r4

-@ sig_lo[] --- r5

-@ lg       --- r6

-

-          .section  .text 

-          .global   Syn_filt_32_asm

-

-Syn_filt_32_asm:

-

-          STMFD   	r13!, {r4 - r12, r14} 

-          LDR           r4,  [r13, #40]                  @ get sig_hi[] address

-          LDR           r5,  [r13, #44]                  @ get sig_lo[] address

-

-          LDRSH         r6,  [r0], #2                    @ load Aq[0]

-          ADD           r7,  r3, #4                      @ 4 + Q_new

-          MOV           r3, r6, ASR r7                   @ a0 = Aq[0] >> (4 + Q_new)

-

-	  SUB           r10, r4, #32                     @ sig_hi[-16] address

-	  SUB           r11, r5, #32                     @ sig_lo[-16] address

-

-	  VLD1.S16      {D0, D1, D2, D3}, [r0]!          @a[1] ~ a[16] 

-  

-          MOV           r8, #0                           @ i = 0

-

-	  VLD1.S16      {D4, D5, D6, D7}, [r10]!         @ sig_hi[-16] ~ sig_hi[-1]

-          VREV64.16     D0, D0

-          VREV64.16     D1, D1

-	  VLD1.S16      {D8, D9, D10, D11}, [r11]!       @ sig_lo[-16] ~ sig_lo[-1]

-          VREV64.16     D2, D2

-          VREV64.16     D3, D3	

-          VDUP.S32      Q15, r8

-              

-SYN_LOOP:

-

-          LDRSH         r6, [r2], #2                     @exc[i]

-	  @L_tmp = L_msu(L_tmp, sig_lo[i - j], a[j])@

-	  VMULL.S16     Q10, D8, D3

-	  VEXT.8        D8, D8, D9, #2

-	  VMLAL.S16     Q10, D9, D2

-	  VMLAL.S16     Q10, D10, D1

-	  VMLAL.S16     Q10, D11, D0

-

-	  VEXT.8        D9, D9, D10, #2

-	  VEXT.8        D10, D10, D11, #2

-	  

-	  VPADD.S32     D28, D20, D21

-          MUL           r12, r6, r3                      @exc[i] * a0

-	  VPADD.S32     D29, D28, D28

-	  VDUP.S32      Q10, D29[0]                      @result1

-          

-	  VMULL.S16     Q11, D4, D3

-	  VMLAL.S16     Q11, D5, D2

-          VSUB.S32      Q10, Q15, Q10

-	  @L_tmp = L_msu(L_tmp, sig_hi[i - j], a[j])@

-

-	  VMLAL.S16     Q11, D6, D1

-	  VEXT.8        D4, D4, D5, #2

-	  VMLAL.S16     Q11, D7, D0

-

-

-	  VEXT.8        D5, D5, D6, #2

-	  VEXT.8        D6, D6, D7, #2

-

-	  VPADD.S32     D28, D22, D23

-          VPADD.S32     D29, D28, D28

-          MOV           r14, r12, LSL #1                 @exc[i] * a0 << 1

-          VDUP.S32      Q11, D29[0]                      @result2

-

-

-

-	  VSHR.S32      Q10, Q10, #11                    @result1 >>= 11

-	  VSHL.S32      Q11, Q11, #1                     @result2 <<= 1

-	  VDUP.S32      Q12, r14                         

-	  VADD.S32      Q12, Q12, Q10                    @L_tmp = L_tmp - (result1 >>= 11) - (result2 <<= 1)

-	  VSUB.S32      Q12, Q12, Q11

-

-	  VSHL.S32      Q12, Q12, #3                     @L_tmp <<= 3

-

-

-	  VSHRN.S32     D20, Q12, #16                    @sig_hi[i] = L_tmp >> 16@

-	  VMOV.S16      r10, D20[0]

-	  VSHR.S32      Q12, Q12, #4                     @L_tmp >>= 4

-	  VEXT.8        D7, D7, D20, #2

-	  STRH          r10, [r4], #2                    @store sig_hi[i]

-          VMOV.S32      r11, D24[0]                      @r11 --- L_tmp >>= 4

-	  ADD           r8, r8, #1

-	  SUB           r12, r11, r10, LSL #12

-	  @MOV           r11, r12, ASR #16                @sig_lo[i]

-	  VDUP.S16      D21, r12

-	  VEXT.8        D11, D11, D21, #2

-	  STRH          r12, [r5], #2                    @stroe sig_lo[i]

-

-          CMP           r8, #64

-          BLT           SYN_LOOP                          

-         

-Syn_filt_32_end:

-		     

-          LDMFD   	    r13!, {r4 - r12, r15} 

-          @ENDFUNC

-          .END

- 

-

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+@
+@**********************************************************************/
+@void Syn_filt_32(
+@     Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients */
+@     Word16 m,                             /* (i)     : order of LP filter             */
+@     Word16 exc[],                         /* (i) Qnew: excitation (exc[i] >> Qnew)    */
+@     Word16 Qnew,                          /* (i)     : exc scaling = 0(min) to 8(max) */
+@     Word16 sig_hi[],                      /* (o) /16 : synthesis high                 */
+@     Word16 sig_lo[],                      /* (o) /16 : synthesis low                  */
+@     Word16 lg                             /* (i)     : size of filtering              */
+@)
+@***********************************************************************
+@ a[]      --- r0
+@ m        --- r1
+@ exc[]    --- r2
+@ Qnew     --- r3
+@ sig_hi[] --- r4
+@ sig_lo[] --- r5
+@ lg       --- r6
+
+          .section  .text
+          .global   Syn_filt_32_asm
+
+Syn_filt_32_asm:
+
+          STMFD   	r13!, {r4 - r12, r14}
+          LDR           r4,  [r13, #40]                  @ get sig_hi[] address
+          LDR           r5,  [r13, #44]                  @ get sig_lo[] address
+
+          LDRSH         r6,  [r0], #2                    @ load Aq[0]
+          ADD           r7,  r3, #4                      @ 4 + Q_new
+          MOV           r3, r6, ASR r7                   @ a0 = Aq[0] >> (4 + Q_new)
+
+	  SUB           r10, r4, #32                     @ sig_hi[-16] address
+	  SUB           r11, r5, #32                     @ sig_lo[-16] address
+
+	  VLD1.S16      {D0, D1, D2, D3}, [r0]!          @a[1] ~ a[16]
+
+          MOV           r8, #0                           @ i = 0
+
+	  VLD1.S16      {D4, D5, D6, D7}, [r10]!         @ sig_hi[-16] ~ sig_hi[-1]
+          VREV64.16     D0, D0
+          VREV64.16     D1, D1
+	  VLD1.S16      {D8, D9, D10, D11}, [r11]!       @ sig_lo[-16] ~ sig_lo[-1]
+          VREV64.16     D2, D2
+          VREV64.16     D3, D3
+          VDUP.S32      Q15, r8
+
+SYN_LOOP:
+
+          LDRSH         r6, [r2], #2                     @exc[i]
+	  @L_tmp = L_msu(L_tmp, sig_lo[i - j], a[j])@
+	  VMULL.S16     Q10, D8, D3
+	  VEXT.8        D8, D8, D9, #2
+	  VMLAL.S16     Q10, D9, D2
+	  VMLAL.S16     Q10, D10, D1
+	  VMLAL.S16     Q10, D11, D0
+
+	  VEXT.8        D9, D9, D10, #2
+	  VEXT.8        D10, D10, D11, #2
+
+	  VPADD.S32     D28, D20, D21
+          MUL           r12, r6, r3                      @exc[i] * a0
+	  VPADD.S32     D29, D28, D28
+	  VDUP.S32      Q10, D29[0]                      @result1
+
+	  VMULL.S16     Q11, D4, D3
+	  VMLAL.S16     Q11, D5, D2
+          VSUB.S32      Q10, Q15, Q10
+	  @L_tmp = L_msu(L_tmp, sig_hi[i - j], a[j])@
+
+	  VMLAL.S16     Q11, D6, D1
+	  VEXT.8        D4, D4, D5, #2
+	  VMLAL.S16     Q11, D7, D0
+
+
+	  VEXT.8        D5, D5, D6, #2
+	  VEXT.8        D6, D6, D7, #2
+
+	  VPADD.S32     D28, D22, D23
+          VPADD.S32     D29, D28, D28
+          MOV           r14, r12, LSL #1                 @exc[i] * a0 << 1
+          VDUP.S32      Q11, D29[0]                      @result2
+
+
+
+	  VSHR.S32      Q10, Q10, #11                    @result1 >>= 11
+	  VSHL.S32      Q11, Q11, #1                     @result2 <<= 1
+	  VDUP.S32      Q12, r14
+	  VADD.S32      Q12, Q12, Q10                    @L_tmp = L_tmp - (result1 >>= 11) - (result2 <<= 1)
+	  VSUB.S32      Q12, Q12, Q11
+
+	  VSHL.S32      Q12, Q12, #3                     @L_tmp <<= 3
+
+
+	  VSHRN.S32     D20, Q12, #16                    @sig_hi[i] = L_tmp >> 16@
+	  VMOV.S16      r10, D20[0]
+	  VSHR.S32      Q12, Q12, #4                     @L_tmp >>= 4
+	  VEXT.8        D7, D7, D20, #2
+	  STRH          r10, [r4], #2                    @store sig_hi[i]
+          VMOV.S32      r11, D24[0]                      @r11 --- L_tmp >>= 4
+	  ADD           r8, r8, #1
+	  SUB           r12, r11, r10, LSL #12
+	  @MOV           r11, r12, ASR #16                @sig_lo[i]
+	  VDUP.S16      D21, r12
+	  VEXT.8        D11, D11, D21, #2
+	  STRH          r12, [r5], #2                    @stroe sig_lo[i]
+
+          CMP           r8, #64
+          BLT           SYN_LOOP
+
+Syn_filt_32_end:
+
+          LDMFD   	    r13!, {r4 - r12, r15}
+          @ENDFUNC
+          .END
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/convolve_neon.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/convolve_neon.s
index 189e33b..8efa9fb 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/convolve_neon.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/convolve_neon.s
@@ -20,22 +20,22 @@
 @*    Word16 y[],        /* (o)     : output vector                          */
 @*    Word16 L           /* (i)     : vector size                            */
 @*)
-@ 
+@
 @ r0 --- x[]
 @ r1 --- h[]
 @ r2 --- y[]
 @ r3 --- L
 
-	.section  .text 
-        .global   Convolve_asm 
+	.section  .text
+        .global   Convolve_asm
 
 Convolve_asm:
 
-        STMFD          r13!, {r4 - r12, r14}  
-        MOV            r3,  #0                        
+        STMFD          r13!, {r4 - r12, r14}
+        MOV            r3,  #0
 	MOV            r11, #0x8000
-        
-LOOP: 
+
+LOOP:
         @MOV            r8, #0                            @ s = 0
         ADD            r4, r1, r3, LSL #1                @ tmpH address
         ADD            r5, r3, #1                        @ i = n + 1
@@ -43,21 +43,21 @@
         LDRSH          r9,  [r6], #2                     @ *tmpX++
         LDRSH          r10, [r4]                         @ *tmpH--
         SUB            r5, r5, #1
-        VMOV.S32       Q10, #0 
-        MUL            r8,  r9, r10 
+        VMOV.S32       Q10, #0
+        MUL            r8,  r9, r10
 
-LOOP1:                    
+LOOP1:
         CMP            r5, #0
         BLE            L1
         SUB            r4, r4, #8
         MOV            r9, r4
-        VLD1.S16       D0, [r6]!   
+        VLD1.S16       D0, [r6]!
         VLD1.S16       D1, [r9]!
         VREV64.16      D1, D1
-        SUBS           r5, r5, #4  
-        VMLAL.S16      Q10, D0, D1         
-        B              LOOP1    
-L1:                  
+        SUBS           r5, r5, #4
+        VMLAL.S16      Q10, D0, D1
+        B              LOOP1
+L1:
         VADD.S32       D20, D20, D21
         VPADD.S32      D20, D20, D20
         VMOV.S32       r5, D20[0]
@@ -73,25 +73,25 @@
         ADD            r5, r3, #1
         MOV            r6, r0
         LDRSH          r9,  [r6], #2                     @ *tmpX++
-        LDRSH          r10, [r4], #-2                     
+        LDRSH          r10, [r4], #-2
         LDRSH          r12, [r6], #2
         LDRSH          r14, [r4]
 
         MUL            r8, r9, r10
         SUB            r5, r5, #2
         MLA            r8, r12, r14, r8
-        
+
         VMOV.S32       Q10, #0
 LOOP2:
         CMP            r5, #0
         BLE            L2
         SUB            r4, r4, #8
         MOV            r9, r4
-        VLD1.S16       D0, [r6]!   
+        VLD1.S16       D0, [r6]!
         VLD1.S16       D1, [r9]!
         SUBS           r5, r5, #4
         VREV64.16      D1, D1
-        VMLAL.S16      Q10, D0, D1 
+        VMLAL.S16      Q10, D0, D1
         B              LOOP2
 L2:
         VADD.S32       D20, D20, D21
@@ -100,7 +100,7 @@
         ADD            r8, r8, r5
         ADD            r8, r11, r8, LSL #1
         MOV            r8, r8, LSR #16                   @extract_h(s)
-        ADD            r3, r3, #1  
+        ADD            r3, r3, #1
         STRH           r8, [r2], #2                      @y[n]
 
 
@@ -115,7 +115,7 @@
         MUL            r8, r9, r10
         LDRSH          r9,  [r6], #2
         LDRSH          r10, [r4]
-        MLA            r8, r12, r14, r8 
+        MLA            r8, r12, r14, r8
         SUB            r5, r5, #3
         MLA            r8, r9, r10, r8
 
@@ -125,12 +125,12 @@
         BLE            L3
         SUB            r4, r4, #8
         MOV            r9, r4
-        VLD1.S16       D0, [r6]!   
+        VLD1.S16       D0, [r6]!
         VLD1.S16       D1, [r9]!
         VREV64.16      D1, D1
         SUBS           r5, r5, #4
-        VMLAL.S16      Q10, D0, D1 
-        B              LOOP3   
+        VMLAL.S16      Q10, D0, D1
+        B              LOOP3
 
 L3:
         VADD.S32       D20, D20, D21
@@ -146,18 +146,18 @@
         ADD            r4, r1, r5, LSL #1                @ tmpH address
         MOV            r6, r0
         VMOV.S32       Q10, #0
-LOOP4:                    
+LOOP4:
         CMP            r5, #0
         BLE            L4
         SUB            r4, r4, #8
         MOV            r9, r4
-        VLD1.S16       D0, [r6]!   
+        VLD1.S16       D0, [r6]!
         VLD1.S16       D1, [r9]!
         VREV64.16      D1, D1
-        SUBS           r5, r5, #4  
-        VMLAL.S16      Q10, D0, D1         
-        B              LOOP4    
-L4:                  
+        SUBS           r5, r5, #4
+        VMLAL.S16      Q10, D0, D1
+        B              LOOP4
+L4:
         VADD.S32       D20, D20, D21
         VPADD.S32      D20, D20, D20
         VMOV.S32       r5,  D20[0]
@@ -165,14 +165,14 @@
         MOV            r5, r5, LSR #16                   @extract_h(s)
         ADD            r3, r3, #1
         STRH           r5, [r2], #2                      @y[n]
-        
+
         CMP            r3, #64
         BLT            LOOP
-                
-Convolve_asm_end: 
- 
+
+Convolve_asm_end:
+
         LDMFD      r13!, {r4 - r12, r15}
-    
+
         @ENDFUNC
         .END
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/cor_h_vec_neon.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/cor_h_vec_neon.s
index 2e339db..8904289 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/cor_h_vec_neon.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/cor_h_vec_neon.s
@@ -1,151 +1,151 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-@

-@static void cor_h_vec_012(

-@		Word16 h[],                           /* (i) scaled impulse response                 */

-@		Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */

-@		Word16 track,                         /* (i) track to use                            */

-@		Word16 sign[],                        /* (i) sign vector                             */

-@		Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */

-@		Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */

-@		Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */

-@)

-@r0 ---- h[]

-@r1 ---- vec[]

-@r2 ---- track

-@r3 ---- sign[]

-@r4 ---- rrixix[][NB_POS]

-@r5 ---- cor_1[]

-@r6 ---- cor_2[]

-

-              .section .text 

-	      .global  cor_h_vec_012_asm

-

-cor_h_vec_012_asm:

-

-             STMFD         r13!, {r4 - r12, r14}

-	     LDR           r4, [r13, #40]                    @load rrixix[][NB_POS]

-	     ADD           r7, r4, r2, LSL #5                @r7 --- p0 = rrixix[track]

-             MOV           r4, #0                            @i=0

-

-	     @r0 --- h[], r1 --- vec[],  r2 --- pos

-	     @r3 --- sign[], r4 --- i, r7 --- p0

-

-LOOPi:

-             MOV           r5, #0                            @L_sum1 = 0

-	     MOV           r6, #0                            @L_sum2 = 0

-	     ADD           r9, r1, r2, LSL #1                @p2 = &vec[pos]

-	     MOV           r10, r0                           @p1 = h

-	     RSB           r11, r2, #62                      @j=62-pos

-

-LOOPj1:

-	     LDRSH         r12, [r10], #2  

-	     LDRSH         r8,  [r9], #2

-	     LDRSH         r14, [r9]

-	     SUBS          r11, r11, #1

-             MLA           r5, r12, r8, r5

-             MLA           r6, r12, r14, r6	 

-	     BGE           LOOPj1

-

-	     LDRSH         r12, [r10], #2                     @*p1++

-	     MOV           r6, r6, LSL #2                     @L_sum2 = (L_sum2 << 2)

-             MLA           r5, r12, r14, r5

-             MOV           r14, #0x8000

-             MOV           r5, r5, LSL #2                     @L_sum1 = (L_sum1 << 2)

-             ADD           r10, r6, r14         

-             ADD           r9, r5, r14

-             MOV           r5, r9, ASR #16

-             MOV           r6, r10, ASR #16

-             ADD           r9, r3, r2, LSL #1                 @address of sign[pos]

-             ADD           r8, r7, #32

-             LDRSH         r10, [r9], #2                 	  @sign[pos]

-	     LDRSH         r11, [r9]                          @sign[pos + 1]

-	     MUL           r12, r5, r10

-	     MUL           r14, r6, r11

-	     MOV           r5, r12, ASR #15

-	     MOV           r6, r14, ASR #15

-	     LDR           r9,  [r13, #44]                   

-	     LDR           r12, [r13, #48]

-             LDRSH         r10, [r7], #2                      @*p0++

-	     LDRSH         r11, [r8]                          @*p3++

-             ADD           r9, r9, r4, LSL #1

-	     ADD           r12, r12, r4, LSL #1

-	     ADD           r5, r5, r10

-	     ADD           r6, r6, r11

-	     STRH          r5, [r9]

-	     STRH          r6, [r12]

-

-             ADD           r2, r2, #4

- 

-             MOV           r5, #0                            @L_sum1 = 0

-	     MOV           r6, #0                            @L_sum2 = 0

-	     ADD           r9, r1, r2, LSL #1                @p2 = &vec[pos]

-	     MOV           r10, r0                           @p1 = h

-	     RSB           r11, r2, #62                      @j=62-pos

-	     ADD           r4, r4, #1                        @i++

-

-LOOPj2:

-	     LDRSH         r12, [r10], #2  

-	     LDRSH         r8,  [r9], #2

-	     LDRSH         r14, [r9]

-	     SUBS          r11, r11, #1

-             MLA           r5, r12, r8, r5

-             MLA           r6, r12, r14, r6	 

-	     BGE           LOOPj2

-

-	     LDRSH         r12, [r10], #2                     @*p1++

-	     MOV           r6, r6, LSL #2                     @L_sum2 = (L_sum2 << 2)

-             MLA           r5, r12, r14, r5

-             MOV           r14, #0x8000

-             MOV           r5, r5, LSL #2                     @L_sum1 = (L_sum1 << 2)

-             ADD           r10, r6, r14        

-             ADD           r9, r5, r14

-

-             MOV           r5, r9, ASR #16

-             MOV           r6, r10, ASR #16

-             ADD           r9, r3, r2, LSL #1                 @address of sign[pos]

-             ADD           r8, r7, #32

-             LDRSH         r10, [r9], #2                 	  @sign[pos]

-	     LDRSH         r11, [r9]                          @sign[pos + 1]

-	     MUL           r12, r5, r10

-	     MUL           r14, r6, r11

-	     MOV           r5, r12, ASR #15

-	     MOV           r6, r14, ASR #15

-	     LDR           r9,  [r13, #44]                   

-	     LDR           r12, [r13, #48]

-             LDRSH         r10, [r7], #2                      @*p0++

-	     LDRSH         r11, [r8]                          @*p3++

-             ADD           r9, r9, r4, LSL #1

-	     ADD           r12, r12, r4, LSL #1

-	     ADD           r5, r5, r10

-	     ADD           r6, r6, r11

-	     STRH          r5, [r9]

-	     STRH          r6, [r12]

-	     ADD           r4, r4, #1                         @i+1

-	     ADD           r2, r2, #4                         @pos += STEP

-	     CMP           r4, #16

-	     

-	     BLT           LOOPi

-         

-the_end:

-             LDMFD         r13!, {r4 - r12, r15}

-             

-	     .END	 

-        

-	

-	  

-

-

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+@
+@static void cor_h_vec_012(
+@		Word16 h[],                           /* (i) scaled impulse response                 */
+@		Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */
+@		Word16 track,                         /* (i) track to use                            */
+@		Word16 sign[],                        /* (i) sign vector                             */
+@		Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */
+@		Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */
+@		Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */
+@)
+@r0 ---- h[]
+@r1 ---- vec[]
+@r2 ---- track
+@r3 ---- sign[]
+@r4 ---- rrixix[][NB_POS]
+@r5 ---- cor_1[]
+@r6 ---- cor_2[]
+
+              .section .text
+	      .global  cor_h_vec_012_asm
+
+cor_h_vec_012_asm:
+
+             STMFD         r13!, {r4 - r12, r14}
+	     LDR           r4, [r13, #40]                    @load rrixix[][NB_POS]
+	     ADD           r7, r4, r2, LSL #5                @r7 --- p0 = rrixix[track]
+             MOV           r4, #0                            @i=0
+
+	     @r0 --- h[], r1 --- vec[],  r2 --- pos
+	     @r3 --- sign[], r4 --- i, r7 --- p0
+
+LOOPi:
+             MOV           r5, #0                            @L_sum1 = 0
+	     MOV           r6, #0                            @L_sum2 = 0
+	     ADD           r9, r1, r2, LSL #1                @p2 = &vec[pos]
+	     MOV           r10, r0                           @p1 = h
+	     RSB           r11, r2, #62                      @j=62-pos
+
+LOOPj1:
+	     LDRSH         r12, [r10], #2
+	     LDRSH         r8,  [r9], #2
+	     LDRSH         r14, [r9]
+	     SUBS          r11, r11, #1
+             MLA           r5, r12, r8, r5
+             MLA           r6, r12, r14, r6
+	     BGE           LOOPj1
+
+	     LDRSH         r12, [r10], #2                     @*p1++
+	     MOV           r6, r6, LSL #2                     @L_sum2 = (L_sum2 << 2)
+             MLA           r5, r12, r14, r5
+             MOV           r14, #0x8000
+             MOV           r5, r5, LSL #2                     @L_sum1 = (L_sum1 << 2)
+             ADD           r10, r6, r14
+             ADD           r9, r5, r14
+             MOV           r5, r9, ASR #16
+             MOV           r6, r10, ASR #16
+             ADD           r9, r3, r2, LSL #1                 @address of sign[pos]
+             ADD           r8, r7, #32
+             LDRSH         r10, [r9], #2                 	  @sign[pos]
+	     LDRSH         r11, [r9]                          @sign[pos + 1]
+	     MUL           r12, r5, r10
+	     MUL           r14, r6, r11
+	     MOV           r5, r12, ASR #15
+	     MOV           r6, r14, ASR #15
+	     LDR           r9,  [r13, #44]
+	     LDR           r12, [r13, #48]
+             LDRSH         r10, [r7], #2                      @*p0++
+	     LDRSH         r11, [r8]                          @*p3++
+             ADD           r9, r9, r4, LSL #1
+	     ADD           r12, r12, r4, LSL #1
+	     ADD           r5, r5, r10
+	     ADD           r6, r6, r11
+	     STRH          r5, [r9]
+	     STRH          r6, [r12]
+
+             ADD           r2, r2, #4
+
+             MOV           r5, #0                            @L_sum1 = 0
+	     MOV           r6, #0                            @L_sum2 = 0
+	     ADD           r9, r1, r2, LSL #1                @p2 = &vec[pos]
+	     MOV           r10, r0                           @p1 = h
+	     RSB           r11, r2, #62                      @j=62-pos
+	     ADD           r4, r4, #1                        @i++
+
+LOOPj2:
+	     LDRSH         r12, [r10], #2
+	     LDRSH         r8,  [r9], #2
+	     LDRSH         r14, [r9]
+	     SUBS          r11, r11, #1
+             MLA           r5, r12, r8, r5
+             MLA           r6, r12, r14, r6
+	     BGE           LOOPj2
+
+	     LDRSH         r12, [r10], #2                     @*p1++
+	     MOV           r6, r6, LSL #2                     @L_sum2 = (L_sum2 << 2)
+             MLA           r5, r12, r14, r5
+             MOV           r14, #0x8000
+             MOV           r5, r5, LSL #2                     @L_sum1 = (L_sum1 << 2)
+             ADD           r10, r6, r14
+             ADD           r9, r5, r14
+
+             MOV           r5, r9, ASR #16
+             MOV           r6, r10, ASR #16
+             ADD           r9, r3, r2, LSL #1                 @address of sign[pos]
+             ADD           r8, r7, #32
+             LDRSH         r10, [r9], #2                 	  @sign[pos]
+	     LDRSH         r11, [r9]                          @sign[pos + 1]
+	     MUL           r12, r5, r10
+	     MUL           r14, r6, r11
+	     MOV           r5, r12, ASR #15
+	     MOV           r6, r14, ASR #15
+	     LDR           r9,  [r13, #44]
+	     LDR           r12, [r13, #48]
+             LDRSH         r10, [r7], #2                      @*p0++
+	     LDRSH         r11, [r8]                          @*p3++
+             ADD           r9, r9, r4, LSL #1
+	     ADD           r12, r12, r4, LSL #1
+	     ADD           r5, r5, r10
+	     ADD           r6, r6, r11
+	     STRH          r5, [r9]
+	     STRH          r6, [r12]
+	     ADD           r4, r4, #1                         @i+1
+	     ADD           r2, r2, #4                         @pos += STEP
+	     CMP           r4, #16
+
+	     BLT           LOOPi
+
+the_end:
+             LDMFD         r13!, {r4 - r12, r15}
+
+	     .END
+
+
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/pred_lt4_1_neon.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/pred_lt4_1_neon.s
index 3b8853f..6b782cb 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/pred_lt4_1_neon.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/pred_lt4_1_neon.s
@@ -1,100 +1,100 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-@

-@void Pred_lt4(

-@     Word16 exc[],                         /* in/out: excitation buffer */

-@     Word16 T0,                            /* input : integer pitch lag */

-@     Word16 frac,                          /* input : fraction of lag   */

-@     Word16 L_subfr                        /* input : subframe size     */

-@)

-@***********************************************************************

-@ r0    ---  exc[]

-@ r1    ---  T0

-@ r2    ---  frac

-@ r3    ---  L_subfr

- 

-          .section  .text 

-          .global   pred_lt4_asm

-          .extern   inter4_2

-

-pred_lt4_asm:

-

-          STMFD   	r13!, {r4 - r12, r14} 

-          SUB           r4, r0, r1, LSL #1                        @ x = exc - T0

-          RSB           r2, r2, #0                                @ frac = - frac

-          SUB           r4, r4, #30                               @ x -= L_INTERPOL2 - 1

-          CMP           r2, #0

-          ADDLT         r2, r2, #4                                @ frac += UP_SAMP

-          SUBLT         r4, r4, #2                                @ x--

-

-          LDR           r11, Lable1

-          RSB           r2, r2, #3                                @ k = UP_SAMP - 1 - frac

-          MOV           r8, #0                                    @ j = 0

-	  ADD           r11, r11, r2, LSL #6                      @ get inter4_2[k][]

-

-	  VLD1.S16      {Q0, Q1}, [r11]!

-	  VLD1.S16      {Q2, Q3}, [r11]!

-          

-	  MOV           r6, #0x8000 

-

-          VLD1.S16      {Q4, Q5}, [r4]!                           @load 16 x[]

-          VLD1.S16      {Q6, Q7}, [r4]!                           @load 16 x[]

-

-LOOP:

-          VQDMULL.S16   Q15, D8, D0

-          VQDMLAL.S16   Q15, D9, D1

-          VQDMLAL.S16   Q15, D10, D2

-          VQDMLAL.S16   Q15, D11, D3

-        

-          VQDMLAL.S16   Q15, D12, D4

-          VQDMLAL.S16   Q15, D13, D5

-          VQDMLAL.S16   Q15, D14, D6

-          VQDMLAL.S16   Q15, D15, D7

-

-          LDRSH         r12, [r4], #2                

-          

-          VEXT.S16      D8, D8, D9, #1

-          VEXT.S16      D9, D9, D10, #1

-          VEXT.S16      D10, D10, D11, #1

-          VEXT.S16      D11, D11, D12, #1

-          VDUP.S16      D24, r12

-          VEXT.S16      D12, D12, D13, #1

-          VEXT.S16      D13, D13, D14, #1

-     

-          VQADD.S32     D30, D30, D31

-	  MOV           r11, #0x8000          

-          VPADD.S32     D30, D30, D30

-          ADD           r8, r8, #1

-          VMOV.S32      r12, D30[0]

-          VEXT.S16      D14, D14, D15, #1          

-

-          QADD          r1, r12, r12                              @ L_sum = (L_sum << 2)

-          VEXT.S16      D15, D15, D24, #1

-          QADD          r5, r1, r6                         

-          MOV           r1, r5, ASR #16

-          CMP           r8, r3

-          STRH          r1, [r0], #2                              @ exc[j] = (L_sum + 0x8000) >> 16

-          BLT           LOOP

-                    

-pred_lt4_end:

-		     

-          LDMFD   	r13!, {r4 - r12, r15} 

- 

-Lable1:

-          .word   	inter4_2

-          @ENDFUNC

-          .END

-

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+@
+@void Pred_lt4(
+@     Word16 exc[],                         /* in/out: excitation buffer */
+@     Word16 T0,                            /* input : integer pitch lag */
+@     Word16 frac,                          /* input : fraction of lag   */
+@     Word16 L_subfr                        /* input : subframe size     */
+@)
+@***********************************************************************
+@ r0    ---  exc[]
+@ r1    ---  T0
+@ r2    ---  frac
+@ r3    ---  L_subfr
+
+          .section  .text
+          .global   pred_lt4_asm
+          .extern   inter4_2
+
+pred_lt4_asm:
+
+          STMFD   	r13!, {r4 - r12, r14}
+          SUB           r4, r0, r1, LSL #1                        @ x = exc - T0
+          RSB           r2, r2, #0                                @ frac = - frac
+          SUB           r4, r4, #30                               @ x -= L_INTERPOL2 - 1
+          CMP           r2, #0
+          ADDLT         r2, r2, #4                                @ frac += UP_SAMP
+          SUBLT         r4, r4, #2                                @ x--
+
+          LDR           r11, Lable1
+          RSB           r2, r2, #3                                @ k = UP_SAMP - 1 - frac
+          MOV           r8, #0                                    @ j = 0
+	  ADD           r11, r11, r2, LSL #6                      @ get inter4_2[k][]
+
+	  VLD1.S16      {Q0, Q1}, [r11]!
+	  VLD1.S16      {Q2, Q3}, [r11]!
+
+	  MOV           r6, #0x8000
+
+          VLD1.S16      {Q4, Q5}, [r4]!                           @load 16 x[]
+          VLD1.S16      {Q6, Q7}, [r4]!                           @load 16 x[]
+
+LOOP:
+          VQDMULL.S16   Q15, D8, D0
+          VQDMLAL.S16   Q15, D9, D1
+          VQDMLAL.S16   Q15, D10, D2
+          VQDMLAL.S16   Q15, D11, D3
+
+          VQDMLAL.S16   Q15, D12, D4
+          VQDMLAL.S16   Q15, D13, D5
+          VQDMLAL.S16   Q15, D14, D6
+          VQDMLAL.S16   Q15, D15, D7
+
+          LDRSH         r12, [r4], #2
+
+          VEXT.S16      D8, D8, D9, #1
+          VEXT.S16      D9, D9, D10, #1
+          VEXT.S16      D10, D10, D11, #1
+          VEXT.S16      D11, D11, D12, #1
+          VDUP.S16      D24, r12
+          VEXT.S16      D12, D12, D13, #1
+          VEXT.S16      D13, D13, D14, #1
+
+          VQADD.S32     D30, D30, D31
+	  MOV           r11, #0x8000
+          VPADD.S32     D30, D30, D30
+          ADD           r8, r8, #1
+          VMOV.S32      r12, D30[0]
+          VEXT.S16      D14, D14, D15, #1
+
+          QADD          r1, r12, r12                              @ L_sum = (L_sum << 2)
+          VEXT.S16      D15, D15, D24, #1
+          QADD          r5, r1, r6
+          MOV           r1, r5, ASR #16
+          CMP           r8, r3
+          STRH          r1, [r0], #2                              @ exc[j] = (L_sum + 0x8000) >> 16
+          BLT           LOOP
+
+pred_lt4_end:
+
+          LDMFD   	r13!, {r4 - r12, r15}
+
+Lable1:
+          .word   	inter4_2
+          @ENDFUNC
+          .END
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/residu_asm_neon.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/residu_asm_neon.s
index b9e6b23..394fa83 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/residu_asm_neon.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/residu_asm_neon.s
@@ -26,17 +26,17 @@
 @lg         RN     r3
 
 	.section   .text
-        .global    Residu_opt 
+        .global    Residu_opt
 
 Residu_opt:
 
-        STMFD          r13!, {r4 - r12, r14} 
+        STMFD          r13!, {r4 - r12, r14}
         SUB            r7, r3, #4                       @i = lg - 4
-        
-        VLD1.S16       {D0, D1, D2, D3}, [r0]!              @get all a[]  
+
+        VLD1.S16       {D0, D1, D2, D3}, [r0]!              @get all a[]
 	VLD1.S16       {D4}, [r0]!
         VMOV.S32       Q8,  #0x8000
-        
+
 LOOP1:
         ADD            r9, r1, r7, LSL #1               @copy the address
         ADD            r10, r2, r7, LSL #1
@@ -45,7 +45,7 @@
         VQDMULL.S16    Q10, D5, D0[0]                  @finish the first L_mult
 
         SUB            r8, r9, #2                       @get the x[i-1] address
-        VLD1.S16       D5, [r8]! 
+        VLD1.S16       D5, [r8]!
         VQDMLAL.S16    Q10, D5, D0[1]
 
         SUB            r8, r9, #4                       @load the x[i-2] address
@@ -53,36 +53,36 @@
         VQDMLAL.S16    Q10, D5, D0[2]
 
         SUB            r8, r9, #6                       @load the x[i-3] address
-        VLD1.S16       D5, [r8]!     
-        VQDMLAL.S16    Q10, D5, D0[3]                    
+        VLD1.S16       D5, [r8]!
+        VQDMLAL.S16    Q10, D5, D0[3]
 
         SUB            r8, r9, #8                       @load the x[i-4] address
-        VLD1.S16       D5, [r8]!     
-        VQDMLAL.S16    Q10, D5, D1[0]  
+        VLD1.S16       D5, [r8]!
+        VQDMLAL.S16    Q10, D5, D1[0]
 
         SUB            r8, r9, #10                      @load the x[i-5] address
-        VLD1.S16       D5, [r8]!     
-        VQDMLAL.S16    Q10, D5, D1[1] 
+        VLD1.S16       D5, [r8]!
+        VQDMLAL.S16    Q10, D5, D1[1]
 
         SUB            r8, r9, #12                      @load the x[i-6] address
-        VLD1.S16       D5, [r8]!     
-        VQDMLAL.S16    Q10, D5, D1[2]  
+        VLD1.S16       D5, [r8]!
+        VQDMLAL.S16    Q10, D5, D1[2]
 
         SUB            r8, r9, #14                      @load the x[i-7] address
-        VLD1.S16       D5, [r8]!     
-        VQDMLAL.S16    Q10, D5, D1[3]  
+        VLD1.S16       D5, [r8]!
+        VQDMLAL.S16    Q10, D5, D1[3]
 
         SUB            r8, r9, #16                      @load the x[i-8] address
-        VLD1.S16       D5, [r8]!     
-        VQDMLAL.S16    Q10, D5, D2[0]  
+        VLD1.S16       D5, [r8]!
+        VQDMLAL.S16    Q10, D5, D2[0]
 
         SUB            r8, r9, #18                      @load the x[i-9] address
-        VLD1.S16       D5, [r8]!     
-        VQDMLAL.S16    Q10, D5, D2[1]         
-           
+        VLD1.S16       D5, [r8]!
+        VQDMLAL.S16    Q10, D5, D2[1]
+
         SUB            r8, r9, #20                      @load the x[i-10] address
-        VLD1.S16       D5, [r8]!     
-        VQDMLAL.S16    Q10, D5, D2[2]  
+        VLD1.S16       D5, [r8]!
+        VQDMLAL.S16    Q10, D5, D2[2]
 
 	SUB            r8, r9, #22                      @load the x[i-11] address
 	VLD1.S16       D5, [r8]!
@@ -117,10 +117,10 @@
 
         BGE            LOOP1
 
-Residu_asm_end: 
- 
+Residu_asm_end:
+
         LDMFD      r13!, {r4 - r12, r15}
-    
+
         @ENDFUNC
         .END
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/scale_sig_neon.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/scale_sig_neon.s
index 14957d8..e45daac 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/scale_sig_neon.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/scale_sig_neon.s
@@ -1,138 +1,138 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-@                   

-@**********************************************************************/

-@void Scale_sig(

-@               Word16 x[],                           /* (i/o) : signal to scale               */

-@               Word16 lg,                            /* (i)   : size of x[]                   */

-@               Word16 exp                            /* (i)   : exponent: x = round(x << exp) */

-@)

-@***********************************************************************

-@  x[]   ---  r0

-@  lg    ---  r1

-@  exp   ---  r2

-

-          .section  .text 

-          .global   Scale_sig_opt

-

-Scale_sig_opt:

-

-          STMFD   	r13!, {r4 - r12, r14} 

-          MOV           r4, #4

-          VMOV.S32      Q15, #0x8000       

-          VDUP.S32      Q14, r2  

-          MOV           r5, r0                          @ copy x[] address    

-          CMP           r1, #64

-          MOVEQ         r4, #1

-          BEQ           LOOP

-	  CMP           r1, #128

-	  MOVEQ         r4, #2

-	  BEQ           LOOP

-          CMP           r1, #256

-          BEQ           LOOP

-	  CMP           r1, #80

-	  MOVEQ         r4, #1

-	  BEQ           LOOP1

-

-LOOP1:

-          VLD1.S16      {Q0, Q1}, [r5]!                 @load 16 Word16 x[]     

-          VSHLL.S16     Q10, D0, #16

-          VSHLL.S16     Q11, D1, #16

-          VSHLL.S16     Q12, D2, #16

-          VSHLL.S16     Q13, D3, #16

-          VSHL.S32      Q10, Q10, Q14

-          VSHL.S32      Q11, Q11, Q14

-          VSHL.S32      Q12, Q12, Q14

-          VSHL.S32      Q13, Q13, Q14

-          VADDHN.S32    D16, Q10, Q15

-          VADDHN.S32    D17, Q11, Q15

-          VADDHN.S32    D18, Q12, Q15

-          VADDHN.S32    D19, Q13, Q15

-          VST1.S16      {Q8, Q9}, [r0]!                 @store 16 Word16 x[]

-

-LOOP:                

-          VLD1.S16      {Q0, Q1}, [r5]!                 @load 16 Word16 x[]

-          VLD1.S16      {Q2, Q3}, [r5]!                 @load 16 Word16 x[]

-          VLD1.S16      {Q4, Q5}, [r5]!                 @load 16 Word16 x[]

-          VLD1.S16      {Q6, Q7}, [r5]!                 @load 16 Word16 x[]

-

-          VSHLL.S16     Q8, D0, #16

-          VSHLL.S16     Q9, D1, #16

-          VSHLL.S16     Q10, D2, #16

-          VSHLL.S16     Q11, D3, #16     

-          VSHL.S32      Q8, Q8, Q14

-          VSHL.S32      Q9, Q9, Q14

-          VSHL.S32      Q10, Q10, Q14

-          VSHL.S32      Q11, Q11, Q14

-          VADDHN.S32    D16, Q8, Q15

-          VADDHN.S32    D17, Q9, Q15

-          VADDHN.S32    D18, Q10, Q15

-          VADDHN.S32    D19, Q11, Q15

-          VST1.S16      {Q8, Q9}, [r0]!                 @store 16 Word16 x[]

-

-   

-          VSHLL.S16     Q12, D4, #16

-          VSHLL.S16     Q13, D5, #16

-          VSHLL.S16     Q10, D6, #16

-          VSHLL.S16     Q11, D7, #16

-          VSHL.S32      Q12, Q12, Q14

-          VSHL.S32      Q13, Q13, Q14

-          VSHL.S32      Q10, Q10, Q14

-          VSHL.S32      Q11, Q11, Q14

-          VADDHN.S32    D16, Q12, Q15

-          VADDHN.S32    D17, Q13, Q15

-          VADDHN.S32    D18, Q10, Q15

-          VADDHN.S32    D19, Q11, Q15

-          VST1.S16      {Q8, Q9}, [r0]!                 @store 16 Word16 x[]

-

-          VSHLL.S16     Q10, D8, #16

-          VSHLL.S16     Q11, D9, #16

-          VSHLL.S16     Q12, D10, #16

-          VSHLL.S16     Q13, D11, #16

-          VSHL.S32      Q10, Q10, Q14

-          VSHL.S32      Q11, Q11, Q14

-          VSHL.S32      Q12, Q12, Q14

-          VSHL.S32      Q13, Q13, Q14

-          VADDHN.S32    D16, Q10, Q15

-          VADDHN.S32    D17, Q11, Q15

-          VADDHN.S32    D18, Q12, Q15

-          VADDHN.S32    D19, Q13, Q15

-          VST1.S16      {Q8, Q9}, [r0]!                 @store 16 Word16 x[]

-

-          VSHLL.S16     Q10, D12, #16   

-          VSHLL.S16     Q11, D13, #16

-          VSHLL.S16     Q12, D14, #16

-          VSHLL.S16     Q13, D15, #16

-          VSHL.S32      Q10, Q10, Q14

-          VSHL.S32      Q11, Q11, Q14

-          VSHL.S32      Q12, Q12, Q14

-          VSHL.S32      Q13, Q13, Q14

-          VADDHN.S32    D16, Q10, Q15

-          VADDHN.S32    D17, Q11, Q15

-          VADDHN.S32    D18, Q12, Q15

-          VADDHN.S32    D19, Q13, Q15 

-          VST1.S16      {Q8, Q9}, [r0]!                 @store 16 Word16 x[]  

-          SUBS          r4, r4, #1

-          BGT           LOOP     

-                

-                          

-Scale_sig_asm_end:

-

-          LDMFD   	r13!, {r4 - r12, r15} 

-          @ENDFUNC

-          .END

- 

-

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+@
+@**********************************************************************/
+@void Scale_sig(
+@               Word16 x[],                           /* (i/o) : signal to scale               */
+@               Word16 lg,                            /* (i)   : size of x[]                   */
+@               Word16 exp                            /* (i)   : exponent: x = round(x << exp) */
+@)
+@***********************************************************************
+@  x[]   ---  r0
+@  lg    ---  r1
+@  exp   ---  r2
+
+          .section  .text
+          .global   Scale_sig_opt
+
+Scale_sig_opt:
+
+          STMFD   	r13!, {r4 - r12, r14}
+          MOV           r4, #4
+          VMOV.S32      Q15, #0x8000
+          VDUP.S32      Q14, r2
+          MOV           r5, r0                          @ copy x[] address
+          CMP           r1, #64
+          MOVEQ         r4, #1
+          BEQ           LOOP
+	  CMP           r1, #128
+	  MOVEQ         r4, #2
+	  BEQ           LOOP
+          CMP           r1, #256
+          BEQ           LOOP
+	  CMP           r1, #80
+	  MOVEQ         r4, #1
+	  BEQ           LOOP1
+
+LOOP1:
+          VLD1.S16      {Q0, Q1}, [r5]!                 @load 16 Word16 x[]
+          VSHLL.S16     Q10, D0, #16
+          VSHLL.S16     Q11, D1, #16
+          VSHLL.S16     Q12, D2, #16
+          VSHLL.S16     Q13, D3, #16
+          VSHL.S32      Q10, Q10, Q14
+          VSHL.S32      Q11, Q11, Q14
+          VSHL.S32      Q12, Q12, Q14
+          VSHL.S32      Q13, Q13, Q14
+          VADDHN.S32    D16, Q10, Q15
+          VADDHN.S32    D17, Q11, Q15
+          VADDHN.S32    D18, Q12, Q15
+          VADDHN.S32    D19, Q13, Q15
+          VST1.S16      {Q8, Q9}, [r0]!                 @store 16 Word16 x[]
+
+LOOP:
+          VLD1.S16      {Q0, Q1}, [r5]!                 @load 16 Word16 x[]
+          VLD1.S16      {Q2, Q3}, [r5]!                 @load 16 Word16 x[]
+          VLD1.S16      {Q4, Q5}, [r5]!                 @load 16 Word16 x[]
+          VLD1.S16      {Q6, Q7}, [r5]!                 @load 16 Word16 x[]
+
+          VSHLL.S16     Q8, D0, #16
+          VSHLL.S16     Q9, D1, #16
+          VSHLL.S16     Q10, D2, #16
+          VSHLL.S16     Q11, D3, #16
+          VSHL.S32      Q8, Q8, Q14
+          VSHL.S32      Q9, Q9, Q14
+          VSHL.S32      Q10, Q10, Q14
+          VSHL.S32      Q11, Q11, Q14
+          VADDHN.S32    D16, Q8, Q15
+          VADDHN.S32    D17, Q9, Q15
+          VADDHN.S32    D18, Q10, Q15
+          VADDHN.S32    D19, Q11, Q15
+          VST1.S16      {Q8, Q9}, [r0]!                 @store 16 Word16 x[]
+
+
+          VSHLL.S16     Q12, D4, #16
+          VSHLL.S16     Q13, D5, #16
+          VSHLL.S16     Q10, D6, #16
+          VSHLL.S16     Q11, D7, #16
+          VSHL.S32      Q12, Q12, Q14
+          VSHL.S32      Q13, Q13, Q14
+          VSHL.S32      Q10, Q10, Q14
+          VSHL.S32      Q11, Q11, Q14
+          VADDHN.S32    D16, Q12, Q15
+          VADDHN.S32    D17, Q13, Q15
+          VADDHN.S32    D18, Q10, Q15
+          VADDHN.S32    D19, Q11, Q15
+          VST1.S16      {Q8, Q9}, [r0]!                 @store 16 Word16 x[]
+
+          VSHLL.S16     Q10, D8, #16
+          VSHLL.S16     Q11, D9, #16
+          VSHLL.S16     Q12, D10, #16
+          VSHLL.S16     Q13, D11, #16
+          VSHL.S32      Q10, Q10, Q14
+          VSHL.S32      Q11, Q11, Q14
+          VSHL.S32      Q12, Q12, Q14
+          VSHL.S32      Q13, Q13, Q14
+          VADDHN.S32    D16, Q10, Q15
+          VADDHN.S32    D17, Q11, Q15
+          VADDHN.S32    D18, Q12, Q15
+          VADDHN.S32    D19, Q13, Q15
+          VST1.S16      {Q8, Q9}, [r0]!                 @store 16 Word16 x[]
+
+          VSHLL.S16     Q10, D12, #16
+          VSHLL.S16     Q11, D13, #16
+          VSHLL.S16     Q12, D14, #16
+          VSHLL.S16     Q13, D15, #16
+          VSHL.S32      Q10, Q10, Q14
+          VSHL.S32      Q11, Q11, Q14
+          VSHL.S32      Q12, Q12, Q14
+          VSHL.S32      Q13, Q13, Q14
+          VADDHN.S32    D16, Q10, Q15
+          VADDHN.S32    D17, Q11, Q15
+          VADDHN.S32    D18, Q12, Q15
+          VADDHN.S32    D19, Q13, Q15
+          VST1.S16      {Q8, Q9}, [r0]!                 @store 16 Word16 x[]
+          SUBS          r4, r4, #1
+          BGT           LOOP
+
+
+Scale_sig_asm_end:
+
+          LDMFD   	r13!, {r4 - r12, r15}
+          @ENDFUNC
+          .END
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/syn_filt_neon.s b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/syn_filt_neon.s
index dc3d4a8..5731bdb 100644
--- a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/syn_filt_neon.s
+++ b/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/syn_filt_neon.s
@@ -1,106 +1,106 @@
-@/*

-@ ** Copyright 2003-2010, VisualOn, Inc.

-@ **

-@ ** Licensed under the Apache License, Version 2.0 (the "License");

-@ ** you may not use this file except in compliance with the License.

-@ ** You may obtain a copy of the License at

-@ **

-@ **     http://www.apache.org/licenses/LICENSE-2.0

-@ **

-@ ** Unless required by applicable law or agreed to in writing, software

-@ ** distributed under the License is distributed on an "AS IS" BASIS,

-@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

-@ ** See the License for the specific language governing permissions and

-@ ** limitations under the License.

-@ */

-@

-@void Syn_filt(

-@     Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients           */

-@     Word16 x[],                           /* (i)     : input signal                             */

-@     Word16 y[],                           /* (o)     : output signal                            */

-@     Word16 mem[],                         /* (i/o)   : memory associated with this filtering.   */

-@)

-@***********************************************************************

-@ a[]    ---   r0

-@ x[]    ---   r1

-@ y[]    ---   r2

-@ mem[]  ---   r3

-@ m ---  16  lg --- 80  update --- 1

-

-          .section  .text 

-          .global   Syn_filt_asm

-

-Syn_filt_asm:

-

-          STMFD   	r13!, {r4 - r12, r14} 

-          SUB           r13, r13, #700                   @ y_buf[L_FRAME16k + M16k]

-   

-          MOV           r4, r3                           @ copy mem[] address

-          MOV           r5, r13                          @ copy yy = y_buf address

-

-          @ for(i = 0@ i < m@ i++)

-          @{

-          @    *yy++ = mem[i]@

-          @} 

-          VLD1.S16      {D0, D1, D2, D3}, [r4]!          @load 16 mems

-	  VST1.S16      {D0, D1, D2, D3}, [r5]!          @store 16 mem[] to *yy

-

-          LDRSH         r5, [r0], #2                     @ load a[0]

-          MOV           r8, #0                           @ i = 0

-          MOV           r5, r5, ASR #1                   @ a0 = a[0] >> 1

-          VMOV.S16      D8[0], r5

-          @ load all a[]

-          VLD1.S16      {D0, D1, D2, D3}, [r0]!          @ load a[1] ~ a[16]

-	  VREV64.16     D0, D0

-	  VREV64.16     D1, D1

-	  VREV64.16     D2, D2

-	  VREV64.16     D3, D3 

-	  MOV           r8, #0                           @ loop times

-	  MOV           r10, r13                         @ temp = y_buf

-	  ADD           r4, r13, #32                     @ yy[i] address

-

-          VLD1.S16      {D4, D5, D6, D7}, [r10]!         @ first 16 temp_p

-

-SYN_LOOP:

-

-          LDRSH         r6, [r1], #2                     @ load x[i]

-	  MUL           r12, r6, r5                      @ L_tmp = x[i] * a0

-	  ADD           r10, r4, r8, LSL #1              @ y[i], yy[i] address

-

-	  VDUP.S32      Q10, r12

-	  VMULL.S16     Q5, D3, D4                    

-          VMLAL.S16     Q5, D2, D5

-          VMLAL.S16     Q5, D1, D6

-          VMLAL.S16     Q5, D0, D7

-          VEXT.8        D4, D4, D5, #2

-          VEXT.8        D5, D5, D6, #2

-          VEXT.8        D6, D6, D7, #2

-          VPADD.S32     D12, D10, D11

-          ADD           r8, r8, #1

-          VPADD.S32     D10, D12, D12

-

-	  VDUP.S32      Q7, D10[0]

-

-	  VSUB.S32      Q9, Q10, Q7

-          VQRSHRN.S32   D20, Q9, #12   

-          VMOV.S16      r9, D20[0]

-          VEXT.8        D7, D7, D20, #2

-          CMP           r8, #80

-          STRH          r9, [r10]                        @ yy[i]

-          STRH          r9, [r2], #2                     @ y[i]          	         

-	  

-          BLT           SYN_LOOP

- 

-          @ update mem[]

-          ADD           r5, r13, #160                    @ yy[64] address

-	  VLD1.S16      {D0, D1, D2, D3}, [r5]!

-	  VST1.S16      {D0, D1, D2, D3}, [r3]!              

-

-Syn_filt_asm_end:

- 

-          ADD           r13, r13, #700		     

-          LDMFD   	r13!, {r4 - r12, r15} 

-          @ENDFUNC

-          .END

- 

-

+@/*
+@ ** Copyright 2003-2010, VisualOn, Inc.
+@ **
+@ ** Licensed under the Apache License, Version 2.0 (the "License");
+@ ** you may not use this file except in compliance with the License.
+@ ** You may obtain a copy of the License at
+@ **
+@ **     http://www.apache.org/licenses/LICENSE-2.0
+@ **
+@ ** Unless required by applicable law or agreed to in writing, software
+@ ** distributed under the License is distributed on an "AS IS" BASIS,
+@ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@ ** See the License for the specific language governing permissions and
+@ ** limitations under the License.
+@ */
+@
+@void Syn_filt(
+@     Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients           */
+@     Word16 x[],                           /* (i)     : input signal                             */
+@     Word16 y[],                           /* (o)     : output signal                            */
+@     Word16 mem[],                         /* (i/o)   : memory associated with this filtering.   */
+@)
+@***********************************************************************
+@ a[]    ---   r0
+@ x[]    ---   r1
+@ y[]    ---   r2
+@ mem[]  ---   r3
+@ m ---  16  lg --- 80  update --- 1
+
+          .section  .text
+          .global   Syn_filt_asm
+
+Syn_filt_asm:
+
+          STMFD   	r13!, {r4 - r12, r14}
+          SUB           r13, r13, #700                   @ y_buf[L_FRAME16k + M16k]
+
+          MOV           r4, r3                           @ copy mem[] address
+          MOV           r5, r13                          @ copy yy = y_buf address
+
+          @ for(i = 0@ i < m@ i++)
+          @{
+          @    *yy++ = mem[i]@
+          @}
+          VLD1.S16      {D0, D1, D2, D3}, [r4]!          @load 16 mems
+	  VST1.S16      {D0, D1, D2, D3}, [r5]!          @store 16 mem[] to *yy
+
+          LDRSH         r5, [r0], #2                     @ load a[0]
+          MOV           r8, #0                           @ i = 0
+          MOV           r5, r5, ASR #1                   @ a0 = a[0] >> 1
+          VMOV.S16      D8[0], r5
+          @ load all a[]
+          VLD1.S16      {D0, D1, D2, D3}, [r0]!          @ load a[1] ~ a[16]
+	  VREV64.16     D0, D0
+	  VREV64.16     D1, D1
+	  VREV64.16     D2, D2
+	  VREV64.16     D3, D3
+	  MOV           r8, #0                           @ loop times
+	  MOV           r10, r13                         @ temp = y_buf
+	  ADD           r4, r13, #32                     @ yy[i] address
+
+          VLD1.S16      {D4, D5, D6, D7}, [r10]!         @ first 16 temp_p
+
+SYN_LOOP:
+
+          LDRSH         r6, [r1], #2                     @ load x[i]
+	  MUL           r12, r6, r5                      @ L_tmp = x[i] * a0
+	  ADD           r10, r4, r8, LSL #1              @ y[i], yy[i] address
+
+	  VDUP.S32      Q10, r12
+	  VMULL.S16     Q5, D3, D4
+          VMLAL.S16     Q5, D2, D5
+          VMLAL.S16     Q5, D1, D6
+          VMLAL.S16     Q5, D0, D7
+          VEXT.8        D4, D4, D5, #2
+          VEXT.8        D5, D5, D6, #2
+          VEXT.8        D6, D6, D7, #2
+          VPADD.S32     D12, D10, D11
+          ADD           r8, r8, #1
+          VPADD.S32     D10, D12, D12
+
+	  VDUP.S32      Q7, D10[0]
+
+	  VSUB.S32      Q9, Q10, Q7
+          VQRSHRN.S32   D20, Q9, #12
+          VMOV.S16      r9, D20[0]
+          VEXT.8        D7, D7, D20, #2
+          CMP           r8, #80
+          STRH          r9, [r10]                        @ yy[i]
+          STRH          r9, [r2], #2                     @ y[i]
+
+          BLT           SYN_LOOP
+
+          @ update mem[]
+          ADD           r5, r13, #160                    @ yy[64] address
+	  VLD1.S16      {D0, D1, D2, D3}, [r5]!
+	  VST1.S16      {D0, D1, D2, D3}, [r3]!
+
+Syn_filt_asm_end:
+
+          ADD           r13, r13, #700
+          LDMFD   	r13!, {r4 - r12, r15}
+          @ENDFUNC
+          .END
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/autocorr.c b/media/libstagefright/codecs/amrwbenc/src/autocorr.c
index 33ed670..8c477ca 100644
--- a/media/libstagefright/codecs/amrwbenc/src/autocorr.c
+++ b/media/libstagefright/codecs/amrwbenc/src/autocorr.c
@@ -1,127 +1,127 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-

-/***********************************************************************

-*       File: autocorr.c                                               *

-*                                                                      *

-*       Description:Compute autocorrelations of signal with windowing  *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "oper_32b.h"

-#include "acelp.h"

-#include "ham_wind.tab"

-

-void Autocorr(

-		Word16 x[],                           /* (i)    : Input signal                      */

-		Word16 m,                             /* (i)    : LPC order                         */

-		Word16 r_h[],                         /* (o) Q15: Autocorrelations  (msb)           */

-		Word16 r_l[]                          /* (o)    : Autocorrelations  (lsb)           */

-	     )

-{

-	Word32 i, norm, shift;

-	Word16 y[L_WINDOW];

-	Word32 L_sum, L_sum1, L_tmp, F_LEN;

-	Word16 *p1,*p2,*p3;

-	const Word16 *p4;

-	/* Windowing of signal */

-	p1 = x;

-	p4 = vo_window;

-	p3 = y;

-

-	for (i = 0; i < L_WINDOW; i+=4)

-	{

-		*p3++ = vo_mult_r((*p1++), (*p4++));

-		*p3++ = vo_mult_r((*p1++), (*p4++));

-		*p3++ = vo_mult_r((*p1++), (*p4++));

-		*p3++ = vo_mult_r((*p1++), (*p4++));

-	}

-

-	/* calculate energy of signal */

-	L_sum = vo_L_deposit_h(16);               /* sqrt(256), avoid overflow after rounding */

-	for (i = 0; i < L_WINDOW; i++)

-	{

-		L_tmp = vo_L_mult(y[i], y[i]);

-		L_tmp = (L_tmp >> 8);

-		L_sum += L_tmp;

-	}

-

-	/* scale signal to avoid overflow in autocorrelation */

-	norm = norm_l(L_sum);

-	shift = 4 - (norm >> 1);

-	if(shift > 0)

-	{

-		p1 = y;

-		for (i = 0; i < L_WINDOW; i+=4)

-		{

-			*p1 = vo_shr_r(*p1, shift); 

-			p1++;

-			*p1 = vo_shr_r(*p1, shift); 

-			p1++;

-			*p1 = vo_shr_r(*p1, shift);

-			p1++;

-			*p1 = vo_shr_r(*p1, shift); 

-			p1++;

-		}

-	}

-

-	/* Compute and normalize r[0] */

-	L_sum = 1; 

-	for (i = 0; i < L_WINDOW; i+=4)

-	{

-		L_sum += vo_L_mult(y[i], y[i]);

-		L_sum += vo_L_mult(y[i+1], y[i+1]);

-		L_sum += vo_L_mult(y[i+2], y[i+2]);

-		L_sum += vo_L_mult(y[i+3], y[i+3]);

-	}

-

-	norm = norm_l(L_sum);

-	L_sum = (L_sum << norm);

-

-	r_h[0] = L_sum >> 16;

-	r_l[0] = (L_sum & 0xffff)>>1;

-

-	/* Compute r[1] to r[m] */

-	for (i = 1; i <= 8; i++)

-	{

-		L_sum1 = 0;

-		L_sum = 0;

-		F_LEN = (Word32)(L_WINDOW - 2*i);

-		p1 = y;

-		p2 = y + (2*i)-1;

-		do{

-			L_sum1 += *p1 * *p2++;

-			L_sum += *p1++ * *p2;

-		}while(--F_LEN!=0);

-

-		L_sum1 += *p1 * *p2++;

-

-		L_sum1 = L_sum1<<norm;

-		L_sum = L_sum<<norm;

-

-		r_h[(2*i)-1] = L_sum1 >> 15;

-		r_l[(2*i)-1] = L_sum1 & 0x00007fff;

-		r_h[(2*i)] = L_sum >> 15;

-		r_l[(2*i)] = L_sum & 0x00007fff;

-	}

-	return;

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+
+/***********************************************************************
+*       File: autocorr.c                                               *
+*                                                                      *
+*       Description:Compute autocorrelations of signal with windowing  *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "oper_32b.h"
+#include "acelp.h"
+#include "ham_wind.tab"
+
+void Autocorr(
+		Word16 x[],                           /* (i)    : Input signal                      */
+		Word16 m,                             /* (i)    : LPC order                         */
+		Word16 r_h[],                         /* (o) Q15: Autocorrelations  (msb)           */
+		Word16 r_l[]                          /* (o)    : Autocorrelations  (lsb)           */
+	     )
+{
+	Word32 i, norm, shift;
+	Word16 y[L_WINDOW];
+	Word32 L_sum, L_sum1, L_tmp, F_LEN;
+	Word16 *p1,*p2,*p3;
+	const Word16 *p4;
+	/* Windowing of signal */
+	p1 = x;
+	p4 = vo_window;
+	p3 = y;
+
+	for (i = 0; i < L_WINDOW; i+=4)
+	{
+		*p3++ = vo_mult_r((*p1++), (*p4++));
+		*p3++ = vo_mult_r((*p1++), (*p4++));
+		*p3++ = vo_mult_r((*p1++), (*p4++));
+		*p3++ = vo_mult_r((*p1++), (*p4++));
+	}
+
+	/* calculate energy of signal */
+	L_sum = vo_L_deposit_h(16);               /* sqrt(256), avoid overflow after rounding */
+	for (i = 0; i < L_WINDOW; i++)
+	{
+		L_tmp = vo_L_mult(y[i], y[i]);
+		L_tmp = (L_tmp >> 8);
+		L_sum += L_tmp;
+	}
+
+	/* scale signal to avoid overflow in autocorrelation */
+	norm = norm_l(L_sum);
+	shift = 4 - (norm >> 1);
+	if(shift > 0)
+	{
+		p1 = y;
+		for (i = 0; i < L_WINDOW; i+=4)
+		{
+			*p1 = vo_shr_r(*p1, shift);
+			p1++;
+			*p1 = vo_shr_r(*p1, shift);
+			p1++;
+			*p1 = vo_shr_r(*p1, shift);
+			p1++;
+			*p1 = vo_shr_r(*p1, shift);
+			p1++;
+		}
+	}
+
+	/* Compute and normalize r[0] */
+	L_sum = 1;
+	for (i = 0; i < L_WINDOW; i+=4)
+	{
+		L_sum += vo_L_mult(y[i], y[i]);
+		L_sum += vo_L_mult(y[i+1], y[i+1]);
+		L_sum += vo_L_mult(y[i+2], y[i+2]);
+		L_sum += vo_L_mult(y[i+3], y[i+3]);
+	}
+
+	norm = norm_l(L_sum);
+	L_sum = (L_sum << norm);
+
+	r_h[0] = L_sum >> 16;
+	r_l[0] = (L_sum & 0xffff)>>1;
+
+	/* Compute r[1] to r[m] */
+	for (i = 1; i <= 8; i++)
+	{
+		L_sum1 = 0;
+		L_sum = 0;
+		F_LEN = (Word32)(L_WINDOW - 2*i);
+		p1 = y;
+		p2 = y + (2*i)-1;
+		do{
+			L_sum1 += *p1 * *p2++;
+			L_sum += *p1++ * *p2;
+		}while(--F_LEN!=0);
+
+		L_sum1 += *p1 * *p2++;
+
+		L_sum1 = L_sum1<<norm;
+		L_sum = L_sum<<norm;
+
+		r_h[(2*i)-1] = L_sum1 >> 15;
+		r_l[(2*i)-1] = L_sum1 & 0x00007fff;
+		r_h[(2*i)] = L_sum >> 15;
+		r_l[(2*i)] = L_sum & 0x00007fff;
+	}
+	return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/az_isp.c b/media/libstagefright/codecs/amrwbenc/src/az_isp.c
index 8259f91..43db27a 100644
--- a/media/libstagefright/codecs/amrwbenc/src/az_isp.c
+++ b/media/libstagefright/codecs/amrwbenc/src/az_isp.c
@@ -1,268 +1,268 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*  File: az_isp.c

-*

-*  Description:

-*-----------------------------------------------------------------------*

-* Compute the ISPs from  the LPC coefficients  (order=M)                *

-*-----------------------------------------------------------------------*

-*                                                                       *

-* The ISPs are the roots of the two polynomials F1(z) and F2(z)         *

-* defined as                                                            *

-*               F1(z) = A(z) + z^-m A(z^-1)                             *

-*  and          F2(z) = A(z) - z^-m A(z^-1)                             *

-*                                                                       *

-* For a even order m=2n, F1(z) has M/2 conjugate roots on the unit      *

-* circle and F2(z) has M/2-1 conjugate roots on the unit circle in      *

-* addition to two roots at 0 and pi.                                    *

-*                                                                       *

-* For a 16th order LP analysis, F1(z) and F2(z) can be written as       *

-*                                                                       *

-*   F1(z) = (1 + a[M])   PRODUCT  (1 - 2 cos(w_i) z^-1 + z^-2 )         *

-*                        i=0,2,4,6,8,10,12,14                           *

-*                                                                       *

-*   F2(z) = (1 - a[M]) (1 - z^-2) PRODUCT (1 - 2 cos(w_i) z^-1 + z^-2 ) *

-*                                 i=1,3,5,7,9,11,13                     *

-*                                                                       *

-* The ISPs are the M-1 frequencies w_i, i=0...M-2 plus the last         *

-* predictor coefficient a[M].                                           *

-*-----------------------------------------------------------------------*

-

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "oper_32b.h"

-#include "stdio.h"

-#include "grid100.tab"

-

-#define M   16

-#define NC  (M/2)

-

-/* local function */

-static __inline Word16 Chebps2(Word16 x, Word16 f[], Word32 n);

-

-void Az_isp(

-		Word16 a[],                           /* (i) Q12 : predictor coefficients                 */

-		Word16 isp[],                         /* (o) Q15 : Immittance spectral pairs              */

-		Word16 old_isp[]                      /* (i)     : old isp[] (in case not found M roots)  */

-	   )

-{

-	Word32 i, j, nf, ip, order;

-	Word16 xlow, ylow, xhigh, yhigh, xmid, ymid, xint;

-	Word16 x, y, sign, exp;

-	Word16 *coef;

-	Word16 f1[NC + 1], f2[NC];

-	Word32 t0;

-	/*-------------------------------------------------------------*

-	 * find the sum and diff polynomials F1(z) and F2(z)           *

-	 *      F1(z) = [A(z) + z^M A(z^-1)]                           *

-	 *      F2(z) = [A(z) - z^M A(z^-1)]/(1-z^-2)                  *

-	 *                                                             *

-	 * for (i=0; i<NC; i++)                                        *

-	 * {                                                           *

-	 *   f1[i] = a[i] + a[M-i];                                    *

-	 *   f2[i] = a[i] - a[M-i];                                    *

-	 * }                                                           *

-	 * f1[NC] = 2.0*a[NC];                                         *

-	 *                                                             *

-	 * for (i=2; i<NC; i++)            Divide by (1-z^-2)          *

-	 *   f2[i] += f2[i-2];                                         *

-	 *-------------------------------------------------------------*/

-	for (i = 0; i < NC; i++)

-	{

-		t0 = a[i] << 15;

-		f1[i] = vo_round(t0 + (a[M - i] << 15));        /* =(a[i]+a[M-i])/2 */

-		f2[i] = vo_round(t0 - (a[M - i] << 15));        /* =(a[i]-a[M-i])/2 */

-	}

-	f1[NC] = a[NC];                        

-	for (i = 2; i < NC; i++)               /* Divide by (1-z^-2) */

-		f2[i] = add1(f2[i], f2[i - 2]);     

-

-	/*---------------------------------------------------------------------*

-	 * Find the ISPs (roots of F1(z) and F2(z) ) using the                 *

-	 * Chebyshev polynomial evaluation.                                    *

-	 * The roots of F1(z) and F2(z) are alternatively searched.            *

-	 * We start by finding the first root of F1(z) then we switch          *

-	 * to F2(z) then back to F1(z) and so on until all roots are found.    *

-	 *                                                                     *

-	 *  - Evaluate Chebyshev pol. at grid points and check for sign change.*

-	 *  - If sign change track the root by subdividing the interval        *

-	 *    2 times and ckecking sign change.                                *

-	 *---------------------------------------------------------------------*/

-	nf = 0;                                  /* number of found frequencies */

-	ip = 0;                                  /* indicator for f1 or f2      */

-	coef = f1;                             

-	order = NC;                            

-	xlow = vogrid[0];                        

-	ylow = Chebps2(xlow, coef, order);

-	j = 0;

-	while ((nf < M - 1) && (j < GRID_POINTS))

-	{

-		j ++;

-		xhigh = xlow;                     

-		yhigh = ylow;                      

-		xlow = vogrid[j];                    

-		ylow = Chebps2(xlow, coef, order);

-		if ((ylow * yhigh) <= (Word32) 0)

-		{

-			/* divide 2 times the interval */

-			for (i = 0; i < 2; i++)

-			{

-				xmid = (xlow >> 1) + (xhigh >> 1);        /* xmid = (xlow + xhigh)/2 */

-				ymid = Chebps2(xmid, coef, order);

-				if ((ylow * ymid) <= (Word32) 0)

-				{

-					yhigh = ymid;         

-					xhigh = xmid;          

-				} else

-				{

-					ylow = ymid;           

-					xlow = xmid;          

-				}

-			}

-			/*-------------------------------------------------------------*

-			 * Linear interpolation                                        *

-			 *    xint = xlow - ylow*(xhigh-xlow)/(yhigh-ylow);            *

-			 *-------------------------------------------------------------*/

-			x = xhigh - xlow;

-			y = yhigh - ylow;

-			if (y == 0)

-			{

-				xint = xlow;               

-			} else

-			{

-				sign = y;                 

-				y = abs_s(y);

-				exp = norm_s(y);

-				y = y << exp;

-				y = div_s((Word16) 16383, y);

-				t0 = x * y;

-				t0 = (t0 >> (19 - exp));

-				y = vo_extract_l(t0);         /* y= (xhigh-xlow)/(yhigh-ylow) in Q11 */

-				if (sign < 0)

-					y = -y;

-				t0 = ylow * y;      /* result in Q26 */

-				t0 = (t0 >> 10);        /* result in Q15 */

-				xint = vo_sub(xlow, vo_extract_l(t0));        /* xint = xlow - ylow*y */

-			}

-			isp[nf] = xint;                

-			xlow = xint;                   

-			nf++;                          

-			if (ip == 0)

-			{

-				ip = 1;                    

-				coef = f2;                

-				order = NC - 1;           

-			} else

-			{

-				ip = 0;                   

-				coef = f1;                 

-				order = NC;              

-			}

-			ylow = Chebps2(xlow, coef, order);

-		}

-	}

-	/* Check if M-1 roots found */

-	if(nf < M - 1)

-	{

-		for (i = 0; i < M; i++)

-		{

-			isp[i] = old_isp[i];          

-		}

-	} else

-	{

-		isp[M - 1] = a[M] << 3;                      /* From Q12 to Q15 with saturation */

-	}

-	return;

-}

-

-/*--------------------------------------------------------------*

-* function  Chebps2:                                           *

-*           ~~~~~~~                                            *

-*    Evaluates the Chebishev polynomial series                 *

-*--------------------------------------------------------------*

-*                                                              *

-*  The polynomial order is                                     *

-*     n = M/2   (M is the prediction order)                    *

-*  The polynomial is given by                                  *

-*    C(x) = f(0)T_n(x) + f(1)T_n-1(x) + ... +f(n-1)T_1(x) + f(n)/2 *

-* Arguments:                                                   *

-*  x:     input value of evaluation; x = cos(frequency) in Q15 *

-*  f[]:   coefficients of the pol.                      in Q11 *

-*  n:     order of the pol.                                    *

-*                                                              *

-* The value of C(x) is returned. (Satured to +-1.99 in Q14)    *

-*                                                              *

-*--------------------------------------------------------------*/

-

-static __inline Word16 Chebps2(Word16 x, Word16 f[], Word32 n)

-{

-	Word32 i, cheb;

-	Word16 b0_h, b0_l, b1_h, b1_l, b2_h, b2_l;

-	Word32 t0;

-

-	/* Note: All computation are done in Q24. */

-

-	t0 = f[0] << 13;

-	b2_h = t0 >> 16;

-	b2_l = (t0 & 0xffff)>>1;

-

-	t0 = ((b2_h * x)<<1) + (((b2_l * x)>>15)<<1);

-	t0 <<= 1;

-	t0 += (f[1] << 13);						/* + f[1] in Q24        */

-

-	b1_h = t0 >> 16;

-	b1_l = (t0 & 0xffff) >> 1;

-

-	for (i = 2; i < n; i++)

-	{

-		t0 = ((b1_h * x)<<1) + (((b1_l * x)>>15)<<1);

-

-		t0 += (b2_h * (-16384))<<1;

-		t0 += (f[i] << 12);

-		t0 <<= 1;

-		t0 -= (b2_l << 1);					/* t0 = 2.0*x*b1 - b2 + f[i]; */

-

-		b0_h = t0 >> 16;

-		b0_l = (t0 & 0xffff) >> 1;

-

-		b2_l = b1_l;                         /* b2 = b1; */

-		b2_h = b1_h;                       

-		b1_l = b0_l;                         /* b1 = b0; */

-		b1_h = b0_h;                       

-	}

-

-	t0 = ((b1_h * x)<<1) + (((b1_l * x)>>15)<<1);

-	t0 += (b2_h * (-32768))<<1;				/* t0 = x*b1 - b2          */

-	t0 -= (b2_l << 1);

-	t0 += (f[n] << 12);						/* t0 = x*b1 - b2 + f[i]/2 */

-

-	t0 = L_shl2(t0, 6);                     /* Q24 to Q30 with saturation */

-

-	cheb = extract_h(t0);                  /* Result in Q14              */

-

-	if (cheb == -32768)

-	{

-		cheb = -32767;                     /* to avoid saturation in Az_isp */

-	}

-	return (cheb);

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*  File: az_isp.c
+*
+*  Description:
+*-----------------------------------------------------------------------*
+* Compute the ISPs from  the LPC coefficients  (order=M)                *
+*-----------------------------------------------------------------------*
+*                                                                       *
+* The ISPs are the roots of the two polynomials F1(z) and F2(z)         *
+* defined as                                                            *
+*               F1(z) = A(z) + z^-m A(z^-1)                             *
+*  and          F2(z) = A(z) - z^-m A(z^-1)                             *
+*                                                                       *
+* For a even order m=2n, F1(z) has M/2 conjugate roots on the unit      *
+* circle and F2(z) has M/2-1 conjugate roots on the unit circle in      *
+* addition to two roots at 0 and pi.                                    *
+*                                                                       *
+* For a 16th order LP analysis, F1(z) and F2(z) can be written as       *
+*                                                                       *
+*   F1(z) = (1 + a[M])   PRODUCT  (1 - 2 cos(w_i) z^-1 + z^-2 )         *
+*                        i=0,2,4,6,8,10,12,14                           *
+*                                                                       *
+*   F2(z) = (1 - a[M]) (1 - z^-2) PRODUCT (1 - 2 cos(w_i) z^-1 + z^-2 ) *
+*                                 i=1,3,5,7,9,11,13                     *
+*                                                                       *
+* The ISPs are the M-1 frequencies w_i, i=0...M-2 plus the last         *
+* predictor coefficient a[M].                                           *
+*-----------------------------------------------------------------------*
+
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "oper_32b.h"
+#include "stdio.h"
+#include "grid100.tab"
+
+#define M   16
+#define NC  (M/2)
+
+/* local function */
+static __inline Word16 Chebps2(Word16 x, Word16 f[], Word32 n);
+
+void Az_isp(
+		Word16 a[],                           /* (i) Q12 : predictor coefficients                 */
+		Word16 isp[],                         /* (o) Q15 : Immittance spectral pairs              */
+		Word16 old_isp[]                      /* (i)     : old isp[] (in case not found M roots)  */
+	   )
+{
+	Word32 i, j, nf, ip, order;
+	Word16 xlow, ylow, xhigh, yhigh, xmid, ymid, xint;
+	Word16 x, y, sign, exp;
+	Word16 *coef;
+	Word16 f1[NC + 1], f2[NC];
+	Word32 t0;
+	/*-------------------------------------------------------------*
+	 * find the sum and diff polynomials F1(z) and F2(z)           *
+	 *      F1(z) = [A(z) + z^M A(z^-1)]                           *
+	 *      F2(z) = [A(z) - z^M A(z^-1)]/(1-z^-2)                  *
+	 *                                                             *
+	 * for (i=0; i<NC; i++)                                        *
+	 * {                                                           *
+	 *   f1[i] = a[i] + a[M-i];                                    *
+	 *   f2[i] = a[i] - a[M-i];                                    *
+	 * }                                                           *
+	 * f1[NC] = 2.0*a[NC];                                         *
+	 *                                                             *
+	 * for (i=2; i<NC; i++)            Divide by (1-z^-2)          *
+	 *   f2[i] += f2[i-2];                                         *
+	 *-------------------------------------------------------------*/
+	for (i = 0; i < NC; i++)
+	{
+		t0 = a[i] << 15;
+		f1[i] = vo_round(t0 + (a[M - i] << 15));        /* =(a[i]+a[M-i])/2 */
+		f2[i] = vo_round(t0 - (a[M - i] << 15));        /* =(a[i]-a[M-i])/2 */
+	}
+	f1[NC] = a[NC];
+	for (i = 2; i < NC; i++)               /* Divide by (1-z^-2) */
+		f2[i] = add1(f2[i], f2[i - 2]);
+
+	/*---------------------------------------------------------------------*
+	 * Find the ISPs (roots of F1(z) and F2(z) ) using the                 *
+	 * Chebyshev polynomial evaluation.                                    *
+	 * The roots of F1(z) and F2(z) are alternatively searched.            *
+	 * We start by finding the first root of F1(z) then we switch          *
+	 * to F2(z) then back to F1(z) and so on until all roots are found.    *
+	 *                                                                     *
+	 *  - Evaluate Chebyshev pol. at grid points and check for sign change.*
+	 *  - If sign change track the root by subdividing the interval        *
+	 *    2 times and ckecking sign change.                                *
+	 *---------------------------------------------------------------------*/
+	nf = 0;                                  /* number of found frequencies */
+	ip = 0;                                  /* indicator for f1 or f2      */
+	coef = f1;
+	order = NC;
+	xlow = vogrid[0];
+	ylow = Chebps2(xlow, coef, order);
+	j = 0;
+	while ((nf < M - 1) && (j < GRID_POINTS))
+	{
+		j ++;
+		xhigh = xlow;
+		yhigh = ylow;
+		xlow = vogrid[j];
+		ylow = Chebps2(xlow, coef, order);
+		if ((ylow * yhigh) <= (Word32) 0)
+		{
+			/* divide 2 times the interval */
+			for (i = 0; i < 2; i++)
+			{
+				xmid = (xlow >> 1) + (xhigh >> 1);        /* xmid = (xlow + xhigh)/2 */
+				ymid = Chebps2(xmid, coef, order);
+				if ((ylow * ymid) <= (Word32) 0)
+				{
+					yhigh = ymid;
+					xhigh = xmid;
+				} else
+				{
+					ylow = ymid;
+					xlow = xmid;
+				}
+			}
+			/*-------------------------------------------------------------*
+			 * Linear interpolation                                        *
+			 *    xint = xlow - ylow*(xhigh-xlow)/(yhigh-ylow);            *
+			 *-------------------------------------------------------------*/
+			x = xhigh - xlow;
+			y = yhigh - ylow;
+			if (y == 0)
+			{
+				xint = xlow;
+			} else
+			{
+				sign = y;
+				y = abs_s(y);
+				exp = norm_s(y);
+				y = y << exp;
+				y = div_s((Word16) 16383, y);
+				t0 = x * y;
+				t0 = (t0 >> (19 - exp));
+				y = vo_extract_l(t0);         /* y= (xhigh-xlow)/(yhigh-ylow) in Q11 */
+				if (sign < 0)
+					y = -y;
+				t0 = ylow * y;      /* result in Q26 */
+				t0 = (t0 >> 10);        /* result in Q15 */
+				xint = vo_sub(xlow, vo_extract_l(t0));        /* xint = xlow - ylow*y */
+			}
+			isp[nf] = xint;
+			xlow = xint;
+			nf++;
+			if (ip == 0)
+			{
+				ip = 1;
+				coef = f2;
+				order = NC - 1;
+			} else
+			{
+				ip = 0;
+				coef = f1;
+				order = NC;
+			}
+			ylow = Chebps2(xlow, coef, order);
+		}
+	}
+	/* Check if M-1 roots found */
+	if(nf < M - 1)
+	{
+		for (i = 0; i < M; i++)
+		{
+			isp[i] = old_isp[i];
+		}
+	} else
+	{
+		isp[M - 1] = a[M] << 3;                      /* From Q12 to Q15 with saturation */
+	}
+	return;
+}
+
+/*--------------------------------------------------------------*
+* function  Chebps2:                                           *
+*           ~~~~~~~                                            *
+*    Evaluates the Chebishev polynomial series                 *
+*--------------------------------------------------------------*
+*                                                              *
+*  The polynomial order is                                     *
+*     n = M/2   (M is the prediction order)                    *
+*  The polynomial is given by                                  *
+*    C(x) = f(0)T_n(x) + f(1)T_n-1(x) + ... +f(n-1)T_1(x) + f(n)/2 *
+* Arguments:                                                   *
+*  x:     input value of evaluation; x = cos(frequency) in Q15 *
+*  f[]:   coefficients of the pol.                      in Q11 *
+*  n:     order of the pol.                                    *
+*                                                              *
+* The value of C(x) is returned. (Satured to +-1.99 in Q14)    *
+*                                                              *
+*--------------------------------------------------------------*/
+
+static __inline Word16 Chebps2(Word16 x, Word16 f[], Word32 n)
+{
+	Word32 i, cheb;
+	Word16 b0_h, b0_l, b1_h, b1_l, b2_h, b2_l;
+	Word32 t0;
+
+	/* Note: All computation are done in Q24. */
+
+	t0 = f[0] << 13;
+	b2_h = t0 >> 16;
+	b2_l = (t0 & 0xffff)>>1;
+
+	t0 = ((b2_h * x)<<1) + (((b2_l * x)>>15)<<1);
+	t0 <<= 1;
+	t0 += (f[1] << 13);						/* + f[1] in Q24        */
+
+	b1_h = t0 >> 16;
+	b1_l = (t0 & 0xffff) >> 1;
+
+	for (i = 2; i < n; i++)
+	{
+		t0 = ((b1_h * x)<<1) + (((b1_l * x)>>15)<<1);
+
+		t0 += (b2_h * (-16384))<<1;
+		t0 += (f[i] << 12);
+		t0 <<= 1;
+		t0 -= (b2_l << 1);					/* t0 = 2.0*x*b1 - b2 + f[i]; */
+
+		b0_h = t0 >> 16;
+		b0_l = (t0 & 0xffff) >> 1;
+
+		b2_l = b1_l;                         /* b2 = b1; */
+		b2_h = b1_h;
+		b1_l = b0_l;                         /* b1 = b0; */
+		b1_h = b0_h;
+	}
+
+	t0 = ((b1_h * x)<<1) + (((b1_l * x)>>15)<<1);
+	t0 += (b2_h * (-32768))<<1;				/* t0 = x*b1 - b2          */
+	t0 -= (b2_l << 1);
+	t0 += (f[n] << 12);						/* t0 = x*b1 - b2 + f[i]/2 */
+
+	t0 = L_shl2(t0, 6);                     /* Q24 to Q30 with saturation */
+
+	cheb = extract_h(t0);                  /* Result in Q14              */
+
+	if (cheb == -32768)
+	{
+		cheb = -32767;                     /* to avoid saturation in Az_isp */
+	}
+	return (cheb);
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/bits.c b/media/libstagefright/codecs/amrwbenc/src/bits.c
index 90d1a00..e78dc1f 100644
--- a/media/libstagefright/codecs/amrwbenc/src/bits.c
+++ b/media/libstagefright/codecs/amrwbenc/src/bits.c
@@ -1,210 +1,210 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-       File: bits.c

-

-	   Description: Performs bit stream manipulation

-

-************************************************************************/

-

-#include <stdlib.h>

-#include <stdio.h>

-#include "typedef.h"

-#include "basic_op.h"

-#include "cnst.h"

-#include "bits.h"

-#include "acelp.h"

-#include "dtx.h"

-#include "mime_io.tab"

-

-

-int PackBits(Word16 prms[],             /*  i: analysis parameters */

-			 Word16 coding_mode,        /*  i: coding bit-stream ratio mode */

-			 Word16 mode,               /*  i: coding bit-stream ratio mode*/ 

-			 Coder_State *st            /*i/o: coder global parameters struct */           

-			 )

-{

-	Word16 i, frame_type;

-	UWord8 temp;

-	UWord8 *stream_ptr;

-	Word16 bitstreamformat = st->frameType;

-

-	unsigned short* dataOut = st->outputStream;

-

-	if (coding_mode == MRDTX)

-	{	   

-		st->sid_update_counter--;

-

-		if (st->prev_ft == TX_SPEECH)

-		{

-			frame_type = TX_SID_FIRST;

-			st->sid_update_counter = 3;

-		} else

-		{

-			if ((st->sid_handover_debt > 0) && (st->sid_update_counter > 2))

-			{

-				/* ensure extra updates are  properly delayed after a possible SID_FIRST */

-				frame_type = TX_SID_UPDATE;

-				st->sid_handover_debt--;

-			} else

-			{

-				if (st->sid_update_counter == 0)

-				{

-					frame_type = TX_SID_UPDATE;

-					st->sid_update_counter = 8;

-				} else

-				{

-					frame_type = TX_NO_DATA;

-				}

-			}

-		}

-	} else

-	{

-		st->sid_update_counter = 8;

-		frame_type = TX_SPEECH;

-	}

-	st->prev_ft = frame_type;

-

-	if(bitstreamformat == 0)				/* default file format */

-	{

-		*(dataOut) = TX_FRAME_TYPE;

-		*(dataOut + 1) = frame_type;

-		*(dataOut + 2) = mode;

-		for (i = 0; i < nb_of_bits[coding_mode]; i++)

-		{

-			*(dataOut + 3 + i) = prms[i];

-		}

-		return  (3 + nb_of_bits[coding_mode])<<1;

-	} else

-	{

-		if (bitstreamformat == 1)		/* ITU file format */

-		{  						

-			*(dataOut) = 0x6b21;

-			if(frame_type != TX_NO_DATA && frame_type != TX_SID_FIRST)

-			{

-				*(dataOut + 1) = nb_of_bits[coding_mode];

-				for (i = 0; i < nb_of_bits[coding_mode]; i++)

-				{

-					if(prms[i] == BIT_0){

-						*(dataOut + 2 + i) = BIT_0_ITU;	 			

-					}

-					else{

-						*(dataOut + 2 + i) = BIT_1_ITU;

-					}

-				}

-				return (2 + nb_of_bits[coding_mode])<<1;   

-			} else

-			{

-				*(dataOut + 1) = 0;

-				return 2<<1;	   

-			}

-		} else							/* MIME/storage file format */

-		{

-#define MRSID 9

-			/* change mode index in case of SID frame */

-			if (coding_mode == MRDTX)

-			{

-				coding_mode = MRSID;

-				if (frame_type == TX_SID_FIRST)

-				{

-					for (i = 0; i < NBBITS_SID; i++)	prms[i] = BIT_0;

-				}

-			}

-			/* -> force NO_DATA frame */

-			if (coding_mode < 0 || coding_mode > 15 || (coding_mode > MRSID && coding_mode < 14))

-			{

-				coding_mode = 15;

-			}

-			/* mark empty frames between SID updates as NO_DATA frames */

-			if (coding_mode == MRSID && frame_type == TX_NO_DATA)

-			{

-				coding_mode = 15;

-			}

-			/* set pointer for packed frame, note that we handle data as bytes */

-			stream_ptr = (UWord8*)dataOut;

-			/* insert table of contents (ToC) byte at the beginning of the packet */

-			*stream_ptr = toc_byte[coding_mode];

-			stream_ptr++;

-			temp = 0;

-			/* sort and pack AMR-WB speech or SID bits */

-			for (i = 1; i < unpacked_size[coding_mode] + 1; i++)

-			{

-				if (prms[sort_ptr[coding_mode][i-1]] == BIT_1)

-				{

-					temp++;

-				}

-				if (i&0x7)

-				{

-					temp <<= 1;

-				}

-				else

-				{

-					*stream_ptr = temp;

-					stream_ptr++;

-					temp = 0;

-				}

-			}

-			/* insert SID type indication and speech mode in case of SID frame */

-			if (coding_mode == MRSID)

-			{

-				if (frame_type == TX_SID_UPDATE)

-				{

-					temp++;

-				}

-				temp <<= 4;

-				temp += mode & 0x000F;

-			}

-			/* insert unused bits (zeros) at the tail of the last byte */

-			if (unused_size[coding_mode])

-			{

-				temp <<= (unused_size[coding_mode] - 1);

-			}

-			*stream_ptr = temp;

-			/* write packed frame into file (1 byte added to cover ToC entry) */

-			return (1 + packed_size[coding_mode]);

-		}

-	}

-}

-

-/*-----------------------------------------------------*

-* Parm_serial -> convert parameters to serial stream  *

-*-----------------------------------------------------*/

-

-void Parm_serial(

-		Word16 value,                         /* input : parameter value */

-		Word16 no_of_bits,                    /* input : number of bits  */

-		Word16 ** prms

-		)

-{

-	Word16 i, bit;

-	*prms += no_of_bits;                  

-	for (i = 0; i < no_of_bits; i++)

-	{

-		bit = (Word16) (value & 0x0001);    /* get lsb */

-		if (bit == 0)

-			*--(*prms) = BIT_0;

-		else

-			*--(*prms) = BIT_1;

-		value >>= 1;          

-	}

-	*prms += no_of_bits;                  

-	return;

-}

-

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+       File: bits.c
+
+	   Description: Performs bit stream manipulation
+
+************************************************************************/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include "typedef.h"
+#include "basic_op.h"
+#include "cnst.h"
+#include "bits.h"
+#include "acelp.h"
+#include "dtx.h"
+#include "mime_io.tab"
+
+
+int PackBits(Word16 prms[],             /*  i: analysis parameters */
+			 Word16 coding_mode,        /*  i: coding bit-stream ratio mode */
+			 Word16 mode,               /*  i: coding bit-stream ratio mode*/
+			 Coder_State *st            /*i/o: coder global parameters struct */
+			 )
+{
+	Word16 i, frame_type;
+	UWord8 temp;
+	UWord8 *stream_ptr;
+	Word16 bitstreamformat = st->frameType;
+
+	unsigned short* dataOut = st->outputStream;
+
+	if (coding_mode == MRDTX)
+	{
+		st->sid_update_counter--;
+
+		if (st->prev_ft == TX_SPEECH)
+		{
+			frame_type = TX_SID_FIRST;
+			st->sid_update_counter = 3;
+		} else
+		{
+			if ((st->sid_handover_debt > 0) && (st->sid_update_counter > 2))
+			{
+				/* ensure extra updates are  properly delayed after a possible SID_FIRST */
+				frame_type = TX_SID_UPDATE;
+				st->sid_handover_debt--;
+			} else
+			{
+				if (st->sid_update_counter == 0)
+				{
+					frame_type = TX_SID_UPDATE;
+					st->sid_update_counter = 8;
+				} else
+				{
+					frame_type = TX_NO_DATA;
+				}
+			}
+		}
+	} else
+	{
+		st->sid_update_counter = 8;
+		frame_type = TX_SPEECH;
+	}
+	st->prev_ft = frame_type;
+
+	if(bitstreamformat == 0)				/* default file format */
+	{
+		*(dataOut) = TX_FRAME_TYPE;
+		*(dataOut + 1) = frame_type;
+		*(dataOut + 2) = mode;
+		for (i = 0; i < nb_of_bits[coding_mode]; i++)
+		{
+			*(dataOut + 3 + i) = prms[i];
+		}
+		return  (3 + nb_of_bits[coding_mode])<<1;
+	} else
+	{
+		if (bitstreamformat == 1)		/* ITU file format */
+		{
+			*(dataOut) = 0x6b21;
+			if(frame_type != TX_NO_DATA && frame_type != TX_SID_FIRST)
+			{
+				*(dataOut + 1) = nb_of_bits[coding_mode];
+				for (i = 0; i < nb_of_bits[coding_mode]; i++)
+				{
+					if(prms[i] == BIT_0){
+						*(dataOut + 2 + i) = BIT_0_ITU;
+					}
+					else{
+						*(dataOut + 2 + i) = BIT_1_ITU;
+					}
+				}
+				return (2 + nb_of_bits[coding_mode])<<1;
+			} else
+			{
+				*(dataOut + 1) = 0;
+				return 2<<1;
+			}
+		} else							/* MIME/storage file format */
+		{
+#define MRSID 9
+			/* change mode index in case of SID frame */
+			if (coding_mode == MRDTX)
+			{
+				coding_mode = MRSID;
+				if (frame_type == TX_SID_FIRST)
+				{
+					for (i = 0; i < NBBITS_SID; i++)	prms[i] = BIT_0;
+				}
+			}
+			/* -> force NO_DATA frame */
+			if (coding_mode < 0 || coding_mode > 15 || (coding_mode > MRSID && coding_mode < 14))
+			{
+				coding_mode = 15;
+			}
+			/* mark empty frames between SID updates as NO_DATA frames */
+			if (coding_mode == MRSID && frame_type == TX_NO_DATA)
+			{
+				coding_mode = 15;
+			}
+			/* set pointer for packed frame, note that we handle data as bytes */
+			stream_ptr = (UWord8*)dataOut;
+			/* insert table of contents (ToC) byte at the beginning of the packet */
+			*stream_ptr = toc_byte[coding_mode];
+			stream_ptr++;
+			temp = 0;
+			/* sort and pack AMR-WB speech or SID bits */
+			for (i = 1; i < unpacked_size[coding_mode] + 1; i++)
+			{
+				if (prms[sort_ptr[coding_mode][i-1]] == BIT_1)
+				{
+					temp++;
+				}
+				if (i&0x7)
+				{
+					temp <<= 1;
+				}
+				else
+				{
+					*stream_ptr = temp;
+					stream_ptr++;
+					temp = 0;
+				}
+			}
+			/* insert SID type indication and speech mode in case of SID frame */
+			if (coding_mode == MRSID)
+			{
+				if (frame_type == TX_SID_UPDATE)
+				{
+					temp++;
+				}
+				temp <<= 4;
+				temp += mode & 0x000F;
+			}
+			/* insert unused bits (zeros) at the tail of the last byte */
+			if (unused_size[coding_mode])
+			{
+				temp <<= (unused_size[coding_mode] - 1);
+			}
+			*stream_ptr = temp;
+			/* write packed frame into file (1 byte added to cover ToC entry) */
+			return (1 + packed_size[coding_mode]);
+		}
+	}
+}
+
+/*-----------------------------------------------------*
+* Parm_serial -> convert parameters to serial stream  *
+*-----------------------------------------------------*/
+
+void Parm_serial(
+		Word16 value,                         /* input : parameter value */
+		Word16 no_of_bits,                    /* input : number of bits  */
+		Word16 ** prms
+		)
+{
+	Word16 i, bit;
+	*prms += no_of_bits;
+	for (i = 0; i < no_of_bits; i++)
+	{
+		bit = (Word16) (value & 0x0001);    /* get lsb */
+		if (bit == 0)
+			*--(*prms) = BIT_0;
+		else
+			*--(*prms) = BIT_1;
+		value >>= 1;
+	}
+	*prms += no_of_bits;
+	return;
+}
+
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/c2t64fx.c b/media/libstagefright/codecs/amrwbenc/src/c2t64fx.c
index 39fc4c5..18698e2 100644
--- a/media/libstagefright/codecs/amrwbenc/src/c2t64fx.c
+++ b/media/libstagefright/codecs/amrwbenc/src/c2t64fx.c
@@ -1,297 +1,297 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/************************************************************************

-*      File: c2t64fx.c                                                  *

-*                                                                       *

-*	   Description:Performs algebraic codebook search for 6.60kbits mode*

-*                                                                       *

-*************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "math_op.h"

-#include "acelp.h"

-#include "cnst.h"

-

-#define NB_TRACK  2

-#define STEP      2

-#define NB_POS    32

-#define MSIZE     1024

-

-/*************************************************************************

-* Function:  ACELP_2t64_fx()                                             *

-*                                                                        *

-* 12 bits algebraic codebook.                                            *

-* 2 tracks x 32 positions per track = 64 samples.                        *

-*                                                                        *

-* 12 bits --> 2 pulses in a frame of 64 samples.                         *

-*                                                                        *

-* All pulses can have two (2) possible amplitudes: +1 or -1.             *

-* Each pulse can have 32 possible positions.                             *

-**************************************************************************/

-

-void ACELP_2t64_fx(

-		Word16 dn[],                          /* (i) <12b : correlation between target x[] and H[]      */

-		Word16 cn[],                          /* (i) <12b : residual after long term prediction         */

-		Word16 H[],                           /* (i) Q12: impulse response of weighted synthesis filter */

-		Word16 code[],                        /* (o) Q9 : algebraic (fixed) codebook excitation         */

-		Word16 y[],                           /* (o) Q9 : filtered fixed codebook excitation            */

-		Word16 * index                        /* (o) : index (12): 5+1+5+1 = 11 bits.                   */

-		)

-{

-	Word32 i, j, k, i0, i1, ix, iy, pos, pos2;

-	Word16 ps, psk, ps1, ps2, alpk, alp1, alp2, sq;

-	Word16 alp, val, exp, k_cn, k_dn;

-	Word16 *p0, *p1, *p2, *psign;

-	Word16 *h, *h_inv, *ptr_h1, *ptr_h2, *ptr_hf;

-

-	Word16 sign[L_SUBFR], vec[L_SUBFR], dn2[L_SUBFR];

-	Word16 h_buf[4 * L_SUBFR] = {0};

-	Word16 rrixix[NB_TRACK][NB_POS];

-	Word16 rrixiy[MSIZE];

-	Word32 s, cor;

-

-	/*----------------------------------------------------------------*

-	 * Find sign for each pulse position.                             *

-	 *----------------------------------------------------------------*/

-	alp = 8192;                              /* alp = 2.0 (Q12) */

-

-	/* calculate energy for normalization of cn[] and dn[] */

-	/* set k_cn = 32..32767 (ener_cn = 2^30..256-0) */

-#ifdef ASM_OPT             /* asm optimization branch */

-	s = Dot_product12_asm(cn, cn, L_SUBFR, &exp);

-#else

-	s = Dot_product12(cn, cn, L_SUBFR, &exp);

-#endif

-

-	Isqrt_n(&s, &exp);

-	s = L_shl(s, add1(exp, 5));             

-	k_cn = vo_round(s);

-

-	/* set k_dn = 32..512 (ener_dn = 2^30..2^22) */

-#ifdef ASM_OPT                  /* asm optimization branch */

-	s = Dot_product12_asm(dn, dn, L_SUBFR, &exp);

-#else

-	s = Dot_product12(dn, dn, L_SUBFR, &exp);

-#endif

-

-	Isqrt_n(&s, &exp);

-	k_dn = vo_round(L_shl(s, (exp + 8)));    /* k_dn = 256..4096 */

-	k_dn = vo_mult_r(alp, k_dn);              /* alp in Q12 */

-

-	/* mix normalized cn[] and dn[] */

-	p0 = cn;

-	p1 = dn;

-	p2 = dn2;

-

-	for (i = 0; i < L_SUBFR/4; i++)

-	{

-		s = (k_cn* (*p0++))+(k_dn * (*p1++));

-		*p2++ = s >> 7;

-		s = (k_cn* (*p0++))+(k_dn * (*p1++));

-		*p2++ = s >> 7;

-		s = (k_cn* (*p0++))+(k_dn * (*p1++));

-		*p2++ = s >> 7;

-		s = (k_cn* (*p0++))+(k_dn * (*p1++));

-		*p2++ = s >> 7; 

-	}

-

-	/* set sign according to dn2[] = k_cn*cn[] + k_dn*dn[]    */

-	for (i = 0; i < L_SUBFR; i ++)

-	{

-		val = dn[i];                   

-		ps = dn2[i];                   

-		if (ps >= 0)

-		{

-			sign[i] = 32767;             /* sign = +1 (Q12) */

-			vec[i] = -32768;           

-		} else

-		{

-			sign[i] = -32768;            /* sign = -1 (Q12) */

-			vec[i] = 32767;            

-			dn[i] = -val;

-		}

-	}

-	/*------------------------------------------------------------*

-	 * Compute h_inv[i].                                          *

-	 *------------------------------------------------------------*/

-	/* impulse response buffer for fast computation */

-	h = h_buf + L_SUBFR;                             

-	h_inv = h + (L_SUBFR<<1);         

-

-	for (i = 0; i < L_SUBFR; i++)

-	{

-		h[i] = H[i];                       

-		h_inv[i] = vo_negate(h[i]);           

-	}

-

-	/*------------------------------------------------------------*

-	 * Compute rrixix[][] needed for the codebook search.         *

-	 * Result is multiplied by 0.5                                *

-	 *------------------------------------------------------------*/

-	/* Init pointers to last position of rrixix[] */

-	p0 = &rrixix[0][NB_POS - 1];           

-	p1 = &rrixix[1][NB_POS - 1];           

-

-	ptr_h1 = h;                            

-	cor = 0x00010000L;                          /* for rounding */

-	for (i = 0; i < NB_POS; i++)

-	{

-		cor += ((*ptr_h1) * (*ptr_h1) << 1);

-		ptr_h1++;

-		*p1-- = (extract_h(cor) >> 1);            

-		cor += ((*ptr_h1) * (*ptr_h1) << 1);

-		ptr_h1++;

-		*p0-- = (extract_h(cor) >> 1);            

-	}

-

-	/*------------------------------------------------------------*

-	 * Compute rrixiy[][] needed for the codebook search.         *

-	 *------------------------------------------------------------*/

-	pos = MSIZE - 1;                       

-	pos2 = MSIZE - 2;                      

-	ptr_hf = h + 1;                        

-

-	for (k = 0; k < NB_POS; k++)

-	{

-		p1 = &rrixiy[pos];                 

-		p0 = &rrixiy[pos2];                

-		cor = 0x00008000L;                        /* for rounding */

-		ptr_h1 = h;                        

-		ptr_h2 = ptr_hf;                   

-

-		for (i = (k + 1); i < NB_POS; i++)

-		{

-			cor += ((*ptr_h1) * (*ptr_h2))<<1;

-			ptr_h1++;

-			ptr_h2++;

-			*p1 = extract_h(cor);          

-			cor += ((*ptr_h1) * (*ptr_h2))<<1;

-			ptr_h1++;

-			ptr_h2++;

-			*p0 = extract_h(cor);         

-

-			p1 -= (NB_POS + 1);

-			p0 -= (NB_POS + 1);

-		}

-		cor += ((*ptr_h1) * (*ptr_h2))<<1;

-		ptr_h1++;

-		ptr_h2++;

-		*p1 = extract_h(cor);              

-

-		pos -= NB_POS;

-		pos2--;

-		ptr_hf += STEP;

-	}

-

-	/*------------------------------------------------------------*

-	 * Modification of rrixiy[][] to take signs into account.     *

-	 *------------------------------------------------------------*/

-	p0 = rrixiy;                          

-	for (i = 0; i < L_SUBFR; i += STEP)

-	{

-		psign = sign;                      

-		if (psign[i] < 0)

-		{

-			psign = vec;                   

-		}

-		for (j = 1; j < L_SUBFR; j += STEP)

-		{

-			*p0 = vo_mult(*p0, psign[j]);     

-			p0++;

-		}

-	}

-	/*-------------------------------------------------------------------*

-	 * search 2 pulses:                                                  *

-	 * ~@~~~~~~~~~~~~~~                                                  *

-	 * 32 pos x 32 pos = 1024 tests (all combinaisons is tested)         *

-	 *-------------------------------------------------------------------*/

-	p0 = rrixix[0];                        

-	p1 = rrixix[1];                        

-	p2 = rrixiy;                          

-

-	psk = -1;                              

-	alpk = 1;                              

-	ix = 0;                                

-	iy = 1;                                

-

-	for (i0 = 0; i0 < L_SUBFR; i0 += STEP)

-	{

-		ps1 = dn[i0];                      

-		alp1 = (*p0++);                    

-		pos = -1;                          

-		for (i1 = 1; i1 < L_SUBFR; i1 += STEP)

-		{

-			ps2 = add1(ps1, dn[i1]);

-			alp2 = add1(alp1, add1(*p1++, *p2++));

-			sq = vo_mult(ps2, ps2);

-			s = vo_L_mult(alpk, sq) - ((psk * alp2)<<1);

-			if (s > 0)

-			{

-				psk = sq;                  

-				alpk = alp2;               

-				pos = i1;                  

-			}

-		}

-		p1 -= NB_POS;

-		if (pos >= 0)

-		{

-			ix = i0;                      

-			iy = pos;                      

-		}

-	}

-	/*-------------------------------------------------------------------*

-	 * Build the codeword, the filtered codeword and index of codevector.*

-	 *-------------------------------------------------------------------*/

-

-	for (i = 0; i < L_SUBFR; i++)

-	{

-		code[i] = 0;                       

-	}

-

-	i0 = (ix >> 1);                       /* pos of pulse 1 (0..31) */

-	i1 = (iy >> 1);                       /* pos of pulse 2 (0..31) */

-	if (sign[ix] > 0)

-	{

-		code[ix] = 512;                     /* codeword in Q9 format */

-		p0 = h - ix;                       

-	} else

-	{

-		code[ix] = -512;                   

-		i0 += NB_POS;                      

-		p0 = h_inv - ix;                   

-	}

-	if (sign[iy] > 0)

-	{

-		code[iy] = 512;                    

-		p1 = h - iy;                       

-	} else

-	{

-		code[iy] = -512;                   

-		i1 += NB_POS;                      

-		p1 = h_inv - iy;                   

-	}

-	*index = add1((i0 << 6), i1);          

-	for (i = 0; i < L_SUBFR; i++)

-	{

-		y[i] = vo_shr_r(add1((*p0++), (*p1++)), 3);

-	}

-	return;

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/************************************************************************
+*      File: c2t64fx.c                                                  *
+*                                                                       *
+*	   Description:Performs algebraic codebook search for 6.60kbits mode*
+*                                                                       *
+*************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "math_op.h"
+#include "acelp.h"
+#include "cnst.h"
+
+#define NB_TRACK  2
+#define STEP      2
+#define NB_POS    32
+#define MSIZE     1024
+
+/*************************************************************************
+* Function:  ACELP_2t64_fx()                                             *
+*                                                                        *
+* 12 bits algebraic codebook.                                            *
+* 2 tracks x 32 positions per track = 64 samples.                        *
+*                                                                        *
+* 12 bits --> 2 pulses in a frame of 64 samples.                         *
+*                                                                        *
+* All pulses can have two (2) possible amplitudes: +1 or -1.             *
+* Each pulse can have 32 possible positions.                             *
+**************************************************************************/
+
+void ACELP_2t64_fx(
+		Word16 dn[],                          /* (i) <12b : correlation between target x[] and H[]      */
+		Word16 cn[],                          /* (i) <12b : residual after long term prediction         */
+		Word16 H[],                           /* (i) Q12: impulse response of weighted synthesis filter */
+		Word16 code[],                        /* (o) Q9 : algebraic (fixed) codebook excitation         */
+		Word16 y[],                           /* (o) Q9 : filtered fixed codebook excitation            */
+		Word16 * index                        /* (o) : index (12): 5+1+5+1 = 11 bits.                   */
+		)
+{
+	Word32 i, j, k, i0, i1, ix, iy, pos, pos2;
+	Word16 ps, psk, ps1, ps2, alpk, alp1, alp2, sq;
+	Word16 alp, val, exp, k_cn, k_dn;
+	Word16 *p0, *p1, *p2, *psign;
+	Word16 *h, *h_inv, *ptr_h1, *ptr_h2, *ptr_hf;
+
+	Word16 sign[L_SUBFR], vec[L_SUBFR], dn2[L_SUBFR];
+	Word16 h_buf[4 * L_SUBFR] = {0};
+	Word16 rrixix[NB_TRACK][NB_POS];
+	Word16 rrixiy[MSIZE];
+	Word32 s, cor;
+
+	/*----------------------------------------------------------------*
+	 * Find sign for each pulse position.                             *
+	 *----------------------------------------------------------------*/
+	alp = 8192;                              /* alp = 2.0 (Q12) */
+
+	/* calculate energy for normalization of cn[] and dn[] */
+	/* set k_cn = 32..32767 (ener_cn = 2^30..256-0) */
+#ifdef ASM_OPT             /* asm optimization branch */
+	s = Dot_product12_asm(cn, cn, L_SUBFR, &exp);
+#else
+	s = Dot_product12(cn, cn, L_SUBFR, &exp);
+#endif
+
+	Isqrt_n(&s, &exp);
+	s = L_shl(s, add1(exp, 5));
+	k_cn = vo_round(s);
+
+	/* set k_dn = 32..512 (ener_dn = 2^30..2^22) */
+#ifdef ASM_OPT                  /* asm optimization branch */
+	s = Dot_product12_asm(dn, dn, L_SUBFR, &exp);
+#else
+	s = Dot_product12(dn, dn, L_SUBFR, &exp);
+#endif
+
+	Isqrt_n(&s, &exp);
+	k_dn = vo_round(L_shl(s, (exp + 8)));    /* k_dn = 256..4096 */
+	k_dn = vo_mult_r(alp, k_dn);              /* alp in Q12 */
+
+	/* mix normalized cn[] and dn[] */
+	p0 = cn;
+	p1 = dn;
+	p2 = dn2;
+
+	for (i = 0; i < L_SUBFR/4; i++)
+	{
+		s = (k_cn* (*p0++))+(k_dn * (*p1++));
+		*p2++ = s >> 7;
+		s = (k_cn* (*p0++))+(k_dn * (*p1++));
+		*p2++ = s >> 7;
+		s = (k_cn* (*p0++))+(k_dn * (*p1++));
+		*p2++ = s >> 7;
+		s = (k_cn* (*p0++))+(k_dn * (*p1++));
+		*p2++ = s >> 7;
+	}
+
+	/* set sign according to dn2[] = k_cn*cn[] + k_dn*dn[]    */
+	for (i = 0; i < L_SUBFR; i ++)
+	{
+		val = dn[i];
+		ps = dn2[i];
+		if (ps >= 0)
+		{
+			sign[i] = 32767;             /* sign = +1 (Q12) */
+			vec[i] = -32768;
+		} else
+		{
+			sign[i] = -32768;            /* sign = -1 (Q12) */
+			vec[i] = 32767;
+			dn[i] = -val;
+		}
+	}
+	/*------------------------------------------------------------*
+	 * Compute h_inv[i].                                          *
+	 *------------------------------------------------------------*/
+	/* impulse response buffer for fast computation */
+	h = h_buf + L_SUBFR;
+	h_inv = h + (L_SUBFR<<1);
+
+	for (i = 0; i < L_SUBFR; i++)
+	{
+		h[i] = H[i];
+		h_inv[i] = vo_negate(h[i]);
+	}
+
+	/*------------------------------------------------------------*
+	 * Compute rrixix[][] needed for the codebook search.         *
+	 * Result is multiplied by 0.5                                *
+	 *------------------------------------------------------------*/
+	/* Init pointers to last position of rrixix[] */
+	p0 = &rrixix[0][NB_POS - 1];
+	p1 = &rrixix[1][NB_POS - 1];
+
+	ptr_h1 = h;
+	cor = 0x00010000L;                          /* for rounding */
+	for (i = 0; i < NB_POS; i++)
+	{
+		cor += ((*ptr_h1) * (*ptr_h1) << 1);
+		ptr_h1++;
+		*p1-- = (extract_h(cor) >> 1);
+		cor += ((*ptr_h1) * (*ptr_h1) << 1);
+		ptr_h1++;
+		*p0-- = (extract_h(cor) >> 1);
+	}
+
+	/*------------------------------------------------------------*
+	 * Compute rrixiy[][] needed for the codebook search.         *
+	 *------------------------------------------------------------*/
+	pos = MSIZE - 1;
+	pos2 = MSIZE - 2;
+	ptr_hf = h + 1;
+
+	for (k = 0; k < NB_POS; k++)
+	{
+		p1 = &rrixiy[pos];
+		p0 = &rrixiy[pos2];
+		cor = 0x00008000L;                        /* for rounding */
+		ptr_h1 = h;
+		ptr_h2 = ptr_hf;
+
+		for (i = (k + 1); i < NB_POS; i++)
+		{
+			cor += ((*ptr_h1) * (*ptr_h2))<<1;
+			ptr_h1++;
+			ptr_h2++;
+			*p1 = extract_h(cor);
+			cor += ((*ptr_h1) * (*ptr_h2))<<1;
+			ptr_h1++;
+			ptr_h2++;
+			*p0 = extract_h(cor);
+
+			p1 -= (NB_POS + 1);
+			p0 -= (NB_POS + 1);
+		}
+		cor += ((*ptr_h1) * (*ptr_h2))<<1;
+		ptr_h1++;
+		ptr_h2++;
+		*p1 = extract_h(cor);
+
+		pos -= NB_POS;
+		pos2--;
+		ptr_hf += STEP;
+	}
+
+	/*------------------------------------------------------------*
+	 * Modification of rrixiy[][] to take signs into account.     *
+	 *------------------------------------------------------------*/
+	p0 = rrixiy;
+	for (i = 0; i < L_SUBFR; i += STEP)
+	{
+		psign = sign;
+		if (psign[i] < 0)
+		{
+			psign = vec;
+		}
+		for (j = 1; j < L_SUBFR; j += STEP)
+		{
+			*p0 = vo_mult(*p0, psign[j]);
+			p0++;
+		}
+	}
+	/*-------------------------------------------------------------------*
+	 * search 2 pulses:                                                  *
+	 * ~@~~~~~~~~~~~~~~                                                  *
+	 * 32 pos x 32 pos = 1024 tests (all combinaisons is tested)         *
+	 *-------------------------------------------------------------------*/
+	p0 = rrixix[0];
+	p1 = rrixix[1];
+	p2 = rrixiy;
+
+	psk = -1;
+	alpk = 1;
+	ix = 0;
+	iy = 1;
+
+	for (i0 = 0; i0 < L_SUBFR; i0 += STEP)
+	{
+		ps1 = dn[i0];
+		alp1 = (*p0++);
+		pos = -1;
+		for (i1 = 1; i1 < L_SUBFR; i1 += STEP)
+		{
+			ps2 = add1(ps1, dn[i1]);
+			alp2 = add1(alp1, add1(*p1++, *p2++));
+			sq = vo_mult(ps2, ps2);
+			s = vo_L_mult(alpk, sq) - ((psk * alp2)<<1);
+			if (s > 0)
+			{
+				psk = sq;
+				alpk = alp2;
+				pos = i1;
+			}
+		}
+		p1 -= NB_POS;
+		if (pos >= 0)
+		{
+			ix = i0;
+			iy = pos;
+		}
+	}
+	/*-------------------------------------------------------------------*
+	 * Build the codeword, the filtered codeword and index of codevector.*
+	 *-------------------------------------------------------------------*/
+
+	for (i = 0; i < L_SUBFR; i++)
+	{
+		code[i] = 0;
+	}
+
+	i0 = (ix >> 1);                       /* pos of pulse 1 (0..31) */
+	i1 = (iy >> 1);                       /* pos of pulse 2 (0..31) */
+	if (sign[ix] > 0)
+	{
+		code[ix] = 512;                     /* codeword in Q9 format */
+		p0 = h - ix;
+	} else
+	{
+		code[ix] = -512;
+		i0 += NB_POS;
+		p0 = h_inv - ix;
+	}
+	if (sign[iy] > 0)
+	{
+		code[iy] = 512;
+		p1 = h - iy;
+	} else
+	{
+		code[iy] = -512;
+		i1 += NB_POS;
+		p1 = h_inv - iy;
+	}
+	*index = add1((i0 << 6), i1);
+	for (i = 0; i < L_SUBFR; i++)
+	{
+		y[i] = vo_shr_r(add1((*p0++), (*p1++)), 3);
+	}
+	return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/c4t64fx.c b/media/libstagefright/codecs/amrwbenc/src/c4t64fx.c
index 27ba95d..1ecc11f 100644
--- a/media/libstagefright/codecs/amrwbenc/src/c4t64fx.c
+++ b/media/libstagefright/codecs/amrwbenc/src/c4t64fx.c
@@ -1,1043 +1,1043 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*      File: c4t64fx.c                                                 *

-*                                                                      *

-*	   Description:Performs algebraic codebook search for higher modes *

-*                                                                      *

-************************************************************************/

-

-/************************************************************************

-* Function: ACELP_4t64_fx()                                             *

-*                                                                       *

-* 20, 36, 44, 52, 64, 72, 88 bits algebraic codebook.                   *

-* 4 tracks x 16 positions per track = 64 samples.                       *

-*                                                                       *

-* 20 bits --> 4 pulses in a frame of 64 samples.                        *

-* 36 bits --> 8 pulses in a frame of 64 samples.                        *

-* 44 bits --> 10 pulses in a frame of 64 samples.                       *

-* 52 bits --> 12 pulses in a frame of 64 samples.                       *

-* 64 bits --> 16 pulses in a frame of 64 samples.                       *

-* 72 bits --> 18 pulses in a frame of 64 samples.                       *

-* 88 bits --> 24 pulses in a frame of 64 samples.                       *

-*                                                                       *

-* All pulses can have two (2) possible amplitudes: +1 or -1.            *

-* Each pulse can have sixteen (16) possible positions.                  *

-*************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "math_op.h"

-#include "acelp.h"

-#include "cnst.h"

-

-#include "q_pulse.h"

-

-static Word16 tipos[36] = {

-	0, 1, 2, 3,                            /* starting point &ipos[0], 1st iter */

-	1, 2, 3, 0,                            /* starting point &ipos[4], 2nd iter */

-	2, 3, 0, 1,                            /* starting point &ipos[8], 3rd iter */

-	3, 0, 1, 2,                            /* starting point &ipos[12], 4th iter */

-	0, 1, 2, 3,

-	1, 2, 3, 0,

-	2, 3, 0, 1,

-	3, 0, 1, 2,

-	0, 1, 2, 3};                           /* end point for 24 pulses &ipos[35], 4th iter */

-

-#define NB_PULSE_MAX  24

-

-#define L_SUBFR   64

-#define NB_TRACK  4

-#define STEP      4

-#define NB_POS    16

-#define MSIZE     256

-#define NB_MAX    8

-#define NPMAXPT   ((NB_PULSE_MAX+NB_TRACK-1)/NB_TRACK)

-

-/* Private functions */

-void cor_h_vec_012(

-		Word16 h[],                           /* (i) scaled impulse response                 */

-		Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */

-		Word16 track,                         /* (i) track to use                            */

-		Word16 sign[],                        /* (i) sign vector                             */

-		Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */

-		Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */

-		Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */

-		);

-

-void cor_h_vec_012_asm(

-		Word16 h[],                           /* (i) scaled impulse response                 */

-		Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */

-		Word16 track,                         /* (i) track to use                            */

-		Word16 sign[],                        /* (i) sign vector                             */

-		Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */

-		Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */

-		Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */

-		);

-

-void cor_h_vec_30(

-		Word16 h[],                           /* (i) scaled impulse response                 */

-		Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */

-		Word16 track,                         /* (i) track to use                            */

-		Word16 sign[],                        /* (i) sign vector                             */

-		Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */

-		Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */

-		Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */

-		);

-

-void search_ixiy(

-		Word16 nb_pos_ix,                     /* (i) nb of pos for pulse 1 (1..8)       */

-		Word16 track_x,                       /* (i) track of pulse 1                   */

-		Word16 track_y,                       /* (i) track of pulse 2                   */

-		Word16 * ps,                          /* (i/o) correlation of all fixed pulses  */

-		Word16 * alp,                         /* (i/o) energy of all fixed pulses       */

-		Word16 * ix,                          /* (o) position of pulse 1                */

-		Word16 * iy,                          /* (o) position of pulse 2                */

-		Word16 dn[],                          /* (i) corr. between target and h[]       */

-		Word16 dn2[],                         /* (i) vector of selected positions       */

-		Word16 cor_x[],                       /* (i) corr. of pulse 1 with fixed pulses */

-		Word16 cor_y[],                       /* (i) corr. of pulse 2 with fixed pulses */

-		Word16 rrixiy[][MSIZE]                /* (i) corr. of pulse 1 with pulse 2   */

-		);

-

-

-void ACELP_4t64_fx(

-		Word16 dn[],                          /* (i) <12b : correlation between target x[] and H[]      */

-		Word16 cn[],                          /* (i) <12b : residual after long term prediction         */

-		Word16 H[],                           /* (i) Q12: impulse response of weighted synthesis filter */

-		Word16 code[],                        /* (o) Q9 : algebraic (fixed) codebook excitation         */

-		Word16 y[],                           /* (o) Q9 : filtered fixed codebook excitation            */

-		Word16 nbbits,                        /* (i) : 20, 36, 44, 52, 64, 72 or 88 bits                */

-		Word16 ser_size,                      /* (i) : bit rate                                         */

-		Word16 _index[]                       /* (o) : index (20): 5+5+5+5 = 20 bits.                   */

-		/* (o) : index (36): 9+9+9+9 = 36 bits.                   */

-		/* (o) : index (44): 13+9+13+9 = 44 bits.                 */

-		/* (o) : index (52): 13+13+13+13 = 52 bits.               */

-		/* (o) : index (64): 2+2+2+2+14+14+14+14 = 64 bits.       */

-		/* (o) : index (72): 10+2+10+2+10+14+10+14 = 72 bits.     */

-		/* (o) : index (88): 11+11+11+11+11+11+11+11 = 88 bits.   */

-		)

-{

-	Word32 i, j, k;

-	Word16 st, ix, iy, pos, index, track, nb_pulse, nbiter, j_temp;

-	Word16 psk, ps, alpk, alp, val, k_cn, k_dn, exp;

-	Word16 *p0, *p1, *p2, *p3, *psign;

-	Word16 *h, *h_inv, *ptr_h1, *ptr_h2, *ptr_hf, h_shift;

-	Word32 s, cor, L_tmp, L_index;

-	Word16 dn2[L_SUBFR], sign[L_SUBFR], vec[L_SUBFR];

-	Word16 ind[NPMAXPT * NB_TRACK];

-	Word16 codvec[NB_PULSE_MAX], nbpos[10];

-	Word16 cor_x[NB_POS], cor_y[NB_POS], pos_max[NB_TRACK];

-	Word16 h_buf[4 * L_SUBFR];

-	Word16 rrixix[NB_TRACK][NB_POS], rrixiy[NB_TRACK][MSIZE];

-	Word16 ipos[NB_PULSE_MAX];

-

-	switch (nbbits)

-	{

-		case 20:                               /* 20 bits, 4 pulses, 4 tracks */

-			nbiter = 4;                          /* 4x16x16=1024 loop */

-			alp = 8192;                          /* alp = 2.0 (Q12) */

-			nb_pulse = 4;                      

-			nbpos[0] = 4;                      

-			nbpos[1] = 8;                      

-			break;

-		case 36:                               /* 36 bits, 8 pulses, 4 tracks */

-			nbiter = 4;                          /* 4x20x16=1280 loop */

-			alp = 4096;                          /* alp = 1.0 (Q12) */

-			nb_pulse = 8;                      

-			nbpos[0] = 4;                      

-			nbpos[1] = 8;                      

-			nbpos[2] = 8;                      

-			break;

-		case 44:                               /* 44 bits, 10 pulses, 4 tracks */

-			nbiter = 4;                          /* 4x26x16=1664 loop */

-			alp = 4096;                          /* alp = 1.0 (Q12) */

-			nb_pulse = 10;                     

-			nbpos[0] = 4;                      

-			nbpos[1] = 6;                      

-			nbpos[2] = 8;                      

-			nbpos[3] = 8;                      

-			break;

-		case 52:                               /* 52 bits, 12 pulses, 4 tracks */

-			nbiter = 4;                          /* 4x26x16=1664 loop */

-			alp = 4096;                          /* alp = 1.0 (Q12) */

-			nb_pulse = 12;                     

-			nbpos[0] = 4;                      

-			nbpos[1] = 6;                      

-			nbpos[2] = 8;                      

-			nbpos[3] = 8;                      

-			break;

-		case 64:                               /* 64 bits, 16 pulses, 4 tracks */

-			nbiter = 3;                          /* 3x36x16=1728 loop */

-			alp = 3277;                          /* alp = 0.8 (Q12) */

-			nb_pulse = 16;                     

-			nbpos[0] = 4;                      

-			nbpos[1] = 4;                      

-			nbpos[2] = 6;                      

-			nbpos[3] = 6;                      

-			nbpos[4] = 8;                      

-			nbpos[5] = 8;                      

-			break;

-		case 72:                               /* 72 bits, 18 pulses, 4 tracks */

-			nbiter = 3;                          /* 3x35x16=1680 loop */

-			alp = 3072;                          /* alp = 0.75 (Q12) */

-			nb_pulse = 18;                     

-			nbpos[0] = 2;                      

-			nbpos[1] = 3;                      

-			nbpos[2] = 4;                      

-			nbpos[3] = 5;                      

-			nbpos[4] = 6;                      

-			nbpos[5] = 7;                      

-			nbpos[6] = 8;                      

-			break;

-		case 88:                               /* 88 bits, 24 pulses, 4 tracks */

-			if(ser_size > 462)

-				nbiter = 1;

-			else

-				nbiter = 2;                    /* 2x53x16=1696 loop */

-

-			alp = 2048;                          /* alp = 0.5 (Q12) */

-			nb_pulse = 24;                     

-			nbpos[0] = 2;                      

-			nbpos[1] = 2;                      

-			nbpos[2] = 3;                      

-			nbpos[3] = 4;                      

-			nbpos[4] = 5;                      

-			nbpos[5] = 6;                      

-			nbpos[6] = 7;                      

-			nbpos[7] = 8;                      

-			nbpos[8] = 8;                      

-			nbpos[9] = 8;                      

-			break;

-		default:

-			nbiter = 0;

-			alp = 0;

-			nb_pulse = 0;

-	}

-

-	for (i = 0; i < nb_pulse; i++)

-	{

-		codvec[i] = i;                     

-	}

-

-	/*----------------------------------------------------------------*

-	 * Find sign for each pulse position.                             *

-	 *----------------------------------------------------------------*/

-	/* calculate energy for normalization of cn[] and dn[] */

-	/* set k_cn = 32..32767 (ener_cn = 2^30..256-0) */

-#ifdef ASM_OPT                  /* asm optimization branch */

-	s = Dot_product12_asm(cn, cn, L_SUBFR, &exp);

-#else

-	s = Dot_product12(cn, cn, L_SUBFR, &exp);

-#endif

-

-	Isqrt_n(&s, &exp);

-	s = L_shl(s, (exp + 5)); 

-	k_cn = extract_h(L_add(s, 0x8000));

-

-	/* set k_dn = 32..512 (ener_dn = 2^30..2^22) */

-#ifdef ASM_OPT                      /* asm optimization branch */

-	s = Dot_product12_asm(dn, dn, L_SUBFR, &exp);

-#else

-	s = Dot_product12(dn, dn, L_SUBFR, &exp);

-#endif

-

-	Isqrt_n(&s, &exp);

-	k_dn = (L_shl(s, (exp + 5 + 3)) + 0x8000) >> 16;    /* k_dn = 256..4096 */

-	k_dn = vo_mult_r(alp, k_dn);              /* alp in Q12 */

-

-	/* mix normalized cn[] and dn[] */

-	p0 = cn;

-	p1 = dn;

-	p2 = dn2;

-

-	for (i = 0; i < L_SUBFR/4; i++)

-	{

-		s = (k_cn* (*p0++))+(k_dn * (*p1++));

-		*p2++ = s >> 7;

-		s = (k_cn* (*p0++))+(k_dn * (*p1++));

-		*p2++ = s >> 7;

-		s = (k_cn* (*p0++))+(k_dn * (*p1++));

-		*p2++ = s >> 7;

-		s = (k_cn* (*p0++))+(k_dn * (*p1++));

-		*p2++ = s >> 7; 

-	}

-

-	/* set sign according to dn2[] = k_cn*cn[] + k_dn*dn[]    */

-	for(i = 0; i < L_SUBFR; i++)

-	{

-		val = dn[i];                   

-		ps = dn2[i];                   

-		if (ps >= 0)

-		{

-			sign[i] = 32767;             /* sign = +1 (Q12) */

-			vec[i] = -32768;           

-		} else

-		{

-			sign[i] = -32768;            /* sign = -1 (Q12) */

-			vec[i] = 32767;            

-			dn[i] = -val;

-			dn2[i] = -ps;

-		}

-	}

-	/*----------------------------------------------------------------*

-	 * Select NB_MAX position per track according to max of dn2[].    *

-	 *----------------------------------------------------------------*/

-	pos = 0;

-	for (i = 0; i < NB_TRACK; i++)

-	{

-		for (k = 0; k < NB_MAX; k++)

-		{

-			ps = -1;                       

-			for (j = i; j < L_SUBFR; j += STEP)

-			{

-				if(dn2[j] > ps)

-				{

-					ps = dn2[j];          

-					pos = j;               

-				}

-			}

-			dn2[pos] = (k - NB_MAX);     /* dn2 < 0 when position is selected */

-			if (k == 0)

-			{

-				pos_max[i] = pos;          

-			}

-		}

-	}

-

-	/*--------------------------------------------------------------*

-	 * Scale h[] to avoid overflow and to get maximum of precision  *

-	 * on correlation.                                              *

-	 *                                                              *

-	 * Maximum of h[] (h[0]) is fixed to 2048 (MAX16 / 16).         *

-	 *  ==> This allow addition of 16 pulses without saturation.    *

-	 *                                                              *

-	 * Energy worst case (on resonant impulse response),            *

-	 * - energy of h[] is approximately MAX/16.                     *

-	 * - During search, the energy is divided by 8 to avoid         *

-	 *   overflow on "alp". (energy of h[] = MAX/128).              *

-	 *  ==> "alp" worst case detected is 22854 on sinusoidal wave.  *

-	 *--------------------------------------------------------------*/

-

-	/* impulse response buffer for fast computation */

-

-	h = h_buf;                             

-	h_inv = h_buf + (2 * L_SUBFR);   

-	L_tmp = 0;

-	for (i = 0; i < L_SUBFR; i++)

-	{

-		*h++ = 0;                          

-		*h_inv++ = 0;   

-		L_tmp += (H[i] * H[i]) << 1;

-	}

-	/* scale h[] down (/2) when energy of h[] is high with many pulses used */

-	val = extract_h(L_tmp);

-	h_shift = 0;                           

-

-	if ((nb_pulse >= 12) && (val > 1024))

-	{

-		h_shift = 1;                       

-	}

-	p0 = H;

-	p1 = h;

-	p2 = h_inv;

-

-	for (i = 0; i < L_SUBFR/4; i++)

-	{

-		*p1 = *p0++ >> h_shift;         

-		*p2++ = -(*p1++);  

-		*p1 = *p0++ >> h_shift;         

-		*p2++ = -(*p1++); 

-		*p1 = *p0++ >> h_shift;         

-		*p2++ = -(*p1++); 

-		*p1 = *p0++ >> h_shift;         

-		*p2++ = -(*p1++); 

-	}

-

-	/*------------------------------------------------------------*

-	 * Compute rrixix[][] needed for the codebook search.         *

-	 * This algorithm compute impulse response energy of all      *

-	 * positions (16) in each track (4).       Total = 4x16 = 64. *

-	 *------------------------------------------------------------*/

-

-	/* storage order --> i3i3, i2i2, i1i1, i0i0 */

-

-	/* Init pointers to last position of rrixix[] */

-	p0 = &rrixix[0][NB_POS - 1];           

-	p1 = &rrixix[1][NB_POS - 1];           

-	p2 = &rrixix[2][NB_POS - 1];           

-	p3 = &rrixix[3][NB_POS - 1];           

-

-	ptr_h1 = h;                            

-	cor = 0x00008000L;                             /* for rounding */

-	for (i = 0; i < NB_POS; i++)

-	{

-		cor += vo_L_mult((*ptr_h1), (*ptr_h1));

-		ptr_h1++;

-		*p3-- = extract_h(cor);            

-		cor += vo_L_mult((*ptr_h1), (*ptr_h1));

-		ptr_h1++;

-		*p2-- = extract_h(cor);            

-		cor += vo_L_mult((*ptr_h1), (*ptr_h1));

-		ptr_h1++;

-		*p1-- = extract_h(cor);            

-		cor += vo_L_mult((*ptr_h1), (*ptr_h1));

-		ptr_h1++;

-		*p0-- = extract_h(cor);            

-	}

-

-	/*------------------------------------------------------------*

-	 * Compute rrixiy[][] needed for the codebook search.         *

-	 * This algorithm compute correlation between 2 pulses        *

-	 * (2 impulses responses) in 4 possible adjacents tracks.     *

-	 * (track 0-1, 1-2, 2-3 and 3-0).     Total = 4x16x16 = 1024. *

-	 *------------------------------------------------------------*/

-

-	/* storage order --> i2i3, i1i2, i0i1, i3i0 */

-

-	pos = MSIZE - 1;                       

-	ptr_hf = h + 1;                        

-

-	for (k = 0; k < NB_POS; k++)

-	{

-		p3 = &rrixiy[2][pos];              

-		p2 = &rrixiy[1][pos];              

-		p1 = &rrixiy[0][pos];              

-		p0 = &rrixiy[3][pos - NB_POS];     

-

-		cor = 0x00008000L;                   /* for rounding */

-		ptr_h1 = h;                        

-		ptr_h2 = ptr_hf;                   

-

-		for (i = k + 1; i < NB_POS; i++)

-		{

-			cor += vo_L_mult((*ptr_h1), (*ptr_h2));

-			ptr_h1++;

-			ptr_h2++;

-			*p3 = extract_h(cor);          

-			cor += vo_L_mult((*ptr_h1), (*ptr_h2));

-			ptr_h1++;

-			ptr_h2++;

-			*p2 = extract_h(cor);          

-			cor += vo_L_mult((*ptr_h1), (*ptr_h2));

-			ptr_h1++;

-			ptr_h2++;

-			*p1 = extract_h(cor);          

-			cor += vo_L_mult((*ptr_h1), (*ptr_h2));

-			ptr_h1++;

-			ptr_h2++;

-			*p0 = extract_h(cor);         

-

-			p3 -= (NB_POS + 1);

-			p2 -= (NB_POS + 1);

-			p1 -= (NB_POS + 1);

-			p0 -= (NB_POS + 1);

-		}

-		cor += vo_L_mult((*ptr_h1), (*ptr_h2));

-		ptr_h1++;

-		ptr_h2++;

-		*p3 = extract_h(cor);              

-		cor += vo_L_mult((*ptr_h1), (*ptr_h2));

-		ptr_h1++;

-		ptr_h2++;

-		*p2 = extract_h(cor);              

-		cor += vo_L_mult((*ptr_h1), (*ptr_h2));

-		ptr_h1++;

-		ptr_h2++;

-		*p1 = extract_h(cor);              

-

-		pos -= NB_POS;

-		ptr_hf += STEP;

-	}

-

-	/* storage order --> i3i0, i2i3, i1i2, i0i1 */

-

-	pos = MSIZE - 1;                       

-	ptr_hf = h + 3;                        

-

-	for (k = 0; k < NB_POS; k++)

-	{

-		p3 = &rrixiy[3][pos];              

-		p2 = &rrixiy[2][pos - 1];          

-		p1 = &rrixiy[1][pos - 1];          

-		p0 = &rrixiy[0][pos - 1];          

-

-		cor = 0x00008000L;								/* for rounding */

-		ptr_h1 = h;                        

-		ptr_h2 = ptr_hf;                   

-

-		for (i = k + 1; i < NB_POS; i++)

-		{

-			cor += vo_L_mult((*ptr_h1), (*ptr_h2));

-			ptr_h1++;

-			ptr_h2++;

-			*p3 = extract_h(cor);          

-			cor += vo_L_mult((*ptr_h1), (*ptr_h2));

-			ptr_h1++;

-			ptr_h2++;

-			*p2 = extract_h(cor);          

-			cor += vo_L_mult((*ptr_h1), (*ptr_h2));

-			ptr_h1++;

-			ptr_h2++;

-			*p1 = extract_h(cor);          

-			cor += vo_L_mult((*ptr_h1), (*ptr_h2));

-			ptr_h1++;

-			ptr_h2++;

-			*p0 = extract_h(cor);          

-

-			p3 -= (NB_POS + 1);

-			p2 -= (NB_POS + 1);

-			p1 -= (NB_POS + 1);

-			p0 -= (NB_POS + 1);

-		}

-		cor += vo_L_mult((*ptr_h1), (*ptr_h2));

-		ptr_h1++;

-		ptr_h2++;

-		*p3 = extract_h(cor);              

-

-		pos--;

-		ptr_hf += STEP;

-	}

-

-	/*------------------------------------------------------------*

-	 * Modification of rrixiy[][] to take signs into account.     *

-	 *------------------------------------------------------------*/

-

-	p0 = &rrixiy[0][0];                    

-

-	for (k = 0; k < NB_TRACK; k++)

-	{

-		j_temp = (k + 1)&0x03;

-		for (i = k; i < L_SUBFR; i += STEP)

-		{

-			psign = sign;                  

-			if (psign[i] < 0)

-			{

-				psign = vec;               

-			}

-			j = j_temp;

-			for (; j < L_SUBFR; j += STEP)

-			{

-				*p0 = vo_mult(*p0, psign[j]);    

-				p0++;

-			}

-		}

-	}

-

-	/*-------------------------------------------------------------------*

-	 *                       Deep first search                           *

-	 *-------------------------------------------------------------------*/

-

-	psk = -1;                              

-	alpk = 1;                              

-

-	for (k = 0; k < nbiter; k++)

-	{

-		j_temp = k<<2;

-		for (i = 0; i < nb_pulse; i++)

-			ipos[i] = tipos[j_temp + i];

-

-		if(nbbits == 20)

-		{

-			pos = 0;                       

-			ps = 0;                        

-			alp = 0;                       

-			for (i = 0; i < L_SUBFR; i++)

-			{

-				vec[i] = 0;                

-			}

-		} else if ((nbbits == 36) || (nbbits == 44))

-		{

-			/* first stage: fix 2 pulses */

-			pos = 2;

-

-			ix = ind[0] = pos_max[ipos[0]];

-			iy = ind[1] = pos_max[ipos[1]];

-			ps = dn[ix] + dn[iy];

-			i = ix >> 2;                /* ix / STEP */

-			j = iy >> 2;                /* iy / STEP */

-			s = rrixix[ipos[0]][i] << 13;

-			s += rrixix[ipos[1]][j] << 13;

-			i = (i << 4) + j;         /* (ix/STEP)*NB_POS + (iy/STEP) */

-			s += rrixiy[ipos[0]][i] << 14;

-			alp = (s + 0x8000) >> 16;

-			if (sign[ix] < 0)

-				p0 = h_inv - ix;

-			else

-				p0 = h - ix;

-			if (sign[iy] < 0)

-				p1 = h_inv - iy;

-			else

-				p1 = h - iy;

-

-			for (i = 0; i < L_SUBFR; i++)

-			{

-				vec[i] = (*p0++) + (*p1++);

-			}

-

-			if(nbbits == 44)

-			{

-				ipos[8] = 0;               

-				ipos[9] = 1;               

-			}

-		} else

-		{

-			/* first stage: fix 4 pulses */

-			pos = 4;

-

-			ix = ind[0] = pos_max[ipos[0]];  

-			iy = ind[1] = pos_max[ipos[1]];  

-			i = ind[2] = pos_max[ipos[2]];   

-			j = ind[3] = pos_max[ipos[3]];   

-			ps = add1(add1(add1(dn[ix], dn[iy]), dn[i]), dn[j]);

-

-			if (sign[ix] < 0)

-				p0 = h_inv - ix;

-			else

-				p0 = h - ix;

-

-			if (sign[iy] < 0)

-				p1 = h_inv - iy;

-			else

-				p1 = h - iy;

-

-			if (sign[i] < 0)

-				p2 = h_inv - i;

-			else

-				p2 = h - i;

-

-			if (sign[j] < 0)

-				p3 = h_inv - j;

-			else

-				p3 = h - j;

-

-			L_tmp = 0L;

-			for(i = 0; i < L_SUBFR; i++)

-			{

-				vec[i]  = add1(add1(add1(*p0++, *p1++), *p2++), *p3++);

-				L_tmp  += (vec[i] * vec[i]) << 1;

-			}

-

-			alp = ((L_tmp >> 3) + 0x8000) >> 16;

-

-			if(nbbits == 72)

-			{

-				ipos[16] = 0;              

-				ipos[17] = 1;              

-			}

-		}

-

-		/* other stages of 2 pulses */

-

-		for (j = pos, st = 0; j < nb_pulse; j += 2, st++)

-		{

-			/*--------------------------------------------------*

-			 * Calculate correlation of all possible positions  *

-			 * of the next 2 pulses with previous fixed pulses. *

-			 * Each pulse can have 16 possible positions.       *

-			 *--------------------------------------------------*/

-			if(ipos[j] == 3)

-			{

-				cor_h_vec_30(h, vec, ipos[j], sign, rrixix, cor_x, cor_y);

-			}

-			else

-			{

-#ifdef ASM_OPT                 /* asm optimization branch */

-				cor_h_vec_012_asm(h, vec, ipos[j], sign, rrixix, cor_x, cor_y);

-#else

-				cor_h_vec_012(h, vec, ipos[j], sign, rrixix, cor_x, cor_y);

-#endif

-			}

-			/*--------------------------------------------------*

-			 * Find best positions of 2 pulses.                 *

-			 *--------------------------------------------------*/

-			search_ixiy(nbpos[st], ipos[j], ipos[j + 1], &ps, &alp,

-					&ix, &iy, dn, dn2, cor_x, cor_y, rrixiy);

-

-			ind[j] = ix;                   

-			ind[j + 1] = iy;               

-

-			if (sign[ix] < 0)

-				p0 = h_inv - ix;

-			else

-				p0 = h - ix;

-			if (sign[iy] < 0)

-				p1 = h_inv - iy;

-			else

-				p1 = h - iy;

-

-			for (i = 0; i < L_SUBFR; i+=4)

-			{

-				vec[i]   += add1((*p0++), (*p1++));       

-				vec[i+1] += add1((*p0++), (*p1++));        

-				vec[i+2] += add1((*p0++), (*p1++));        

-				vec[i+3] += add1((*p0++), (*p1++));      

-			}

-		}

-		/* memorise the best codevector */

-		ps = vo_mult(ps, ps);

-		s = vo_L_msu(vo_L_mult(alpk, ps), psk, alp);

-		if (s > 0)

-		{

-			psk = ps;                      

-			alpk = alp;                    

-			for (i = 0; i < nb_pulse; i++)

-			{

-				codvec[i] = ind[i];        

-			}

-			for (i = 0; i < L_SUBFR; i++)

-			{

-				y[i] = vec[i];             

-			}

-		}

-	}

-	/*-------------------------------------------------------------------*

-	 * Build the codeword, the filtered codeword and index of codevector.*

-	 *-------------------------------------------------------------------*/

-	for (i = 0; i < NPMAXPT * NB_TRACK; i++)

-	{

-		ind[i] = -1;                       

-	}

-	for (i = 0; i < L_SUBFR; i++)

-	{

-		code[i] = 0;                       

-		y[i] = vo_shr_r(y[i], 3);               /* Q12 to Q9 */

-	}

-	val = (512 >> h_shift);               /* codeword in Q9 format */

-	for (k = 0; k < nb_pulse; k++)

-	{

-		i = codvec[k];                       /* read pulse position */

-		j = sign[i];                         /* read sign           */

-		index = i >> 2;                 /* index = pos of pulse (0..15) */

-		track = (Word16) (i & 0x03);         /* track = i % NB_TRACK (0..3)  */

-

-		if (j > 0)

-		{

-			code[i] += val;   

-			codvec[k] += 128;  

-		} else

-		{

-			code[i] -= val;   

-			index += NB_POS;    

-		}

-

-		i = (Word16)((vo_L_mult(track, NPMAXPT) >> 1));

-

-		while (ind[i] >= 0)

-		{

-			i += 1;

-		}

-		ind[i] = index;                    

-	}

-

-	k = 0;                                 

-	/* Build index of codevector */

-	if(nbbits == 20)

-	{

-		for (track = 0; track < NB_TRACK; track++)

-		{

-			_index[track] = (Word16)(quant_1p_N1(ind[k], 4));

-			k += NPMAXPT;

-		}

-	} else if(nbbits == 36)

-	{

-		for (track = 0; track < NB_TRACK; track++)

-		{

-			_index[track] = (Word16)(quant_2p_2N1(ind[k], ind[k + 1], 4));

-			k += NPMAXPT;

-		}

-	} else if(nbbits == 44)

-	{

-		for (track = 0; track < NB_TRACK - 2; track++)

-		{

-			_index[track] = (Word16)(quant_3p_3N1(ind[k], ind[k + 1], ind[k + 2], 4));

-			k += NPMAXPT;

-		}

-		for (track = 2; track < NB_TRACK; track++)

-		{

-			_index[track] = (Word16)(quant_2p_2N1(ind[k], ind[k + 1], 4));

-			k += NPMAXPT;

-		}

-	} else if(nbbits == 52)

-	{

-		for (track = 0; track < NB_TRACK; track++)

-		{

-			_index[track] = (Word16)(quant_3p_3N1(ind[k], ind[k + 1], ind[k + 2], 4));

-			k += NPMAXPT;

-		}

-	} else if(nbbits == 64)

-	{

-		for (track = 0; track < NB_TRACK; track++)

-		{

-			L_index = quant_4p_4N(&ind[k], 4);

-			_index[track] = (Word16)((L_index >> 14) & 3);

-			_index[track + NB_TRACK] = (Word16)(L_index & 0x3FFF);

-			k += NPMAXPT;

-		}

-	} else if(nbbits == 72)

-	{

-		for (track = 0; track < NB_TRACK - 2; track++)

-		{

-			L_index = quant_5p_5N(&ind[k], 4);

-			_index[track] = (Word16)((L_index >> 10) & 0x03FF);

-			_index[track + NB_TRACK] = (Word16)(L_index & 0x03FF);

-			k += NPMAXPT;

-		}

-		for (track = 2; track < NB_TRACK; track++)

-		{

-			L_index = quant_4p_4N(&ind[k], 4);

-			_index[track] = (Word16)((L_index >> 14) & 3);

-			_index[track + NB_TRACK] = (Word16)(L_index & 0x3FFF);

-			k += NPMAXPT;

-		}

-	} else if(nbbits == 88)

-	{

-		for (track = 0; track < NB_TRACK; track++)

-		{

-			L_index = quant_6p_6N_2(&ind[k], 4);

-			_index[track] = (Word16)((L_index >> 11) & 0x07FF);

-			_index[track + NB_TRACK] = (Word16)(L_index & 0x07FF);

-			k += NPMAXPT;

-		}

-	}

-	return;

-}

-

-

-/*-------------------------------------------------------------------*

- * Function  cor_h_vec()                                             *

- * ~~~~~~~~~~~~~~~~~~~~~                                             *

- * Compute correlations of h[] with vec[] for the specified track.   *

- *-------------------------------------------------------------------*/

-void cor_h_vec_30(

-		Word16 h[],                           /* (i) scaled impulse response                 */

-		Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */

-		Word16 track,                         /* (i) track to use                            */

-		Word16 sign[],                        /* (i) sign vector                             */

-		Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */

-		Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */

-		Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */

-		)

-{

-	Word32 i, j, pos, corr;

-	Word16 *p0, *p1, *p2,*p3,*cor_x,*cor_y;

-	Word32 L_sum1,L_sum2;

-	cor_x = cor_1;

-	cor_y = cor_2;

-	p0 = rrixix[track];

-	p3 = rrixix[0];

-	pos = track;

-

-	for (i = 0; i < NB_POS; i+=2)

-	{

-		L_sum1 = L_sum2 = 0L;

-		p1 = h;

-		p2 = &vec[pos];

-		for (j=pos;j < L_SUBFR; j++)

-		{

-			L_sum1 += *p1 * *p2;		

-			p2-=3;

-			L_sum2 += *p1++ * *p2;		

-			p2+=4;

-		}

-		p2-=3;

-		L_sum2 += *p1++ * *p2++;	

-		L_sum2 += *p1++ * *p2++;	

-		L_sum2 += *p1++ * *p2++;	

-

-		L_sum1 = (L_sum1 << 2);

-		L_sum2 = (L_sum2 << 2);

-

-		corr = vo_round(L_sum1);	

-		*cor_x++ = vo_mult(corr, sign[pos]) + (*p0++);

-		corr = vo_round(L_sum2);

-		*cor_y++ = vo_mult(corr, sign[pos-3]) + (*p3++);

-		pos += STEP;

-

-		L_sum1 = L_sum2 = 0L;

-		p1 = h;

-		p2 = &vec[pos];

-		for (j=pos;j < L_SUBFR; j++)

-		{

-			L_sum1 += *p1 * *p2;		

-			p2-=3;

-			L_sum2 += *p1++ * *p2;		

-			p2+=4;

-		}

-		p2-=3;

-		L_sum2 += *p1++ * *p2++;	

-		L_sum2 += *p1++ * *p2++;	

-		L_sum2 += *p1++ * *p2++;	

-

-		L_sum1 = (L_sum1 << 2);

-		L_sum2 = (L_sum2 << 2);

-

-		corr = vo_round(L_sum1);	

-		*cor_x++ = vo_mult(corr, sign[pos]) + (*p0++);

-		corr = vo_round(L_sum2);

-		*cor_y++ = vo_mult(corr, sign[pos-3]) + (*p3++);

-		pos += STEP;

-	}

-	return;

-}

-

-void cor_h_vec_012(

-		Word16 h[],                           /* (i) scaled impulse response                 */

-		Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */

-		Word16 track,                         /* (i) track to use                            */

-		Word16 sign[],                        /* (i) sign vector                             */

-		Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */

-		Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */

-		Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */

-		)

-{

-	Word32 i, j, pos, corr;

-	Word16 *p0, *p1, *p2,*p3,*cor_x,*cor_y;

-	Word32 L_sum1,L_sum2;

-	cor_x = cor_1;

-	cor_y = cor_2;

-	p0 = rrixix[track];

-	p3 = rrixix[track+1];

-	pos = track;

-

-	for (i = 0; i < NB_POS; i+=2)

-	{

-		L_sum1 = L_sum2 = 0L;

-		p1 = h;

-		p2 = &vec[pos];

-		for (j=62-pos ;j >= 0; j--)

-		{

-			L_sum1 += *p1 * *p2++;

-			L_sum2 += *p1++ * *p2;

-		}

-		L_sum1 += *p1 * *p2;

-		L_sum1 = (L_sum1 << 2);

-		L_sum2 = (L_sum2 << 2);

-

-		corr = (L_sum1 + 0x8000) >> 16;

-		cor_x[i] = vo_mult(corr, sign[pos]) + (*p0++);

-		corr = (L_sum2 + 0x8000) >> 16;

-		cor_y[i] = vo_mult(corr, sign[pos + 1]) + (*p3++);

-		pos += STEP;

-

-		L_sum1 = L_sum2 = 0L;

-		p1 = h;

-		p2 = &vec[pos];

-		for (j= 62-pos;j >= 0; j--)

-		{

-			L_sum1 += *p1 * *p2++;

-			L_sum2 += *p1++ * *p2;

-		}

-		L_sum1 += *p1 * *p2;

-		L_sum1 = (L_sum1 << 2);

-		L_sum2 = (L_sum2 << 2);

-

-		corr = (L_sum1 + 0x8000) >> 16;

-		cor_x[i+1] = vo_mult(corr, sign[pos]) + (*p0++);

-		corr = (L_sum2 + 0x8000) >> 16;

-		cor_y[i+1] = vo_mult(corr, sign[pos + 1]) + (*p3++);

-		pos += STEP;

-	}

-	return;

-}

-

-/*-------------------------------------------------------------------*

- * Function  search_ixiy()                                           *

- * ~~~~~~~~~~~~~~~~~~~~~~~                                           *

- * Find the best positions of 2 pulses in a subframe.                *

- *-------------------------------------------------------------------*/

-

-void search_ixiy(

-		Word16 nb_pos_ix,                     /* (i) nb of pos for pulse 1 (1..8)       */

-		Word16 track_x,                       /* (i) track of pulse 1                   */

-		Word16 track_y,                       /* (i) track of pulse 2                   */

-		Word16 * ps,                          /* (i/o) correlation of all fixed pulses  */

-		Word16 * alp,                         /* (i/o) energy of all fixed pulses       */

-		Word16 * ix,                          /* (o) position of pulse 1                */

-		Word16 * iy,                          /* (o) position of pulse 2                */

-		Word16 dn[],                          /* (i) corr. between target and h[]       */

-		Word16 dn2[],                         /* (i) vector of selected positions       */

-		Word16 cor_x[],                       /* (i) corr. of pulse 1 with fixed pulses */

-		Word16 cor_y[],                       /* (i) corr. of pulse 2 with fixed pulses */

-		Word16 rrixiy[][MSIZE]                /* (i) corr. of pulse 1 with pulse 2   */

-		)

-{

-	Word32 x, y, pos, thres_ix;

-	Word16 ps1, ps2, sq, sqk;

-	Word16 alp_16, alpk;

-	Word16 *p0, *p1, *p2;

-	Word32 s, alp0, alp1, alp2;

-

-	p0 = cor_x;                            

-	p1 = cor_y;                            

-	p2 = rrixiy[track_x];                  

-

-	thres_ix = nb_pos_ix - NB_MAX;

-

-	alp0 = L_deposit_h(*alp);

-	alp0 = (alp0 + 0x00008000L);       /* for rounding */

-

-	sqk = -1;                              

-	alpk = 1;                              

-

-	for (x = track_x; x < L_SUBFR; x += STEP)

-	{

-		ps1 = *ps + dn[x];

-		alp1 = alp0 + ((*p0++)<<13);

-

-		if (dn2[x] < thres_ix)

-		{

-			pos = -1;

-			for (y = track_y; y < L_SUBFR; y += STEP)

-			{

-				ps2 = add1(ps1, dn[y]);

-

-				alp2 = alp1 + ((*p1++)<<13);

-				alp2 = alp2 + ((*p2++)<<14);

-				alp_16 = extract_h(alp2);

-				sq = vo_mult(ps2, ps2);

-				s = vo_L_mult(alpk, sq) - ((sqk * alp_16)<<1);

-

-				if (s > 0)

-				{

-					sqk = sq;              

-					alpk = alp_16;         

-					pos = y;               

-				}

-			}

-			p1 -= NB_POS;

-

-			if (pos >= 0)

-			{

-				*ix = x;                   

-				*iy = pos;                 

-			}

-		} else

-		{

-			p2 += NB_POS;

-		}

-	}

-

-	*ps = add1(*ps, add1(dn[*ix], dn[*iy])); 

-	*alp = alpk;                           

-

-	return;

-}

-

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*      File: c4t64fx.c                                                 *
+*                                                                      *
+*	   Description:Performs algebraic codebook search for higher modes *
+*                                                                      *
+************************************************************************/
+
+/************************************************************************
+* Function: ACELP_4t64_fx()                                             *
+*                                                                       *
+* 20, 36, 44, 52, 64, 72, 88 bits algebraic codebook.                   *
+* 4 tracks x 16 positions per track = 64 samples.                       *
+*                                                                       *
+* 20 bits --> 4 pulses in a frame of 64 samples.                        *
+* 36 bits --> 8 pulses in a frame of 64 samples.                        *
+* 44 bits --> 10 pulses in a frame of 64 samples.                       *
+* 52 bits --> 12 pulses in a frame of 64 samples.                       *
+* 64 bits --> 16 pulses in a frame of 64 samples.                       *
+* 72 bits --> 18 pulses in a frame of 64 samples.                       *
+* 88 bits --> 24 pulses in a frame of 64 samples.                       *
+*                                                                       *
+* All pulses can have two (2) possible amplitudes: +1 or -1.            *
+* Each pulse can have sixteen (16) possible positions.                  *
+*************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "math_op.h"
+#include "acelp.h"
+#include "cnst.h"
+
+#include "q_pulse.h"
+
+static Word16 tipos[36] = {
+	0, 1, 2, 3,                            /* starting point &ipos[0], 1st iter */
+	1, 2, 3, 0,                            /* starting point &ipos[4], 2nd iter */
+	2, 3, 0, 1,                            /* starting point &ipos[8], 3rd iter */
+	3, 0, 1, 2,                            /* starting point &ipos[12], 4th iter */
+	0, 1, 2, 3,
+	1, 2, 3, 0,
+	2, 3, 0, 1,
+	3, 0, 1, 2,
+	0, 1, 2, 3};                           /* end point for 24 pulses &ipos[35], 4th iter */
+
+#define NB_PULSE_MAX  24
+
+#define L_SUBFR   64
+#define NB_TRACK  4
+#define STEP      4
+#define NB_POS    16
+#define MSIZE     256
+#define NB_MAX    8
+#define NPMAXPT   ((NB_PULSE_MAX+NB_TRACK-1)/NB_TRACK)
+
+/* Private functions */
+void cor_h_vec_012(
+		Word16 h[],                           /* (i) scaled impulse response                 */
+		Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */
+		Word16 track,                         /* (i) track to use                            */
+		Word16 sign[],                        /* (i) sign vector                             */
+		Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */
+		Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */
+		Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */
+		);
+
+void cor_h_vec_012_asm(
+		Word16 h[],                           /* (i) scaled impulse response                 */
+		Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */
+		Word16 track,                         /* (i) track to use                            */
+		Word16 sign[],                        /* (i) sign vector                             */
+		Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */
+		Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */
+		Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */
+		);
+
+void cor_h_vec_30(
+		Word16 h[],                           /* (i) scaled impulse response                 */
+		Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */
+		Word16 track,                         /* (i) track to use                            */
+		Word16 sign[],                        /* (i) sign vector                             */
+		Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */
+		Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */
+		Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */
+		);
+
+void search_ixiy(
+		Word16 nb_pos_ix,                     /* (i) nb of pos for pulse 1 (1..8)       */
+		Word16 track_x,                       /* (i) track of pulse 1                   */
+		Word16 track_y,                       /* (i) track of pulse 2                   */
+		Word16 * ps,                          /* (i/o) correlation of all fixed pulses  */
+		Word16 * alp,                         /* (i/o) energy of all fixed pulses       */
+		Word16 * ix,                          /* (o) position of pulse 1                */
+		Word16 * iy,                          /* (o) position of pulse 2                */
+		Word16 dn[],                          /* (i) corr. between target and h[]       */
+		Word16 dn2[],                         /* (i) vector of selected positions       */
+		Word16 cor_x[],                       /* (i) corr. of pulse 1 with fixed pulses */
+		Word16 cor_y[],                       /* (i) corr. of pulse 2 with fixed pulses */
+		Word16 rrixiy[][MSIZE]                /* (i) corr. of pulse 1 with pulse 2   */
+		);
+
+
+void ACELP_4t64_fx(
+		Word16 dn[],                          /* (i) <12b : correlation between target x[] and H[]      */
+		Word16 cn[],                          /* (i) <12b : residual after long term prediction         */
+		Word16 H[],                           /* (i) Q12: impulse response of weighted synthesis filter */
+		Word16 code[],                        /* (o) Q9 : algebraic (fixed) codebook excitation         */
+		Word16 y[],                           /* (o) Q9 : filtered fixed codebook excitation            */
+		Word16 nbbits,                        /* (i) : 20, 36, 44, 52, 64, 72 or 88 bits                */
+		Word16 ser_size,                      /* (i) : bit rate                                         */
+		Word16 _index[]                       /* (o) : index (20): 5+5+5+5 = 20 bits.                   */
+		/* (o) : index (36): 9+9+9+9 = 36 bits.                   */
+		/* (o) : index (44): 13+9+13+9 = 44 bits.                 */
+		/* (o) : index (52): 13+13+13+13 = 52 bits.               */
+		/* (o) : index (64): 2+2+2+2+14+14+14+14 = 64 bits.       */
+		/* (o) : index (72): 10+2+10+2+10+14+10+14 = 72 bits.     */
+		/* (o) : index (88): 11+11+11+11+11+11+11+11 = 88 bits.   */
+		)
+{
+	Word32 i, j, k;
+	Word16 st, ix, iy, pos, index, track, nb_pulse, nbiter, j_temp;
+	Word16 psk, ps, alpk, alp, val, k_cn, k_dn, exp;
+	Word16 *p0, *p1, *p2, *p3, *psign;
+	Word16 *h, *h_inv, *ptr_h1, *ptr_h2, *ptr_hf, h_shift;
+	Word32 s, cor, L_tmp, L_index;
+	Word16 dn2[L_SUBFR], sign[L_SUBFR], vec[L_SUBFR];
+	Word16 ind[NPMAXPT * NB_TRACK];
+	Word16 codvec[NB_PULSE_MAX], nbpos[10];
+	Word16 cor_x[NB_POS], cor_y[NB_POS], pos_max[NB_TRACK];
+	Word16 h_buf[4 * L_SUBFR];
+	Word16 rrixix[NB_TRACK][NB_POS], rrixiy[NB_TRACK][MSIZE];
+	Word16 ipos[NB_PULSE_MAX];
+
+	switch (nbbits)
+	{
+		case 20:                               /* 20 bits, 4 pulses, 4 tracks */
+			nbiter = 4;                          /* 4x16x16=1024 loop */
+			alp = 8192;                          /* alp = 2.0 (Q12) */
+			nb_pulse = 4;
+			nbpos[0] = 4;
+			nbpos[1] = 8;
+			break;
+		case 36:                               /* 36 bits, 8 pulses, 4 tracks */
+			nbiter = 4;                          /* 4x20x16=1280 loop */
+			alp = 4096;                          /* alp = 1.0 (Q12) */
+			nb_pulse = 8;
+			nbpos[0] = 4;
+			nbpos[1] = 8;
+			nbpos[2] = 8;
+			break;
+		case 44:                               /* 44 bits, 10 pulses, 4 tracks */
+			nbiter = 4;                          /* 4x26x16=1664 loop */
+			alp = 4096;                          /* alp = 1.0 (Q12) */
+			nb_pulse = 10;
+			nbpos[0] = 4;
+			nbpos[1] = 6;
+			nbpos[2] = 8;
+			nbpos[3] = 8;
+			break;
+		case 52:                               /* 52 bits, 12 pulses, 4 tracks */
+			nbiter = 4;                          /* 4x26x16=1664 loop */
+			alp = 4096;                          /* alp = 1.0 (Q12) */
+			nb_pulse = 12;
+			nbpos[0] = 4;
+			nbpos[1] = 6;
+			nbpos[2] = 8;
+			nbpos[3] = 8;
+			break;
+		case 64:                               /* 64 bits, 16 pulses, 4 tracks */
+			nbiter = 3;                          /* 3x36x16=1728 loop */
+			alp = 3277;                          /* alp = 0.8 (Q12) */
+			nb_pulse = 16;
+			nbpos[0] = 4;
+			nbpos[1] = 4;
+			nbpos[2] = 6;
+			nbpos[3] = 6;
+			nbpos[4] = 8;
+			nbpos[5] = 8;
+			break;
+		case 72:                               /* 72 bits, 18 pulses, 4 tracks */
+			nbiter = 3;                          /* 3x35x16=1680 loop */
+			alp = 3072;                          /* alp = 0.75 (Q12) */
+			nb_pulse = 18;
+			nbpos[0] = 2;
+			nbpos[1] = 3;
+			nbpos[2] = 4;
+			nbpos[3] = 5;
+			nbpos[4] = 6;
+			nbpos[5] = 7;
+			nbpos[6] = 8;
+			break;
+		case 88:                               /* 88 bits, 24 pulses, 4 tracks */
+			if(ser_size > 462)
+				nbiter = 1;
+			else
+				nbiter = 2;                    /* 2x53x16=1696 loop */
+
+			alp = 2048;                          /* alp = 0.5 (Q12) */
+			nb_pulse = 24;
+			nbpos[0] = 2;
+			nbpos[1] = 2;
+			nbpos[2] = 3;
+			nbpos[3] = 4;
+			nbpos[4] = 5;
+			nbpos[5] = 6;
+			nbpos[6] = 7;
+			nbpos[7] = 8;
+			nbpos[8] = 8;
+			nbpos[9] = 8;
+			break;
+		default:
+			nbiter = 0;
+			alp = 0;
+			nb_pulse = 0;
+	}
+
+	for (i = 0; i < nb_pulse; i++)
+	{
+		codvec[i] = i;
+	}
+
+	/*----------------------------------------------------------------*
+	 * Find sign for each pulse position.                             *
+	 *----------------------------------------------------------------*/
+	/* calculate energy for normalization of cn[] and dn[] */
+	/* set k_cn = 32..32767 (ener_cn = 2^30..256-0) */
+#ifdef ASM_OPT                  /* asm optimization branch */
+	s = Dot_product12_asm(cn, cn, L_SUBFR, &exp);
+#else
+	s = Dot_product12(cn, cn, L_SUBFR, &exp);
+#endif
+
+	Isqrt_n(&s, &exp);
+	s = L_shl(s, (exp + 5));
+	k_cn = extract_h(L_add(s, 0x8000));
+
+	/* set k_dn = 32..512 (ener_dn = 2^30..2^22) */
+#ifdef ASM_OPT                      /* asm optimization branch */
+	s = Dot_product12_asm(dn, dn, L_SUBFR, &exp);
+#else
+	s = Dot_product12(dn, dn, L_SUBFR, &exp);
+#endif
+
+	Isqrt_n(&s, &exp);
+	k_dn = (L_shl(s, (exp + 5 + 3)) + 0x8000) >> 16;    /* k_dn = 256..4096 */
+	k_dn = vo_mult_r(alp, k_dn);              /* alp in Q12 */
+
+	/* mix normalized cn[] and dn[] */
+	p0 = cn;
+	p1 = dn;
+	p2 = dn2;
+
+	for (i = 0; i < L_SUBFR/4; i++)
+	{
+		s = (k_cn* (*p0++))+(k_dn * (*p1++));
+		*p2++ = s >> 7;
+		s = (k_cn* (*p0++))+(k_dn * (*p1++));
+		*p2++ = s >> 7;
+		s = (k_cn* (*p0++))+(k_dn * (*p1++));
+		*p2++ = s >> 7;
+		s = (k_cn* (*p0++))+(k_dn * (*p1++));
+		*p2++ = s >> 7;
+	}
+
+	/* set sign according to dn2[] = k_cn*cn[] + k_dn*dn[]    */
+	for(i = 0; i < L_SUBFR; i++)
+	{
+		val = dn[i];
+		ps = dn2[i];
+		if (ps >= 0)
+		{
+			sign[i] = 32767;             /* sign = +1 (Q12) */
+			vec[i] = -32768;
+		} else
+		{
+			sign[i] = -32768;            /* sign = -1 (Q12) */
+			vec[i] = 32767;
+			dn[i] = -val;
+			dn2[i] = -ps;
+		}
+	}
+	/*----------------------------------------------------------------*
+	 * Select NB_MAX position per track according to max of dn2[].    *
+	 *----------------------------------------------------------------*/
+	pos = 0;
+	for (i = 0; i < NB_TRACK; i++)
+	{
+		for (k = 0; k < NB_MAX; k++)
+		{
+			ps = -1;
+			for (j = i; j < L_SUBFR; j += STEP)
+			{
+				if(dn2[j] > ps)
+				{
+					ps = dn2[j];
+					pos = j;
+				}
+			}
+			dn2[pos] = (k - NB_MAX);     /* dn2 < 0 when position is selected */
+			if (k == 0)
+			{
+				pos_max[i] = pos;
+			}
+		}
+	}
+
+	/*--------------------------------------------------------------*
+	 * Scale h[] to avoid overflow and to get maximum of precision  *
+	 * on correlation.                                              *
+	 *                                                              *
+	 * Maximum of h[] (h[0]) is fixed to 2048 (MAX16 / 16).         *
+	 *  ==> This allow addition of 16 pulses without saturation.    *
+	 *                                                              *
+	 * Energy worst case (on resonant impulse response),            *
+	 * - energy of h[] is approximately MAX/16.                     *
+	 * - During search, the energy is divided by 8 to avoid         *
+	 *   overflow on "alp". (energy of h[] = MAX/128).              *
+	 *  ==> "alp" worst case detected is 22854 on sinusoidal wave.  *
+	 *--------------------------------------------------------------*/
+
+	/* impulse response buffer for fast computation */
+
+	h = h_buf;
+	h_inv = h_buf + (2 * L_SUBFR);
+	L_tmp = 0;
+	for (i = 0; i < L_SUBFR; i++)
+	{
+		*h++ = 0;
+		*h_inv++ = 0;
+		L_tmp += (H[i] * H[i]) << 1;
+	}
+	/* scale h[] down (/2) when energy of h[] is high with many pulses used */
+	val = extract_h(L_tmp);
+	h_shift = 0;
+
+	if ((nb_pulse >= 12) && (val > 1024))
+	{
+		h_shift = 1;
+	}
+	p0 = H;
+	p1 = h;
+	p2 = h_inv;
+
+	for (i = 0; i < L_SUBFR/4; i++)
+	{
+		*p1 = *p0++ >> h_shift;
+		*p2++ = -(*p1++);
+		*p1 = *p0++ >> h_shift;
+		*p2++ = -(*p1++);
+		*p1 = *p0++ >> h_shift;
+		*p2++ = -(*p1++);
+		*p1 = *p0++ >> h_shift;
+		*p2++ = -(*p1++);
+	}
+
+	/*------------------------------------------------------------*
+	 * Compute rrixix[][] needed for the codebook search.         *
+	 * This algorithm compute impulse response energy of all      *
+	 * positions (16) in each track (4).       Total = 4x16 = 64. *
+	 *------------------------------------------------------------*/
+
+	/* storage order --> i3i3, i2i2, i1i1, i0i0 */
+
+	/* Init pointers to last position of rrixix[] */
+	p0 = &rrixix[0][NB_POS - 1];
+	p1 = &rrixix[1][NB_POS - 1];
+	p2 = &rrixix[2][NB_POS - 1];
+	p3 = &rrixix[3][NB_POS - 1];
+
+	ptr_h1 = h;
+	cor = 0x00008000L;                             /* for rounding */
+	for (i = 0; i < NB_POS; i++)
+	{
+		cor += vo_L_mult((*ptr_h1), (*ptr_h1));
+		ptr_h1++;
+		*p3-- = extract_h(cor);
+		cor += vo_L_mult((*ptr_h1), (*ptr_h1));
+		ptr_h1++;
+		*p2-- = extract_h(cor);
+		cor += vo_L_mult((*ptr_h1), (*ptr_h1));
+		ptr_h1++;
+		*p1-- = extract_h(cor);
+		cor += vo_L_mult((*ptr_h1), (*ptr_h1));
+		ptr_h1++;
+		*p0-- = extract_h(cor);
+	}
+
+	/*------------------------------------------------------------*
+	 * Compute rrixiy[][] needed for the codebook search.         *
+	 * This algorithm compute correlation between 2 pulses        *
+	 * (2 impulses responses) in 4 possible adjacents tracks.     *
+	 * (track 0-1, 1-2, 2-3 and 3-0).     Total = 4x16x16 = 1024. *
+	 *------------------------------------------------------------*/
+
+	/* storage order --> i2i3, i1i2, i0i1, i3i0 */
+
+	pos = MSIZE - 1;
+	ptr_hf = h + 1;
+
+	for (k = 0; k < NB_POS; k++)
+	{
+		p3 = &rrixiy[2][pos];
+		p2 = &rrixiy[1][pos];
+		p1 = &rrixiy[0][pos];
+		p0 = &rrixiy[3][pos - NB_POS];
+
+		cor = 0x00008000L;                   /* for rounding */
+		ptr_h1 = h;
+		ptr_h2 = ptr_hf;
+
+		for (i = k + 1; i < NB_POS; i++)
+		{
+			cor += vo_L_mult((*ptr_h1), (*ptr_h2));
+			ptr_h1++;
+			ptr_h2++;
+			*p3 = extract_h(cor);
+			cor += vo_L_mult((*ptr_h1), (*ptr_h2));
+			ptr_h1++;
+			ptr_h2++;
+			*p2 = extract_h(cor);
+			cor += vo_L_mult((*ptr_h1), (*ptr_h2));
+			ptr_h1++;
+			ptr_h2++;
+			*p1 = extract_h(cor);
+			cor += vo_L_mult((*ptr_h1), (*ptr_h2));
+			ptr_h1++;
+			ptr_h2++;
+			*p0 = extract_h(cor);
+
+			p3 -= (NB_POS + 1);
+			p2 -= (NB_POS + 1);
+			p1 -= (NB_POS + 1);
+			p0 -= (NB_POS + 1);
+		}
+		cor += vo_L_mult((*ptr_h1), (*ptr_h2));
+		ptr_h1++;
+		ptr_h2++;
+		*p3 = extract_h(cor);
+		cor += vo_L_mult((*ptr_h1), (*ptr_h2));
+		ptr_h1++;
+		ptr_h2++;
+		*p2 = extract_h(cor);
+		cor += vo_L_mult((*ptr_h1), (*ptr_h2));
+		ptr_h1++;
+		ptr_h2++;
+		*p1 = extract_h(cor);
+
+		pos -= NB_POS;
+		ptr_hf += STEP;
+	}
+
+	/* storage order --> i3i0, i2i3, i1i2, i0i1 */
+
+	pos = MSIZE - 1;
+	ptr_hf = h + 3;
+
+	for (k = 0; k < NB_POS; k++)
+	{
+		p3 = &rrixiy[3][pos];
+		p2 = &rrixiy[2][pos - 1];
+		p1 = &rrixiy[1][pos - 1];
+		p0 = &rrixiy[0][pos - 1];
+
+		cor = 0x00008000L;								/* for rounding */
+		ptr_h1 = h;
+		ptr_h2 = ptr_hf;
+
+		for (i = k + 1; i < NB_POS; i++)
+		{
+			cor += vo_L_mult((*ptr_h1), (*ptr_h2));
+			ptr_h1++;
+			ptr_h2++;
+			*p3 = extract_h(cor);
+			cor += vo_L_mult((*ptr_h1), (*ptr_h2));
+			ptr_h1++;
+			ptr_h2++;
+			*p2 = extract_h(cor);
+			cor += vo_L_mult((*ptr_h1), (*ptr_h2));
+			ptr_h1++;
+			ptr_h2++;
+			*p1 = extract_h(cor);
+			cor += vo_L_mult((*ptr_h1), (*ptr_h2));
+			ptr_h1++;
+			ptr_h2++;
+			*p0 = extract_h(cor);
+
+			p3 -= (NB_POS + 1);
+			p2 -= (NB_POS + 1);
+			p1 -= (NB_POS + 1);
+			p0 -= (NB_POS + 1);
+		}
+		cor += vo_L_mult((*ptr_h1), (*ptr_h2));
+		ptr_h1++;
+		ptr_h2++;
+		*p3 = extract_h(cor);
+
+		pos--;
+		ptr_hf += STEP;
+	}
+
+	/*------------------------------------------------------------*
+	 * Modification of rrixiy[][] to take signs into account.     *
+	 *------------------------------------------------------------*/
+
+	p0 = &rrixiy[0][0];
+
+	for (k = 0; k < NB_TRACK; k++)
+	{
+		j_temp = (k + 1)&0x03;
+		for (i = k; i < L_SUBFR; i += STEP)
+		{
+			psign = sign;
+			if (psign[i] < 0)
+			{
+				psign = vec;
+			}
+			j = j_temp;
+			for (; j < L_SUBFR; j += STEP)
+			{
+				*p0 = vo_mult(*p0, psign[j]);
+				p0++;
+			}
+		}
+	}
+
+	/*-------------------------------------------------------------------*
+	 *                       Deep first search                           *
+	 *-------------------------------------------------------------------*/
+
+	psk = -1;
+	alpk = 1;
+
+	for (k = 0; k < nbiter; k++)
+	{
+		j_temp = k<<2;
+		for (i = 0; i < nb_pulse; i++)
+			ipos[i] = tipos[j_temp + i];
+
+		if(nbbits == 20)
+		{
+			pos = 0;
+			ps = 0;
+			alp = 0;
+			for (i = 0; i < L_SUBFR; i++)
+			{
+				vec[i] = 0;
+			}
+		} else if ((nbbits == 36) || (nbbits == 44))
+		{
+			/* first stage: fix 2 pulses */
+			pos = 2;
+
+			ix = ind[0] = pos_max[ipos[0]];
+			iy = ind[1] = pos_max[ipos[1]];
+			ps = dn[ix] + dn[iy];
+			i = ix >> 2;                /* ix / STEP */
+			j = iy >> 2;                /* iy / STEP */
+			s = rrixix[ipos[0]][i] << 13;
+			s += rrixix[ipos[1]][j] << 13;
+			i = (i << 4) + j;         /* (ix/STEP)*NB_POS + (iy/STEP) */
+			s += rrixiy[ipos[0]][i] << 14;
+			alp = (s + 0x8000) >> 16;
+			if (sign[ix] < 0)
+				p0 = h_inv - ix;
+			else
+				p0 = h - ix;
+			if (sign[iy] < 0)
+				p1 = h_inv - iy;
+			else
+				p1 = h - iy;
+
+			for (i = 0; i < L_SUBFR; i++)
+			{
+				vec[i] = (*p0++) + (*p1++);
+			}
+
+			if(nbbits == 44)
+			{
+				ipos[8] = 0;
+				ipos[9] = 1;
+			}
+		} else
+		{
+			/* first stage: fix 4 pulses */
+			pos = 4;
+
+			ix = ind[0] = pos_max[ipos[0]];
+			iy = ind[1] = pos_max[ipos[1]];
+			i = ind[2] = pos_max[ipos[2]];
+			j = ind[3] = pos_max[ipos[3]];
+			ps = add1(add1(add1(dn[ix], dn[iy]), dn[i]), dn[j]);
+
+			if (sign[ix] < 0)
+				p0 = h_inv - ix;
+			else
+				p0 = h - ix;
+
+			if (sign[iy] < 0)
+				p1 = h_inv - iy;
+			else
+				p1 = h - iy;
+
+			if (sign[i] < 0)
+				p2 = h_inv - i;
+			else
+				p2 = h - i;
+
+			if (sign[j] < 0)
+				p3 = h_inv - j;
+			else
+				p3 = h - j;
+
+			L_tmp = 0L;
+			for(i = 0; i < L_SUBFR; i++)
+			{
+				vec[i]  = add1(add1(add1(*p0++, *p1++), *p2++), *p3++);
+				L_tmp  += (vec[i] * vec[i]) << 1;
+			}
+
+			alp = ((L_tmp >> 3) + 0x8000) >> 16;
+
+			if(nbbits == 72)
+			{
+				ipos[16] = 0;
+				ipos[17] = 1;
+			}
+		}
+
+		/* other stages of 2 pulses */
+
+		for (j = pos, st = 0; j < nb_pulse; j += 2, st++)
+		{
+			/*--------------------------------------------------*
+			 * Calculate correlation of all possible positions  *
+			 * of the next 2 pulses with previous fixed pulses. *
+			 * Each pulse can have 16 possible positions.       *
+			 *--------------------------------------------------*/
+			if(ipos[j] == 3)
+			{
+				cor_h_vec_30(h, vec, ipos[j], sign, rrixix, cor_x, cor_y);
+			}
+			else
+			{
+#ifdef ASM_OPT                 /* asm optimization branch */
+				cor_h_vec_012_asm(h, vec, ipos[j], sign, rrixix, cor_x, cor_y);
+#else
+				cor_h_vec_012(h, vec, ipos[j], sign, rrixix, cor_x, cor_y);
+#endif
+			}
+			/*--------------------------------------------------*
+			 * Find best positions of 2 pulses.                 *
+			 *--------------------------------------------------*/
+			search_ixiy(nbpos[st], ipos[j], ipos[j + 1], &ps, &alp,
+					&ix, &iy, dn, dn2, cor_x, cor_y, rrixiy);
+
+			ind[j] = ix;
+			ind[j + 1] = iy;
+
+			if (sign[ix] < 0)
+				p0 = h_inv - ix;
+			else
+				p0 = h - ix;
+			if (sign[iy] < 0)
+				p1 = h_inv - iy;
+			else
+				p1 = h - iy;
+
+			for (i = 0; i < L_SUBFR; i+=4)
+			{
+				vec[i]   += add1((*p0++), (*p1++));
+				vec[i+1] += add1((*p0++), (*p1++));
+				vec[i+2] += add1((*p0++), (*p1++));
+				vec[i+3] += add1((*p0++), (*p1++));
+			}
+		}
+		/* memorise the best codevector */
+		ps = vo_mult(ps, ps);
+		s = vo_L_msu(vo_L_mult(alpk, ps), psk, alp);
+		if (s > 0)
+		{
+			psk = ps;
+			alpk = alp;
+			for (i = 0; i < nb_pulse; i++)
+			{
+				codvec[i] = ind[i];
+			}
+			for (i = 0; i < L_SUBFR; i++)
+			{
+				y[i] = vec[i];
+			}
+		}
+	}
+	/*-------------------------------------------------------------------*
+	 * Build the codeword, the filtered codeword and index of codevector.*
+	 *-------------------------------------------------------------------*/
+	for (i = 0; i < NPMAXPT * NB_TRACK; i++)
+	{
+		ind[i] = -1;
+	}
+	for (i = 0; i < L_SUBFR; i++)
+	{
+		code[i] = 0;
+		y[i] = vo_shr_r(y[i], 3);               /* Q12 to Q9 */
+	}
+	val = (512 >> h_shift);               /* codeword in Q9 format */
+	for (k = 0; k < nb_pulse; k++)
+	{
+		i = codvec[k];                       /* read pulse position */
+		j = sign[i];                         /* read sign           */
+		index = i >> 2;                 /* index = pos of pulse (0..15) */
+		track = (Word16) (i & 0x03);         /* track = i % NB_TRACK (0..3)  */
+
+		if (j > 0)
+		{
+			code[i] += val;
+			codvec[k] += 128;
+		} else
+		{
+			code[i] -= val;
+			index += NB_POS;
+		}
+
+		i = (Word16)((vo_L_mult(track, NPMAXPT) >> 1));
+
+		while (ind[i] >= 0)
+		{
+			i += 1;
+		}
+		ind[i] = index;
+	}
+
+	k = 0;
+	/* Build index of codevector */
+	if(nbbits == 20)
+	{
+		for (track = 0; track < NB_TRACK; track++)
+		{
+			_index[track] = (Word16)(quant_1p_N1(ind[k], 4));
+			k += NPMAXPT;
+		}
+	} else if(nbbits == 36)
+	{
+		for (track = 0; track < NB_TRACK; track++)
+		{
+			_index[track] = (Word16)(quant_2p_2N1(ind[k], ind[k + 1], 4));
+			k += NPMAXPT;
+		}
+	} else if(nbbits == 44)
+	{
+		for (track = 0; track < NB_TRACK - 2; track++)
+		{
+			_index[track] = (Word16)(quant_3p_3N1(ind[k], ind[k + 1], ind[k + 2], 4));
+			k += NPMAXPT;
+		}
+		for (track = 2; track < NB_TRACK; track++)
+		{
+			_index[track] = (Word16)(quant_2p_2N1(ind[k], ind[k + 1], 4));
+			k += NPMAXPT;
+		}
+	} else if(nbbits == 52)
+	{
+		for (track = 0; track < NB_TRACK; track++)
+		{
+			_index[track] = (Word16)(quant_3p_3N1(ind[k], ind[k + 1], ind[k + 2], 4));
+			k += NPMAXPT;
+		}
+	} else if(nbbits == 64)
+	{
+		for (track = 0; track < NB_TRACK; track++)
+		{
+			L_index = quant_4p_4N(&ind[k], 4);
+			_index[track] = (Word16)((L_index >> 14) & 3);
+			_index[track + NB_TRACK] = (Word16)(L_index & 0x3FFF);
+			k += NPMAXPT;
+		}
+	} else if(nbbits == 72)
+	{
+		for (track = 0; track < NB_TRACK - 2; track++)
+		{
+			L_index = quant_5p_5N(&ind[k], 4);
+			_index[track] = (Word16)((L_index >> 10) & 0x03FF);
+			_index[track + NB_TRACK] = (Word16)(L_index & 0x03FF);
+			k += NPMAXPT;
+		}
+		for (track = 2; track < NB_TRACK; track++)
+		{
+			L_index = quant_4p_4N(&ind[k], 4);
+			_index[track] = (Word16)((L_index >> 14) & 3);
+			_index[track + NB_TRACK] = (Word16)(L_index & 0x3FFF);
+			k += NPMAXPT;
+		}
+	} else if(nbbits == 88)
+	{
+		for (track = 0; track < NB_TRACK; track++)
+		{
+			L_index = quant_6p_6N_2(&ind[k], 4);
+			_index[track] = (Word16)((L_index >> 11) & 0x07FF);
+			_index[track + NB_TRACK] = (Word16)(L_index & 0x07FF);
+			k += NPMAXPT;
+		}
+	}
+	return;
+}
+
+
+/*-------------------------------------------------------------------*
+ * Function  cor_h_vec()                                             *
+ * ~~~~~~~~~~~~~~~~~~~~~                                             *
+ * Compute correlations of h[] with vec[] for the specified track.   *
+ *-------------------------------------------------------------------*/
+void cor_h_vec_30(
+		Word16 h[],                           /* (i) scaled impulse response                 */
+		Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */
+		Word16 track,                         /* (i) track to use                            */
+		Word16 sign[],                        /* (i) sign vector                             */
+		Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */
+		Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */
+		Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */
+		)
+{
+	Word32 i, j, pos, corr;
+	Word16 *p0, *p1, *p2,*p3,*cor_x,*cor_y;
+	Word32 L_sum1,L_sum2;
+	cor_x = cor_1;
+	cor_y = cor_2;
+	p0 = rrixix[track];
+	p3 = rrixix[0];
+	pos = track;
+
+	for (i = 0; i < NB_POS; i+=2)
+	{
+		L_sum1 = L_sum2 = 0L;
+		p1 = h;
+		p2 = &vec[pos];
+		for (j=pos;j < L_SUBFR; j++)
+		{
+			L_sum1 += *p1 * *p2;
+			p2-=3;
+			L_sum2 += *p1++ * *p2;
+			p2+=4;
+		}
+		p2-=3;
+		L_sum2 += *p1++ * *p2++;
+		L_sum2 += *p1++ * *p2++;
+		L_sum2 += *p1++ * *p2++;
+
+		L_sum1 = (L_sum1 << 2);
+		L_sum2 = (L_sum2 << 2);
+
+		corr = vo_round(L_sum1);
+		*cor_x++ = vo_mult(corr, sign[pos]) + (*p0++);
+		corr = vo_round(L_sum2);
+		*cor_y++ = vo_mult(corr, sign[pos-3]) + (*p3++);
+		pos += STEP;
+
+		L_sum1 = L_sum2 = 0L;
+		p1 = h;
+		p2 = &vec[pos];
+		for (j=pos;j < L_SUBFR; j++)
+		{
+			L_sum1 += *p1 * *p2;
+			p2-=3;
+			L_sum2 += *p1++ * *p2;
+			p2+=4;
+		}
+		p2-=3;
+		L_sum2 += *p1++ * *p2++;
+		L_sum2 += *p1++ * *p2++;
+		L_sum2 += *p1++ * *p2++;
+
+		L_sum1 = (L_sum1 << 2);
+		L_sum2 = (L_sum2 << 2);
+
+		corr = vo_round(L_sum1);
+		*cor_x++ = vo_mult(corr, sign[pos]) + (*p0++);
+		corr = vo_round(L_sum2);
+		*cor_y++ = vo_mult(corr, sign[pos-3]) + (*p3++);
+		pos += STEP;
+	}
+	return;
+}
+
+void cor_h_vec_012(
+		Word16 h[],                           /* (i) scaled impulse response                 */
+		Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */
+		Word16 track,                         /* (i) track to use                            */
+		Word16 sign[],                        /* (i) sign vector                             */
+		Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */
+		Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */
+		Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */
+		)
+{
+	Word32 i, j, pos, corr;
+	Word16 *p0, *p1, *p2,*p3,*cor_x,*cor_y;
+	Word32 L_sum1,L_sum2;
+	cor_x = cor_1;
+	cor_y = cor_2;
+	p0 = rrixix[track];
+	p3 = rrixix[track+1];
+	pos = track;
+
+	for (i = 0; i < NB_POS; i+=2)
+	{
+		L_sum1 = L_sum2 = 0L;
+		p1 = h;
+		p2 = &vec[pos];
+		for (j=62-pos ;j >= 0; j--)
+		{
+			L_sum1 += *p1 * *p2++;
+			L_sum2 += *p1++ * *p2;
+		}
+		L_sum1 += *p1 * *p2;
+		L_sum1 = (L_sum1 << 2);
+		L_sum2 = (L_sum2 << 2);
+
+		corr = (L_sum1 + 0x8000) >> 16;
+		cor_x[i] = vo_mult(corr, sign[pos]) + (*p0++);
+		corr = (L_sum2 + 0x8000) >> 16;
+		cor_y[i] = vo_mult(corr, sign[pos + 1]) + (*p3++);
+		pos += STEP;
+
+		L_sum1 = L_sum2 = 0L;
+		p1 = h;
+		p2 = &vec[pos];
+		for (j= 62-pos;j >= 0; j--)
+		{
+			L_sum1 += *p1 * *p2++;
+			L_sum2 += *p1++ * *p2;
+		}
+		L_sum1 += *p1 * *p2;
+		L_sum1 = (L_sum1 << 2);
+		L_sum2 = (L_sum2 << 2);
+
+		corr = (L_sum1 + 0x8000) >> 16;
+		cor_x[i+1] = vo_mult(corr, sign[pos]) + (*p0++);
+		corr = (L_sum2 + 0x8000) >> 16;
+		cor_y[i+1] = vo_mult(corr, sign[pos + 1]) + (*p3++);
+		pos += STEP;
+	}
+	return;
+}
+
+/*-------------------------------------------------------------------*
+ * Function  search_ixiy()                                           *
+ * ~~~~~~~~~~~~~~~~~~~~~~~                                           *
+ * Find the best positions of 2 pulses in a subframe.                *
+ *-------------------------------------------------------------------*/
+
+void search_ixiy(
+		Word16 nb_pos_ix,                     /* (i) nb of pos for pulse 1 (1..8)       */
+		Word16 track_x,                       /* (i) track of pulse 1                   */
+		Word16 track_y,                       /* (i) track of pulse 2                   */
+		Word16 * ps,                          /* (i/o) correlation of all fixed pulses  */
+		Word16 * alp,                         /* (i/o) energy of all fixed pulses       */
+		Word16 * ix,                          /* (o) position of pulse 1                */
+		Word16 * iy,                          /* (o) position of pulse 2                */
+		Word16 dn[],                          /* (i) corr. between target and h[]       */
+		Word16 dn2[],                         /* (i) vector of selected positions       */
+		Word16 cor_x[],                       /* (i) corr. of pulse 1 with fixed pulses */
+		Word16 cor_y[],                       /* (i) corr. of pulse 2 with fixed pulses */
+		Word16 rrixiy[][MSIZE]                /* (i) corr. of pulse 1 with pulse 2   */
+		)
+{
+	Word32 x, y, pos, thres_ix;
+	Word16 ps1, ps2, sq, sqk;
+	Word16 alp_16, alpk;
+	Word16 *p0, *p1, *p2;
+	Word32 s, alp0, alp1, alp2;
+
+	p0 = cor_x;
+	p1 = cor_y;
+	p2 = rrixiy[track_x];
+
+	thres_ix = nb_pos_ix - NB_MAX;
+
+	alp0 = L_deposit_h(*alp);
+	alp0 = (alp0 + 0x00008000L);       /* for rounding */
+
+	sqk = -1;
+	alpk = 1;
+
+	for (x = track_x; x < L_SUBFR; x += STEP)
+	{
+		ps1 = *ps + dn[x];
+		alp1 = alp0 + ((*p0++)<<13);
+
+		if (dn2[x] < thres_ix)
+		{
+			pos = -1;
+			for (y = track_y; y < L_SUBFR; y += STEP)
+			{
+				ps2 = add1(ps1, dn[y]);
+
+				alp2 = alp1 + ((*p1++)<<13);
+				alp2 = alp2 + ((*p2++)<<14);
+				alp_16 = extract_h(alp2);
+				sq = vo_mult(ps2, ps2);
+				s = vo_L_mult(alpk, sq) - ((sqk * alp_16)<<1);
+
+				if (s > 0)
+				{
+					sqk = sq;
+					alpk = alp_16;
+					pos = y;
+				}
+			}
+			p1 -= NB_POS;
+
+			if (pos >= 0)
+			{
+				*ix = x;
+				*iy = pos;
+			}
+		} else
+		{
+			p2 += NB_POS;
+		}
+	}
+
+	*ps = add1(*ps, add1(dn[*ix], dn[*iy]));
+	*alp = alpk;
+
+	return;
+}
+
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/cmnMemory.c b/media/libstagefright/codecs/amrwbenc/src/cmnMemory.c
deleted file mode 100644
index c17264c..0000000
--- a/media/libstagefright/codecs/amrwbenc/src/cmnMemory.c
+++ /dev/null
@@ -1,73 +0,0 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		cmnMemory.c

-

-	Content:	sample code for memory operator implementation

-

-*******************************************************************************/

-#include "cmnMemory.h"

-

-#include <malloc.h>

-#if defined LINUX

-#include <string.h>

-#endif

-

-//VO_MEM_OPERATOR		g_memOP;

-

-VO_U32 cmnMemAlloc (VO_S32 uID,  VO_MEM_INFO * pMemInfo)

-{

-	if (!pMemInfo)

-		return VO_ERR_INVALID_ARG;

-

-	pMemInfo->VBuffer = malloc (pMemInfo->Size);

-	return 0;

-}

-

-VO_U32 cmnMemFree (VO_S32 uID, VO_PTR pMem)

-{

-	free (pMem);

-	return 0;

-}

-

-VO_U32	cmnMemSet (VO_S32 uID, VO_PTR pBuff, VO_U8 uValue, VO_U32 uSize)

-{

-	memset (pBuff, uValue, uSize);

-	return 0;

-}

-

-VO_U32	cmnMemCopy (VO_S32 uID, VO_PTR pDest, VO_PTR pSource, VO_U32 uSize)

-{

-	memcpy (pDest, pSource, uSize);

-	return 0;

-}

-

-VO_U32	cmnMemCheck (VO_S32 uID, VO_PTR pBuffer, VO_U32 uSize)

-{

-	return 0;

-}

-

-VO_S32 cmnMemCompare (VO_S32 uID, VO_PTR pBuffer1, VO_PTR pBuffer2, VO_U32 uSize)

-{

-	return memcmp(pBuffer1, pBuffer2, uSize);

-}

-

-VO_U32	cmnMemMove (VO_S32 uID, VO_PTR pDest, VO_PTR pSource, VO_U32 uSize)

-{

-	memmove (pDest, pSource, uSize);

-	return 0;

-}

-

diff --git a/media/libstagefright/codecs/amrwbenc/src/convolve.c b/media/libstagefright/codecs/amrwbenc/src/convolve.c
index 66c74d6..acba532 100644
--- a/media/libstagefright/codecs/amrwbenc/src/convolve.c
+++ b/media/libstagefright/codecs/amrwbenc/src/convolve.c
@@ -1,109 +1,109 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-       File: convolve.c

-

-	   Description:Perform the convolution between two vectors x[] and h[]

-	               and write the result in the vector y[]

-

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-

-void Convolve (

-		Word16 x[],        /* (i)     : input vector                           */

-		Word16 h[],        /* (i)     : impulse response                       */

-		Word16 y[],        /* (o)     : output vector                          */

-		Word16 L           /* (i)     : vector size                            */

-	      )

-{

-	Word32  i, n;

-	Word16 *tmpH,*tmpX;

-	Word32 s;

-	for (n = 0; n < 64;)

-	{

-		tmpH = h+n;

-		tmpX = x;

-		i=n+1;

-		s = vo_mult32((*tmpX++), (*tmpH--));i--;

-		while(i>0)

-		{

-			s += vo_mult32((*tmpX++), (*tmpH--));

-			s += vo_mult32((*tmpX++), (*tmpH--));

-			s += vo_mult32((*tmpX++), (*tmpH--));

-			s += vo_mult32((*tmpX++), (*tmpH--));

-			i -= 4;

-		}

-		y[n] = ((s<<1) + 0x8000)>>16;   

-		n++;

-

-		tmpH = h+n;

-		tmpX = x;

-		i=n+1;

-		s =  vo_mult32((*tmpX++), (*tmpH--));i--;

-		s += vo_mult32((*tmpX++), (*tmpH--));i--;

-

-		while(i>0)

-		{

-			s += vo_mult32((*tmpX++), (*tmpH--));

-			s += vo_mult32((*tmpX++), (*tmpH--));

-			s += vo_mult32((*tmpX++), (*tmpH--));

-			s += vo_mult32((*tmpX++), (*tmpH--));

-			i -= 4;

-		}

-		y[n] = ((s<<1) + 0x8000)>>16;    

-		n++;

-

-		tmpH = h+n;

-		tmpX = x;

-		i=n+1;

-		s =  vo_mult32((*tmpX++), (*tmpH--));i--;

-		s += vo_mult32((*tmpX++), (*tmpH--));i--;

-		s += vo_mult32((*tmpX++), (*tmpH--));i--;

-

-		while(i>0)

-		{

-			s += vo_mult32((*tmpX++), (*tmpH--));

-			s += vo_mult32((*tmpX++), (*tmpH--));

-			s += vo_mult32((*tmpX++), (*tmpH--));

-			s += vo_mult32((*tmpX++), (*tmpH--));

-			i -= 4;

-		}

-		y[n] = ((s<<1) + 0x8000)>>16;   

-		n++;

-

-		s = 0;

-		tmpH = h+n;

-		tmpX = x;

-		i=n+1;

-		while(i>0)

-		{

-			s += vo_mult32((*tmpX++), (*tmpH--));

-			s += vo_mult32((*tmpX++), (*tmpH--));

-			s += vo_mult32((*tmpX++), (*tmpH--));

-			s += vo_mult32((*tmpX++), (*tmpH--));

-			i -= 4;

-		}

-		y[n] = ((s<<1) + 0x8000)>>16;   

-		n++;        

-	}

-	return;

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+       File: convolve.c
+
+	   Description:Perform the convolution between two vectors x[] and h[]
+	               and write the result in the vector y[]
+
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+
+void Convolve (
+		Word16 x[],        /* (i)     : input vector                           */
+		Word16 h[],        /* (i)     : impulse response                       */
+		Word16 y[],        /* (o)     : output vector                          */
+		Word16 L           /* (i)     : vector size                            */
+	      )
+{
+	Word32  i, n;
+	Word16 *tmpH,*tmpX;
+	Word32 s;
+	for (n = 0; n < 64;)
+	{
+		tmpH = h+n;
+		tmpX = x;
+		i=n+1;
+		s = vo_mult32((*tmpX++), (*tmpH--));i--;
+		while(i>0)
+		{
+			s += vo_mult32((*tmpX++), (*tmpH--));
+			s += vo_mult32((*tmpX++), (*tmpH--));
+			s += vo_mult32((*tmpX++), (*tmpH--));
+			s += vo_mult32((*tmpX++), (*tmpH--));
+			i -= 4;
+		}
+		y[n] = ((s<<1) + 0x8000)>>16;
+		n++;
+
+		tmpH = h+n;
+		tmpX = x;
+		i=n+1;
+		s =  vo_mult32((*tmpX++), (*tmpH--));i--;
+		s += vo_mult32((*tmpX++), (*tmpH--));i--;
+
+		while(i>0)
+		{
+			s += vo_mult32((*tmpX++), (*tmpH--));
+			s += vo_mult32((*tmpX++), (*tmpH--));
+			s += vo_mult32((*tmpX++), (*tmpH--));
+			s += vo_mult32((*tmpX++), (*tmpH--));
+			i -= 4;
+		}
+		y[n] = ((s<<1) + 0x8000)>>16;
+		n++;
+
+		tmpH = h+n;
+		tmpX = x;
+		i=n+1;
+		s =  vo_mult32((*tmpX++), (*tmpH--));i--;
+		s += vo_mult32((*tmpX++), (*tmpH--));i--;
+		s += vo_mult32((*tmpX++), (*tmpH--));i--;
+
+		while(i>0)
+		{
+			s += vo_mult32((*tmpX++), (*tmpH--));
+			s += vo_mult32((*tmpX++), (*tmpH--));
+			s += vo_mult32((*tmpX++), (*tmpH--));
+			s += vo_mult32((*tmpX++), (*tmpH--));
+			i -= 4;
+		}
+		y[n] = ((s<<1) + 0x8000)>>16;
+		n++;
+
+		s = 0;
+		tmpH = h+n;
+		tmpX = x;
+		i=n+1;
+		while(i>0)
+		{
+			s += vo_mult32((*tmpX++), (*tmpH--));
+			s += vo_mult32((*tmpX++), (*tmpH--));
+			s += vo_mult32((*tmpX++), (*tmpH--));
+			s += vo_mult32((*tmpX++), (*tmpH--));
+			i -= 4;
+		}
+		y[n] = ((s<<1) + 0x8000)>>16;
+		n++;
+	}
+	return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/cor_h_x.c b/media/libstagefright/codecs/amrwbenc/src/cor_h_x.c
index 3c2e9d5..d9245ed 100644
--- a/media/libstagefright/codecs/amrwbenc/src/cor_h_x.c
+++ b/media/libstagefright/codecs/amrwbenc/src/cor_h_x.c
@@ -1,127 +1,127 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*       File: cor_h_x.c                                                *

-*                                                                      *

-*	   Description:Compute correlation between target "x[]" and "h[]"  *

-*	               Designed for codebook search (24 pulses, 4 tracks,  * 

-*				   4 pulses per track, 16 positions in each track) to  *

-*				   avoid saturation.                                   *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "math_op.h"

-

-#define L_SUBFR   64

-#define NB_TRACK  4

-#define STEP      4

-

-void cor_h_x(

-		Word16 h[],                           /* (i) Q12 : impulse response of weighted synthesis filter */

-		Word16 x[],                           /* (i) Q0  : target vector                                 */

-		Word16 dn[]                           /* (o) <12bit : correlation between target and h[]         */

-	    )

-{

-	Word32 i, j;

-	Word32 L_tmp, y32[L_SUBFR], L_tot;

-	Word16 *p1, *p2;

-	Word32 *p3;

-	Word32 L_max, L_max1, L_max2, L_max3;

-	/* first keep the result on 32 bits and find absolute maximum */

-	L_tot  = 1;                            

-	L_max  = 0; 

-	L_max1 = 0;

-	L_max2 = 0;

-	L_max3 = 0;

-	for (i = 0; i < L_SUBFR; i += STEP)

-	{

-		L_tmp = 1;                                    /* 1 -> to avoid null dn[] */

-		p1 = &x[i];

-		p2 = &h[0];

-		for (j = i; j < L_SUBFR; j++)

-			L_tmp += vo_L_mult(*p1++, *p2++);

-

-		y32[i] = L_tmp;               

-		L_tmp = (L_tmp > 0)? L_tmp:-L_tmp;

-		if(L_tmp > L_max)

-		{

-			L_max = L_tmp;             

-		}

-

-		L_tmp = 1L;

-		p1 = &x[i+1];

-		p2 = &h[0];

-		for (j = i+1; j < L_SUBFR; j++)

-			L_tmp += vo_L_mult(*p1++, *p2++);

-

-		y32[i+1] = L_tmp;               

-		L_tmp = (L_tmp > 0)? L_tmp:-L_tmp;

-		if(L_tmp > L_max1)

-		{

-			L_max1 = L_tmp;             

-		}

-

-		L_tmp = 1;

-		p1 = &x[i+2];

-		p2 = &h[0];

-		for (j = i+2; j < L_SUBFR; j++)

-			L_tmp += vo_L_mult(*p1++, *p2++);

-

-		y32[i+2] = L_tmp;               

-		L_tmp = (L_tmp > 0)? L_tmp:-L_tmp;

-		if(L_tmp > L_max2)

-		{

-			L_max2 = L_tmp;             

-		}

-

-		L_tmp = 1;

-		p1 = &x[i+3];

-		p2 = &h[0];

-		for (j = i+3; j < L_SUBFR; j++)

-			L_tmp += vo_L_mult(*p1++, *p2++);

-

-		y32[i+3] = L_tmp;               

-		L_tmp = (L_tmp > 0)? L_tmp:-L_tmp;

-		if(L_tmp > L_max3)

-		{

-			L_max3 = L_tmp;             

-		}

-	}

-	/* tot += 3*max / 8 */

-	L_max = ((L_max + L_max1 + L_max2 + L_max3) >> 2);

-	L_tot = vo_L_add(L_tot, L_max);       /* +max/4 */

-	L_tot = vo_L_add(L_tot, (L_max >> 1));  /* +max/8 */

-

-	/* Find the number of right shifts to do on y32[] so that    */

-	/* 6.0 x sumation of max of dn[] in each track not saturate. */

-	j = norm_l(L_tot) - 4;             /* 4 -> 16 x tot */

-	p1 = dn;

-	p3 = y32;

-	for (i = 0; i < L_SUBFR; i+=4)

-	{

-		*p1++ = vo_round(L_shl(*p3++, j));

-		*p1++ = vo_round(L_shl(*p3++, j));

-		*p1++ = vo_round(L_shl(*p3++, j));

-		*p1++ = vo_round(L_shl(*p3++, j));

-	}

-	return;

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*       File: cor_h_x.c                                                *
+*                                                                      *
+*	   Description:Compute correlation between target "x[]" and "h[]"  *
+*	               Designed for codebook search (24 pulses, 4 tracks,  *
+*				   4 pulses per track, 16 positions in each track) to  *
+*				   avoid saturation.                                   *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "math_op.h"
+
+#define L_SUBFR   64
+#define NB_TRACK  4
+#define STEP      4
+
+void cor_h_x(
+		Word16 h[],                           /* (i) Q12 : impulse response of weighted synthesis filter */
+		Word16 x[],                           /* (i) Q0  : target vector                                 */
+		Word16 dn[]                           /* (o) <12bit : correlation between target and h[]         */
+	    )
+{
+	Word32 i, j;
+	Word32 L_tmp, y32[L_SUBFR], L_tot;
+	Word16 *p1, *p2;
+	Word32 *p3;
+	Word32 L_max, L_max1, L_max2, L_max3;
+	/* first keep the result on 32 bits and find absolute maximum */
+	L_tot  = 1;
+	L_max  = 0;
+	L_max1 = 0;
+	L_max2 = 0;
+	L_max3 = 0;
+	for (i = 0; i < L_SUBFR; i += STEP)
+	{
+		L_tmp = 1;                                    /* 1 -> to avoid null dn[] */
+		p1 = &x[i];
+		p2 = &h[0];
+		for (j = i; j < L_SUBFR; j++)
+			L_tmp += vo_L_mult(*p1++, *p2++);
+
+		y32[i] = L_tmp;
+		L_tmp = (L_tmp > 0)? L_tmp:-L_tmp;
+		if(L_tmp > L_max)
+		{
+			L_max = L_tmp;
+		}
+
+		L_tmp = 1L;
+		p1 = &x[i+1];
+		p2 = &h[0];
+		for (j = i+1; j < L_SUBFR; j++)
+			L_tmp += vo_L_mult(*p1++, *p2++);
+
+		y32[i+1] = L_tmp;
+		L_tmp = (L_tmp > 0)? L_tmp:-L_tmp;
+		if(L_tmp > L_max1)
+		{
+			L_max1 = L_tmp;
+		}
+
+		L_tmp = 1;
+		p1 = &x[i+2];
+		p2 = &h[0];
+		for (j = i+2; j < L_SUBFR; j++)
+			L_tmp += vo_L_mult(*p1++, *p2++);
+
+		y32[i+2] = L_tmp;
+		L_tmp = (L_tmp > 0)? L_tmp:-L_tmp;
+		if(L_tmp > L_max2)
+		{
+			L_max2 = L_tmp;
+		}
+
+		L_tmp = 1;
+		p1 = &x[i+3];
+		p2 = &h[0];
+		for (j = i+3; j < L_SUBFR; j++)
+			L_tmp += vo_L_mult(*p1++, *p2++);
+
+		y32[i+3] = L_tmp;
+		L_tmp = (L_tmp > 0)? L_tmp:-L_tmp;
+		if(L_tmp > L_max3)
+		{
+			L_max3 = L_tmp;
+		}
+	}
+	/* tot += 3*max / 8 */
+	L_max = ((L_max + L_max1 + L_max2 + L_max3) >> 2);
+	L_tot = vo_L_add(L_tot, L_max);       /* +max/4 */
+	L_tot = vo_L_add(L_tot, (L_max >> 1));  /* +max/8 */
+
+	/* Find the number of right shifts to do on y32[] so that    */
+	/* 6.0 x sumation of max of dn[] in each track not saturate. */
+	j = norm_l(L_tot) - 4;             /* 4 -> 16 x tot */
+	p1 = dn;
+	p3 = y32;
+	for (i = 0; i < L_SUBFR; i+=4)
+	{
+		*p1++ = vo_round(L_shl(*p3++, j));
+		*p1++ = vo_round(L_shl(*p3++, j));
+		*p1++ = vo_round(L_shl(*p3++, j));
+		*p1++ = vo_round(L_shl(*p3++, j));
+	}
+	return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/decim54.c b/media/libstagefright/codecs/amrwbenc/src/decim54.c
index 429a7d6..3b88514 100644
--- a/media/libstagefright/codecs/amrwbenc/src/decim54.c
+++ b/media/libstagefright/codecs/amrwbenc/src/decim54.c
@@ -1,146 +1,146 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*      File: decim54.c                                                 *

-*                                                                      *

-*	   Description:Decimation of 16kHz signal to 12.8kHz           *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "acelp.h"

-#include "cnst.h"

-

-#define FAC5   5

-#define DOWN_FAC  26215                    /* 4/5 in Q15 */

-

-#define NB_COEF_DOWN  15

-

-/* Local functions */

-static void Down_samp(

-		Word16 * sig,                         /* input:  signal to downsampling  */

-		Word16 * sig_d,                       /* output: downsampled signal      */

-		Word16 L_frame_d                      /* input:  length of output        */

-		);

-

-/* 1/5 resolution interpolation filter  (in Q14)  */

-/* -1.5dB @ 6kHz, -6dB @ 6.4kHz, -10dB @ 6.6kHz, -20dB @ 6.9kHz, -25dB @ 7kHz, -55dB @ 8kHz */

-

-static Word16 fir_down1[4][30] =

-{

-	{-5, 24, -50, 54, 0, -128, 294, -408, 344, 0, -647, 1505, -2379, 3034, 13107, 3034, -2379, 1505, -647, 0, 344, -408,

-	294, -128, 0, 54, -50, 24, -5, 0},

-

-	{-6, 19, -26, 0, 77, -188, 270, -233, 0, 434, -964, 1366, -1293, 0, 12254, 6575, -2746, 1030, 0, -507, 601, -441,

-	198, 0, -95, 99, -58, 18, 0, -1},

-

-	{-3, 9, 0, -41, 111, -170, 153, 0, -295, 649, -888, 770, 0, -1997, 9894, 9894, -1997, 0, 770, -888, 649, -295, 0,

-	153, -170, 111, -41, 0, 9, -3},

-

-	{-1, 0, 18, -58, 99, -95, 0, 198, -441, 601, -507, 0, 1030, -2746, 6575, 12254, 0, -1293, 1366, -964, 434, 0,

-	-233, 270, -188, 77, 0, -26, 19, -6}

-};

-

-void Init_Decim_12k8(

-		Word16 mem[]                          /* output: memory (2*NB_COEF_DOWN) set to zeros */

-		)

-{

-	Set_zero(mem, 2 * NB_COEF_DOWN);

-	return;

-}

-

-void Decim_12k8(

-		Word16 sig16k[],                      /* input:  signal to downsampling  */

-		Word16 lg,                            /* input:  length of input         */

-		Word16 sig12k8[],                     /* output: decimated signal        */

-		Word16 mem[]                          /* in/out: memory (2*NB_COEF_DOWN) */

-	       )

-{

-	Word16 lg_down;

-	Word16 signal[L_FRAME16k + (2 * NB_COEF_DOWN)];

-

-	Copy(mem, signal, 2 * NB_COEF_DOWN);

-

-	Copy(sig16k, signal + (2 * NB_COEF_DOWN), lg);

-

-	lg_down = (lg * DOWN_FAC)>>15;

-

-	Down_samp(signal + NB_COEF_DOWN, sig12k8, lg_down);

-

-	Copy(signal + lg, mem, 2 * NB_COEF_DOWN);

-

-	return;

-}

-

-static void Down_samp(

-		Word16 * sig,                         /* input:  signal to downsampling  */

-		Word16 * sig_d,                       /* output: downsampled signal      */

-		Word16 L_frame_d                      /* input:  length of output        */

-		)

-{

-	Word32 i, j, frac, pos;

-	Word16 *x, *y;

-	Word32 L_sum;

-

-	pos = 0;                                 /* position is in Q2 -> 1/4 resolution  */

-	for (j = 0; j < L_frame_d; j++)

-	{

-		i = (pos >> 2);                   /* integer part     */

-		frac = pos & 3;                   /* fractional part */

-		x = sig + i - NB_COEF_DOWN + 1;

-		y = (Word16 *)(fir_down1 + frac);

-

-		L_sum = vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x++),(*y++));

-		L_sum += vo_mult32((*x),(*y));

-

-		L_sum = L_shl2(L_sum, 2);              

-		sig_d[j] = extract_h(L_add(L_sum, 0x8000)); 

-		pos += FAC5;              /* pos + 5/4 */

-	}

-	return;

-}

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*      File: decim54.c                                                 *
+*                                                                      *
+*	   Description:Decimation of 16kHz signal to 12.8kHz           *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "acelp.h"
+#include "cnst.h"
+
+#define FAC5   5
+#define DOWN_FAC  26215                    /* 4/5 in Q15 */
+
+#define NB_COEF_DOWN  15
+
+/* Local functions */
+static void Down_samp(
+		Word16 * sig,                         /* input:  signal to downsampling  */
+		Word16 * sig_d,                       /* output: downsampled signal      */
+		Word16 L_frame_d                      /* input:  length of output        */
+		);
+
+/* 1/5 resolution interpolation filter  (in Q14)  */
+/* -1.5dB @ 6kHz, -6dB @ 6.4kHz, -10dB @ 6.6kHz, -20dB @ 6.9kHz, -25dB @ 7kHz, -55dB @ 8kHz */
+
+static Word16 fir_down1[4][30] =
+{
+	{-5, 24, -50, 54, 0, -128, 294, -408, 344, 0, -647, 1505, -2379, 3034, 13107, 3034, -2379, 1505, -647, 0, 344, -408,
+	294, -128, 0, 54, -50, 24, -5, 0},
+
+	{-6, 19, -26, 0, 77, -188, 270, -233, 0, 434, -964, 1366, -1293, 0, 12254, 6575, -2746, 1030, 0, -507, 601, -441,
+	198, 0, -95, 99, -58, 18, 0, -1},
+
+	{-3, 9, 0, -41, 111, -170, 153, 0, -295, 649, -888, 770, 0, -1997, 9894, 9894, -1997, 0, 770, -888, 649, -295, 0,
+	153, -170, 111, -41, 0, 9, -3},
+
+	{-1, 0, 18, -58, 99, -95, 0, 198, -441, 601, -507, 0, 1030, -2746, 6575, 12254, 0, -1293, 1366, -964, 434, 0,
+	-233, 270, -188, 77, 0, -26, 19, -6}
+};
+
+void Init_Decim_12k8(
+		Word16 mem[]                          /* output: memory (2*NB_COEF_DOWN) set to zeros */
+		)
+{
+	Set_zero(mem, 2 * NB_COEF_DOWN);
+	return;
+}
+
+void Decim_12k8(
+		Word16 sig16k[],                      /* input:  signal to downsampling  */
+		Word16 lg,                            /* input:  length of input         */
+		Word16 sig12k8[],                     /* output: decimated signal        */
+		Word16 mem[]                          /* in/out: memory (2*NB_COEF_DOWN) */
+	       )
+{
+	Word16 lg_down;
+	Word16 signal[L_FRAME16k + (2 * NB_COEF_DOWN)];
+
+	Copy(mem, signal, 2 * NB_COEF_DOWN);
+
+	Copy(sig16k, signal + (2 * NB_COEF_DOWN), lg);
+
+	lg_down = (lg * DOWN_FAC)>>15;
+
+	Down_samp(signal + NB_COEF_DOWN, sig12k8, lg_down);
+
+	Copy(signal + lg, mem, 2 * NB_COEF_DOWN);
+
+	return;
+}
+
+static void Down_samp(
+		Word16 * sig,                         /* input:  signal to downsampling  */
+		Word16 * sig_d,                       /* output: downsampled signal      */
+		Word16 L_frame_d                      /* input:  length of output        */
+		)
+{
+	Word32 i, j, frac, pos;
+	Word16 *x, *y;
+	Word32 L_sum;
+
+	pos = 0;                                 /* position is in Q2 -> 1/4 resolution  */
+	for (j = 0; j < L_frame_d; j++)
+	{
+		i = (pos >> 2);                   /* integer part     */
+		frac = pos & 3;                   /* fractional part */
+		x = sig + i - NB_COEF_DOWN + 1;
+		y = (Word16 *)(fir_down1 + frac);
+
+		L_sum = vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x++),(*y++));
+		L_sum += vo_mult32((*x),(*y));
+
+		L_sum = L_shl2(L_sum, 2);
+		sig_d[j] = extract_h(L_add(L_sum, 0x8000));
+		pos += FAC5;              /* pos + 5/4 */
+	}
+	return;
+}
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/deemph.c b/media/libstagefright/codecs/amrwbenc/src/deemph.c
index 6ad528d..0c49d6b 100644
--- a/media/libstagefright/codecs/amrwbenc/src/deemph.c
+++ b/media/libstagefright/codecs/amrwbenc/src/deemph.c
@@ -1,117 +1,117 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*       File: deemph.c                                                 *

-*                                                                      *

-*	   Description:filtering through 1/(1-mu z^ -1)                    *

-*	               Deemph2 --> signal is divided by 2                  *

-*				   Deemph_32 --> for 32 bits signal.                   *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "math_op.h"

-

-void Deemph(

-		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */

-		Word16 mu,                            /* (i) Q15 : deemphasis factor                      */

-		Word16 L,                             /* (i)     : vector size                            */

-		Word16 * mem                          /* (i/o)   : memory (y[-1])                         */

-	   )

-{

-	Word32 i;

-	Word32 L_tmp;

-

-	L_tmp = L_deposit_h(x[0]);

-	L_tmp = L_mac(L_tmp, *mem, mu);

-	x[0] = vo_round(L_tmp);                   

-

-	for (i = 1; i < L; i++)

-	{

-		L_tmp = L_deposit_h(x[i]);

-		L_tmp = L_mac(L_tmp, x[i - 1], mu);

-		x[i] = voround(L_tmp);               

-	}

-

-	*mem = x[L - 1];                       

-

-	return;

-}

-

-

-void Deemph2(

-		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */

-		Word16 mu,                            /* (i) Q15 : deemphasis factor                      */

-		Word16 L,                             /* (i)     : vector size                            */

-		Word16 * mem                          /* (i/o)   : memory (y[-1])                         */

-	    )

-{

-	Word32 i;

-	Word32 L_tmp;

-	L_tmp = x[0] << 15;

-	L_tmp += ((*mem) * mu)<<1;

-	x[0] = (L_tmp + 0x8000)>>16;                   

-	for (i = 1; i < L; i++)

-	{

-		L_tmp = x[i] << 15;

-		L_tmp += (x[i - 1] * mu)<<1;

-		x[i] = (L_tmp + 0x8000)>>16;               

-	}

-	*mem = x[L - 1];                       

-	return;

-}

-

-

-void Deemph_32(

-		Word16 x_hi[],                        /* (i)     : input signal (bit31..16) */

-		Word16 x_lo[],                        /* (i)     : input signal (bit15..4)  */

-		Word16 y[],                           /* (o)     : output signal (x16)      */

-		Word16 mu,                            /* (i) Q15 : deemphasis factor        */

-		Word16 L,                             /* (i)     : vector size              */

-		Word16 * mem                          /* (i/o)   : memory (y[-1])           */

-	      )

-{

-	Word16 fac;

-	Word32 i, L_tmp;

-

-	fac = mu >> 1;                                /* Q15 --> Q14 */

-

-	L_tmp = L_deposit_h(x_hi[0]);

-	L_tmp += (x_lo[0] * 8)<<1;

-	L_tmp = (L_tmp << 3);

-	L_tmp += ((*mem) * fac)<<1;

-	L_tmp = (L_tmp << 1);               

-	y[0] = (L_tmp + 0x8000)>>16;                  

-

-	for (i = 1; i < L; i++)

-	{

-		L_tmp = L_deposit_h(x_hi[i]);

-		L_tmp += (x_lo[i] * 8)<<1;

-		L_tmp = (L_tmp << 3);

-		L_tmp += (y[i - 1] * fac)<<1;

-		L_tmp = (L_tmp << 1);           

-		y[i] = (L_tmp + 0x8000)>>16;               

-	}

-

-	*mem = y[L - 1];                       

-

-	return;

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*       File: deemph.c                                                 *
+*                                                                      *
+*	   Description:filtering through 1/(1-mu z^ -1)                    *
+*	               Deemph2 --> signal is divided by 2                  *
+*				   Deemph_32 --> for 32 bits signal.                   *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "math_op.h"
+
+void Deemph(
+		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
+		Word16 mu,                            /* (i) Q15 : deemphasis factor                      */
+		Word16 L,                             /* (i)     : vector size                            */
+		Word16 * mem                          /* (i/o)   : memory (y[-1])                         */
+	   )
+{
+	Word32 i;
+	Word32 L_tmp;
+
+	L_tmp = L_deposit_h(x[0]);
+	L_tmp = L_mac(L_tmp, *mem, mu);
+	x[0] = vo_round(L_tmp);
+
+	for (i = 1; i < L; i++)
+	{
+		L_tmp = L_deposit_h(x[i]);
+		L_tmp = L_mac(L_tmp, x[i - 1], mu);
+		x[i] = voround(L_tmp);
+	}
+
+	*mem = x[L - 1];
+
+	return;
+}
+
+
+void Deemph2(
+		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
+		Word16 mu,                            /* (i) Q15 : deemphasis factor                      */
+		Word16 L,                             /* (i)     : vector size                            */
+		Word16 * mem                          /* (i/o)   : memory (y[-1])                         */
+	    )
+{
+	Word32 i;
+	Word32 L_tmp;
+	L_tmp = x[0] << 15;
+	L_tmp += ((*mem) * mu)<<1;
+	x[0] = (L_tmp + 0x8000)>>16;
+	for (i = 1; i < L; i++)
+	{
+		L_tmp = x[i] << 15;
+		L_tmp += (x[i - 1] * mu)<<1;
+		x[i] = (L_tmp + 0x8000)>>16;
+	}
+	*mem = x[L - 1];
+	return;
+}
+
+
+void Deemph_32(
+		Word16 x_hi[],                        /* (i)     : input signal (bit31..16) */
+		Word16 x_lo[],                        /* (i)     : input signal (bit15..4)  */
+		Word16 y[],                           /* (o)     : output signal (x16)      */
+		Word16 mu,                            /* (i) Q15 : deemphasis factor        */
+		Word16 L,                             /* (i)     : vector size              */
+		Word16 * mem                          /* (i/o)   : memory (y[-1])           */
+	      )
+{
+	Word16 fac;
+	Word32 i, L_tmp;
+
+	fac = mu >> 1;                                /* Q15 --> Q14 */
+
+	L_tmp = L_deposit_h(x_hi[0]);
+	L_tmp += (x_lo[0] * 8)<<1;
+	L_tmp = (L_tmp << 3);
+	L_tmp += ((*mem) * fac)<<1;
+	L_tmp = (L_tmp << 1);
+	y[0] = (L_tmp + 0x8000)>>16;
+
+	for (i = 1; i < L; i++)
+	{
+		L_tmp = L_deposit_h(x_hi[i]);
+		L_tmp += (x_lo[i] * 8)<<1;
+		L_tmp = (L_tmp << 3);
+		L_tmp += (y[i - 1] * fac)<<1;
+		L_tmp = (L_tmp << 1);
+		y[i] = (L_tmp + 0x8000)>>16;
+	}
+
+	*mem = y[L - 1];
+
+	return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/dtx.c b/media/libstagefright/codecs/amrwbenc/src/dtx.c
index 02921eb..2cfaced 100644
--- a/media/libstagefright/codecs/amrwbenc/src/dtx.c
+++ b/media/libstagefright/codecs/amrwbenc/src/dtx.c
@@ -1,605 +1,605 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*       File: dtx.c                                                    *

-*                                                                      *

-*	    Description:DTX functions                                  *

-*                                                                      *

-************************************************************************/

-

-#include <stdio.h>

-#include <stdlib.h>

-#include "typedef.h"

-#include "basic_op.h"

-#include "oper_32b.h"

-#include "math_op.h"

-#include "cnst.h"

-#include "acelp.h"                         /* prototype of functions    */

-#include "bits.h"

-#include "dtx.h"

-#include "log2.h"

-#include "mem_align.h"

-

-static void aver_isf_history(

-		Word16 isf_old[],

-		Word16 indices[],

-		Word32 isf_aver[]

-		);

-

-static void find_frame_indices(

-		Word16 isf_old_tx[],

-		Word16 indices[],

-		dtx_encState * st

-		);

-

-static Word16 dithering_control(

-		dtx_encState * st

-		);

-

-/* excitation energy adjustment depending on speech coder mode used, Q7 */

-static Word16 en_adjust[9] =

-{

-	230,                                   /* mode0 = 7k  :  -5.4dB  */

-	179,                                   /* mode1 = 9k  :  -4.2dB  */

-	141,                                   /* mode2 = 12k :  -3.3dB  */

-	128,                                   /* mode3 = 14k :  -3.0dB  */

-	122,                                   /* mode4 = 16k :  -2.85dB */

-	115,                                   /* mode5 = 18k :  -2.7dB  */

-	115,                                   /* mode6 = 20k :  -2.7dB  */

-	115,                                   /* mode7 = 23k :  -2.7dB  */

-	115                                    /* mode8 = 24k :  -2.7dB  */

-};

-

-/**************************************************************************

-*

-* Function    : dtx_enc_init

-*

-**************************************************************************/

-Word16 dtx_enc_init(dtx_encState ** st, Word16 isf_init[], VO_MEM_OPERATOR *pMemOP)

-{

-	dtx_encState *s;

-

-	if (st == (dtx_encState **) NULL)

-	{

-		fprintf(stderr, "dtx_enc_init: invalid parameter\n");

-		return -1;

-	}

-	*st = NULL;

-

-	/* allocate memory */

-	if ((s = (dtx_encState *)mem_malloc(pMemOP, sizeof(dtx_encState), 32, VO_INDEX_ENC_AMRWB)) == NULL)

-	{

-		fprintf(stderr, "dtx_enc_init: can not malloc state structure\n");

-		return -1;

-	}

-	dtx_enc_reset(s, isf_init);

-	*st = s;

-	return 0;

-}

-

-/**************************************************************************

-*

-* Function    : dtx_enc_reset

-*

-**************************************************************************/

-Word16 dtx_enc_reset(dtx_encState * st, Word16 isf_init[])

-{

-	Word32 i;

-

-	if (st == (dtx_encState *) NULL)

-	{

-		fprintf(stderr, "dtx_enc_reset: invalid parameter\n");

-		return -1;

-	}

-	st->hist_ptr = 0;                      

-	st->log_en_index = 0;                  

-

-	/* Init isf_hist[] */

-	for (i = 0; i < DTX_HIST_SIZE; i++)

-	{

-		Copy(isf_init, &st->isf_hist[i * M], M);

-	}

-	st->cng_seed = RANDOM_INITSEED;       

-

-	/* Reset energy history */

-	Set_zero(st->log_en_hist, DTX_HIST_SIZE);

-

-	st->dtxHangoverCount = DTX_HANG_CONST; 

-	st->decAnaElapsedCount = 32767;        

-

-	for (i = 0; i < 28; i++)

-	{

-		st->D[i] = 0;                      

-	}

-

-	for (i = 0; i < DTX_HIST_SIZE - 1; i++)

-	{

-		st->sumD[i] = 0;                   

-	}

-

-	return 1;

-}

-

-/**************************************************************************

-*

-* Function    : dtx_enc_exit

-*

-**************************************************************************/

-void dtx_enc_exit(dtx_encState ** st, VO_MEM_OPERATOR *pMemOP)

-{

-	if (st == NULL || *st == NULL)

-		return;

-	/* deallocate memory */

-	mem_free(pMemOP, *st, VO_INDEX_ENC_AMRWB);

-	*st = NULL;

-	return;

-}

-

-

-/**************************************************************************

-*

-* Function    : dtx_enc

-*

-**************************************************************************/

-Word16 dtx_enc(

-		dtx_encState * st,                    /* i/o : State struct                                         */

-		Word16 isf[M],                        /* o   : CN ISF vector                                        */

-		Word16 * exc2,                        /* o   : CN excitation                                        */

-		Word16 ** prms

-	      )

-{

-	Word32 i, j;

-	Word16 indice[7];

-	Word16 log_en, gain, level, exp, exp0, tmp;

-	Word16 log_en_int_e, log_en_int_m;

-	Word32 L_isf[M], ener32, level32;

-	Word16 isf_order[3];

-	Word16 CN_dith;

-

-	/* VOX mode computation of SID parameters */

-	log_en = 0;

-	for (i = 0; i < M; i++)

-	{

-		L_isf[i] = 0;

-	}

-	/* average energy and isf */

-	for (i = 0; i < DTX_HIST_SIZE; i++)

-	{

-		/* Division by DTX_HIST_SIZE = 8 has been done in dtx_buffer. log_en is in Q10 */

-		log_en = add(log_en, st->log_en_hist[i]);

-

-	}

-	find_frame_indices(st->isf_hist, isf_order, st);

-	aver_isf_history(st->isf_hist, isf_order, L_isf);

-

-	for (j = 0; j < M; j++)

-	{

-		isf[j] = (Word16)(L_isf[j] >> 3);  /* divide by 8 */

-	}

-

-	/* quantize logarithmic energy to 6 bits (-6 : 66 dB) which corresponds to -2:22 in log2(E).  */

-	/* st->log_en_index = (short)( (log_en + 2.0) * 2.625 ); */

-

-	/* increase dynamics to 7 bits (Q8) */

-	log_en = (log_en >> 2);

-

-	/* Add 2 in Q8 = 512 to get log2(E) between 0:24 */

-	log_en = add(log_en, 512);

-

-	/* Multiply by 2.625 to get full 6 bit range. 2.625 = 21504 in Q13. The result is in Q6 */

-	log_en = mult(log_en, 21504);

-

-	/* Quantize Energy */

-	st->log_en_index = shr(log_en, 6);

-

-	if(st->log_en_index > 63)

-	{

-		st->log_en_index = 63;

-	}

-	if (st->log_en_index < 0)

-	{

-		st->log_en_index = 0;

-	}

-	/* Quantize ISFs */

-	Qisf_ns(isf, isf, indice);

-

-

-	Parm_serial(indice[0], 6, prms);

-	Parm_serial(indice[1], 6, prms);

-	Parm_serial(indice[2], 6, prms);

-	Parm_serial(indice[3], 5, prms);

-	Parm_serial(indice[4], 5, prms);

-

-	Parm_serial((st->log_en_index), 6, prms);

-

-	CN_dith = dithering_control(st);

-	Parm_serial(CN_dith, 1, prms);

-

-	/* level = (float)( pow( 2.0f, (float)st->log_en_index / 2.625 - 2.0 ) );    */

-	/* log2(E) in Q9 (log2(E) lies in between -2:22) */

-	log_en = shl(st->log_en_index, 15 - 6);

-

-	/* Divide by 2.625; log_en will be between 0:24  */

-	log_en = mult(log_en, 12483);

-	/* the result corresponds to log2(gain) in Q10 */

-

-	/* Find integer part  */

-	log_en_int_e = (log_en >> 10);

-

-	/* Find fractional part */

-	log_en_int_m = (Word16) (log_en & 0x3ff);

-	log_en_int_m = shl(log_en_int_m, 5);

-

-	/* Subtract 2 from log_en in Q9, i.e divide the gain by 2 (energy by 4) */

-	/* Add 16 in order to have the result of pow2 in Q16 */

-	log_en_int_e = add(log_en_int_e, 16 - 1);

-

-	level32 = Pow2(log_en_int_e, log_en_int_m); /* Q16 */

-	exp0 = norm_l(level32);

-	level32 = (level32 << exp0);        /* level in Q31 */

-	exp0 = (15 - exp0);

-	level = extract_h(level32);            /* level in Q15 */

-

-	/* generate white noise vector */

-	for (i = 0; i < L_FRAME; i++)

-	{

-		exc2[i] = (Random(&(st->cng_seed)) >> 4);

-	}

-

-	/* gain = level / sqrt(ener) * sqrt(L_FRAME) */

-

-	/* energy of generated excitation */

-	ener32 = Dot_product12(exc2, exc2, L_FRAME, &exp);

-

-	Isqrt_n(&ener32, &exp);

-

-	gain = extract_h(ener32);

-

-	gain = mult(level, gain);              /* gain in Q15 */

-

-	exp = add(exp0, exp);

-

-	/* Multiply by sqrt(L_FRAME)=16, i.e. shift left by 4 */

-	exp += 4;

-

-	for (i = 0; i < L_FRAME; i++)

-	{

-		tmp = mult(exc2[i], gain);         /* Q0 * Q15 */

-		exc2[i] = shl(tmp, exp); 

-	}

-

-	return 0;

-}

-

-/**************************************************************************

-*

-* Function    : dtx_buffer Purpose     : handles the DTX buffer

-*

-**************************************************************************/

-Word16 dtx_buffer(

-		dtx_encState * st,                    /* i/o : State struct                    */

-		Word16 isf_new[],                     /* i   : isf vector                      */

-		Word32 enr,                           /* i   : residual energy (in L_FRAME)    */

-		Word16 codec_mode

-		)

-{

-	Word16 log_en;

-

-	Word16 log_en_e;

-	Word16 log_en_m;

-	st->hist_ptr = add(st->hist_ptr, 1); 

-	if(st->hist_ptr == DTX_HIST_SIZE)

-	{

-		st->hist_ptr = 0;

-	}

-	/* copy lsp vector into buffer */

-	Copy(isf_new, &st->isf_hist[st->hist_ptr * M], M);

-

-	/* log_en = (float)log10(enr*0.0059322)/(float)log10(2.0f);  */

-	Log2(enr, &log_en_e, &log_en_m);

-

-	/* convert exponent and mantissa to Word16 Q7. Q7 is used to simplify averaging in dtx_enc */

-	log_en = shl(log_en_e, 7);             /* Q7 */

-	log_en = add(log_en, shr(log_en_m, 15 - 7));

-

-	/* Find energy per sample by multiplying with 0.0059322, i.e subtract log2(1/0.0059322) = 7.39722 The

-	 * constant 0.0059322 takes into account windowings and analysis length from autocorrelation

-	 * computations; 7.39722 in Q7 = 947  */

-	/* Subtract 3 dB = 0.99658 in log2(E) = 127 in Q7. */

-	/* log_en = sub( log_en, 947 + en_adjust[codec_mode] ); */

-

-	/* Find energy per sample (divide by L_FRAME=256), i.e subtract log2(256) = 8.0  (1024 in Q7) */

-	/* Subtract 3 dB = 0.99658 in log2(E) = 127 in Q7. */

-

-	log_en = sub(log_en, add(1024, en_adjust[codec_mode]));

-

-	/* Insert into the buffer */

-	st->log_en_hist[st->hist_ptr] = log_en;

-	return 0;

-}

-

-/**************************************************************************

-*

-* Function    : tx_dtx_handler Purpose     : adds extra speech hangover

-*                                            to analyze speech on

-*                                            the decoding side.

-**************************************************************************/

-void tx_dtx_handler(dtx_encState * st,     /* i/o : State struct           */

-		Word16 vad_flag,                      /* i   : vad decision           */

-		Word16 * usedMode                     /* i/o : mode changed or not    */

-		)

-{

-

-	/* this state machine is in synch with the GSMEFR txDtx machine      */

-	st->decAnaElapsedCount = add(st->decAnaElapsedCount, 1); 

-

-	if (vad_flag != 0)

-	{

-		st->dtxHangoverCount = DTX_HANG_CONST;

-	} else

-	{                                      /* non-speech */

-		if (st->dtxHangoverCount == 0)

-		{                                  /* out of decoder analysis hangover  */

-			st->decAnaElapsedCount = 0;    

-			*usedMode = MRDTX;            

-		} else

-		{                                  /* in possible analysis hangover */

-			st->dtxHangoverCount = sub(st->dtxHangoverCount, 1);

-

-			/* decAnaElapsedCount + dtxHangoverCount < DTX_ELAPSED_FRAMES_THRESH */

-			if (sub(add(st->decAnaElapsedCount, st->dtxHangoverCount),

-						DTX_ELAPSED_FRAMES_THRESH) < 0)

-			{

-				*usedMode = MRDTX;

-				/* if short time since decoder update, do not add extra HO */

-			}

-			/* else override VAD and stay in speech mode *usedMode and add extra hangover */

-		}

-	}

-

-	return;

-}

-

-

-

-static void aver_isf_history(

-		Word16 isf_old[],

-		Word16 indices[],

-		Word32 isf_aver[]

-		)

-{

-	Word32 i, j, k;

-	Word16 isf_tmp[2 * M];

-	Word32 L_tmp;

-

-	/* Memorize in isf_tmp[][] the ISF vectors to be replaced by */

-	/* the median ISF vector prior to the averaging               */

-	for (k = 0; k < 2; k++)

-	{

-		if ((indices[k] + 1) != 0)

-		{

-			for (i = 0; i < M; i++)

-			{

-				isf_tmp[k * M + i] = isf_old[indices[k] * M + i];      

-				isf_old[indices[k] * M + i] = isf_old[indices[2] * M + i];    

-			}

-		}

-	}

-

-	/* Perform the ISF averaging */

-	for (j = 0; j < M; j++)

-	{

-		L_tmp = 0;                      

-

-		for (i = 0; i < DTX_HIST_SIZE; i++)

-		{

-			L_tmp = L_add(L_tmp, L_deposit_l(isf_old[i * M + j]));

-		}

-		isf_aver[j] = L_tmp;              

-	}

-

-	/* Retrieve from isf_tmp[][] the ISF vectors saved prior to averaging */

-	for (k = 0; k < 2; k++)

-	{

-		if ((indices[k] + 1) != 0)

-		{

-			for (i = 0; i < M; i++)

-			{

-				isf_old[indices[k] * M + i] = isf_tmp[k * M + i];

-			}

-		}

-	}

-

-	return;

-}

-

-static void find_frame_indices(

-		Word16 isf_old_tx[],

-		Word16 indices[],

-		dtx_encState * st

-		)

-{

-	Word32 L_tmp, summin, summax, summax2nd;

-	Word16 i, j, tmp;

-	Word16 ptr;

-

-	/* Remove the effect of the oldest frame from the column */

-	/* sum sumD[0..DTX_HIST_SIZE-1]. sumD[DTX_HIST_SIZE] is    */

-	/* not updated since it will be removed later.           */

-

-	tmp = DTX_HIST_SIZE_MIN_ONE;           

-	j = -1;                                

-	for (i = 0; i < DTX_HIST_SIZE_MIN_ONE; i++)

-	{

-		j = add(j, tmp);

-		st->sumD[i] = L_sub(st->sumD[i], st->D[j]);     

-		tmp = sub(tmp, 1);

-	}

-

-	/* Shift the column sum sumD. The element sumD[DTX_HIST_SIZE-1]    */

-	/* corresponding to the oldest frame is removed. The sum of     */

-	/* the distances between the latest isf and other isfs, */

-	/* i.e. the element sumD[0], will be computed during this call. */

-	/* Hence this element is initialized to zero.                   */

-

-	for (i = DTX_HIST_SIZE_MIN_ONE; i > 0; i--)

-	{

-		st->sumD[i] = st->sumD[i - 1];     

-	}

-	st->sumD[0] = 0;                       

-

-	/* Remove the oldest frame from the distance matrix.           */

-	/* Note that the distance matrix is replaced by a one-         */

-	/* dimensional array to save static memory.                    */

-

-	tmp = 0;                               

-	for (i = 27; i >= 12; i = (Word16) (i - tmp))

-	{

-		tmp = add(tmp, 1);

-		for (j = tmp; j > 0; j--)

-		{

-			st->D[i - j + 1] = st->D[i - j - tmp];   

-		}

-	}

-

-	/* Compute the first column of the distance matrix D            */

-	/* (squared Euclidean distances from isf1[] to isf_old_tx[][]). */

-

-	ptr = st->hist_ptr;                 

-	for (i = 1; i < DTX_HIST_SIZE; i++)

-	{

-		/* Compute the distance between the latest isf and the other isfs. */

-		ptr = sub(ptr, 1);

-		if (ptr < 0)

-		{

-			ptr = DTX_HIST_SIZE_MIN_ONE;   

-		}

-		L_tmp = 0;                         

-		for (j = 0; j < M; j++)

-		{

-			tmp = sub(isf_old_tx[st->hist_ptr * M + j], isf_old_tx[ptr * M + j]);

-			L_tmp = L_mac(L_tmp, tmp, tmp);

-		}

-		st->D[i - 1] = L_tmp;           

-

-		/* Update also the column sums. */

-		st->sumD[0] = L_add(st->sumD[0], st->D[i - 1]); 

-		st->sumD[i] = L_add(st->sumD[i], st->D[i - 1]); 

-	}

-

-	/* Find the minimum and maximum distances */

-	summax = st->sumD[0];                  

-	summin = st->sumD[0];                  

-	indices[0] = 0;                        

-	indices[2] = 0;                        

-	for (i = 1; i < DTX_HIST_SIZE; i++)

-	{

-		if (L_sub(st->sumD[i], summax) > 0)

-		{

-			indices[0] = i;                

-			summax = st->sumD[i];          

-		}

-		if (L_sub(st->sumD[i], summin) < 0)

-		{

-			indices[2] = i;                

-			summin = st->sumD[i];          

-		}

-	}

-

-	/* Find the second largest distance */

-	summax2nd = -2147483647L;              

-	indices[1] = -1;                       

-	for (i = 0; i < DTX_HIST_SIZE; i++)

-	{

-		if ((L_sub(st->sumD[i], summax2nd) > 0) && (sub(i, indices[0]) != 0))

-		{

-			indices[1] = i;                

-			summax2nd = st->sumD[i];       

-		}

-	}

-

-	for (i = 0; i < 3; i++)

-	{

-		indices[i] = sub(st->hist_ptr, indices[i]);     

-		if (indices[i] < 0)

-		{

-			indices[i] = add(indices[i], DTX_HIST_SIZE);       

-		}

-	}

-

-	/* If maximum distance/MED_THRESH is smaller than minimum distance */

-	/* then the median ISF vector replacement is not performed         */

-	tmp = norm_l(summax);

-	summax = (summax << tmp);

-	summin = (summin << tmp);

-	L_tmp = L_mult(voround(summax), INV_MED_THRESH);

-	if(L_tmp <= summin)

-	{

-		indices[0] = -1; 

-	}

-	/* If second largest distance/MED_THRESH is smaller than     */

-	/* minimum distance then the median ISF vector replacement is    */

-	/* not performed                                                 */

-	summax2nd = L_shl(summax2nd, tmp);

-	L_tmp = L_mult(voround(summax2nd), INV_MED_THRESH);

-	if(L_tmp <= summin)

-	{

-		indices[1] = -1;                 

-	}

-	return;

-}

-

-static Word16 dithering_control(

-		dtx_encState * st

-		)

-{

-	Word16 tmp, mean, CN_dith, gain_diff;

-	Word32 i, ISF_diff;

-

-	/* determine how stationary the spectrum of background noise is */

-	ISF_diff = 0;

-	for (i = 0; i < 8; i++)

-	{

-		ISF_diff = L_add(ISF_diff, st->sumD[i]);

-	}

-	if ((ISF_diff >> 26) > 0)

-	{

-		CN_dith = 1;

-	} else

-	{

-		CN_dith = 0;

-	}

-

-	/* determine how stationary the energy of background noise is */

-	mean = 0;

-	for (i = 0; i < DTX_HIST_SIZE; i++)

-	{

-		mean = add(mean, st->log_en_hist[i]);

-	}

-	mean = (mean >> 3);

-	gain_diff = 0;

-	for (i = 0; i < DTX_HIST_SIZE; i++)

-	{

-		tmp = abs_s(sub(st->log_en_hist[i], mean));

-		gain_diff = add(gain_diff, tmp);

-	}

-	if (gain_diff > GAIN_THR)

-	{

-		CN_dith = 1;

-	}

-	return CN_dith;

-}

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*       File: dtx.c                                                    *
+*                                                                      *
+*	    Description:DTX functions                                  *
+*                                                                      *
+************************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "typedef.h"
+#include "basic_op.h"
+#include "oper_32b.h"
+#include "math_op.h"
+#include "cnst.h"
+#include "acelp.h"                         /* prototype of functions    */
+#include "bits.h"
+#include "dtx.h"
+#include "log2.h"
+#include "mem_align.h"
+
+static void aver_isf_history(
+		Word16 isf_old[],
+		Word16 indices[],
+		Word32 isf_aver[]
+		);
+
+static void find_frame_indices(
+		Word16 isf_old_tx[],
+		Word16 indices[],
+		dtx_encState * st
+		);
+
+static Word16 dithering_control(
+		dtx_encState * st
+		);
+
+/* excitation energy adjustment depending on speech coder mode used, Q7 */
+static Word16 en_adjust[9] =
+{
+	230,                                   /* mode0 = 7k  :  -5.4dB  */
+	179,                                   /* mode1 = 9k  :  -4.2dB  */
+	141,                                   /* mode2 = 12k :  -3.3dB  */
+	128,                                   /* mode3 = 14k :  -3.0dB  */
+	122,                                   /* mode4 = 16k :  -2.85dB */
+	115,                                   /* mode5 = 18k :  -2.7dB  */
+	115,                                   /* mode6 = 20k :  -2.7dB  */
+	115,                                   /* mode7 = 23k :  -2.7dB  */
+	115                                    /* mode8 = 24k :  -2.7dB  */
+};
+
+/**************************************************************************
+*
+* Function    : dtx_enc_init
+*
+**************************************************************************/
+Word16 dtx_enc_init(dtx_encState ** st, Word16 isf_init[], VO_MEM_OPERATOR *pMemOP)
+{
+	dtx_encState *s;
+
+	if (st == (dtx_encState **) NULL)
+	{
+		fprintf(stderr, "dtx_enc_init: invalid parameter\n");
+		return -1;
+	}
+	*st = NULL;
+
+	/* allocate memory */
+	if ((s = (dtx_encState *)mem_malloc(pMemOP, sizeof(dtx_encState), 32, VO_INDEX_ENC_AMRWB)) == NULL)
+	{
+		fprintf(stderr, "dtx_enc_init: can not malloc state structure\n");
+		return -1;
+	}
+	dtx_enc_reset(s, isf_init);
+	*st = s;
+	return 0;
+}
+
+/**************************************************************************
+*
+* Function    : dtx_enc_reset
+*
+**************************************************************************/
+Word16 dtx_enc_reset(dtx_encState * st, Word16 isf_init[])
+{
+	Word32 i;
+
+	if (st == (dtx_encState *) NULL)
+	{
+		fprintf(stderr, "dtx_enc_reset: invalid parameter\n");
+		return -1;
+	}
+	st->hist_ptr = 0;
+	st->log_en_index = 0;
+
+	/* Init isf_hist[] */
+	for (i = 0; i < DTX_HIST_SIZE; i++)
+	{
+		Copy(isf_init, &st->isf_hist[i * M], M);
+	}
+	st->cng_seed = RANDOM_INITSEED;
+
+	/* Reset energy history */
+	Set_zero(st->log_en_hist, DTX_HIST_SIZE);
+
+	st->dtxHangoverCount = DTX_HANG_CONST;
+	st->decAnaElapsedCount = 32767;
+
+	for (i = 0; i < 28; i++)
+	{
+		st->D[i] = 0;
+	}
+
+	for (i = 0; i < DTX_HIST_SIZE - 1; i++)
+	{
+		st->sumD[i] = 0;
+	}
+
+	return 1;
+}
+
+/**************************************************************************
+*
+* Function    : dtx_enc_exit
+*
+**************************************************************************/
+void dtx_enc_exit(dtx_encState ** st, VO_MEM_OPERATOR *pMemOP)
+{
+	if (st == NULL || *st == NULL)
+		return;
+	/* deallocate memory */
+	mem_free(pMemOP, *st, VO_INDEX_ENC_AMRWB);
+	*st = NULL;
+	return;
+}
+
+
+/**************************************************************************
+*
+* Function    : dtx_enc
+*
+**************************************************************************/
+Word16 dtx_enc(
+		dtx_encState * st,                    /* i/o : State struct                                         */
+		Word16 isf[M],                        /* o   : CN ISF vector                                        */
+		Word16 * exc2,                        /* o   : CN excitation                                        */
+		Word16 ** prms
+	      )
+{
+	Word32 i, j;
+	Word16 indice[7];
+	Word16 log_en, gain, level, exp, exp0, tmp;
+	Word16 log_en_int_e, log_en_int_m;
+	Word32 L_isf[M], ener32, level32;
+	Word16 isf_order[3];
+	Word16 CN_dith;
+
+	/* VOX mode computation of SID parameters */
+	log_en = 0;
+	for (i = 0; i < M; i++)
+	{
+		L_isf[i] = 0;
+	}
+	/* average energy and isf */
+	for (i = 0; i < DTX_HIST_SIZE; i++)
+	{
+		/* Division by DTX_HIST_SIZE = 8 has been done in dtx_buffer. log_en is in Q10 */
+		log_en = add(log_en, st->log_en_hist[i]);
+
+	}
+	find_frame_indices(st->isf_hist, isf_order, st);
+	aver_isf_history(st->isf_hist, isf_order, L_isf);
+
+	for (j = 0; j < M; j++)
+	{
+		isf[j] = (Word16)(L_isf[j] >> 3);  /* divide by 8 */
+	}
+
+	/* quantize logarithmic energy to 6 bits (-6 : 66 dB) which corresponds to -2:22 in log2(E).  */
+	/* st->log_en_index = (short)( (log_en + 2.0) * 2.625 ); */
+
+	/* increase dynamics to 7 bits (Q8) */
+	log_en = (log_en >> 2);
+
+	/* Add 2 in Q8 = 512 to get log2(E) between 0:24 */
+	log_en = add(log_en, 512);
+
+	/* Multiply by 2.625 to get full 6 bit range. 2.625 = 21504 in Q13. The result is in Q6 */
+	log_en = mult(log_en, 21504);
+
+	/* Quantize Energy */
+	st->log_en_index = shr(log_en, 6);
+
+	if(st->log_en_index > 63)
+	{
+		st->log_en_index = 63;
+	}
+	if (st->log_en_index < 0)
+	{
+		st->log_en_index = 0;
+	}
+	/* Quantize ISFs */
+	Qisf_ns(isf, isf, indice);
+
+
+	Parm_serial(indice[0], 6, prms);
+	Parm_serial(indice[1], 6, prms);
+	Parm_serial(indice[2], 6, prms);
+	Parm_serial(indice[3], 5, prms);
+	Parm_serial(indice[4], 5, prms);
+
+	Parm_serial((st->log_en_index), 6, prms);
+
+	CN_dith = dithering_control(st);
+	Parm_serial(CN_dith, 1, prms);
+
+	/* level = (float)( pow( 2.0f, (float)st->log_en_index / 2.625 - 2.0 ) );    */
+	/* log2(E) in Q9 (log2(E) lies in between -2:22) */
+	log_en = shl(st->log_en_index, 15 - 6);
+
+	/* Divide by 2.625; log_en will be between 0:24  */
+	log_en = mult(log_en, 12483);
+	/* the result corresponds to log2(gain) in Q10 */
+
+	/* Find integer part  */
+	log_en_int_e = (log_en >> 10);
+
+	/* Find fractional part */
+	log_en_int_m = (Word16) (log_en & 0x3ff);
+	log_en_int_m = shl(log_en_int_m, 5);
+
+	/* Subtract 2 from log_en in Q9, i.e divide the gain by 2 (energy by 4) */
+	/* Add 16 in order to have the result of pow2 in Q16 */
+	log_en_int_e = add(log_en_int_e, 16 - 1);
+
+	level32 = Pow2(log_en_int_e, log_en_int_m); /* Q16 */
+	exp0 = norm_l(level32);
+	level32 = (level32 << exp0);        /* level in Q31 */
+	exp0 = (15 - exp0);
+	level = extract_h(level32);            /* level in Q15 */
+
+	/* generate white noise vector */
+	for (i = 0; i < L_FRAME; i++)
+	{
+		exc2[i] = (Random(&(st->cng_seed)) >> 4);
+	}
+
+	/* gain = level / sqrt(ener) * sqrt(L_FRAME) */
+
+	/* energy of generated excitation */
+	ener32 = Dot_product12(exc2, exc2, L_FRAME, &exp);
+
+	Isqrt_n(&ener32, &exp);
+
+	gain = extract_h(ener32);
+
+	gain = mult(level, gain);              /* gain in Q15 */
+
+	exp = add(exp0, exp);
+
+	/* Multiply by sqrt(L_FRAME)=16, i.e. shift left by 4 */
+	exp += 4;
+
+	for (i = 0; i < L_FRAME; i++)
+	{
+		tmp = mult(exc2[i], gain);         /* Q0 * Q15 */
+		exc2[i] = shl(tmp, exp);
+	}
+
+	return 0;
+}
+
+/**************************************************************************
+*
+* Function    : dtx_buffer Purpose     : handles the DTX buffer
+*
+**************************************************************************/
+Word16 dtx_buffer(
+		dtx_encState * st,                    /* i/o : State struct                    */
+		Word16 isf_new[],                     /* i   : isf vector                      */
+		Word32 enr,                           /* i   : residual energy (in L_FRAME)    */
+		Word16 codec_mode
+		)
+{
+	Word16 log_en;
+
+	Word16 log_en_e;
+	Word16 log_en_m;
+	st->hist_ptr = add(st->hist_ptr, 1);
+	if(st->hist_ptr == DTX_HIST_SIZE)
+	{
+		st->hist_ptr = 0;
+	}
+	/* copy lsp vector into buffer */
+	Copy(isf_new, &st->isf_hist[st->hist_ptr * M], M);
+
+	/* log_en = (float)log10(enr*0.0059322)/(float)log10(2.0f);  */
+	Log2(enr, &log_en_e, &log_en_m);
+
+	/* convert exponent and mantissa to Word16 Q7. Q7 is used to simplify averaging in dtx_enc */
+	log_en = shl(log_en_e, 7);             /* Q7 */
+	log_en = add(log_en, shr(log_en_m, 15 - 7));
+
+	/* Find energy per sample by multiplying with 0.0059322, i.e subtract log2(1/0.0059322) = 7.39722 The
+	 * constant 0.0059322 takes into account windowings and analysis length from autocorrelation
+	 * computations; 7.39722 in Q7 = 947  */
+	/* Subtract 3 dB = 0.99658 in log2(E) = 127 in Q7. */
+	/* log_en = sub( log_en, 947 + en_adjust[codec_mode] ); */
+
+	/* Find energy per sample (divide by L_FRAME=256), i.e subtract log2(256) = 8.0  (1024 in Q7) */
+	/* Subtract 3 dB = 0.99658 in log2(E) = 127 in Q7. */
+
+	log_en = sub(log_en, add(1024, en_adjust[codec_mode]));
+
+	/* Insert into the buffer */
+	st->log_en_hist[st->hist_ptr] = log_en;
+	return 0;
+}
+
+/**************************************************************************
+*
+* Function    : tx_dtx_handler Purpose     : adds extra speech hangover
+*                                            to analyze speech on
+*                                            the decoding side.
+**************************************************************************/
+void tx_dtx_handler(dtx_encState * st,     /* i/o : State struct           */
+		Word16 vad_flag,                      /* i   : vad decision           */
+		Word16 * usedMode                     /* i/o : mode changed or not    */
+		)
+{
+
+	/* this state machine is in synch with the GSMEFR txDtx machine      */
+	st->decAnaElapsedCount = add(st->decAnaElapsedCount, 1);
+
+	if (vad_flag != 0)
+	{
+		st->dtxHangoverCount = DTX_HANG_CONST;
+	} else
+	{                                      /* non-speech */
+		if (st->dtxHangoverCount == 0)
+		{                                  /* out of decoder analysis hangover  */
+			st->decAnaElapsedCount = 0;
+			*usedMode = MRDTX;
+		} else
+		{                                  /* in possible analysis hangover */
+			st->dtxHangoverCount = sub(st->dtxHangoverCount, 1);
+
+			/* decAnaElapsedCount + dtxHangoverCount < DTX_ELAPSED_FRAMES_THRESH */
+			if (sub(add(st->decAnaElapsedCount, st->dtxHangoverCount),
+						DTX_ELAPSED_FRAMES_THRESH) < 0)
+			{
+				*usedMode = MRDTX;
+				/* if short time since decoder update, do not add extra HO */
+			}
+			/* else override VAD and stay in speech mode *usedMode and add extra hangover */
+		}
+	}
+
+	return;
+}
+
+
+
+static void aver_isf_history(
+		Word16 isf_old[],
+		Word16 indices[],
+		Word32 isf_aver[]
+		)
+{
+	Word32 i, j, k;
+	Word16 isf_tmp[2 * M];
+	Word32 L_tmp;
+
+	/* Memorize in isf_tmp[][] the ISF vectors to be replaced by */
+	/* the median ISF vector prior to the averaging               */
+	for (k = 0; k < 2; k++)
+	{
+		if ((indices[k] + 1) != 0)
+		{
+			for (i = 0; i < M; i++)
+			{
+				isf_tmp[k * M + i] = isf_old[indices[k] * M + i];
+				isf_old[indices[k] * M + i] = isf_old[indices[2] * M + i];
+			}
+		}
+	}
+
+	/* Perform the ISF averaging */
+	for (j = 0; j < M; j++)
+	{
+		L_tmp = 0;
+
+		for (i = 0; i < DTX_HIST_SIZE; i++)
+		{
+			L_tmp = L_add(L_tmp, L_deposit_l(isf_old[i * M + j]));
+		}
+		isf_aver[j] = L_tmp;
+	}
+
+	/* Retrieve from isf_tmp[][] the ISF vectors saved prior to averaging */
+	for (k = 0; k < 2; k++)
+	{
+		if ((indices[k] + 1) != 0)
+		{
+			for (i = 0; i < M; i++)
+			{
+				isf_old[indices[k] * M + i] = isf_tmp[k * M + i];
+			}
+		}
+	}
+
+	return;
+}
+
+static void find_frame_indices(
+		Word16 isf_old_tx[],
+		Word16 indices[],
+		dtx_encState * st
+		)
+{
+	Word32 L_tmp, summin, summax, summax2nd;
+	Word16 i, j, tmp;
+	Word16 ptr;
+
+	/* Remove the effect of the oldest frame from the column */
+	/* sum sumD[0..DTX_HIST_SIZE-1]. sumD[DTX_HIST_SIZE] is    */
+	/* not updated since it will be removed later.           */
+
+	tmp = DTX_HIST_SIZE_MIN_ONE;
+	j = -1;
+	for (i = 0; i < DTX_HIST_SIZE_MIN_ONE; i++)
+	{
+		j = add(j, tmp);
+		st->sumD[i] = L_sub(st->sumD[i], st->D[j]);
+		tmp = sub(tmp, 1);
+	}
+
+	/* Shift the column sum sumD. The element sumD[DTX_HIST_SIZE-1]    */
+	/* corresponding to the oldest frame is removed. The sum of     */
+	/* the distances between the latest isf and other isfs, */
+	/* i.e. the element sumD[0], will be computed during this call. */
+	/* Hence this element is initialized to zero.                   */
+
+	for (i = DTX_HIST_SIZE_MIN_ONE; i > 0; i--)
+	{
+		st->sumD[i] = st->sumD[i - 1];
+	}
+	st->sumD[0] = 0;
+
+	/* Remove the oldest frame from the distance matrix.           */
+	/* Note that the distance matrix is replaced by a one-         */
+	/* dimensional array to save static memory.                    */
+
+	tmp = 0;
+	for (i = 27; i >= 12; i = (Word16) (i - tmp))
+	{
+		tmp = add(tmp, 1);
+		for (j = tmp; j > 0; j--)
+		{
+			st->D[i - j + 1] = st->D[i - j - tmp];
+		}
+	}
+
+	/* Compute the first column of the distance matrix D            */
+	/* (squared Euclidean distances from isf1[] to isf_old_tx[][]). */
+
+	ptr = st->hist_ptr;
+	for (i = 1; i < DTX_HIST_SIZE; i++)
+	{
+		/* Compute the distance between the latest isf and the other isfs. */
+		ptr = sub(ptr, 1);
+		if (ptr < 0)
+		{
+			ptr = DTX_HIST_SIZE_MIN_ONE;
+		}
+		L_tmp = 0;
+		for (j = 0; j < M; j++)
+		{
+			tmp = sub(isf_old_tx[st->hist_ptr * M + j], isf_old_tx[ptr * M + j]);
+			L_tmp = L_mac(L_tmp, tmp, tmp);
+		}
+		st->D[i - 1] = L_tmp;
+
+		/* Update also the column sums. */
+		st->sumD[0] = L_add(st->sumD[0], st->D[i - 1]);
+		st->sumD[i] = L_add(st->sumD[i], st->D[i - 1]);
+	}
+
+	/* Find the minimum and maximum distances */
+	summax = st->sumD[0];
+	summin = st->sumD[0];
+	indices[0] = 0;
+	indices[2] = 0;
+	for (i = 1; i < DTX_HIST_SIZE; i++)
+	{
+		if (L_sub(st->sumD[i], summax) > 0)
+		{
+			indices[0] = i;
+			summax = st->sumD[i];
+		}
+		if (L_sub(st->sumD[i], summin) < 0)
+		{
+			indices[2] = i;
+			summin = st->sumD[i];
+		}
+	}
+
+	/* Find the second largest distance */
+	summax2nd = -2147483647L;
+	indices[1] = -1;
+	for (i = 0; i < DTX_HIST_SIZE; i++)
+	{
+		if ((L_sub(st->sumD[i], summax2nd) > 0) && (sub(i, indices[0]) != 0))
+		{
+			indices[1] = i;
+			summax2nd = st->sumD[i];
+		}
+	}
+
+	for (i = 0; i < 3; i++)
+	{
+		indices[i] = sub(st->hist_ptr, indices[i]);
+		if (indices[i] < 0)
+		{
+			indices[i] = add(indices[i], DTX_HIST_SIZE);
+		}
+	}
+
+	/* If maximum distance/MED_THRESH is smaller than minimum distance */
+	/* then the median ISF vector replacement is not performed         */
+	tmp = norm_l(summax);
+	summax = (summax << tmp);
+	summin = (summin << tmp);
+	L_tmp = L_mult(voround(summax), INV_MED_THRESH);
+	if(L_tmp <= summin)
+	{
+		indices[0] = -1;
+	}
+	/* If second largest distance/MED_THRESH is smaller than     */
+	/* minimum distance then the median ISF vector replacement is    */
+	/* not performed                                                 */
+	summax2nd = L_shl(summax2nd, tmp);
+	L_tmp = L_mult(voround(summax2nd), INV_MED_THRESH);
+	if(L_tmp <= summin)
+	{
+		indices[1] = -1;
+	}
+	return;
+}
+
+static Word16 dithering_control(
+		dtx_encState * st
+		)
+{
+	Word16 tmp, mean, CN_dith, gain_diff;
+	Word32 i, ISF_diff;
+
+	/* determine how stationary the spectrum of background noise is */
+	ISF_diff = 0;
+	for (i = 0; i < 8; i++)
+	{
+		ISF_diff = L_add(ISF_diff, st->sumD[i]);
+	}
+	if ((ISF_diff >> 26) > 0)
+	{
+		CN_dith = 1;
+	} else
+	{
+		CN_dith = 0;
+	}
+
+	/* determine how stationary the energy of background noise is */
+	mean = 0;
+	for (i = 0; i < DTX_HIST_SIZE; i++)
+	{
+		mean = add(mean, st->log_en_hist[i]);
+	}
+	mean = (mean >> 3);
+	gain_diff = 0;
+	for (i = 0; i < DTX_HIST_SIZE; i++)
+	{
+		tmp = abs_s(sub(st->log_en_hist[i], mean));
+		gain_diff = add(gain_diff, tmp);
+	}
+	if (gain_diff > GAIN_THR)
+	{
+		CN_dith = 1;
+	}
+	return CN_dith;
+}
diff --git a/media/libstagefright/codecs/amrwbenc/src/g_pitch.c b/media/libstagefright/codecs/amrwbenc/src/g_pitch.c
index 570138e..d681f2e 100644
--- a/media/libstagefright/codecs/amrwbenc/src/g_pitch.c
+++ b/media/libstagefright/codecs/amrwbenc/src/g_pitch.c
@@ -1,79 +1,79 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*      File: g_pitch.c                                                 *

-*                                                                      *

-*	   Description:Compute the gain of pitch. Result in Q12        *

-*	               if(gain < 0) gain = 0                           *

-*				   if(gain > 1.2) gain = 1.2           *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "math_op.h"

-

-Word16 G_pitch(                            /* (o) Q14 : Gain of pitch lag saturated to 1.2   */

-		Word16 xn[],                          /* (i)     : Pitch target.                        */

-		Word16 y1[],                          /* (i)     : filtered adaptive codebook.          */

-		Word16 g_coeff[],                     /* : Correlations need for gain quantization.     */

-		Word16 L_subfr                        /* : Length of subframe.                          */

-	      )

-{

-	Word32 i;

-	Word16 xy, yy, exp_xy, exp_yy, gain;

-	/* Compute scalar product <y1[],y1[]> */

-#ifdef ASM_OPT                  /* asm optimization branch */

-	/* Compute scalar product <xn[],y1[]> */

-	xy = extract_h(Dot_product12_asm(xn, y1, L_subfr, &exp_xy));

-	yy = extract_h(Dot_product12_asm(y1, y1, L_subfr, &exp_yy));

-

-#else

-	/* Compute scalar product <xn[],y1[]> */

-	xy = extract_h(Dot_product12(xn, y1, L_subfr, &exp_xy));

-	yy = extract_h(Dot_product12(y1, y1, L_subfr, &exp_yy));

-

-#endif

-

-	g_coeff[0] = yy;                       

-	g_coeff[1] = exp_yy;                   

-	g_coeff[2] = xy;                       

-	g_coeff[3] = exp_xy;                   

-

-	/* If (xy < 0) gain = 0 */

-	if (xy < 0)

-		return ((Word16) 0);

-

-	/* compute gain = xy/yy */

-

-	xy >>= 1;                       /* Be sure xy < yy */

-	gain = div_s(xy, yy);

-

-	i = exp_xy;

-	i -= exp_yy;

-

-	gain = shl(gain, i);                   

-

-	/* if (gain > 1.2) gain = 1.2  in Q14 */

-	if(gain > 19661)

-	{

-		gain = 19661;                      

-	}

-	return (gain);

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*      File: g_pitch.c                                                 *
+*                                                                      *
+*	   Description:Compute the gain of pitch. Result in Q12        *
+*	               if(gain < 0) gain = 0                           *
+*				   if(gain > 1.2) gain = 1.2           *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "math_op.h"
+
+Word16 G_pitch(                            /* (o) Q14 : Gain of pitch lag saturated to 1.2   */
+		Word16 xn[],                          /* (i)     : Pitch target.                        */
+		Word16 y1[],                          /* (i)     : filtered adaptive codebook.          */
+		Word16 g_coeff[],                     /* : Correlations need for gain quantization.     */
+		Word16 L_subfr                        /* : Length of subframe.                          */
+	      )
+{
+	Word32 i;
+	Word16 xy, yy, exp_xy, exp_yy, gain;
+	/* Compute scalar product <y1[],y1[]> */
+#ifdef ASM_OPT                  /* asm optimization branch */
+	/* Compute scalar product <xn[],y1[]> */
+	xy = extract_h(Dot_product12_asm(xn, y1, L_subfr, &exp_xy));
+	yy = extract_h(Dot_product12_asm(y1, y1, L_subfr, &exp_yy));
+
+#else
+	/* Compute scalar product <xn[],y1[]> */
+	xy = extract_h(Dot_product12(xn, y1, L_subfr, &exp_xy));
+	yy = extract_h(Dot_product12(y1, y1, L_subfr, &exp_yy));
+
+#endif
+
+	g_coeff[0] = yy;
+	g_coeff[1] = exp_yy;
+	g_coeff[2] = xy;
+	g_coeff[3] = exp_xy;
+
+	/* If (xy < 0) gain = 0 */
+	if (xy < 0)
+		return ((Word16) 0);
+
+	/* compute gain = xy/yy */
+
+	xy >>= 1;                       /* Be sure xy < yy */
+	gain = div_s(xy, yy);
+
+	i = exp_xy;
+	i -= exp_yy;
+
+	gain = shl(gain, i);
+
+	/* if (gain > 1.2) gain = 1.2  in Q14 */
+	if(gain > 19661)
+	{
+		gain = 19661;
+	}
+	return (gain);
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/gpclip.c b/media/libstagefright/codecs/amrwbenc/src/gpclip.c
index e23f2f4..800b3f9 100644
--- a/media/libstagefright/codecs/amrwbenc/src/gpclip.c
+++ b/media/libstagefright/codecs/amrwbenc/src/gpclip.c
@@ -1,110 +1,110 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/**************************************************************************

-*      File: gpclip.c                                                     *

-*                                                                         *

-*      Description:To avoid unstable synthesis on frame erasure, the gain *

-*      need to be limited(gain pitch < 1.0) when the following            *

-*      case occurs                                                        *

-*      a resonance on LPC filter(lp_disp < 60Hz)                          *

-*      a good pitch prediction (lp_gp > 0.95)                             *

-*                                                                         *   

-***************************************************************************/

-#include "typedef.h"

-#include "basic_op.h"

-

-#define DIST_ISF_MAX    307                /* 120 Hz (6400Hz=16384) */

-#define DIST_ISF_THRES  154                /* 60     (6400Hz=16384) */

-#define GAIN_PIT_THRES  14746              /* 0.9 in Q14 */

-#define GAIN_PIT_MIN    9830               /* 0.6 in Q14 */

-#define M               16

-

-

-void Init_gp_clip(

-		Word16 mem[]                          /* (o) : memory of gain of pitch clipping algorithm */

-		)

-{

-	mem[0] = DIST_ISF_MAX;                 

-	mem[1] = GAIN_PIT_MIN;                 

-}

-

-

-Word16 Gp_clip(

-		Word16 mem[]                          /* (i/o) : memory of gain of pitch clipping algorithm */

-	      )

-{

-	Word16 clip = 0;

-	if ((mem[0] < DIST_ISF_THRES) && (mem[1] > GAIN_PIT_THRES))

-		clip = 1;                          

-

-	return (clip);

-}

-

-

-void Gp_clip_test_isf(

-		Word16 isf[],                         /* (i)   : isf values (in frequency domain)           */

-		Word16 mem[]                          /* (i/o) : memory of gain of pitch clipping algorithm */

-		)

-{

-	Word16 dist, dist_min;

-	Word32 i;

-

-	dist_min = vo_sub(isf[1], isf[0]);

-

-	for (i = 2; i < M - 1; i++)

-	{

-		dist = vo_sub(isf[i], isf[i - 1]);

-		if(dist < dist_min)

-		{

-			dist_min = dist;               

-		}

-	}

-

-	dist = extract_h(L_mac(vo_L_mult(26214, mem[0]), 6554, dist_min));

-

-	if (dist > DIST_ISF_MAX)

-	{

-		dist = DIST_ISF_MAX;               

-	}

-	mem[0] = dist;                        

-

-	return;

-}

-

-

-void Gp_clip_test_gain_pit(

-		Word16 gain_pit,                      /* (i) Q14 : gain of quantized pitch                    */

-		Word16 mem[]                          /* (i/o)   : memory of gain of pitch clipping algorithm */

-		)

-{

-	Word16 gain;

-	Word32 L_tmp;

-	L_tmp = (29491 * mem[1])<<1;

-	L_tmp += (3277 * gain_pit)<<1;

-

-	gain = extract_h(L_tmp);

-

-	if(gain < GAIN_PIT_MIN)

-	{

-		gain = GAIN_PIT_MIN;              

-	}

-	mem[1] = gain;                         

-	return;

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/**************************************************************************
+*      File: gpclip.c                                                     *
+*                                                                         *
+*      Description:To avoid unstable synthesis on frame erasure, the gain *
+*      need to be limited(gain pitch < 1.0) when the following            *
+*      case occurs                                                        *
+*      a resonance on LPC filter(lp_disp < 60Hz)                          *
+*      a good pitch prediction (lp_gp > 0.95)                             *
+*                                                                         *
+***************************************************************************/
+#include "typedef.h"
+#include "basic_op.h"
+
+#define DIST_ISF_MAX    307                /* 120 Hz (6400Hz=16384) */
+#define DIST_ISF_THRES  154                /* 60     (6400Hz=16384) */
+#define GAIN_PIT_THRES  14746              /* 0.9 in Q14 */
+#define GAIN_PIT_MIN    9830               /* 0.6 in Q14 */
+#define M               16
+
+
+void Init_gp_clip(
+		Word16 mem[]                          /* (o) : memory of gain of pitch clipping algorithm */
+		)
+{
+	mem[0] = DIST_ISF_MAX;
+	mem[1] = GAIN_PIT_MIN;
+}
+
+
+Word16 Gp_clip(
+		Word16 mem[]                          /* (i/o) : memory of gain of pitch clipping algorithm */
+	      )
+{
+	Word16 clip = 0;
+	if ((mem[0] < DIST_ISF_THRES) && (mem[1] > GAIN_PIT_THRES))
+		clip = 1;
+
+	return (clip);
+}
+
+
+void Gp_clip_test_isf(
+		Word16 isf[],                         /* (i)   : isf values (in frequency domain)           */
+		Word16 mem[]                          /* (i/o) : memory of gain of pitch clipping algorithm */
+		)
+{
+	Word16 dist, dist_min;
+	Word32 i;
+
+	dist_min = vo_sub(isf[1], isf[0]);
+
+	for (i = 2; i < M - 1; i++)
+	{
+		dist = vo_sub(isf[i], isf[i - 1]);
+		if(dist < dist_min)
+		{
+			dist_min = dist;
+		}
+	}
+
+	dist = extract_h(L_mac(vo_L_mult(26214, mem[0]), 6554, dist_min));
+
+	if (dist > DIST_ISF_MAX)
+	{
+		dist = DIST_ISF_MAX;
+	}
+	mem[0] = dist;
+
+	return;
+}
+
+
+void Gp_clip_test_gain_pit(
+		Word16 gain_pit,                      /* (i) Q14 : gain of quantized pitch                    */
+		Word16 mem[]                          /* (i/o)   : memory of gain of pitch clipping algorithm */
+		)
+{
+	Word16 gain;
+	Word32 L_tmp;
+	L_tmp = (29491 * mem[1])<<1;
+	L_tmp += (3277 * gain_pit)<<1;
+
+	gain = extract_h(L_tmp);
+
+	if(gain < GAIN_PIT_MIN)
+	{
+		gain = GAIN_PIT_MIN;
+	}
+	mem[1] = gain;
+	return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/homing.c b/media/libstagefright/codecs/amrwbenc/src/homing.c
index 015633f..565040f 100644
--- a/media/libstagefright/codecs/amrwbenc/src/homing.c
+++ b/media/libstagefright/codecs/amrwbenc/src/homing.c
@@ -1,46 +1,46 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*       File: homing.c                                                 *

-*                                                                      *

-*       Description:Performs the homing routines                       *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "cnst.h"

-#include "basic_op.h"

-#include "bits.h"

-#include "homing.tab"

-

-Word16 encoder_homing_frame_test(Word16 input_frame[])

-{

-	Word32 i;

-	Word16 j = 0;

-

-	/* check 320 input samples for matching EHF_MASK: defined in e_homing.h */

-	for (i = 0; i < L_FRAME16k; i++)

-	{

-		j = (Word16) (input_frame[i] ^ EHF_MASK);

-

-		if (j)

-			break;

-	}

-

-	return (Word16) (!j);

-}

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*       File: homing.c                                                 *
+*                                                                      *
+*       Description:Performs the homing routines                       *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "cnst.h"
+#include "basic_op.h"
+#include "bits.h"
+#include "homing.tab"
+
+Word16 encoder_homing_frame_test(Word16 input_frame[])
+{
+	Word32 i;
+	Word16 j = 0;
+
+	/* check 320 input samples for matching EHF_MASK: defined in e_homing.h */
+	for (i = 0; i < L_FRAME16k; i++)
+	{
+		j = (Word16) (input_frame[i] ^ EHF_MASK);
+
+		if (j)
+			break;
+	}
+
+	return (Word16) (!j);
+}
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/hp400.c b/media/libstagefright/codecs/amrwbenc/src/hp400.c
index 463a53a..a6f9701 100644
--- a/media/libstagefright/codecs/amrwbenc/src/hp400.c
+++ b/media/libstagefright/codecs/amrwbenc/src/hp400.c
@@ -1,106 +1,106 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*      File: hp400.c                                                    *

-*                                                                       *

-*      Description:                                                     *

-* 2nd order high pass filter with cut off frequency at 400 Hz.          *

-* Designed with cheby2 function in MATLAB.                              *

-* Optimized for fixed-point to get the following frequency response:    *

-*                                                                       *

-*  frequency:     0Hz   100Hz  200Hz  300Hz  400Hz  630Hz  1.5kHz  3kHz *

-*  dB loss:     -infdB  -30dB  -20dB  -10dB  -3dB   +6dB    +1dB    0dB *

-*                                                                       *

-* Algorithm:                                                            *

-*                                                                       *

-*  y[i] = b[0]*x[i] + b[1]*x[i-1] + b[2]*x[i-2]                         *

-*                   + a[1]*y[i-1] + a[2]*y[i-2];                        *

-*                                                                       *

-*  Word16 b[3] = {3660, -7320,  3660};       in Q12                     *

-*  Word16 a[3] = {4096,  7320, -3540};       in Q12                     *

-*                                                                       *

-*  float -->   b[3] = {0.893554687, -1.787109375,  0.893554687};        *

-*              a[3] = {1.000000000,  1.787109375, -0.864257812};        *

-*                                                                       *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "oper_32b.h"

-#include "acelp.h"

-

-/* filter coefficients  */

-static Word16 b[3] = {915, -1830, 915};         /* Q12 (/4) */

-static Word16 a[3] = {16384, 29280, -14160};    /* Q12 (x4) */

-/* Initialization of static values */

-

-void Init_HP400_12k8(Word16 mem[])

-{

-	Set_zero(mem, 6);

-}

-

-

-void HP400_12k8(

-		Word16 signal[],                      /* input signal / output is divided by 16 */

-		Word16 lg,                            /* lenght of signal    */

-		Word16 mem[]                          /* filter memory [6]   */

-	       )

-{

-	Word16  x2;

-	Word16 y2_hi, y2_lo, y1_hi, y1_lo, x0, x1;

-	Word32 L_tmp;

-	Word32 num;

-	y2_hi = *mem++;

-	y2_lo = *mem++;

-	y1_hi = *mem++;

-	y1_lo = *mem++;

-	x0 = *mem++;   

-	x1 = *mem;   

-	num = (Word32)lg;

-	do

-	{

-		x2 = x1;

-		x1 = x0;

-		x0 = *signal;

-		/* y[i] = b[0]*x[i] + b[1]*x[i-1] + b140[2]*x[i-2]  */

-		/* + a[1]*y[i-1] + a[2] * y[i-2];  */

-		L_tmp = 8192L;                    /* rounding to maximise precision */

-		L_tmp += y1_lo * a[1];

-		L_tmp += y2_lo * a[2];

-		L_tmp = L_tmp >> 14;

-		L_tmp += (y1_hi * a[1] + y2_hi * a[2] + (x0 + x2)* b[0] + x1 * b[1]) << 1;

-		L_tmp <<= 1;           /* coeff Q12 --> Q13 */

-		y2_hi = y1_hi;

-		y2_lo = y1_lo;

-		y1_hi = (Word16)(L_tmp>>16);

-		y1_lo = (Word16)((L_tmp & 0xffff)>>1);

-

-		/* signal is divided by 16 to avoid overflow in energy computation */

-		*signal++ = (L_tmp + 0x8000) >> 16;

-	}while(--num !=0);

-

-	*mem-- = x1;

-	*mem-- = x0;

-	*mem-- = y1_lo;

-	*mem-- = y1_hi;

-	*mem-- = y2_lo;

-	*mem   = y2_hi;  

-	return;

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*      File: hp400.c                                                    *
+*                                                                       *
+*      Description:                                                     *
+* 2nd order high pass filter with cut off frequency at 400 Hz.          *
+* Designed with cheby2 function in MATLAB.                              *
+* Optimized for fixed-point to get the following frequency response:    *
+*                                                                       *
+*  frequency:     0Hz   100Hz  200Hz  300Hz  400Hz  630Hz  1.5kHz  3kHz *
+*  dB loss:     -infdB  -30dB  -20dB  -10dB  -3dB   +6dB    +1dB    0dB *
+*                                                                       *
+* Algorithm:                                                            *
+*                                                                       *
+*  y[i] = b[0]*x[i] + b[1]*x[i-1] + b[2]*x[i-2]                         *
+*                   + a[1]*y[i-1] + a[2]*y[i-2];                        *
+*                                                                       *
+*  Word16 b[3] = {3660, -7320,  3660};       in Q12                     *
+*  Word16 a[3] = {4096,  7320, -3540};       in Q12                     *
+*                                                                       *
+*  float -->   b[3] = {0.893554687, -1.787109375,  0.893554687};        *
+*              a[3] = {1.000000000,  1.787109375, -0.864257812};        *
+*                                                                       *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "oper_32b.h"
+#include "acelp.h"
+
+/* filter coefficients  */
+static Word16 b[3] = {915, -1830, 915};         /* Q12 (/4) */
+static Word16 a[3] = {16384, 29280, -14160};    /* Q12 (x4) */
+/* Initialization of static values */
+
+void Init_HP400_12k8(Word16 mem[])
+{
+	Set_zero(mem, 6);
+}
+
+
+void HP400_12k8(
+		Word16 signal[],                      /* input signal / output is divided by 16 */
+		Word16 lg,                            /* lenght of signal    */
+		Word16 mem[]                          /* filter memory [6]   */
+	       )
+{
+	Word16  x2;
+	Word16 y2_hi, y2_lo, y1_hi, y1_lo, x0, x1;
+	Word32 L_tmp;
+	Word32 num;
+	y2_hi = *mem++;
+	y2_lo = *mem++;
+	y1_hi = *mem++;
+	y1_lo = *mem++;
+	x0 = *mem++;
+	x1 = *mem;
+	num = (Word32)lg;
+	do
+	{
+		x2 = x1;
+		x1 = x0;
+		x0 = *signal;
+		/* y[i] = b[0]*x[i] + b[1]*x[i-1] + b140[2]*x[i-2]  */
+		/* + a[1]*y[i-1] + a[2] * y[i-2];  */
+		L_tmp = 8192L;                    /* rounding to maximise precision */
+		L_tmp += y1_lo * a[1];
+		L_tmp += y2_lo * a[2];
+		L_tmp = L_tmp >> 14;
+		L_tmp += (y1_hi * a[1] + y2_hi * a[2] + (x0 + x2)* b[0] + x1 * b[1]) << 1;
+		L_tmp <<= 1;           /* coeff Q12 --> Q13 */
+		y2_hi = y1_hi;
+		y2_lo = y1_lo;
+		y1_hi = (Word16)(L_tmp>>16);
+		y1_lo = (Word16)((L_tmp & 0xffff)>>1);
+
+		/* signal is divided by 16 to avoid overflow in energy computation */
+		*signal++ = (L_tmp + 0x8000) >> 16;
+	}while(--num !=0);
+
+	*mem-- = x1;
+	*mem-- = x0;
+	*mem-- = y1_lo;
+	*mem-- = y1_hi;
+	*mem-- = y2_lo;
+	*mem   = y2_hi;
+	return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/hp50.c b/media/libstagefright/codecs/amrwbenc/src/hp50.c
index 53e3d7b..c1c7b83 100644
--- a/media/libstagefright/codecs/amrwbenc/src/hp50.c
+++ b/media/libstagefright/codecs/amrwbenc/src/hp50.c
@@ -1,106 +1,106 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*      File: hp50.c                                                     *

-*                                                                       *

-*	   Description:                                                 *

-* 2nd order high pass filter with cut off frequency at 31 Hz.           *

-* Designed with cheby2 function in MATLAB.                              *

-* Optimized for fixed-point to get the following frequency response:    *

-*                                                                       *

-*  frequency:     0Hz    14Hz  24Hz   31Hz   37Hz   41Hz   47Hz         *

-*  dB loss:     -infdB  -15dB  -6dB   -3dB  -1.5dB  -1dB  -0.5dB        *

-*                                                                       *

-* Algorithm:                                                            *

-*                                                                       *

-*  y[i] = b[0]*x[i] + b[1]*x[i-1] + b[2]*x[i-2]                         *

-*                   + a[1]*y[i-1] + a[2]*y[i-2];                        *

-*                                                                       *

-*  Word16 b[3] = {4053, -8106, 4053};       in Q12                      *

-*  Word16 a[3] = {8192, 16211, -8021};       in Q12                     *

-*                                                                       *

-*  float -->   b[3] = {0.989501953, -1.979003906,  0.989501953};        *

-*              a[3] = {1.000000000,  1.978881836, -0.979125977};        *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "oper_32b.h"

-#include "cnst.h"

-#include "acelp.h"

-

-/* filter coefficients  */

-static Word16 b[3] = {4053, -8106, 4053};  /* Q12 */

-static Word16 a[3] = {8192, 16211, -8021}; /* Q12 (x2) */

-

-/* Initialization of static values */

-

-void Init_HP50_12k8(Word16 mem[])

-{

-	Set_zero(mem, 6);

-}

-

-

-void HP50_12k8(

-		Word16 signal[],                      /* input/output signal */

-		Word16 lg,                            /* lenght of signal    */

-		Word16 mem[]                          /* filter memory [6]   */

-	      )

-{

-	Word16 x2;

-	Word16 y2_hi, y2_lo, y1_hi, y1_lo, x0, x1;

-	Word32 L_tmp;

-	Word32 num;

-

-	y2_hi = *mem++;

-	y2_lo = *mem++;

-	y1_hi = *mem++;

-	y1_lo = *mem++;

-	x0 = *mem++;   

-	x1 = *mem;

-	num = (Word32)lg;

-	do

-	{

-		x2 = x1;

-		x1 = x0;

-		x0 = *signal;

-		/* y[i] = b[0]*x[i] + b[1]*x[i-1] + b140[2]*x[i-2]  */

-		/* + a[1]*y[i-1] + a[2] * y[i-2];  */

-		L_tmp = 8192 ;                    /* rounding to maximise precision */

-		L_tmp += y1_lo * a[1];

-		L_tmp += y2_lo * a[2];

-		L_tmp = L_tmp >> 14;

-		L_tmp += (y1_hi * a[1] + y2_hi * a[2] + (x0 + x2) * b[0] + x1 * b[1]) << 1;

-		L_tmp <<= 2;           /* coeff Q12 --> Q13 */

-		y2_hi = y1_hi;

-		y2_lo = y1_lo;

-		y1_hi = (Word16)(L_tmp>>16);

-		y1_lo = (Word16)((L_tmp & 0xffff)>>1);

-		*signal++ = extract_h((L_add((L_tmp<<1), 0x8000)));

-	}while(--num !=0);

-

-	*mem-- = x1;

-	*mem-- = x0;

-	*mem-- = y1_lo;

-	*mem-- = y1_hi;

-	*mem-- = y2_lo;

-	*mem-- = y2_hi;  

-

-	return;

-}

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*      File: hp50.c                                                     *
+*                                                                       *
+*	   Description:                                                 *
+* 2nd order high pass filter with cut off frequency at 31 Hz.           *
+* Designed with cheby2 function in MATLAB.                              *
+* Optimized for fixed-point to get the following frequency response:    *
+*                                                                       *
+*  frequency:     0Hz    14Hz  24Hz   31Hz   37Hz   41Hz   47Hz         *
+*  dB loss:     -infdB  -15dB  -6dB   -3dB  -1.5dB  -1dB  -0.5dB        *
+*                                                                       *
+* Algorithm:                                                            *
+*                                                                       *
+*  y[i] = b[0]*x[i] + b[1]*x[i-1] + b[2]*x[i-2]                         *
+*                   + a[1]*y[i-1] + a[2]*y[i-2];                        *
+*                                                                       *
+*  Word16 b[3] = {4053, -8106, 4053};       in Q12                      *
+*  Word16 a[3] = {8192, 16211, -8021};       in Q12                     *
+*                                                                       *
+*  float -->   b[3] = {0.989501953, -1.979003906,  0.989501953};        *
+*              a[3] = {1.000000000,  1.978881836, -0.979125977};        *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "oper_32b.h"
+#include "cnst.h"
+#include "acelp.h"
+
+/* filter coefficients  */
+static Word16 b[3] = {4053, -8106, 4053};  /* Q12 */
+static Word16 a[3] = {8192, 16211, -8021}; /* Q12 (x2) */
+
+/* Initialization of static values */
+
+void Init_HP50_12k8(Word16 mem[])
+{
+	Set_zero(mem, 6);
+}
+
+
+void HP50_12k8(
+		Word16 signal[],                      /* input/output signal */
+		Word16 lg,                            /* lenght of signal    */
+		Word16 mem[]                          /* filter memory [6]   */
+	      )
+{
+	Word16 x2;
+	Word16 y2_hi, y2_lo, y1_hi, y1_lo, x0, x1;
+	Word32 L_tmp;
+	Word32 num;
+
+	y2_hi = *mem++;
+	y2_lo = *mem++;
+	y1_hi = *mem++;
+	y1_lo = *mem++;
+	x0 = *mem++;
+	x1 = *mem;
+	num = (Word32)lg;
+	do
+	{
+		x2 = x1;
+		x1 = x0;
+		x0 = *signal;
+		/* y[i] = b[0]*x[i] + b[1]*x[i-1] + b140[2]*x[i-2]  */
+		/* + a[1]*y[i-1] + a[2] * y[i-2];  */
+		L_tmp = 8192 ;                    /* rounding to maximise precision */
+		L_tmp += y1_lo * a[1];
+		L_tmp += y2_lo * a[2];
+		L_tmp = L_tmp >> 14;
+		L_tmp += (y1_hi * a[1] + y2_hi * a[2] + (x0 + x2) * b[0] + x1 * b[1]) << 1;
+		L_tmp <<= 2;           /* coeff Q12 --> Q13 */
+		y2_hi = y1_hi;
+		y2_lo = y1_lo;
+		y1_hi = (Word16)(L_tmp>>16);
+		y1_lo = (Word16)((L_tmp & 0xffff)>>1);
+		*signal++ = extract_h((L_add((L_tmp<<1), 0x8000)));
+	}while(--num !=0);
+
+	*mem-- = x1;
+	*mem-- = x0;
+	*mem-- = y1_lo;
+	*mem-- = y1_hi;
+	*mem-- = y2_lo;
+	*mem-- = y2_hi;
+
+	return;
+}
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/hp6k.c b/media/libstagefright/codecs/amrwbenc/src/hp6k.c
index 5ee5b20..8e66eb0 100644
--- a/media/libstagefright/codecs/amrwbenc/src/hp6k.c
+++ b/media/libstagefright/codecs/amrwbenc/src/hp6k.c
@@ -1,93 +1,93 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*       File: hp6k.c                                                    *

-*                                                                       *

-*	Description:15th order band pass 6kHz to 7kHz FIR filter        *

-*       frequency: 4kHz   5kHz  5.5kHz  6kHz  6.5kHz  7kHz 7.5kHz 8kHz  *

-*	dB loss:  -60dB  -45dB  -13dB   -3dB   0dB    -3dB -13dB  -45dB *

-*	                                                                *                                                                 

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "acelp.h"

-#include "cnst.h"

-

-#define L_FIR 31

-

-/* filter coefficients (gain=4.0) */

-

-Word16 fir_6k_7k[L_FIR] =

-{

-	-32, 47, 32, -27, -369,

-	1122, -1421, 0, 3798, -8880,

-	12349, -10984, 3548, 7766, -18001,

-	22118, -18001, 7766, 3548, -10984,

-	12349, -8880, 3798, 0, -1421,

-	1122, -369, -27, 32, 47,

-	-32

-};

-

-

-void Init_Filt_6k_7k(Word16 mem[])         /* mem[30] */

-{

-	Set_zero(mem, L_FIR - 1);

-	return;

-}

-

-void Filt_6k_7k(

-		Word16 signal[],                      /* input:  signal                  */

-		Word16 lg,                            /* input:  length of input         */

-		Word16 mem[]                          /* in/out: memory (size=30)        */

-	       )

-{

-	Word16 x[L_SUBFR16k + (L_FIR - 1)];

-	Word32 i, L_tmp;

-

-	Copy(mem, x, L_FIR - 1);

-	for (i = lg - 1; i >= 0; i--)

-	{

-		x[i + L_FIR - 1] = signal[i] >> 2;                         /* gain of filter = 4 */

-	}	

-	for (i = 0; i < lg; i++)

-	{

-		L_tmp =  (x[i] + x[i+ 30]) * fir_6k_7k[0];

-		L_tmp += (x[i+1] + x[i + 29]) * fir_6k_7k[1];

-		L_tmp += (x[i+2] + x[i + 28]) * fir_6k_7k[2];

-		L_tmp += (x[i+3] + x[i + 27]) * fir_6k_7k[3];

-		L_tmp += (x[i+4] + x[i + 26]) * fir_6k_7k[4];

-		L_tmp += (x[i+5] + x[i + 25]) * fir_6k_7k[5];

-		L_tmp += (x[i+6] + x[i + 24]) * fir_6k_7k[6];

-		L_tmp += (x[i+7] + x[i + 23]) * fir_6k_7k[7];

-		L_tmp += (x[i+8] + x[i + 22]) * fir_6k_7k[8];

-		L_tmp += (x[i+9] + x[i + 21]) * fir_6k_7k[9];

-		L_tmp += (x[i+10] + x[i + 20]) * fir_6k_7k[10];

-		L_tmp += (x[i+11] + x[i + 19]) * fir_6k_7k[11];

-		L_tmp += (x[i+12] + x[i + 18]) * fir_6k_7k[12];

-		L_tmp += (x[i+13] + x[i + 17]) * fir_6k_7k[13];

-		L_tmp += (x[i+14] + x[i + 16]) * fir_6k_7k[14];

-		L_tmp += (x[i+15]) * fir_6k_7k[15];

-		signal[i] = (L_tmp + 0x4000) >> 15;

-	}

-

-	Copy(x + lg, mem, L_FIR - 1);

-

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*       File: hp6k.c                                                    *
+*                                                                       *
+*	Description:15th order band pass 6kHz to 7kHz FIR filter        *
+*       frequency: 4kHz   5kHz  5.5kHz  6kHz  6.5kHz  7kHz 7.5kHz 8kHz  *
+*	dB loss:  -60dB  -45dB  -13dB   -3dB   0dB    -3dB -13dB  -45dB *
+*	                                                                *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "acelp.h"
+#include "cnst.h"
+
+#define L_FIR 31
+
+/* filter coefficients (gain=4.0) */
+
+Word16 fir_6k_7k[L_FIR] =
+{
+	-32, 47, 32, -27, -369,
+	1122, -1421, 0, 3798, -8880,
+	12349, -10984, 3548, 7766, -18001,
+	22118, -18001, 7766, 3548, -10984,
+	12349, -8880, 3798, 0, -1421,
+	1122, -369, -27, 32, 47,
+	-32
+};
+
+
+void Init_Filt_6k_7k(Word16 mem[])         /* mem[30] */
+{
+	Set_zero(mem, L_FIR - 1);
+	return;
+}
+
+void Filt_6k_7k(
+		Word16 signal[],                      /* input:  signal                  */
+		Word16 lg,                            /* input:  length of input         */
+		Word16 mem[]                          /* in/out: memory (size=30)        */
+	       )
+{
+	Word16 x[L_SUBFR16k + (L_FIR - 1)];
+	Word32 i, L_tmp;
+
+	Copy(mem, x, L_FIR - 1);
+	for (i = lg - 1; i >= 0; i--)
+	{
+		x[i + L_FIR - 1] = signal[i] >> 2;                         /* gain of filter = 4 */
+	}
+	for (i = 0; i < lg; i++)
+	{
+		L_tmp =  (x[i] + x[i+ 30]) * fir_6k_7k[0];
+		L_tmp += (x[i+1] + x[i + 29]) * fir_6k_7k[1];
+		L_tmp += (x[i+2] + x[i + 28]) * fir_6k_7k[2];
+		L_tmp += (x[i+3] + x[i + 27]) * fir_6k_7k[3];
+		L_tmp += (x[i+4] + x[i + 26]) * fir_6k_7k[4];
+		L_tmp += (x[i+5] + x[i + 25]) * fir_6k_7k[5];
+		L_tmp += (x[i+6] + x[i + 24]) * fir_6k_7k[6];
+		L_tmp += (x[i+7] + x[i + 23]) * fir_6k_7k[7];
+		L_tmp += (x[i+8] + x[i + 22]) * fir_6k_7k[8];
+		L_tmp += (x[i+9] + x[i + 21]) * fir_6k_7k[9];
+		L_tmp += (x[i+10] + x[i + 20]) * fir_6k_7k[10];
+		L_tmp += (x[i+11] + x[i + 19]) * fir_6k_7k[11];
+		L_tmp += (x[i+12] + x[i + 18]) * fir_6k_7k[12];
+		L_tmp += (x[i+13] + x[i + 17]) * fir_6k_7k[13];
+		L_tmp += (x[i+14] + x[i + 16]) * fir_6k_7k[14];
+		L_tmp += (x[i+15]) * fir_6k_7k[15];
+		signal[i] = (L_tmp + 0x4000) >> 15;
+	}
+
+	Copy(x + lg, mem, L_FIR - 1);
+
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/hp_wsp.c b/media/libstagefright/codecs/amrwbenc/src/hp_wsp.c
index 7fb62a4..bc1ec49 100644
--- a/media/libstagefright/codecs/amrwbenc/src/hp_wsp.c
+++ b/media/libstagefright/codecs/amrwbenc/src/hp_wsp.c
@@ -1,148 +1,148 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*       File: hp_wsp.c                                                  *

-*       Description:                                                    *

-*       3nd order high pass filter with cut off frequency at 180Hz      *

-* Algorithm:                                                            *

-*                                                                       *

-*  y[i] = b[0]*x[i] + b[1]*x[i-1] + b[2]*x[i-2] + b[3]*x[i-3]           *

-*                   + a[1]*y[i-1] + a[2]*y[i-2] + a[3]*y[i-3];          *

-*                                                                       *

-* float a_coef[HP_ORDER]= {                                             *

-*    -2.64436711600664f,                                                *

-*    2.35087386625360f,                                                 *

-*   -0.70001156927424f};                                                *

-*                                                                       *

-* float b_coef[HP_ORDER+1]= {                                           *

-*     -0.83787057505665f,                                               *

-*    2.50975570071058f,                                                 *

-*   -2.50975570071058f,                                                 *

-*    0.83787057505665f};                                                *

-*                                                                       *

-*************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "oper_32b.h"

-#include "acelp.h"

-

-/* filter coefficients in Q12 */

-static Word16 a[4] = {8192, 21663, -19258, 5734};

-static Word16 b[4] = {-3432, +10280, -10280, +3432};

-

-/* Initialization of static values */

-void Init_Hp_wsp(Word16 mem[])

-{

-	Set_zero(mem, 9);

-

-	return;

-}

-

-void scale_mem_Hp_wsp(Word16 mem[], Word16 exp)

-{

-	Word32 i;

-	Word32 L_tmp;

-

-	for (i = 0; i < 6; i += 2)

-	{

-		L_tmp = ((mem[i] << 16) + (mem[i + 1]<<1));

-		L_tmp = L_shl(L_tmp, exp);

-		mem[i] = L_tmp >> 16;

-		mem[i + 1] = (L_tmp & 0xffff)>>1;

-	}

-

-	for (i = 6; i < 9; i++)

-	{

-		L_tmp = L_deposit_h(mem[i]);       /* x[i] */

-		L_tmp = L_shl(L_tmp, exp);

-		mem[i] = vo_round(L_tmp);

-	}

-

-	return;

-}

-

-

-void Hp_wsp(

-		Word16 wsp[],                         /* i   : wsp[]  signal       */

-		Word16 hp_wsp[],                      /* o   : hypass wsp[]        */

-		Word16 lg,                            /* i   : lenght of signal    */

-		Word16 mem[]                          /* i/o : filter memory [9]   */

-	   )

-{

-	Word16 x0, x1, x2, x3;

-	Word16 y3_hi, y3_lo, y2_hi, y2_lo, y1_hi, y1_lo;

-	Word32 i, L_tmp;

-

-	y3_hi = mem[0];                        

-	y3_lo = mem[1];                        

-	y2_hi = mem[2];                        

-	y2_lo = mem[3];                        

-	y1_hi = mem[4];                        

-	y1_lo = mem[5];                        

-	x0 = mem[6];                           

-	x1 = mem[7];                           

-	x2 = mem[8];                           

-

-	for (i = 0; i < lg; i++)

-	{

-		x3 = x2;                           

-		x2 = x1;                           

-		x1 = x0;                           

-		x0 = wsp[i];                       

-		/* y[i] = b[0]*x[i] + b[1]*x[i-1] + b140[2]*x[i-2] + b[3]*x[i-3]  */

-		/* + a[1]*y[i-1] + a[2] * y[i-2]  + a[3]*y[i-3]  */

-

-		L_tmp = 16384L;                    /* rounding to maximise precision */

-		L_tmp += (y1_lo * a[1])<<1;

-		L_tmp += (y2_lo * a[2])<<1;

-		L_tmp += (y3_lo * a[3])<<1;

-		L_tmp = L_tmp >> 15;

-		L_tmp += (y1_hi * a[1])<<1;

-		L_tmp += (y2_hi * a[2])<<1;

-		L_tmp += (y3_hi * a[3])<<1;

-		L_tmp += (x0 * b[0])<<1;

-		L_tmp += (x1 * b[1])<<1;

-		L_tmp += (x2 * b[2])<<1;

-		L_tmp += (x3 * b[3])<<1;

-

-		L_tmp = L_tmp << 2;

-

-		y3_hi = y2_hi;                     

-		y3_lo = y2_lo;                     

-		y2_hi = y1_hi;                     

-		y2_lo = y1_lo; 

-		y1_hi = L_tmp >> 16;

-		y1_lo = (L_tmp & 0xffff) >>1;

-

-		hp_wsp[i] = (L_tmp + 0x4000)>>15;          

-	}

-

-	mem[0] = y3_hi;                        

-	mem[1] = y3_lo;                        

-	mem[2] = y2_hi;                        

-	mem[3] = y2_lo;                        

-	mem[4] = y1_hi;                        

-	mem[5] = y1_lo;                        

-	mem[6] = x0;                           

-	mem[7] = x1;                           

-	mem[8] = x2;                           

-

-	return;

-}

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*       File: hp_wsp.c                                                  *
+*       Description:                                                    *
+*       3nd order high pass filter with cut off frequency at 180Hz      *
+* Algorithm:                                                            *
+*                                                                       *
+*  y[i] = b[0]*x[i] + b[1]*x[i-1] + b[2]*x[i-2] + b[3]*x[i-3]           *
+*                   + a[1]*y[i-1] + a[2]*y[i-2] + a[3]*y[i-3];          *
+*                                                                       *
+* float a_coef[HP_ORDER]= {                                             *
+*    -2.64436711600664f,                                                *
+*    2.35087386625360f,                                                 *
+*   -0.70001156927424f};                                                *
+*                                                                       *
+* float b_coef[HP_ORDER+1]= {                                           *
+*     -0.83787057505665f,                                               *
+*    2.50975570071058f,                                                 *
+*   -2.50975570071058f,                                                 *
+*    0.83787057505665f};                                                *
+*                                                                       *
+*************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "oper_32b.h"
+#include "acelp.h"
+
+/* filter coefficients in Q12 */
+static Word16 a[4] = {8192, 21663, -19258, 5734};
+static Word16 b[4] = {-3432, +10280, -10280, +3432};
+
+/* Initialization of static values */
+void Init_Hp_wsp(Word16 mem[])
+{
+	Set_zero(mem, 9);
+
+	return;
+}
+
+void scale_mem_Hp_wsp(Word16 mem[], Word16 exp)
+{
+	Word32 i;
+	Word32 L_tmp;
+
+	for (i = 0; i < 6; i += 2)
+	{
+		L_tmp = ((mem[i] << 16) + (mem[i + 1]<<1));
+		L_tmp = L_shl(L_tmp, exp);
+		mem[i] = L_tmp >> 16;
+		mem[i + 1] = (L_tmp & 0xffff)>>1;
+	}
+
+	for (i = 6; i < 9; i++)
+	{
+		L_tmp = L_deposit_h(mem[i]);       /* x[i] */
+		L_tmp = L_shl(L_tmp, exp);
+		mem[i] = vo_round(L_tmp);
+	}
+
+	return;
+}
+
+
+void Hp_wsp(
+		Word16 wsp[],                         /* i   : wsp[]  signal       */
+		Word16 hp_wsp[],                      /* o   : hypass wsp[]        */
+		Word16 lg,                            /* i   : lenght of signal    */
+		Word16 mem[]                          /* i/o : filter memory [9]   */
+	   )
+{
+	Word16 x0, x1, x2, x3;
+	Word16 y3_hi, y3_lo, y2_hi, y2_lo, y1_hi, y1_lo;
+	Word32 i, L_tmp;
+
+	y3_hi = mem[0];
+	y3_lo = mem[1];
+	y2_hi = mem[2];
+	y2_lo = mem[3];
+	y1_hi = mem[4];
+	y1_lo = mem[5];
+	x0 = mem[6];
+	x1 = mem[7];
+	x2 = mem[8];
+
+	for (i = 0; i < lg; i++)
+	{
+		x3 = x2;
+		x2 = x1;
+		x1 = x0;
+		x0 = wsp[i];
+		/* y[i] = b[0]*x[i] + b[1]*x[i-1] + b140[2]*x[i-2] + b[3]*x[i-3]  */
+		/* + a[1]*y[i-1] + a[2] * y[i-2]  + a[3]*y[i-3]  */
+
+		L_tmp = 16384L;                    /* rounding to maximise precision */
+		L_tmp += (y1_lo * a[1])<<1;
+		L_tmp += (y2_lo * a[2])<<1;
+		L_tmp += (y3_lo * a[3])<<1;
+		L_tmp = L_tmp >> 15;
+		L_tmp += (y1_hi * a[1])<<1;
+		L_tmp += (y2_hi * a[2])<<1;
+		L_tmp += (y3_hi * a[3])<<1;
+		L_tmp += (x0 * b[0])<<1;
+		L_tmp += (x1 * b[1])<<1;
+		L_tmp += (x2 * b[2])<<1;
+		L_tmp += (x3 * b[3])<<1;
+
+		L_tmp = L_tmp << 2;
+
+		y3_hi = y2_hi;
+		y3_lo = y2_lo;
+		y2_hi = y1_hi;
+		y2_lo = y1_lo;
+		y1_hi = L_tmp >> 16;
+		y1_lo = (L_tmp & 0xffff) >>1;
+
+		hp_wsp[i] = (L_tmp + 0x4000)>>15;
+	}
+
+	mem[0] = y3_hi;
+	mem[1] = y3_lo;
+	mem[2] = y2_hi;
+	mem[3] = y2_lo;
+	mem[4] = y1_hi;
+	mem[5] = y1_lo;
+	mem[6] = x0;
+	mem[7] = x1;
+	mem[8] = x2;
+
+	return;
+}
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/int_lpc.c b/media/libstagefright/codecs/amrwbenc/src/int_lpc.c
index be1fd0b..1119bc7 100644
--- a/media/libstagefright/codecs/amrwbenc/src/int_lpc.c
+++ b/media/libstagefright/codecs/amrwbenc/src/int_lpc.c
@@ -1,66 +1,66 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*      File: int_lpc.c                                                 *

-*                                                                      *

-*      Description:Interpolation of the LP parameters in 4 subframes.  *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "cnst.h"

-#include "acelp.h"

-

-#define MP1 (M+1)

-

-

-void Int_isp(

-		Word16 isp_old[],                     /* input : isps from past frame              */

-		Word16 isp_new[],                     /* input : isps from present frame           */

-		Word16 frac[],                        /* input : fraction for 3 first subfr (Q15)  */

-		Word16 Az[]                           /* output: LP coefficients in 4 subframes    */

-	    )

-{

-	Word32 i, k; 

-	Word16 fac_old, fac_new;

-	Word16 isp[M];

-	Word32 L_tmp;

-

-	for (k = 0; k < 3; k++)

-	{

-		fac_new = frac[k];                

-		fac_old = (32767 - fac_new) + 1;  /* 1.0 - fac_new */

-

-		for (i = 0; i < M; i++)

-		{

-			L_tmp = (isp_old[i] * fac_old)<<1;

-			L_tmp += (isp_new[i] * fac_new)<<1;

-			isp[i] = (L_tmp + 0x8000)>>16;        

-		}

-		Isp_Az(isp, Az, M, 0);

-		Az += MP1;

-	}

-

-	/* 4th subframe: isp_new (frac=1.0) */

-	Isp_Az(isp_new, Az, M, 0);

-

-	return;

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*      File: int_lpc.c                                                 *
+*                                                                      *
+*      Description:Interpolation of the LP parameters in 4 subframes.  *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "cnst.h"
+#include "acelp.h"
+
+#define MP1 (M+1)
+
+
+void Int_isp(
+		Word16 isp_old[],                     /* input : isps from past frame              */
+		Word16 isp_new[],                     /* input : isps from present frame           */
+		Word16 frac[],                        /* input : fraction for 3 first subfr (Q15)  */
+		Word16 Az[]                           /* output: LP coefficients in 4 subframes    */
+	    )
+{
+	Word32 i, k;
+	Word16 fac_old, fac_new;
+	Word16 isp[M];
+	Word32 L_tmp;
+
+	for (k = 0; k < 3; k++)
+	{
+		fac_new = frac[k];
+		fac_old = (32767 - fac_new) + 1;  /* 1.0 - fac_new */
+
+		for (i = 0; i < M; i++)
+		{
+			L_tmp = (isp_old[i] * fac_old)<<1;
+			L_tmp += (isp_new[i] * fac_new)<<1;
+			isp[i] = (L_tmp + 0x8000)>>16;
+		}
+		Isp_Az(isp, Az, M, 0);
+		Az += MP1;
+	}
+
+	/* 4th subframe: isp_new (frac=1.0) */
+	Isp_Az(isp_new, Az, M, 0);
+
+	return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/isp_az.c b/media/libstagefright/codecs/amrwbenc/src/isp_az.c
index 7b44d12..30a8bbd 100644
--- a/media/libstagefright/codecs/amrwbenc/src/isp_az.c
+++ b/media/libstagefright/codecs/amrwbenc/src/isp_az.c
@@ -1,247 +1,247 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*      File: isp_az.c                                                  *

-*                                                                      *

-*      Description:Compute the LPC coefficients from isp (order=M)     *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "oper_32b.h"

-#include "cnst.h"

-

-#define NC (M/2)

-#define NC16k (M16k/2)

-

-/* local function */

-

-static void Get_isp_pol(Word16 * isp, Word32 * f, Word16 n);

-static void Get_isp_pol_16kHz(Word16 * isp, Word32 * f, Word16 n);

-

-void Isp_Az(

-		Word16 isp[],                         /* (i) Q15 : Immittance spectral pairs            */

-		Word16 a[],                           /* (o) Q12 : predictor coefficients (order = M)   */

-		Word16 m,

-		Word16 adaptive_scaling               /* (i) 0   : adaptive scaling disabled */

-		                                      /*     1   : adaptive scaling enabled  */

-	   )

-{

-	Word32 i, j; 

-	Word16 hi, lo;

-	Word32 f1[NC16k + 1], f2[NC16k];

-	Word16 nc;

-	Word32 t0;

-	Word16 q, q_sug;

-	Word32 tmax;

-

-	nc = (m >> 1);

-	if(nc > 8)

-	{

-		Get_isp_pol_16kHz(&isp[0], f1, nc);

-		for (i = 0; i <= nc; i++)

-		{

-			f1[i] = f1[i] << 2;

-		}

-	} else

-		Get_isp_pol(&isp[0], f1, nc);

-

-	if (nc > 8)

-	{

-		Get_isp_pol_16kHz(&isp[1], f2, (nc - 1));

-		for (i = 0; i <= nc - 1; i++)

-		{

-			f2[i] = f2[i] << 2;

-		}

-	} else

-		Get_isp_pol(&isp[1], f2, (nc - 1));

-

-	/*-----------------------------------------------------*

-	 *  Multiply F2(z) by (1 - z^-2)                       *

-	 *-----------------------------------------------------*/

-

-	for (i = (nc - 1); i > 1; i--)

-	{

-		f2[i] = vo_L_sub(f2[i], f2[i - 2]);          /* f2[i] -= f2[i-2]; */

-	}

-

-	/*----------------------------------------------------------*

-	 *  Scale F1(z) by (1+isp[m-1])  and  F2(z) by (1-isp[m-1]) *

-	 *----------------------------------------------------------*/

-

-	for (i = 0; i < nc; i++)

-	{

-		/* f1[i] *= (1.0 + isp[M-1]); */

-

-		hi = f1[i] >> 16;

-		lo = (f1[i] & 0xffff)>>1;

-

-		t0 = Mpy_32_16(hi, lo, isp[m - 1]);

-		f1[i] = vo_L_add(f1[i], t0); 

-

-		/* f2[i] *= (1.0 - isp[M-1]); */

-

-		hi = f2[i] >> 16;

-		lo = (f2[i] & 0xffff)>>1;

-		t0 = Mpy_32_16(hi, lo, isp[m - 1]);

-		f2[i] = vo_L_sub(f2[i], t0); 

-	}

-

-	/*-----------------------------------------------------*

-	 *  A(z) = (F1(z)+F2(z))/2                             *

-	 *  F1(z) is symmetric and F2(z) is antisymmetric      *

-	 *-----------------------------------------------------*/

-

-	/* a[0] = 1.0; */

-	a[0] = 4096;  

-	tmax = 1;                            

-	for (i = 1, j = m - 1; i < nc; i++, j--)

-	{

-		/* a[i] = 0.5*(f1[i] + f2[i]); */

-

-		t0 = vo_L_add(f1[i], f2[i]);          /* f1[i] + f2[i]             */

-		tmax |= L_abs(t0);                 

-		a[i] = (Word16)(vo_L_shr_r(t0, 12)); /* from Q23 to Q12 and * 0.5 */

-

-		/* a[j] = 0.5*(f1[i] - f2[i]); */

-

-		t0 = vo_L_sub(f1[i], f2[i]);          /* f1[i] - f2[i]             */

-		tmax |= L_abs(t0);                

-		a[j] = (Word16)(vo_L_shr_r(t0, 12)); /* from Q23 to Q12 and * 0.5 */

-	}

-

-	/* rescale data if overflow has occured and reprocess the loop */

-	if(adaptive_scaling == 1)

-		q = 4 - norm_l(tmax);        /* adaptive scaling enabled */

-	else

-		q = 0;                           /* adaptive scaling disabled */

-

-	if (q > 0)

-	{

-		q_sug = (12 + q);

-		for (i = 1, j = m - 1; i < nc; i++, j--)

-		{

-			/* a[i] = 0.5*(f1[i] + f2[i]); */

-			t0 = vo_L_add(f1[i], f2[i]);          /* f1[i] + f2[i]             */

-			a[i] = (Word16)(vo_L_shr_r(t0, q_sug)); /* from Q23 to Q12 and * 0.5 */

-

-			/* a[j] = 0.5*(f1[i] - f2[i]); */

-			t0 = vo_L_sub(f1[i], f2[i]);          /* f1[i] - f2[i]             */

-			a[j] = (Word16)(vo_L_shr_r(t0, q_sug)); /* from Q23 to Q12 and * 0.5 */

-		}

-		a[0] = shr(a[0], q); 

-	}

-	else

-	{

-		q_sug = 12; 

-		q     = 0; 

-	}

-	/* a[NC] = 0.5*f1[NC]*(1.0 + isp[M-1]); */

-	hi = f1[nc] >> 16;

-	lo = (f1[nc] & 0xffff)>>1;

-	t0 = Mpy_32_16(hi, lo, isp[m - 1]);

-	t0 = vo_L_add(f1[nc], t0);

-	a[nc] = (Word16)(L_shr_r(t0, q_sug));    /* from Q23 to Q12 and * 0.5 */

-	/* a[m] = isp[m-1]; */

-

-	a[m] = vo_shr_r(isp[m - 1], (3 + q));           /* from Q15 to Q12          */

-	return;

-}

-

-/*-----------------------------------------------------------*

-* procedure Get_isp_pol:                                    *

-*           ~~~~~~~~~~~                                     *

-*   Find the polynomial F1(z) or F2(z) from the ISPs.       *

-* This is performed by expanding the product polynomials:   *

-*                                                           *

-* F1(z) =   product   ( 1 - 2 isp_i z^-1 + z^-2 )           *

-*         i=0,2,4,6,8                                       *

-* F2(z) =   product   ( 1 - 2 isp_i z^-1 + z^-2 )           *

-*         i=1,3,5,7                                         *

-*                                                           *

-* where isp_i are the ISPs in the cosine domain.            *

-*-----------------------------------------------------------*

-*                                                           *

-* Parameters:                                               *

-*  isp[]   : isp vector (cosine domaine)         in Q15     *

-*  f[]     : the coefficients of F1 or F2        in Q23     *

-*  n       : == NC for F1(z); == NC-1 for F2(z)             *

-*-----------------------------------------------------------*/

-

-static void Get_isp_pol(Word16 * isp, Word32 * f, Word16 n)

-{

-	Word16 hi, lo;

-	Word32 i, j, t0;

-	/* All computation in Q23 */

-

-	f[0] = vo_L_mult(4096, 1024);               /* f[0] = 1.0;        in Q23  */

-	f[1] = vo_L_mult(isp[0], -256);             /* f[1] = -2.0*isp[0] in Q23  */

-

-	f += 2;                                  /* Advance f pointer          */

-	isp += 2;                                /* Advance isp pointer        */

-	for (i = 2; i <= n; i++)

-	{

-		*f = f[-2];                        

-		for (j = 1; j < i; j++, f--)

-		{

-			hi = f[-1]>>16;

-			lo = (f[-1] & 0xffff)>>1;

-

-			t0 = Mpy_32_16(hi, lo, *isp);  /* t0 = f[-1] * isp    */

-			t0 = t0 << 1;

-			*f = vo_L_sub(*f, t0);              /* *f -= t0            */

-			*f = vo_L_add(*f, f[-2]);           /* *f += f[-2]         */

-		}

-		*f -= (*isp << 9);           /* *f -= isp<<8        */

-		f += i;                            /* Advance f pointer   */

-		isp += 2;                          /* Advance isp pointer */

-	}

-	return;

-}

-

-static void Get_isp_pol_16kHz(Word16 * isp, Word32 * f, Word16 n)

-{

-	Word16 hi, lo;

-	Word32 i, j, t0;

-

-	/* All computation in Q23 */

-	f[0] = L_mult(4096, 256);                /* f[0] = 1.0;        in Q23  */

-	f[1] = L_mult(isp[0], -64);              /* f[1] = -2.0*isp[0] in Q23  */

-

-	f += 2;                                  /* Advance f pointer          */

-	isp += 2;                                /* Advance isp pointer        */

-

-	for (i = 2; i <= n; i++)

-	{

-		*f = f[-2];                        

-		for (j = 1; j < i; j++, f--)

-		{

-			VO_L_Extract(f[-1], &hi, &lo);

-			t0 = Mpy_32_16(hi, lo, *isp);  /* t0 = f[-1] * isp    */

-			t0 = L_shl2(t0, 1);

-			*f = L_sub(*f, t0);              /* *f -= t0            */

-			*f = L_add(*f, f[-2]);           /* *f += f[-2]         */

-		}

-		*f = L_msu(*f, *isp, 64);            /* *f -= isp<<8        */

-		f += i;                            /* Advance f pointer   */

-		isp += 2;                          /* Advance isp pointer */

-	}

-	return;

-}

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*      File: isp_az.c                                                  *
+*                                                                      *
+*      Description:Compute the LPC coefficients from isp (order=M)     *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "oper_32b.h"
+#include "cnst.h"
+
+#define NC (M/2)
+#define NC16k (M16k/2)
+
+/* local function */
+
+static void Get_isp_pol(Word16 * isp, Word32 * f, Word16 n);
+static void Get_isp_pol_16kHz(Word16 * isp, Word32 * f, Word16 n);
+
+void Isp_Az(
+		Word16 isp[],                         /* (i) Q15 : Immittance spectral pairs            */
+		Word16 a[],                           /* (o) Q12 : predictor coefficients (order = M)   */
+		Word16 m,
+		Word16 adaptive_scaling               /* (i) 0   : adaptive scaling disabled */
+		                                      /*     1   : adaptive scaling enabled  */
+	   )
+{
+	Word32 i, j;
+	Word16 hi, lo;
+	Word32 f1[NC16k + 1], f2[NC16k];
+	Word16 nc;
+	Word32 t0;
+	Word16 q, q_sug;
+	Word32 tmax;
+
+	nc = (m >> 1);
+	if(nc > 8)
+	{
+		Get_isp_pol_16kHz(&isp[0], f1, nc);
+		for (i = 0; i <= nc; i++)
+		{
+			f1[i] = f1[i] << 2;
+		}
+	} else
+		Get_isp_pol(&isp[0], f1, nc);
+
+	if (nc > 8)
+	{
+		Get_isp_pol_16kHz(&isp[1], f2, (nc - 1));
+		for (i = 0; i <= nc - 1; i++)
+		{
+			f2[i] = f2[i] << 2;
+		}
+	} else
+		Get_isp_pol(&isp[1], f2, (nc - 1));
+
+	/*-----------------------------------------------------*
+	 *  Multiply F2(z) by (1 - z^-2)                       *
+	 *-----------------------------------------------------*/
+
+	for (i = (nc - 1); i > 1; i--)
+	{
+		f2[i] = vo_L_sub(f2[i], f2[i - 2]);          /* f2[i] -= f2[i-2]; */
+	}
+
+	/*----------------------------------------------------------*
+	 *  Scale F1(z) by (1+isp[m-1])  and  F2(z) by (1-isp[m-1]) *
+	 *----------------------------------------------------------*/
+
+	for (i = 0; i < nc; i++)
+	{
+		/* f1[i] *= (1.0 + isp[M-1]); */
+
+		hi = f1[i] >> 16;
+		lo = (f1[i] & 0xffff)>>1;
+
+		t0 = Mpy_32_16(hi, lo, isp[m - 1]);
+		f1[i] = vo_L_add(f1[i], t0);
+
+		/* f2[i] *= (1.0 - isp[M-1]); */
+
+		hi = f2[i] >> 16;
+		lo = (f2[i] & 0xffff)>>1;
+		t0 = Mpy_32_16(hi, lo, isp[m - 1]);
+		f2[i] = vo_L_sub(f2[i], t0);
+	}
+
+	/*-----------------------------------------------------*
+	 *  A(z) = (F1(z)+F2(z))/2                             *
+	 *  F1(z) is symmetric and F2(z) is antisymmetric      *
+	 *-----------------------------------------------------*/
+
+	/* a[0] = 1.0; */
+	a[0] = 4096;
+	tmax = 1;
+	for (i = 1, j = m - 1; i < nc; i++, j--)
+	{
+		/* a[i] = 0.5*(f1[i] + f2[i]); */
+
+		t0 = vo_L_add(f1[i], f2[i]);          /* f1[i] + f2[i]             */
+		tmax |= L_abs(t0);
+		a[i] = (Word16)(vo_L_shr_r(t0, 12)); /* from Q23 to Q12 and * 0.5 */
+
+		/* a[j] = 0.5*(f1[i] - f2[i]); */
+
+		t0 = vo_L_sub(f1[i], f2[i]);          /* f1[i] - f2[i]             */
+		tmax |= L_abs(t0);
+		a[j] = (Word16)(vo_L_shr_r(t0, 12)); /* from Q23 to Q12 and * 0.5 */
+	}
+
+	/* rescale data if overflow has occured and reprocess the loop */
+	if(adaptive_scaling == 1)
+		q = 4 - norm_l(tmax);        /* adaptive scaling enabled */
+	else
+		q = 0;                           /* adaptive scaling disabled */
+
+	if (q > 0)
+	{
+		q_sug = (12 + q);
+		for (i = 1, j = m - 1; i < nc; i++, j--)
+		{
+			/* a[i] = 0.5*(f1[i] + f2[i]); */
+			t0 = vo_L_add(f1[i], f2[i]);          /* f1[i] + f2[i]             */
+			a[i] = (Word16)(vo_L_shr_r(t0, q_sug)); /* from Q23 to Q12 and * 0.5 */
+
+			/* a[j] = 0.5*(f1[i] - f2[i]); */
+			t0 = vo_L_sub(f1[i], f2[i]);          /* f1[i] - f2[i]             */
+			a[j] = (Word16)(vo_L_shr_r(t0, q_sug)); /* from Q23 to Q12 and * 0.5 */
+		}
+		a[0] = shr(a[0], q);
+	}
+	else
+	{
+		q_sug = 12;
+		q     = 0;
+	}
+	/* a[NC] = 0.5*f1[NC]*(1.0 + isp[M-1]); */
+	hi = f1[nc] >> 16;
+	lo = (f1[nc] & 0xffff)>>1;
+	t0 = Mpy_32_16(hi, lo, isp[m - 1]);
+	t0 = vo_L_add(f1[nc], t0);
+	a[nc] = (Word16)(L_shr_r(t0, q_sug));    /* from Q23 to Q12 and * 0.5 */
+	/* a[m] = isp[m-1]; */
+
+	a[m] = vo_shr_r(isp[m - 1], (3 + q));           /* from Q15 to Q12          */
+	return;
+}
+
+/*-----------------------------------------------------------*
+* procedure Get_isp_pol:                                    *
+*           ~~~~~~~~~~~                                     *
+*   Find the polynomial F1(z) or F2(z) from the ISPs.       *
+* This is performed by expanding the product polynomials:   *
+*                                                           *
+* F1(z) =   product   ( 1 - 2 isp_i z^-1 + z^-2 )           *
+*         i=0,2,4,6,8                                       *
+* F2(z) =   product   ( 1 - 2 isp_i z^-1 + z^-2 )           *
+*         i=1,3,5,7                                         *
+*                                                           *
+* where isp_i are the ISPs in the cosine domain.            *
+*-----------------------------------------------------------*
+*                                                           *
+* Parameters:                                               *
+*  isp[]   : isp vector (cosine domaine)         in Q15     *
+*  f[]     : the coefficients of F1 or F2        in Q23     *
+*  n       : == NC for F1(z); == NC-1 for F2(z)             *
+*-----------------------------------------------------------*/
+
+static void Get_isp_pol(Word16 * isp, Word32 * f, Word16 n)
+{
+	Word16 hi, lo;
+	Word32 i, j, t0;
+	/* All computation in Q23 */
+
+	f[0] = vo_L_mult(4096, 1024);               /* f[0] = 1.0;        in Q23  */
+	f[1] = vo_L_mult(isp[0], -256);             /* f[1] = -2.0*isp[0] in Q23  */
+
+	f += 2;                                  /* Advance f pointer          */
+	isp += 2;                                /* Advance isp pointer        */
+	for (i = 2; i <= n; i++)
+	{
+		*f = f[-2];
+		for (j = 1; j < i; j++, f--)
+		{
+			hi = f[-1]>>16;
+			lo = (f[-1] & 0xffff)>>1;
+
+			t0 = Mpy_32_16(hi, lo, *isp);  /* t0 = f[-1] * isp    */
+			t0 = t0 << 1;
+			*f = vo_L_sub(*f, t0);              /* *f -= t0            */
+			*f = vo_L_add(*f, f[-2]);           /* *f += f[-2]         */
+		}
+		*f -= (*isp << 9);           /* *f -= isp<<8        */
+		f += i;                            /* Advance f pointer   */
+		isp += 2;                          /* Advance isp pointer */
+	}
+	return;
+}
+
+static void Get_isp_pol_16kHz(Word16 * isp, Word32 * f, Word16 n)
+{
+	Word16 hi, lo;
+	Word32 i, j, t0;
+
+	/* All computation in Q23 */
+	f[0] = L_mult(4096, 256);                /* f[0] = 1.0;        in Q23  */
+	f[1] = L_mult(isp[0], -64);              /* f[1] = -2.0*isp[0] in Q23  */
+
+	f += 2;                                  /* Advance f pointer          */
+	isp += 2;                                /* Advance isp pointer        */
+
+	for (i = 2; i <= n; i++)
+	{
+		*f = f[-2];
+		for (j = 1; j < i; j++, f--)
+		{
+			VO_L_Extract(f[-1], &hi, &lo);
+			t0 = Mpy_32_16(hi, lo, *isp);  /* t0 = f[-1] * isp    */
+			t0 = L_shl2(t0, 1);
+			*f = L_sub(*f, t0);              /* *f -= t0            */
+			*f = L_add(*f, f[-2]);           /* *f += f[-2]         */
+		}
+		*f = L_msu(*f, *isp, 64);            /* *f -= isp<<8        */
+		f += i;                            /* Advance f pointer   */
+		isp += 2;                          /* Advance isp pointer */
+	}
+	return;
+}
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/isp_isf.c b/media/libstagefright/codecs/amrwbenc/src/isp_isf.c
index 6c6e389..b4ba408 100644
--- a/media/libstagefright/codecs/amrwbenc/src/isp_isf.c
+++ b/media/libstagefright/codecs/amrwbenc/src/isp_isf.c
@@ -1,91 +1,91 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*       File: isp_isf.c                                                *

-*                                                                      *

-*       Description:                                                   *

-*	Isp_isf   Transformation isp to isf                            *

-*	Isf_isp   Transformation isf to isp                            *

-*                                                                      *

-*	The transformation from isp[i] to isf[i] and isf[i] to isp[i]  *

-*	are approximated by a look-up table and interpolation          *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "isp_isf.tab"                     /* Look-up table for transformations */

-

-void Isp_isf(

-		Word16 isp[],                         /* (i) Q15 : isp[m] (range: -1<=val<1)                */

-		Word16 isf[],                         /* (o) Q15 : isf[m] normalized (range: 0.0<=val<=0.5) */

-		Word16 m                              /* (i)     : LPC order                                */

-	    )

-{

-	Word32 i, ind;

-	Word32 L_tmp;

-	ind = 127;                               /* beging at end of table -1 */

-	for (i = (m - 1); i >= 0; i--)

-	{

-		if (i >= (m - 2))

-		{                                  /* m-2 is a constant */

-			ind = 127;                       /* beging at end of table -1 */

-		}

-		/* find value in table that is just greater than isp[i] */

-		while (table[ind] < isp[i])

-			ind--;

-		/* acos(isp[i])= ind*128 + ( ( isp[i]-table[ind] ) * slope[ind] )/2048 */

-		L_tmp = vo_L_mult(vo_sub(isp[i], table[ind]), slope[ind]);

-		isf[i] = vo_round((L_tmp << 4));   /* (isp[i]-table[ind])*slope[ind])>>11 */

-		isf[i] = add1(isf[i], (ind << 7)); 

-	}

-	isf[m - 1] = (isf[m - 1] >> 1);      

-	return;

-}

-

-

-void Isf_isp(

-		Word16 isf[],                         /* (i) Q15 : isf[m] normalized (range: 0.0<=val<=0.5) */

-		Word16 isp[],                         /* (o) Q15 : isp[m] (range: -1<=val<1)                */

-		Word16 m                              /* (i)     : LPC order                                */

-	    )

-{

-	Word16 offset;

-	Word32 i, ind, L_tmp;

-

-	for (i = 0; i < m - 1; i++)

-	{

-		isp[i] = isf[i];                  

-	}

-	isp[m - 1] = (isf[m - 1] << 1);

-

-	for (i = 0; i < m; i++)

-	{

-		ind = (isp[i] >> 7);                      /* ind    = b7-b15 of isf[i] */

-		offset = (Word16) (isp[i] & 0x007f);      /* offset = b0-b6  of isf[i] */

-

-		/* isp[i] = table[ind]+ ((table[ind+1]-table[ind])*offset) / 128 */

-		L_tmp = vo_L_mult(vo_sub(table[ind + 1], table[ind]), offset);

-		isp[i] = add1(table[ind], (Word16)((L_tmp >> 8)));   

-	}

-

-	return;

-}

-

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*       File: isp_isf.c                                                *
+*                                                                      *
+*       Description:                                                   *
+*	Isp_isf   Transformation isp to isf                            *
+*	Isf_isp   Transformation isf to isp                            *
+*                                                                      *
+*	The transformation from isp[i] to isf[i] and isf[i] to isp[i]  *
+*	are approximated by a look-up table and interpolation          *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "isp_isf.tab"                     /* Look-up table for transformations */
+
+void Isp_isf(
+		Word16 isp[],                         /* (i) Q15 : isp[m] (range: -1<=val<1)                */
+		Word16 isf[],                         /* (o) Q15 : isf[m] normalized (range: 0.0<=val<=0.5) */
+		Word16 m                              /* (i)     : LPC order                                */
+	    )
+{
+	Word32 i, ind;
+	Word32 L_tmp;
+	ind = 127;                               /* beging at end of table -1 */
+	for (i = (m - 1); i >= 0; i--)
+	{
+		if (i >= (m - 2))
+		{                                  /* m-2 is a constant */
+			ind = 127;                       /* beging at end of table -1 */
+		}
+		/* find value in table that is just greater than isp[i] */
+		while (table[ind] < isp[i])
+			ind--;
+		/* acos(isp[i])= ind*128 + ( ( isp[i]-table[ind] ) * slope[ind] )/2048 */
+		L_tmp = vo_L_mult(vo_sub(isp[i], table[ind]), slope[ind]);
+		isf[i] = vo_round((L_tmp << 4));   /* (isp[i]-table[ind])*slope[ind])>>11 */
+		isf[i] = add1(isf[i], (ind << 7));
+	}
+	isf[m - 1] = (isf[m - 1] >> 1);
+	return;
+}
+
+
+void Isf_isp(
+		Word16 isf[],                         /* (i) Q15 : isf[m] normalized (range: 0.0<=val<=0.5) */
+		Word16 isp[],                         /* (o) Q15 : isp[m] (range: -1<=val<1)                */
+		Word16 m                              /* (i)     : LPC order                                */
+	    )
+{
+	Word16 offset;
+	Word32 i, ind, L_tmp;
+
+	for (i = 0; i < m - 1; i++)
+	{
+		isp[i] = isf[i];
+	}
+	isp[m - 1] = (isf[m - 1] << 1);
+
+	for (i = 0; i < m; i++)
+	{
+		ind = (isp[i] >> 7);                      /* ind    = b7-b15 of isf[i] */
+		offset = (Word16) (isp[i] & 0x007f);      /* offset = b0-b6  of isf[i] */
+
+		/* isp[i] = table[ind]+ ((table[ind+1]-table[ind])*offset) / 128 */
+		L_tmp = vo_L_mult(vo_sub(table[ind + 1], table[ind]), offset);
+		isp[i] = add1(table[ind], (Word16)((L_tmp >> 8)));
+	}
+
+	return;
+}
+
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/lag_wind.c b/media/libstagefright/codecs/amrwbenc/src/lag_wind.c
index 0397704..49c622c 100644
--- a/media/libstagefright/codecs/amrwbenc/src/lag_wind.c
+++ b/media/libstagefright/codecs/amrwbenc/src/lag_wind.c
@@ -1,49 +1,49 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*      File: lag_wind.c                                                *

-*                                                                      *

-*	   Description: Lag_windows on autocorrelations                *

-*	                r[i] *= lag_wind[i]                            *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "oper_32b.h"

-#include "lag_wind.tab"

-

-

-void Lag_window(

-		Word16 r_h[],                         /* (i/o)   : Autocorrelations  (msb)          */

-		Word16 r_l[]                          /* (i/o)   : Autocorrelations  (lsb)          */

-	       )

-{

-	Word32 i;

-	Word32 x;

-

-	for (i = 1; i <= M; i++)

-	{

-		x = Mpy_32(r_h[i], r_l[i], volag_h[i - 1], volag_l[i - 1]);

-		r_h[i] = x >> 16;

-		r_l[i] = (x & 0xffff)>>1;

-	}

-	return;

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*      File: lag_wind.c                                                *
+*                                                                      *
+*	   Description: Lag_windows on autocorrelations                *
+*	                r[i] *= lag_wind[i]                            *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "oper_32b.h"
+#include "lag_wind.tab"
+
+
+void Lag_window(
+		Word16 r_h[],                         /* (i/o)   : Autocorrelations  (msb)          */
+		Word16 r_l[]                          /* (i/o)   : Autocorrelations  (lsb)          */
+	       )
+{
+	Word32 i;
+	Word32 x;
+
+	for (i = 1; i <= M; i++)
+	{
+		x = Mpy_32(r_h[i], r_l[i], volag_h[i - 1], volag_l[i - 1]);
+		r_h[i] = x >> 16;
+		r_l[i] = (x & 0xffff)>>1;
+	}
+	return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/levinson.c b/media/libstagefright/codecs/amrwbenc/src/levinson.c
index 8bc6f62..4b2f8ed 100644
--- a/media/libstagefright/codecs/amrwbenc/src/levinson.c
+++ b/media/libstagefright/codecs/amrwbenc/src/levinson.c
@@ -1,250 +1,250 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*      File: levinson.c                                                *

-*                                                                      *

-*      Description:LEVINSON-DURBIN algorithm in double precision       *

-*                                                                      *

-************************************************************************/

-/*---------------------------------------------------------------------------*

- *                         LEVINSON.C					     *

- *---------------------------------------------------------------------------*

- *                                                                           *

- *      LEVINSON-DURBIN algorithm in double precision                        *

- *                                                                           *

- *                                                                           *

- * Algorithm                                                                 *

- *                                                                           *

- *       R[i]    autocorrelations.                                           *

- *       A[i]    filter coefficients.                                        *

- *       K       reflection coefficients.                                    *

- *       Alpha   prediction gain.                                            *

- *                                                                           *

- *       Initialization:                                                     *

- *               A[0] = 1                                                    *

- *               K    = -R[1]/R[0]                                           *

- *               A[1] = K                                                    *

- *               Alpha = R[0] * (1-K**2]                                     *

- *                                                                           *

- *       Do for  i = 2 to M                                                  *

- *                                                                           *

- *            S =  SUM ( R[j]*A[i-j] ,j=1,i-1 ) +  R[i]                      *

- *                                                                           *

- *            K = -S / Alpha                                                 *

- *                                                                           *

- *            An[j] = A[j] + K*A[i-j]   for j=1 to i-1                       *

- *                                      where   An[i] = new A[i]             *

- *            An[i]=K                                                        *

- *                                                                           *

- *            Alpha=Alpha * (1-K**2)                                         *

- *                                                                           *

- *       END                                                                 *

- *                                                                           *

- * Remarks on the dynamics of the calculations.                              *

- *                                                                           *

- *       The numbers used are in double precision in the following format :  *

- *       A = AH <<16 + AL<<1.  AH and AL are 16 bit signed integers.         *

- *       Since the LSB's also contain a sign bit, this format does not       *

- *       correspond to standard 32 bit integers.  We use this format since   *

- *       it allows fast execution of multiplications and divisions.          *

- *                                                                           *

- *       "DPF" will refer to this special format in the following text.      *

- *       See oper_32b.c                                                      *

- *                                                                           *

- *       The R[i] were normalized in routine AUTO (hence, R[i] < 1.0).       *

- *       The K[i] and Alpha are theoretically < 1.0.                         *

- *       The A[i], for a sampling frequency of 8 kHz, are in practice        *

- *       always inferior to 16.0.                                            *

- *                                                                           *

- *       These characteristics allow straigthforward fixed-point             *

- *       implementation.  We choose to represent the parameters as           *

- *       follows :                                                           *

- *                                                                           *

- *               R[i]    Q31   +- .99..                                      *

- *               K[i]    Q31   +- .99..                                      *

- *               Alpha   Normalized -> mantissa in Q31 plus exponent         *

- *               A[i]    Q27   +- 15.999..                                   *

- *                                                                           *

- *       The additions are performed in 32 bit.  For the summation used      *

- *       to calculate the K[i], we multiply numbers in Q31 by numbers        *

- *       in Q27, with the result of the multiplications in Q27,              *

- *       resulting in a dynamic of +- 16.  This is sufficient to avoid       *

- *       overflow, since the final result of the summation is                *

- *       necessarily < 1.0 as both the K[i] and Alpha are                    *

- *       theoretically < 1.0.                                                *

- *___________________________________________________________________________*/

-#include "typedef.h"

-#include "basic_op.h"

-#include "oper_32b.h"

-#include "acelp.h"

-

-#define M   16

-#define NC  (M/2)

-

-void Init_Levinson(

-		Word16 * mem                          /* output  :static memory (18 words) */

-		)

-{

-	Set_zero(mem, 18);                     /* old_A[0..M-1] = 0, old_rc[0..1] = 0 */

-	return;

-}

-

-

-void Levinson(

-		Word16 Rh[],                          /* (i)     : Rh[M+1] Vector of autocorrelations (msb) */

-		Word16 Rl[],                          /* (i)     : Rl[M+1] Vector of autocorrelations (lsb) */

-		Word16 A[],                           /* (o) Q12 : A[M]    LPC coefficients  (m = 16)       */

-		Word16 rc[],                          /* (o) Q15 : rc[M]   Reflection coefficients.         */

-		Word16 * mem                          /* (i/o)   :static memory (18 words)                  */

-	     )

-{

-	Word32 i, j;

-	Word16 hi, lo;

-	Word16 Kh, Kl;                         /* reflection coefficient; hi and lo           */

-	Word16 alp_h, alp_l, alp_exp;          /* Prediction gain; hi lo and exponent         */

-	Word16 Ah[M + 1], Al[M + 1];           /* LPC coef. in double prec.                   */

-	Word16 Anh[M + 1], Anl[M + 1];         /* LPC coef.for next iteration in double prec. */

-	Word32 t0, t1, t2;                     /* temporary variable                          */

-	Word16 *old_A, *old_rc;

-

-	/* Last A(z) for case of unstable filter */

-	old_A = mem;                           

-	old_rc = mem + M;                      

-

-	/* K = A[1] = -R[1] / R[0] */

-

-	t1 = ((Rh[1] << 16) + (Rl[1] << 1));   /* R[1] in Q31 */

-	t2 = L_abs(t1);                        /* abs R[1]         */

-	t0 = Div_32(t2, Rh[0], Rl[0]);         /* R[1]/R[0] in Q31 */

-	if (t1 > 0)

-		t0 = -t0;                          /* -R[1]/R[0]       */

-

-	Kh = t0 >> 16;

-	Kl = (t0 & 0xffff)>>1;

-	rc[0] = Kh;                            

-	t0 = (t0 >> 4);                        /* A[1] in Q27      */

-

-	Ah[1] = t0 >> 16;

-	Al[1] = (t0 & 0xffff)>>1;

-

-	/* Alpha = R[0] * (1-K**2) */

-	t0 = Mpy_32(Kh, Kl, Kh, Kl);           /* K*K      in Q31 */

-	t0 = L_abs(t0);                        /* Some case <0 !! */

-	t0 = vo_L_sub((Word32) 0x7fffffffL, t0);  /* 1 - K*K  in Q31 */

-

-	hi = t0 >> 16;

-	lo = (t0 & 0xffff)>>1;

-

-	t0 = Mpy_32(Rh[0], Rl[0], hi, lo);     /* Alpha in Q31    */

-

-	/* Normalize Alpha */

-	alp_exp = norm_l(t0);

-	t0 = (t0 << alp_exp);

-

-	alp_h = t0 >> 16;

-	alp_l = (t0 & 0xffff)>>1;

-	/*--------------------------------------*

-	 * ITERATIONS  I=2 to M                 *

-	 *--------------------------------------*/

-	for (i = 2; i <= M; i++)

-	{

-		/* t0 = SUM ( R[j]*A[i-j] ,j=1,i-1 ) +  R[i] */

-		t0 = 0;                           

-		for (j = 1; j < i; j++)

-			t0 = vo_L_add(t0, Mpy_32(Rh[j], Rl[j], Ah[i - j], Al[i - j]));

-

-		t0 = t0 << 4;                 /* result in Q27 -> convert to Q31 */

-		/* No overflow possible            */

-		t1 = ((Rh[i] << 16) + (Rl[i] << 1));

-		t0 = vo_L_add(t0, t1);                /* add R[i] in Q31                 */

-

-		/* K = -t0 / Alpha */

-		t1 = L_abs(t0);

-		t2 = Div_32(t1, alp_h, alp_l);     /* abs(t0)/Alpha                   */

-		if (t0 > 0)

-			t2 = -t2;                   /* K =-t0/Alpha                    */

-		t2 = (t2 << alp_exp);           /* denormalize; compare to Alpha   */

-

-		Kh = t2 >> 16;

-		Kl = (t2 & 0xffff)>>1;

-

-		rc[i - 1] = Kh;                   

-		/* Test for unstable filter. If unstable keep old A(z) */

-		if (abs_s(Kh) > 32750)

-		{

-			A[0] = 4096;                    /* Ai[0] not stored (always 1.0) */

-			for (j = 0; j < M; j++)

-			{

-				A[j + 1] = old_A[j];       

-			}

-			rc[0] = old_rc[0];             /* only two rc coefficients are needed */

-			rc[1] = old_rc[1];

-			return;

-		}

-		/*------------------------------------------*

-		 *  Compute new LPC coeff. -> An[i]         *

-		 *  An[j]= A[j] + K*A[i-j]     , j=1 to i-1 *

-		 *  An[i]= K                                *

-		 *------------------------------------------*/

-		for (j = 1; j < i; j++)

-		{

-			t0 = Mpy_32(Kh, Kl, Ah[i - j], Al[i - j]);

-			t0 = vo_L_add(t0, ((Ah[j] << 16) + (Al[j] << 1)));

-			Anh[j] = t0 >> 16;

-			Anl[j] = (t0 & 0xffff)>>1;

-		}

-		t2 = (t2 >> 4);                 /* t2 = K in Q31 ->convert to Q27  */

-

-		VO_L_Extract(t2, &Anh[i], &Anl[i]);   /* An[i] in Q27                    */

-

-		/* Alpha = Alpha * (1-K**2) */

-		t0 = Mpy_32(Kh, Kl, Kh, Kl);               /* K*K      in Q31 */

-		t0 = L_abs(t0);                            /* Some case <0 !! */

-		t0 = vo_L_sub((Word32) 0x7fffffffL, t0);   /* 1 - K*K  in Q31 */

-		hi = t0 >> 16;

-		lo = (t0 & 0xffff)>>1;

-		t0 = Mpy_32(alp_h, alp_l, hi, lo); /* Alpha in Q31    */

-

-		/* Normalize Alpha */

-		j = norm_l(t0);

-		t0 = (t0 << j);

-		alp_h = t0 >> 16;

-		alp_l = (t0 & 0xffff)>>1;

-		alp_exp += j;         /* Add normalization to alp_exp */

-

-		/* A[j] = An[j] */

-		for (j = 1; j <= i; j++)

-		{

-			Ah[j] = Anh[j];               

-			Al[j] = Anl[j];                

-		}

-	}

-	/* Truncate A[i] in Q27 to Q12 with rounding */

-	A[0] = 4096;                          

-	for (i = 1; i <= M; i++)

-	{

-		t0 = (Ah[i] << 16) + (Al[i] << 1);

-		old_A[i - 1] = A[i] = vo_round((t0 << 1));      

-	}

-	old_rc[0] = rc[0];                    

-	old_rc[1] = rc[1];                    

-

-	return;

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*      File: levinson.c                                                *
+*                                                                      *
+*      Description:LEVINSON-DURBIN algorithm in double precision       *
+*                                                                      *
+************************************************************************/
+/*---------------------------------------------------------------------------*
+ *                         LEVINSON.C					     *
+ *---------------------------------------------------------------------------*
+ *                                                                           *
+ *      LEVINSON-DURBIN algorithm in double precision                        *
+ *                                                                           *
+ *                                                                           *
+ * Algorithm                                                                 *
+ *                                                                           *
+ *       R[i]    autocorrelations.                                           *
+ *       A[i]    filter coefficients.                                        *
+ *       K       reflection coefficients.                                    *
+ *       Alpha   prediction gain.                                            *
+ *                                                                           *
+ *       Initialization:                                                     *
+ *               A[0] = 1                                                    *
+ *               K    = -R[1]/R[0]                                           *
+ *               A[1] = K                                                    *
+ *               Alpha = R[0] * (1-K**2]                                     *
+ *                                                                           *
+ *       Do for  i = 2 to M                                                  *
+ *                                                                           *
+ *            S =  SUM ( R[j]*A[i-j] ,j=1,i-1 ) +  R[i]                      *
+ *                                                                           *
+ *            K = -S / Alpha                                                 *
+ *                                                                           *
+ *            An[j] = A[j] + K*A[i-j]   for j=1 to i-1                       *
+ *                                      where   An[i] = new A[i]             *
+ *            An[i]=K                                                        *
+ *                                                                           *
+ *            Alpha=Alpha * (1-K**2)                                         *
+ *                                                                           *
+ *       END                                                                 *
+ *                                                                           *
+ * Remarks on the dynamics of the calculations.                              *
+ *                                                                           *
+ *       The numbers used are in double precision in the following format :  *
+ *       A = AH <<16 + AL<<1.  AH and AL are 16 bit signed integers.         *
+ *       Since the LSB's also contain a sign bit, this format does not       *
+ *       correspond to standard 32 bit integers.  We use this format since   *
+ *       it allows fast execution of multiplications and divisions.          *
+ *                                                                           *
+ *       "DPF" will refer to this special format in the following text.      *
+ *       See oper_32b.c                                                      *
+ *                                                                           *
+ *       The R[i] were normalized in routine AUTO (hence, R[i] < 1.0).       *
+ *       The K[i] and Alpha are theoretically < 1.0.                         *
+ *       The A[i], for a sampling frequency of 8 kHz, are in practice        *
+ *       always inferior to 16.0.                                            *
+ *                                                                           *
+ *       These characteristics allow straigthforward fixed-point             *
+ *       implementation.  We choose to represent the parameters as           *
+ *       follows :                                                           *
+ *                                                                           *
+ *               R[i]    Q31   +- .99..                                      *
+ *               K[i]    Q31   +- .99..                                      *
+ *               Alpha   Normalized -> mantissa in Q31 plus exponent         *
+ *               A[i]    Q27   +- 15.999..                                   *
+ *                                                                           *
+ *       The additions are performed in 32 bit.  For the summation used      *
+ *       to calculate the K[i], we multiply numbers in Q31 by numbers        *
+ *       in Q27, with the result of the multiplications in Q27,              *
+ *       resulting in a dynamic of +- 16.  This is sufficient to avoid       *
+ *       overflow, since the final result of the summation is                *
+ *       necessarily < 1.0 as both the K[i] and Alpha are                    *
+ *       theoretically < 1.0.                                                *
+ *___________________________________________________________________________*/
+#include "typedef.h"
+#include "basic_op.h"
+#include "oper_32b.h"
+#include "acelp.h"
+
+#define M   16
+#define NC  (M/2)
+
+void Init_Levinson(
+		Word16 * mem                          /* output  :static memory (18 words) */
+		)
+{
+	Set_zero(mem, 18);                     /* old_A[0..M-1] = 0, old_rc[0..1] = 0 */
+	return;
+}
+
+
+void Levinson(
+		Word16 Rh[],                          /* (i)     : Rh[M+1] Vector of autocorrelations (msb) */
+		Word16 Rl[],                          /* (i)     : Rl[M+1] Vector of autocorrelations (lsb) */
+		Word16 A[],                           /* (o) Q12 : A[M]    LPC coefficients  (m = 16)       */
+		Word16 rc[],                          /* (o) Q15 : rc[M]   Reflection coefficients.         */
+		Word16 * mem                          /* (i/o)   :static memory (18 words)                  */
+	     )
+{
+	Word32 i, j;
+	Word16 hi, lo;
+	Word16 Kh, Kl;                         /* reflection coefficient; hi and lo           */
+	Word16 alp_h, alp_l, alp_exp;          /* Prediction gain; hi lo and exponent         */
+	Word16 Ah[M + 1], Al[M + 1];           /* LPC coef. in double prec.                   */
+	Word16 Anh[M + 1], Anl[M + 1];         /* LPC coef.for next iteration in double prec. */
+	Word32 t0, t1, t2;                     /* temporary variable                          */
+	Word16 *old_A, *old_rc;
+
+	/* Last A(z) for case of unstable filter */
+	old_A = mem;
+	old_rc = mem + M;
+
+	/* K = A[1] = -R[1] / R[0] */
+
+	t1 = ((Rh[1] << 16) + (Rl[1] << 1));   /* R[1] in Q31 */
+	t2 = L_abs(t1);                        /* abs R[1]         */
+	t0 = Div_32(t2, Rh[0], Rl[0]);         /* R[1]/R[0] in Q31 */
+	if (t1 > 0)
+		t0 = -t0;                          /* -R[1]/R[0]       */
+
+	Kh = t0 >> 16;
+	Kl = (t0 & 0xffff)>>1;
+	rc[0] = Kh;
+	t0 = (t0 >> 4);                        /* A[1] in Q27      */
+
+	Ah[1] = t0 >> 16;
+	Al[1] = (t0 & 0xffff)>>1;
+
+	/* Alpha = R[0] * (1-K**2) */
+	t0 = Mpy_32(Kh, Kl, Kh, Kl);           /* K*K      in Q31 */
+	t0 = L_abs(t0);                        /* Some case <0 !! */
+	t0 = vo_L_sub((Word32) 0x7fffffffL, t0);  /* 1 - K*K  in Q31 */
+
+	hi = t0 >> 16;
+	lo = (t0 & 0xffff)>>1;
+
+	t0 = Mpy_32(Rh[0], Rl[0], hi, lo);     /* Alpha in Q31    */
+
+	/* Normalize Alpha */
+	alp_exp = norm_l(t0);
+	t0 = (t0 << alp_exp);
+
+	alp_h = t0 >> 16;
+	alp_l = (t0 & 0xffff)>>1;
+	/*--------------------------------------*
+	 * ITERATIONS  I=2 to M                 *
+	 *--------------------------------------*/
+	for (i = 2; i <= M; i++)
+	{
+		/* t0 = SUM ( R[j]*A[i-j] ,j=1,i-1 ) +  R[i] */
+		t0 = 0;
+		for (j = 1; j < i; j++)
+			t0 = vo_L_add(t0, Mpy_32(Rh[j], Rl[j], Ah[i - j], Al[i - j]));
+
+		t0 = t0 << 4;                 /* result in Q27 -> convert to Q31 */
+		/* No overflow possible            */
+		t1 = ((Rh[i] << 16) + (Rl[i] << 1));
+		t0 = vo_L_add(t0, t1);                /* add R[i] in Q31                 */
+
+		/* K = -t0 / Alpha */
+		t1 = L_abs(t0);
+		t2 = Div_32(t1, alp_h, alp_l);     /* abs(t0)/Alpha                   */
+		if (t0 > 0)
+			t2 = -t2;                   /* K =-t0/Alpha                    */
+		t2 = (t2 << alp_exp);           /* denormalize; compare to Alpha   */
+
+		Kh = t2 >> 16;
+		Kl = (t2 & 0xffff)>>1;
+
+		rc[i - 1] = Kh;
+		/* Test for unstable filter. If unstable keep old A(z) */
+		if (abs_s(Kh) > 32750)
+		{
+			A[0] = 4096;                    /* Ai[0] not stored (always 1.0) */
+			for (j = 0; j < M; j++)
+			{
+				A[j + 1] = old_A[j];
+			}
+			rc[0] = old_rc[0];             /* only two rc coefficients are needed */
+			rc[1] = old_rc[1];
+			return;
+		}
+		/*------------------------------------------*
+		 *  Compute new LPC coeff. -> An[i]         *
+		 *  An[j]= A[j] + K*A[i-j]     , j=1 to i-1 *
+		 *  An[i]= K                                *
+		 *------------------------------------------*/
+		for (j = 1; j < i; j++)
+		{
+			t0 = Mpy_32(Kh, Kl, Ah[i - j], Al[i - j]);
+			t0 = vo_L_add(t0, ((Ah[j] << 16) + (Al[j] << 1)));
+			Anh[j] = t0 >> 16;
+			Anl[j] = (t0 & 0xffff)>>1;
+		}
+		t2 = (t2 >> 4);                 /* t2 = K in Q31 ->convert to Q27  */
+
+		VO_L_Extract(t2, &Anh[i], &Anl[i]);   /* An[i] in Q27                    */
+
+		/* Alpha = Alpha * (1-K**2) */
+		t0 = Mpy_32(Kh, Kl, Kh, Kl);               /* K*K      in Q31 */
+		t0 = L_abs(t0);                            /* Some case <0 !! */
+		t0 = vo_L_sub((Word32) 0x7fffffffL, t0);   /* 1 - K*K  in Q31 */
+		hi = t0 >> 16;
+		lo = (t0 & 0xffff)>>1;
+		t0 = Mpy_32(alp_h, alp_l, hi, lo); /* Alpha in Q31    */
+
+		/* Normalize Alpha */
+		j = norm_l(t0);
+		t0 = (t0 << j);
+		alp_h = t0 >> 16;
+		alp_l = (t0 & 0xffff)>>1;
+		alp_exp += j;         /* Add normalization to alp_exp */
+
+		/* A[j] = An[j] */
+		for (j = 1; j <= i; j++)
+		{
+			Ah[j] = Anh[j];
+			Al[j] = Anl[j];
+		}
+	}
+	/* Truncate A[i] in Q27 to Q12 with rounding */
+	A[0] = 4096;
+	for (i = 1; i <= M; i++)
+	{
+		t0 = (Ah[i] << 16) + (Al[i] << 1);
+		old_A[i - 1] = A[i] = vo_round((t0 << 1));
+	}
+	old_rc[0] = rc[0];
+	old_rc[1] = rc[1];
+
+	return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/log2.c b/media/libstagefright/codecs/amrwbenc/src/log2.c
index cd3d815..0f65541 100644
--- a/media/libstagefright/codecs/amrwbenc/src/log2.c
+++ b/media/libstagefright/codecs/amrwbenc/src/log2.c
@@ -1,111 +1,111 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*                                                                      *

-*      File             : log2.c                                       *

-*      Purpose          : Computes log2(L_x)                           *

-*                                                                      *

-************************************************************************/

-

-#include "log2.h"

-/********************************************************************************

-*                         INCLUDE FILES

-*********************************************************************************/

-#include "typedef.h"

-#include "basic_op.h"

-

-/*********************************************************************************

-*                         LOCAL VARIABLES AND TABLES

-**********************************************************************************/

-#include "log2_tab.h"     /* Table for Log2() */

-

-/*************************************************************************

-*

-*   FUNCTION:   Log2_norm()

-*

-*   PURPOSE:   Computes log2(L_x, exp),  where   L_x is positive and

-*              normalized, and exp is the normalisation exponent

-*              If L_x is negative or zero, the result is 0.

-*

-*   DESCRIPTION:

-*        The function Log2(L_x) is approximated by a table and linear

-*        interpolation. The following steps are used to compute Log2(L_x)

-*

-*           1- exponent = 30-norm_exponent

-*           2- i = bit25-b31 of L_x;  32<=i<=63  (because of normalization).

-*           3- a = bit10-b24

-*           4- i -=32

-*           5- fraction = table[i]<<16 - (table[i] - table[i+1]) * a * 2

-*

-*************************************************************************/

-

-void Log2_norm (

-		Word32 L_x,         /* (i) : input value (normalized)                    */

-		Word16 exp,         /* (i) : norm_l (L_x)                                */

-		Word16 *exponent,   /* (o) : Integer part of Log2.   (range: 0<=val<=30) */

-		Word16 *fraction    /* (o) : Fractional part of Log2. (range: 0<=val<1)  */

-	       )

-{

-	Word16 i, a, tmp;

-	Word32 L_y;

-	if (L_x <= (Word32) 0)

-	{

-		*exponent = 0; 

-		*fraction = 0; 

-		return;

-	}

-	*exponent = (30 - exp); 

-	L_x = (L_x >> 9);

-	i = extract_h (L_x);                /* Extract b25-b31 */

-	L_x = (L_x >> 1);

-	a = (Word16)(L_x);                /* Extract b10-b24 of fraction */

-	a = (Word16)(a & (Word16)0x7fff);

-	i -= 32;

-	L_y = L_deposit_h (table[i]);       /* table[i] << 16        */

-	tmp = vo_sub(table[i], table[i + 1]); /* table[i] - table[i+1] */

-	L_y = vo_L_msu (L_y, tmp, a);          /* L_y -= tmp*a*2        */

-	*fraction = extract_h (L_y); 

-

-	return;

-}

-

-/*************************************************************************

-*

-*   FUNCTION:   Log2()

-*

-*   PURPOSE:   Computes log2(L_x),  where   L_x is positive.

-*              If L_x is negative or zero, the result is 0.

-*

-*   DESCRIPTION:

-*        normalizes L_x and then calls Log2_norm().

-*

-*************************************************************************/

-

-void Log2 (

-		Word32 L_x,         /* (i) : input value                                 */

-		Word16 *exponent,   /* (o) : Integer part of Log2.   (range: 0<=val<=30) */

-		Word16 *fraction    /* (o) : Fractional part of Log2. (range: 0<=val<1) */

-	  )

-{

-	Word16 exp;

-

-	exp = norm_l(L_x);

-	Log2_norm ((L_x << exp), exp, exponent, fraction);

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*                                                                      *
+*      File             : log2.c                                       *
+*      Purpose          : Computes log2(L_x)                           *
+*                                                                      *
+************************************************************************/
+
+#include "log2.h"
+/********************************************************************************
+*                         INCLUDE FILES
+*********************************************************************************/
+#include "typedef.h"
+#include "basic_op.h"
+
+/*********************************************************************************
+*                         LOCAL VARIABLES AND TABLES
+**********************************************************************************/
+#include "log2_tab.h"     /* Table for Log2() */
+
+/*************************************************************************
+*
+*   FUNCTION:   Log2_norm()
+*
+*   PURPOSE:   Computes log2(L_x, exp),  where   L_x is positive and
+*              normalized, and exp is the normalisation exponent
+*              If L_x is negative or zero, the result is 0.
+*
+*   DESCRIPTION:
+*        The function Log2(L_x) is approximated by a table and linear
+*        interpolation. The following steps are used to compute Log2(L_x)
+*
+*           1- exponent = 30-norm_exponent
+*           2- i = bit25-b31 of L_x;  32<=i<=63  (because of normalization).
+*           3- a = bit10-b24
+*           4- i -=32
+*           5- fraction = table[i]<<16 - (table[i] - table[i+1]) * a * 2
+*
+*************************************************************************/
+
+void Log2_norm (
+		Word32 L_x,         /* (i) : input value (normalized)                    */
+		Word16 exp,         /* (i) : norm_l (L_x)                                */
+		Word16 *exponent,   /* (o) : Integer part of Log2.   (range: 0<=val<=30) */
+		Word16 *fraction    /* (o) : Fractional part of Log2. (range: 0<=val<1)  */
+	       )
+{
+	Word16 i, a, tmp;
+	Word32 L_y;
+	if (L_x <= (Word32) 0)
+	{
+		*exponent = 0;
+		*fraction = 0;
+		return;
+	}
+	*exponent = (30 - exp);
+	L_x = (L_x >> 9);
+	i = extract_h (L_x);                /* Extract b25-b31 */
+	L_x = (L_x >> 1);
+	a = (Word16)(L_x);                /* Extract b10-b24 of fraction */
+	a = (Word16)(a & (Word16)0x7fff);
+	i -= 32;
+	L_y = L_deposit_h (table[i]);       /* table[i] << 16        */
+	tmp = vo_sub(table[i], table[i + 1]); /* table[i] - table[i+1] */
+	L_y = vo_L_msu (L_y, tmp, a);          /* L_y -= tmp*a*2        */
+	*fraction = extract_h (L_y);
+
+	return;
+}
+
+/*************************************************************************
+*
+*   FUNCTION:   Log2()
+*
+*   PURPOSE:   Computes log2(L_x),  where   L_x is positive.
+*              If L_x is negative or zero, the result is 0.
+*
+*   DESCRIPTION:
+*        normalizes L_x and then calls Log2_norm().
+*
+*************************************************************************/
+
+void Log2 (
+		Word32 L_x,         /* (i) : input value                                 */
+		Word16 *exponent,   /* (o) : Integer part of Log2.   (range: 0<=val<=30) */
+		Word16 *fraction    /* (o) : Fractional part of Log2. (range: 0<=val<1) */
+	  )
+{
+	Word16 exp;
+
+	exp = norm_l(L_x);
+	Log2_norm ((L_x << exp), exp, exponent, fraction);
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/lp_dec2.c b/media/libstagefright/codecs/amrwbenc/src/lp_dec2.c
index 63b746b..1d5d076 100644
--- a/media/libstagefright/codecs/amrwbenc/src/lp_dec2.c
+++ b/media/libstagefright/codecs/amrwbenc/src/lp_dec2.c
@@ -1,70 +1,70 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*       File: lp_dec2.c                                                *

-*                                                                      *

-*	Description:Decimate a vector by 2 with 2nd order fir filter   *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "cnst.h"

-

-#define L_FIR  5

-#define L_MEM  (L_FIR-2)

-

-/* static float h_fir[L_FIR] = {0.13, 0.23, 0.28, 0.23, 0.13}; */

-/* fixed-point: sum of coef = 32767 to avoid overflow on DC */

-static Word16 h_fir[L_FIR] = {4260, 7536, 9175, 7536, 4260};

-

-void LP_Decim2(

-		Word16 x[],                           /* in/out: signal to process         */

-		Word16 l,                             /* input : size of filtering         */

-		Word16 mem[]                          /* in/out: memory (size=3)           */

-	      )

-{

-	Word16 *p_x, x_buf[L_FRAME + L_MEM];

-	Word32 i, j;

-	Word32 L_tmp;

-	/* copy initial filter states into buffer */

-	p_x = x_buf;                           

-	for (i = 0; i < L_MEM; i++)

-	{

-		*p_x++ = mem[i];  

-		mem[i] = x[l - L_MEM + i];  

-	}

-	for (i = 0; i < l; i++)

-	{

-		*p_x++ = x[i];                     

-	}

-	for (i = 0, j = 0; i < l; i += 2, j++)

-	{

-		p_x = &x_buf[i];  

-		L_tmp  = ((*p_x++) * h_fir[0]);

-		L_tmp += ((*p_x++) * h_fir[1]);

-		L_tmp += ((*p_x++) * h_fir[2]);

-		L_tmp += ((*p_x++) * h_fir[3]);

-		L_tmp += ((*p_x++) * h_fir[4]);

-		x[j] = (L_tmp + 0x4000)>>15;              

-	}

-	return;

-}

-

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*       File: lp_dec2.c                                                *
+*                                                                      *
+*	Description:Decimate a vector by 2 with 2nd order fir filter   *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "cnst.h"
+
+#define L_FIR  5
+#define L_MEM  (L_FIR-2)
+
+/* static float h_fir[L_FIR] = {0.13, 0.23, 0.28, 0.23, 0.13}; */
+/* fixed-point: sum of coef = 32767 to avoid overflow on DC */
+static Word16 h_fir[L_FIR] = {4260, 7536, 9175, 7536, 4260};
+
+void LP_Decim2(
+		Word16 x[],                           /* in/out: signal to process         */
+		Word16 l,                             /* input : size of filtering         */
+		Word16 mem[]                          /* in/out: memory (size=3)           */
+	      )
+{
+	Word16 *p_x, x_buf[L_FRAME + L_MEM];
+	Word32 i, j;
+	Word32 L_tmp;
+	/* copy initial filter states into buffer */
+	p_x = x_buf;
+	for (i = 0; i < L_MEM; i++)
+	{
+		*p_x++ = mem[i];
+		mem[i] = x[l - L_MEM + i];
+	}
+	for (i = 0; i < l; i++)
+	{
+		*p_x++ = x[i];
+	}
+	for (i = 0, j = 0; i < l; i += 2, j++)
+	{
+		p_x = &x_buf[i];
+		L_tmp  = ((*p_x++) * h_fir[0]);
+		L_tmp += ((*p_x++) * h_fir[1]);
+		L_tmp += ((*p_x++) * h_fir[2]);
+		L_tmp += ((*p_x++) * h_fir[3]);
+		L_tmp += ((*p_x++) * h_fir[4]);
+		x[j] = (L_tmp + 0x4000)>>15;
+	}
+	return;
+}
+
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/math_op.c b/media/libstagefright/codecs/amrwbenc/src/math_op.c
index 1c95ed0..7affbb2 100644
--- a/media/libstagefright/codecs/amrwbenc/src/math_op.c
+++ b/media/libstagefright/codecs/amrwbenc/src/math_op.c
@@ -1,219 +1,219 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/*___________________________________________________________________________

-|                                                                           |

-|  This file contains mathematic operations in fixed point.                 |

-|                                                                           |

-|  Isqrt()              : inverse square root (16 bits precision).          |

-|  Pow2()               : 2^x  (16 bits precision).                         |

-|  Log2()               : log2 (16 bits precision).                         |

-|  Dot_product()        : scalar product of <x[],y[]>                       |

-|                                                                           |

-|  These operations are not standard double precision operations.           |

-|  They are used where low complexity is important and the full 32 bits     |

-|  precision is not necessary. For example, the function Div_32() has a     |

-|  24 bits precision which is enough for our purposes.                      |

-|                                                                           |

-|  In this file, the values use theses representations:                     |

-|                                                                           |

-|  Word32 L_32     : standard signed 32 bits format                         |

-|  Word16 hi, lo   : L_32 = hi<<16 + lo<<1  (DPF - Double Precision Format) |

-|  Word32 frac, Word16 exp : L_32 = frac << exp-31  (normalised format)     |

-|  Word16 int, frac        : L_32 = int.frac        (fractional format)     |

-|___________________________________________________________________________|

-*/

-#include "typedef.h"

-#include "basic_op.h"

-#include "math_op.h"

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : Isqrt                                                   |

-|                                                                           |

-|       Compute 1/sqrt(L_x).                                                |

-|       if L_x is negative or zero, result is 1 (7fffffff).                 |

-|---------------------------------------------------------------------------|

-|  Algorithm:                                                               |

-|                                                                           |

-|   1- Normalization of L_x.                                                |

-|   2- call Isqrt_n(L_x, exponant)                                          |

-|   3- L_y = L_x << exponant                                                |

-|___________________________________________________________________________|

-*/

-Word32 Isqrt(                              /* (o) Q31 : output value (range: 0<=val<1)         */

-		Word32 L_x                            /* (i) Q0  : input value  (range: 0<=val<=7fffffff) */

-	    )

-{

-	Word16 exp;

-	Word32 L_y;

-	exp = norm_l(L_x);

-	L_x = (L_x << exp);                 /* L_x is normalized */

-	exp = (31 - exp);

-	Isqrt_n(&L_x, &exp);

-	L_y = (L_x << exp);                 /* denormalization   */

-	return (L_y);

-}

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : Isqrt_n                                                 |

-|                                                                           |

-|       Compute 1/sqrt(value).                                              |

-|       if value is negative or zero, result is 1 (frac=7fffffff, exp=0).   |

-|---------------------------------------------------------------------------|

-|  Algorithm:                                                               |

-|                                                                           |

-|   The function 1/sqrt(value) is approximated by a table and linear        |

-|   interpolation.                                                          |

-|                                                                           |

-|   1- If exponant is odd then shift fraction right once.                   |

-|   2- exponant = -((exponant-1)>>1)                                        |

-|   3- i = bit25-b30 of fraction, 16 <= i <= 63 ->because of normalization. |

-|   4- a = bit10-b24                                                        |

-|   5- i -=16                                                               |

-|   6- fraction = table[i]<<16 - (table[i] - table[i+1]) * a * 2            |

-|___________________________________________________________________________|

-*/

-static Word16 table_isqrt[49] =

-{

-	32767, 31790, 30894, 30070, 29309, 28602, 27945, 27330, 26755, 26214,

-	25705, 25225, 24770, 24339, 23930, 23541, 23170, 22817, 22479, 22155,

-	21845, 21548, 21263, 20988, 20724, 20470, 20225, 19988, 19760, 19539,

-	19326, 19119, 18919, 18725, 18536, 18354, 18176, 18004, 17837, 17674,

-	17515, 17361, 17211, 17064, 16921, 16782, 16646, 16514, 16384

-};

-

-void Isqrt_n(

-		Word32 * frac,                        /* (i/o) Q31: normalized value (1.0 < frac <= 0.5) */

-		Word16 * exp                          /* (i/o)    : exponent (value = frac x 2^exponent) */

-	    )

-{

-	Word16 i, a, tmp;

-

-	if (*frac <= (Word32) 0)

-	{

-		*exp = 0;                          

-		*frac = 0x7fffffffL;               

-		return;

-	}

-

-	if((*exp & 1) == 1)                       /*If exponant odd -> shift right */

-		*frac = (*frac) >> 1;

-

-	*exp = negate((*exp - 1) >> 1);   

-

-	*frac = (*frac >> 9);               

-	i = extract_h(*frac);                  /* Extract b25-b31 */

-	*frac = (*frac >> 1);              

-	a = (Word16)(*frac);                  /* Extract b10-b24 */

-	a = (Word16) (a & (Word16) 0x7fff);    

-	i -= 16;

-	*frac = L_deposit_h(table_isqrt[i]);   /* table[i] << 16         */

-	tmp = vo_sub(table_isqrt[i], table_isqrt[i + 1]);      /* table[i] - table[i+1]) */

-	*frac = vo_L_msu(*frac, tmp, a);          /* frac -=  tmp*a*2       */

-

-	return;

-}

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : Pow2()                                                  |

-|                                                                           |

-|     L_x = pow(2.0, exponant.fraction)         (exponant = interger part)  |

-|         = pow(2.0, 0.fraction) << exponant                                |

-|---------------------------------------------------------------------------|

-|  Algorithm:                                                               |

-|                                                                           |

-|   The function Pow2(L_x) is approximated by a table and linear            |

-|   interpolation.                                                          |

-|                                                                           |

-|   1- i = bit10-b15 of fraction,   0 <= i <= 31                            |

-|   2- a = bit0-b9   of fraction                                            |

-|   3- L_x = table[i]<<16 - (table[i] - table[i+1]) * a * 2                 |

-|   4- L_x = L_x >> (30-exponant)     (with rounding)                       |

-|___________________________________________________________________________|

-*/

-static Word16 table_pow2[33] =

-{

-	16384, 16743, 17109, 17484, 17867, 18258, 18658, 19066, 19484, 19911,

-	20347, 20792, 21247, 21713, 22188, 22674, 23170, 23678, 24196, 24726,

-	25268, 25821, 26386, 26964, 27554, 28158, 28774, 29405, 30048, 30706,

-	31379, 32066, 32767

-};

-

-Word32 Pow2(                               /* (o) Q0  : result       (range: 0<=val<=0x7fffffff) */

-		Word16 exponant,                      /* (i) Q0  : Integer part.      (range: 0<=val<=30)   */

-		Word16 fraction                       /* (i) Q15 : Fractionnal part.  (range: 0.0<=val<1.0) */

-	   )

-{

-	Word16 exp, i, a, tmp;

-	Word32 L_x;

-

-	L_x = vo_L_mult(fraction, 32);            /* L_x = fraction<<6           */

-	i = extract_h(L_x);                    /* Extract b10-b16 of fraction */

-	L_x =L_x >> 1;

-	a = (Word16)(L_x);                    /* Extract b0-b9   of fraction */

-	a = (Word16) (a & (Word16) 0x7fff); 

-

-	L_x = L_deposit_h(table_pow2[i]);      /* table[i] << 16        */

-	tmp = vo_sub(table_pow2[i], table_pow2[i + 1]);        /* table[i] - table[i+1] */

-	L_x -= (tmp * a)<<1;              /* L_x -= tmp*a*2        */

-

-	exp = vo_sub(30, exponant);

-	L_x = vo_L_shr_r(L_x, exp);

-

-	return (L_x);

-}

-

-/*___________________________________________________________________________

-|                                                                           |

-|   Function Name : Dot_product12()                                         |

-|                                                                           |

-|       Compute scalar product of <x[],y[]> using accumulator.              |

-|                                                                           |

-|       The result is normalized (in Q31) with exponent (0..30).            |

-|---------------------------------------------------------------------------|

-|  Algorithm:                                                               |

-|                                                                           |

-|       dot_product = sum(x[i]*y[i])     i=0..N-1                           |

-|___________________________________________________________________________|

-*/

-

-Word32 Dot_product12(                      /* (o) Q31: normalized result (1 < val <= -1) */

-		Word16 x[],                           /* (i) 12bits: x vector                       */

-		Word16 y[],                           /* (i) 12bits: y vector                       */

-		Word16 lg,                            /* (i)    : vector length                     */

-		Word16 * exp                          /* (o)    : exponent of result (0..+30)       */

-		)

-{

-	Word16 sft;

-	Word32 i, L_sum;

-	L_sum = 0;

-	for (i = 0; i < lg; i++)

-	{

-		L_sum += x[i] * y[i];

-	}

-	L_sum = (L_sum << 1) + 1;

-	/* Normalize acc in Q31 */

-	sft = norm_l(L_sum);

-	L_sum = L_sum << sft;

-	*exp = 30 - sft;            /* exponent = 0..30 */

-	return (L_sum);

-

-}

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/*___________________________________________________________________________
+|                                                                           |
+|  This file contains mathematic operations in fixed point.                 |
+|                                                                           |
+|  Isqrt()              : inverse square root (16 bits precision).          |
+|  Pow2()               : 2^x  (16 bits precision).                         |
+|  Log2()               : log2 (16 bits precision).                         |
+|  Dot_product()        : scalar product of <x[],y[]>                       |
+|                                                                           |
+|  These operations are not standard double precision operations.           |
+|  They are used where low complexity is important and the full 32 bits     |
+|  precision is not necessary. For example, the function Div_32() has a     |
+|  24 bits precision which is enough for our purposes.                      |
+|                                                                           |
+|  In this file, the values use theses representations:                     |
+|                                                                           |
+|  Word32 L_32     : standard signed 32 bits format                         |
+|  Word16 hi, lo   : L_32 = hi<<16 + lo<<1  (DPF - Double Precision Format) |
+|  Word32 frac, Word16 exp : L_32 = frac << exp-31  (normalised format)     |
+|  Word16 int, frac        : L_32 = int.frac        (fractional format)     |
+|___________________________________________________________________________|
+*/
+#include "typedef.h"
+#include "basic_op.h"
+#include "math_op.h"
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : Isqrt                                                   |
+|                                                                           |
+|       Compute 1/sqrt(L_x).                                                |
+|       if L_x is negative or zero, result is 1 (7fffffff).                 |
+|---------------------------------------------------------------------------|
+|  Algorithm:                                                               |
+|                                                                           |
+|   1- Normalization of L_x.                                                |
+|   2- call Isqrt_n(L_x, exponant)                                          |
+|   3- L_y = L_x << exponant                                                |
+|___________________________________________________________________________|
+*/
+Word32 Isqrt(                              /* (o) Q31 : output value (range: 0<=val<1)         */
+		Word32 L_x                            /* (i) Q0  : input value  (range: 0<=val<=7fffffff) */
+	    )
+{
+	Word16 exp;
+	Word32 L_y;
+	exp = norm_l(L_x);
+	L_x = (L_x << exp);                 /* L_x is normalized */
+	exp = (31 - exp);
+	Isqrt_n(&L_x, &exp);
+	L_y = (L_x << exp);                 /* denormalization   */
+	return (L_y);
+}
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : Isqrt_n                                                 |
+|                                                                           |
+|       Compute 1/sqrt(value).                                              |
+|       if value is negative or zero, result is 1 (frac=7fffffff, exp=0).   |
+|---------------------------------------------------------------------------|
+|  Algorithm:                                                               |
+|                                                                           |
+|   The function 1/sqrt(value) is approximated by a table and linear        |
+|   interpolation.                                                          |
+|                                                                           |
+|   1- If exponant is odd then shift fraction right once.                   |
+|   2- exponant = -((exponant-1)>>1)                                        |
+|   3- i = bit25-b30 of fraction, 16 <= i <= 63 ->because of normalization. |
+|   4- a = bit10-b24                                                        |
+|   5- i -=16                                                               |
+|   6- fraction = table[i]<<16 - (table[i] - table[i+1]) * a * 2            |
+|___________________________________________________________________________|
+*/
+static Word16 table_isqrt[49] =
+{
+	32767, 31790, 30894, 30070, 29309, 28602, 27945, 27330, 26755, 26214,
+	25705, 25225, 24770, 24339, 23930, 23541, 23170, 22817, 22479, 22155,
+	21845, 21548, 21263, 20988, 20724, 20470, 20225, 19988, 19760, 19539,
+	19326, 19119, 18919, 18725, 18536, 18354, 18176, 18004, 17837, 17674,
+	17515, 17361, 17211, 17064, 16921, 16782, 16646, 16514, 16384
+};
+
+void Isqrt_n(
+		Word32 * frac,                        /* (i/o) Q31: normalized value (1.0 < frac <= 0.5) */
+		Word16 * exp                          /* (i/o)    : exponent (value = frac x 2^exponent) */
+	    )
+{
+	Word16 i, a, tmp;
+
+	if (*frac <= (Word32) 0)
+	{
+		*exp = 0;
+		*frac = 0x7fffffffL;
+		return;
+	}
+
+	if((*exp & 1) == 1)                       /*If exponant odd -> shift right */
+		*frac = (*frac) >> 1;
+
+	*exp = negate((*exp - 1) >> 1);
+
+	*frac = (*frac >> 9);
+	i = extract_h(*frac);                  /* Extract b25-b31 */
+	*frac = (*frac >> 1);
+	a = (Word16)(*frac);                  /* Extract b10-b24 */
+	a = (Word16) (a & (Word16) 0x7fff);
+	i -= 16;
+	*frac = L_deposit_h(table_isqrt[i]);   /* table[i] << 16         */
+	tmp = vo_sub(table_isqrt[i], table_isqrt[i + 1]);      /* table[i] - table[i+1]) */
+	*frac = vo_L_msu(*frac, tmp, a);          /* frac -=  tmp*a*2       */
+
+	return;
+}
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : Pow2()                                                  |
+|                                                                           |
+|     L_x = pow(2.0, exponant.fraction)         (exponant = interger part)  |
+|         = pow(2.0, 0.fraction) << exponant                                |
+|---------------------------------------------------------------------------|
+|  Algorithm:                                                               |
+|                                                                           |
+|   The function Pow2(L_x) is approximated by a table and linear            |
+|   interpolation.                                                          |
+|                                                                           |
+|   1- i = bit10-b15 of fraction,   0 <= i <= 31                            |
+|   2- a = bit0-b9   of fraction                                            |
+|   3- L_x = table[i]<<16 - (table[i] - table[i+1]) * a * 2                 |
+|   4- L_x = L_x >> (30-exponant)     (with rounding)                       |
+|___________________________________________________________________________|
+*/
+static Word16 table_pow2[33] =
+{
+	16384, 16743, 17109, 17484, 17867, 18258, 18658, 19066, 19484, 19911,
+	20347, 20792, 21247, 21713, 22188, 22674, 23170, 23678, 24196, 24726,
+	25268, 25821, 26386, 26964, 27554, 28158, 28774, 29405, 30048, 30706,
+	31379, 32066, 32767
+};
+
+Word32 Pow2(                               /* (o) Q0  : result       (range: 0<=val<=0x7fffffff) */
+		Word16 exponant,                      /* (i) Q0  : Integer part.      (range: 0<=val<=30)   */
+		Word16 fraction                       /* (i) Q15 : Fractionnal part.  (range: 0.0<=val<1.0) */
+	   )
+{
+	Word16 exp, i, a, tmp;
+	Word32 L_x;
+
+	L_x = vo_L_mult(fraction, 32);            /* L_x = fraction<<6           */
+	i = extract_h(L_x);                    /* Extract b10-b16 of fraction */
+	L_x =L_x >> 1;
+	a = (Word16)(L_x);                    /* Extract b0-b9   of fraction */
+	a = (Word16) (a & (Word16) 0x7fff);
+
+	L_x = L_deposit_h(table_pow2[i]);      /* table[i] << 16        */
+	tmp = vo_sub(table_pow2[i], table_pow2[i + 1]);        /* table[i] - table[i+1] */
+	L_x -= (tmp * a)<<1;              /* L_x -= tmp*a*2        */
+
+	exp = vo_sub(30, exponant);
+	L_x = vo_L_shr_r(L_x, exp);
+
+	return (L_x);
+}
+
+/*___________________________________________________________________________
+|                                                                           |
+|   Function Name : Dot_product12()                                         |
+|                                                                           |
+|       Compute scalar product of <x[],y[]> using accumulator.              |
+|                                                                           |
+|       The result is normalized (in Q31) with exponent (0..30).            |
+|---------------------------------------------------------------------------|
+|  Algorithm:                                                               |
+|                                                                           |
+|       dot_product = sum(x[i]*y[i])     i=0..N-1                           |
+|___________________________________________________________________________|
+*/
+
+Word32 Dot_product12(                      /* (o) Q31: normalized result (1 < val <= -1) */
+		Word16 x[],                           /* (i) 12bits: x vector                       */
+		Word16 y[],                           /* (i) 12bits: y vector                       */
+		Word16 lg,                            /* (i)    : vector length                     */
+		Word16 * exp                          /* (o)    : exponent of result (0..+30)       */
+		)
+{
+	Word16 sft;
+	Word32 i, L_sum;
+	L_sum = 0;
+	for (i = 0; i < lg; i++)
+	{
+		L_sum += x[i] * y[i];
+	}
+	L_sum = (L_sum << 1) + 1;
+	/* Normalize acc in Q31 */
+	sft = norm_l(L_sum);
+	L_sum = L_sum << sft;
+	*exp = 30 - sft;            /* exponent = 0..30 */
+	return (L_sum);
+
+}
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/mem_align.c b/media/libstagefright/codecs/amrwbenc/src/mem_align.c
index e58915a..a29baf3 100644
--- a/media/libstagefright/codecs/amrwbenc/src/mem_align.c
+++ b/media/libstagefright/codecs/amrwbenc/src/mem_align.c
@@ -27,7 +27,7 @@
 /*****************************************************************************
 *
 * function name: mem_malloc
-* description:  malloc the alignments memory 
+* description:  malloc the alignments memory
 * returns:      the point of the memory
 *
 **********************************************************************************/
diff --git a/media/libstagefright/codecs/amrwbenc/src/oper_32b.c b/media/libstagefright/codecs/amrwbenc/src/oper_32b.c
index 5f1523e..27cad76 100644
--- a/media/libstagefright/codecs/amrwbenc/src/oper_32b.c
+++ b/media/libstagefright/codecs/amrwbenc/src/oper_32b.c
@@ -1,223 +1,223 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/*****************************************************************************

- *  This file contains operations in double precision.                       *

- *  These operations are not standard double precision operations.           *

- *  They are used where single precision is not enough but the full 32 bits  *

- *  precision is not necessary. For example, the function Div_32() has a     *

- *  24 bits precision which is enough for our purposes.                      *

- *                                                                           *

- *  The double precision numbers use a special representation:               *

- *                                                                           *

- *     L_32 = hi<<16 + lo<<1                                                 *

- *                                                                           *

- *  L_32 is a 32 bit integer.                                                *

- *  hi and lo are 16 bit signed integers.                                    *

- *  As the low part also contains the sign, this allows fast multiplication. *

- *                                                                           *

- *      0x8000 0000 <= L_32 <= 0x7fff fffe.                                  *

- *                                                                           *

- *  We will use DPF (Double Precision Format )in this file to specify        *

- *  this special format.                                                     *

- *****************************************************************************

-*/

-#include "typedef.h"

-#include "basic_op.h"

-#include "oper_32b.h"

-

-/*****************************************************************************

- *                                                                           *

- *  Function L_Extract()                                                     *

- *                                                                           *

- *  Extract from a 32 bit integer two 16 bit DPF.                            *

- *                                                                           *

- *  Arguments:                                                               *

- *                                                                           *

- *   L_32      : 32 bit integer.                                             *

- *               0x8000 0000 <= L_32 <= 0x7fff ffff.                         *

- *   hi        : b16 to b31 of L_32                                          *

- *   lo        : (L_32 - hi<<16)>>1                                          *

- *****************************************************************************

-*/

-

-__inline void VO_L_Extract (Word32 L_32, Word16 *hi, Word16 *lo)

-{

-	*hi = (Word16)(L_32 >> 16);

-	*lo = (Word16)((L_32 & 0xffff) >> 1);

-	return;

-}

-

-/*****************************************************************************

- *                                                                           *

- *  Function L_Comp()                                                        *

- *                                                                           *

- *  Compose from two 16 bit DPF a 32 bit integer.                            *

- *                                                                           *

- *     L_32 = hi<<16 + lo<<1                                                 *

- *                                                                           *

- *  Arguments:                                                               *

- *                                                                           *

- *   hi        msb                                                           *

- *   lo        lsf (with sign)                                               *

- *                                                                           *

- *   Return Value :                                                          *

- *                                                                           *

- *             32 bit long signed integer (Word32) whose value falls in the  *

- *             range : 0x8000 0000 <= L_32 <= 0x7fff fff0.                   *

- *                                                                           *

- *****************************************************************************

-*/

-

-Word32 L_Comp (Word16 hi, Word16 lo)

-{

-	Word32 L_32;

-

-	L_32 = L_deposit_h (hi);

-

-	return (L_mac (L_32, lo, 1));       /* = hi<<16 + lo<<1 */

-}

-

-/*****************************************************************************

- * Function Mpy_32()                                                         *

- *                                                                           *

- *   Multiply two 32 bit integers (DPF). The result is divided by 2**31      *

- *                                                                           *

- *   L_32 = (hi1*hi2)<<1 + ( (hi1*lo2)>>15 + (lo1*hi2)>>15 )<<1              *

- *                                                                           *

- *   This operation can also be viewed as the multiplication of two Q31      *

- *   number and the result is also in Q31.                                   *

- *                                                                           *

- * Arguments:                                                                *

- *                                                                           *

- *  hi1         hi part of first number                                      *

- *  lo1         lo part of first number                                      *

- *  hi2         hi part of second number                                     *

- *  lo2         lo part of second number                                     *

- *                                                                           *

- *****************************************************************************

-*/

-

-__inline Word32  Mpy_32 (Word16 hi1, Word16 lo1, Word16 hi2, Word16 lo2)

-{

-	Word32 L_32;

-	L_32 = (hi1 * hi2);

-	L_32 += (hi1 * lo2) >> 15;

-	L_32 += (lo1 * hi2) >> 15;

-	L_32 <<= 1;

-

-	return (L_32);

-}

-

-/*****************************************************************************

- * Function Mpy_32_16()                                                      *

- *                                                                           *

- *   Multiply a 16 bit integer by a 32 bit (DPF). The result is divided      *

- *   by 2**15                                                                *

- *                                                                           *

- *                                                                           *

- *   L_32 = (hi1*lo2)<<1 + ((lo1*lo2)>>15)<<1                                *

- *                                                                           *

- * Arguments:                                                                *

- *                                                                           *

- *  hi          hi part of 32 bit number.                                    *

- *  lo          lo part of 32 bit number.                                    *

- *  n           16 bit number.                                               *

- *                                                                           *

- *****************************************************************************

-*/

-

-__inline Word32 Mpy_32_16 (Word16 hi, Word16 lo, Word16 n)

-{

-	Word32 L_32;

-

-	L_32 = (hi * n)<<1;

-	L_32 += (((lo * n)>>15)<<1);

-

-	return (L_32);

-}

-

-/*****************************************************************************

- *                                                                           *

- *   Function Name : Div_32                                                  *

- *                                                                           *

- *   Purpose :                                                               *

- *             Fractional integer division of two 32 bit numbers.            *

- *             L_num / L_denom.                                              *

- *             L_num and L_denom must be positive and L_num < L_denom.       *

- *             L_denom = denom_hi<<16 + denom_lo<<1                          *

- *             denom_hi is a normalize number.                               *

- *                                                                           *

- *   Inputs :                                                                *

- *                                                                           *

- *    L_num                                                                  *

- *             32 bit long signed integer (Word32) whose value falls in the  *

- *             range : 0x0000 0000 < L_num < L_denom                         *

- *                                                                           *

- *    L_denom = denom_hi<<16 + denom_lo<<1      (DPF)                        *

- *                                                                           *

- *       denom_hi                                                            *

- *             16 bit positive normalized integer whose value falls in the   *

- *             range : 0x4000 < hi < 0x7fff                                  *

- *       denom_lo                                                            *

- *             16 bit positive integer whose value falls in the              *

- *             range : 0 < lo < 0x7fff                                       *

- *                                                                           *

- *   Return Value :                                                          *

- *                                                                           *

- *    L_div                                                                  *

- *             32 bit long signed integer (Word32) whose value falls in the  *

- *             range : 0x0000 0000 <= L_div <= 0x7fff ffff.                  *

- *                                                                           *

- *  Algorithm:                                                               *

- *                                                                           *

- *  - find = 1/L_denom.                                                      *

- *      First approximation: approx = 1 / denom_hi                           *

- *      1/L_denom = approx * (2.0 - L_denom * approx )                       *

- *                                                                           *

- *  -  result = L_num * (1/L_denom)                                          *

- *****************************************************************************

-*/

-

-Word32 Div_32 (Word32 L_num, Word16 denom_hi, Word16 denom_lo)

-{

-	Word16 approx, hi, lo, n_hi, n_lo;

-	Word32 L_32;

-

-	/* First approximation: 1 / L_denom = 1/denom_hi */

-

-	approx = div_s ((Word16) 0x3fff, denom_hi);

-

-	/* 1/L_denom = approx * (2.0 - L_denom * approx) */

-

-	L_32 = Mpy_32_16 (denom_hi, denom_lo, approx);

-

-	L_32 = L_sub ((Word32) 0x7fffffffL, L_32);

-	hi = L_32 >> 16;

-	lo = (L_32 & 0xffff) >> 1;

-

-	L_32 = Mpy_32_16 (hi, lo, approx);

-

-	/* L_num * (1/L_denom) */

-	hi = L_32 >> 16;

-	lo = (L_32 & 0xffff) >> 1;

-	VO_L_Extract (L_num, &n_hi, &n_lo);

-	L_32 = Mpy_32 (n_hi, n_lo, hi, lo);

-	L_32 = L_shl2(L_32, 2);

-

-	return (L_32);

-}

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/*****************************************************************************
+ *  This file contains operations in double precision.                       *
+ *  These operations are not standard double precision operations.           *
+ *  They are used where single precision is not enough but the full 32 bits  *
+ *  precision is not necessary. For example, the function Div_32() has a     *
+ *  24 bits precision which is enough for our purposes.                      *
+ *                                                                           *
+ *  The double precision numbers use a special representation:               *
+ *                                                                           *
+ *     L_32 = hi<<16 + lo<<1                                                 *
+ *                                                                           *
+ *  L_32 is a 32 bit integer.                                                *
+ *  hi and lo are 16 bit signed integers.                                    *
+ *  As the low part also contains the sign, this allows fast multiplication. *
+ *                                                                           *
+ *      0x8000 0000 <= L_32 <= 0x7fff fffe.                                  *
+ *                                                                           *
+ *  We will use DPF (Double Precision Format )in this file to specify        *
+ *  this special format.                                                     *
+ *****************************************************************************
+*/
+#include "typedef.h"
+#include "basic_op.h"
+#include "oper_32b.h"
+
+/*****************************************************************************
+ *                                                                           *
+ *  Function L_Extract()                                                     *
+ *                                                                           *
+ *  Extract from a 32 bit integer two 16 bit DPF.                            *
+ *                                                                           *
+ *  Arguments:                                                               *
+ *                                                                           *
+ *   L_32      : 32 bit integer.                                             *
+ *               0x8000 0000 <= L_32 <= 0x7fff ffff.                         *
+ *   hi        : b16 to b31 of L_32                                          *
+ *   lo        : (L_32 - hi<<16)>>1                                          *
+ *****************************************************************************
+*/
+
+__inline void VO_L_Extract (Word32 L_32, Word16 *hi, Word16 *lo)
+{
+	*hi = (Word16)(L_32 >> 16);
+	*lo = (Word16)((L_32 & 0xffff) >> 1);
+	return;
+}
+
+/*****************************************************************************
+ *                                                                           *
+ *  Function L_Comp()                                                        *
+ *                                                                           *
+ *  Compose from two 16 bit DPF a 32 bit integer.                            *
+ *                                                                           *
+ *     L_32 = hi<<16 + lo<<1                                                 *
+ *                                                                           *
+ *  Arguments:                                                               *
+ *                                                                           *
+ *   hi        msb                                                           *
+ *   lo        lsf (with sign)                                               *
+ *                                                                           *
+ *   Return Value :                                                          *
+ *                                                                           *
+ *             32 bit long signed integer (Word32) whose value falls in the  *
+ *             range : 0x8000 0000 <= L_32 <= 0x7fff fff0.                   *
+ *                                                                           *
+ *****************************************************************************
+*/
+
+Word32 L_Comp (Word16 hi, Word16 lo)
+{
+	Word32 L_32;
+
+	L_32 = L_deposit_h (hi);
+
+	return (L_mac (L_32, lo, 1));       /* = hi<<16 + lo<<1 */
+}
+
+/*****************************************************************************
+ * Function Mpy_32()                                                         *
+ *                                                                           *
+ *   Multiply two 32 bit integers (DPF). The result is divided by 2**31      *
+ *                                                                           *
+ *   L_32 = (hi1*hi2)<<1 + ( (hi1*lo2)>>15 + (lo1*hi2)>>15 )<<1              *
+ *                                                                           *
+ *   This operation can also be viewed as the multiplication of two Q31      *
+ *   number and the result is also in Q31.                                   *
+ *                                                                           *
+ * Arguments:                                                                *
+ *                                                                           *
+ *  hi1         hi part of first number                                      *
+ *  lo1         lo part of first number                                      *
+ *  hi2         hi part of second number                                     *
+ *  lo2         lo part of second number                                     *
+ *                                                                           *
+ *****************************************************************************
+*/
+
+__inline Word32  Mpy_32 (Word16 hi1, Word16 lo1, Word16 hi2, Word16 lo2)
+{
+	Word32 L_32;
+	L_32 = (hi1 * hi2);
+	L_32 += (hi1 * lo2) >> 15;
+	L_32 += (lo1 * hi2) >> 15;
+	L_32 <<= 1;
+
+	return (L_32);
+}
+
+/*****************************************************************************
+ * Function Mpy_32_16()                                                      *
+ *                                                                           *
+ *   Multiply a 16 bit integer by a 32 bit (DPF). The result is divided      *
+ *   by 2**15                                                                *
+ *                                                                           *
+ *                                                                           *
+ *   L_32 = (hi1*lo2)<<1 + ((lo1*lo2)>>15)<<1                                *
+ *                                                                           *
+ * Arguments:                                                                *
+ *                                                                           *
+ *  hi          hi part of 32 bit number.                                    *
+ *  lo          lo part of 32 bit number.                                    *
+ *  n           16 bit number.                                               *
+ *                                                                           *
+ *****************************************************************************
+*/
+
+__inline Word32 Mpy_32_16 (Word16 hi, Word16 lo, Word16 n)
+{
+	Word32 L_32;
+
+	L_32 = (hi * n)<<1;
+	L_32 += (((lo * n)>>15)<<1);
+
+	return (L_32);
+}
+
+/*****************************************************************************
+ *                                                                           *
+ *   Function Name : Div_32                                                  *
+ *                                                                           *
+ *   Purpose :                                                               *
+ *             Fractional integer division of two 32 bit numbers.            *
+ *             L_num / L_denom.                                              *
+ *             L_num and L_denom must be positive and L_num < L_denom.       *
+ *             L_denom = denom_hi<<16 + denom_lo<<1                          *
+ *             denom_hi is a normalize number.                               *
+ *                                                                           *
+ *   Inputs :                                                                *
+ *                                                                           *
+ *    L_num                                                                  *
+ *             32 bit long signed integer (Word32) whose value falls in the  *
+ *             range : 0x0000 0000 < L_num < L_denom                         *
+ *                                                                           *
+ *    L_denom = denom_hi<<16 + denom_lo<<1      (DPF)                        *
+ *                                                                           *
+ *       denom_hi                                                            *
+ *             16 bit positive normalized integer whose value falls in the   *
+ *             range : 0x4000 < hi < 0x7fff                                  *
+ *       denom_lo                                                            *
+ *             16 bit positive integer whose value falls in the              *
+ *             range : 0 < lo < 0x7fff                                       *
+ *                                                                           *
+ *   Return Value :                                                          *
+ *                                                                           *
+ *    L_div                                                                  *
+ *             32 bit long signed integer (Word32) whose value falls in the  *
+ *             range : 0x0000 0000 <= L_div <= 0x7fff ffff.                  *
+ *                                                                           *
+ *  Algorithm:                                                               *
+ *                                                                           *
+ *  - find = 1/L_denom.                                                      *
+ *      First approximation: approx = 1 / denom_hi                           *
+ *      1/L_denom = approx * (2.0 - L_denom * approx )                       *
+ *                                                                           *
+ *  -  result = L_num * (1/L_denom)                                          *
+ *****************************************************************************
+*/
+
+Word32 Div_32 (Word32 L_num, Word16 denom_hi, Word16 denom_lo)
+{
+	Word16 approx, hi, lo, n_hi, n_lo;
+	Word32 L_32;
+
+	/* First approximation: 1 / L_denom = 1/denom_hi */
+
+	approx = div_s ((Word16) 0x3fff, denom_hi);
+
+	/* 1/L_denom = approx * (2.0 - L_denom * approx) */
+
+	L_32 = Mpy_32_16 (denom_hi, denom_lo, approx);
+
+	L_32 = L_sub ((Word32) 0x7fffffffL, L_32);
+	hi = L_32 >> 16;
+	lo = (L_32 & 0xffff) >> 1;
+
+	L_32 = Mpy_32_16 (hi, lo, approx);
+
+	/* L_num * (1/L_denom) */
+	hi = L_32 >> 16;
+	lo = (L_32 & 0xffff) >> 1;
+	VO_L_Extract (L_num, &n_hi, &n_lo);
+	L_32 = Mpy_32 (n_hi, n_lo, hi, lo);
+	L_32 = L_shl2(L_32, 2);
+
+	return (L_32);
+}
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/p_med_ol.c b/media/libstagefright/codecs/amrwbenc/src/p_med_ol.c
index 39ee966..b8174b9 100644
--- a/media/libstagefright/codecs/amrwbenc/src/p_med_ol.c
+++ b/media/libstagefright/codecs/amrwbenc/src/p_med_ol.c
@@ -1,256 +1,256 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*      File: p_med_ol.c                                                *

-*                                                                      *

-*      Description: Compute the open loop pitch lag                    *

-*	            output: open loop pitch lag                        *                            

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "acelp.h"

-#include "oper_32b.h"

-#include "math_op.h"

-#include "p_med_ol.tab"

-

-Word16 Pitch_med_ol(

-		   Word16      wsp[],        /*   i: signal used to compute the open loop pitch*/  

-                                     /*      wsp[-pit_max] to wsp[-1] should be known */

-		   Coder_State *st,          /* i/o: codec global structure */

-		   Word16      L_frame       /*   i: length of frame to compute pitch */

-		)

-{

-	Word16 Tm;

-	Word16 hi, lo;

-	Word16 *ww, *we, *hp_wsp;

-	Word16 exp_R0, exp_R1, exp_R2;

-	Word32 i, j, max, R0, R1, R2;

-	Word16 *p1, *p2;

-	Word16 L_min = 17;                   /* minimum pitch lag: PIT_MIN / OPL_DECIM */

-	Word16 L_max = 115;                  /* maximum pitch lag: PIT_MAX / OPL_DECIM */

-	Word16 L_0 = st->old_T0_med;         /* old open-loop pitch */

-	Word16 *gain = &(st->ol_gain);       /* normalize correlation of hp_wsp for the lag */

-	Word16 *hp_wsp_mem = st->hp_wsp_mem; /* memory of the hypass filter for hp_wsp[] (lg = 9)*/

-	Word16 *old_hp_wsp = st->old_hp_wsp; /* hypass wsp[] */

-	Word16 wght_flg = st->ol_wght_flg;   /* is weighting function used */

-

-	ww = &corrweight[198];

-	we = &corrweight[98 + L_max - L_0];

-

-	max = MIN_32;                          

-	Tm = 0;                                

-	for (i = L_max; i > L_min; i--)

-	{

-		/* Compute the correlation */

-		R0 = 0;

-		p1 = wsp;

-		p2 = &wsp[-i];

-		for (j = 0; j < L_frame; j+=4)

-		{

-			R0 += vo_L_mult((*p1++), (*p2++));

-			R0 += vo_L_mult((*p1++), (*p2++));

-			R0 += vo_L_mult((*p1++), (*p2++));

-			R0 += vo_L_mult((*p1++), (*p2++));     

-		}

-		/* Weighting of the correlation function.   */

-		hi = R0>>16;

-		lo = (R0 & 0xffff)>>1;

-

-		R0 = Mpy_32_16(hi, lo, *ww);

-		ww--;

-

-		if ((L_0 > 0) && (wght_flg > 0))

-		{

-			/* Weight the neighbourhood of the old lag. */

-			hi = R0>>16;

-			lo = (R0 & 0xffff)>>1;

-			R0 = Mpy_32_16(hi, lo, *we);

-			we--;

-		}

-		if(R0 >= max)

-		{

-			max = R0;

-			Tm = i;

-		}

-	}

-

-	/* Hypass the wsp[] vector */

-	hp_wsp = old_hp_wsp + L_max;           

-	Hp_wsp(wsp, hp_wsp, L_frame, hp_wsp_mem);

-

-	/* Compute normalize correlation at delay Tm */

-	R0 = 0;                                

-	R1 = 0;                               

-	R2 = 0; 

-	p1 = hp_wsp;

-	p2 = hp_wsp - Tm;

-	for (j = 0; j < L_frame; j+=4)

-	{

-		R2 += vo_mult32(*p1, *p1);

-		R1 += vo_mult32(*p2, *p2);

-		R0 += vo_mult32(*p1++, *p2++);

-		R2 += vo_mult32(*p1, *p1);

-		R1 += vo_mult32(*p2, *p2);

-		R0 += vo_mult32(*p1++, *p2++);

-		R2 += vo_mult32(*p1, *p1);

-		R1 += vo_mult32(*p2, *p2);

-		R0 += vo_mult32(*p1++, *p2++);

-		R2 += vo_mult32(*p1, *p1);

-		R1 += vo_mult32(*p2, *p2);

-		R0 += vo_mult32(*p1++, *p2++);

-	}

-	R0 = R0 <<1;

-	R1 = (R1 <<1) + 1L;

-	R2 = (R2 <<1) + 1L;

-	/* gain = R0/ sqrt(R1*R2) */

-

-	exp_R0 = norm_l(R0);

-	R0 = (R0 << exp_R0);

-

-	exp_R1 = norm_l(R1);

-	R1 = (R1 << exp_R1);

-

-	exp_R2 = norm_l(R2);

-	R2 = (R2 << exp_R2);

-

-

-	R1 = vo_L_mult(vo_round(R1), vo_round(R2));

-

-	i = norm_l(R1);

-	R1 = (R1 << i);

-

-	exp_R1 += exp_R2;

-	exp_R1 += i;

-	exp_R1 = 62 - exp_R1;

-

-	Isqrt_n(&R1, &exp_R1);

-

-	R0 = vo_L_mult(voround(R0), voround(R1));

-	exp_R0 = 31 - exp_R0;

-	exp_R0 += exp_R1;

-

-	*gain = vo_round(L_shl(R0, exp_R0));

-

-	/* Shitf hp_wsp[] for next frame */

-

-	for (i = 0; i < L_max; i++)

-	{

-		old_hp_wsp[i] = old_hp_wsp[i + L_frame];

-	}

-

-	return (Tm);

-}

-

-/************************************************************************

-*  Function: median5                                                    *

-*                                                                       *

-*      Returns the median of the set {X[-2], X[-1],..., X[2]},          *

-*      whose elements are 16-bit integers.                              *

-*                                                                       *

-*  Input:                                                               *

-*      X[-2:2]   16-bit integers.                                       *

-*                                                                       *

-*  Return:                                                              *

-*      The median of {X[-2], X[-1],..., X[2]}.                          *

-************************************************************************/

-

-Word16 median5(Word16 x[])

-{

-	Word16 x1, x2, x3, x4, x5;

-	Word16 tmp;

-

-	x1 = x[-2];                            

-	x2 = x[-1];                            

-	x3 = x[0];                             

-	x4 = x[1];                             

-	x5 = x[2];                             

-

-	if (x2 < x1)

-	{

-		tmp = x1;

-		x1 = x2;

-		x2 = tmp;                          

-	}

-	if (x3 < x1)

-	{

-		tmp = x1;

-		x1 = x3;

-		x3 = tmp;                          

-	}

-	if (x4 < x1)

-	{

-		tmp = x1;

-		x1 = x4;

-		x4 = tmp;                          

-	}

-	if (x5 < x1)

-	{

-		x5 = x1;                           

-	}

-	if (x3 < x2)

-	{

-		tmp = x2;

-		x2 = x3;

-		x3 = tmp;                          

-	}

-	if (x4 < x2)

-	{

-		tmp = x2;

-		x2 = x4;

-		x4 = tmp;                          

-	}

-	if (x5 < x2)

-	{

-		x5 = x2;                           

-	}

-	if (x4 < x3)

-	{

-		x3 = x4;                           

-	}

-	if (x5 < x3)

-	{

-		x3 = x5;                           

-	}

-	return (x3);

-}

-

-

-Word16 Med_olag(                           /* output : median of  5 previous open-loop lags       */

-		Word16 prev_ol_lag,                /* input  : previous open-loop lag                     */

-		Word16 old_ol_lag[5]

-	       )

-{

-	Word32 i;

-

-	/* Use median of 5 previous open-loop lags as old lag */

-

-	for (i = 4; i > 0; i--)

-	{

-		old_ol_lag[i] = old_ol_lag[i - 1]; 

-	}

-

-	old_ol_lag[0] = prev_ol_lag;           

-

-	i = median5(&old_ol_lag[2]);

-

-	return i;

-

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*      File: p_med_ol.c                                                *
+*                                                                      *
+*      Description: Compute the open loop pitch lag                    *
+*	            output: open loop pitch lag                        *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "acelp.h"
+#include "oper_32b.h"
+#include "math_op.h"
+#include "p_med_ol.tab"
+
+Word16 Pitch_med_ol(
+		   Word16      wsp[],        /*   i: signal used to compute the open loop pitch*/
+                                     /*      wsp[-pit_max] to wsp[-1] should be known */
+		   Coder_State *st,          /* i/o: codec global structure */
+		   Word16      L_frame       /*   i: length of frame to compute pitch */
+		)
+{
+	Word16 Tm;
+	Word16 hi, lo;
+	Word16 *ww, *we, *hp_wsp;
+	Word16 exp_R0, exp_R1, exp_R2;
+	Word32 i, j, max, R0, R1, R2;
+	Word16 *p1, *p2;
+	Word16 L_min = 17;                   /* minimum pitch lag: PIT_MIN / OPL_DECIM */
+	Word16 L_max = 115;                  /* maximum pitch lag: PIT_MAX / OPL_DECIM */
+	Word16 L_0 = st->old_T0_med;         /* old open-loop pitch */
+	Word16 *gain = &(st->ol_gain);       /* normalize correlation of hp_wsp for the lag */
+	Word16 *hp_wsp_mem = st->hp_wsp_mem; /* memory of the hypass filter for hp_wsp[] (lg = 9)*/
+	Word16 *old_hp_wsp = st->old_hp_wsp; /* hypass wsp[] */
+	Word16 wght_flg = st->ol_wght_flg;   /* is weighting function used */
+
+	ww = &corrweight[198];
+	we = &corrweight[98 + L_max - L_0];
+
+	max = MIN_32;
+	Tm = 0;
+	for (i = L_max; i > L_min; i--)
+	{
+		/* Compute the correlation */
+		R0 = 0;
+		p1 = wsp;
+		p2 = &wsp[-i];
+		for (j = 0; j < L_frame; j+=4)
+		{
+			R0 += vo_L_mult((*p1++), (*p2++));
+			R0 += vo_L_mult((*p1++), (*p2++));
+			R0 += vo_L_mult((*p1++), (*p2++));
+			R0 += vo_L_mult((*p1++), (*p2++));
+		}
+		/* Weighting of the correlation function.   */
+		hi = R0>>16;
+		lo = (R0 & 0xffff)>>1;
+
+		R0 = Mpy_32_16(hi, lo, *ww);
+		ww--;
+
+		if ((L_0 > 0) && (wght_flg > 0))
+		{
+			/* Weight the neighbourhood of the old lag. */
+			hi = R0>>16;
+			lo = (R0 & 0xffff)>>1;
+			R0 = Mpy_32_16(hi, lo, *we);
+			we--;
+		}
+		if(R0 >= max)
+		{
+			max = R0;
+			Tm = i;
+		}
+	}
+
+	/* Hypass the wsp[] vector */
+	hp_wsp = old_hp_wsp + L_max;
+	Hp_wsp(wsp, hp_wsp, L_frame, hp_wsp_mem);
+
+	/* Compute normalize correlation at delay Tm */
+	R0 = 0;
+	R1 = 0;
+	R2 = 0;
+	p1 = hp_wsp;
+	p2 = hp_wsp - Tm;
+	for (j = 0; j < L_frame; j+=4)
+	{
+		R2 += vo_mult32(*p1, *p1);
+		R1 += vo_mult32(*p2, *p2);
+		R0 += vo_mult32(*p1++, *p2++);
+		R2 += vo_mult32(*p1, *p1);
+		R1 += vo_mult32(*p2, *p2);
+		R0 += vo_mult32(*p1++, *p2++);
+		R2 += vo_mult32(*p1, *p1);
+		R1 += vo_mult32(*p2, *p2);
+		R0 += vo_mult32(*p1++, *p2++);
+		R2 += vo_mult32(*p1, *p1);
+		R1 += vo_mult32(*p2, *p2);
+		R0 += vo_mult32(*p1++, *p2++);
+	}
+	R0 = R0 <<1;
+	R1 = (R1 <<1) + 1L;
+	R2 = (R2 <<1) + 1L;
+	/* gain = R0/ sqrt(R1*R2) */
+
+	exp_R0 = norm_l(R0);
+	R0 = (R0 << exp_R0);
+
+	exp_R1 = norm_l(R1);
+	R1 = (R1 << exp_R1);
+
+	exp_R2 = norm_l(R2);
+	R2 = (R2 << exp_R2);
+
+
+	R1 = vo_L_mult(vo_round(R1), vo_round(R2));
+
+	i = norm_l(R1);
+	R1 = (R1 << i);
+
+	exp_R1 += exp_R2;
+	exp_R1 += i;
+	exp_R1 = 62 - exp_R1;
+
+	Isqrt_n(&R1, &exp_R1);
+
+	R0 = vo_L_mult(voround(R0), voround(R1));
+	exp_R0 = 31 - exp_R0;
+	exp_R0 += exp_R1;
+
+	*gain = vo_round(L_shl(R0, exp_R0));
+
+	/* Shitf hp_wsp[] for next frame */
+
+	for (i = 0; i < L_max; i++)
+	{
+		old_hp_wsp[i] = old_hp_wsp[i + L_frame];
+	}
+
+	return (Tm);
+}
+
+/************************************************************************
+*  Function: median5                                                    *
+*                                                                       *
+*      Returns the median of the set {X[-2], X[-1],..., X[2]},          *
+*      whose elements are 16-bit integers.                              *
+*                                                                       *
+*  Input:                                                               *
+*      X[-2:2]   16-bit integers.                                       *
+*                                                                       *
+*  Return:                                                              *
+*      The median of {X[-2], X[-1],..., X[2]}.                          *
+************************************************************************/
+
+Word16 median5(Word16 x[])
+{
+	Word16 x1, x2, x3, x4, x5;
+	Word16 tmp;
+
+	x1 = x[-2];
+	x2 = x[-1];
+	x3 = x[0];
+	x4 = x[1];
+	x5 = x[2];
+
+	if (x2 < x1)
+	{
+		tmp = x1;
+		x1 = x2;
+		x2 = tmp;
+	}
+	if (x3 < x1)
+	{
+		tmp = x1;
+		x1 = x3;
+		x3 = tmp;
+	}
+	if (x4 < x1)
+	{
+		tmp = x1;
+		x1 = x4;
+		x4 = tmp;
+	}
+	if (x5 < x1)
+	{
+		x5 = x1;
+	}
+	if (x3 < x2)
+	{
+		tmp = x2;
+		x2 = x3;
+		x3 = tmp;
+	}
+	if (x4 < x2)
+	{
+		tmp = x2;
+		x2 = x4;
+		x4 = tmp;
+	}
+	if (x5 < x2)
+	{
+		x5 = x2;
+	}
+	if (x4 < x3)
+	{
+		x3 = x4;
+	}
+	if (x5 < x3)
+	{
+		x3 = x5;
+	}
+	return (x3);
+}
+
+
+Word16 Med_olag(                           /* output : median of  5 previous open-loop lags       */
+		Word16 prev_ol_lag,                /* input  : previous open-loop lag                     */
+		Word16 old_ol_lag[5]
+	       )
+{
+	Word32 i;
+
+	/* Use median of 5 previous open-loop lags as old lag */
+
+	for (i = 4; i > 0; i--)
+	{
+		old_ol_lag[i] = old_ol_lag[i - 1];
+	}
+
+	old_ol_lag[0] = prev_ol_lag;
+
+	i = median5(&old_ol_lag[2]);
+
+	return i;
+
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/pit_shrp.c b/media/libstagefright/codecs/amrwbenc/src/pit_shrp.c
index c8a227c..6f55b8f 100644
--- a/media/libstagefright/codecs/amrwbenc/src/pit_shrp.c
+++ b/media/libstagefright/codecs/amrwbenc/src/pit_shrp.c
@@ -1,49 +1,49 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*      File: pit_shrp.c                                                *

-*                                                                      *

-*      Description: Performs Pitch sharpening routine                  *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-

-void Pit_shrp(

-		Word16 * x,                           /* in/out: impulse response (or algebraic code) */

-		Word16 pit_lag,                       /* input : pitch lag                            */

-		Word16 sharp,                         /* input : pitch sharpening factor (Q15)        */

-		Word16 L_subfr                        /* input : subframe size                        */

-	     )

-{

-	Word32 i;

-	Word32 L_tmp;

-	Word16 *x_ptr = x + pit_lag;

-

-	for (i = pit_lag; i < L_subfr; i++)

-	{

-		L_tmp = (*x_ptr << 15);

-		L_tmp += *x++ * sharp;

-		*x_ptr++ = ((L_tmp + 0x4000)>>15);

-	}

-

-	return;

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*      File: pit_shrp.c                                                *
+*                                                                      *
+*      Description: Performs Pitch sharpening routine                  *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+
+void Pit_shrp(
+		Word16 * x,                           /* in/out: impulse response (or algebraic code) */
+		Word16 pit_lag,                       /* input : pitch lag                            */
+		Word16 sharp,                         /* input : pitch sharpening factor (Q15)        */
+		Word16 L_subfr                        /* input : subframe size                        */
+	     )
+{
+	Word32 i;
+	Word32 L_tmp;
+	Word16 *x_ptr = x + pit_lag;
+
+	for (i = pit_lag; i < L_subfr; i++)
+	{
+		L_tmp = (*x_ptr << 15);
+		L_tmp += *x++ * sharp;
+		*x_ptr++ = ((L_tmp + 0x4000)>>15);
+	}
+
+	return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/pitch_f4.c b/media/libstagefright/codecs/amrwbenc/src/pitch_f4.c
index c115b11b..0d66c31 100644
--- a/media/libstagefright/codecs/amrwbenc/src/pitch_f4.c
+++ b/media/libstagefright/codecs/amrwbenc/src/pitch_f4.c
@@ -1,324 +1,324 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*      File: pitch_f4.c                                                *

-*                                                                      *

-*      Description: Find the closed loop pitch period with             *

-*	            1/4 subsample resolution.                          *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "math_op.h"

-#include "acelp.h"

-#include "cnst.h"

-

-#define UP_SAMP      4

-#define L_INTERPOL1  4

-

-/* Local functions */

-

-#ifdef ASM_OPT

-void Norm_corr_asm(

-		Word16 exc[],                         /* (i)     : excitation buffer                     */

-		Word16 xn[],                          /* (i)     : target vector                         */

-		Word16 h[],                           /* (i) Q15 : impulse response of synth/wgt filters */

-		Word16 L_subfr,

-		Word16 t_min,                         /* (i)     : minimum value of pitch lag.           */

-		Word16 t_max,                         /* (i)     : maximum value of pitch lag.           */

-		Word16 corr_norm[]                    /* (o) Q15 : normalized correlation                */

-		);

-#else

-static void Norm_Corr(

-		Word16 exc[],                         /* (i)     : excitation buffer                     */

-		Word16 xn[],                          /* (i)     : target vector                         */

-		Word16 h[],                           /* (i) Q15 : impulse response of synth/wgt filters */

-		Word16 L_subfr,

-		Word16 t_min,                         /* (i)     : minimum value of pitch lag.           */

-		Word16 t_max,                         /* (i)     : maximum value of pitch lag.           */

-		Word16 corr_norm[]                    /* (o) Q15 : normalized correlation                */

-		);

-#endif

-

-static Word16 Interpol_4(                  /* (o)  : interpolated value  */

-		Word16 * x,                           /* (i)  : input vector        */

-		Word32 frac                           /* (i)  : fraction (-4..+3)   */

-		);

-

-

-Word16 Pitch_fr4(                          /* (o)     : pitch period.                         */

-		Word16 exc[],                         /* (i)     : excitation buffer                     */

-		Word16 xn[],                          /* (i)     : target vector                         */

-		Word16 h[],                           /* (i) Q15 : impulse response of synth/wgt filters */

-		Word16 t0_min,                        /* (i)     : minimum value in the searched range.  */

-		Word16 t0_max,                        /* (i)     : maximum value in the searched range.  */

-		Word16 * pit_frac,                    /* (o)     : chosen fraction (0, 1, 2 or 3).       */

-		Word16 i_subfr,                       /* (i)     : indicator for first subframe.         */

-		Word16 t0_fr2,                        /* (i)     : minimum value for resolution 1/2      */

-		Word16 t0_fr1,                        /* (i)     : minimum value for resolution 1        */

-		Word16 L_subfr                        /* (i)     : Length of subframe                    */

-		)

-{

-	Word32 fraction, i;

-	Word16 t_min, t_max;

-	Word16 max, t0, step, temp;

-	Word16 *corr;

-	Word16 corr_v[40];                     /* Total length = t0_max-t0_min+1+2*L_inter */

-

-	/* Find interval to compute normalized correlation */

-

-	t_min = t0_min - L_INTERPOL1;

-	t_max = t0_max + L_INTERPOL1;

-	corr = &corr_v[-t_min];

-	/* Compute normalized correlation between target and filtered excitation */

-#ifdef ASM_OPT               /* asm optimization branch */

-    Norm_corr_asm(exc, xn, h, L_subfr, t_min, t_max, corr);

-#else

-	Norm_Corr(exc, xn, h, L_subfr, t_min, t_max, corr);

-#endif 

-

-	/* Find integer pitch */

-

-	max = corr[t0_min];

-	t0 = t0_min;

-	for (i = t0_min + 1; i <= t0_max; i++)

-	{

-		if (corr[i] >= max)

-		{

-			max = corr[i];                 

-			t0 = i;                        

-		}

-	}

-	/* If first subframe and t0 >= t0_fr1, do not search fractionnal pitch */

-	if ((i_subfr == 0) && (t0 >= t0_fr1))

-	{

-		*pit_frac = 0;

-		return (t0);

-	}

-	/*------------------------------------------------------------------*

-	 * Search fractionnal pitch with 1/4 subsample resolution.          *

-	 * Test the fractions around t0 and choose the one which maximizes  *

-	 * the interpolated normalized correlation.                         *

-	 *------------------------------------------------------------------*/

-

-	step = 1;               /* 1/4 subsample resolution */

-	fraction = -3;

-	if ((t0_fr2 == PIT_MIN)||((i_subfr == 0) && (t0 >= t0_fr2)))

-	{

-		step = 2;              /* 1/2 subsample resolution */

-		fraction = -2;

-	}

-	if(t0 == t0_min)

-	{

-		fraction = 0;

-	}

-	max = Interpol_4(&corr[t0], fraction);

-

-	for (i = fraction + step; i <= 3; i += step)

-	{

-		temp = Interpol_4(&corr[t0], i);

-		if(temp > max)

-		{

-			max = temp;

-			fraction = i;

-		}

-	}

-	/* limit the fraction value in the interval [0,1,2,3] */

-	if (fraction < 0)

-	{

-		fraction += UP_SAMP;

-		t0 -= 1;

-	}

-	*pit_frac = fraction;

-	return (t0);

-}

-

-

-/***********************************************************************************

-* Function:  Norm_Corr()                                                            *

-*                                                                                   *

-* Description: Find the normalized correlation between the target vector and the    *

-* filtered past excitation.                                                         *

-* (correlation between target and filtered excitation divided by the                *

-*  square root of energy of target and filtered excitation).                        *

-************************************************************************************/

-#ifndef ASM_OPT

-static void Norm_Corr(

-		Word16 exc[],                         /* (i)     : excitation buffer                     */

-		Word16 xn[],                          /* (i)     : target vector                         */

-		Word16 h[],                           /* (i) Q15 : impulse response of synth/wgt filters */

-		Word16 L_subfr,

-		Word16 t_min,                         /* (i)     : minimum value of pitch lag.           */

-		Word16 t_max,                         /* (i)     : maximum value of pitch lag.           */

-		Word16 corr_norm[])                   /* (o) Q15 : normalized correlation                */

-{

-	Word32 i, k, t;

-	Word32 corr, exp_corr, norm, exp, scale;

-	Word16 exp_norm, excf[L_SUBFR], tmp;

-	Word32 L_tmp, L_tmp1, L_tmp2;

-

-	/* compute the filtered excitation for the first delay t_min */

-	k = -t_min;

-

-#ifdef ASM_OPT              /* asm optimization branch */

-	Convolve_asm(&exc[k], h, excf, 64);

-#else

-	Convolve(&exc[k], h, excf, 64);

-#endif

-

-	/* Compute rounded down 1/sqrt(energy of xn[]) */

-	L_tmp = 0; 

-	for (i = 0; i < 64; i+=4)

-	{

-		L_tmp += (xn[i] * xn[i]);

-		L_tmp += (xn[i+1] * xn[i+1]);

-		L_tmp += (xn[i+2] * xn[i+2]);

-		L_tmp += (xn[i+3] * xn[i+3]);

-	}

-

-	L_tmp = (L_tmp << 1) + 1;

-	exp = norm_l(L_tmp);

-	exp = (32 - exp);

-	//exp = exp + 2;                     /* energy of xn[] x 2 + rounded up     */

-	scale = -(exp >> 1);           /* (1<<scale) < 1/sqrt(energy rounded) */

-

-	/* loop for every possible period */

-

-	for (t = t_min; t <= t_max; t++)

-	{

-		/* Compute correlation between xn[] and excf[] */

-		L_tmp  = 0;  

-		L_tmp1 = 0;

-		for (i = 0; i < 64; i+=4)

-		{

-			L_tmp  += (xn[i] * excf[i]);

-			L_tmp1 += (excf[i] * excf[i]);

-			L_tmp  += (xn[i+1] * excf[i+1]);

-			L_tmp1 += (excf[i+1] * excf[i+1]);

-			L_tmp  += (xn[i+2] * excf[i+2]);

-			L_tmp1 += (excf[i+2] * excf[i+2]);

-			L_tmp  += (xn[i+3] * excf[i+3]);

-			L_tmp1 += (excf[i+3] * excf[i+3]);

-		}

-

-		L_tmp = (L_tmp << 1) + 1;

-		L_tmp1 = (L_tmp1 << 1) + 1;

-

-		exp = norm_l(L_tmp);

-		L_tmp = (L_tmp << exp);

-		exp_corr = (30 - exp);

-		corr = extract_h(L_tmp);

-

-		exp = norm_l(L_tmp1);

-		L_tmp = (L_tmp1 << exp);

-		exp_norm = (30 - exp);

-

-		Isqrt_n(&L_tmp, &exp_norm);

-		norm = extract_h(L_tmp);

-

-		/* Normalize correlation = correlation * (1/sqrt(energy)) */

-

-		L_tmp = vo_L_mult(corr, norm);

-

-		L_tmp2 = exp_corr + exp_norm + scale;

-		if(L_tmp2 < 0)

-		{

-			L_tmp2 = -L_tmp2;

-			L_tmp = L_tmp >> L_tmp2;

-		}

-		else

-		{

-			L_tmp = L_tmp << L_tmp2;

-		}

-

-		corr_norm[t] = vo_round(L_tmp);      

-		/* modify the filtered excitation excf[] for the next iteration */

-

-		if(t != t_max)

-		{

-			k = -(t + 1);

-			tmp = exc[k];

-			for (i = 63; i > 0; i--)

-			{

-				excf[i] = add1(vo_mult(tmp, h[i]), excf[i - 1]);

-			}

-			excf[0] = vo_mult(tmp, h[0]);

-		}

-	}

-	return;

-}

-

-#endif

-/************************************************************************************

-* Function: Interpol_4()                                                             *

-*                                                                                    *

-* Description: For interpolating the normalized correlation with 1/4 resolution.     *

-**************************************************************************************/

-

-/* 1/4 resolution interpolation filter (-3 dB at 0.791*fs/2) in Q14 */

-static Word16 inter4_1[4][8] =

-{

-	{-12, 420, -1732, 5429, 13418, -1242, 73, 32},

-	{-26, 455, -2142, 9910, 9910,  -2142, 455, -26},

-	{32,  73, -1242, 13418, 5429, -1732, 420, -12},

-	{206, -766, 1376, 14746, 1376, -766, 206, 0}

-};

-

-/*** Coefficients in floating point

-static float inter4_1[UP_SAMP*L_INTERPOL1+1] = {

-0.900000,

-0.818959,  0.604850,  0.331379,  0.083958,

--0.075795, -0.130717, -0.105685, -0.046774,

-0.004467,  0.027789,  0.025642,  0.012571,

-0.001927, -0.001571, -0.000753,  0.000000};

-***/

-

-static Word16 Interpol_4(                  /* (o)  : interpolated value  */

-		Word16 * x,                           /* (i)  : input vector        */

-		Word32 frac                           /* (i)  : fraction (-4..+3)   */

-		)

-{

-	Word16 sum;

-	Word32  k, L_sum;

-	Word16 *ptr;

-

-	if (frac < 0)

-	{

-		frac += UP_SAMP;

-		x--;

-	}

-	x = x - L_INTERPOL1 + 1;

-	k = UP_SAMP - 1 - frac;

-	ptr = &(inter4_1[k][0]);

-

-	L_sum  = vo_mult32(x[0], (*ptr++));

-	L_sum += vo_mult32(x[1], (*ptr++));

-	L_sum += vo_mult32(x[2], (*ptr++));

-	L_sum += vo_mult32(x[3], (*ptr++));

-	L_sum += vo_mult32(x[4], (*ptr++));  

-	L_sum += vo_mult32(x[5], (*ptr++));

-	L_sum += vo_mult32(x[6], (*ptr++));

-	L_sum += vo_mult32(x[7], (*ptr++));   

-

-	sum = extract_h(L_add(L_shl2(L_sum, 2), 0x8000));

-	return (sum);

-}

-

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*      File: pitch_f4.c                                                *
+*                                                                      *
+*      Description: Find the closed loop pitch period with             *
+*	            1/4 subsample resolution.                          *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "math_op.h"
+#include "acelp.h"
+#include "cnst.h"
+
+#define UP_SAMP      4
+#define L_INTERPOL1  4
+
+/* Local functions */
+
+#ifdef ASM_OPT
+void Norm_corr_asm(
+		Word16 exc[],                         /* (i)     : excitation buffer                     */
+		Word16 xn[],                          /* (i)     : target vector                         */
+		Word16 h[],                           /* (i) Q15 : impulse response of synth/wgt filters */
+		Word16 L_subfr,
+		Word16 t_min,                         /* (i)     : minimum value of pitch lag.           */
+		Word16 t_max,                         /* (i)     : maximum value of pitch lag.           */
+		Word16 corr_norm[]                    /* (o) Q15 : normalized correlation                */
+		);
+#else
+static void Norm_Corr(
+		Word16 exc[],                         /* (i)     : excitation buffer                     */
+		Word16 xn[],                          /* (i)     : target vector                         */
+		Word16 h[],                           /* (i) Q15 : impulse response of synth/wgt filters */
+		Word16 L_subfr,
+		Word16 t_min,                         /* (i)     : minimum value of pitch lag.           */
+		Word16 t_max,                         /* (i)     : maximum value of pitch lag.           */
+		Word16 corr_norm[]                    /* (o) Q15 : normalized correlation                */
+		);
+#endif
+
+static Word16 Interpol_4(                  /* (o)  : interpolated value  */
+		Word16 * x,                           /* (i)  : input vector        */
+		Word32 frac                           /* (i)  : fraction (-4..+3)   */
+		);
+
+
+Word16 Pitch_fr4(                          /* (o)     : pitch period.                         */
+		Word16 exc[],                         /* (i)     : excitation buffer                     */
+		Word16 xn[],                          /* (i)     : target vector                         */
+		Word16 h[],                           /* (i) Q15 : impulse response of synth/wgt filters */
+		Word16 t0_min,                        /* (i)     : minimum value in the searched range.  */
+		Word16 t0_max,                        /* (i)     : maximum value in the searched range.  */
+		Word16 * pit_frac,                    /* (o)     : chosen fraction (0, 1, 2 or 3).       */
+		Word16 i_subfr,                       /* (i)     : indicator for first subframe.         */
+		Word16 t0_fr2,                        /* (i)     : minimum value for resolution 1/2      */
+		Word16 t0_fr1,                        /* (i)     : minimum value for resolution 1        */
+		Word16 L_subfr                        /* (i)     : Length of subframe                    */
+		)
+{
+	Word32 fraction, i;
+	Word16 t_min, t_max;
+	Word16 max, t0, step, temp;
+	Word16 *corr;
+	Word16 corr_v[40];                     /* Total length = t0_max-t0_min+1+2*L_inter */
+
+	/* Find interval to compute normalized correlation */
+
+	t_min = t0_min - L_INTERPOL1;
+	t_max = t0_max + L_INTERPOL1;
+	corr = &corr_v[-t_min];
+	/* Compute normalized correlation between target and filtered excitation */
+#ifdef ASM_OPT               /* asm optimization branch */
+    Norm_corr_asm(exc, xn, h, L_subfr, t_min, t_max, corr);
+#else
+	Norm_Corr(exc, xn, h, L_subfr, t_min, t_max, corr);
+#endif
+
+	/* Find integer pitch */
+
+	max = corr[t0_min];
+	t0 = t0_min;
+	for (i = t0_min + 1; i <= t0_max; i++)
+	{
+		if (corr[i] >= max)
+		{
+			max = corr[i];
+			t0 = i;
+		}
+	}
+	/* If first subframe and t0 >= t0_fr1, do not search fractionnal pitch */
+	if ((i_subfr == 0) && (t0 >= t0_fr1))
+	{
+		*pit_frac = 0;
+		return (t0);
+	}
+	/*------------------------------------------------------------------*
+	 * Search fractionnal pitch with 1/4 subsample resolution.          *
+	 * Test the fractions around t0 and choose the one which maximizes  *
+	 * the interpolated normalized correlation.                         *
+	 *------------------------------------------------------------------*/
+
+	step = 1;               /* 1/4 subsample resolution */
+	fraction = -3;
+	if ((t0_fr2 == PIT_MIN)||((i_subfr == 0) && (t0 >= t0_fr2)))
+	{
+		step = 2;              /* 1/2 subsample resolution */
+		fraction = -2;
+	}
+	if(t0 == t0_min)
+	{
+		fraction = 0;
+	}
+	max = Interpol_4(&corr[t0], fraction);
+
+	for (i = fraction + step; i <= 3; i += step)
+	{
+		temp = Interpol_4(&corr[t0], i);
+		if(temp > max)
+		{
+			max = temp;
+			fraction = i;
+		}
+	}
+	/* limit the fraction value in the interval [0,1,2,3] */
+	if (fraction < 0)
+	{
+		fraction += UP_SAMP;
+		t0 -= 1;
+	}
+	*pit_frac = fraction;
+	return (t0);
+}
+
+
+/***********************************************************************************
+* Function:  Norm_Corr()                                                            *
+*                                                                                   *
+* Description: Find the normalized correlation between the target vector and the    *
+* filtered past excitation.                                                         *
+* (correlation between target and filtered excitation divided by the                *
+*  square root of energy of target and filtered excitation).                        *
+************************************************************************************/
+#ifndef ASM_OPT
+static void Norm_Corr(
+		Word16 exc[],                         /* (i)     : excitation buffer                     */
+		Word16 xn[],                          /* (i)     : target vector                         */
+		Word16 h[],                           /* (i) Q15 : impulse response of synth/wgt filters */
+		Word16 L_subfr,
+		Word16 t_min,                         /* (i)     : minimum value of pitch lag.           */
+		Word16 t_max,                         /* (i)     : maximum value of pitch lag.           */
+		Word16 corr_norm[])                   /* (o) Q15 : normalized correlation                */
+{
+	Word32 i, k, t;
+	Word32 corr, exp_corr, norm, exp, scale;
+	Word16 exp_norm, excf[L_SUBFR], tmp;
+	Word32 L_tmp, L_tmp1, L_tmp2;
+
+	/* compute the filtered excitation for the first delay t_min */
+	k = -t_min;
+
+#ifdef ASM_OPT              /* asm optimization branch */
+	Convolve_asm(&exc[k], h, excf, 64);
+#else
+	Convolve(&exc[k], h, excf, 64);
+#endif
+
+	/* Compute rounded down 1/sqrt(energy of xn[]) */
+	L_tmp = 0;
+	for (i = 0; i < 64; i+=4)
+	{
+		L_tmp += (xn[i] * xn[i]);
+		L_tmp += (xn[i+1] * xn[i+1]);
+		L_tmp += (xn[i+2] * xn[i+2]);
+		L_tmp += (xn[i+3] * xn[i+3]);
+	}
+
+	L_tmp = (L_tmp << 1) + 1;
+	exp = norm_l(L_tmp);
+	exp = (32 - exp);
+	//exp = exp + 2;                     /* energy of xn[] x 2 + rounded up     */
+	scale = -(exp >> 1);           /* (1<<scale) < 1/sqrt(energy rounded) */
+
+	/* loop for every possible period */
+
+	for (t = t_min; t <= t_max; t++)
+	{
+		/* Compute correlation between xn[] and excf[] */
+		L_tmp  = 0;
+		L_tmp1 = 0;
+		for (i = 0; i < 64; i+=4)
+		{
+			L_tmp  += (xn[i] * excf[i]);
+			L_tmp1 += (excf[i] * excf[i]);
+			L_tmp  += (xn[i+1] * excf[i+1]);
+			L_tmp1 += (excf[i+1] * excf[i+1]);
+			L_tmp  += (xn[i+2] * excf[i+2]);
+			L_tmp1 += (excf[i+2] * excf[i+2]);
+			L_tmp  += (xn[i+3] * excf[i+3]);
+			L_tmp1 += (excf[i+3] * excf[i+3]);
+		}
+
+		L_tmp = (L_tmp << 1) + 1;
+		L_tmp1 = (L_tmp1 << 1) + 1;
+
+		exp = norm_l(L_tmp);
+		L_tmp = (L_tmp << exp);
+		exp_corr = (30 - exp);
+		corr = extract_h(L_tmp);
+
+		exp = norm_l(L_tmp1);
+		L_tmp = (L_tmp1 << exp);
+		exp_norm = (30 - exp);
+
+		Isqrt_n(&L_tmp, &exp_norm);
+		norm = extract_h(L_tmp);
+
+		/* Normalize correlation = correlation * (1/sqrt(energy)) */
+
+		L_tmp = vo_L_mult(corr, norm);
+
+		L_tmp2 = exp_corr + exp_norm + scale;
+		if(L_tmp2 < 0)
+		{
+			L_tmp2 = -L_tmp2;
+			L_tmp = L_tmp >> L_tmp2;
+		}
+		else
+		{
+			L_tmp = L_tmp << L_tmp2;
+		}
+
+		corr_norm[t] = vo_round(L_tmp);
+		/* modify the filtered excitation excf[] for the next iteration */
+
+		if(t != t_max)
+		{
+			k = -(t + 1);
+			tmp = exc[k];
+			for (i = 63; i > 0; i--)
+			{
+				excf[i] = add1(vo_mult(tmp, h[i]), excf[i - 1]);
+			}
+			excf[0] = vo_mult(tmp, h[0]);
+		}
+	}
+	return;
+}
+
+#endif
+/************************************************************************************
+* Function: Interpol_4()                                                             *
+*                                                                                    *
+* Description: For interpolating the normalized correlation with 1/4 resolution.     *
+**************************************************************************************/
+
+/* 1/4 resolution interpolation filter (-3 dB at 0.791*fs/2) in Q14 */
+static Word16 inter4_1[4][8] =
+{
+	{-12, 420, -1732, 5429, 13418, -1242, 73, 32},
+	{-26, 455, -2142, 9910, 9910,  -2142, 455, -26},
+	{32,  73, -1242, 13418, 5429, -1732, 420, -12},
+	{206, -766, 1376, 14746, 1376, -766, 206, 0}
+};
+
+/*** Coefficients in floating point
+static float inter4_1[UP_SAMP*L_INTERPOL1+1] = {
+0.900000,
+0.818959,  0.604850,  0.331379,  0.083958,
+-0.075795, -0.130717, -0.105685, -0.046774,
+0.004467,  0.027789,  0.025642,  0.012571,
+0.001927, -0.001571, -0.000753,  0.000000};
+***/
+
+static Word16 Interpol_4(                  /* (o)  : interpolated value  */
+		Word16 * x,                           /* (i)  : input vector        */
+		Word32 frac                           /* (i)  : fraction (-4..+3)   */
+		)
+{
+	Word16 sum;
+	Word32  k, L_sum;
+	Word16 *ptr;
+
+	if (frac < 0)
+	{
+		frac += UP_SAMP;
+		x--;
+	}
+	x = x - L_INTERPOL1 + 1;
+	k = UP_SAMP - 1 - frac;
+	ptr = &(inter4_1[k][0]);
+
+	L_sum  = vo_mult32(x[0], (*ptr++));
+	L_sum += vo_mult32(x[1], (*ptr++));
+	L_sum += vo_mult32(x[2], (*ptr++));
+	L_sum += vo_mult32(x[3], (*ptr++));
+	L_sum += vo_mult32(x[4], (*ptr++));
+	L_sum += vo_mult32(x[5], (*ptr++));
+	L_sum += vo_mult32(x[6], (*ptr++));
+	L_sum += vo_mult32(x[7], (*ptr++));
+
+	sum = extract_h(L_add(L_shl2(L_sum, 2), 0x8000));
+	return (sum);
+}
+
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/pred_lt4.c b/media/libstagefright/codecs/amrwbenc/src/pred_lt4.c
index ac1ff22..8404cf9 100644
--- a/media/libstagefright/codecs/amrwbenc/src/pred_lt4.c
+++ b/media/libstagefright/codecs/amrwbenc/src/pred_lt4.c
@@ -1,120 +1,120 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*      File: pred_lt4.c                                                *

-*                                                                      *

-*      Description: Compute the result of long term prediction with    *

-*      fractional interpolation of resolution 1/4                      *

-*      on return exc[0..L_subr-1] contains the interpolated signal     *

-*      (adaptive codebook excitation)                                  *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-

-#define UP_SAMP      4

-#define L_INTERPOL2  16

-

-/* 1/4 resolution interpolation filter (-3 dB at 0.856*fs/2) in Q14 */

-

-Word16 inter4_2[4][32] =

-{

-	{0,-2,4,-2,-10,38,-88,165,-275,424,-619,871,-1207,1699,-2598,5531,14031,-2147,780,-249,

-	-16,153,-213,226,-209,175,-133,91,-55,28,-10,2},

-

-	{1,-7,19,-33,47,-52,43,-9,-60,175,-355,626,-1044,1749,-3267,10359,10359,-3267,1749,-1044,

-	626,-355,175,-60,-9,43,-52,47,-33,19, -7, 1},

-

-	{2,-10,28,-55,91,-133,175,-209,226,-213,153,-16,-249,780,-2147,14031,5531,-2598,1699,-1207,

-	871,-619,424,-275,165,-88,38,-10,-2,4,-2,0},

-

-	{1,-7,22,-49,92,-153,231,-325,431,-544,656,-762,853,-923,968,15401,968,-923,853,-762,

-	656,-544,431,-325,231,-153,92,-49,22,-7, 1, 0}

-

-};

-

-void Pred_lt4(

-		Word16 exc[],                         /* in/out: excitation buffer */

-		Word16 T0,                            /* input : integer pitch lag */

-		Word16 frac,                          /* input : fraction of lag   */

-		Word16 L_subfr                        /* input : subframe size     */

-	     )

-{

-	Word16 j, k, *x;

-	Word32 L_sum;

-	Word16 *ptr, *ptr1;

-	Word16 *ptr2;

-

-	x = exc - T0;   

-	frac = -frac;

-	if (frac < 0)

-	{

-		frac += UP_SAMP;

-		x--;

-	}   

-	x -= 15;                                     /* x = L_INTERPOL2 - 1 */

-	k = 3 - frac;                                /* k = UP_SAMP - 1 - frac */

-

-	ptr2 = &(inter4_2[k][0]);

-	for (j = 0; j < L_subfr; j++)

-	{

-		ptr = ptr2;

-		ptr1 = x;

-		L_sum  = vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-		L_sum += vo_mult32((*ptr1++), (*ptr++));

-

-		L_sum = L_shl2(L_sum, 2);

-		exc[j] = extract_h(L_add(L_sum, 0x8000));

-		x++;

-	}

-

-	return;

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*      File: pred_lt4.c                                                *
+*                                                                      *
+*      Description: Compute the result of long term prediction with    *
+*      fractional interpolation of resolution 1/4                      *
+*      on return exc[0..L_subr-1] contains the interpolated signal     *
+*      (adaptive codebook excitation)                                  *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+
+#define UP_SAMP      4
+#define L_INTERPOL2  16
+
+/* 1/4 resolution interpolation filter (-3 dB at 0.856*fs/2) in Q14 */
+
+Word16 inter4_2[4][32] =
+{
+	{0,-2,4,-2,-10,38,-88,165,-275,424,-619,871,-1207,1699,-2598,5531,14031,-2147,780,-249,
+	-16,153,-213,226,-209,175,-133,91,-55,28,-10,2},
+
+	{1,-7,19,-33,47,-52,43,-9,-60,175,-355,626,-1044,1749,-3267,10359,10359,-3267,1749,-1044,
+	626,-355,175,-60,-9,43,-52,47,-33,19, -7, 1},
+
+	{2,-10,28,-55,91,-133,175,-209,226,-213,153,-16,-249,780,-2147,14031,5531,-2598,1699,-1207,
+	871,-619,424,-275,165,-88,38,-10,-2,4,-2,0},
+
+	{1,-7,22,-49,92,-153,231,-325,431,-544,656,-762,853,-923,968,15401,968,-923,853,-762,
+	656,-544,431,-325,231,-153,92,-49,22,-7, 1, 0}
+
+};
+
+void Pred_lt4(
+		Word16 exc[],                         /* in/out: excitation buffer */
+		Word16 T0,                            /* input : integer pitch lag */
+		Word16 frac,                          /* input : fraction of lag   */
+		Word16 L_subfr                        /* input : subframe size     */
+	     )
+{
+	Word16 j, k, *x;
+	Word32 L_sum;
+	Word16 *ptr, *ptr1;
+	Word16 *ptr2;
+
+	x = exc - T0;
+	frac = -frac;
+	if (frac < 0)
+	{
+		frac += UP_SAMP;
+		x--;
+	}
+	x -= 15;                                     /* x = L_INTERPOL2 - 1 */
+	k = 3 - frac;                                /* k = UP_SAMP - 1 - frac */
+
+	ptr2 = &(inter4_2[k][0]);
+	for (j = 0; j < L_subfr; j++)
+	{
+		ptr = ptr2;
+		ptr1 = x;
+		L_sum  = vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+		L_sum += vo_mult32((*ptr1++), (*ptr++));
+
+		L_sum = L_shl2(L_sum, 2);
+		exc[j] = extract_h(L_add(L_sum, 0x8000));
+		x++;
+	}
+
+	return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/preemph.c b/media/libstagefright/codecs/amrwbenc/src/preemph.c
index f5bcd33..c867bf7 100644
--- a/media/libstagefright/codecs/amrwbenc/src/preemph.c
+++ b/media/libstagefright/codecs/amrwbenc/src/preemph.c
@@ -1,88 +1,88 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*      File: preemph.c                                                *

-*                                                                     *

-*      Description: Preemphasis: filtering through 1 - g z^-1         *

-*	           Preemph2 --> signal is multiplied by 2             *

-*                                                                     *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-

-void Preemph(

-		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */

-		Word16 mu,                            /* (i) Q15 : preemphasis coefficient                */

-		Word16 lg,                            /* (i)     : lenght of filtering                    */

-		Word16 * mem                          /* (i/o)   : memory (x[-1])                         */

-	    )

-{

-	Word16 temp;

-	Word32 i, L_tmp;

-

-	temp = x[lg - 1];                     

-

-	for (i = lg - 1; i > 0; i--)

-	{

-		L_tmp = L_deposit_h(x[i]);

-		L_tmp -= (x[i - 1] * mu)<<1;

-		x[i] = (L_tmp + 0x8000)>>16;               

-	}

-

-	L_tmp = L_deposit_h(x[0]);

-	L_tmp -= ((*mem) * mu)<<1;

-	x[0] = (L_tmp + 0x8000)>>16;                   

-

-	*mem = temp;                           

-

-	return;

-}

-

-

-void Preemph2(

-		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */

-		Word16 mu,                            /* (i) Q15 : preemphasis coefficient                */

-		Word16 lg,                            /* (i)     : lenght of filtering                    */

-		Word16 * mem                          /* (i/o)   : memory (x[-1])                         */

-	     )

-{

-	Word16 temp;

-	Word32 i, L_tmp;

-

-	temp = x[lg - 1];                     

-

-	for (i = (Word16) (lg - 1); i > 0; i--)

-	{

-		L_tmp = L_deposit_h(x[i]);

-		L_tmp -= (x[i - 1] * mu)<<1;

-		L_tmp = (L_tmp << 1);

-		x[i] = (L_tmp + 0x8000)>>16;               

-	}

-

-	L_tmp = L_deposit_h(x[0]);

-	L_tmp -= ((*mem) * mu)<<1;

-	L_tmp = (L_tmp << 1);

-	x[0] = (L_tmp + 0x8000)>>16;                   

-

-	*mem = temp;                           

-

-	return;

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*      File: preemph.c                                                *
+*                                                                     *
+*      Description: Preemphasis: filtering through 1 - g z^-1         *
+*	           Preemph2 --> signal is multiplied by 2             *
+*                                                                     *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+
+void Preemph(
+		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
+		Word16 mu,                            /* (i) Q15 : preemphasis coefficient                */
+		Word16 lg,                            /* (i)     : lenght of filtering                    */
+		Word16 * mem                          /* (i/o)   : memory (x[-1])                         */
+	    )
+{
+	Word16 temp;
+	Word32 i, L_tmp;
+
+	temp = x[lg - 1];
+
+	for (i = lg - 1; i > 0; i--)
+	{
+		L_tmp = L_deposit_h(x[i]);
+		L_tmp -= (x[i - 1] * mu)<<1;
+		x[i] = (L_tmp + 0x8000)>>16;
+	}
+
+	L_tmp = L_deposit_h(x[0]);
+	L_tmp -= ((*mem) * mu)<<1;
+	x[0] = (L_tmp + 0x8000)>>16;
+
+	*mem = temp;
+
+	return;
+}
+
+
+void Preemph2(
+		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
+		Word16 mu,                            /* (i) Q15 : preemphasis coefficient                */
+		Word16 lg,                            /* (i)     : lenght of filtering                    */
+		Word16 * mem                          /* (i/o)   : memory (x[-1])                         */
+	     )
+{
+	Word16 temp;
+	Word32 i, L_tmp;
+
+	temp = x[lg - 1];
+
+	for (i = (Word16) (lg - 1); i > 0; i--)
+	{
+		L_tmp = L_deposit_h(x[i]);
+		L_tmp -= (x[i - 1] * mu)<<1;
+		L_tmp = (L_tmp << 1);
+		x[i] = (L_tmp + 0x8000)>>16;
+	}
+
+	L_tmp = L_deposit_h(x[0]);
+	L_tmp -= ((*mem) * mu)<<1;
+	L_tmp = (L_tmp << 1);
+	x[0] = (L_tmp + 0x8000)>>16;
+
+	*mem = temp;
+
+	return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/q_gain2.c b/media/libstagefright/codecs/amrwbenc/src/q_gain2.c
index 59eefe4..e8ca043 100644
--- a/media/libstagefright/codecs/amrwbenc/src/q_gain2.c
+++ b/media/libstagefright/codecs/amrwbenc/src/q_gain2.c
@@ -1,346 +1,346 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/**************************************************************************

-*  File: q_gain2.c                                                         *

-*                                                                          *

-*  Description:                                                            *

-* Quantization of pitch and codebook gains.                                *

-* MA prediction is performed on the innovation energy (in dB with mean     *

-* removed).                                                                *

-* An initial predicted gain, g_0, is first determined and the correction   *

-* factor     alpha = gain / g_0    is quantized.                           *

-* The pitch gain and the correction factor are vector quantized and the    *

-* mean-squared weighted error criterion is used in the quantizer search.   *

-****************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "oper_32b.h"

-#include "math_op.h"

-#include "log2.h"

-#include "acelp.h"

-#include "q_gain2.tab"

-

-#define MEAN_ENER    30

-#define RANGE        64

-#define PRED_ORDER   4

-

-

-/* MA prediction coeff ={0.5, 0.4, 0.3, 0.2} in Q13 */

-static Word16 pred[PRED_ORDER] = {4096, 3277, 2458, 1638};

-

-

-void Init_Q_gain2(

-		Word16 * mem                          /* output  :static memory (2 words)      */

-		)

-{

-	Word32 i;

-

-	/* 4nd order quantizer energy predictor (init to -14.0 in Q10) */

-	for (i = 0; i < PRED_ORDER; i++)

-	{

-		mem[i] = -14336;                     /* past_qua_en[i] */

-	}

-

-	return;

-}

-

-Word16 Q_gain2(                            /* Return index of quantization.          */

-		Word16 xn[],                          /* (i) Q_xn: Target vector.               */

-		Word16 y1[],                          /* (i) Q_xn: Adaptive codebook.           */

-		Word16 Q_xn,                          /* (i)     : xn and y1 format             */

-		Word16 y2[],                          /* (i) Q9  : Filtered innovative vector.  */

-		Word16 code[],                        /* (i) Q9  : Innovative vector.           */

-		Word16 g_coeff[],                     /* (i)     : Correlations <xn y1> <y1 y1> */

-		/*           Compute in G_pitch().        */

-		Word16 L_subfr,                       /* (i)     : Subframe lenght.             */

-		Word16 nbits,                         /* (i)     : number of bits (6 or 7)      */

-		Word16 * gain_pit,                    /* (i/o)Q14: Pitch gain.                  */

-		Word32 * gain_cod,                    /* (o) Q16 : Code gain.                   */

-		Word16 gp_clip,                       /* (i)     : Gp Clipping flag             */

-		Word16 * mem                          /* (i/o)   : static memory (2 words)      */

-	      )

-{

-	Word16 index, *p, min_ind, size;

-	Word16 exp, frac, gcode0, exp_gcode0, e_max, exp_code, qua_ener;

-	Word16 g_pitch, g2_pitch, g_code, g_pit_cod, g2_code, g2_code_lo;

-	Word16 coeff[5], coeff_lo[5], exp_coeff[5];

-	Word16 exp_max[5];

-	Word32 i, j, L_tmp, dist_min;

-	Word16 *past_qua_en, *t_qua_gain;

-

-	past_qua_en = mem;                     

-

-	/*-----------------------------------------------------------------*

-	 * - Find the initial quantization pitch index                     *

-	 * - Set gains search range                                        *

-	 *-----------------------------------------------------------------*/

-	if (nbits == 6)

-	{

-		t_qua_gain = t_qua_gain6b;         

-		min_ind = 0;                       

-		size = RANGE;                      

-

-		if(gp_clip == 1)

-		{

-			size = size - 16;          /* limit gain pitch to 1.0 */

-		}

-	} else

-	{

-		t_qua_gain = t_qua_gain7b;         

-

-		p = t_qua_gain7b + RANGE;            /* pt at 1/4th of table */

-

-		j = nb_qua_gain7b - RANGE;         

-

-		if (gp_clip == 1)

-		{

-			j = j - 27;                /* limit gain pitch to 1.0 */

-		}

-		min_ind = 0;                       

-		g_pitch = *gain_pit;               

-

-		for (i = 0; i < j; i++, p += 2)

-		{

-			if (g_pitch > *p)

-			{

-				min_ind = min_ind + 1;

-			}

-		}

-		size = RANGE;                      

-	}

-

-	/*------------------------------------------------------------------*

-	 *  Compute coefficient need for the quantization.                  *

-	 *                                                                  *

-	 *  coeff[0] =    y1 y1                                             *

-	 *  coeff[1] = -2 xn y1                                             *

-	 *  coeff[2] =    y2 y2                                             *

-	 *  coeff[3] = -2 xn y2                                             *

-	 *  coeff[4] =  2 y1 y2                                             *

-	 *                                                                  *

-	 * Product <y1 y1> and <xn y1> have been compute in G_pitch() and   *

-	 * are in vector g_coeff[].                                         *

-	 *------------------------------------------------------------------*/

-

-	coeff[0] = g_coeff[0];                 

-	exp_coeff[0] = g_coeff[1];             

-	coeff[1] = negate(g_coeff[2]);                    /* coeff[1] = -2 xn y1 */

-	exp_coeff[1] = g_coeff[3] + 1;     

-

-	/* Compute scalar product <y2[],y2[]> */

-#ifdef ASM_OPT                   /* asm optimization branch */

-	coeff[2] = extract_h(Dot_product12_asm(y2, y2, L_subfr, &exp));

-#else

-	coeff[2] = extract_h(Dot_product12(y2, y2, L_subfr, &exp));

-#endif

-	exp_coeff[2] = (exp - 18) + (Q_xn << 1);     /* -18 (y2 Q9) */

-

-	/* Compute scalar product -2*<xn[],y2[]> */

-#ifdef ASM_OPT                  /* asm optimization branch */

-	coeff[3] = extract_h(L_negate(Dot_product12_asm(xn, y2, L_subfr, &exp)));

-#else

-	coeff[3] = extract_h(L_negate(Dot_product12(xn, y2, L_subfr, &exp)));

-#endif

-

-	exp_coeff[3] = (exp - 8) + Q_xn;  /* -9 (y2 Q9), +1 (2 xn y2) */

-

-	/* Compute scalar product 2*<y1[],y2[]> */

-#ifdef ASM_OPT                 /* asm optimization branch */

-	coeff[4] = extract_h(Dot_product12_asm(y1, y2, L_subfr, &exp));

-#else

-	coeff[4] = extract_h(Dot_product12(y1, y2, L_subfr, &exp));

-#endif

-	exp_coeff[4] = (exp - 8) + Q_xn;  /* -9 (y2 Q9), +1 (2 y1 y2) */

-

-	/*-----------------------------------------------------------------*

-	 *  Find energy of code and compute:                               *

-	 *                                                                 *

-	 *    L_tmp = MEAN_ENER - 10log10(energy of code/ L_subfr)         *

-	 *          = MEAN_ENER - 3.0103*log2(energy of code/ L_subfr)     *

-	 *-----------------------------------------------------------------*/

-#ifdef ASM_OPT                 /* asm optimization branch */

-	L_tmp = Dot_product12_asm(code, code, L_subfr, &exp_code);

-#else

-	L_tmp = Dot_product12(code, code, L_subfr, &exp_code);

-#endif

-	/* exp_code: -18 (code in Q9), -6 (/L_subfr), -31 (L_tmp Q31->Q0) */

-	exp_code = (exp_code - (18 + 6 + 31));

-

-	Log2(L_tmp, &exp, &frac);

-	exp += exp_code;

-	L_tmp = Mpy_32_16(exp, frac, -24660);  /* x -3.0103(Q13) -> Q14 */

-

-	L_tmp += (MEAN_ENER * 8192)<<1; /* + MEAN_ENER in Q14 */

-

-	/*-----------------------------------------------------------------*

-	 * Compute gcode0.                                                 *

-	 *  = Sum(i=0,1) pred[i]*past_qua_en[i] + mean_ener - ener_code    *

-	 *-----------------------------------------------------------------*/

-	L_tmp = (L_tmp << 10);              /* From Q14 to Q24 */

-	L_tmp += (pred[0] * past_qua_en[0])<<1;      /* Q13*Q10 -> Q24 */

-	L_tmp += (pred[1] * past_qua_en[1])<<1;      /* Q13*Q10 -> Q24 */

-	L_tmp += (pred[2] * past_qua_en[2])<<1;      /* Q13*Q10 -> Q24 */

-	L_tmp += (pred[3] * past_qua_en[3])<<1;      /* Q13*Q10 -> Q24 */

-

-	gcode0 = extract_h(L_tmp);             /* From Q24 to Q8  */

-

-	/*-----------------------------------------------------------------*

-	 * gcode0 = pow(10.0, gcode0/20)                                   *

-	 *        = pow(2, 3.321928*gcode0/20)                             *

-	 *        = pow(2, 0.166096*gcode0)                                *

-	 *-----------------------------------------------------------------*/

-

-	L_tmp = vo_L_mult(gcode0, 5443);          /* *0.166096 in Q15 -> Q24     */

-	L_tmp = L_tmp >> 8;               /* From Q24 to Q16             */

-	VO_L_Extract(L_tmp, &exp_gcode0, &frac);  /* Extract exponent of gcode0  */

-

-	gcode0 = (Word16)(Pow2(14, frac));    /* Put 14 as exponent so that  */

-	/* output of Pow2() will be:   */

-	/* 16384 < Pow2() <= 32767     */

-	exp_gcode0 -= 14;

-

-	/*-------------------------------------------------------------------------*

-	 * Find the best quantizer                                                 *

-	 * ~~~~~~~~~~~~~~~~~~~~~~~                                                 *

-	 * Before doing the computation we need to aling exponents of coeff[]      *

-	 * to be sure to have the maximum precision.                               *

-	 *                                                                         *

-	 * In the table the pitch gains are in Q14, the code gains are in Q11 and  *

-	 * are multiply by gcode0 which have been multiply by 2^exp_gcode0.        *

-	 * Also when we compute g_pitch*g_pitch, g_code*g_code and g_pitch*g_code  *

-	 * we divide by 2^15.                                                      *

-	 * Considering all the scaling above we have:                              *

-	 *                                                                         *

-	 *   exp_code = exp_gcode0-11+15 = exp_gcode0+4                            *

-	 *                                                                         *

-	 *   g_pitch*g_pitch  = -14-14+15                                          *

-	 *   g_pitch          = -14                                                *

-	 *   g_code*g_code    = (2*exp_code)+15                                    *

-	 *   g_code           = exp_code                                           *

-	 *   g_pitch*g_code   = -14 + exp_code +15                                 *

-	 *                                                                         *

-	 *   g_pitch*g_pitch * coeff[0]  ;exp_max0 = exp_coeff[0] - 13             *

-	 *   g_pitch         * coeff[1]  ;exp_max1 = exp_coeff[1] - 14             *

-	 *   g_code*g_code   * coeff[2]  ;exp_max2 = exp_coeff[2] +15+(2*exp_code) *

-	 *   g_code          * coeff[3]  ;exp_max3 = exp_coeff[3] + exp_code       *

-	 *   g_pitch*g_code  * coeff[4]  ;exp_max4 = exp_coeff[4] + 1 + exp_code   *

-	 *-------------------------------------------------------------------------*/

-

-	exp_code = (exp_gcode0 + 4);

-	exp_max[0] = (exp_coeff[0] - 13);    

-	exp_max[1] = (exp_coeff[1] - 14);    

-	exp_max[2] = (exp_coeff[2] + (15 + (exp_code << 1)));  

-	exp_max[3] = (exp_coeff[3] + exp_code);   

-	exp_max[4] = (exp_coeff[4] + (1 + exp_code));  

-

-	/* Find maximum exponant */

-

-	e_max = exp_max[0];                   

-	for (i = 1; i < 5; i++)

-	{

-		if(exp_max[i] > e_max)

-		{

-			e_max = exp_max[i];            

-		}

-	}

-

-	/* align coeff[] and save in special 32 bit double precision */

-

-	for (i = 0; i < 5; i++)

-	{

-		j = add1(vo_sub(e_max, exp_max[i]), 2);/* /4 to avoid overflow */

-		L_tmp = L_deposit_h(coeff[i]);

-		L_tmp = L_shr(L_tmp, j);

-		VO_L_Extract(L_tmp, &coeff[i], &coeff_lo[i]);

-		coeff_lo[i] = (coeff_lo[i] >> 3);   /* lo >> 3 */

-	}

-

-	/* Codebook search */

-	dist_min = MAX_32;                     

-	p = &t_qua_gain[min_ind << 1];      

-

-	index = 0;                             

-	for (i = 0; i < size; i++)

-	{

-		g_pitch = *p++;                    

-		g_code = *p++;                     

-

-		g_code = ((g_code * gcode0) + 0x4000)>>15;

-		g2_pitch = ((g_pitch * g_pitch) + 0x4000)>>15;

-		g_pit_cod = ((g_code * g_pitch) + 0x4000)>>15;

-		L_tmp = (g_code * g_code)<<1;

-		VO_L_Extract(L_tmp, &g2_code, &g2_code_lo);

-

-		L_tmp = (coeff[2] * g2_code_lo)<<1;

-		L_tmp =  (L_tmp >> 3);

-		L_tmp += (coeff_lo[0] * g2_pitch)<<1;

-		L_tmp += (coeff_lo[1] * g_pitch)<<1;

-		L_tmp += (coeff_lo[2] * g2_code)<<1;

-		L_tmp += (coeff_lo[3] * g_code)<<1;

-		L_tmp += (coeff_lo[4] * g_pit_cod)<<1;

-		L_tmp =  (L_tmp >> 12);

-		L_tmp += (coeff[0] * g2_pitch)<<1;

-		L_tmp += (coeff[1] * g_pitch)<<1;

-		L_tmp += (coeff[2] * g2_code)<<1;

-		L_tmp += (coeff[3] * g_code)<<1;

-		L_tmp += (coeff[4] * g_pit_cod)<<1;

-

-		if(L_tmp < dist_min)

-		{

-			dist_min = L_tmp;              

-			index = i;                     

-		}

-	}

-

-	/* Read the quantized gains */

-	index = index + min_ind;

-	p = &t_qua_gain[(index + index)];    

-	*gain_pit = *p++;                       /* selected pitch gain in Q14 */

-	g_code = *p++;                          /* selected code gain in Q11  */

-

-	L_tmp = vo_L_mult(g_code, gcode0);             /* Q11*Q0 -> Q12 */

-	L_tmp = L_shl(L_tmp, (exp_gcode0 + 4));   /* Q12 -> Q16 */

-

-	*gain_cod = L_tmp;                       /* gain of code in Q16 */

-

-	/*---------------------------------------------------*

-	 * qua_ener = 20*log10(g_code)                       *

-	 *          = 6.0206*log2(g_code)                    *

-	 *          = 6.0206*(log2(g_codeQ11) - 11)          *

-	 *---------------------------------------------------*/

-

-	L_tmp = L_deposit_l(g_code);

-	Log2(L_tmp, &exp, &frac);

-	exp -= 11;

-	L_tmp = Mpy_32_16(exp, frac, 24660);   /* x 6.0206 in Q12 */

-

-	qua_ener = (Word16)(L_tmp >> 3); /* result in Q10 */

-

-	/* update table of past quantized energies */

-

-	past_qua_en[3] = past_qua_en[2];       

-	past_qua_en[2] = past_qua_en[1];       

-	past_qua_en[1] = past_qua_en[0];       

-	past_qua_en[0] = qua_ener;             

-

-	return (index);

-}

-

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/**************************************************************************
+*  File: q_gain2.c                                                         *
+*                                                                          *
+*  Description:                                                            *
+* Quantization of pitch and codebook gains.                                *
+* MA prediction is performed on the innovation energy (in dB with mean     *
+* removed).                                                                *
+* An initial predicted gain, g_0, is first determined and the correction   *
+* factor     alpha = gain / g_0    is quantized.                           *
+* The pitch gain and the correction factor are vector quantized and the    *
+* mean-squared weighted error criterion is used in the quantizer search.   *
+****************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "oper_32b.h"
+#include "math_op.h"
+#include "log2.h"
+#include "acelp.h"
+#include "q_gain2.tab"
+
+#define MEAN_ENER    30
+#define RANGE        64
+#define PRED_ORDER   4
+
+
+/* MA prediction coeff ={0.5, 0.4, 0.3, 0.2} in Q13 */
+static Word16 pred[PRED_ORDER] = {4096, 3277, 2458, 1638};
+
+
+void Init_Q_gain2(
+		Word16 * mem                          /* output  :static memory (2 words)      */
+		)
+{
+	Word32 i;
+
+	/* 4nd order quantizer energy predictor (init to -14.0 in Q10) */
+	for (i = 0; i < PRED_ORDER; i++)
+	{
+		mem[i] = -14336;                     /* past_qua_en[i] */
+	}
+
+	return;
+}
+
+Word16 Q_gain2(                            /* Return index of quantization.          */
+		Word16 xn[],                          /* (i) Q_xn: Target vector.               */
+		Word16 y1[],                          /* (i) Q_xn: Adaptive codebook.           */
+		Word16 Q_xn,                          /* (i)     : xn and y1 format             */
+		Word16 y2[],                          /* (i) Q9  : Filtered innovative vector.  */
+		Word16 code[],                        /* (i) Q9  : Innovative vector.           */
+		Word16 g_coeff[],                     /* (i)     : Correlations <xn y1> <y1 y1> */
+		/*           Compute in G_pitch().        */
+		Word16 L_subfr,                       /* (i)     : Subframe lenght.             */
+		Word16 nbits,                         /* (i)     : number of bits (6 or 7)      */
+		Word16 * gain_pit,                    /* (i/o)Q14: Pitch gain.                  */
+		Word32 * gain_cod,                    /* (o) Q16 : Code gain.                   */
+		Word16 gp_clip,                       /* (i)     : Gp Clipping flag             */
+		Word16 * mem                          /* (i/o)   : static memory (2 words)      */
+	      )
+{
+	Word16 index, *p, min_ind, size;
+	Word16 exp, frac, gcode0, exp_gcode0, e_max, exp_code, qua_ener;
+	Word16 g_pitch, g2_pitch, g_code, g_pit_cod, g2_code, g2_code_lo;
+	Word16 coeff[5], coeff_lo[5], exp_coeff[5];
+	Word16 exp_max[5];
+	Word32 i, j, L_tmp, dist_min;
+	Word16 *past_qua_en, *t_qua_gain;
+
+	past_qua_en = mem;
+
+	/*-----------------------------------------------------------------*
+	 * - Find the initial quantization pitch index                     *
+	 * - Set gains search range                                        *
+	 *-----------------------------------------------------------------*/
+	if (nbits == 6)
+	{
+		t_qua_gain = t_qua_gain6b;
+		min_ind = 0;
+		size = RANGE;
+
+		if(gp_clip == 1)
+		{
+			size = size - 16;          /* limit gain pitch to 1.0 */
+		}
+	} else
+	{
+		t_qua_gain = t_qua_gain7b;
+
+		p = t_qua_gain7b + RANGE;            /* pt at 1/4th of table */
+
+		j = nb_qua_gain7b - RANGE;
+
+		if (gp_clip == 1)
+		{
+			j = j - 27;                /* limit gain pitch to 1.0 */
+		}
+		min_ind = 0;
+		g_pitch = *gain_pit;
+
+		for (i = 0; i < j; i++, p += 2)
+		{
+			if (g_pitch > *p)
+			{
+				min_ind = min_ind + 1;
+			}
+		}
+		size = RANGE;
+	}
+
+	/*------------------------------------------------------------------*
+	 *  Compute coefficient need for the quantization.                  *
+	 *                                                                  *
+	 *  coeff[0] =    y1 y1                                             *
+	 *  coeff[1] = -2 xn y1                                             *
+	 *  coeff[2] =    y2 y2                                             *
+	 *  coeff[3] = -2 xn y2                                             *
+	 *  coeff[4] =  2 y1 y2                                             *
+	 *                                                                  *
+	 * Product <y1 y1> and <xn y1> have been compute in G_pitch() and   *
+	 * are in vector g_coeff[].                                         *
+	 *------------------------------------------------------------------*/
+
+	coeff[0] = g_coeff[0];
+	exp_coeff[0] = g_coeff[1];
+	coeff[1] = negate(g_coeff[2]);                    /* coeff[1] = -2 xn y1 */
+	exp_coeff[1] = g_coeff[3] + 1;
+
+	/* Compute scalar product <y2[],y2[]> */
+#ifdef ASM_OPT                   /* asm optimization branch */
+	coeff[2] = extract_h(Dot_product12_asm(y2, y2, L_subfr, &exp));
+#else
+	coeff[2] = extract_h(Dot_product12(y2, y2, L_subfr, &exp));
+#endif
+	exp_coeff[2] = (exp - 18) + (Q_xn << 1);     /* -18 (y2 Q9) */
+
+	/* Compute scalar product -2*<xn[],y2[]> */
+#ifdef ASM_OPT                  /* asm optimization branch */
+	coeff[3] = extract_h(L_negate(Dot_product12_asm(xn, y2, L_subfr, &exp)));
+#else
+	coeff[3] = extract_h(L_negate(Dot_product12(xn, y2, L_subfr, &exp)));
+#endif
+
+	exp_coeff[3] = (exp - 8) + Q_xn;  /* -9 (y2 Q9), +1 (2 xn y2) */
+
+	/* Compute scalar product 2*<y1[],y2[]> */
+#ifdef ASM_OPT                 /* asm optimization branch */
+	coeff[4] = extract_h(Dot_product12_asm(y1, y2, L_subfr, &exp));
+#else
+	coeff[4] = extract_h(Dot_product12(y1, y2, L_subfr, &exp));
+#endif
+	exp_coeff[4] = (exp - 8) + Q_xn;  /* -9 (y2 Q9), +1 (2 y1 y2) */
+
+	/*-----------------------------------------------------------------*
+	 *  Find energy of code and compute:                               *
+	 *                                                                 *
+	 *    L_tmp = MEAN_ENER - 10log10(energy of code/ L_subfr)         *
+	 *          = MEAN_ENER - 3.0103*log2(energy of code/ L_subfr)     *
+	 *-----------------------------------------------------------------*/
+#ifdef ASM_OPT                 /* asm optimization branch */
+	L_tmp = Dot_product12_asm(code, code, L_subfr, &exp_code);
+#else
+	L_tmp = Dot_product12(code, code, L_subfr, &exp_code);
+#endif
+	/* exp_code: -18 (code in Q9), -6 (/L_subfr), -31 (L_tmp Q31->Q0) */
+	exp_code = (exp_code - (18 + 6 + 31));
+
+	Log2(L_tmp, &exp, &frac);
+	exp += exp_code;
+	L_tmp = Mpy_32_16(exp, frac, -24660);  /* x -3.0103(Q13) -> Q14 */
+
+	L_tmp += (MEAN_ENER * 8192)<<1; /* + MEAN_ENER in Q14 */
+
+	/*-----------------------------------------------------------------*
+	 * Compute gcode0.                                                 *
+	 *  = Sum(i=0,1) pred[i]*past_qua_en[i] + mean_ener - ener_code    *
+	 *-----------------------------------------------------------------*/
+	L_tmp = (L_tmp << 10);              /* From Q14 to Q24 */
+	L_tmp += (pred[0] * past_qua_en[0])<<1;      /* Q13*Q10 -> Q24 */
+	L_tmp += (pred[1] * past_qua_en[1])<<1;      /* Q13*Q10 -> Q24 */
+	L_tmp += (pred[2] * past_qua_en[2])<<1;      /* Q13*Q10 -> Q24 */
+	L_tmp += (pred[3] * past_qua_en[3])<<1;      /* Q13*Q10 -> Q24 */
+
+	gcode0 = extract_h(L_tmp);             /* From Q24 to Q8  */
+
+	/*-----------------------------------------------------------------*
+	 * gcode0 = pow(10.0, gcode0/20)                                   *
+	 *        = pow(2, 3.321928*gcode0/20)                             *
+	 *        = pow(2, 0.166096*gcode0)                                *
+	 *-----------------------------------------------------------------*/
+
+	L_tmp = vo_L_mult(gcode0, 5443);          /* *0.166096 in Q15 -> Q24     */
+	L_tmp = L_tmp >> 8;               /* From Q24 to Q16             */
+	VO_L_Extract(L_tmp, &exp_gcode0, &frac);  /* Extract exponent of gcode0  */
+
+	gcode0 = (Word16)(Pow2(14, frac));    /* Put 14 as exponent so that  */
+	/* output of Pow2() will be:   */
+	/* 16384 < Pow2() <= 32767     */
+	exp_gcode0 -= 14;
+
+	/*-------------------------------------------------------------------------*
+	 * Find the best quantizer                                                 *
+	 * ~~~~~~~~~~~~~~~~~~~~~~~                                                 *
+	 * Before doing the computation we need to aling exponents of coeff[]      *
+	 * to be sure to have the maximum precision.                               *
+	 *                                                                         *
+	 * In the table the pitch gains are in Q14, the code gains are in Q11 and  *
+	 * are multiply by gcode0 which have been multiply by 2^exp_gcode0.        *
+	 * Also when we compute g_pitch*g_pitch, g_code*g_code and g_pitch*g_code  *
+	 * we divide by 2^15.                                                      *
+	 * Considering all the scaling above we have:                              *
+	 *                                                                         *
+	 *   exp_code = exp_gcode0-11+15 = exp_gcode0+4                            *
+	 *                                                                         *
+	 *   g_pitch*g_pitch  = -14-14+15                                          *
+	 *   g_pitch          = -14                                                *
+	 *   g_code*g_code    = (2*exp_code)+15                                    *
+	 *   g_code           = exp_code                                           *
+	 *   g_pitch*g_code   = -14 + exp_code +15                                 *
+	 *                                                                         *
+	 *   g_pitch*g_pitch * coeff[0]  ;exp_max0 = exp_coeff[0] - 13             *
+	 *   g_pitch         * coeff[1]  ;exp_max1 = exp_coeff[1] - 14             *
+	 *   g_code*g_code   * coeff[2]  ;exp_max2 = exp_coeff[2] +15+(2*exp_code) *
+	 *   g_code          * coeff[3]  ;exp_max3 = exp_coeff[3] + exp_code       *
+	 *   g_pitch*g_code  * coeff[4]  ;exp_max4 = exp_coeff[4] + 1 + exp_code   *
+	 *-------------------------------------------------------------------------*/
+
+	exp_code = (exp_gcode0 + 4);
+	exp_max[0] = (exp_coeff[0] - 13);
+	exp_max[1] = (exp_coeff[1] - 14);
+	exp_max[2] = (exp_coeff[2] + (15 + (exp_code << 1)));
+	exp_max[3] = (exp_coeff[3] + exp_code);
+	exp_max[4] = (exp_coeff[4] + (1 + exp_code));
+
+	/* Find maximum exponant */
+
+	e_max = exp_max[0];
+	for (i = 1; i < 5; i++)
+	{
+		if(exp_max[i] > e_max)
+		{
+			e_max = exp_max[i];
+		}
+	}
+
+	/* align coeff[] and save in special 32 bit double precision */
+
+	for (i = 0; i < 5; i++)
+	{
+		j = add1(vo_sub(e_max, exp_max[i]), 2);/* /4 to avoid overflow */
+		L_tmp = L_deposit_h(coeff[i]);
+		L_tmp = L_shr(L_tmp, j);
+		VO_L_Extract(L_tmp, &coeff[i], &coeff_lo[i]);
+		coeff_lo[i] = (coeff_lo[i] >> 3);   /* lo >> 3 */
+	}
+
+	/* Codebook search */
+	dist_min = MAX_32;
+	p = &t_qua_gain[min_ind << 1];
+
+	index = 0;
+	for (i = 0; i < size; i++)
+	{
+		g_pitch = *p++;
+		g_code = *p++;
+
+		g_code = ((g_code * gcode0) + 0x4000)>>15;
+		g2_pitch = ((g_pitch * g_pitch) + 0x4000)>>15;
+		g_pit_cod = ((g_code * g_pitch) + 0x4000)>>15;
+		L_tmp = (g_code * g_code)<<1;
+		VO_L_Extract(L_tmp, &g2_code, &g2_code_lo);
+
+		L_tmp = (coeff[2] * g2_code_lo)<<1;
+		L_tmp =  (L_tmp >> 3);
+		L_tmp += (coeff_lo[0] * g2_pitch)<<1;
+		L_tmp += (coeff_lo[1] * g_pitch)<<1;
+		L_tmp += (coeff_lo[2] * g2_code)<<1;
+		L_tmp += (coeff_lo[3] * g_code)<<1;
+		L_tmp += (coeff_lo[4] * g_pit_cod)<<1;
+		L_tmp =  (L_tmp >> 12);
+		L_tmp += (coeff[0] * g2_pitch)<<1;
+		L_tmp += (coeff[1] * g_pitch)<<1;
+		L_tmp += (coeff[2] * g2_code)<<1;
+		L_tmp += (coeff[3] * g_code)<<1;
+		L_tmp += (coeff[4] * g_pit_cod)<<1;
+
+		if(L_tmp < dist_min)
+		{
+			dist_min = L_tmp;
+			index = i;
+		}
+	}
+
+	/* Read the quantized gains */
+	index = index + min_ind;
+	p = &t_qua_gain[(index + index)];
+	*gain_pit = *p++;                       /* selected pitch gain in Q14 */
+	g_code = *p++;                          /* selected code gain in Q11  */
+
+	L_tmp = vo_L_mult(g_code, gcode0);             /* Q11*Q0 -> Q12 */
+	L_tmp = L_shl(L_tmp, (exp_gcode0 + 4));   /* Q12 -> Q16 */
+
+	*gain_cod = L_tmp;                       /* gain of code in Q16 */
+
+	/*---------------------------------------------------*
+	 * qua_ener = 20*log10(g_code)                       *
+	 *          = 6.0206*log2(g_code)                    *
+	 *          = 6.0206*(log2(g_codeQ11) - 11)          *
+	 *---------------------------------------------------*/
+
+	L_tmp = L_deposit_l(g_code);
+	Log2(L_tmp, &exp, &frac);
+	exp -= 11;
+	L_tmp = Mpy_32_16(exp, frac, 24660);   /* x 6.0206 in Q12 */
+
+	qua_ener = (Word16)(L_tmp >> 3); /* result in Q10 */
+
+	/* update table of past quantized energies */
+
+	past_qua_en[3] = past_qua_en[2];
+	past_qua_en[2] = past_qua_en[1];
+	past_qua_en[1] = past_qua_en[0];
+	past_qua_en[0] = qua_ener;
+
+	return (index);
+}
+
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/q_pulse.c b/media/libstagefright/codecs/amrwbenc/src/q_pulse.c
index a28ba40..80a0b73 100644
--- a/media/libstagefright/codecs/amrwbenc/src/q_pulse.c
+++ b/media/libstagefright/codecs/amrwbenc/src/q_pulse.c
@@ -1,400 +1,400 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*      File: q_pulse.c                                                 *

-*                                                                      *

-*      Description: Coding and decoding of algebraic codebook          *

-*                                                                      *

-************************************************************************/

-

-#include <stdio.h>

-#include "typedef.h"

-#include "basic_op.h"

-#include "q_pulse.h"

-

-#define NB_POS 16                          /* pos in track, mask for sign bit */

-

-Word32 quant_1p_N1(                        /* (o) return N+1 bits             */

-		Word16 pos,                        /* (i) position of the pulse       */

-		Word16 N)                          /* (i) number of bits for position */

-{

-	Word16 mask;

-	Word32 index;

-

-	mask = (1 << N) - 1;              /* mask = ((1<<N)-1); */

-	/*-------------------------------------------------------*

-	 * Quantization of 1 pulse with N+1 bits:                *

-	 *-------------------------------------------------------*/

-	index = L_deposit_l((Word16) (pos & mask));

-	if ((pos & NB_POS) != 0)

-	{

-		index = vo_L_add(index, L_deposit_l(1 << N));   /* index += 1 << N; */

-	}

-	return (index);

-}

-

-

-Word32 quant_2p_2N1(                       /* (o) return (2*N)+1 bits         */

-		Word16 pos1,                          /* (i) position of the pulse 1     */

-		Word16 pos2,                          /* (i) position of the pulse 2     */

-		Word16 N)                             /* (i) number of bits for position */

-{

-	Word16 mask, tmp;

-	Word32 index;

-	mask = (1 << N) - 1;              /* mask = ((1<<N)-1); */

-	/*-------------------------------------------------------*

-	 * Quantization of 2 pulses with 2*N+1 bits:             *

-	 *-------------------------------------------------------*/

-	if (((pos2 ^ pos1) & NB_POS) == 0)

-	{

-		/* sign of 1st pulse == sign of 2th pulse */

-		if(pos1 <= pos2)          /* ((pos1 - pos2) <= 0) */

-		{

-			/* index = ((pos1 & mask) << N) + (pos2 & mask); */

-			index = L_deposit_l(add1((((Word16) (pos1 & mask)) << N), ((Word16) (pos2 & mask))));

-		} else

-		{

-			/* ((pos2 & mask) << N) + (pos1 & mask); */

-			index = L_deposit_l(add1((((Word16) (pos2 & mask)) << N), ((Word16) (pos1 & mask))));

-		}

-		if ((pos1 & NB_POS) != 0)

-		{

-			tmp = (N << 1);

-			index = vo_L_add(index, (1L << tmp));       /* index += 1 << (2*N); */

-		}

-	} else

-	{

-		/* sign of 1st pulse != sign of 2th pulse */

-		if (vo_sub((Word16) (pos1 & mask), (Word16) (pos2 & mask)) <= 0)

-		{

-			/* index = ((pos2 & mask) << N) + (pos1 & mask); */

-			index = L_deposit_l(add1((((Word16) (pos2 & mask)) << N), ((Word16) (pos1 & mask)))); 

-			if ((pos2 & NB_POS) != 0)

-			{

-				tmp = (N << 1);           /* index += 1 << (2*N); */

-				index = vo_L_add(index, (1L << tmp));

-			}

-		} else

-		{

-			/* index = ((pos1 & mask) << N) + (pos2 & mask);	 */

-			index = L_deposit_l(add1((((Word16) (pos1 & mask)) << N), ((Word16) (pos2 & mask)))); 

-			if ((pos1 & NB_POS) != 0)

-			{

-				tmp = (N << 1);

-				index = vo_L_add(index, (1 << tmp));    /* index += 1 << (2*N); */

-			}

-		}

-	}

-	return (index);

-}

-

-

-Word32 quant_3p_3N1(                       /* (o) return (3*N)+1 bits         */

-		Word16 pos1,                          /* (i) position of the pulse 1     */

-		Word16 pos2,                          /* (i) position of the pulse 2     */

-		Word16 pos3,                          /* (i) position of the pulse 3     */

-		Word16 N)                             /* (i) number of bits for position */

-{

-	Word16 nb_pos;

-	Word32 index;

-

-	nb_pos =(1 <<(N - 1));            /* nb_pos = (1<<(N-1)); */

-	/*-------------------------------------------------------*

-	 * Quantization of 3 pulses with 3*N+1 bits:             *

-	 *-------------------------------------------------------*/

-	if (((pos1 ^ pos2) & nb_pos) == 0)

-	{

-		index = quant_2p_2N1(pos1, pos2, sub(N, 1));    /* index = quant_2p_2N1(pos1, pos2, (N-1)); */

-		/* index += (pos1 & nb_pos) << N; */

-		index = vo_L_add(index, (L_deposit_l((Word16) (pos1 & nb_pos)) << N));  

-		/* index += quant_1p_N1(pos3, N) << (2*N); */

-		index = vo_L_add(index, (quant_1p_N1(pos3, N)<<(N << 1)));

-

-	} else if (((pos1 ^ pos3) & nb_pos) == 0)

-	{

-		index = quant_2p_2N1(pos1, pos3, sub(N, 1));    /* index = quant_2p_2N1(pos1, pos3, (N-1)); */

-		index = vo_L_add(index, (L_deposit_l((Word16) (pos1 & nb_pos)) << N)); 

-		/* index += (pos1 & nb_pos) << N; */

-		index = vo_L_add(index, (quant_1p_N1(pos2, N) << (N << 1)));

-		/* index += quant_1p_N1(pos2, N) <<

-		 * (2*N); */

-	} else

-	{

-		index = quant_2p_2N1(pos2, pos3, (N - 1));    /* index = quant_2p_2N1(pos2, pos3, (N-1)); */

-		/* index += (pos2 & nb_pos) << N;			 */

-		index = vo_L_add(index, (L_deposit_l((Word16) (pos2 & nb_pos)) << N));  

-		/* index += quant_1p_N1(pos1, N) << (2*N);	 */

-		index = vo_L_add(index, (quant_1p_N1(pos1, N) << (N << 1)));

-	}

-	return (index);

-}

-

-

-Word32 quant_4p_4N1(                       /* (o) return (4*N)+1 bits         */

-		Word16 pos1,                          /* (i) position of the pulse 1     */

-		Word16 pos2,                          /* (i) position of the pulse 2     */

-		Word16 pos3,                          /* (i) position of the pulse 3     */

-		Word16 pos4,                          /* (i) position of the pulse 4     */

-		Word16 N)                             /* (i) number of bits for position */

-{

-	Word16 nb_pos;

-	Word32 index;

-

-	nb_pos = 1 << (N - 1);            /* nb_pos = (1<<(N-1));  */

-	/*-------------------------------------------------------*

-	 * Quantization of 4 pulses with 4*N+1 bits:             *

-	 *-------------------------------------------------------*/

-	if (((pos1 ^ pos2) & nb_pos) == 0)

-	{

-		index = quant_2p_2N1(pos1, pos2, sub(N, 1));    /* index = quant_2p_2N1(pos1, pos2, (N-1)); */

-		/* index += (pos1 & nb_pos) << N;	 */

-		index = vo_L_add(index, (L_deposit_l((Word16) (pos1 & nb_pos)) << N));  

-		/* index += quant_2p_2N1(pos3, pos4, N) << (2*N); */

-		index = vo_L_add(index, (quant_2p_2N1(pos3, pos4, N) << (N << 1)));

-	} else if (((pos1 ^ pos3) & nb_pos) == 0)

-	{

-		index = quant_2p_2N1(pos1, pos3, (N - 1));

-		/* index += (pos1 & nb_pos) << N; */

-		index = vo_L_add(index, (L_deposit_l((Word16) (pos1 & nb_pos)) << N));  

-		/* index += quant_2p_2N1(pos2, pos4, N) << (2*N); */

-		index = vo_L_add(index, (quant_2p_2N1(pos2, pos4, N) << (N << 1)));

-	} else

-	{

-		index = quant_2p_2N1(pos2, pos3, (N - 1));

-		/* index += (pos2 & nb_pos) << N; */

-		index = vo_L_add(index, (L_deposit_l((Word16) (pos2 & nb_pos)) << N));  

-		/* index += quant_2p_2N1(pos1, pos4, N) << (2*N); */

-		index = vo_L_add(index, (quant_2p_2N1(pos1, pos4, N) << (N << 1)));

-	}

-	return (index);

-}

-

-

-Word32 quant_4p_4N(                        /* (o) return 4*N bits             */

-		Word16 pos[],                         /* (i) position of the pulse 1..4  */

-		Word16 N)                             /* (i) number of bits for position */

-{

-	Word16 nb_pos, mask, n_1, tmp;

-	Word16 posA[4], posB[4];

-	Word32 i, j, k, index;

-

-	n_1 = (Word16) (N - 1);                

-	nb_pos = (1 << n_1);                  /* nb_pos = (1<<n_1); */

-	mask = vo_sub((1 << N), 1);              /* mask = ((1<<N)-1); */

-

-	i = 0;                                 

-	j = 0;                                 

-	for (k = 0; k < 4; k++)

-	{

-		if ((pos[k] & nb_pos) == 0)

-		{

-			posA[i++] = pos[k];            

-		} else

-		{

-			posB[j++] = pos[k];            

-		}

-	}

-

-	switch (i)

-	{

-		case 0:

-			tmp = vo_sub((N << 2), 3);           /* index = 1 << ((4*N)-3); */

-			index = (1L << tmp);

-			/* index += quant_4p_4N1(posB[0], posB[1], posB[2], posB[3], n_1); */

-			index = vo_L_add(index, quant_4p_4N1(posB[0], posB[1], posB[2], posB[3], n_1));

-			break;

-		case 1:

-			/* index = quant_1p_N1(posA[0], n_1) << ((3*n_1)+1); */

-			tmp = add1((Word16)((vo_L_mult(3, n_1) >> 1)), 1);

-			index = L_shl(quant_1p_N1(posA[0], n_1), tmp);

-			/* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1); */

-			index = vo_L_add(index, quant_3p_3N1(posB[0], posB[1], posB[2], n_1));

-			break;

-		case 2:

-			tmp = ((n_1 << 1) + 1);         /* index = quant_2p_2N1(posA[0], posA[1], n_1) << ((2*n_1)+1); */

-			index = L_shl(quant_2p_2N1(posA[0], posA[1], n_1), tmp);

-			/* index += quant_2p_2N1(posB[0], posB[1], n_1); */

-			index = vo_L_add(index, quant_2p_2N1(posB[0], posB[1], n_1));

-			break;

-		case 3:

-			/* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << N; */

-			index = L_shl(quant_3p_3N1(posA[0], posA[1], posA[2], n_1), N);

-			index = vo_L_add(index, quant_1p_N1(posB[0], n_1));        /* index += quant_1p_N1(posB[0], n_1); */

-			break;

-		case 4:

-			index = quant_4p_4N1(posA[0], posA[1], posA[2], posA[3], n_1);

-			break;

-		default:

-			index = 0;

-			fprintf(stderr, "Error in function quant_4p_4N\n");

-	}

-	tmp = ((N << 2) - 2);               /* index += (i & 3) << ((4*N)-2); */

-	index = vo_L_add(index, L_shl((L_deposit_l(i) & (3L)), tmp));

-

-	return (index);

-}

-

-

-

-Word32 quant_5p_5N(                        /* (o) return 5*N bits             */

-		Word16 pos[],                         /* (i) position of the pulse 1..5  */

-		Word16 N)                             /* (i) number of bits for position */

-{

-	Word16 nb_pos, n_1, tmp;

-	Word16 posA[5], posB[5];

-	Word32 i, j, k, index, tmp2;

-

-	n_1 = (Word16) (N - 1);                

-	nb_pos = (1 << n_1);                  /* nb_pos = (1<<n_1); */

-

-	i = 0;                                 

-	j = 0;                                 

-	for (k = 0; k < 5; k++)

-	{

-		if ((pos[k] & nb_pos) == 0)

-		{

-			posA[i++] = pos[k];            

-		} else

-		{

-			posB[j++] = pos[k];            

-		}

-	}

-

-	switch (i)

-	{

-		case 0:

-			tmp = vo_sub((Word16)((vo_L_mult(5, N) >> 1)), 1);        /* ((5*N)-1)) */

-			index = L_shl(1L, tmp);   /* index = 1 << ((5*N)-1); */

-			tmp = add1((N << 1), 1);  /* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1) << ((2*N)+1);*/

-			tmp2 = L_shl(quant_3p_3N1(posB[0], posB[1], posB[2], n_1), tmp);

-			index = vo_L_add(index, tmp2);

-			index = vo_L_add(index, quant_2p_2N1(posB[3], posB[4], N));        /* index += quant_2p_2N1(posB[3], posB[4], N); */

-			break;

-		case 1:

-			tmp = vo_sub((Word16)((vo_L_mult(5, N) >> 1)), 1);        /* index = 1 << ((5*N)-1); */

-			index = L_shl(1L, tmp);

-			tmp = add1((N << 1), 1);   /* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1) <<((2*N)+1);  */

-			tmp2 = L_shl(quant_3p_3N1(posB[0], posB[1], posB[2], n_1), tmp);

-			index = vo_L_add(index, tmp2);

-			index = vo_L_add(index, quant_2p_2N1(posB[3], posA[0], N));        /* index += quant_2p_2N1(posB[3], posA[0], N); */

-			break;

-		case 2:

-			tmp = vo_sub((Word16)((vo_L_mult(5, N) >> 1)), 1);        /* ((5*N)-1)) */

-			index = L_shl(1L, tmp);            /* index = 1 << ((5*N)-1); */

-			tmp = add1((N << 1), 1);           /* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1) << ((2*N)+1);  */

-			tmp2 = L_shl(quant_3p_3N1(posB[0], posB[1], posB[2], n_1), tmp);

-			index = vo_L_add(index, tmp2);

-			index = vo_L_add(index, quant_2p_2N1(posA[0], posA[1], N));        /* index += quant_2p_2N1(posA[0], posA[1], N); */

-			break;

-		case 3:

-			tmp = add1((N << 1), 1);           /* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << ((2*N)+1);  */

-			index = L_shl(quant_3p_3N1(posA[0], posA[1], posA[2], n_1), tmp);

-			index = vo_L_add(index, quant_2p_2N1(posB[0], posB[1], N));        /* index += quant_2p_2N1(posB[0], posB[1], N); */

-			break;

-		case 4:

-			tmp = add1((N << 1), 1);           /* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << ((2*N)+1);  */

-			index = L_shl(quant_3p_3N1(posA[0], posA[1], posA[2], n_1), tmp);

-			index = vo_L_add(index, quant_2p_2N1(posA[3], posB[0], N));        /* index += quant_2p_2N1(posA[3], posB[0], N); */

-			break;

-		case 5:

-			tmp = add1((N << 1), 1);           /* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << ((2*N)+1);  */

-			index = L_shl(quant_3p_3N1(posA[0], posA[1], posA[2], n_1), tmp);

-			index = vo_L_add(index, quant_2p_2N1(posA[3], posA[4], N));        /* index += quant_2p_2N1(posA[3], posA[4], N); */

-			break;

-		default:

-			index = 0;

-			fprintf(stderr, "Error in function quant_5p_5N\n");

-	}

-

-	return (index);

-}

-

-

-Word32 quant_6p_6N_2(                      /* (o) return (6*N)-2 bits         */

-		Word16 pos[],                         /* (i) position of the pulse 1..6  */

-		Word16 N)                             /* (i) number of bits for position */

-{

-	Word16 nb_pos, n_1;

-	Word16 posA[6], posB[6];

-	Word32 i, j, k, index;

-

-	/* !!  N and n_1 are constants -> it doesn't need to be operated by Basic Operators */

-	n_1 = (Word16) (N - 1);                

-	nb_pos = (1 << n_1);                  /* nb_pos = (1<<n_1); */

-

-	i = 0;                                 

-	j = 0;                                 

-	for (k = 0; k < 6; k++)

-	{

-		if ((pos[k] & nb_pos) == 0)

-		{

-			posA[i++] = pos[k];            

-		} else

-		{

-			posB[j++] = pos[k];            

-		}

-	}

-

-	switch (i)

-	{

-		case 0:

-			index = (1 << (Word16) (6 * N - 5));        /* index = 1 << ((6*N)-5); */

-			index = vo_L_add(index, (quant_5p_5N(posB, n_1) << N)); /* index += quant_5p_5N(posB, n_1) << N; */

-			index = vo_L_add(index, quant_1p_N1(posB[5], n_1));        /* index += quant_1p_N1(posB[5], n_1); */

-			break;

-		case 1:

-			index = (1L << (Word16) (6 * N - 5));        /* index = 1 << ((6*N)-5); */

-			index = vo_L_add(index, (quant_5p_5N(posB, n_1) << N)); /* index += quant_5p_5N(posB, n_1) << N; */

-			index = vo_L_add(index, quant_1p_N1(posA[0], n_1));        /* index += quant_1p_N1(posA[0], n_1); */

-			break;

-		case 2:

-			index = (1L << (Word16) (6 * N - 5));        /* index = 1 << ((6*N)-5); */

-			/* index += quant_4p_4N(posB, n_1) << ((2*n_1)+1); */

-			index = vo_L_add(index, (quant_4p_4N(posB, n_1) << (Word16) (2 * n_1 + 1)));

-			index = vo_L_add(index, quant_2p_2N1(posA[0], posA[1], n_1));      /* index += quant_2p_2N1(posA[0], posA[1], n_1); */

-			break;

-		case 3:

-			index = (quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << (Word16) (3 * n_1 + 1));    

-			                                  /* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << ((3*n_1)+1); */

-			index =vo_L_add(index, quant_3p_3N1(posB[0], posB[1], posB[2], n_1));     

-			                                 /* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1); */

-			break;

-		case 4:

-			i = 2;                            

-			index = (quant_4p_4N(posA, n_1) << (Word16) (2 * n_1 + 1));  /* index = quant_4p_4N(posA, n_1) << ((2*n_1)+1); */

-			index = vo_L_add(index, quant_2p_2N1(posB[0], posB[1], n_1));      /* index += quant_2p_2N1(posB[0], posB[1], n_1); */

-			break;

-		case 5:

-			i = 1;                            

-			index = (quant_5p_5N(posA, n_1) << N);       /* index = quant_5p_5N(posA, n_1) << N; */

-			index = vo_L_add(index, quant_1p_N1(posB[0], n_1));        /* index += quant_1p_N1(posB[0], n_1); */

-			break;

-		case 6:

-			i = 0;                             

-			index = (quant_5p_5N(posA, n_1) << N);       /* index = quant_5p_5N(posA, n_1) << N; */

-			index = vo_L_add(index, quant_1p_N1(posA[5], n_1));        /* index += quant_1p_N1(posA[5], n_1); */

-			break;

-		default:

-			index = 0;

-			fprintf(stderr, "Error in function quant_6p_6N_2\n");

-	}

-	index = vo_L_add(index, ((L_deposit_l(i) & 3L) << (Word16) (6 * N - 4)));   /* index += (i & 3) << ((6*N)-4); */

-

-	return (index);

-}

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*      File: q_pulse.c                                                 *
+*                                                                      *
+*      Description: Coding and decoding of algebraic codebook          *
+*                                                                      *
+************************************************************************/
+
+#include <stdio.h>
+#include "typedef.h"
+#include "basic_op.h"
+#include "q_pulse.h"
+
+#define NB_POS 16                          /* pos in track, mask for sign bit */
+
+Word32 quant_1p_N1(                        /* (o) return N+1 bits             */
+		Word16 pos,                        /* (i) position of the pulse       */
+		Word16 N)                          /* (i) number of bits for position */
+{
+	Word16 mask;
+	Word32 index;
+
+	mask = (1 << N) - 1;              /* mask = ((1<<N)-1); */
+	/*-------------------------------------------------------*
+	 * Quantization of 1 pulse with N+1 bits:                *
+	 *-------------------------------------------------------*/
+	index = L_deposit_l((Word16) (pos & mask));
+	if ((pos & NB_POS) != 0)
+	{
+		index = vo_L_add(index, L_deposit_l(1 << N));   /* index += 1 << N; */
+	}
+	return (index);
+}
+
+
+Word32 quant_2p_2N1(                       /* (o) return (2*N)+1 bits         */
+		Word16 pos1,                          /* (i) position of the pulse 1     */
+		Word16 pos2,                          /* (i) position of the pulse 2     */
+		Word16 N)                             /* (i) number of bits for position */
+{
+	Word16 mask, tmp;
+	Word32 index;
+	mask = (1 << N) - 1;              /* mask = ((1<<N)-1); */
+	/*-------------------------------------------------------*
+	 * Quantization of 2 pulses with 2*N+1 bits:             *
+	 *-------------------------------------------------------*/
+	if (((pos2 ^ pos1) & NB_POS) == 0)
+	{
+		/* sign of 1st pulse == sign of 2th pulse */
+		if(pos1 <= pos2)          /* ((pos1 - pos2) <= 0) */
+		{
+			/* index = ((pos1 & mask) << N) + (pos2 & mask); */
+			index = L_deposit_l(add1((((Word16) (pos1 & mask)) << N), ((Word16) (pos2 & mask))));
+		} else
+		{
+			/* ((pos2 & mask) << N) + (pos1 & mask); */
+			index = L_deposit_l(add1((((Word16) (pos2 & mask)) << N), ((Word16) (pos1 & mask))));
+		}
+		if ((pos1 & NB_POS) != 0)
+		{
+			tmp = (N << 1);
+			index = vo_L_add(index, (1L << tmp));       /* index += 1 << (2*N); */
+		}
+	} else
+	{
+		/* sign of 1st pulse != sign of 2th pulse */
+		if (vo_sub((Word16) (pos1 & mask), (Word16) (pos2 & mask)) <= 0)
+		{
+			/* index = ((pos2 & mask) << N) + (pos1 & mask); */
+			index = L_deposit_l(add1((((Word16) (pos2 & mask)) << N), ((Word16) (pos1 & mask))));
+			if ((pos2 & NB_POS) != 0)
+			{
+				tmp = (N << 1);           /* index += 1 << (2*N); */
+				index = vo_L_add(index, (1L << tmp));
+			}
+		} else
+		{
+			/* index = ((pos1 & mask) << N) + (pos2 & mask);	 */
+			index = L_deposit_l(add1((((Word16) (pos1 & mask)) << N), ((Word16) (pos2 & mask))));
+			if ((pos1 & NB_POS) != 0)
+			{
+				tmp = (N << 1);
+				index = vo_L_add(index, (1 << tmp));    /* index += 1 << (2*N); */
+			}
+		}
+	}
+	return (index);
+}
+
+
+Word32 quant_3p_3N1(                       /* (o) return (3*N)+1 bits         */
+		Word16 pos1,                          /* (i) position of the pulse 1     */
+		Word16 pos2,                          /* (i) position of the pulse 2     */
+		Word16 pos3,                          /* (i) position of the pulse 3     */
+		Word16 N)                             /* (i) number of bits for position */
+{
+	Word16 nb_pos;
+	Word32 index;
+
+	nb_pos =(1 <<(N - 1));            /* nb_pos = (1<<(N-1)); */
+	/*-------------------------------------------------------*
+	 * Quantization of 3 pulses with 3*N+1 bits:             *
+	 *-------------------------------------------------------*/
+	if (((pos1 ^ pos2) & nb_pos) == 0)
+	{
+		index = quant_2p_2N1(pos1, pos2, sub(N, 1));    /* index = quant_2p_2N1(pos1, pos2, (N-1)); */
+		/* index += (pos1 & nb_pos) << N; */
+		index = vo_L_add(index, (L_deposit_l((Word16) (pos1 & nb_pos)) << N));
+		/* index += quant_1p_N1(pos3, N) << (2*N); */
+		index = vo_L_add(index, (quant_1p_N1(pos3, N)<<(N << 1)));
+
+	} else if (((pos1 ^ pos3) & nb_pos) == 0)
+	{
+		index = quant_2p_2N1(pos1, pos3, sub(N, 1));    /* index = quant_2p_2N1(pos1, pos3, (N-1)); */
+		index = vo_L_add(index, (L_deposit_l((Word16) (pos1 & nb_pos)) << N));
+		/* index += (pos1 & nb_pos) << N; */
+		index = vo_L_add(index, (quant_1p_N1(pos2, N) << (N << 1)));
+		/* index += quant_1p_N1(pos2, N) <<
+		 * (2*N); */
+	} else
+	{
+		index = quant_2p_2N1(pos2, pos3, (N - 1));    /* index = quant_2p_2N1(pos2, pos3, (N-1)); */
+		/* index += (pos2 & nb_pos) << N;			 */
+		index = vo_L_add(index, (L_deposit_l((Word16) (pos2 & nb_pos)) << N));
+		/* index += quant_1p_N1(pos1, N) << (2*N);	 */
+		index = vo_L_add(index, (quant_1p_N1(pos1, N) << (N << 1)));
+	}
+	return (index);
+}
+
+
+Word32 quant_4p_4N1(                       /* (o) return (4*N)+1 bits         */
+		Word16 pos1,                          /* (i) position of the pulse 1     */
+		Word16 pos2,                          /* (i) position of the pulse 2     */
+		Word16 pos3,                          /* (i) position of the pulse 3     */
+		Word16 pos4,                          /* (i) position of the pulse 4     */
+		Word16 N)                             /* (i) number of bits for position */
+{
+	Word16 nb_pos;
+	Word32 index;
+
+	nb_pos = 1 << (N - 1);            /* nb_pos = (1<<(N-1));  */
+	/*-------------------------------------------------------*
+	 * Quantization of 4 pulses with 4*N+1 bits:             *
+	 *-------------------------------------------------------*/
+	if (((pos1 ^ pos2) & nb_pos) == 0)
+	{
+		index = quant_2p_2N1(pos1, pos2, sub(N, 1));    /* index = quant_2p_2N1(pos1, pos2, (N-1)); */
+		/* index += (pos1 & nb_pos) << N;	 */
+		index = vo_L_add(index, (L_deposit_l((Word16) (pos1 & nb_pos)) << N));
+		/* index += quant_2p_2N1(pos3, pos4, N) << (2*N); */
+		index = vo_L_add(index, (quant_2p_2N1(pos3, pos4, N) << (N << 1)));
+	} else if (((pos1 ^ pos3) & nb_pos) == 0)
+	{
+		index = quant_2p_2N1(pos1, pos3, (N - 1));
+		/* index += (pos1 & nb_pos) << N; */
+		index = vo_L_add(index, (L_deposit_l((Word16) (pos1 & nb_pos)) << N));
+		/* index += quant_2p_2N1(pos2, pos4, N) << (2*N); */
+		index = vo_L_add(index, (quant_2p_2N1(pos2, pos4, N) << (N << 1)));
+	} else
+	{
+		index = quant_2p_2N1(pos2, pos3, (N - 1));
+		/* index += (pos2 & nb_pos) << N; */
+		index = vo_L_add(index, (L_deposit_l((Word16) (pos2 & nb_pos)) << N));
+		/* index += quant_2p_2N1(pos1, pos4, N) << (2*N); */
+		index = vo_L_add(index, (quant_2p_2N1(pos1, pos4, N) << (N << 1)));
+	}
+	return (index);
+}
+
+
+Word32 quant_4p_4N(                        /* (o) return 4*N bits             */
+		Word16 pos[],                         /* (i) position of the pulse 1..4  */
+		Word16 N)                             /* (i) number of bits for position */
+{
+	Word16 nb_pos, mask, n_1, tmp;
+	Word16 posA[4], posB[4];
+	Word32 i, j, k, index;
+
+	n_1 = (Word16) (N - 1);
+	nb_pos = (1 << n_1);                  /* nb_pos = (1<<n_1); */
+	mask = vo_sub((1 << N), 1);              /* mask = ((1<<N)-1); */
+
+	i = 0;
+	j = 0;
+	for (k = 0; k < 4; k++)
+	{
+		if ((pos[k] & nb_pos) == 0)
+		{
+			posA[i++] = pos[k];
+		} else
+		{
+			posB[j++] = pos[k];
+		}
+	}
+
+	switch (i)
+	{
+		case 0:
+			tmp = vo_sub((N << 2), 3);           /* index = 1 << ((4*N)-3); */
+			index = (1L << tmp);
+			/* index += quant_4p_4N1(posB[0], posB[1], posB[2], posB[3], n_1); */
+			index = vo_L_add(index, quant_4p_4N1(posB[0], posB[1], posB[2], posB[3], n_1));
+			break;
+		case 1:
+			/* index = quant_1p_N1(posA[0], n_1) << ((3*n_1)+1); */
+			tmp = add1((Word16)((vo_L_mult(3, n_1) >> 1)), 1);
+			index = L_shl(quant_1p_N1(posA[0], n_1), tmp);
+			/* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1); */
+			index = vo_L_add(index, quant_3p_3N1(posB[0], posB[1], posB[2], n_1));
+			break;
+		case 2:
+			tmp = ((n_1 << 1) + 1);         /* index = quant_2p_2N1(posA[0], posA[1], n_1) << ((2*n_1)+1); */
+			index = L_shl(quant_2p_2N1(posA[0], posA[1], n_1), tmp);
+			/* index += quant_2p_2N1(posB[0], posB[1], n_1); */
+			index = vo_L_add(index, quant_2p_2N1(posB[0], posB[1], n_1));
+			break;
+		case 3:
+			/* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << N; */
+			index = L_shl(quant_3p_3N1(posA[0], posA[1], posA[2], n_1), N);
+			index = vo_L_add(index, quant_1p_N1(posB[0], n_1));        /* index += quant_1p_N1(posB[0], n_1); */
+			break;
+		case 4:
+			index = quant_4p_4N1(posA[0], posA[1], posA[2], posA[3], n_1);
+			break;
+		default:
+			index = 0;
+			fprintf(stderr, "Error in function quant_4p_4N\n");
+	}
+	tmp = ((N << 2) - 2);               /* index += (i & 3) << ((4*N)-2); */
+	index = vo_L_add(index, L_shl((L_deposit_l(i) & (3L)), tmp));
+
+	return (index);
+}
+
+
+
+Word32 quant_5p_5N(                        /* (o) return 5*N bits             */
+		Word16 pos[],                         /* (i) position of the pulse 1..5  */
+		Word16 N)                             /* (i) number of bits for position */
+{
+	Word16 nb_pos, n_1, tmp;
+	Word16 posA[5], posB[5];
+	Word32 i, j, k, index, tmp2;
+
+	n_1 = (Word16) (N - 1);
+	nb_pos = (1 << n_1);                  /* nb_pos = (1<<n_1); */
+
+	i = 0;
+	j = 0;
+	for (k = 0; k < 5; k++)
+	{
+		if ((pos[k] & nb_pos) == 0)
+		{
+			posA[i++] = pos[k];
+		} else
+		{
+			posB[j++] = pos[k];
+		}
+	}
+
+	switch (i)
+	{
+		case 0:
+			tmp = vo_sub((Word16)((vo_L_mult(5, N) >> 1)), 1);        /* ((5*N)-1)) */
+			index = L_shl(1L, tmp);   /* index = 1 << ((5*N)-1); */
+			tmp = add1((N << 1), 1);  /* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1) << ((2*N)+1);*/
+			tmp2 = L_shl(quant_3p_3N1(posB[0], posB[1], posB[2], n_1), tmp);
+			index = vo_L_add(index, tmp2);
+			index = vo_L_add(index, quant_2p_2N1(posB[3], posB[4], N));        /* index += quant_2p_2N1(posB[3], posB[4], N); */
+			break;
+		case 1:
+			tmp = vo_sub((Word16)((vo_L_mult(5, N) >> 1)), 1);        /* index = 1 << ((5*N)-1); */
+			index = L_shl(1L, tmp);
+			tmp = add1((N << 1), 1);   /* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1) <<((2*N)+1);  */
+			tmp2 = L_shl(quant_3p_3N1(posB[0], posB[1], posB[2], n_1), tmp);
+			index = vo_L_add(index, tmp2);
+			index = vo_L_add(index, quant_2p_2N1(posB[3], posA[0], N));        /* index += quant_2p_2N1(posB[3], posA[0], N); */
+			break;
+		case 2:
+			tmp = vo_sub((Word16)((vo_L_mult(5, N) >> 1)), 1);        /* ((5*N)-1)) */
+			index = L_shl(1L, tmp);            /* index = 1 << ((5*N)-1); */
+			tmp = add1((N << 1), 1);           /* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1) << ((2*N)+1);  */
+			tmp2 = L_shl(quant_3p_3N1(posB[0], posB[1], posB[2], n_1), tmp);
+			index = vo_L_add(index, tmp2);
+			index = vo_L_add(index, quant_2p_2N1(posA[0], posA[1], N));        /* index += quant_2p_2N1(posA[0], posA[1], N); */
+			break;
+		case 3:
+			tmp = add1((N << 1), 1);           /* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << ((2*N)+1);  */
+			index = L_shl(quant_3p_3N1(posA[0], posA[1], posA[2], n_1), tmp);
+			index = vo_L_add(index, quant_2p_2N1(posB[0], posB[1], N));        /* index += quant_2p_2N1(posB[0], posB[1], N); */
+			break;
+		case 4:
+			tmp = add1((N << 1), 1);           /* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << ((2*N)+1);  */
+			index = L_shl(quant_3p_3N1(posA[0], posA[1], posA[2], n_1), tmp);
+			index = vo_L_add(index, quant_2p_2N1(posA[3], posB[0], N));        /* index += quant_2p_2N1(posA[3], posB[0], N); */
+			break;
+		case 5:
+			tmp = add1((N << 1), 1);           /* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << ((2*N)+1);  */
+			index = L_shl(quant_3p_3N1(posA[0], posA[1], posA[2], n_1), tmp);
+			index = vo_L_add(index, quant_2p_2N1(posA[3], posA[4], N));        /* index += quant_2p_2N1(posA[3], posA[4], N); */
+			break;
+		default:
+			index = 0;
+			fprintf(stderr, "Error in function quant_5p_5N\n");
+	}
+
+	return (index);
+}
+
+
+Word32 quant_6p_6N_2(                      /* (o) return (6*N)-2 bits         */
+		Word16 pos[],                         /* (i) position of the pulse 1..6  */
+		Word16 N)                             /* (i) number of bits for position */
+{
+	Word16 nb_pos, n_1;
+	Word16 posA[6], posB[6];
+	Word32 i, j, k, index;
+
+	/* !!  N and n_1 are constants -> it doesn't need to be operated by Basic Operators */
+	n_1 = (Word16) (N - 1);
+	nb_pos = (1 << n_1);                  /* nb_pos = (1<<n_1); */
+
+	i = 0;
+	j = 0;
+	for (k = 0; k < 6; k++)
+	{
+		if ((pos[k] & nb_pos) == 0)
+		{
+			posA[i++] = pos[k];
+		} else
+		{
+			posB[j++] = pos[k];
+		}
+	}
+
+	switch (i)
+	{
+		case 0:
+			index = (1 << (Word16) (6 * N - 5));        /* index = 1 << ((6*N)-5); */
+			index = vo_L_add(index, (quant_5p_5N(posB, n_1) << N)); /* index += quant_5p_5N(posB, n_1) << N; */
+			index = vo_L_add(index, quant_1p_N1(posB[5], n_1));        /* index += quant_1p_N1(posB[5], n_1); */
+			break;
+		case 1:
+			index = (1L << (Word16) (6 * N - 5));        /* index = 1 << ((6*N)-5); */
+			index = vo_L_add(index, (quant_5p_5N(posB, n_1) << N)); /* index += quant_5p_5N(posB, n_1) << N; */
+			index = vo_L_add(index, quant_1p_N1(posA[0], n_1));        /* index += quant_1p_N1(posA[0], n_1); */
+			break;
+		case 2:
+			index = (1L << (Word16) (6 * N - 5));        /* index = 1 << ((6*N)-5); */
+			/* index += quant_4p_4N(posB, n_1) << ((2*n_1)+1); */
+			index = vo_L_add(index, (quant_4p_4N(posB, n_1) << (Word16) (2 * n_1 + 1)));
+			index = vo_L_add(index, quant_2p_2N1(posA[0], posA[1], n_1));      /* index += quant_2p_2N1(posA[0], posA[1], n_1); */
+			break;
+		case 3:
+			index = (quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << (Word16) (3 * n_1 + 1));
+			                                  /* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << ((3*n_1)+1); */
+			index =vo_L_add(index, quant_3p_3N1(posB[0], posB[1], posB[2], n_1));
+			                                 /* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1); */
+			break;
+		case 4:
+			i = 2;
+			index = (quant_4p_4N(posA, n_1) << (Word16) (2 * n_1 + 1));  /* index = quant_4p_4N(posA, n_1) << ((2*n_1)+1); */
+			index = vo_L_add(index, quant_2p_2N1(posB[0], posB[1], n_1));      /* index += quant_2p_2N1(posB[0], posB[1], n_1); */
+			break;
+		case 5:
+			i = 1;
+			index = (quant_5p_5N(posA, n_1) << N);       /* index = quant_5p_5N(posA, n_1) << N; */
+			index = vo_L_add(index, quant_1p_N1(posB[0], n_1));        /* index += quant_1p_N1(posB[0], n_1); */
+			break;
+		case 6:
+			i = 0;
+			index = (quant_5p_5N(posA, n_1) << N);       /* index = quant_5p_5N(posA, n_1) << N; */
+			index = vo_L_add(index, quant_1p_N1(posA[5], n_1));        /* index += quant_1p_N1(posA[5], n_1); */
+			break;
+		default:
+			index = 0;
+			fprintf(stderr, "Error in function quant_6p_6N_2\n");
+	}
+	index = vo_L_add(index, ((L_deposit_l(i) & 3L) << (Word16) (6 * N - 4)));   /* index += (i & 3) << ((6*N)-4); */
+
+	return (index);
+}
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/qisf_ns.c b/media/libstagefright/codecs/amrwbenc/src/qisf_ns.c
index 00b0a53..fc2f00d 100644
--- a/media/libstagefright/codecs/amrwbenc/src/qisf_ns.c
+++ b/media/libstagefright/codecs/amrwbenc/src/qisf_ns.c
@@ -1,111 +1,111 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***************************************************************************

-*      File: qisf_ns.c                                                     *

-*                                                                          *

-*      Description: Coding/Decoding of ISF parameters for background noise.*

-*                    The ISF vector is quantized using VQ with split-by-5  *

-*                                                                          *

-****************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "acelp.h"

-#include "qisf_ns.tab"                     /* Codebooks of ISFs */

-

-/*------------------------------------------------------------------*

-* routine:   Qisf_ns()                                             *

-*            ~~~~~~~~~                                             *

-*------------------------------------------------------------------*/

-

-void Qisf_ns(

-		Word16 * isf1,                        /* input : ISF in the frequency domain (0..0.5) */

-		Word16 * isf_q,                       /* output: quantized ISF                        */

-		Word16 * indice                       /* output: quantization indices                 */

-	    )

-{

-	Word16 i;

-	Word32 tmp;

-

-	for (i = 0; i < ORDER; i++)

-	{

-		isf_q[i] = sub(isf1[i], mean_isf_noise[i]);     

-	}

-

-	indice[0] = Sub_VQ(&isf_q[0], dico1_isf_noise, 2, SIZE_BK_NOISE1, &tmp);    

-	indice[1] = Sub_VQ(&isf_q[2], dico2_isf_noise, 3, SIZE_BK_NOISE2, &tmp);    

-	indice[2] = Sub_VQ(&isf_q[5], dico3_isf_noise, 3, SIZE_BK_NOISE3, &tmp);    

-	indice[3] = Sub_VQ(&isf_q[8], dico4_isf_noise, 4, SIZE_BK_NOISE4, &tmp);    

-	indice[4] = Sub_VQ(&isf_q[12], dico5_isf_noise, 4, SIZE_BK_NOISE5, &tmp);   

-

-	/* decoding the ISFs */

-

-	Disf_ns(indice, isf_q);

-

-	return;

-}

-

-/********************************************************************

-* Function:   Disf_ns()                                             *

-*            ~~~~~~~~~                                              *

-* Decoding of ISF parameters                                        *

-*-------------------------------------------------------------------*

-*  Arguments:                                                       *

-*    indice[] : indices of the selected codebook entries            *

-*    isf[]    : quantized ISFs (in frequency domain)                *

-*********************************************************************/

-

-void Disf_ns(

-		Word16 * indice,                      /* input:  quantization indices                  */

-		Word16 * isf_q                        /* input : ISF in the frequency domain (0..0.5)  */

-	    )

-{

-	Word16 i;

-

-	for (i = 0; i < 2; i++)

-	{

-		isf_q[i] = dico1_isf_noise[indice[0] * 2 + i];  

-	}

-	for (i = 0; i < 3; i++)

-	{

-		isf_q[i + 2] = dico2_isf_noise[indice[1] * 3 + i];      

-	}

-	for (i = 0; i < 3; i++)

-	{

-		isf_q[i + 5] = dico3_isf_noise[indice[2] * 3 + i];      

-	}

-	for (i = 0; i < 4; i++)

-	{

-		isf_q[i + 8] = dico4_isf_noise[indice[3] * 4 + i];      

-	}

-	for (i = 0; i < 4; i++)

-	{

-		isf_q[i + 12] = dico5_isf_noise[indice[4] * 4 + i];     

-	}

-

-	for (i = 0; i < ORDER; i++)

-	{

-		isf_q[i] = add(isf_q[i], mean_isf_noise[i]);   

-	}

-

-	Reorder_isf(isf_q, ISF_GAP, ORDER);

-

-	return;

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***************************************************************************
+*      File: qisf_ns.c                                                     *
+*                                                                          *
+*      Description: Coding/Decoding of ISF parameters for background noise.*
+*                    The ISF vector is quantized using VQ with split-by-5  *
+*                                                                          *
+****************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "acelp.h"
+#include "qisf_ns.tab"                     /* Codebooks of ISFs */
+
+/*------------------------------------------------------------------*
+* routine:   Qisf_ns()                                             *
+*            ~~~~~~~~~                                             *
+*------------------------------------------------------------------*/
+
+void Qisf_ns(
+		Word16 * isf1,                        /* input : ISF in the frequency domain (0..0.5) */
+		Word16 * isf_q,                       /* output: quantized ISF                        */
+		Word16 * indice                       /* output: quantization indices                 */
+	    )
+{
+	Word16 i;
+	Word32 tmp;
+
+	for (i = 0; i < ORDER; i++)
+	{
+		isf_q[i] = sub(isf1[i], mean_isf_noise[i]);
+	}
+
+	indice[0] = Sub_VQ(&isf_q[0], dico1_isf_noise, 2, SIZE_BK_NOISE1, &tmp);
+	indice[1] = Sub_VQ(&isf_q[2], dico2_isf_noise, 3, SIZE_BK_NOISE2, &tmp);
+	indice[2] = Sub_VQ(&isf_q[5], dico3_isf_noise, 3, SIZE_BK_NOISE3, &tmp);
+	indice[3] = Sub_VQ(&isf_q[8], dico4_isf_noise, 4, SIZE_BK_NOISE4, &tmp);
+	indice[4] = Sub_VQ(&isf_q[12], dico5_isf_noise, 4, SIZE_BK_NOISE5, &tmp);
+
+	/* decoding the ISFs */
+
+	Disf_ns(indice, isf_q);
+
+	return;
+}
+
+/********************************************************************
+* Function:   Disf_ns()                                             *
+*            ~~~~~~~~~                                              *
+* Decoding of ISF parameters                                        *
+*-------------------------------------------------------------------*
+*  Arguments:                                                       *
+*    indice[] : indices of the selected codebook entries            *
+*    isf[]    : quantized ISFs (in frequency domain)                *
+*********************************************************************/
+
+void Disf_ns(
+		Word16 * indice,                      /* input:  quantization indices                  */
+		Word16 * isf_q                        /* input : ISF in the frequency domain (0..0.5)  */
+	    )
+{
+	Word16 i;
+
+	for (i = 0; i < 2; i++)
+	{
+		isf_q[i] = dico1_isf_noise[indice[0] * 2 + i];
+	}
+	for (i = 0; i < 3; i++)
+	{
+		isf_q[i + 2] = dico2_isf_noise[indice[1] * 3 + i];
+	}
+	for (i = 0; i < 3; i++)
+	{
+		isf_q[i + 5] = dico3_isf_noise[indice[2] * 3 + i];
+	}
+	for (i = 0; i < 4; i++)
+	{
+		isf_q[i + 8] = dico4_isf_noise[indice[3] * 4 + i];
+	}
+	for (i = 0; i < 4; i++)
+	{
+		isf_q[i + 12] = dico5_isf_noise[indice[4] * 4 + i];
+	}
+
+	for (i = 0; i < ORDER; i++)
+	{
+		isf_q[i] = add(isf_q[i], mean_isf_noise[i]);
+	}
+
+	Reorder_isf(isf_q, ISF_GAP, ORDER);
+
+	return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/qpisf_2s.c b/media/libstagefright/codecs/amrwbenc/src/qpisf_2s.c
index ccedb5c..c711cd0 100644
--- a/media/libstagefright/codecs/amrwbenc/src/qpisf_2s.c
+++ b/media/libstagefright/codecs/amrwbenc/src/qpisf_2s.c
@@ -1,542 +1,542 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*       File: apisf_2s.c                                               *

-*                                                                      *

-*       Description: Coding/Decodeing of ISF parameters with predication

-*       The ISF vector is quantized using two-stage VQ with split-by-2 *

-*       in 1st stage and split-by-5(or 3) in the second stage          *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "cnst.h"

-#include "acelp.h"

-#include "qpisf_2s.tab"                    /* Codebooks of isfs */

-

-#define MU         10923                   /* Prediction factor   (1.0/3.0) in Q15 */

-#define N_SURV_MAX 4                       /* 4 survivors max */

-#define ALPHA      29491                   /* 0. 9 in Q15     */

-#define ONE_ALPHA (32768-ALPHA)            /* (1.0 - ALPHA) in Q15 */

-

-/* private functions */

-static void VQ_stage1(

-		Word16 * x,                           /* input : ISF residual vector           */

-		Word16 * dico,                        /* input : quantization codebook         */

-		Word16 dim,                           /* input : dimention of vector           */

-		Word16 dico_size,                     /* input : size of quantization codebook */

-		Word16 * index,                       /* output: indices of survivors          */

-		Word16 surv                           /* input : number of survivor            */

-		);

-

-/**************************************************************************

-* Function:   Qpisf_2s_46B()                                              *

-*                                                                         *

-* Description: Quantization of isf parameters with prediction. (46 bits)  *

-*                                                                         *

-* The isf vector is quantized using two-stage VQ with split-by-2 in       *

-*  1st stage and split-by-5 in the second stage.                          *

-***************************************************************************/

-

-void Qpisf_2s_46b(

-		Word16 * isf1,                        /* (i) Q15 : ISF in the frequency domain (0..0.5) */

-		Word16 * isf_q,                       /* (o) Q15 : quantized ISF               (0..0.5) */

-		Word16 * past_isfq,                   /* (io)Q15 : past ISF quantizer                   */

-		Word16 * indice,                      /* (o)     : quantization indices                 */

-		Word16 nb_surv                        /* (i)     : number of survivor (1, 2, 3 or 4)    */

-		)

-{

-	Word16 tmp_ind[5];

-	Word16 surv1[N_SURV_MAX];              /* indices of survivors from 1st stage */

-	Word32 i, k, temp, min_err, distance;

-	Word16 isf[ORDER];

-	Word16 isf_stage2[ORDER];

-

-	for (i = 0; i < ORDER; i++)

-	{

-		isf[i] = vo_sub(isf1[i], mean_isf[i]);

-		isf[i] = vo_sub(isf[i], vo_mult(MU, past_isfq[i])); 

-	}

-

-	VQ_stage1(&isf[0], dico1_isf, 9, SIZE_BK1, surv1, nb_surv);

-

-	distance = MAX_32;          

-

-	for (k = 0; k < nb_surv; k++)

-	{

-		for (i = 0; i < 9; i++)

-		{

-			isf_stage2[i] = vo_sub(isf[i], dico1_isf[i + surv1[k] * 9]); 

-		}

-		tmp_ind[0] = Sub_VQ(&isf_stage2[0], dico21_isf, 3, SIZE_BK21, &min_err); 

-		temp = min_err;

-		tmp_ind[1] = Sub_VQ(&isf_stage2[3], dico22_isf, 3, SIZE_BK22, &min_err); 

-		temp = vo_L_add(temp, min_err);

-		tmp_ind[2] = Sub_VQ(&isf_stage2[6], dico23_isf, 3, SIZE_BK23, &min_err);  

-		temp = vo_L_add(temp, min_err);

-

-		if(temp < distance)

-		{

-			distance = temp;               

-			indice[0] = surv1[k];          

-			for (i = 0; i < 3; i++)

-			{

-				indice[i + 2] = tmp_ind[i];

-			}

-		}

-	}

-

-

-	VQ_stage1(&isf[9], dico2_isf, 7, SIZE_BK2, surv1, nb_surv);

-

-	distance = MAX_32;                   

-

-	for (k = 0; k < nb_surv; k++)

-	{

-		for (i = 0; i < 7; i++)

-		{

-			isf_stage2[i] = vo_sub(isf[9 + i], dico2_isf[i + surv1[k] * 7]);       

-		}

-

-		tmp_ind[0] = Sub_VQ(&isf_stage2[0], dico24_isf, 3, SIZE_BK24, &min_err);

-		temp = min_err; 

-		tmp_ind[1] = Sub_VQ(&isf_stage2[3], dico25_isf, 4, SIZE_BK25, &min_err);

-		temp = vo_L_add(temp, min_err);

-

-		if(temp < distance)

-		{

-			distance = temp;               

-			indice[1] = surv1[k];          

-			for (i = 0; i < 2; i++)

-			{

-				indice[i + 5] = tmp_ind[i];

-			}

-		}

-	}

-

-	Dpisf_2s_46b(indice, isf_q, past_isfq, isf_q, isf_q, 0, 0);

-

-	return;

-}

-

-/*****************************************************************************

-* Function:   Qpisf_2s_36B()                                                 *

-*                                                                            *

-* Description: Quantization of isf parameters with prediction. (36 bits)     *

-*                                                                            *

-* The isf vector is quantized using two-stage VQ with split-by-2 in          *

-*  1st stage and split-by-3 in the second stage.                             *

-******************************************************************************/

-

-void Qpisf_2s_36b(

-		Word16 * isf1,                        /* (i) Q15 : ISF in the frequency domain (0..0.5) */

-		Word16 * isf_q,                       /* (o) Q15 : quantized ISF               (0..0.5) */

-		Word16 * past_isfq,                   /* (io)Q15 : past ISF quantizer                   */

-		Word16 * indice,                      /* (o)     : quantization indices                 */

-		Word16 nb_surv                        /* (i)     : number of survivor (1, 2, 3 or 4)    */

-		)

-{

-	Word16 i, k, tmp_ind[5];

-	Word16 surv1[N_SURV_MAX];              /* indices of survivors from 1st stage */

-	Word32 temp, min_err, distance;

-	Word16 isf[ORDER];

-	Word16 isf_stage2[ORDER];

-

-	for (i = 0; i < ORDER; i++)

-	{

-		isf[i] = vo_sub(isf1[i], mean_isf[i]);

-		isf[i] = vo_sub(isf[i], vo_mult(MU, past_isfq[i]));

-	}

-

-	VQ_stage1(&isf[0], dico1_isf, 9, SIZE_BK1, surv1, nb_surv);

-

-	distance = MAX_32;                  

-

-	for (k = 0; k < nb_surv; k++)

-	{

-		for (i = 0; i < 9; i++)

-		{

-			isf_stage2[i] = vo_sub(isf[i], dico1_isf[i + surv1[k] * 9]); 

-		}

-

-		tmp_ind[0] = Sub_VQ(&isf_stage2[0], dico21_isf_36b, 5, SIZE_BK21_36b, &min_err);        

-		temp = min_err;                  

-		tmp_ind[1] = Sub_VQ(&isf_stage2[5], dico22_isf_36b, 4, SIZE_BK22_36b, &min_err);        

-		temp = vo_L_add(temp, min_err);

-

-		if(temp < distance)

-		{

-			distance = temp;               

-			indice[0] = surv1[k];          

-			for (i = 0; i < 2; i++)

-			{

-				indice[i + 2] = tmp_ind[i];

-			}

-		}

-	}

-

-	VQ_stage1(&isf[9], dico2_isf, 7, SIZE_BK2, surv1, nb_surv);

-	distance = MAX_32;                    

-

-	for (k = 0; k < nb_surv; k++)

-	{

-		for (i = 0; i < 7; i++)

-		{

-			isf_stage2[i] = vo_sub(isf[9 + i], dico2_isf[i + surv1[k] * 7]);     

-		}

-

-		tmp_ind[0] = Sub_VQ(&isf_stage2[0], dico23_isf_36b, 7, SIZE_BK23_36b, &min_err);  

-		temp = min_err;                  

-

-		if(temp < distance)

-		{

-			distance = temp;               

-			indice[1] = surv1[k];          

-			indice[4] = tmp_ind[0];        

-		}

-	}

-

-	Dpisf_2s_36b(indice, isf_q, past_isfq, isf_q, isf_q, 0, 0);

-

-	return;

-}

-

-/*********************************************************************

-* Function: Dpisf_2s_46b()                                           *

-*                                                                    *

-* Description: Decoding of ISF parameters                            *

-**********************************************************************/

-

-void Dpisf_2s_46b(

-		Word16 * indice,                      /* input:  quantization indices                       */

-		Word16 * isf_q,                       /* output: quantized ISF in frequency domain (0..0.5) */

-		Word16 * past_isfq,                   /* i/0   : past ISF quantizer                    */

-		Word16 * isfold,                      /* input : past quantized ISF                    */

-		Word16 * isf_buf,                     /* input : isf buffer                                                        */

-		Word16 bfi,                           /* input : Bad frame indicator                   */

-		Word16 enc_dec

-		)

-{

-	Word16 ref_isf[M], tmp;

-	Word32 i, j, L_tmp;

-

-	if (bfi == 0)                          /* Good frame */

-	{

-		for (i = 0; i < 9; i++)

-		{

-			isf_q[i] = dico1_isf[indice[0] * 9 + i];    

-		}

-		for (i = 0; i < 7; i++)

-		{

-			isf_q[i + 9] = dico2_isf[indice[1] * 7 + i];       

-		}

-

-		for (i = 0; i < 3; i++)

-		{

-			isf_q[i] = add1(isf_q[i], dico21_isf[indice[2] * 3 + i]);   

-			isf_q[i + 3] = add1(isf_q[i + 3], dico22_isf[indice[3] * 3 + i]);  

-			isf_q[i + 6] = add1(isf_q[i + 6], dico23_isf[indice[4] * 3 + i]); 

-			isf_q[i + 9] = add1(isf_q[i + 9], dico24_isf[indice[5] * 3 + i]); 

-		}

-

-		for (i = 0; i < 4; i++)

-		{

-			isf_q[i + 12] = add1(isf_q[i + 12], dico25_isf[indice[6] * 4 + i]);  

-		}

-

-		for (i = 0; i < ORDER; i++)

-		{

-			tmp = isf_q[i];               

-			isf_q[i] = add1(tmp, mean_isf[i]);  

-			isf_q[i] = add1(isf_q[i], vo_mult(MU, past_isfq[i]));

-			past_isfq[i] = tmp;  

-		}

-

-		if (enc_dec)

-		{

-			for (i = 0; i < M; i++)

-			{

-				for (j = (L_MEANBUF - 1); j > 0; j--)

-				{

-					isf_buf[j * M + i] = isf_buf[(j - 1) * M + i]; 

-				}

-				isf_buf[i] = isf_q[i]; 

-			}

-		}

-	} else

-	{                                      /* bad frame */

-		for (i = 0; i < M; i++)

-		{

-			L_tmp = mean_isf[i] << 14;

-			for (j = 0; j < L_MEANBUF; j++)

-			{

-				L_tmp += (isf_buf[j * M + i] << 14);

-			}

-			ref_isf[i] = vo_round(L_tmp);

-		}

-

-		/* use the past ISFs slightly shifted towards their mean */

-		for (i = 0; i < ORDER; i++)

-		{

-			isf_q[i] = add1(vo_mult(ALPHA, isfold[i]), vo_mult(ONE_ALPHA, ref_isf[i])); 

-		}

-

-		/* estimate past quantized residual to be used in next frame */

-		for (i = 0; i < ORDER; i++)

-		{

-			tmp = add1(ref_isf[i], vo_mult(past_isfq[i], MU));      /* predicted ISF */

-			past_isfq[i] = vo_sub(isf_q[i], tmp); 

-			past_isfq[i] = (past_isfq[i] >> 1);        /* past_isfq[i] *= 0.5 */

-		}

-	}

-

-	Reorder_isf(isf_q, ISF_GAP, ORDER);

-	return;

-}

-

-/*********************************************************************

-* Function:   Disf_2s_36b()                                          *

-*                                                                    *

-* Description: Decoding of ISF parameters                            *

-*********************************************************************/

-

-void Dpisf_2s_36b(

-		Word16 * indice,                      /* input:  quantization indices                       */

-		Word16 * isf_q,                       /* output: quantized ISF in frequency domain (0..0.5) */

-		Word16 * past_isfq,                   /* i/0   : past ISF quantizer                    */

-		Word16 * isfold,                      /* input : past quantized ISF                    */

-		Word16 * isf_buf,                     /* input : isf buffer                                                        */

-		Word16 bfi,                           /* input : Bad frame indicator                   */

-		Word16 enc_dec

-		)

-{

-	Word16 ref_isf[M], tmp;

-	Word32 i, j, L_tmp;

-

-	if (bfi == 0)                          /* Good frame */

-	{

-		for (i = 0; i < 9; i++)

-		{

-			isf_q[i] = dico1_isf[indice[0] * 9 + i];    

-		}

-		for (i = 0; i < 7; i++)

-		{

-			isf_q[i + 9] = dico2_isf[indice[1] * 7 + i];       

-		}

-

-		for (i = 0; i < 5; i++)

-		{

-			isf_q[i] = add1(isf_q[i], dico21_isf_36b[indice[2] * 5 + i]);       

-		}

-		for (i = 0; i < 4; i++)

-		{

-			isf_q[i + 5] = add1(isf_q[i + 5], dico22_isf_36b[indice[3] * 4 + i]);        

-		}

-		for (i = 0; i < 7; i++)

-		{

-			isf_q[i + 9] = add1(isf_q[i + 9], dico23_isf_36b[indice[4] * 7 + i]);       

-		}

-

-		for (i = 0; i < ORDER; i++)

-		{

-			tmp = isf_q[i];

-			isf_q[i] = add1(tmp, mean_isf[i]);   

-			isf_q[i] = add1(isf_q[i], vo_mult(MU, past_isfq[i]));   

-			past_isfq[i] = tmp;           

-		}

-

-

-		if (enc_dec)

-		{

-			for (i = 0; i < M; i++)

-			{

-				for (j = (L_MEANBUF - 1); j > 0; j--)

-				{

-					isf_buf[j * M + i] = isf_buf[(j - 1) * M + i];      

-				}

-				isf_buf[i] = isf_q[i];    

-			}

-		}

-	} else

-	{                                      /* bad frame */

-		for (i = 0; i < M; i++)

-		{

-			L_tmp = (mean_isf[i] << 14);

-			for (j = 0; j < L_MEANBUF; j++)

-			{

-				L_tmp += (isf_buf[j * M + i] << 14);

-			}

-			ref_isf[i] = vo_round(L_tmp);    

-		}

-

-		/* use the past ISFs slightly shifted towards their mean */

-		for (i = 0; i < ORDER; i++)

-		{

-			isf_q[i] = add1(vo_mult(ALPHA, isfold[i]), vo_mult(ONE_ALPHA, ref_isf[i]));        

-		}

-

-		/* estimate past quantized residual to be used in next frame */

-		for (i = 0; i < ORDER; i++)

-		{

-			tmp = add1(ref_isf[i], vo_mult(past_isfq[i], MU));      /* predicted ISF */

-			past_isfq[i] = vo_sub(isf_q[i], tmp);  

-			past_isfq[i] = past_isfq[i] >> 1;         /* past_isfq[i] *= 0.5 */

-		}

-	}

-

-	Reorder_isf(isf_q, ISF_GAP, ORDER);

-

-	return;

-}

-

-

-/***************************************************************************

-* Function:  Reorder_isf()                                                 *

-*                                                                          *

-* Description: To make sure that the  isfs are properly order and to       *

-*              keep a certain minimum distance between consecutive isfs.   *

-*--------------------------------------------------------------------------*

-*    Argument         description                     in/out               *

-*                                                                          *

-*     isf[]           vector of isfs                    i/o                *

-*     min_dist        minimum required distance         i                  *

-*     n               LPC order                         i                  *

-****************************************************************************/

-

-void Reorder_isf(

-		Word16 * isf,                         /* (i/o) Q15: ISF in the frequency domain (0..0.5) */

-		Word16 min_dist,                      /* (i) Q15  : minimum distance to keep             */

-		Word16 n                              /* (i)      : number of ISF                        */

-		)

-{

-	Word32 i; 

-	Word16 isf_min;

-

-	isf_min = min_dist;                    

-	for (i = 0; i < n - 1; i++)

-	{

-		if(isf[i] < isf_min)

-		{

-			isf[i] = isf_min;              

-		}

-		isf_min = (isf[i] + min_dist);

-	}

-	return;

-}

-

-

-Word16 Sub_VQ(                             /* output: return quantization index     */

-		Word16 * x,                           /* input : ISF residual vector           */

-		Word16 * dico,                        /* input : quantization codebook         */

-		Word16 dim,                           /* input : dimention of vector           */

-		Word16 dico_size,                     /* input : size of quantization codebook */

-		Word32 * distance                     /* output: error of quantization         */

-	     )

-{

-	Word16 temp, *p_dico;

-	Word32 i, j, index;

-	Word32 dist_min, dist;

-

-	dist_min = MAX_32;                     

-	p_dico = dico;                         

-

-	index = 0;                             

-	for (i = 0; i < dico_size; i++)

-	{

-		dist = 0;  

-

-		for (j = 0; j < dim; j++)

-		{

-			temp = x[j] - (*p_dico++);

-			dist += (temp * temp)<<1;

-		}

-

-		if(dist < dist_min)

-		{

-			dist_min = dist;               

-			index = i;                     

-		}

-	}

-

-	*distance = dist_min;                  

-

-	/* Reading the selected vector */

-	p_dico = &dico[index * dim];           

-	for (j = 0; j < dim; j++)

-	{

-		x[j] = *p_dico++;                  

-	}

-

-	return index;

-}

-

-

-static void VQ_stage1(

-		Word16 * x,                           /* input : ISF residual vector           */

-		Word16 * dico,                        /* input : quantization codebook         */

-		Word16 dim,                           /* input : dimention of vector           */

-		Word16 dico_size,                     /* input : size of quantization codebook */

-		Word16 * index,                       /* output: indices of survivors          */

-		Word16 surv                           /* input : number of survivor            */

-		)

-{

-	Word16 temp, *p_dico;

-	Word32 i, j, k, l;

-	Word32 dist_min[N_SURV_MAX], dist;

-

-	dist_min[0] = MAX_32;

-	dist_min[1] = MAX_32;

-	dist_min[2] = MAX_32;

-	dist_min[3] = MAX_32;

-	index[0] = 0;

-	index[1] = 1;

-	index[2] = 2;

-	index[3] = 3;

-

-	p_dico = dico;                         

-

-	for (i = 0; i < dico_size; i++)

-	{

-		dist = 0;                          

-		for (j = 0; j < dim; j++)

-		{

-			temp = x[j] -  (*p_dico++);

-			dist += (temp * temp)<<1;

-		}

-

-		for (k = 0; k < surv; k++)

-		{

-			if(dist < dist_min[k])

-			{

-				for (l = surv - 1; l > k; l--)

-				{

-					dist_min[l] = dist_min[l - 1];      

-					index[l] = index[l - 1];    

-				}

-				dist_min[k] = dist;        

-				index[k] = i;              

-				break;

-			}

-		}

-	}

-	return;

-}

-

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*       File: apisf_2s.c                                               *
+*                                                                      *
+*       Description: Coding/Decodeing of ISF parameters with predication
+*       The ISF vector is quantized using two-stage VQ with split-by-2 *
+*       in 1st stage and split-by-5(or 3) in the second stage          *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "cnst.h"
+#include "acelp.h"
+#include "qpisf_2s.tab"                    /* Codebooks of isfs */
+
+#define MU         10923                   /* Prediction factor   (1.0/3.0) in Q15 */
+#define N_SURV_MAX 4                       /* 4 survivors max */
+#define ALPHA      29491                   /* 0. 9 in Q15     */
+#define ONE_ALPHA (32768-ALPHA)            /* (1.0 - ALPHA) in Q15 */
+
+/* private functions */
+static void VQ_stage1(
+		Word16 * x,                           /* input : ISF residual vector           */
+		Word16 * dico,                        /* input : quantization codebook         */
+		Word16 dim,                           /* input : dimention of vector           */
+		Word16 dico_size,                     /* input : size of quantization codebook */
+		Word16 * index,                       /* output: indices of survivors          */
+		Word16 surv                           /* input : number of survivor            */
+		);
+
+/**************************************************************************
+* Function:   Qpisf_2s_46B()                                              *
+*                                                                         *
+* Description: Quantization of isf parameters with prediction. (46 bits)  *
+*                                                                         *
+* The isf vector is quantized using two-stage VQ with split-by-2 in       *
+*  1st stage and split-by-5 in the second stage.                          *
+***************************************************************************/
+
+void Qpisf_2s_46b(
+		Word16 * isf1,                        /* (i) Q15 : ISF in the frequency domain (0..0.5) */
+		Word16 * isf_q,                       /* (o) Q15 : quantized ISF               (0..0.5) */
+		Word16 * past_isfq,                   /* (io)Q15 : past ISF quantizer                   */
+		Word16 * indice,                      /* (o)     : quantization indices                 */
+		Word16 nb_surv                        /* (i)     : number of survivor (1, 2, 3 or 4)    */
+		)
+{
+	Word16 tmp_ind[5];
+	Word16 surv1[N_SURV_MAX];              /* indices of survivors from 1st stage */
+	Word32 i, k, temp, min_err, distance;
+	Word16 isf[ORDER];
+	Word16 isf_stage2[ORDER];
+
+	for (i = 0; i < ORDER; i++)
+	{
+		isf[i] = vo_sub(isf1[i], mean_isf[i]);
+		isf[i] = vo_sub(isf[i], vo_mult(MU, past_isfq[i]));
+	}
+
+	VQ_stage1(&isf[0], dico1_isf, 9, SIZE_BK1, surv1, nb_surv);
+
+	distance = MAX_32;
+
+	for (k = 0; k < nb_surv; k++)
+	{
+		for (i = 0; i < 9; i++)
+		{
+			isf_stage2[i] = vo_sub(isf[i], dico1_isf[i + surv1[k] * 9]);
+		}
+		tmp_ind[0] = Sub_VQ(&isf_stage2[0], dico21_isf, 3, SIZE_BK21, &min_err);
+		temp = min_err;
+		tmp_ind[1] = Sub_VQ(&isf_stage2[3], dico22_isf, 3, SIZE_BK22, &min_err);
+		temp = vo_L_add(temp, min_err);
+		tmp_ind[2] = Sub_VQ(&isf_stage2[6], dico23_isf, 3, SIZE_BK23, &min_err);
+		temp = vo_L_add(temp, min_err);
+
+		if(temp < distance)
+		{
+			distance = temp;
+			indice[0] = surv1[k];
+			for (i = 0; i < 3; i++)
+			{
+				indice[i + 2] = tmp_ind[i];
+			}
+		}
+	}
+
+
+	VQ_stage1(&isf[9], dico2_isf, 7, SIZE_BK2, surv1, nb_surv);
+
+	distance = MAX_32;
+
+	for (k = 0; k < nb_surv; k++)
+	{
+		for (i = 0; i < 7; i++)
+		{
+			isf_stage2[i] = vo_sub(isf[9 + i], dico2_isf[i + surv1[k] * 7]);
+		}
+
+		tmp_ind[0] = Sub_VQ(&isf_stage2[0], dico24_isf, 3, SIZE_BK24, &min_err);
+		temp = min_err;
+		tmp_ind[1] = Sub_VQ(&isf_stage2[3], dico25_isf, 4, SIZE_BK25, &min_err);
+		temp = vo_L_add(temp, min_err);
+
+		if(temp < distance)
+		{
+			distance = temp;
+			indice[1] = surv1[k];
+			for (i = 0; i < 2; i++)
+			{
+				indice[i + 5] = tmp_ind[i];
+			}
+		}
+	}
+
+	Dpisf_2s_46b(indice, isf_q, past_isfq, isf_q, isf_q, 0, 0);
+
+	return;
+}
+
+/*****************************************************************************
+* Function:   Qpisf_2s_36B()                                                 *
+*                                                                            *
+* Description: Quantization of isf parameters with prediction. (36 bits)     *
+*                                                                            *
+* The isf vector is quantized using two-stage VQ with split-by-2 in          *
+*  1st stage and split-by-3 in the second stage.                             *
+******************************************************************************/
+
+void Qpisf_2s_36b(
+		Word16 * isf1,                        /* (i) Q15 : ISF in the frequency domain (0..0.5) */
+		Word16 * isf_q,                       /* (o) Q15 : quantized ISF               (0..0.5) */
+		Word16 * past_isfq,                   /* (io)Q15 : past ISF quantizer                   */
+		Word16 * indice,                      /* (o)     : quantization indices                 */
+		Word16 nb_surv                        /* (i)     : number of survivor (1, 2, 3 or 4)    */
+		)
+{
+	Word16 i, k, tmp_ind[5];
+	Word16 surv1[N_SURV_MAX];              /* indices of survivors from 1st stage */
+	Word32 temp, min_err, distance;
+	Word16 isf[ORDER];
+	Word16 isf_stage2[ORDER];
+
+	for (i = 0; i < ORDER; i++)
+	{
+		isf[i] = vo_sub(isf1[i], mean_isf[i]);
+		isf[i] = vo_sub(isf[i], vo_mult(MU, past_isfq[i]));
+	}
+
+	VQ_stage1(&isf[0], dico1_isf, 9, SIZE_BK1, surv1, nb_surv);
+
+	distance = MAX_32;
+
+	for (k = 0; k < nb_surv; k++)
+	{
+		for (i = 0; i < 9; i++)
+		{
+			isf_stage2[i] = vo_sub(isf[i], dico1_isf[i + surv1[k] * 9]);
+		}
+
+		tmp_ind[0] = Sub_VQ(&isf_stage2[0], dico21_isf_36b, 5, SIZE_BK21_36b, &min_err);
+		temp = min_err;
+		tmp_ind[1] = Sub_VQ(&isf_stage2[5], dico22_isf_36b, 4, SIZE_BK22_36b, &min_err);
+		temp = vo_L_add(temp, min_err);
+
+		if(temp < distance)
+		{
+			distance = temp;
+			indice[0] = surv1[k];
+			for (i = 0; i < 2; i++)
+			{
+				indice[i + 2] = tmp_ind[i];
+			}
+		}
+	}
+
+	VQ_stage1(&isf[9], dico2_isf, 7, SIZE_BK2, surv1, nb_surv);
+	distance = MAX_32;
+
+	for (k = 0; k < nb_surv; k++)
+	{
+		for (i = 0; i < 7; i++)
+		{
+			isf_stage2[i] = vo_sub(isf[9 + i], dico2_isf[i + surv1[k] * 7]);
+		}
+
+		tmp_ind[0] = Sub_VQ(&isf_stage2[0], dico23_isf_36b, 7, SIZE_BK23_36b, &min_err);
+		temp = min_err;
+
+		if(temp < distance)
+		{
+			distance = temp;
+			indice[1] = surv1[k];
+			indice[4] = tmp_ind[0];
+		}
+	}
+
+	Dpisf_2s_36b(indice, isf_q, past_isfq, isf_q, isf_q, 0, 0);
+
+	return;
+}
+
+/*********************************************************************
+* Function: Dpisf_2s_46b()                                           *
+*                                                                    *
+* Description: Decoding of ISF parameters                            *
+**********************************************************************/
+
+void Dpisf_2s_46b(
+		Word16 * indice,                      /* input:  quantization indices                       */
+		Word16 * isf_q,                       /* output: quantized ISF in frequency domain (0..0.5) */
+		Word16 * past_isfq,                   /* i/0   : past ISF quantizer                    */
+		Word16 * isfold,                      /* input : past quantized ISF                    */
+		Word16 * isf_buf,                     /* input : isf buffer                                                        */
+		Word16 bfi,                           /* input : Bad frame indicator                   */
+		Word16 enc_dec
+		)
+{
+	Word16 ref_isf[M], tmp;
+	Word32 i, j, L_tmp;
+
+	if (bfi == 0)                          /* Good frame */
+	{
+		for (i = 0; i < 9; i++)
+		{
+			isf_q[i] = dico1_isf[indice[0] * 9 + i];
+		}
+		for (i = 0; i < 7; i++)
+		{
+			isf_q[i + 9] = dico2_isf[indice[1] * 7 + i];
+		}
+
+		for (i = 0; i < 3; i++)
+		{
+			isf_q[i] = add1(isf_q[i], dico21_isf[indice[2] * 3 + i]);
+			isf_q[i + 3] = add1(isf_q[i + 3], dico22_isf[indice[3] * 3 + i]);
+			isf_q[i + 6] = add1(isf_q[i + 6], dico23_isf[indice[4] * 3 + i]);
+			isf_q[i + 9] = add1(isf_q[i + 9], dico24_isf[indice[5] * 3 + i]);
+		}
+
+		for (i = 0; i < 4; i++)
+		{
+			isf_q[i + 12] = add1(isf_q[i + 12], dico25_isf[indice[6] * 4 + i]);
+		}
+
+		for (i = 0; i < ORDER; i++)
+		{
+			tmp = isf_q[i];
+			isf_q[i] = add1(tmp, mean_isf[i]);
+			isf_q[i] = add1(isf_q[i], vo_mult(MU, past_isfq[i]));
+			past_isfq[i] = tmp;
+		}
+
+		if (enc_dec)
+		{
+			for (i = 0; i < M; i++)
+			{
+				for (j = (L_MEANBUF - 1); j > 0; j--)
+				{
+					isf_buf[j * M + i] = isf_buf[(j - 1) * M + i];
+				}
+				isf_buf[i] = isf_q[i];
+			}
+		}
+	} else
+	{                                      /* bad frame */
+		for (i = 0; i < M; i++)
+		{
+			L_tmp = mean_isf[i] << 14;
+			for (j = 0; j < L_MEANBUF; j++)
+			{
+				L_tmp += (isf_buf[j * M + i] << 14);
+			}
+			ref_isf[i] = vo_round(L_tmp);
+		}
+
+		/* use the past ISFs slightly shifted towards their mean */
+		for (i = 0; i < ORDER; i++)
+		{
+			isf_q[i] = add1(vo_mult(ALPHA, isfold[i]), vo_mult(ONE_ALPHA, ref_isf[i]));
+		}
+
+		/* estimate past quantized residual to be used in next frame */
+		for (i = 0; i < ORDER; i++)
+		{
+			tmp = add1(ref_isf[i], vo_mult(past_isfq[i], MU));      /* predicted ISF */
+			past_isfq[i] = vo_sub(isf_q[i], tmp);
+			past_isfq[i] = (past_isfq[i] >> 1);        /* past_isfq[i] *= 0.5 */
+		}
+	}
+
+	Reorder_isf(isf_q, ISF_GAP, ORDER);
+	return;
+}
+
+/*********************************************************************
+* Function:   Disf_2s_36b()                                          *
+*                                                                    *
+* Description: Decoding of ISF parameters                            *
+*********************************************************************/
+
+void Dpisf_2s_36b(
+		Word16 * indice,                      /* input:  quantization indices                       */
+		Word16 * isf_q,                       /* output: quantized ISF in frequency domain (0..0.5) */
+		Word16 * past_isfq,                   /* i/0   : past ISF quantizer                    */
+		Word16 * isfold,                      /* input : past quantized ISF                    */
+		Word16 * isf_buf,                     /* input : isf buffer                                                        */
+		Word16 bfi,                           /* input : Bad frame indicator                   */
+		Word16 enc_dec
+		)
+{
+	Word16 ref_isf[M], tmp;
+	Word32 i, j, L_tmp;
+
+	if (bfi == 0)                          /* Good frame */
+	{
+		for (i = 0; i < 9; i++)
+		{
+			isf_q[i] = dico1_isf[indice[0] * 9 + i];
+		}
+		for (i = 0; i < 7; i++)
+		{
+			isf_q[i + 9] = dico2_isf[indice[1] * 7 + i];
+		}
+
+		for (i = 0; i < 5; i++)
+		{
+			isf_q[i] = add1(isf_q[i], dico21_isf_36b[indice[2] * 5 + i]);
+		}
+		for (i = 0; i < 4; i++)
+		{
+			isf_q[i + 5] = add1(isf_q[i + 5], dico22_isf_36b[indice[3] * 4 + i]);
+		}
+		for (i = 0; i < 7; i++)
+		{
+			isf_q[i + 9] = add1(isf_q[i + 9], dico23_isf_36b[indice[4] * 7 + i]);
+		}
+
+		for (i = 0; i < ORDER; i++)
+		{
+			tmp = isf_q[i];
+			isf_q[i] = add1(tmp, mean_isf[i]);
+			isf_q[i] = add1(isf_q[i], vo_mult(MU, past_isfq[i]));
+			past_isfq[i] = tmp;
+		}
+
+
+		if (enc_dec)
+		{
+			for (i = 0; i < M; i++)
+			{
+				for (j = (L_MEANBUF - 1); j > 0; j--)
+				{
+					isf_buf[j * M + i] = isf_buf[(j - 1) * M + i];
+				}
+				isf_buf[i] = isf_q[i];
+			}
+		}
+	} else
+	{                                      /* bad frame */
+		for (i = 0; i < M; i++)
+		{
+			L_tmp = (mean_isf[i] << 14);
+			for (j = 0; j < L_MEANBUF; j++)
+			{
+				L_tmp += (isf_buf[j * M + i] << 14);
+			}
+			ref_isf[i] = vo_round(L_tmp);
+		}
+
+		/* use the past ISFs slightly shifted towards their mean */
+		for (i = 0; i < ORDER; i++)
+		{
+			isf_q[i] = add1(vo_mult(ALPHA, isfold[i]), vo_mult(ONE_ALPHA, ref_isf[i]));
+		}
+
+		/* estimate past quantized residual to be used in next frame */
+		for (i = 0; i < ORDER; i++)
+		{
+			tmp = add1(ref_isf[i], vo_mult(past_isfq[i], MU));      /* predicted ISF */
+			past_isfq[i] = vo_sub(isf_q[i], tmp);
+			past_isfq[i] = past_isfq[i] >> 1;         /* past_isfq[i] *= 0.5 */
+		}
+	}
+
+	Reorder_isf(isf_q, ISF_GAP, ORDER);
+
+	return;
+}
+
+
+/***************************************************************************
+* Function:  Reorder_isf()                                                 *
+*                                                                          *
+* Description: To make sure that the  isfs are properly order and to       *
+*              keep a certain minimum distance between consecutive isfs.   *
+*--------------------------------------------------------------------------*
+*    Argument         description                     in/out               *
+*                                                                          *
+*     isf[]           vector of isfs                    i/o                *
+*     min_dist        minimum required distance         i                  *
+*     n               LPC order                         i                  *
+****************************************************************************/
+
+void Reorder_isf(
+		Word16 * isf,                         /* (i/o) Q15: ISF in the frequency domain (0..0.5) */
+		Word16 min_dist,                      /* (i) Q15  : minimum distance to keep             */
+		Word16 n                              /* (i)      : number of ISF                        */
+		)
+{
+	Word32 i;
+	Word16 isf_min;
+
+	isf_min = min_dist;
+	for (i = 0; i < n - 1; i++)
+	{
+		if(isf[i] < isf_min)
+		{
+			isf[i] = isf_min;
+		}
+		isf_min = (isf[i] + min_dist);
+	}
+	return;
+}
+
+
+Word16 Sub_VQ(                             /* output: return quantization index     */
+		Word16 * x,                           /* input : ISF residual vector           */
+		Word16 * dico,                        /* input : quantization codebook         */
+		Word16 dim,                           /* input : dimention of vector           */
+		Word16 dico_size,                     /* input : size of quantization codebook */
+		Word32 * distance                     /* output: error of quantization         */
+	     )
+{
+	Word16 temp, *p_dico;
+	Word32 i, j, index;
+	Word32 dist_min, dist;
+
+	dist_min = MAX_32;
+	p_dico = dico;
+
+	index = 0;
+	for (i = 0; i < dico_size; i++)
+	{
+		dist = 0;
+
+		for (j = 0; j < dim; j++)
+		{
+			temp = x[j] - (*p_dico++);
+			dist += (temp * temp)<<1;
+		}
+
+		if(dist < dist_min)
+		{
+			dist_min = dist;
+			index = i;
+		}
+	}
+
+	*distance = dist_min;
+
+	/* Reading the selected vector */
+	p_dico = &dico[index * dim];
+	for (j = 0; j < dim; j++)
+	{
+		x[j] = *p_dico++;
+	}
+
+	return index;
+}
+
+
+static void VQ_stage1(
+		Word16 * x,                           /* input : ISF residual vector           */
+		Word16 * dico,                        /* input : quantization codebook         */
+		Word16 dim,                           /* input : dimention of vector           */
+		Word16 dico_size,                     /* input : size of quantization codebook */
+		Word16 * index,                       /* output: indices of survivors          */
+		Word16 surv                           /* input : number of survivor            */
+		)
+{
+	Word16 temp, *p_dico;
+	Word32 i, j, k, l;
+	Word32 dist_min[N_SURV_MAX], dist;
+
+	dist_min[0] = MAX_32;
+	dist_min[1] = MAX_32;
+	dist_min[2] = MAX_32;
+	dist_min[3] = MAX_32;
+	index[0] = 0;
+	index[1] = 1;
+	index[2] = 2;
+	index[3] = 3;
+
+	p_dico = dico;
+
+	for (i = 0; i < dico_size; i++)
+	{
+		dist = 0;
+		for (j = 0; j < dim; j++)
+		{
+			temp = x[j] -  (*p_dico++);
+			dist += (temp * temp)<<1;
+		}
+
+		for (k = 0; k < surv; k++)
+		{
+			if(dist < dist_min[k])
+			{
+				for (l = surv - 1; l > k; l--)
+				{
+					dist_min[l] = dist_min[l - 1];
+					index[l] = index[l - 1];
+				}
+				dist_min[k] = dist;
+				index[k] = i;
+				break;
+			}
+		}
+	}
+	return;
+}
+
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/random.c b/media/libstagefright/codecs/amrwbenc/src/random.c
index 8baa8bf..b896863 100644
--- a/media/libstagefright/codecs/amrwbenc/src/random.c
+++ b/media/libstagefright/codecs/amrwbenc/src/random.c
@@ -1,33 +1,33 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*       File: random.c                                                 *

-*                                                                      *

-*       Description: Signed 16 bits random generator                   *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-

-Word16 Random(Word16 * seed)

-{

-	/* static Word16 seed = 21845; */

-	*seed = (Word16)(L_add((L_mult(*seed, 31821) >> 1), 13849L));

-	return (*seed);

-}

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*       File: random.c                                                 *
+*                                                                      *
+*       Description: Signed 16 bits random generator                   *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+
+Word16 Random(Word16 * seed)
+{
+	/* static Word16 seed = 21845; */
+	*seed = (Word16)(L_add((L_mult(*seed, 31821) >> 1), 13849L));
+	return (*seed);
+}
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/residu.c b/media/libstagefright/codecs/amrwbenc/src/residu.c
index 6829882..b0c04b5 100644
--- a/media/libstagefright/codecs/amrwbenc/src/residu.c
+++ b/media/libstagefright/codecs/amrwbenc/src/residu.c
@@ -1,67 +1,67 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*  File: residu.c                                                      *

-*                                                                      *

-*  Description: Compute the LPC residual by filtering                  *

-*             the input speech through A(z)                            *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-

-void Residu(

-		Word16 a[],                           /* (i) Q12 : prediction coefficients                     */

-		Word16 x[],                           /* (i)     : speech (values x[-m..-1] are needed         */

-		Word16 y[],                           /* (o) x2  : residual signal                             */

-		Word16 lg                             /* (i)     : size of filtering                           */

-		)

-{

-	Word16 i,*p1, *p2;

-	Word32 s;

-	for (i = 0; i < lg; i++)

-	{

-		p1 = a;

-		p2 = &x[i];

-		s  = vo_mult32((*p1++), (*p2--));

-		s += vo_mult32((*p1++), (*p2--));

-		s += vo_mult32((*p1++), (*p2--));

-		s += vo_mult32((*p1++), (*p2--));

-		s += vo_mult32((*p1++), (*p2--));

-		s += vo_mult32((*p1++), (*p2--));

-		s += vo_mult32((*p1++), (*p2--));

-		s += vo_mult32((*p1++), (*p2--));

-		s += vo_mult32((*p1++), (*p2--));

-		s += vo_mult32((*p1++), (*p2--));

-		s += vo_mult32((*p1++), (*p2--));

-		s += vo_mult32((*p1++), (*p2--));

-		s += vo_mult32((*p1++), (*p2--));

-		s += vo_mult32((*p1++), (*p2--));

-		s += vo_mult32((*p1++), (*p2--));

-		s += vo_mult32((*p1++), (*p2--));

-		s += vo_mult32((*p1), (*p2));

-

-		s = L_shl2(s, 5); 

-		y[i] = extract_h(L_add(s, 0x8000));

-	}

-

-	return;

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*  File: residu.c                                                      *
+*                                                                      *
+*  Description: Compute the LPC residual by filtering                  *
+*             the input speech through A(z)                            *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+
+void Residu(
+		Word16 a[],                           /* (i) Q12 : prediction coefficients                     */
+		Word16 x[],                           /* (i)     : speech (values x[-m..-1] are needed         */
+		Word16 y[],                           /* (o) x2  : residual signal                             */
+		Word16 lg                             /* (i)     : size of filtering                           */
+		)
+{
+	Word16 i,*p1, *p2;
+	Word32 s;
+	for (i = 0; i < lg; i++)
+	{
+		p1 = a;
+		p2 = &x[i];
+		s  = vo_mult32((*p1++), (*p2--));
+		s += vo_mult32((*p1++), (*p2--));
+		s += vo_mult32((*p1++), (*p2--));
+		s += vo_mult32((*p1++), (*p2--));
+		s += vo_mult32((*p1++), (*p2--));
+		s += vo_mult32((*p1++), (*p2--));
+		s += vo_mult32((*p1++), (*p2--));
+		s += vo_mult32((*p1++), (*p2--));
+		s += vo_mult32((*p1++), (*p2--));
+		s += vo_mult32((*p1++), (*p2--));
+		s += vo_mult32((*p1++), (*p2--));
+		s += vo_mult32((*p1++), (*p2--));
+		s += vo_mult32((*p1++), (*p2--));
+		s += vo_mult32((*p1++), (*p2--));
+		s += vo_mult32((*p1++), (*p2--));
+		s += vo_mult32((*p1++), (*p2--));
+		s += vo_mult32((*p1), (*p2));
+
+		s = L_shl2(s, 5);
+		y[i] = extract_h(L_add(s, 0x8000));
+	}
+
+	return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/scale.c b/media/libstagefright/codecs/amrwbenc/src/scale.c
index af40121..418cc06 100644
--- a/media/libstagefright/codecs/amrwbenc/src/scale.c
+++ b/media/libstagefright/codecs/amrwbenc/src/scale.c
@@ -1,57 +1,57 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*       File: scale.c                                                  *

-*                                                                      *

-*       Description: Scale signal to get maximum of dynamic            *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-

-void Scale_sig(

-		Word16 x[],                           /* (i/o) : signal to scale               */

-		Word16 lg,                            /* (i)   : size of x[]                   */

-		Word16 exp                            /* (i)   : exponent: x = round(x << exp) */

-	      )

-{

-	Word32 i;

-	Word32 L_tmp;

-	if(exp > 0)

-	{

-		for (i = lg - 1 ; i >= 0; i--)

-		{

-			L_tmp = L_shl2(x[i], 16 + exp);  

-			x[i] = extract_h(L_add(L_tmp, 0x8000));            

-		}

-	}

-	else

-	{

-		exp = -exp;

-		for (i = lg - 1; i >= 0; i--)

-		{

-			L_tmp = x[i] << 16;

-			L_tmp >>= exp; 

-			x[i] = (L_tmp + 0x8000)>>16;            

-		}

-	}

-	return;

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*       File: scale.c                                                  *
+*                                                                      *
+*       Description: Scale signal to get maximum of dynamic            *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+
+void Scale_sig(
+		Word16 x[],                           /* (i/o) : signal to scale               */
+		Word16 lg,                            /* (i)   : size of x[]                   */
+		Word16 exp                            /* (i)   : exponent: x = round(x << exp) */
+	      )
+{
+	Word32 i;
+	Word32 L_tmp;
+	if(exp > 0)
+	{
+		for (i = lg - 1 ; i >= 0; i--)
+		{
+			L_tmp = L_shl2(x[i], 16 + exp);
+			x[i] = extract_h(L_add(L_tmp, 0x8000));
+		}
+	}
+	else
+	{
+		exp = -exp;
+		for (i = lg - 1; i >= 0; i--)
+		{
+			L_tmp = x[i] << 16;
+			L_tmp >>= exp;
+			x[i] = (L_tmp + 0x8000)>>16;
+		}
+	}
+	return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/stream.c b/media/libstagefright/codecs/amrwbenc/src/stream.c
index a708235..780f009 100644
--- a/media/libstagefright/codecs/amrwbenc/src/stream.c
+++ b/media/libstagefright/codecs/amrwbenc/src/stream.c
@@ -1,58 +1,58 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*       File: stream.c                                                 *

-*                                                                      *

-*       Description: VOME API Buffer Operator Implement Code           *

-*                                                                      *

-************************************************************************/

-

-#include "stream.h"

-

-void voAWB_InitFrameBuffer(FrameStream *stream)

-{

-	stream->set_ptr = NULL;

-	stream->frame_ptr_bk = stream->frame_ptr;

-	stream->set_len = 0;

-	stream->framebuffer_len = 0;

-	stream->frame_storelen = 0;	

-}

-

-void voAWB_UpdateFrameBuffer(

-		FrameStream *stream, 

-		VO_MEM_OPERATOR *pMemOP

-		)

-{

-	int  len;

-	len  = MIN(Frame_Maxsize - stream->frame_storelen, stream->set_len);

-	pMemOP->Copy(VO_INDEX_ENC_AMRWB, stream->frame_ptr_bk + stream->frame_storelen , stream->set_ptr, len);

-	stream->set_len -= len;

-	stream->set_ptr += len;

-	stream->framebuffer_len = stream->frame_storelen + len;

-	stream->frame_ptr = stream->frame_ptr_bk;

-	stream->used_len += len;

-}

-

-void voAWB_FlushFrameBuffer(FrameStream *stream)

-{

-	stream->set_ptr = NULL;

-	stream->frame_ptr_bk = stream->frame_ptr;

-	stream->set_len = 0;

-	stream->framebuffer_len = 0;

-	stream->frame_storelen = 0;	

-}

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*       File: stream.c                                                 *
+*                                                                      *
+*       Description: VOME API Buffer Operator Implement Code           *
+*                                                                      *
+************************************************************************/
+
+#include "stream.h"
+
+void voAWB_InitFrameBuffer(FrameStream *stream)
+{
+	stream->set_ptr = NULL;
+	stream->frame_ptr_bk = stream->frame_ptr;
+	stream->set_len = 0;
+	stream->framebuffer_len = 0;
+	stream->frame_storelen = 0;
+}
+
+void voAWB_UpdateFrameBuffer(
+		FrameStream *stream,
+		VO_MEM_OPERATOR *pMemOP
+		)
+{
+	int  len;
+	len  = MIN(Frame_Maxsize - stream->frame_storelen, stream->set_len);
+	pMemOP->Copy(VO_INDEX_ENC_AMRWB, stream->frame_ptr_bk + stream->frame_storelen , stream->set_ptr, len);
+	stream->set_len -= len;
+	stream->set_ptr += len;
+	stream->framebuffer_len = stream->frame_storelen + len;
+	stream->frame_ptr = stream->frame_ptr_bk;
+	stream->used_len += len;
+}
+
+void voAWB_FlushFrameBuffer(FrameStream *stream)
+{
+	stream->set_ptr = NULL;
+	stream->frame_ptr_bk = stream->frame_ptr;
+	stream->set_len = 0;
+	stream->framebuffer_len = 0;
+	stream->frame_storelen = 0;
+}
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/syn_filt.c b/media/libstagefright/codecs/amrwbenc/src/syn_filt.c
index 6c1fb8e..1bda05a 100644
--- a/media/libstagefright/codecs/amrwbenc/src/syn_filt.c
+++ b/media/libstagefright/codecs/amrwbenc/src/syn_filt.c
@@ -1,160 +1,160 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*       File: syn_filt.c                                               *

-*                                                                      *

-*       Description: Do the synthesis filtering 1/A(z)                 *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "math_op.h"

-#include "cnst.h"

-

-void Syn_filt(

-		Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients           */

-		Word16 x[],                           /* (i)     : input signal                             */

-		Word16 y[],                           /* (o)     : output signal                            */

-		Word16 lg,                            /* (i)     : size of filtering                        */

-		Word16 mem[],                         /* (i/o)   : memory associated with this filtering.   */

-		Word16 update                         /* (i)     : 0=no update, 1=update of memory.         */

-	     )

-{

-	Word32 i, a0;

-	Word16 y_buf[L_SUBFR16k + M16k];

-	Word32 L_tmp;

-	Word16 *yy, *p1, *p2;

-	yy = &y_buf[0];                        

-	/* copy initial filter states into synthesis buffer */

-	for (i = 0; i < 16; i++)

-	{

-		*yy++ = mem[i];                    

-	}

-	a0 = (a[0] >> 1);                     /* input / 2 */

-	/* Do the filtering. */

-	for (i = 0; i < lg; i++)

-	{

-		p1 = &a[1];

-		p2 = &yy[i-1];

-		L_tmp  = vo_mult32(a0, x[i]);

-		L_tmp -= vo_mult32((*p1++), (*p2--));

-		L_tmp -= vo_mult32((*p1++), (*p2--));

-		L_tmp -= vo_mult32((*p1++), (*p2--));

-		L_tmp -= vo_mult32((*p1++), (*p2--));

-		L_tmp -= vo_mult32((*p1++), (*p2--));

-		L_tmp -= vo_mult32((*p1++), (*p2--));

-		L_tmp -= vo_mult32((*p1++), (*p2--));

-		L_tmp -= vo_mult32((*p1++), (*p2--));

-		L_tmp -= vo_mult32((*p1++), (*p2--));

-		L_tmp -= vo_mult32((*p1++), (*p2--));

-		L_tmp -= vo_mult32((*p1++), (*p2--));

-		L_tmp -= vo_mult32((*p1++), (*p2--));

-		L_tmp -= vo_mult32((*p1++), (*p2--));

-		L_tmp -= vo_mult32((*p1++), (*p2--));

-		L_tmp -= vo_mult32((*p1++), (*p2--));

-		L_tmp -= vo_mult32((*p1), (*p2));

-

-		L_tmp = L_shl2(L_tmp, 4);

-		y[i] = yy[i] = extract_h(L_add(L_tmp, 0x8000));  

-	}

-	/* Update memory if required */

-	if (update)

-		for (i = 0; i < 16; i++)

-		{

-			mem[i] = yy[lg - 16 + i];

-		}

-	return;

-}

-

-

-void Syn_filt_32(

-		Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients */

-		Word16 m,                             /* (i)     : order of LP filter             */

-		Word16 exc[],                         /* (i) Qnew: excitation (exc[i] >> Qnew)    */

-		Word16 Qnew,                          /* (i)     : exc scaling = 0(min) to 8(max) */

-		Word16 sig_hi[],                      /* (o) /16 : synthesis high                 */

-		Word16 sig_lo[],                      /* (o) /16 : synthesis low                  */

-		Word16 lg                             /* (i)     : size of filtering              */

-		)

-{

-	Word32 i,a0;

-	Word32 L_tmp, L_tmp1;

-	Word16 *p1, *p2, *p3;

-	a0 = a[0] >> (4 + Qnew);          /* input / 16 and >>Qnew */

-	/* Do the filtering. */

-	for (i = 0; i < lg; i++)

-	{

-		L_tmp  = 0; 

-		L_tmp1 = 0;

-		p1 = a;

-		p2 = &sig_lo[i - 1];

-		p3 = &sig_hi[i - 1];

-

-		L_tmp  -= vo_mult32((*p2--), (*p1));

-		L_tmp1 -= vo_mult32((*p3--), (*p1++));

-		L_tmp  -= vo_mult32((*p2--), (*p1));

-		L_tmp1 -= vo_mult32((*p3--), (*p1++));

-		L_tmp  -= vo_mult32((*p2--), (*p1));

-		L_tmp1 -= vo_mult32((*p3--), (*p1++));

-		L_tmp  -= vo_mult32((*p2--), (*p1));

-		L_tmp1 -= vo_mult32((*p3--), (*p1++));

-		L_tmp  -= vo_mult32((*p2--), (*p1));

-		L_tmp1 -= vo_mult32((*p3--), (*p1++));

-		L_tmp  -= vo_mult32((*p2--), (*p1));

-		L_tmp1 -= vo_mult32((*p3--), (*p1++));

-		L_tmp  -= vo_mult32((*p2--), (*p1));

-		L_tmp1 -= vo_mult32((*p3--), (*p1++));

-		L_tmp  -= vo_mult32((*p2--), (*p1));

-		L_tmp1 -= vo_mult32((*p3--), (*p1++));

-		L_tmp  -= vo_mult32((*p2--), (*p1));

-		L_tmp1 -= vo_mult32((*p3--), (*p1++));

-		L_tmp  -= vo_mult32((*p2--), (*p1));

-		L_tmp1 -= vo_mult32((*p3--), (*p1++));

-		L_tmp  -= vo_mult32((*p2--), (*p1));

-		L_tmp1 -= vo_mult32((*p3--), (*p1++));

-		L_tmp  -= vo_mult32((*p2--), (*p1));

-		L_tmp1 -= vo_mult32((*p3--), (*p1++));

-		L_tmp  -= vo_mult32((*p2--), (*p1));

-		L_tmp1 -= vo_mult32((*p3--), (*p1++));

-		L_tmp  -= vo_mult32((*p2--), (*p1));

-		L_tmp1 -= vo_mult32((*p3--), (*p1++));

-		L_tmp  -= vo_mult32((*p2--), (*p1));

-		L_tmp1 -= vo_mult32((*p3--), (*p1++));

-		L_tmp  -= vo_mult32((*p2--), (*p1));

-		L_tmp1 -= vo_mult32((*p3--), (*p1++));

-

-		L_tmp = L_tmp >> 11;      

-		L_tmp += vo_L_mult(exc[i], a0);

-

-		/* sig_hi = bit16 to bit31 of synthesis */

-		L_tmp = L_tmp - (L_tmp1<<1);

-

-		L_tmp = L_tmp >> 3;           /* ai in Q12 */

-		sig_hi[i] = extract_h(L_tmp);      

-

-		/* sig_lo = bit4 to bit15 of synthesis */

-		L_tmp >>= 4;           /* 4 : sig_lo[i] >> 4 */

-		sig_lo[i] = (Word16)((L_tmp - (sig_hi[i] << 13)));  

-	}

-

-	return;

-}

-

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*       File: syn_filt.c                                               *
+*                                                                      *
+*       Description: Do the synthesis filtering 1/A(z)                 *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "math_op.h"
+#include "cnst.h"
+
+void Syn_filt(
+		Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients           */
+		Word16 x[],                           /* (i)     : input signal                             */
+		Word16 y[],                           /* (o)     : output signal                            */
+		Word16 lg,                            /* (i)     : size of filtering                        */
+		Word16 mem[],                         /* (i/o)   : memory associated with this filtering.   */
+		Word16 update                         /* (i)     : 0=no update, 1=update of memory.         */
+	     )
+{
+	Word32 i, a0;
+	Word16 y_buf[L_SUBFR16k + M16k];
+	Word32 L_tmp;
+	Word16 *yy, *p1, *p2;
+	yy = &y_buf[0];
+	/* copy initial filter states into synthesis buffer */
+	for (i = 0; i < 16; i++)
+	{
+		*yy++ = mem[i];
+	}
+	a0 = (a[0] >> 1);                     /* input / 2 */
+	/* Do the filtering. */
+	for (i = 0; i < lg; i++)
+	{
+		p1 = &a[1];
+		p2 = &yy[i-1];
+		L_tmp  = vo_mult32(a0, x[i]);
+		L_tmp -= vo_mult32((*p1++), (*p2--));
+		L_tmp -= vo_mult32((*p1++), (*p2--));
+		L_tmp -= vo_mult32((*p1++), (*p2--));
+		L_tmp -= vo_mult32((*p1++), (*p2--));
+		L_tmp -= vo_mult32((*p1++), (*p2--));
+		L_tmp -= vo_mult32((*p1++), (*p2--));
+		L_tmp -= vo_mult32((*p1++), (*p2--));
+		L_tmp -= vo_mult32((*p1++), (*p2--));
+		L_tmp -= vo_mult32((*p1++), (*p2--));
+		L_tmp -= vo_mult32((*p1++), (*p2--));
+		L_tmp -= vo_mult32((*p1++), (*p2--));
+		L_tmp -= vo_mult32((*p1++), (*p2--));
+		L_tmp -= vo_mult32((*p1++), (*p2--));
+		L_tmp -= vo_mult32((*p1++), (*p2--));
+		L_tmp -= vo_mult32((*p1++), (*p2--));
+		L_tmp -= vo_mult32((*p1), (*p2));
+
+		L_tmp = L_shl2(L_tmp, 4);
+		y[i] = yy[i] = extract_h(L_add(L_tmp, 0x8000));
+	}
+	/* Update memory if required */
+	if (update)
+		for (i = 0; i < 16; i++)
+		{
+			mem[i] = yy[lg - 16 + i];
+		}
+	return;
+}
+
+
+void Syn_filt_32(
+		Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients */
+		Word16 m,                             /* (i)     : order of LP filter             */
+		Word16 exc[],                         /* (i) Qnew: excitation (exc[i] >> Qnew)    */
+		Word16 Qnew,                          /* (i)     : exc scaling = 0(min) to 8(max) */
+		Word16 sig_hi[],                      /* (o) /16 : synthesis high                 */
+		Word16 sig_lo[],                      /* (o) /16 : synthesis low                  */
+		Word16 lg                             /* (i)     : size of filtering              */
+		)
+{
+	Word32 i,a0;
+	Word32 L_tmp, L_tmp1;
+	Word16 *p1, *p2, *p3;
+	a0 = a[0] >> (4 + Qnew);          /* input / 16 and >>Qnew */
+	/* Do the filtering. */
+	for (i = 0; i < lg; i++)
+	{
+		L_tmp  = 0;
+		L_tmp1 = 0;
+		p1 = a;
+		p2 = &sig_lo[i - 1];
+		p3 = &sig_hi[i - 1];
+
+		L_tmp  -= vo_mult32((*p2--), (*p1));
+		L_tmp1 -= vo_mult32((*p3--), (*p1++));
+		L_tmp  -= vo_mult32((*p2--), (*p1));
+		L_tmp1 -= vo_mult32((*p3--), (*p1++));
+		L_tmp  -= vo_mult32((*p2--), (*p1));
+		L_tmp1 -= vo_mult32((*p3--), (*p1++));
+		L_tmp  -= vo_mult32((*p2--), (*p1));
+		L_tmp1 -= vo_mult32((*p3--), (*p1++));
+		L_tmp  -= vo_mult32((*p2--), (*p1));
+		L_tmp1 -= vo_mult32((*p3--), (*p1++));
+		L_tmp  -= vo_mult32((*p2--), (*p1));
+		L_tmp1 -= vo_mult32((*p3--), (*p1++));
+		L_tmp  -= vo_mult32((*p2--), (*p1));
+		L_tmp1 -= vo_mult32((*p3--), (*p1++));
+		L_tmp  -= vo_mult32((*p2--), (*p1));
+		L_tmp1 -= vo_mult32((*p3--), (*p1++));
+		L_tmp  -= vo_mult32((*p2--), (*p1));
+		L_tmp1 -= vo_mult32((*p3--), (*p1++));
+		L_tmp  -= vo_mult32((*p2--), (*p1));
+		L_tmp1 -= vo_mult32((*p3--), (*p1++));
+		L_tmp  -= vo_mult32((*p2--), (*p1));
+		L_tmp1 -= vo_mult32((*p3--), (*p1++));
+		L_tmp  -= vo_mult32((*p2--), (*p1));
+		L_tmp1 -= vo_mult32((*p3--), (*p1++));
+		L_tmp  -= vo_mult32((*p2--), (*p1));
+		L_tmp1 -= vo_mult32((*p3--), (*p1++));
+		L_tmp  -= vo_mult32((*p2--), (*p1));
+		L_tmp1 -= vo_mult32((*p3--), (*p1++));
+		L_tmp  -= vo_mult32((*p2--), (*p1));
+		L_tmp1 -= vo_mult32((*p3--), (*p1++));
+		L_tmp  -= vo_mult32((*p2--), (*p1));
+		L_tmp1 -= vo_mult32((*p3--), (*p1++));
+
+		L_tmp = L_tmp >> 11;
+		L_tmp += vo_L_mult(exc[i], a0);
+
+		/* sig_hi = bit16 to bit31 of synthesis */
+		L_tmp = L_tmp - (L_tmp1<<1);
+
+		L_tmp = L_tmp >> 3;           /* ai in Q12 */
+		sig_hi[i] = extract_h(L_tmp);
+
+		/* sig_lo = bit4 to bit15 of synthesis */
+		L_tmp >>= 4;           /* 4 : sig_lo[i] >> 4 */
+		sig_lo[i] = (Word16)((L_tmp - (sig_hi[i] << 13)));
+	}
+
+	return;
+}
+
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/updt_tar.c b/media/libstagefright/codecs/amrwbenc/src/updt_tar.c
index f3e5650..96779fd 100644
--- a/media/libstagefright/codecs/amrwbenc/src/updt_tar.c
+++ b/media/libstagefright/codecs/amrwbenc/src/updt_tar.c
@@ -1,49 +1,49 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*       File: updt_tar.c                                               *

-*                                                                      *

-*       Description: Update the target vector for codebook search      *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-

-void Updt_tar(

-		Word16 * x,                           /* (i) Q0  : old target (for pitch search)     */

-		Word16 * x2,                          /* (o) Q0  : new target (for codebook search)  */

-		Word16 * y,                           /* (i) Q0  : filtered adaptive codebook vector */

-		Word16 gain,                          /* (i) Q14 : adaptive codebook gain            */

-		Word16 L                              /* (i)     : subframe size                     */

-	     )

-{

-	Word32 i;

-	Word32 L_tmp;

-

-	for (i = 0; i < L; i++)

-	{

-		L_tmp = x[i] << 15;

-		L_tmp -= (y[i] * gain)<<1;

-		x2[i] = extract_h(L_shl2(L_tmp, 1)); 

-	}

-

-	return;

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*       File: updt_tar.c                                               *
+*                                                                      *
+*       Description: Update the target vector for codebook search      *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+
+void Updt_tar(
+		Word16 * x,                           /* (i) Q0  : old target (for pitch search)     */
+		Word16 * x2,                          /* (o) Q0  : new target (for codebook search)  */
+		Word16 * y,                           /* (i) Q0  : filtered adaptive codebook vector */
+		Word16 gain,                          /* (i) Q14 : adaptive codebook gain            */
+		Word16 L                              /* (i)     : subframe size                     */
+	     )
+{
+	Word32 i;
+	Word32 L_tmp;
+
+	for (i = 0; i < L; i++)
+	{
+		L_tmp = x[i] << 15;
+		L_tmp -= (y[i] * gain)<<1;
+		x2[i] = extract_h(L_shl2(L_tmp, 1));
+	}
+
+	return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/util.c b/media/libstagefright/codecs/amrwbenc/src/util.c
index 78141dd..76ab1b1 100644
--- a/media/libstagefright/codecs/amrwbenc/src/util.c
+++ b/media/libstagefright/codecs/amrwbenc/src/util.c
@@ -1,74 +1,74 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*       File: util.c                                                   *

-*                                                                      *

-*       Description: Reset and Copy buffer                             *

-*                                                                      *

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-

-/***********************************************************************

-* Function:  Set_zero()                                             *

-* Description: Set vector x[] to zero                               *

-************************************************************************/

-

-void Set_zero(

-		Word16 x[],                           /* (o)    : vector to clear     */

-		Word16 L                              /* (i)    : length of vector    */

-	     )

-{

-	Word32 num = (Word32)L;

-	do{

-		*x++ = 0;

-	}while(--num !=0);

-}

-

-

-/*********************************************************************

-* Function: Copy()                                                   *

-*                                                                    *

-* Description: Copy vector x[] to y[]                                *

-*********************************************************************/

-

-void Copy(

-		Word16 x[],                           /* (i)   : input vector   */

-		Word16 y[],                           /* (o)   : output vector  */

-		Word16 L                              /* (i)   : vector length  */

-	 )

-{

-	Word32	temp1,temp2,num;

-	if(L&1)

-	{

-		temp1 = *x++;

-		*y++ = temp1;

-	}

-	num = (Word32)(L>>1);

-	temp1 = *x++;

-	temp2 = *x++;

-	do{

-		*y++ = temp1;

-		*y++ = temp2;

-		temp1 = *x++;

-		temp2 = *x++;

-	}while(--num!=0);

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*       File: util.c                                                   *
+*                                                                      *
+*       Description: Reset and Copy buffer                             *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+
+/***********************************************************************
+* Function:  Set_zero()                                             *
+* Description: Set vector x[] to zero                               *
+************************************************************************/
+
+void Set_zero(
+		Word16 x[],                           /* (o)    : vector to clear     */
+		Word16 L                              /* (i)    : length of vector    */
+	     )
+{
+	Word32 num = (Word32)L;
+	do{
+		*x++ = 0;
+	}while(--num !=0);
+}
+
+
+/*********************************************************************
+* Function: Copy()                                                   *
+*                                                                    *
+* Description: Copy vector x[] to y[]                                *
+*********************************************************************/
+
+void Copy(
+		Word16 x[],                           /* (i)   : input vector   */
+		Word16 y[],                           /* (o)   : output vector  */
+		Word16 L                              /* (i)   : vector length  */
+	 )
+{
+	Word32	temp1,temp2,num;
+	if(L&1)
+	{
+		temp1 = *x++;
+		*y++ = temp1;
+	}
+	num = (Word32)(L>>1);
+	temp1 = *x++;
+	temp2 = *x++;
+	do{
+		*y++ = temp1;
+		*y++ = temp2;
+		temp1 = *x++;
+		temp2 = *x++;
+	}while(--num!=0);
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/voAMRWBEnc.c b/media/libstagefright/codecs/amrwbenc/src/voAMRWBEnc.c
index d0d99a7..0f4d689 100644
--- a/media/libstagefright/codecs/amrwbenc/src/voAMRWBEnc.c
+++ b/media/libstagefright/codecs/amrwbenc/src/voAMRWBEnc.c
@@ -1,1941 +1,1941 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*      File: voAMRWBEnc.c                                              *

-*                                                                      *

-*      Description: Performs the main encoder routine                  *

-*                   Fixed-point C simulation of AMR WB ACELP coding    *

-*		    algorithm with 20 msspeech frames for              *

-*		    wideband speech signals.                           *

-*                                                                      *

-************************************************************************/

-

-#include <stdio.h>

-#include <stdlib.h>

-#include "typedef.h"

-#include "basic_op.h"

-#include "oper_32b.h"

-#include "math_op.h"

-#include "cnst.h"

-#include "acelp.h"

-#include "cod_main.h"

-#include "bits.h"

-#include "main.h"

-#include "voAMRWB.h"

-#include "mem_align.h"

-#include "cmnMemory.h"

-

-#ifdef __cplusplus

-extern "C" {

-#endif

-

-/* LPC interpolation coef {0.45, 0.8, 0.96, 1.0}; in Q15 */

-static Word16 interpol_frac[NB_SUBFR] = {14746, 26214, 31457, 32767};

-

-/* isp tables for initialization */

-static Word16 isp_init[M] =

-{

-	32138, 30274, 27246, 23170, 18205, 12540, 6393, 0,

-	-6393, -12540, -18205, -23170, -27246, -30274, -32138, 1475

-};

-

-static Word16 isf_init[M] =

-{

-	1024, 2048, 3072, 4096, 5120, 6144, 7168, 8192,

-	9216, 10240, 11264, 12288, 13312, 14336, 15360, 3840

-};

-

-/* High Band encoding */

-static const Word16 HP_gain[16] =

-{

-	3624, 4673, 5597, 6479, 7425, 8378, 9324, 10264,

-	11210, 12206, 13391, 14844, 16770, 19655, 24289, 32728

-};

-

-/* Private function declaration */

-static Word16 synthesis(

-			Word16 Aq[],                          /* A(z)  : quantized Az               */

-			Word16 exc[],                         /* (i)   : excitation at 12kHz        */

-			Word16 Q_new,                         /* (i)   : scaling performed on exc   */

-			Word16 synth16k[],                    /* (o)   : 16kHz synthesis signal     */

-			Coder_State * st                      /* (i/o) : State structure            */

-			);

-

-/* Codec some parameters initialization */

-void Reset_encoder(void *st, Word16 reset_all)

-{

-	Word16 i;

-	Coder_State *cod_state;

-	cod_state = (Coder_State *) st;

-	Set_zero(cod_state->old_exc, PIT_MAX + L_INTERPOL);

-	Set_zero(cod_state->mem_syn, M);

-	Set_zero(cod_state->past_isfq, M);

-	cod_state->mem_w0 = 0;                 

-	cod_state->tilt_code = 0;              

-	cod_state->first_frame = 1;            

-	Init_gp_clip(cod_state->gp_clip);

-	cod_state->L_gc_thres = 0;             

-	if (reset_all != 0)

-	{

-		/* Static vectors to zero */

-		Set_zero(cod_state->old_speech, L_TOTAL - L_FRAME);

-		Set_zero(cod_state->old_wsp, (PIT_MAX / OPL_DECIM));

-		Set_zero(cod_state->mem_decim2, 3);

-		/* routines initialization */

-		Init_Decim_12k8(cod_state->mem_decim);

-		Init_HP50_12k8(cod_state->mem_sig_in);

-		Init_Levinson(cod_state->mem_levinson);

-		Init_Q_gain2(cod_state->qua_gain);

-		Init_Hp_wsp(cod_state->hp_wsp_mem);

-		/* isp initialization */

-		Copy(isp_init, cod_state->ispold, M);

-		Copy(isp_init, cod_state->ispold_q, M);

-		/* variable initialization */

-		cod_state->mem_preemph = 0;        

-		cod_state->mem_wsp = 0;            

-		cod_state->Q_old = 15;             

-		cod_state->Q_max[0] = 15;          

-		cod_state->Q_max[1] = 15;          

-		cod_state->old_wsp_max = 0;        

-		cod_state->old_wsp_shift = 0;      

-		/* pitch ol initialization */

-		cod_state->old_T0_med = 40;        

-		cod_state->ol_gain = 0;            

-		cod_state->ada_w = 0;              

-		cod_state->ol_wght_flg = 0;        

-		for (i = 0; i < 5; i++)

-		{

-			cod_state->old_ol_lag[i] = 40; 

-		}

-		Set_zero(cod_state->old_hp_wsp, (L_FRAME / 2) / OPL_DECIM + (PIT_MAX / OPL_DECIM));

-		Set_zero(cod_state->mem_syn_hf, M);

-		Set_zero(cod_state->mem_syn_hi, M);

-		Set_zero(cod_state->mem_syn_lo, M);

-		Init_HP50_12k8(cod_state->mem_sig_out);

-		Init_Filt_6k_7k(cod_state->mem_hf);

-		Init_HP400_12k8(cod_state->mem_hp400);

-		Copy(isf_init, cod_state->isfold, M);

-		cod_state->mem_deemph = 0;         

-		cod_state->seed2 = 21845;          

-		Init_Filt_6k_7k(cod_state->mem_hf2);

-		cod_state->gain_alpha = 32767;     

-		cod_state->vad_hist = 0;

-		wb_vad_reset(cod_state->vadSt);

-		dtx_enc_reset(cod_state->dtx_encSt, isf_init);

-	}

-	return;

-}

-

-/*-----------------------------------------------------------------*

-*   Funtion  coder                                                *

-*            ~~~~~                                                *

-*   ->Main coder routine.                                         *

-*                                                                 *

-*-----------------------------------------------------------------*/

-void coder(

-		Word16 * mode,                        /* input :  used mode                             */

-		Word16 speech16k[],                   /* input :  320 new speech samples (at 16 kHz)    */

-		Word16 prms[],                        /* output:  output parameters                     */

-		Word16 * ser_size,                    /* output:  bit rate of the used mode             */

-		void *spe_state,                      /* i/o   :  State structure                       */

-		Word16 allow_dtx                      /* input :  DTX ON/OFF                            */

-	  )

-{

-	/* Coder states */

-	Coder_State *st;

-	/* Speech vector */

-	Word16 old_speech[L_TOTAL];

-	Word16 *new_speech, *speech, *p_window;

-

-	/* Weighted speech vector */

-	Word16 old_wsp[L_FRAME + (PIT_MAX / OPL_DECIM)];

-	Word16 *wsp;

-

-	/* Excitation vector */

-	Word16 old_exc[(L_FRAME + 1) + PIT_MAX + L_INTERPOL];

-	Word16 *exc;

-

-	/* LPC coefficients */

-	Word16 r_h[M + 1], r_l[M + 1];         /* Autocorrelations of windowed speech  */

-	Word16 rc[M];                          /* Reflection coefficients.             */

-	Word16 Ap[M + 1];                      /* A(z) with spectral expansion         */

-	Word16 ispnew[M];                      /* immittance spectral pairs at 4nd sfr */

-	Word16 ispnew_q[M];                    /* quantized ISPs at 4nd subframe       */

-	Word16 isf[M];                         /* ISF (frequency domain) at 4nd sfr    */

-	Word16 *p_A, *p_Aq;                    /* ptr to A(z) for the 4 subframes      */

-	Word16 A[NB_SUBFR * (M + 1)];          /* A(z) unquantized for the 4 subframes */

-	Word16 Aq[NB_SUBFR * (M + 1)];         /* A(z)   quantized for the 4 subframes */

-

-	/* Other vectors */

-	Word16 xn[L_SUBFR];                    /* Target vector for pitch search     */

-	Word16 xn2[L_SUBFR];                   /* Target vector for codebook search  */

-	Word16 dn[L_SUBFR];                    /* Correlation between xn2 and h1     */

-	Word16 cn[L_SUBFR];                    /* Target vector in residual domain   */

-	Word16 h1[L_SUBFR];                    /* Impulse response vector            */

-	Word16 h2[L_SUBFR];                    /* Impulse response vector            */

-	Word16 code[L_SUBFR];                  /* Fixed codebook excitation          */

-	Word16 y1[L_SUBFR];                    /* Filtered adaptive excitation       */

-	Word16 y2[L_SUBFR];                    /* Filtered adaptive excitation       */

-	Word16 error[M + L_SUBFR];             /* error of quantization              */

-	Word16 synth[L_SUBFR];                 /* 12.8kHz synthesis vector           */

-	Word16 exc2[L_FRAME];                  /* excitation vector                  */

-	Word16 buf[L_FRAME];                   /* VAD buffer                         */

-

-	/* Scalars */

-	Word32 i, j, i_subfr, select, pit_flag, clip_gain, vad_flag;

-	Word16 codec_mode;

-	Word16 T_op, T_op2, T0, T0_min, T0_max, T0_frac, index;

-	Word16 gain_pit, gain_code, g_coeff[4], g_coeff2[4];

-	Word16 tmp, gain1, gain2, exp, Q_new, mu, shift, max;

-	Word16 voice_fac;

-	Word16 indice[8];

-	Word32 L_tmp, L_gain_code, L_max, L_tmp1;

-	Word16 code2[L_SUBFR];                         /* Fixed codebook excitation  */

-	Word16 stab_fac, fac, gain_code_lo;

-

-	Word16 corr_gain;

-	Word16 *vo_p0, *vo_p1, *vo_p2, *vo_p3;

-

-	st = (Coder_State *) spe_state;

-

-	*ser_size = nb_of_bits[*mode];         

-	codec_mode = *mode;                    

-

-	/*--------------------------------------------------------------------------*

-	 *          Initialize pointers to speech vector.                           *

-	 *                                                                          *

-	 *                                                                          *

-	 *                    |-------|-------|-------|-------|-------|-------|     *

-	 *                     past sp   sf1     sf2     sf3     sf4    L_NEXT      *

-	 *                    <-------  Total speech buffer (L_TOTAL)   ------>     *

-	 *              old_speech                                                  *

-	 *                    <-------  LPC analysis window (L_WINDOW)  ------>     *

-	 *                    |       <-- present frame (L_FRAME) ---->             *

-	 *                   p_window |       <----- new speech (L_FRAME) ---->     *

-	 *                            |       |                                     *

-	 *                          speech    |                                     *

-	 *                                 new_speech                               *

-	 *--------------------------------------------------------------------------*/

-

-	new_speech = old_speech + L_TOTAL - L_FRAME - L_FILT;         /* New speech     */

-	speech = old_speech + L_TOTAL - L_FRAME - L_NEXT;             /* Present frame  */

-	p_window = old_speech + L_TOTAL - L_WINDOW; 

-

-	exc = old_exc + PIT_MAX + L_INTERPOL;  

-	wsp = old_wsp + (PIT_MAX / OPL_DECIM); 

-

-	/* copy coder memory state into working space */

-	Copy(st->old_speech, old_speech, L_TOTAL - L_FRAME);

-	Copy(st->old_wsp, old_wsp, PIT_MAX / OPL_DECIM);

-	Copy(st->old_exc, old_exc, PIT_MAX + L_INTERPOL);

-

-	/*---------------------------------------------------------------*

-	 * Down sampling signal from 16kHz to 12.8kHz                    *

-	 * -> The signal is extended by L_FILT samples (padded to zero)  *

-	 * to avoid additional delay (L_FILT samples) in the coder.      *

-	 * The last L_FILT samples are approximated after decimation and *

-	 * are used (and windowed) only in autocorrelations.             *

-	 *---------------------------------------------------------------*/

-

-	Decim_12k8(speech16k, L_FRAME16k, new_speech, st->mem_decim);

-

-	/* last L_FILT samples for autocorrelation window */

-	Copy(st->mem_decim, code, 2 * L_FILT16k);

-	Set_zero(error, L_FILT16k);            /* set next sample to zero */

-	Decim_12k8(error, L_FILT16k, new_speech + L_FRAME, code);

-

-	/*---------------------------------------------------------------*

-	 * Perform 50Hz HP filtering of input signal.                    *

-	 *---------------------------------------------------------------*/

-

-	HP50_12k8(new_speech, L_FRAME, st->mem_sig_in);

-

-	/* last L_FILT samples for autocorrelation window */

-	Copy(st->mem_sig_in, code, 6);

-	HP50_12k8(new_speech + L_FRAME, L_FILT, code);

-

-	/*---------------------------------------------------------------*

-	 * Perform fixed preemphasis through 1 - g z^-1                  *

-	 * Scale signal to get maximum of precision in filtering         *

-	 *---------------------------------------------------------------*/

-

-	mu = PREEMPH_FAC >> 1;              /* Q15 --> Q14 */

-

-	/* get max of new preemphased samples (L_FRAME+L_FILT) */

-	L_tmp = new_speech[0] << 15;

-	L_tmp -= (st->mem_preemph * mu)<<1;

-	L_max = L_abs(L_tmp);

-

-	for (i = 1; i < L_FRAME + L_FILT; i++)

-	{

-		L_tmp = new_speech[i] << 15;

-		L_tmp -= (new_speech[i - 1] * mu)<<1;

-		L_tmp = L_abs(L_tmp);

-		if(L_tmp > L_max)

-		{

-			L_max = L_tmp;                 

-		}

-	}

-

-	/* get scaling factor for new and previous samples */

-	/* limit scaling to Q_MAX to keep dynamic for ringing in low signal */

-	/* limit scaling to Q_MAX also to avoid a[0]<1 in syn_filt_32 */

-	tmp = extract_h(L_max);

-	if (tmp == 0)

-	{

-		shift = Q_MAX;                     

-	} else

-	{

-		shift = norm_s(tmp) - 1;

-		if (shift < 0)

-		{

-			shift = 0;                     

-		}

-		if (shift > Q_MAX)

-		{

-			shift = Q_MAX;                 

-		}

-	}

-	Q_new = shift;                         

-	if (Q_new > st->Q_max[0])

-	{

-		Q_new = st->Q_max[0];              

-	}

-	if (Q_new > st->Q_max[1])

-	{

-		Q_new = st->Q_max[1];              

-	}

-	exp = (Q_new - st->Q_old);

-	st->Q_old = Q_new;                     

-	st->Q_max[1] = st->Q_max[0];           

-	st->Q_max[0] = shift;                  

-

-	/* preemphasis with scaling (L_FRAME+L_FILT) */

-	tmp = new_speech[L_FRAME - 1];         

-

-	for (i = L_FRAME + L_FILT - 1; i > 0; i--)

-	{

-		L_tmp = new_speech[i] << 15;

-		L_tmp -= (new_speech[i - 1] * mu)<<1;

-		L_tmp = (L_tmp << Q_new);

-		new_speech[i] = vo_round(L_tmp);      

-	}

-

-	L_tmp = new_speech[0] << 15;

-	L_tmp -= (st->mem_preemph * mu)<<1;

-	L_tmp = (L_tmp << Q_new);

-	new_speech[0] = vo_round(L_tmp);          

-

-	st->mem_preemph = tmp;                 

-

-	/* scale previous samples and memory */

-

-	Scale_sig(old_speech, L_TOTAL - L_FRAME - L_FILT, exp);

-	Scale_sig(old_exc, PIT_MAX + L_INTERPOL, exp);

-	Scale_sig(st->mem_syn, M, exp);

-	Scale_sig(st->mem_decim2, 3, exp);

-	Scale_sig(&(st->mem_wsp), 1, exp);

-	Scale_sig(&(st->mem_w0), 1, exp);

-

-	/*------------------------------------------------------------------------*

-	 *  Call VAD                                                              *

-	 *  Preemphesis scale down signal in low frequency and keep dynamic in HF.*

-	 *  Vad work slightly in futur (new_speech = speech + L_NEXT - L_FILT).   *

-	 *------------------------------------------------------------------------*/

-	Copy(new_speech, buf, L_FRAME);

-

-#ifdef ASM_OPT        /* asm optimization branch */

-	Scale_sig_opt(buf, L_FRAME, 1 - Q_new);

-#else

-	Scale_sig(buf, L_FRAME, 1 - Q_new);

-#endif

-

-	vad_flag = wb_vad(st->vadSt, buf);          /* Voice Activity Detection */ 

-	if (vad_flag == 0)

-	{

-		st->vad_hist = (st->vad_hist + 1);        

-	} else

-	{

-		st->vad_hist = 0;             

-	}

-

-	/* DTX processing */

-	if (allow_dtx != 0)

-	{

-		/* Note that mode may change here */

-		tx_dtx_handler(st->dtx_encSt, vad_flag, mode);

-		*ser_size = nb_of_bits[*mode]; 

-	}

-

-	if(*mode != MRDTX)

-	{

-		Parm_serial(vad_flag, 1, &prms);

-	}

-	/*------------------------------------------------------------------------*

-	 *  Perform LPC analysis                                                  *

-	 *  ~~~~~~~~~~~~~~~~~~~~                                                  *

-	 *   - autocorrelation + lag windowing                                    *

-	 *   - Levinson-durbin algorithm to find a[]                              *

-	 *   - convert a[] to isp[]                                               *

-	 *   - convert isp[] to isf[] for quantization                            *

-	 *   - quantize and code the isf[]                                        *

-	 *   - convert isf[] to isp[] for interpolation                           *

-	 *   - find the interpolated ISPs and convert to a[] for the 4 subframes  *

-	 *------------------------------------------------------------------------*/

-

-	/* LP analysis centered at 4nd subframe */

-	Autocorr(p_window, M, r_h, r_l);                        /* Autocorrelations */

-	Lag_window(r_h, r_l);                                   /* Lag windowing    */

-	Levinson(r_h, r_l, A, rc, st->mem_levinson);            /* Levinson Durbin  */

-	Az_isp(A, ispnew, st->ispold);                          /* From A(z) to ISP */

-

-	/* Find the interpolated ISPs and convert to a[] for all subframes */

-	Int_isp(st->ispold, ispnew, interpol_frac, A);

-

-	/* update ispold[] for the next frame */

-	Copy(ispnew, st->ispold, M);

-

-	/* Convert ISPs to frequency domain 0..6400 */

-	Isp_isf(ispnew, isf, M);

-

-	/* check resonance for pitch clipping algorithm */

-	Gp_clip_test_isf(isf, st->gp_clip);

-

-	/*----------------------------------------------------------------------*

-	 *  Perform PITCH_OL analysis                                           *

-	 *  ~~~~~~~~~~~~~~~~~~~~~~~~~                                           *

-	 * - Find the residual res[] for the whole speech frame                 *

-	 * - Find the weighted input speech wsp[] for the whole speech frame    *

-	 * - scale wsp[] to avoid overflow in pitch estimation                  *

-	 * - Find open loop pitch lag for whole speech frame                    *

-	 *----------------------------------------------------------------------*/

-	p_A = A;                             

-	for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)

-	{

-		/* Weighting of LPC coefficients */

-		Weight_a(p_A, Ap, GAMMA1, M);

-

-#ifdef ASM_OPT                    /* asm optimization branch */

-		Residu_opt(Ap, &speech[i_subfr], &wsp[i_subfr], L_SUBFR);

-#else

-		Residu(Ap, &speech[i_subfr], &wsp[i_subfr], L_SUBFR);

-#endif

-

-		p_A += (M + 1);                    

-	}

-

-	Deemph2(wsp, TILT_FAC, L_FRAME, &(st->mem_wsp));

-

-	/* find maximum value on wsp[] for 12 bits scaling */

-	max = 0;                              

-	for (i = 0; i < L_FRAME; i++)

-	{

-		tmp = abs_s(wsp[i]);

-		if(tmp > max)

-		{

-			max = tmp;                     

-		}

-	}

-	tmp = st->old_wsp_max;                 

-	if(max > tmp)

-	{

-		tmp = max;                         /* tmp = max(wsp_max, old_wsp_max) */

-	}

-	st->old_wsp_max = max;                

-

-	shift = norm_s(tmp) - 3;

-	if (shift > 0)

-	{

-		shift = 0;                         /* shift = 0..-3 */

-	}

-	/* decimation of wsp[] to search pitch in LF and to reduce complexity */

-	LP_Decim2(wsp, L_FRAME, st->mem_decim2);

-

-	/* scale wsp[] in 12 bits to avoid overflow */

-#ifdef  ASM_OPT                  /* asm optimization branch */

-	Scale_sig_opt(wsp, L_FRAME / OPL_DECIM, shift);

-#else

-	Scale_sig(wsp, L_FRAME / OPL_DECIM, shift);

-#endif

-	/* scale old_wsp (warning: exp must be Q_new-Q_old) */

-	exp = exp + (shift - st->old_wsp_shift);

-	st->old_wsp_shift = shift;

-

-	Scale_sig(old_wsp, PIT_MAX / OPL_DECIM, exp);

-	Scale_sig(st->old_hp_wsp, PIT_MAX / OPL_DECIM, exp);

-

-	scale_mem_Hp_wsp(st->hp_wsp_mem, exp);

-

-	/* Find open loop pitch lag for whole speech frame */

-

-	if(*ser_size == NBBITS_7k)

-	{

-		/* Find open loop pitch lag for whole speech frame */

-		T_op = Pitch_med_ol(wsp, st, L_FRAME / OPL_DECIM);

-	} else

-	{

-		/* Find open loop pitch lag for first 1/2 frame */

-		T_op = Pitch_med_ol(wsp, st, (L_FRAME/2) / OPL_DECIM);

-	}

-

-	if(st->ol_gain > 19661)       /* 0.6 in Q15 */

-	{

-		st->old_T0_med = Med_olag(T_op, st->old_ol_lag);       

-		st->ada_w = 32767;                 

-	} else

-	{

-		st->ada_w = vo_mult(st->ada_w, 29491);

-	}

-

-	if(st->ada_w < 26214)

-		st->ol_wght_flg = 0;

-	else

-		st->ol_wght_flg = 1;

-

-	wb_vad_tone_detection(st->vadSt, st->ol_gain);

-	T_op *= OPL_DECIM;                     

-

-	if(*ser_size != NBBITS_7k)

-	{

-		/* Find open loop pitch lag for second 1/2 frame */

-		T_op2 = Pitch_med_ol(wsp + ((L_FRAME / 2) / OPL_DECIM), st, (L_FRAME/2) / OPL_DECIM);

-

-		if(st->ol_gain > 19661)   /* 0.6 in Q15 */

-		{

-			st->old_T0_med = Med_olag(T_op2, st->old_ol_lag);  

-			st->ada_w = 32767;             

-		} else

-		{

-			st->ada_w = mult(st->ada_w, 29491); 

-		}

-

-		if(st->ada_w < 26214)

-			st->ol_wght_flg = 0;

-		else

-			st->ol_wght_flg = 1;

-

-		wb_vad_tone_detection(st->vadSt, st->ol_gain);

-

-		T_op2 *= OPL_DECIM;                

-

-	} else

-	{

-		T_op2 = T_op;                      

-	}

-	/*----------------------------------------------------------------------*

-	 *                              DTX-CNG                                 *

-	 *----------------------------------------------------------------------*/

-	if(*mode == MRDTX)            /* CNG mode */

-	{

-		/* Buffer isf's and energy */

-#ifdef ASM_OPT                   /* asm optimization branch */

-		Residu_opt(&A[3 * (M + 1)], speech, exc, L_FRAME);

-#else

-		Residu(&A[3 * (M + 1)], speech, exc, L_FRAME);

-#endif

-

-		for (i = 0; i < L_FRAME; i++)

-		{

-			exc2[i] = shr(exc[i], Q_new);  

-		}

-

-		L_tmp = 0;                         

-		for (i = 0; i < L_FRAME; i++)

-			L_tmp += (exc2[i] * exc2[i])<<1;

-

-		L_tmp >>= 1;

-

-		dtx_buffer(st->dtx_encSt, isf, L_tmp, codec_mode);

-

-		/* Quantize and code the ISFs */

-		dtx_enc(st->dtx_encSt, isf, exc2, &prms);

-

-		/* Convert ISFs to the cosine domain */

-		Isf_isp(isf, ispnew_q, M);

-		Isp_Az(ispnew_q, Aq, M, 0);

-

-		for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)

-		{

-			corr_gain = synthesis(Aq, &exc2[i_subfr], 0, &speech16k[i_subfr * 5 / 4], st);

-		}

-		Copy(isf, st->isfold, M);

-

-		/* reset speech coder memories */

-		Reset_encoder(st, 0);

-

-		/*--------------------------------------------------*

-		 * Update signal for next frame.                    *

-		 * -> save past of speech[] and wsp[].              *

-		 *--------------------------------------------------*/

-

-		Copy(&old_speech[L_FRAME], st->old_speech, L_TOTAL - L_FRAME);

-		Copy(&old_wsp[L_FRAME / OPL_DECIM], st->old_wsp, PIT_MAX / OPL_DECIM);

-

-		return;

-	}

-	/*----------------------------------------------------------------------*

-	 *                               ACELP                                  *

-	 *----------------------------------------------------------------------*/

-

-	/* Quantize and code the ISFs */

-

-	if (*ser_size <= NBBITS_7k)

-	{

-		Qpisf_2s_36b(isf, isf, st->past_isfq, indice, 4);

-

-		Parm_serial(indice[0], 8, &prms);

-		Parm_serial(indice[1], 8, &prms);

-		Parm_serial(indice[2], 7, &prms);

-		Parm_serial(indice[3], 7, &prms);

-		Parm_serial(indice[4], 6, &prms);

-	} else

-	{

-		Qpisf_2s_46b(isf, isf, st->past_isfq, indice, 4);

-

-		Parm_serial(indice[0], 8, &prms);

-		Parm_serial(indice[1], 8, &prms);

-		Parm_serial(indice[2], 6, &prms);

-		Parm_serial(indice[3], 7, &prms);

-		Parm_serial(indice[4], 7, &prms);

-		Parm_serial(indice[5], 5, &prms);

-		Parm_serial(indice[6], 5, &prms);

-	}

-

-	/* Check stability on isf : distance between old isf and current isf */

-

-	L_tmp = 0;                           

-	for (i = 0; i < M - 1; i++)

-	{

-		tmp = vo_sub(isf[i], st->isfold[i]);

-		L_tmp += (tmp * tmp)<<1;

-	}

-

-	tmp = extract_h(L_shl2(L_tmp, 8)); 

-

-	tmp = vo_mult(tmp, 26214);                /* tmp = L_tmp*0.8/256 */

-	tmp = vo_sub(20480, tmp);                 /* 1.25 - tmp (in Q14) */

-

-	stab_fac = shl(tmp, 1); 

-

-	if (stab_fac < 0)

-	{

-		stab_fac = 0;                      

-	}

-	Copy(isf, st->isfold, M);

-

-	/* Convert ISFs to the cosine domain */

-	Isf_isp(isf, ispnew_q, M);

-

-	if (st->first_frame != 0)

-	{

-		st->first_frame = 0;              

-		Copy(ispnew_q, st->ispold_q, M);

-	}

-	/* Find the interpolated ISPs and convert to a[] for all subframes */

-

-	Int_isp(st->ispold_q, ispnew_q, interpol_frac, Aq);

-

-	/* update ispold[] for the next frame */

-	Copy(ispnew_q, st->ispold_q, M);

-

-	p_Aq = Aq;

-	for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)

-	{

-#ifdef ASM_OPT               /* asm optimization branch */

-		Residu_opt(p_Aq, &speech[i_subfr], &exc[i_subfr], L_SUBFR);

-#else

-		Residu(p_Aq, &speech[i_subfr], &exc[i_subfr], L_SUBFR);

-#endif

-		p_Aq += (M + 1);                   

-	}

-

-	/* Buffer isf's and energy for dtx on non-speech frame */

-	if (vad_flag == 0)

-	{

-		for (i = 0; i < L_FRAME; i++)

-		{

-			exc2[i] = exc[i] >> Q_new;

-		}

-		L_tmp = 0;                         

-		for (i = 0; i < L_FRAME; i++)

-			L_tmp += (exc2[i] * exc2[i])<<1;

-		L_tmp >>= 1;

-

-		dtx_buffer(st->dtx_encSt, isf, L_tmp, codec_mode);

-	}

-	/* range for closed loop pitch search in 1st subframe */

-

-	T0_min = T_op - 8;

-	if (T0_min < PIT_MIN)

-	{

-		T0_min = PIT_MIN;                  

-	}

-	T0_max = (T0_min + 15);

-

-	if(T0_max > PIT_MAX)

-	{

-		T0_max = PIT_MAX;                  

-		T0_min = T0_max - 15;          

-	}

-	/*------------------------------------------------------------------------*

-	 *          Loop for every subframe in the analysis frame                 *

-	 *------------------------------------------------------------------------*

-	 *  To find the pitch and innovation parameters. The subframe size is     *

-	 *  L_SUBFR and the loop is repeated L_FRAME/L_SUBFR times.               *

-	 *     - compute the target signal for pitch search                       *

-	 *     - compute impulse response of weighted synthesis filter (h1[])     *

-	 *     - find the closed-loop pitch parameters                            *

-	 *     - encode the pitch dealy                                           *

-	 *     - find 2 lt prediction (with / without LP filter for lt pred)      *

-	 *     - find 2 pitch gains and choose the best lt prediction.            *

-	 *     - find target vector for codebook search                           *

-	 *     - update the impulse response h1[] for codebook search             *

-	 *     - correlation between target vector and impulse response           *

-	 *     - codebook search and encoding                                     *

-	 *     - VQ of pitch and codebook gains                                   *

-	 *     - find voicing factor and tilt of code for next subframe.          *

-	 *     - update states of weighting filter                                *

-	 *     - find excitation and synthesis speech                             *

-	 *------------------------------------------------------------------------*/

-	p_A = A;                               

-	p_Aq = Aq;                             

-	for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)

-	{

-		pit_flag = i_subfr;                

-		if ((i_subfr == 2 * L_SUBFR) && (*ser_size > NBBITS_7k))

-		{

-			pit_flag = 0;                 

-			/* range for closed loop pitch search in 3rd subframe */

-			T0_min = (T_op2 - 8);

-

-			if (T0_min < PIT_MIN)

-			{

-				T0_min = PIT_MIN;          

-			}

-			T0_max = (T0_min + 15);

-			if (T0_max > PIT_MAX)

-			{

-				T0_max = PIT_MAX;         

-				T0_min = (T0_max - 15);

-			}

-		}

-		/*-----------------------------------------------------------------------*

-		 *                                                                       *

-		 *        Find the target vector for pitch search:                       *

-		 *        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                        *

-		 *                                                                       *

-		 *             |------|  res[n]                                          *

-		 * speech[n]---| A(z) |--------                                          *

-		 *             |------|       |   |--------| error[n]  |------|          *

-		 *                   zero -- (-)--| 1/A(z) |-----------| W(z) |-- target *

-		 *                   exc          |--------|           |------|          *

-		 *                                                                       *

-		 * Instead of subtracting the zero-input response of filters from        *

-		 * the weighted input speech, the above configuration is used to         *

-		 * compute the target vector.                                            *

-		 *                                                                       *

-		 *-----------------------------------------------------------------------*/

-

-		for (i = 0; i < M; i++)

-		{

-			error[i] = vo_sub(speech[i + i_subfr - M], st->mem_syn[i]);

-		}

-

-#ifdef ASM_OPT              /* asm optimization branch */

-		Residu_opt(p_Aq, &speech[i_subfr], &exc[i_subfr], L_SUBFR);

-#else

-		Residu(p_Aq, &speech[i_subfr], &exc[i_subfr], L_SUBFR);

-#endif

-		Syn_filt(p_Aq, &exc[i_subfr], error + M, L_SUBFR, error, 0);

-		Weight_a(p_A, Ap, GAMMA1, M);

-

-#ifdef ASM_OPT             /* asm optimization branch */

-		Residu_opt(Ap, error + M, xn, L_SUBFR);

-#else

-		Residu(Ap, error + M, xn, L_SUBFR);

-#endif

-		Deemph2(xn, TILT_FAC, L_SUBFR, &(st->mem_w0));

-

-		/*----------------------------------------------------------------------*

-		 * Find approx. target in residual domain "cn[]" for inovation search.  *

-		 *----------------------------------------------------------------------*/

-		/* first half: xn[] --> cn[] */

-		Set_zero(code, M);

-		Copy(xn, code + M, L_SUBFR / 2);

-		tmp = 0;                          

-		Preemph2(code + M, TILT_FAC, L_SUBFR / 2, &tmp);

-		Weight_a(p_A, Ap, GAMMA1, M);

-		Syn_filt(Ap,code + M, code + M, L_SUBFR / 2, code, 0);

-

-#ifdef ASM_OPT                /* asm optimization branch */

-		Residu_opt(p_Aq,code + M, cn, L_SUBFR / 2);

-#else

-		Residu(p_Aq,code + M, cn, L_SUBFR / 2);

-#endif

-

-		/* second half: res[] --> cn[] (approximated and faster) */

-		Copy(&exc[i_subfr + (L_SUBFR / 2)], cn + (L_SUBFR / 2), L_SUBFR / 2);

-

-		/*---------------------------------------------------------------*

-		 * Compute impulse response, h1[], of weighted synthesis filter  * 

-		 *---------------------------------------------------------------*/

-

-		Set_zero(error, M + L_SUBFR);

-		Weight_a(p_A, error + M, GAMMA1, M);

-

-		vo_p0 = error+M;

-		vo_p3 = h1;

-		for (i = 0; i < L_SUBFR; i++)

-		{

-			L_tmp = *vo_p0 << 14;        /* x4 (Q12 to Q14) */

-			vo_p1 = p_Aq + 1;

-			vo_p2 = vo_p0-1;

-			for (j = 1; j <= M/4; j++)

-			{

-				L_tmp -= *vo_p1++ * *vo_p2--;

-				L_tmp -= *vo_p1++ * *vo_p2--;

-				L_tmp -= *vo_p1++ * *vo_p2--;

-				L_tmp -= *vo_p1++ * *vo_p2--;

-			}

-			*vo_p3++ = *vo_p0++ = vo_round((L_tmp <<4));

-		}

-		/* deemph without division by 2 -> Q14 to Q15 */

-		tmp = 0; 

-		Deemph2(h1, TILT_FAC, L_SUBFR, &tmp);   /* h1 in Q14 */

-

-		/* h2 in Q12 for codebook search */

-		Copy(h1, h2, L_SUBFR);

-

-		/*---------------------------------------------------------------*

-		 * scale xn[] and h1[] to avoid overflow in dot_product12()      *

-		 *---------------------------------------------------------------*/

-#ifdef  ASM_OPT                  /* asm optimization branch */

-		Scale_sig_opt(h2, L_SUBFR, -2);

-		Scale_sig_opt(xn, L_SUBFR, shift);     /* scaling of xn[] to limit dynamic at 12 bits */

-		Scale_sig_opt(h1, L_SUBFR, 1 + shift);  /* set h1[] in Q15 with scaling for convolution */

-#else

-		Scale_sig(h2, L_SUBFR, -2);

-		Scale_sig(xn, L_SUBFR, shift);     /* scaling of xn[] to limit dynamic at 12 bits */

-		Scale_sig(h1, L_SUBFR, 1 + shift);  /* set h1[] in Q15 with scaling for convolution */

-#endif

-		/*----------------------------------------------------------------------*

-		 *                 Closed-loop fractional pitch search                  *

-		 *----------------------------------------------------------------------*/

-		/* find closed loop fractional pitch  lag */

-		if(*ser_size <= NBBITS_9k)

-		{

-			T0 = Pitch_fr4(&exc[i_subfr], xn, h1, T0_min, T0_max, &T0_frac,

-					pit_flag, PIT_MIN, PIT_FR1_8b, L_SUBFR);

-

-			/* encode pitch lag */

-			if (pit_flag == 0)             /* if 1st/3rd subframe */

-			{

-				/*--------------------------------------------------------------*

-				 * The pitch range for the 1st/3rd subframe is encoded with     *

-				 * 8 bits and is divided as follows:                            *

-				 *   PIT_MIN to PIT_FR1-1  resolution 1/2 (frac = 0 or 2)       *

-				 *   PIT_FR1 to PIT_MAX    resolution 1   (frac = 0)            *

-				 *--------------------------------------------------------------*/

-				if (T0 < PIT_FR1_8b)

-				{

-					index = ((T0 << 1) + (T0_frac >> 1) - (PIT_MIN<<1));

-				} else

-				{

-					index = ((T0 - PIT_FR1_8b) + ((PIT_FR1_8b - PIT_MIN)*2));

-				}

-

-				Parm_serial(index, 8, &prms);

-

-				/* find T0_min and T0_max for subframe 2 and 4 */

-				T0_min = (T0 - 8);

-				if (T0_min < PIT_MIN)

-				{

-					T0_min = PIT_MIN;

-				}

-				T0_max = T0_min + 15;

-				if (T0_max > PIT_MAX)

-				{

-					T0_max = PIT_MAX;

-					T0_min = (T0_max - 15);

-				}

-			} else

-			{                              /* if subframe 2 or 4 */

-				/*--------------------------------------------------------------*

-				 * The pitch range for subframe 2 or 4 is encoded with 5 bits:  *

-				 *   T0_min  to T0_max     resolution 1/2 (frac = 0 or 2)       *

-				 *--------------------------------------------------------------*/

-				i = (T0 - T0_min);

-				index = (i << 1) + (T0_frac >> 1);

-

-				Parm_serial(index, 5, &prms);

-			}

-		} else

-		{

-			T0 = Pitch_fr4(&exc[i_subfr], xn, h1, T0_min, T0_max, &T0_frac,

-					pit_flag, PIT_FR2, PIT_FR1_9b, L_SUBFR);

-

-			/* encode pitch lag */

-			if (pit_flag == 0)             /* if 1st/3rd subframe */

-			{

-				/*--------------------------------------------------------------*

-				 * The pitch range for the 1st/3rd subframe is encoded with     *

-				 * 9 bits and is divided as follows:                            *

-				 *   PIT_MIN to PIT_FR2-1  resolution 1/4 (frac = 0,1,2 or 3)   *

-				 *   PIT_FR2 to PIT_FR1-1  resolution 1/2 (frac = 0 or 1)       *

-				 *   PIT_FR1 to PIT_MAX    resolution 1   (frac = 0)            *

-				 *--------------------------------------------------------------*/

-

-				if (T0 < PIT_FR2)

-				{

-					index = ((T0 << 2) + T0_frac) - (PIT_MIN << 2);

-				} else if(T0 < PIT_FR1_9b)

-				{

-					index = ((((T0 << 1) + (T0_frac >> 1)) - (PIT_FR2<<1)) + ((PIT_FR2 - PIT_MIN)<<2));

-				} else

-				{

-					index = (((T0 - PIT_FR1_9b) + ((PIT_FR2 - PIT_MIN)<<2)) + ((PIT_FR1_9b - PIT_FR2)<<1));

-				}

-

-				Parm_serial(index, 9, &prms);

-

-				/* find T0_min and T0_max for subframe 2 and 4 */

-

-				T0_min = (T0 - 8);

-				if (T0_min < PIT_MIN)

-				{

-					T0_min = PIT_MIN; 

-				}

-				T0_max = T0_min + 15;

-

-				if (T0_max > PIT_MAX)

-				{

-					T0_max = PIT_MAX;

-					T0_min = (T0_max - 15);

-				}

-			} else

-			{                              /* if subframe 2 or 4 */

-				/*--------------------------------------------------------------*

-				 * The pitch range for subframe 2 or 4 is encoded with 6 bits:  *

-				 *   T0_min  to T0_max     resolution 1/4 (frac = 0,1,2 or 3)   *

-				 *--------------------------------------------------------------*/

-				i = (T0 - T0_min);

-				index = (i << 2) + T0_frac;

-				Parm_serial(index, 6, &prms);

-			}

-		}

-

-		/*-----------------------------------------------------------------*

-		 * Gain clipping test to avoid unstable synthesis on frame erasure *

-		 *-----------------------------------------------------------------*/

-

-		clip_gain = 0;

-		if((st->gp_clip[0] < 154) && (st->gp_clip[1] > 14746))

-			clip_gain = 1;

-

-		/*-----------------------------------------------------------------*

-		 * - find unity gain pitch excitation (adaptive codebook entry)    *

-		 *   with fractional interpolation.                                *

-		 * - find filtered pitch exc. y1[]=exc[] convolved with h1[])      *

-		 * - compute pitch gain1                                           *

-		 *-----------------------------------------------------------------*/

-		/* find pitch exitation */

-#ifdef ASM_OPT                  /* asm optimization branch */

-		pred_lt4_asm(&exc[i_subfr], T0, T0_frac, L_SUBFR + 1);

-#else

-		Pred_lt4(&exc[i_subfr], T0, T0_frac, L_SUBFR + 1);

-#endif

-		if (*ser_size > NBBITS_9k)

-		{

-#ifdef ASM_OPT                   /* asm optimization branch */

-			Convolve_asm(&exc[i_subfr], h1, y1, L_SUBFR);

-#else

-			Convolve(&exc[i_subfr], h1, y1, L_SUBFR);

-#endif 

-			gain1 = G_pitch(xn, y1, g_coeff, L_SUBFR);

-			/* clip gain if necessary to avoid problem at decoder */

-			if ((clip_gain != 0) && (gain1 > GP_CLIP))

-			{

-				gain1 = GP_CLIP; 

-			}

-			/* find energy of new target xn2[] */

-			Updt_tar(xn, dn, y1, gain1, L_SUBFR);       /* dn used temporary */

-		} else

-		{

-			gain1 = 0; 

-		}

-		/*-----------------------------------------------------------------*

-		 * - find pitch excitation filtered by 1st order LP filter.        *

-		 * - find filtered pitch exc. y2[]=exc[] convolved with h1[])      *

-		 * - compute pitch gain2                                           *

-		 *-----------------------------------------------------------------*/

-		/* find pitch excitation with lp filter */

-		vo_p0 = exc + i_subfr-1;

-		vo_p1 = code;

-		/* find pitch excitation with lp filter */

-		for (i = 0; i < L_SUBFR/2; i++)

-		{

-			L_tmp = 5898 * *vo_p0++;

-			L_tmp1 = 5898 * *vo_p0;

-			L_tmp += 20972 * *vo_p0++;

-			L_tmp1 += 20972 * *vo_p0++;

-			L_tmp1 += 5898 * *vo_p0--;

-			L_tmp += 5898 * *vo_p0;

-			*vo_p1++ = (L_tmp + 0x4000)>>15;

-			*vo_p1++ = (L_tmp1 + 0x4000)>>15;

-		}

-

-#ifdef ASM_OPT                 /* asm optimization branch */

-		Convolve_asm(code, h1, y2, L_SUBFR);

-#else

-		Convolve(code, h1, y2, L_SUBFR);

-#endif 

-

-		gain2 = G_pitch(xn, y2, g_coeff2, L_SUBFR);

-

-		/* clip gain if necessary to avoid problem at decoder */

-		if ((clip_gain != 0) && (gain2 > GP_CLIP))

-		{

-			gain2 = GP_CLIP;

-		}

-		/* find energy of new target xn2[] */

-		Updt_tar(xn, xn2, y2, gain2, L_SUBFR);

-		/*-----------------------------------------------------------------*

-		 * use the best prediction (minimise quadratic error).             *

-		 *-----------------------------------------------------------------*/

-		select = 0; 

-		if(*ser_size > NBBITS_9k)

-		{

-			L_tmp = 0L;

-			vo_p0 = dn;

-			vo_p1 = xn2;

-			for (i = 0; i < L_SUBFR/2; i++)

-			{

-				L_tmp += *vo_p0 * *vo_p0;

-				vo_p0++;

-				L_tmp -= *vo_p1 * *vo_p1;

-				vo_p1++;

-				L_tmp += *vo_p0 * *vo_p0;

-				vo_p0++;

-				L_tmp -= *vo_p1 * *vo_p1;

-				vo_p1++;

-			}

-

-			if (L_tmp <= 0)

-			{

-				select = 1; 

-			}

-			Parm_serial(select, 1, &prms);

-		}

-		if (select == 0)

-		{

-			/* use the lp filter for pitch excitation prediction */

-			gain_pit = gain2;

-			Copy(code, &exc[i_subfr], L_SUBFR);

-			Copy(y2, y1, L_SUBFR);

-			Copy(g_coeff2, g_coeff, 4);

-		} else

-		{

-			/* no filter used for pitch excitation prediction */

-			gain_pit = gain1;

-			Copy(dn, xn2, L_SUBFR);        /* target vector for codebook search */

-		}

-		/*-----------------------------------------------------------------*

-		 * - update cn[] for codebook search                               *

-		 *-----------------------------------------------------------------*/

-		Updt_tar(cn, cn, &exc[i_subfr], gain_pit, L_SUBFR);

-

-#ifdef  ASM_OPT                           /* asm optimization branch */

-		Scale_sig_opt(cn, L_SUBFR, shift);     /* scaling of cn[] to limit dynamic at 12 bits */

-#else

-		Scale_sig(cn, L_SUBFR, shift);     /* scaling of cn[] to limit dynamic at 12 bits */

-#endif

-		/*-----------------------------------------------------------------*

-		 * - include fixed-gain pitch contribution into impulse resp. h1[] *

-		 *-----------------------------------------------------------------*/

-		tmp = 0;

-		Preemph(h2, st->tilt_code, L_SUBFR, &tmp);

-

-		if (T0_frac > 2)

-			T0 = (T0 + 1);

-		Pit_shrp(h2, T0, PIT_SHARP, L_SUBFR);

-		/*-----------------------------------------------------------------*

-		 * - Correlation between target xn2[] and impulse response h1[]    *

-		 * - Innovative codebook search                                    *

-		 *-----------------------------------------------------------------*/

-		cor_h_x(h2, xn2, dn);

-		if (*ser_size <= NBBITS_7k)

-		{

-			ACELP_2t64_fx(dn, cn, h2, code, y2, indice);

-

-			Parm_serial(indice[0], 12, &prms);

-		} else if(*ser_size <= NBBITS_9k)

-		{

-			ACELP_4t64_fx(dn, cn, h2, code, y2, 20, *ser_size, indice);

-

-			Parm_serial(indice[0], 5, &prms);

-			Parm_serial(indice[1], 5, &prms);

-			Parm_serial(indice[2], 5, &prms);

-			Parm_serial(indice[3], 5, &prms);

-		} else if(*ser_size <= NBBITS_12k)

-		{

-			ACELP_4t64_fx(dn, cn, h2, code, y2, 36, *ser_size, indice);

-

-			Parm_serial(indice[0], 9, &prms);

-			Parm_serial(indice[1], 9, &prms);

-			Parm_serial(indice[2], 9, &prms);

-			Parm_serial(indice[3], 9, &prms);

-		} else if(*ser_size <= NBBITS_14k)

-		{

-			ACELP_4t64_fx(dn, cn, h2, code, y2, 44, *ser_size, indice);

-

-			Parm_serial(indice[0], 13, &prms);

-			Parm_serial(indice[1], 13, &prms);

-			Parm_serial(indice[2], 9, &prms);

-			Parm_serial(indice[3], 9, &prms);

-		} else if(*ser_size <= NBBITS_16k)

-		{

-			ACELP_4t64_fx(dn, cn, h2, code, y2, 52, *ser_size, indice);

-

-			Parm_serial(indice[0], 13, &prms);

-			Parm_serial(indice[1], 13, &prms);

-			Parm_serial(indice[2], 13, &prms);

-			Parm_serial(indice[3], 13, &prms);

-		} else if(*ser_size <= NBBITS_18k)

-		{

-			ACELP_4t64_fx(dn, cn, h2, code, y2, 64, *ser_size, indice);

-

-			Parm_serial(indice[0], 2, &prms);

-			Parm_serial(indice[1], 2, &prms);

-			Parm_serial(indice[2], 2, &prms);

-			Parm_serial(indice[3], 2, &prms);

-			Parm_serial(indice[4], 14, &prms);

-			Parm_serial(indice[5], 14, &prms);

-			Parm_serial(indice[6], 14, &prms);

-			Parm_serial(indice[7], 14, &prms);

-		} else if(*ser_size <= NBBITS_20k)

-		{

-			ACELP_4t64_fx(dn, cn, h2, code, y2, 72, *ser_size, indice);

-

-			Parm_serial(indice[0], 10, &prms);

-			Parm_serial(indice[1], 10, &prms);

-			Parm_serial(indice[2], 2, &prms);

-			Parm_serial(indice[3], 2, &prms);

-			Parm_serial(indice[4], 10, &prms);

-			Parm_serial(indice[5], 10, &prms);

-			Parm_serial(indice[6], 14, &prms);

-			Parm_serial(indice[7], 14, &prms);

-		} else

-		{

-			ACELP_4t64_fx(dn, cn, h2, code, y2, 88, *ser_size, indice);

-

-			Parm_serial(indice[0], 11, &prms);

-			Parm_serial(indice[1], 11, &prms);

-			Parm_serial(indice[2], 11, &prms);

-			Parm_serial(indice[3], 11, &prms);

-			Parm_serial(indice[4], 11, &prms);

-			Parm_serial(indice[5], 11, &prms);

-			Parm_serial(indice[6], 11, &prms);

-			Parm_serial(indice[7], 11, &prms);

-		}

-		/*-------------------------------------------------------*

-		 * - Add the fixed-gain pitch contribution to code[].    *

-		 *-------------------------------------------------------*/

-		tmp = 0; 

-		Preemph(code, st->tilt_code, L_SUBFR, &tmp);

-		Pit_shrp(code, T0, PIT_SHARP, L_SUBFR);

-		/*----------------------------------------------------------*

-		 *  - Compute the fixed codebook gain                       *

-		 *  - quantize fixed codebook gain                          *

-		 *----------------------------------------------------------*/

-		if(*ser_size <= NBBITS_9k)

-		{

-			index = Q_gain2(xn, y1, Q_new + shift, y2, code, g_coeff, L_SUBFR, 6,

-					&gain_pit, &L_gain_code, clip_gain, st->qua_gain);

-			Parm_serial(index, 6, &prms);

-		} else

-		{

-			index = Q_gain2(xn, y1, Q_new + shift, y2, code, g_coeff, L_SUBFR, 7,

-					&gain_pit, &L_gain_code, clip_gain, st->qua_gain);

-			Parm_serial(index, 7, &prms);

-		}

-		/* test quantized gain of pitch for pitch clipping algorithm */

-		Gp_clip_test_gain_pit(gain_pit, st->gp_clip);

-

-		L_tmp = L_shl(L_gain_code, Q_new); 

-		gain_code = extract_h(L_add(L_tmp, 0x8000));

-

-		/*----------------------------------------------------------*

-		 * Update parameters for the next subframe.                 *

-		 * - tilt of code: 0.0 (unvoiced) to 0.5 (voiced)           *

-		 *----------------------------------------------------------*/

-		/* find voice factor in Q15 (1=voiced, -1=unvoiced) */

-		Copy(&exc[i_subfr], exc2, L_SUBFR);

-

-#ifdef ASM_OPT                           /* asm optimization branch */

-		Scale_sig_opt(exc2, L_SUBFR, shift);

-#else

-		Scale_sig(exc2, L_SUBFR, shift);

-#endif

-		voice_fac = voice_factor(exc2, shift, gain_pit, code, gain_code, L_SUBFR);

-		/* tilt of code for next subframe: 0.5=voiced, 0=unvoiced */

-		st->tilt_code = ((voice_fac >> 2) + 8192);

-		/*------------------------------------------------------*

-		 * - Update filter's memory "mem_w0" for finding the    *

-		 *   target vector in the next subframe.                *

-		 * - Find the total excitation                          *

-		 * - Find synthesis speech to update mem_syn[].         *

-		 *------------------------------------------------------*/

-

-		/* y2 in Q9, gain_pit in Q14 */

-		L_tmp = (gain_code * y2[L_SUBFR - 1])<<1;

-		L_tmp = L_shl(L_tmp, (5 + shift));

-		L_tmp = L_negate(L_tmp);

-		L_tmp += (xn[L_SUBFR - 1] * 16384)<<1;

-		L_tmp -= (y1[L_SUBFR - 1] * gain_pit)<<1;

-		L_tmp = L_shl(L_tmp, (1 - shift));

-		st->mem_w0 = extract_h(L_add(L_tmp, 0x8000));

-

-		if (*ser_size >= NBBITS_24k)

-			Copy(&exc[i_subfr], exc2, L_SUBFR);

-

-		for (i = 0; i < L_SUBFR; i++)

-		{

-			/* code in Q9, gain_pit in Q14 */

-			L_tmp = (gain_code * code[i])<<1;

-			L_tmp = (L_tmp << 5);

-			L_tmp += (exc[i + i_subfr] * gain_pit)<<1;

-			L_tmp = L_shl2(L_tmp, 1); 

-			exc[i + i_subfr] = extract_h(L_add(L_tmp, 0x8000));

-		}

-

-		Syn_filt(p_Aq,&exc[i_subfr], synth, L_SUBFR, st->mem_syn, 1);

-

-		if(*ser_size >= NBBITS_24k)

-		{

-			/*------------------------------------------------------------*

-			 * phase dispersion to enhance noise in low bit rate          *

-			 *------------------------------------------------------------*/

-			/* L_gain_code in Q16 */

-			VO_L_Extract(L_gain_code, &gain_code, &gain_code_lo);

-

-			/*------------------------------------------------------------*

-			 * noise enhancer                                             *

-			 * ~~~~~~~~~~~~~~                                             *

-			 * - Enhance excitation on noise. (modify gain of code)       *

-			 *   If signal is noisy and LPC filter is stable, move gain   *

-			 *   of code 1.5 dB toward gain of code threshold.            *

-			 *   This decrease by 3 dB noise energy variation.            *

-			 *------------------------------------------------------------*/

-			tmp = (16384 - (voice_fac >> 1));        /* 1=unvoiced, 0=voiced */

-			fac = vo_mult(stab_fac, tmp);

-			L_tmp = L_gain_code; 

-			if(L_tmp < st->L_gc_thres)

-			{

-				L_tmp = vo_L_add(L_tmp, Mpy_32_16(gain_code, gain_code_lo, 6226));

-				if(L_tmp > st->L_gc_thres)

-				{

-					L_tmp = st->L_gc_thres;

-				}

-			} else

-			{

-				L_tmp = Mpy_32_16(gain_code, gain_code_lo, 27536);

-				if(L_tmp < st->L_gc_thres)

-				{

-					L_tmp = st->L_gc_thres;

-				}

-			}

-			st->L_gc_thres = L_tmp;

-

-			L_gain_code = Mpy_32_16(gain_code, gain_code_lo, (32767 - fac));

-			VO_L_Extract(L_tmp, &gain_code, &gain_code_lo);

-			L_gain_code = vo_L_add(L_gain_code, Mpy_32_16(gain_code, gain_code_lo, fac));

-

-			/*------------------------------------------------------------*

-			 * pitch enhancer                                             *

-			 * ~~~~~~~~~~~~~~                                             *

-			 * - Enhance excitation on voice. (HP filtering of code)      *

-			 *   On voiced signal, filtering of code by a smooth fir HP   *

-			 *   filter to decrease energy of code in low frequency.      *

-			 *------------------------------------------------------------*/

-

-			tmp = ((voice_fac >> 3) + 4096); /* 0.25=voiced, 0=unvoiced */

-

-			L_tmp = L_deposit_h(code[0]);

-			L_tmp -= (code[1] * tmp)<<1;

-			code2[0] = vo_round(L_tmp); 

-

-			for (i = 1; i < L_SUBFR - 1; i++)

-			{

-				L_tmp = L_deposit_h(code[i]);

-				L_tmp -= (code[i + 1] * tmp)<<1;

-				L_tmp -= (code[i - 1] * tmp)<<1;

-				code2[i] = vo_round(L_tmp); 

-			}

-

-			L_tmp = L_deposit_h(code[L_SUBFR - 1]);

-			L_tmp -= (code[L_SUBFR - 2] * tmp)<<1;

-			code2[L_SUBFR - 1] = vo_round(L_tmp); 

-

-			/* build excitation */

-			gain_code = vo_round(L_shl(L_gain_code, Q_new));

-

-			for (i = 0; i < L_SUBFR; i++)

-			{

-				L_tmp = (code2[i] * gain_code)<<1;

-				L_tmp = (L_tmp << 5);

-				L_tmp += (exc2[i] * gain_pit)<<1;

-				L_tmp = (L_tmp << 1);

-				exc2[i] = vo_round(L_tmp);

-			}

-

-			corr_gain = synthesis(p_Aq, exc2, Q_new, &speech16k[i_subfr * 5 / 4], st);

-			Parm_serial(corr_gain, 4, &prms);

-		}

-		p_A += (M + 1);

-		p_Aq += (M + 1);

-	}                                      /* end of subframe loop */

-

-	/*--------------------------------------------------*

-	 * Update signal for next frame.                    *

-	 * -> save past of speech[], wsp[] and exc[].       *

-	 *--------------------------------------------------*/

-	Copy(&old_speech[L_FRAME], st->old_speech, L_TOTAL - L_FRAME);

-	Copy(&old_wsp[L_FRAME / OPL_DECIM], st->old_wsp, PIT_MAX / OPL_DECIM);

-	Copy(&old_exc[L_FRAME], st->old_exc, PIT_MAX + L_INTERPOL);

-	return;

-}

-

-/*-----------------------------------------------------*

-* Function synthesis()                                *

-*                                                     *

-* Synthesis of signal at 16kHz with HF extension.     *

-*                                                     *

-*-----------------------------------------------------*/

-

-static Word16 synthesis(

-		Word16 Aq[],                          /* A(z)  : quantized Az               */

-		Word16 exc[],                         /* (i)   : excitation at 12kHz        */

-		Word16 Q_new,                         /* (i)   : scaling performed on exc   */

-		Word16 synth16k[],                    /* (o)   : 16kHz synthesis signal     */

-		Coder_State * st                      /* (i/o) : State structure            */

-		)

-{

-	Word16 fac, tmp, exp;

-	Word16 ener, exp_ener;

-	Word32 L_tmp, i;

-

-	Word16 synth_hi[M + L_SUBFR], synth_lo[M + L_SUBFR];

-	Word16 synth[L_SUBFR];

-	Word16 HF[L_SUBFR16k];                 /* High Frequency vector      */

-	Word16 Ap[M + 1];

-

-	Word16 HF_SP[L_SUBFR16k];              /* High Frequency vector (from original signal) */

-

-	Word16 HP_est_gain, HP_calc_gain, HP_corr_gain;

-	Word16 dist_min, dist;

-	Word16 HP_gain_ind = 0;

-	Word16 gain1, gain2;

-	Word16 weight1, weight2;

-

-	/*------------------------------------------------------------*

-	 * speech synthesis                                           *

-	 * ~~~~~~~~~~~~~~~~                                           *

-	 * - Find synthesis speech corresponding to exc2[].           *

-	 * - Perform fixed deemphasis and hp 50hz filtering.          *

-	 * - Oversampling from 12.8kHz to 16kHz.                      *

-	 *------------------------------------------------------------*/

-	Copy(st->mem_syn_hi, synth_hi, M);

-	Copy(st->mem_syn_lo, synth_lo, M);

-

-#ifdef ASM_OPT                 /* asm optimization branch */

-	Syn_filt_32_asm(Aq, M, exc, Q_new, synth_hi + M, synth_lo + M, L_SUBFR);

-#else

-	Syn_filt_32(Aq, M, exc, Q_new, synth_hi + M, synth_lo + M, L_SUBFR);

-#endif

-

-	Copy(synth_hi + L_SUBFR, st->mem_syn_hi, M);

-	Copy(synth_lo + L_SUBFR, st->mem_syn_lo, M);

-

-#ifdef ASM_OPT                 /* asm optimization branch */

-	Deemph_32_asm(synth_hi + M, synth_lo + M, synth, &(st->mem_deemph));

-#else

-	Deemph_32(synth_hi + M, synth_lo + M, synth, PREEMPH_FAC, L_SUBFR, &(st->mem_deemph));

-#endif

-

-	HP50_12k8(synth, L_SUBFR, st->mem_sig_out);

-

-	/* Original speech signal as reference for high band gain quantisation */

-	for (i = 0; i < L_SUBFR16k; i++)

-	{

-		HF_SP[i] = synth16k[i]; 

-	}

-

-	/*------------------------------------------------------*

-	 * HF noise synthesis                                   *

-	 * ~~~~~~~~~~~~~~~~~~                                   *

-	 * - Generate HF noise between 5.5 and 7.5 kHz.         *

-	 * - Set energy of noise according to synthesis tilt.   *

-	 *     tilt > 0.8 ==> - 14 dB (voiced)                  *

-	 *     tilt   0.5 ==> - 6 dB  (voiced or noise)         *

-	 *     tilt < 0.0 ==>   0 dB  (noise)                   *

-	 *------------------------------------------------------*/

-	/* generate white noise vector */

-	for (i = 0; i < L_SUBFR16k; i++)

-	{

-		HF[i] = Random(&(st->seed2))>>3;

-	}

-	/* energy of excitation */

-#ifdef ASM_OPT                    /* asm optimization branch */

-	Scale_sig_opt(exc, L_SUBFR, -3);

-	Q_new = Q_new - 3;

-	ener = extract_h(Dot_product12_asm(exc, exc, L_SUBFR, &exp_ener));

-#else

-	Scale_sig(exc, L_SUBFR, -3);

-	Q_new = Q_new - 3;

-	ener = extract_h(Dot_product12(exc, exc, L_SUBFR, &exp_ener));

-#endif

-

-	exp_ener = exp_ener - (Q_new + Q_new);

-	/* set energy of white noise to energy of excitation */

-#ifdef ASM_OPT              /* asm optimization branch */

-	tmp = extract_h(Dot_product12_asm(HF, HF, L_SUBFR16k, &exp));

-#else

-	tmp = extract_h(Dot_product12(HF, HF, L_SUBFR16k, &exp));

-#endif

-

-	if(tmp > ener)

-	{

-		tmp = (tmp >> 1);                 /* Be sure tmp < ener */

-		exp = (exp + 1);

-	}

-	L_tmp = L_deposit_h(div_s(tmp, ener)); /* result is normalized */

-	exp = (exp - exp_ener);

-	Isqrt_n(&L_tmp, &exp);

-	L_tmp = L_shl(L_tmp, (exp + 1));       /* L_tmp x 2, L_tmp in Q31 */

-	tmp = extract_h(L_tmp);                /* tmp = 2 x sqrt(ener_exc/ener_hf) */

-

-	for (i = 0; i < L_SUBFR16k; i++)

-	{

-		HF[i] = vo_mult(HF[i], tmp);

-	}

-

-	/* find tilt of synthesis speech (tilt: 1=voiced, -1=unvoiced) */

-	HP400_12k8(synth, L_SUBFR, st->mem_hp400);

-

-	L_tmp = 1L;

-	for (i = 0; i < L_SUBFR; i++)

-		L_tmp += (synth[i] * synth[i])<<1;

-

-	exp = norm_l(L_tmp);

-	ener = extract_h(L_tmp << exp);   /* ener = r[0] */

-

-	L_tmp = 1L;

-	for (i = 1; i < L_SUBFR; i++)

-		L_tmp +=(synth[i] * synth[i - 1])<<1;

-

-	tmp = extract_h(L_tmp << exp);    /* tmp = r[1] */

-

-	if (tmp > 0)

-	{

-		fac = div_s(tmp, ener);

-	} else

-	{

-		fac = 0; 

-	}

-

-	/* modify energy of white noise according to synthesis tilt */

-	gain1 = 32767 - fac;

-	gain2 = vo_mult(gain1, 20480);

-	gain2 = shl(gain2, 1);

-

-	if (st->vad_hist > 0)

-	{

-		weight1 = 0;

-		weight2 = 32767;

-	} else

-	{

-		weight1 = 32767;

-		weight2 = 0;

-	}

-	tmp = vo_mult(weight1, gain1);

-	tmp = add1(tmp, vo_mult(weight2, gain2));

-

-	if (tmp != 0)

-	{

-		tmp = (tmp + 1);

-	}

-	HP_est_gain = tmp;

-

-	if(HP_est_gain < 3277)

-	{

-		HP_est_gain = 3277;                /* 0.1 in Q15 */

-	}

-	/* synthesis of noise: 4.8kHz..5.6kHz --> 6kHz..7kHz */

-	Weight_a(Aq, Ap, 19661, M);            /* fac=0.6 */

-

-#ifdef ASM_OPT                /* asm optimization branch */

-	Syn_filt_asm(Ap, HF, HF, st->mem_syn_hf);

-	/* noise High Pass filtering (1ms of delay) */

-	Filt_6k_7k_asm(HF, L_SUBFR16k, st->mem_hf);

-	/* filtering of the original signal */

-	Filt_6k_7k_asm(HF_SP, L_SUBFR16k, st->mem_hf2);

-

-	/* check the gain difference */

-	Scale_sig_opt(HF_SP, L_SUBFR16k, -1);

-	ener = extract_h(Dot_product12_asm(HF_SP, HF_SP, L_SUBFR16k, &exp_ener));

-	/* set energy of white noise to energy of excitation */

-	tmp = extract_h(Dot_product12_asm(HF, HF, L_SUBFR16k, &exp));

-#else

-	Syn_filt(Ap, HF, HF, L_SUBFR16k, st->mem_syn_hf, 1);

-	/* noise High Pass filtering (1ms of delay) */

-	Filt_6k_7k(HF, L_SUBFR16k, st->mem_hf);

-	/* filtering of the original signal */

-	Filt_6k_7k(HF_SP, L_SUBFR16k, st->mem_hf2);

-	/* check the gain difference */

-	Scale_sig(HF_SP, L_SUBFR16k, -1);

-	ener = extract_h(Dot_product12(HF_SP, HF_SP, L_SUBFR16k, &exp_ener));

-	/* set energy of white noise to energy of excitation */

-	tmp = extract_h(Dot_product12(HF, HF, L_SUBFR16k, &exp));

-#endif

-

-	if (tmp > ener)

-	{

-		tmp = (tmp >> 1);                 /* Be sure tmp < ener */

-		exp = (exp + 1);

-	}

-	L_tmp = L_deposit_h(div_s(tmp, ener)); /* result is normalized */

-	exp = vo_sub(exp, exp_ener);

-	Isqrt_n(&L_tmp, &exp);

-	L_tmp = L_shl(L_tmp, exp);             /* L_tmp, L_tmp in Q31 */

-	HP_calc_gain = extract_h(L_tmp);       /* tmp = sqrt(ener_input/ener_hf) */

-

-	/* st->gain_alpha *= st->dtx_encSt->dtxHangoverCount/7 */

-	L_tmp = (vo_L_mult(st->dtx_encSt->dtxHangoverCount, 4681) << 15);

-	st->gain_alpha = vo_mult(st->gain_alpha, extract_h(L_tmp));

-

-	if(st->dtx_encSt->dtxHangoverCount > 6)

-		st->gain_alpha = 32767;

-	HP_est_gain = HP_est_gain >> 1;     /* From Q15 to Q14 */

-	HP_corr_gain = add1(vo_mult(HP_calc_gain, st->gain_alpha), vo_mult((32767 - st->gain_alpha), HP_est_gain));

-

-	/* Quantise the correction gain */

-	dist_min = 32767;

-	for (i = 0; i < 16; i++)

-	{

-		dist = vo_mult((HP_corr_gain - HP_gain[i]), (HP_corr_gain - HP_gain[i]));

-		if (dist_min > dist)

-		{

-			dist_min = dist;

-			HP_gain_ind = i;

-		}

-	}

-	HP_corr_gain = HP_gain[HP_gain_ind];

-	/* return the quantised gain index when using the highest mode, otherwise zero */

-	return (HP_gain_ind);

-}

-

-/*************************************************

-*

-* Breif: Codec main function 

-*

-**************************************************/

-

-int AMR_Enc_Encode(HAMRENC hCodec)

-{

-	Word32 i;

-	Coder_State *gData = (Coder_State*)hCodec;

-	Word16 *signal;

-	Word16 packed_size = 0;

-	Word16 prms[NB_BITS_MAX];

-	Word16 coding_mode = 0, nb_bits, allow_dtx, mode, reset_flag;

-	mode = gData->mode;

-	coding_mode = gData->mode;

-	nb_bits = nb_of_bits[mode];

-	signal = (Word16 *)gData->inputStream;

-	allow_dtx = gData->allow_dtx;

-

-	/* check for homing frame */

-	reset_flag = encoder_homing_frame_test(signal);

-

-	for (i = 0; i < L_FRAME16k; i++)   /* Delete the 2 LSBs (14-bit input) */

-	{

-		*(signal + i) = (Word16) (*(signal + i) & 0xfffC);

-	}

-

-	coder(&coding_mode, signal, prms, &nb_bits, gData, allow_dtx);

-	packed_size = PackBits(prms, coding_mode, mode, gData);

-	if (reset_flag != 0)

-	{

-		Reset_encoder(gData, 1);

-	}

-	return packed_size;

-}

-

-/***************************************************************************

-*

-*Brief: Codec API function --- Initialize the codec and return a codec handle

-*

-***************************************************************************/

-

-VO_U32 VO_API voAMRWB_Init(VO_HANDLE * phCodec,                   /* o: the audio codec handle */

-						   VO_AUDIO_CODINGTYPE vType,             /* i: Codec Type ID */

-						   VO_CODEC_INIT_USERDATA * pUserData     /* i: init Parameters */

-						   )

-{

-	Coder_State *st;

-	FrameStream *stream;

-#ifdef USE_DEAULT_MEM

-	VO_MEM_OPERATOR voMemoprator;

-#endif

-	VO_MEM_OPERATOR *pMemOP;

-	int interMem = 0;

-

-	if(pUserData == NULL || pUserData->memflag != VO_IMF_USERMEMOPERATOR || pUserData->memData == NULL )

-	{

-#ifdef USE_DEAULT_MEM

-		voMemoprator.Alloc = cmnMemAlloc;

-		voMemoprator.Copy = cmnMemCopy;

-		voMemoprator.Free = cmnMemFree;

-		voMemoprator.Set = cmnMemSet;

-		voMemoprator.Check = cmnMemCheck;

-		interMem = 1;

-		pMemOP = &voMemoprator;

-#else

-		*phCodec = NULL;

-		return VO_ERR_INVALID_ARG;

-#endif

-	}

-	else

-	{

-		pMemOP = (VO_MEM_OPERATOR *)pUserData->memData;

-	} 

-	/*-------------------------------------------------------------------------*

-	 * Memory allocation for coder state.                                      *

-	 *-------------------------------------------------------------------------*/

-	if ((st = (Coder_State *)mem_malloc(pMemOP, sizeof(Coder_State), 32, VO_INDEX_ENC_AMRWB)) == NULL)

-	{

-		return VO_ERR_OUTOF_MEMORY;

-	}

-

-	st->vadSt = NULL;                      

-	st->dtx_encSt = NULL;                  

-	st->sid_update_counter = 3;

-	st->sid_handover_debt = 0;

-	st->prev_ft = TX_SPEECH;

-	st->inputStream = NULL;

-	st->inputSize = 0;

-

-	/* Default setting */

-	st->mode = VOAMRWB_MD2385;                        /* bit rate 23.85kbps */

-	st->frameType = VOAMRWB_RFC3267;                  /* frame type: RFC3267 */

-	st->allow_dtx = 0;                                /* disable DTX mode */

-

-	st->outputStream = NULL;

-	st->outputSize = 0;

-

-	st->stream = (FrameStream *)mem_malloc(pMemOP, sizeof(FrameStream), 32, VO_INDEX_ENC_AMRWB);

-	if(st->stream == NULL)

-		return VO_ERR_OUTOF_MEMORY;

-

-	st->stream->frame_ptr = (unsigned char *)mem_malloc(pMemOP, Frame_Maxsize, 32, VO_INDEX_ENC_AMRWB);

-	if(st->stream->frame_ptr == NULL)

-		return  VO_ERR_OUTOF_MEMORY;

-

-	stream = st->stream;

-	voAWB_InitFrameBuffer(stream);

-

-	wb_vad_init(&(st->vadSt), pMemOP);

-	dtx_enc_init(&(st->dtx_encSt), isf_init, pMemOP);

-

-	Reset_encoder((void *) st, 1);

-

-	if(interMem)

-	{

-		st->voMemoprator.Alloc = cmnMemAlloc;

-		st->voMemoprator.Copy = cmnMemCopy;

-		st->voMemoprator.Free = cmnMemFree;

-		st->voMemoprator.Set = cmnMemSet;

-		st->voMemoprator.Check = cmnMemCheck;

-		pMemOP = &st->voMemoprator;

-	}

-

-	st->pvoMemop = pMemOP;

-

-	*phCodec = (void *) st;

-

-	return VO_ERR_NONE;

-}

-

-/**********************************************************************************

-*

-* Brief: Codec API function: Input PCM data

-*

-***********************************************************************************/

-

-VO_U32 VO_API voAMRWB_SetInputData(

-		VO_HANDLE hCodec,                   /* i/o: The codec handle which was created by Init function */

-		VO_CODECBUFFER * pInput             /*   i: The input buffer parameter  */

-		)

-{

-	Coder_State  *gData;

-	FrameStream  *stream;

-

-	if(NULL == hCodec)

-	{

-		return VO_ERR_INVALID_ARG;

-	}

-

-	gData = (Coder_State *)hCodec;

-	stream = gData->stream;

-

-	if(NULL == pInput || NULL == pInput->Buffer || 0 > pInput->Length)

-	{

-		return VO_ERR_INVALID_ARG;

-	}

-

-	stream->set_ptr    = pInput->Buffer;

-	stream->set_len    = pInput->Length;

-	stream->frame_ptr  = stream->frame_ptr_bk;

-	stream->used_len   = 0;

-

-	return VO_ERR_NONE;

-}

-

-/**************************************************************************************

-*

-* Brief: Codec API function: Get the compression audio data frame by frame

-*

-***************************************************************************************/

-

-VO_U32 VO_API voAMRWB_GetOutputData(

-		VO_HANDLE hCodec,                    /* i: The Codec Handle which was created by Init function*/

-		VO_CODECBUFFER * pOutput,            /* o: The output audio data */

-		VO_AUDIO_OUTPUTINFO * pAudioFormat   /* o: The encoder module filled audio format and used the input size*/

-		)

-{

-	Coder_State* gData = (Coder_State*)hCodec;

-	VO_MEM_OPERATOR  *pMemOP;

-	FrameStream  *stream = (FrameStream *)gData->stream;

-	pMemOP = (VO_MEM_OPERATOR  *)gData->pvoMemop;

-

-	if(stream->framebuffer_len  < Frame_MaxByte)         /* check the work buffer len */

-	{

-		stream->frame_storelen = stream->framebuffer_len;

-		if(stream->frame_storelen)

-		{

-			pMemOP->Copy(VO_INDEX_ENC_AMRWB, stream->frame_ptr_bk , stream->frame_ptr , stream->frame_storelen);

-		}

-		if(stream->set_len > 0)

-		{

-			voAWB_UpdateFrameBuffer(stream, pMemOP);

-		}

-		if(stream->framebuffer_len < Frame_MaxByte)

-		{

-			if(pAudioFormat)

-				pAudioFormat->InputUsed = stream->used_len;

-			return VO_ERR_INPUT_BUFFER_SMALL;

-		}

-	}

-

-	gData->inputStream = stream->frame_ptr;

-	gData->outputStream = (unsigned short*)pOutput->Buffer;

-

-	gData->outputSize = AMR_Enc_Encode(gData);         /* encoder main function */

-

-	pOutput->Length = gData->outputSize;               /* get the output buffer length */

-	stream->frame_ptr += 640;                          /* update the work buffer ptr */

-	stream->framebuffer_len  -= 640;

-

-	if(pAudioFormat)                                   /* return output audio information */

-	{

-		pAudioFormat->Format.Channels = 1;

-		pAudioFormat->Format.SampleRate = 8000;

-		pAudioFormat->Format.SampleBits = 16;	

-		pAudioFormat->InputUsed = stream->used_len;

-	}

-	return VO_ERR_NONE;

-}

-

-/*************************************************************************

-*

-* Brief: Codec API function---set the data by specified parameter ID

-*

-*************************************************************************/

-

-

-VO_U32 VO_API voAMRWB_SetParam(

-		VO_HANDLE hCodec,   /* i/o: The Codec Handle which was created by Init function */

-		VO_S32 uParamID,    /*   i: The param ID */

-		VO_PTR pData        /*   i: The param value depend on the ID */

-		)

-{

-	Coder_State* gData = (Coder_State*)hCodec;

-	FrameStream *stream = (FrameStream *)(gData->stream);

-	int *lValue = (int*)pData;

-

-	switch(uParamID)

-	{

-		/* setting AMR-WB frame type*/

-		case VO_PID_AMRWB_FRAMETYPE:

-			if(*lValue < VOAMRWB_DEFAULT || *lValue > VOAMRWB_RFC3267)

-				return VO_ERR_WRONG_PARAM_ID; 

-			gData->frameType = *lValue;

-			break;

-		/* setting AMR-WB bit rate */

-		case VO_PID_AMRWB_MODE:

-			{

-				if(*lValue < VOAMRWB_MD66 || *lValue > VOAMRWB_MD2385)

-					return VO_ERR_WRONG_PARAM_ID; 

-				gData->mode = *lValue;

-			}

-			break;

-		/* enable or disable DTX mode */

-		case VO_PID_AMRWB_DTX:

-			gData->allow_dtx = (Word16)(*lValue);

-			break;

-

-		case VO_PID_COMMON_HEADDATA:

-			break;

-        /* flush the work buffer */

-		case VO_PID_COMMON_FLUSH:

-			stream->set_ptr = NULL;

-			stream->frame_storelen = 0;

-			stream->framebuffer_len = 0;

-			stream->set_len = 0;

-			break;

-

-		default:

-			return VO_ERR_WRONG_PARAM_ID;

-	}

-	return VO_ERR_NONE;

-}

-

-/**************************************************************************

-*

-*Brief: Codec API function---Get the data by specified parameter ID

-*

-***************************************************************************/

-

-VO_U32 VO_API voAMRWB_GetParam(

-		VO_HANDLE hCodec,      /* i: The Codec Handle which was created by Init function */

-		VO_S32 uParamID,       /* i: The param ID */

-		VO_PTR pData           /* o: The param value depend on the ID */

-		)

-{

-	int    temp;

-	Coder_State* gData = (Coder_State*)hCodec;

-

-	if (gData==NULL) 

-		return VO_ERR_INVALID_ARG;

-	switch(uParamID)

-	{

-		/* output audio format */

-		case VO_PID_AMRWB_FORMAT:

-			{

-				VO_AUDIO_FORMAT* fmt = (VO_AUDIO_FORMAT*)pData;

-				fmt->Channels   = 1;

-				fmt->SampleRate = 16000;

-				fmt->SampleBits = 16;

-				break;

-			}

-        /* output audio channel number */

-		case VO_PID_AMRWB_CHANNELS:

-			temp = 1;

-			pData = (void *)(&temp);

-			break;

-        /* output audio sample rate */

-		case VO_PID_AMRWB_SAMPLERATE:

-			temp = 16000;

-			pData = (void *)(&temp);

-			break;

-		/* output audio frame type */

-		case VO_PID_AMRWB_FRAMETYPE:

-			temp = gData->frameType;

-			pData = (void *)(&temp);

-			break;

-		/* output audio bit rate */

-		case VO_PID_AMRWB_MODE:

-			temp = gData->mode;

-			pData = (void *)(&temp);

-			break;

-		default:

-			return VO_ERR_WRONG_PARAM_ID;

-	}

-

-	return VO_ERR_NONE;

-}

-

-/***********************************************************************************

-*

-* Brief: Codec API function---Release the codec after all encoder operations are done

-*

-*************************************************************************************/

-

-VO_U32 VO_API voAMRWB_Uninit(VO_HANDLE hCodec           /* i/o: Codec handle pointer */

-							 )

-{

-	Coder_State* gData = (Coder_State*)hCodec;

-	VO_MEM_OPERATOR *pMemOP;

-	pMemOP = gData->pvoMemop;

-

-	if(hCodec)

-	{

-		if(gData->stream)

-		{

-			if(gData->stream->frame_ptr_bk)

-			{

-				mem_free(pMemOP, gData->stream->frame_ptr_bk, VO_INDEX_ENC_AMRWB);

-				gData->stream->frame_ptr_bk = NULL;

-			}

-			mem_free(pMemOP, gData->stream, VO_INDEX_ENC_AMRWB);

-			gData->stream = NULL;

-		}

-		wb_vad_exit(&(((Coder_State *) gData)->vadSt), pMemOP);

-		dtx_enc_exit(&(((Coder_State *) gData)->dtx_encSt), pMemOP);

-

-		mem_free(pMemOP, hCodec, VO_INDEX_ENC_AMRWB);

-		hCodec = NULL;

-	}

-

-	return VO_ERR_NONE;

-}

-

-/********************************************************************************

-*

-* Brief: voGetAMRWBEncAPI gets the API handle of the codec

-*

-********************************************************************************/

-

-VO_S32 VO_API voGetAMRWBEncAPI(

-							   VO_AUDIO_CODECAPI * pEncHandle      /* i/o: Codec handle pointer */

-							   )

-{

-	if(NULL == pEncHandle)

-		return VO_ERR_INVALID_ARG;

-	pEncHandle->Init = voAMRWB_Init;

-	pEncHandle->SetInputData = voAMRWB_SetInputData;

-	pEncHandle->GetOutputData = voAMRWB_GetOutputData;

-	pEncHandle->SetParam = voAMRWB_SetParam;

-	pEncHandle->GetParam = voAMRWB_GetParam;

-	pEncHandle->Uninit = voAMRWB_Uninit;

-

-	return VO_ERR_NONE;

-}

-

-#ifdef __cplusplus

-}

-#endif

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*      File: voAMRWBEnc.c                                              *
+*                                                                      *
+*      Description: Performs the main encoder routine                  *
+*                   Fixed-point C simulation of AMR WB ACELP coding    *
+*		    algorithm with 20 msspeech frames for              *
+*		    wideband speech signals.                           *
+*                                                                      *
+************************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "typedef.h"
+#include "basic_op.h"
+#include "oper_32b.h"
+#include "math_op.h"
+#include "cnst.h"
+#include "acelp.h"
+#include "cod_main.h"
+#include "bits.h"
+#include "main.h"
+#include "voAMRWB.h"
+#include "mem_align.h"
+#include "cmnMemory.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* LPC interpolation coef {0.45, 0.8, 0.96, 1.0}; in Q15 */
+static Word16 interpol_frac[NB_SUBFR] = {14746, 26214, 31457, 32767};
+
+/* isp tables for initialization */
+static Word16 isp_init[M] =
+{
+	32138, 30274, 27246, 23170, 18205, 12540, 6393, 0,
+	-6393, -12540, -18205, -23170, -27246, -30274, -32138, 1475
+};
+
+static Word16 isf_init[M] =
+{
+	1024, 2048, 3072, 4096, 5120, 6144, 7168, 8192,
+	9216, 10240, 11264, 12288, 13312, 14336, 15360, 3840
+};
+
+/* High Band encoding */
+static const Word16 HP_gain[16] =
+{
+	3624, 4673, 5597, 6479, 7425, 8378, 9324, 10264,
+	11210, 12206, 13391, 14844, 16770, 19655, 24289, 32728
+};
+
+/* Private function declaration */
+static Word16 synthesis(
+			Word16 Aq[],                          /* A(z)  : quantized Az               */
+			Word16 exc[],                         /* (i)   : excitation at 12kHz        */
+			Word16 Q_new,                         /* (i)   : scaling performed on exc   */
+			Word16 synth16k[],                    /* (o)   : 16kHz synthesis signal     */
+			Coder_State * st                      /* (i/o) : State structure            */
+			);
+
+/* Codec some parameters initialization */
+void Reset_encoder(void *st, Word16 reset_all)
+{
+	Word16 i;
+	Coder_State *cod_state;
+	cod_state = (Coder_State *) st;
+	Set_zero(cod_state->old_exc, PIT_MAX + L_INTERPOL);
+	Set_zero(cod_state->mem_syn, M);
+	Set_zero(cod_state->past_isfq, M);
+	cod_state->mem_w0 = 0;
+	cod_state->tilt_code = 0;
+	cod_state->first_frame = 1;
+	Init_gp_clip(cod_state->gp_clip);
+	cod_state->L_gc_thres = 0;
+	if (reset_all != 0)
+	{
+		/* Static vectors to zero */
+		Set_zero(cod_state->old_speech, L_TOTAL - L_FRAME);
+		Set_zero(cod_state->old_wsp, (PIT_MAX / OPL_DECIM));
+		Set_zero(cod_state->mem_decim2, 3);
+		/* routines initialization */
+		Init_Decim_12k8(cod_state->mem_decim);
+		Init_HP50_12k8(cod_state->mem_sig_in);
+		Init_Levinson(cod_state->mem_levinson);
+		Init_Q_gain2(cod_state->qua_gain);
+		Init_Hp_wsp(cod_state->hp_wsp_mem);
+		/* isp initialization */
+		Copy(isp_init, cod_state->ispold, M);
+		Copy(isp_init, cod_state->ispold_q, M);
+		/* variable initialization */
+		cod_state->mem_preemph = 0;
+		cod_state->mem_wsp = 0;
+		cod_state->Q_old = 15;
+		cod_state->Q_max[0] = 15;
+		cod_state->Q_max[1] = 15;
+		cod_state->old_wsp_max = 0;
+		cod_state->old_wsp_shift = 0;
+		/* pitch ol initialization */
+		cod_state->old_T0_med = 40;
+		cod_state->ol_gain = 0;
+		cod_state->ada_w = 0;
+		cod_state->ol_wght_flg = 0;
+		for (i = 0; i < 5; i++)
+		{
+			cod_state->old_ol_lag[i] = 40;
+		}
+		Set_zero(cod_state->old_hp_wsp, (L_FRAME / 2) / OPL_DECIM + (PIT_MAX / OPL_DECIM));
+		Set_zero(cod_state->mem_syn_hf, M);
+		Set_zero(cod_state->mem_syn_hi, M);
+		Set_zero(cod_state->mem_syn_lo, M);
+		Init_HP50_12k8(cod_state->mem_sig_out);
+		Init_Filt_6k_7k(cod_state->mem_hf);
+		Init_HP400_12k8(cod_state->mem_hp400);
+		Copy(isf_init, cod_state->isfold, M);
+		cod_state->mem_deemph = 0;
+		cod_state->seed2 = 21845;
+		Init_Filt_6k_7k(cod_state->mem_hf2);
+		cod_state->gain_alpha = 32767;
+		cod_state->vad_hist = 0;
+		wb_vad_reset(cod_state->vadSt);
+		dtx_enc_reset(cod_state->dtx_encSt, isf_init);
+	}
+	return;
+}
+
+/*-----------------------------------------------------------------*
+*   Funtion  coder                                                *
+*            ~~~~~                                                *
+*   ->Main coder routine.                                         *
+*                                                                 *
+*-----------------------------------------------------------------*/
+void coder(
+		Word16 * mode,                        /* input :  used mode                             */
+		Word16 speech16k[],                   /* input :  320 new speech samples (at 16 kHz)    */
+		Word16 prms[],                        /* output:  output parameters                     */
+		Word16 * ser_size,                    /* output:  bit rate of the used mode             */
+		void *spe_state,                      /* i/o   :  State structure                       */
+		Word16 allow_dtx                      /* input :  DTX ON/OFF                            */
+	  )
+{
+	/* Coder states */
+	Coder_State *st;
+	/* Speech vector */
+	Word16 old_speech[L_TOTAL];
+	Word16 *new_speech, *speech, *p_window;
+
+	/* Weighted speech vector */
+	Word16 old_wsp[L_FRAME + (PIT_MAX / OPL_DECIM)];
+	Word16 *wsp;
+
+	/* Excitation vector */
+	Word16 old_exc[(L_FRAME + 1) + PIT_MAX + L_INTERPOL];
+	Word16 *exc;
+
+	/* LPC coefficients */
+	Word16 r_h[M + 1], r_l[M + 1];         /* Autocorrelations of windowed speech  */
+	Word16 rc[M];                          /* Reflection coefficients.             */
+	Word16 Ap[M + 1];                      /* A(z) with spectral expansion         */
+	Word16 ispnew[M];                      /* immittance spectral pairs at 4nd sfr */
+	Word16 ispnew_q[M];                    /* quantized ISPs at 4nd subframe       */
+	Word16 isf[M];                         /* ISF (frequency domain) at 4nd sfr    */
+	Word16 *p_A, *p_Aq;                    /* ptr to A(z) for the 4 subframes      */
+	Word16 A[NB_SUBFR * (M + 1)];          /* A(z) unquantized for the 4 subframes */
+	Word16 Aq[NB_SUBFR * (M + 1)];         /* A(z)   quantized for the 4 subframes */
+
+	/* Other vectors */
+	Word16 xn[L_SUBFR];                    /* Target vector for pitch search     */
+	Word16 xn2[L_SUBFR];                   /* Target vector for codebook search  */
+	Word16 dn[L_SUBFR];                    /* Correlation between xn2 and h1     */
+	Word16 cn[L_SUBFR];                    /* Target vector in residual domain   */
+	Word16 h1[L_SUBFR];                    /* Impulse response vector            */
+	Word16 h2[L_SUBFR];                    /* Impulse response vector            */
+	Word16 code[L_SUBFR];                  /* Fixed codebook excitation          */
+	Word16 y1[L_SUBFR];                    /* Filtered adaptive excitation       */
+	Word16 y2[L_SUBFR];                    /* Filtered adaptive excitation       */
+	Word16 error[M + L_SUBFR];             /* error of quantization              */
+	Word16 synth[L_SUBFR];                 /* 12.8kHz synthesis vector           */
+	Word16 exc2[L_FRAME];                  /* excitation vector                  */
+	Word16 buf[L_FRAME];                   /* VAD buffer                         */
+
+	/* Scalars */
+	Word32 i, j, i_subfr, select, pit_flag, clip_gain, vad_flag;
+	Word16 codec_mode;
+	Word16 T_op, T_op2, T0, T0_min, T0_max, T0_frac, index;
+	Word16 gain_pit, gain_code, g_coeff[4], g_coeff2[4];
+	Word16 tmp, gain1, gain2, exp, Q_new, mu, shift, max;
+	Word16 voice_fac;
+	Word16 indice[8];
+	Word32 L_tmp, L_gain_code, L_max, L_tmp1;
+	Word16 code2[L_SUBFR];                         /* Fixed codebook excitation  */
+	Word16 stab_fac, fac, gain_code_lo;
+
+	Word16 corr_gain;
+	Word16 *vo_p0, *vo_p1, *vo_p2, *vo_p3;
+
+	st = (Coder_State *) spe_state;
+
+	*ser_size = nb_of_bits[*mode];
+	codec_mode = *mode;
+
+	/*--------------------------------------------------------------------------*
+	 *          Initialize pointers to speech vector.                           *
+	 *                                                                          *
+	 *                                                                          *
+	 *                    |-------|-------|-------|-------|-------|-------|     *
+	 *                     past sp   sf1     sf2     sf3     sf4    L_NEXT      *
+	 *                    <-------  Total speech buffer (L_TOTAL)   ------>     *
+	 *              old_speech                                                  *
+	 *                    <-------  LPC analysis window (L_WINDOW)  ------>     *
+	 *                    |       <-- present frame (L_FRAME) ---->             *
+	 *                   p_window |       <----- new speech (L_FRAME) ---->     *
+	 *                            |       |                                     *
+	 *                          speech    |                                     *
+	 *                                 new_speech                               *
+	 *--------------------------------------------------------------------------*/
+
+	new_speech = old_speech + L_TOTAL - L_FRAME - L_FILT;         /* New speech     */
+	speech = old_speech + L_TOTAL - L_FRAME - L_NEXT;             /* Present frame  */
+	p_window = old_speech + L_TOTAL - L_WINDOW;
+
+	exc = old_exc + PIT_MAX + L_INTERPOL;
+	wsp = old_wsp + (PIT_MAX / OPL_DECIM);
+
+	/* copy coder memory state into working space */
+	Copy(st->old_speech, old_speech, L_TOTAL - L_FRAME);
+	Copy(st->old_wsp, old_wsp, PIT_MAX / OPL_DECIM);
+	Copy(st->old_exc, old_exc, PIT_MAX + L_INTERPOL);
+
+	/*---------------------------------------------------------------*
+	 * Down sampling signal from 16kHz to 12.8kHz                    *
+	 * -> The signal is extended by L_FILT samples (padded to zero)  *
+	 * to avoid additional delay (L_FILT samples) in the coder.      *
+	 * The last L_FILT samples are approximated after decimation and *
+	 * are used (and windowed) only in autocorrelations.             *
+	 *---------------------------------------------------------------*/
+
+	Decim_12k8(speech16k, L_FRAME16k, new_speech, st->mem_decim);
+
+	/* last L_FILT samples for autocorrelation window */
+	Copy(st->mem_decim, code, 2 * L_FILT16k);
+	Set_zero(error, L_FILT16k);            /* set next sample to zero */
+	Decim_12k8(error, L_FILT16k, new_speech + L_FRAME, code);
+
+	/*---------------------------------------------------------------*
+	 * Perform 50Hz HP filtering of input signal.                    *
+	 *---------------------------------------------------------------*/
+
+	HP50_12k8(new_speech, L_FRAME, st->mem_sig_in);
+
+	/* last L_FILT samples for autocorrelation window */
+	Copy(st->mem_sig_in, code, 6);
+	HP50_12k8(new_speech + L_FRAME, L_FILT, code);
+
+	/*---------------------------------------------------------------*
+	 * Perform fixed preemphasis through 1 - g z^-1                  *
+	 * Scale signal to get maximum of precision in filtering         *
+	 *---------------------------------------------------------------*/
+
+	mu = PREEMPH_FAC >> 1;              /* Q15 --> Q14 */
+
+	/* get max of new preemphased samples (L_FRAME+L_FILT) */
+	L_tmp = new_speech[0] << 15;
+	L_tmp -= (st->mem_preemph * mu)<<1;
+	L_max = L_abs(L_tmp);
+
+	for (i = 1; i < L_FRAME + L_FILT; i++)
+	{
+		L_tmp = new_speech[i] << 15;
+		L_tmp -= (new_speech[i - 1] * mu)<<1;
+		L_tmp = L_abs(L_tmp);
+		if(L_tmp > L_max)
+		{
+			L_max = L_tmp;
+		}
+	}
+
+	/* get scaling factor for new and previous samples */
+	/* limit scaling to Q_MAX to keep dynamic for ringing in low signal */
+	/* limit scaling to Q_MAX also to avoid a[0]<1 in syn_filt_32 */
+	tmp = extract_h(L_max);
+	if (tmp == 0)
+	{
+		shift = Q_MAX;
+	} else
+	{
+		shift = norm_s(tmp) - 1;
+		if (shift < 0)
+		{
+			shift = 0;
+		}
+		if (shift > Q_MAX)
+		{
+			shift = Q_MAX;
+		}
+	}
+	Q_new = shift;
+	if (Q_new > st->Q_max[0])
+	{
+		Q_new = st->Q_max[0];
+	}
+	if (Q_new > st->Q_max[1])
+	{
+		Q_new = st->Q_max[1];
+	}
+	exp = (Q_new - st->Q_old);
+	st->Q_old = Q_new;
+	st->Q_max[1] = st->Q_max[0];
+	st->Q_max[0] = shift;
+
+	/* preemphasis with scaling (L_FRAME+L_FILT) */
+	tmp = new_speech[L_FRAME - 1];
+
+	for (i = L_FRAME + L_FILT - 1; i > 0; i--)
+	{
+		L_tmp = new_speech[i] << 15;
+		L_tmp -= (new_speech[i - 1] * mu)<<1;
+		L_tmp = (L_tmp << Q_new);
+		new_speech[i] = vo_round(L_tmp);
+	}
+
+	L_tmp = new_speech[0] << 15;
+	L_tmp -= (st->mem_preemph * mu)<<1;
+	L_tmp = (L_tmp << Q_new);
+	new_speech[0] = vo_round(L_tmp);
+
+	st->mem_preemph = tmp;
+
+	/* scale previous samples and memory */
+
+	Scale_sig(old_speech, L_TOTAL - L_FRAME - L_FILT, exp);
+	Scale_sig(old_exc, PIT_MAX + L_INTERPOL, exp);
+	Scale_sig(st->mem_syn, M, exp);
+	Scale_sig(st->mem_decim2, 3, exp);
+	Scale_sig(&(st->mem_wsp), 1, exp);
+	Scale_sig(&(st->mem_w0), 1, exp);
+
+	/*------------------------------------------------------------------------*
+	 *  Call VAD                                                              *
+	 *  Preemphesis scale down signal in low frequency and keep dynamic in HF.*
+	 *  Vad work slightly in futur (new_speech = speech + L_NEXT - L_FILT).   *
+	 *------------------------------------------------------------------------*/
+	Copy(new_speech, buf, L_FRAME);
+
+#ifdef ASM_OPT        /* asm optimization branch */
+	Scale_sig_opt(buf, L_FRAME, 1 - Q_new);
+#else
+	Scale_sig(buf, L_FRAME, 1 - Q_new);
+#endif
+
+	vad_flag = wb_vad(st->vadSt, buf);          /* Voice Activity Detection */
+	if (vad_flag == 0)
+	{
+		st->vad_hist = (st->vad_hist + 1);
+	} else
+	{
+		st->vad_hist = 0;
+	}
+
+	/* DTX processing */
+	if (allow_dtx != 0)
+	{
+		/* Note that mode may change here */
+		tx_dtx_handler(st->dtx_encSt, vad_flag, mode);
+		*ser_size = nb_of_bits[*mode];
+	}
+
+	if(*mode != MRDTX)
+	{
+		Parm_serial(vad_flag, 1, &prms);
+	}
+	/*------------------------------------------------------------------------*
+	 *  Perform LPC analysis                                                  *
+	 *  ~~~~~~~~~~~~~~~~~~~~                                                  *
+	 *   - autocorrelation + lag windowing                                    *
+	 *   - Levinson-durbin algorithm to find a[]                              *
+	 *   - convert a[] to isp[]                                               *
+	 *   - convert isp[] to isf[] for quantization                            *
+	 *   - quantize and code the isf[]                                        *
+	 *   - convert isf[] to isp[] for interpolation                           *
+	 *   - find the interpolated ISPs and convert to a[] for the 4 subframes  *
+	 *------------------------------------------------------------------------*/
+
+	/* LP analysis centered at 4nd subframe */
+	Autocorr(p_window, M, r_h, r_l);                        /* Autocorrelations */
+	Lag_window(r_h, r_l);                                   /* Lag windowing    */
+	Levinson(r_h, r_l, A, rc, st->mem_levinson);            /* Levinson Durbin  */
+	Az_isp(A, ispnew, st->ispold);                          /* From A(z) to ISP */
+
+	/* Find the interpolated ISPs and convert to a[] for all subframes */
+	Int_isp(st->ispold, ispnew, interpol_frac, A);
+
+	/* update ispold[] for the next frame */
+	Copy(ispnew, st->ispold, M);
+
+	/* Convert ISPs to frequency domain 0..6400 */
+	Isp_isf(ispnew, isf, M);
+
+	/* check resonance for pitch clipping algorithm */
+	Gp_clip_test_isf(isf, st->gp_clip);
+
+	/*----------------------------------------------------------------------*
+	 *  Perform PITCH_OL analysis                                           *
+	 *  ~~~~~~~~~~~~~~~~~~~~~~~~~                                           *
+	 * - Find the residual res[] for the whole speech frame                 *
+	 * - Find the weighted input speech wsp[] for the whole speech frame    *
+	 * - scale wsp[] to avoid overflow in pitch estimation                  *
+	 * - Find open loop pitch lag for whole speech frame                    *
+	 *----------------------------------------------------------------------*/
+	p_A = A;
+	for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
+	{
+		/* Weighting of LPC coefficients */
+		Weight_a(p_A, Ap, GAMMA1, M);
+
+#ifdef ASM_OPT                    /* asm optimization branch */
+		Residu_opt(Ap, &speech[i_subfr], &wsp[i_subfr], L_SUBFR);
+#else
+		Residu(Ap, &speech[i_subfr], &wsp[i_subfr], L_SUBFR);
+#endif
+
+		p_A += (M + 1);
+	}
+
+	Deemph2(wsp, TILT_FAC, L_FRAME, &(st->mem_wsp));
+
+	/* find maximum value on wsp[] for 12 bits scaling */
+	max = 0;
+	for (i = 0; i < L_FRAME; i++)
+	{
+		tmp = abs_s(wsp[i]);
+		if(tmp > max)
+		{
+			max = tmp;
+		}
+	}
+	tmp = st->old_wsp_max;
+	if(max > tmp)
+	{
+		tmp = max;                         /* tmp = max(wsp_max, old_wsp_max) */
+	}
+	st->old_wsp_max = max;
+
+	shift = norm_s(tmp) - 3;
+	if (shift > 0)
+	{
+		shift = 0;                         /* shift = 0..-3 */
+	}
+	/* decimation of wsp[] to search pitch in LF and to reduce complexity */
+	LP_Decim2(wsp, L_FRAME, st->mem_decim2);
+
+	/* scale wsp[] in 12 bits to avoid overflow */
+#ifdef  ASM_OPT                  /* asm optimization branch */
+	Scale_sig_opt(wsp, L_FRAME / OPL_DECIM, shift);
+#else
+	Scale_sig(wsp, L_FRAME / OPL_DECIM, shift);
+#endif
+	/* scale old_wsp (warning: exp must be Q_new-Q_old) */
+	exp = exp + (shift - st->old_wsp_shift);
+	st->old_wsp_shift = shift;
+
+	Scale_sig(old_wsp, PIT_MAX / OPL_DECIM, exp);
+	Scale_sig(st->old_hp_wsp, PIT_MAX / OPL_DECIM, exp);
+
+	scale_mem_Hp_wsp(st->hp_wsp_mem, exp);
+
+	/* Find open loop pitch lag for whole speech frame */
+
+	if(*ser_size == NBBITS_7k)
+	{
+		/* Find open loop pitch lag for whole speech frame */
+		T_op = Pitch_med_ol(wsp, st, L_FRAME / OPL_DECIM);
+	} else
+	{
+		/* Find open loop pitch lag for first 1/2 frame */
+		T_op = Pitch_med_ol(wsp, st, (L_FRAME/2) / OPL_DECIM);
+	}
+
+	if(st->ol_gain > 19661)       /* 0.6 in Q15 */
+	{
+		st->old_T0_med = Med_olag(T_op, st->old_ol_lag);
+		st->ada_w = 32767;
+	} else
+	{
+		st->ada_w = vo_mult(st->ada_w, 29491);
+	}
+
+	if(st->ada_w < 26214)
+		st->ol_wght_flg = 0;
+	else
+		st->ol_wght_flg = 1;
+
+	wb_vad_tone_detection(st->vadSt, st->ol_gain);
+	T_op *= OPL_DECIM;
+
+	if(*ser_size != NBBITS_7k)
+	{
+		/* Find open loop pitch lag for second 1/2 frame */
+		T_op2 = Pitch_med_ol(wsp + ((L_FRAME / 2) / OPL_DECIM), st, (L_FRAME/2) / OPL_DECIM);
+
+		if(st->ol_gain > 19661)   /* 0.6 in Q15 */
+		{
+			st->old_T0_med = Med_olag(T_op2, st->old_ol_lag);
+			st->ada_w = 32767;
+		} else
+		{
+			st->ada_w = mult(st->ada_w, 29491);
+		}
+
+		if(st->ada_w < 26214)
+			st->ol_wght_flg = 0;
+		else
+			st->ol_wght_flg = 1;
+
+		wb_vad_tone_detection(st->vadSt, st->ol_gain);
+
+		T_op2 *= OPL_DECIM;
+
+	} else
+	{
+		T_op2 = T_op;
+	}
+	/*----------------------------------------------------------------------*
+	 *                              DTX-CNG                                 *
+	 *----------------------------------------------------------------------*/
+	if(*mode == MRDTX)            /* CNG mode */
+	{
+		/* Buffer isf's and energy */
+#ifdef ASM_OPT                   /* asm optimization branch */
+		Residu_opt(&A[3 * (M + 1)], speech, exc, L_FRAME);
+#else
+		Residu(&A[3 * (M + 1)], speech, exc, L_FRAME);
+#endif
+
+		for (i = 0; i < L_FRAME; i++)
+		{
+			exc2[i] = shr(exc[i], Q_new);
+		}
+
+		L_tmp = 0;
+		for (i = 0; i < L_FRAME; i++)
+			L_tmp += (exc2[i] * exc2[i])<<1;
+
+		L_tmp >>= 1;
+
+		dtx_buffer(st->dtx_encSt, isf, L_tmp, codec_mode);
+
+		/* Quantize and code the ISFs */
+		dtx_enc(st->dtx_encSt, isf, exc2, &prms);
+
+		/* Convert ISFs to the cosine domain */
+		Isf_isp(isf, ispnew_q, M);
+		Isp_Az(ispnew_q, Aq, M, 0);
+
+		for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
+		{
+			corr_gain = synthesis(Aq, &exc2[i_subfr], 0, &speech16k[i_subfr * 5 / 4], st);
+		}
+		Copy(isf, st->isfold, M);
+
+		/* reset speech coder memories */
+		Reset_encoder(st, 0);
+
+		/*--------------------------------------------------*
+		 * Update signal for next frame.                    *
+		 * -> save past of speech[] and wsp[].              *
+		 *--------------------------------------------------*/
+
+		Copy(&old_speech[L_FRAME], st->old_speech, L_TOTAL - L_FRAME);
+		Copy(&old_wsp[L_FRAME / OPL_DECIM], st->old_wsp, PIT_MAX / OPL_DECIM);
+
+		return;
+	}
+	/*----------------------------------------------------------------------*
+	 *                               ACELP                                  *
+	 *----------------------------------------------------------------------*/
+
+	/* Quantize and code the ISFs */
+
+	if (*ser_size <= NBBITS_7k)
+	{
+		Qpisf_2s_36b(isf, isf, st->past_isfq, indice, 4);
+
+		Parm_serial(indice[0], 8, &prms);
+		Parm_serial(indice[1], 8, &prms);
+		Parm_serial(indice[2], 7, &prms);
+		Parm_serial(indice[3], 7, &prms);
+		Parm_serial(indice[4], 6, &prms);
+	} else
+	{
+		Qpisf_2s_46b(isf, isf, st->past_isfq, indice, 4);
+
+		Parm_serial(indice[0], 8, &prms);
+		Parm_serial(indice[1], 8, &prms);
+		Parm_serial(indice[2], 6, &prms);
+		Parm_serial(indice[3], 7, &prms);
+		Parm_serial(indice[4], 7, &prms);
+		Parm_serial(indice[5], 5, &prms);
+		Parm_serial(indice[6], 5, &prms);
+	}
+
+	/* Check stability on isf : distance between old isf and current isf */
+
+	L_tmp = 0;
+	for (i = 0; i < M - 1; i++)
+	{
+		tmp = vo_sub(isf[i], st->isfold[i]);
+		L_tmp += (tmp * tmp)<<1;
+	}
+
+	tmp = extract_h(L_shl2(L_tmp, 8));
+
+	tmp = vo_mult(tmp, 26214);                /* tmp = L_tmp*0.8/256 */
+	tmp = vo_sub(20480, tmp);                 /* 1.25 - tmp (in Q14) */
+
+	stab_fac = shl(tmp, 1);
+
+	if (stab_fac < 0)
+	{
+		stab_fac = 0;
+	}
+	Copy(isf, st->isfold, M);
+
+	/* Convert ISFs to the cosine domain */
+	Isf_isp(isf, ispnew_q, M);
+
+	if (st->first_frame != 0)
+	{
+		st->first_frame = 0;
+		Copy(ispnew_q, st->ispold_q, M);
+	}
+	/* Find the interpolated ISPs and convert to a[] for all subframes */
+
+	Int_isp(st->ispold_q, ispnew_q, interpol_frac, Aq);
+
+	/* update ispold[] for the next frame */
+	Copy(ispnew_q, st->ispold_q, M);
+
+	p_Aq = Aq;
+	for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
+	{
+#ifdef ASM_OPT               /* asm optimization branch */
+		Residu_opt(p_Aq, &speech[i_subfr], &exc[i_subfr], L_SUBFR);
+#else
+		Residu(p_Aq, &speech[i_subfr], &exc[i_subfr], L_SUBFR);
+#endif
+		p_Aq += (M + 1);
+	}
+
+	/* Buffer isf's and energy for dtx on non-speech frame */
+	if (vad_flag == 0)
+	{
+		for (i = 0; i < L_FRAME; i++)
+		{
+			exc2[i] = exc[i] >> Q_new;
+		}
+		L_tmp = 0;
+		for (i = 0; i < L_FRAME; i++)
+			L_tmp += (exc2[i] * exc2[i])<<1;
+		L_tmp >>= 1;
+
+		dtx_buffer(st->dtx_encSt, isf, L_tmp, codec_mode);
+	}
+	/* range for closed loop pitch search in 1st subframe */
+
+	T0_min = T_op - 8;
+	if (T0_min < PIT_MIN)
+	{
+		T0_min = PIT_MIN;
+	}
+	T0_max = (T0_min + 15);
+
+	if(T0_max > PIT_MAX)
+	{
+		T0_max = PIT_MAX;
+		T0_min = T0_max - 15;
+	}
+	/*------------------------------------------------------------------------*
+	 *          Loop for every subframe in the analysis frame                 *
+	 *------------------------------------------------------------------------*
+	 *  To find the pitch and innovation parameters. The subframe size is     *
+	 *  L_SUBFR and the loop is repeated L_FRAME/L_SUBFR times.               *
+	 *     - compute the target signal for pitch search                       *
+	 *     - compute impulse response of weighted synthesis filter (h1[])     *
+	 *     - find the closed-loop pitch parameters                            *
+	 *     - encode the pitch dealy                                           *
+	 *     - find 2 lt prediction (with / without LP filter for lt pred)      *
+	 *     - find 2 pitch gains and choose the best lt prediction.            *
+	 *     - find target vector for codebook search                           *
+	 *     - update the impulse response h1[] for codebook search             *
+	 *     - correlation between target vector and impulse response           *
+	 *     - codebook search and encoding                                     *
+	 *     - VQ of pitch and codebook gains                                   *
+	 *     - find voicing factor and tilt of code for next subframe.          *
+	 *     - update states of weighting filter                                *
+	 *     - find excitation and synthesis speech                             *
+	 *------------------------------------------------------------------------*/
+	p_A = A;
+	p_Aq = Aq;
+	for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
+	{
+		pit_flag = i_subfr;
+		if ((i_subfr == 2 * L_SUBFR) && (*ser_size > NBBITS_7k))
+		{
+			pit_flag = 0;
+			/* range for closed loop pitch search in 3rd subframe */
+			T0_min = (T_op2 - 8);
+
+			if (T0_min < PIT_MIN)
+			{
+				T0_min = PIT_MIN;
+			}
+			T0_max = (T0_min + 15);
+			if (T0_max > PIT_MAX)
+			{
+				T0_max = PIT_MAX;
+				T0_min = (T0_max - 15);
+			}
+		}
+		/*-----------------------------------------------------------------------*
+		 *                                                                       *
+		 *        Find the target vector for pitch search:                       *
+		 *        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                        *
+		 *                                                                       *
+		 *             |------|  res[n]                                          *
+		 * speech[n]---| A(z) |--------                                          *
+		 *             |------|       |   |--------| error[n]  |------|          *
+		 *                   zero -- (-)--| 1/A(z) |-----------| W(z) |-- target *
+		 *                   exc          |--------|           |------|          *
+		 *                                                                       *
+		 * Instead of subtracting the zero-input response of filters from        *
+		 * the weighted input speech, the above configuration is used to         *
+		 * compute the target vector.                                            *
+		 *                                                                       *
+		 *-----------------------------------------------------------------------*/
+
+		for (i = 0; i < M; i++)
+		{
+			error[i] = vo_sub(speech[i + i_subfr - M], st->mem_syn[i]);
+		}
+
+#ifdef ASM_OPT              /* asm optimization branch */
+		Residu_opt(p_Aq, &speech[i_subfr], &exc[i_subfr], L_SUBFR);
+#else
+		Residu(p_Aq, &speech[i_subfr], &exc[i_subfr], L_SUBFR);
+#endif
+		Syn_filt(p_Aq, &exc[i_subfr], error + M, L_SUBFR, error, 0);
+		Weight_a(p_A, Ap, GAMMA1, M);
+
+#ifdef ASM_OPT             /* asm optimization branch */
+		Residu_opt(Ap, error + M, xn, L_SUBFR);
+#else
+		Residu(Ap, error + M, xn, L_SUBFR);
+#endif
+		Deemph2(xn, TILT_FAC, L_SUBFR, &(st->mem_w0));
+
+		/*----------------------------------------------------------------------*
+		 * Find approx. target in residual domain "cn[]" for inovation search.  *
+		 *----------------------------------------------------------------------*/
+		/* first half: xn[] --> cn[] */
+		Set_zero(code, M);
+		Copy(xn, code + M, L_SUBFR / 2);
+		tmp = 0;
+		Preemph2(code + M, TILT_FAC, L_SUBFR / 2, &tmp);
+		Weight_a(p_A, Ap, GAMMA1, M);
+		Syn_filt(Ap,code + M, code + M, L_SUBFR / 2, code, 0);
+
+#ifdef ASM_OPT                /* asm optimization branch */
+		Residu_opt(p_Aq,code + M, cn, L_SUBFR / 2);
+#else
+		Residu(p_Aq,code + M, cn, L_SUBFR / 2);
+#endif
+
+		/* second half: res[] --> cn[] (approximated and faster) */
+		Copy(&exc[i_subfr + (L_SUBFR / 2)], cn + (L_SUBFR / 2), L_SUBFR / 2);
+
+		/*---------------------------------------------------------------*
+		 * Compute impulse response, h1[], of weighted synthesis filter  *
+		 *---------------------------------------------------------------*/
+
+		Set_zero(error, M + L_SUBFR);
+		Weight_a(p_A, error + M, GAMMA1, M);
+
+		vo_p0 = error+M;
+		vo_p3 = h1;
+		for (i = 0; i < L_SUBFR; i++)
+		{
+			L_tmp = *vo_p0 << 14;        /* x4 (Q12 to Q14) */
+			vo_p1 = p_Aq + 1;
+			vo_p2 = vo_p0-1;
+			for (j = 1; j <= M/4; j++)
+			{
+				L_tmp -= *vo_p1++ * *vo_p2--;
+				L_tmp -= *vo_p1++ * *vo_p2--;
+				L_tmp -= *vo_p1++ * *vo_p2--;
+				L_tmp -= *vo_p1++ * *vo_p2--;
+			}
+			*vo_p3++ = *vo_p0++ = vo_round((L_tmp <<4));
+		}
+		/* deemph without division by 2 -> Q14 to Q15 */
+		tmp = 0;
+		Deemph2(h1, TILT_FAC, L_SUBFR, &tmp);   /* h1 in Q14 */
+
+		/* h2 in Q12 for codebook search */
+		Copy(h1, h2, L_SUBFR);
+
+		/*---------------------------------------------------------------*
+		 * scale xn[] and h1[] to avoid overflow in dot_product12()      *
+		 *---------------------------------------------------------------*/
+#ifdef  ASM_OPT                  /* asm optimization branch */
+		Scale_sig_opt(h2, L_SUBFR, -2);
+		Scale_sig_opt(xn, L_SUBFR, shift);     /* scaling of xn[] to limit dynamic at 12 bits */
+		Scale_sig_opt(h1, L_SUBFR, 1 + shift);  /* set h1[] in Q15 with scaling for convolution */
+#else
+		Scale_sig(h2, L_SUBFR, -2);
+		Scale_sig(xn, L_SUBFR, shift);     /* scaling of xn[] to limit dynamic at 12 bits */
+		Scale_sig(h1, L_SUBFR, 1 + shift);  /* set h1[] in Q15 with scaling for convolution */
+#endif
+		/*----------------------------------------------------------------------*
+		 *                 Closed-loop fractional pitch search                  *
+		 *----------------------------------------------------------------------*/
+		/* find closed loop fractional pitch  lag */
+		if(*ser_size <= NBBITS_9k)
+		{
+			T0 = Pitch_fr4(&exc[i_subfr], xn, h1, T0_min, T0_max, &T0_frac,
+					pit_flag, PIT_MIN, PIT_FR1_8b, L_SUBFR);
+
+			/* encode pitch lag */
+			if (pit_flag == 0)             /* if 1st/3rd subframe */
+			{
+				/*--------------------------------------------------------------*
+				 * The pitch range for the 1st/3rd subframe is encoded with     *
+				 * 8 bits and is divided as follows:                            *
+				 *   PIT_MIN to PIT_FR1-1  resolution 1/2 (frac = 0 or 2)       *
+				 *   PIT_FR1 to PIT_MAX    resolution 1   (frac = 0)            *
+				 *--------------------------------------------------------------*/
+				if (T0 < PIT_FR1_8b)
+				{
+					index = ((T0 << 1) + (T0_frac >> 1) - (PIT_MIN<<1));
+				} else
+				{
+					index = ((T0 - PIT_FR1_8b) + ((PIT_FR1_8b - PIT_MIN)*2));
+				}
+
+				Parm_serial(index, 8, &prms);
+
+				/* find T0_min and T0_max for subframe 2 and 4 */
+				T0_min = (T0 - 8);
+				if (T0_min < PIT_MIN)
+				{
+					T0_min = PIT_MIN;
+				}
+				T0_max = T0_min + 15;
+				if (T0_max > PIT_MAX)
+				{
+					T0_max = PIT_MAX;
+					T0_min = (T0_max - 15);
+				}
+			} else
+			{                              /* if subframe 2 or 4 */
+				/*--------------------------------------------------------------*
+				 * The pitch range for subframe 2 or 4 is encoded with 5 bits:  *
+				 *   T0_min  to T0_max     resolution 1/2 (frac = 0 or 2)       *
+				 *--------------------------------------------------------------*/
+				i = (T0 - T0_min);
+				index = (i << 1) + (T0_frac >> 1);
+
+				Parm_serial(index, 5, &prms);
+			}
+		} else
+		{
+			T0 = Pitch_fr4(&exc[i_subfr], xn, h1, T0_min, T0_max, &T0_frac,
+					pit_flag, PIT_FR2, PIT_FR1_9b, L_SUBFR);
+
+			/* encode pitch lag */
+			if (pit_flag == 0)             /* if 1st/3rd subframe */
+			{
+				/*--------------------------------------------------------------*
+				 * The pitch range for the 1st/3rd subframe is encoded with     *
+				 * 9 bits and is divided as follows:                            *
+				 *   PIT_MIN to PIT_FR2-1  resolution 1/4 (frac = 0,1,2 or 3)   *
+				 *   PIT_FR2 to PIT_FR1-1  resolution 1/2 (frac = 0 or 1)       *
+				 *   PIT_FR1 to PIT_MAX    resolution 1   (frac = 0)            *
+				 *--------------------------------------------------------------*/
+
+				if (T0 < PIT_FR2)
+				{
+					index = ((T0 << 2) + T0_frac) - (PIT_MIN << 2);
+				} else if(T0 < PIT_FR1_9b)
+				{
+					index = ((((T0 << 1) + (T0_frac >> 1)) - (PIT_FR2<<1)) + ((PIT_FR2 - PIT_MIN)<<2));
+				} else
+				{
+					index = (((T0 - PIT_FR1_9b) + ((PIT_FR2 - PIT_MIN)<<2)) + ((PIT_FR1_9b - PIT_FR2)<<1));
+				}
+
+				Parm_serial(index, 9, &prms);
+
+				/* find T0_min and T0_max for subframe 2 and 4 */
+
+				T0_min = (T0 - 8);
+				if (T0_min < PIT_MIN)
+				{
+					T0_min = PIT_MIN;
+				}
+				T0_max = T0_min + 15;
+
+				if (T0_max > PIT_MAX)
+				{
+					T0_max = PIT_MAX;
+					T0_min = (T0_max - 15);
+				}
+			} else
+			{                              /* if subframe 2 or 4 */
+				/*--------------------------------------------------------------*
+				 * The pitch range for subframe 2 or 4 is encoded with 6 bits:  *
+				 *   T0_min  to T0_max     resolution 1/4 (frac = 0,1,2 or 3)   *
+				 *--------------------------------------------------------------*/
+				i = (T0 - T0_min);
+				index = (i << 2) + T0_frac;
+				Parm_serial(index, 6, &prms);
+			}
+		}
+
+		/*-----------------------------------------------------------------*
+		 * Gain clipping test to avoid unstable synthesis on frame erasure *
+		 *-----------------------------------------------------------------*/
+
+		clip_gain = 0;
+		if((st->gp_clip[0] < 154) && (st->gp_clip[1] > 14746))
+			clip_gain = 1;
+
+		/*-----------------------------------------------------------------*
+		 * - find unity gain pitch excitation (adaptive codebook entry)    *
+		 *   with fractional interpolation.                                *
+		 * - find filtered pitch exc. y1[]=exc[] convolved with h1[])      *
+		 * - compute pitch gain1                                           *
+		 *-----------------------------------------------------------------*/
+		/* find pitch exitation */
+#ifdef ASM_OPT                  /* asm optimization branch */
+		pred_lt4_asm(&exc[i_subfr], T0, T0_frac, L_SUBFR + 1);
+#else
+		Pred_lt4(&exc[i_subfr], T0, T0_frac, L_SUBFR + 1);
+#endif
+		if (*ser_size > NBBITS_9k)
+		{
+#ifdef ASM_OPT                   /* asm optimization branch */
+			Convolve_asm(&exc[i_subfr], h1, y1, L_SUBFR);
+#else
+			Convolve(&exc[i_subfr], h1, y1, L_SUBFR);
+#endif
+			gain1 = G_pitch(xn, y1, g_coeff, L_SUBFR);
+			/* clip gain if necessary to avoid problem at decoder */
+			if ((clip_gain != 0) && (gain1 > GP_CLIP))
+			{
+				gain1 = GP_CLIP;
+			}
+			/* find energy of new target xn2[] */
+			Updt_tar(xn, dn, y1, gain1, L_SUBFR);       /* dn used temporary */
+		} else
+		{
+			gain1 = 0;
+		}
+		/*-----------------------------------------------------------------*
+		 * - find pitch excitation filtered by 1st order LP filter.        *
+		 * - find filtered pitch exc. y2[]=exc[] convolved with h1[])      *
+		 * - compute pitch gain2                                           *
+		 *-----------------------------------------------------------------*/
+		/* find pitch excitation with lp filter */
+		vo_p0 = exc + i_subfr-1;
+		vo_p1 = code;
+		/* find pitch excitation with lp filter */
+		for (i = 0; i < L_SUBFR/2; i++)
+		{
+			L_tmp = 5898 * *vo_p0++;
+			L_tmp1 = 5898 * *vo_p0;
+			L_tmp += 20972 * *vo_p0++;
+			L_tmp1 += 20972 * *vo_p0++;
+			L_tmp1 += 5898 * *vo_p0--;
+			L_tmp += 5898 * *vo_p0;
+			*vo_p1++ = (L_tmp + 0x4000)>>15;
+			*vo_p1++ = (L_tmp1 + 0x4000)>>15;
+		}
+
+#ifdef ASM_OPT                 /* asm optimization branch */
+		Convolve_asm(code, h1, y2, L_SUBFR);
+#else
+		Convolve(code, h1, y2, L_SUBFR);
+#endif
+
+		gain2 = G_pitch(xn, y2, g_coeff2, L_SUBFR);
+
+		/* clip gain if necessary to avoid problem at decoder */
+		if ((clip_gain != 0) && (gain2 > GP_CLIP))
+		{
+			gain2 = GP_CLIP;
+		}
+		/* find energy of new target xn2[] */
+		Updt_tar(xn, xn2, y2, gain2, L_SUBFR);
+		/*-----------------------------------------------------------------*
+		 * use the best prediction (minimise quadratic error).             *
+		 *-----------------------------------------------------------------*/
+		select = 0;
+		if(*ser_size > NBBITS_9k)
+		{
+			L_tmp = 0L;
+			vo_p0 = dn;
+			vo_p1 = xn2;
+			for (i = 0; i < L_SUBFR/2; i++)
+			{
+				L_tmp += *vo_p0 * *vo_p0;
+				vo_p0++;
+				L_tmp -= *vo_p1 * *vo_p1;
+				vo_p1++;
+				L_tmp += *vo_p0 * *vo_p0;
+				vo_p0++;
+				L_tmp -= *vo_p1 * *vo_p1;
+				vo_p1++;
+			}
+
+			if (L_tmp <= 0)
+			{
+				select = 1;
+			}
+			Parm_serial(select, 1, &prms);
+		}
+		if (select == 0)
+		{
+			/* use the lp filter for pitch excitation prediction */
+			gain_pit = gain2;
+			Copy(code, &exc[i_subfr], L_SUBFR);
+			Copy(y2, y1, L_SUBFR);
+			Copy(g_coeff2, g_coeff, 4);
+		} else
+		{
+			/* no filter used for pitch excitation prediction */
+			gain_pit = gain1;
+			Copy(dn, xn2, L_SUBFR);        /* target vector for codebook search */
+		}
+		/*-----------------------------------------------------------------*
+		 * - update cn[] for codebook search                               *
+		 *-----------------------------------------------------------------*/
+		Updt_tar(cn, cn, &exc[i_subfr], gain_pit, L_SUBFR);
+
+#ifdef  ASM_OPT                           /* asm optimization branch */
+		Scale_sig_opt(cn, L_SUBFR, shift);     /* scaling of cn[] to limit dynamic at 12 bits */
+#else
+		Scale_sig(cn, L_SUBFR, shift);     /* scaling of cn[] to limit dynamic at 12 bits */
+#endif
+		/*-----------------------------------------------------------------*
+		 * - include fixed-gain pitch contribution into impulse resp. h1[] *
+		 *-----------------------------------------------------------------*/
+		tmp = 0;
+		Preemph(h2, st->tilt_code, L_SUBFR, &tmp);
+
+		if (T0_frac > 2)
+			T0 = (T0 + 1);
+		Pit_shrp(h2, T0, PIT_SHARP, L_SUBFR);
+		/*-----------------------------------------------------------------*
+		 * - Correlation between target xn2[] and impulse response h1[]    *
+		 * - Innovative codebook search                                    *
+		 *-----------------------------------------------------------------*/
+		cor_h_x(h2, xn2, dn);
+		if (*ser_size <= NBBITS_7k)
+		{
+			ACELP_2t64_fx(dn, cn, h2, code, y2, indice);
+
+			Parm_serial(indice[0], 12, &prms);
+		} else if(*ser_size <= NBBITS_9k)
+		{
+			ACELP_4t64_fx(dn, cn, h2, code, y2, 20, *ser_size, indice);
+
+			Parm_serial(indice[0], 5, &prms);
+			Parm_serial(indice[1], 5, &prms);
+			Parm_serial(indice[2], 5, &prms);
+			Parm_serial(indice[3], 5, &prms);
+		} else if(*ser_size <= NBBITS_12k)
+		{
+			ACELP_4t64_fx(dn, cn, h2, code, y2, 36, *ser_size, indice);
+
+			Parm_serial(indice[0], 9, &prms);
+			Parm_serial(indice[1], 9, &prms);
+			Parm_serial(indice[2], 9, &prms);
+			Parm_serial(indice[3], 9, &prms);
+		} else if(*ser_size <= NBBITS_14k)
+		{
+			ACELP_4t64_fx(dn, cn, h2, code, y2, 44, *ser_size, indice);
+
+			Parm_serial(indice[0], 13, &prms);
+			Parm_serial(indice[1], 13, &prms);
+			Parm_serial(indice[2], 9, &prms);
+			Parm_serial(indice[3], 9, &prms);
+		} else if(*ser_size <= NBBITS_16k)
+		{
+			ACELP_4t64_fx(dn, cn, h2, code, y2, 52, *ser_size, indice);
+
+			Parm_serial(indice[0], 13, &prms);
+			Parm_serial(indice[1], 13, &prms);
+			Parm_serial(indice[2], 13, &prms);
+			Parm_serial(indice[3], 13, &prms);
+		} else if(*ser_size <= NBBITS_18k)
+		{
+			ACELP_4t64_fx(dn, cn, h2, code, y2, 64, *ser_size, indice);
+
+			Parm_serial(indice[0], 2, &prms);
+			Parm_serial(indice[1], 2, &prms);
+			Parm_serial(indice[2], 2, &prms);
+			Parm_serial(indice[3], 2, &prms);
+			Parm_serial(indice[4], 14, &prms);
+			Parm_serial(indice[5], 14, &prms);
+			Parm_serial(indice[6], 14, &prms);
+			Parm_serial(indice[7], 14, &prms);
+		} else if(*ser_size <= NBBITS_20k)
+		{
+			ACELP_4t64_fx(dn, cn, h2, code, y2, 72, *ser_size, indice);
+
+			Parm_serial(indice[0], 10, &prms);
+			Parm_serial(indice[1], 10, &prms);
+			Parm_serial(indice[2], 2, &prms);
+			Parm_serial(indice[3], 2, &prms);
+			Parm_serial(indice[4], 10, &prms);
+			Parm_serial(indice[5], 10, &prms);
+			Parm_serial(indice[6], 14, &prms);
+			Parm_serial(indice[7], 14, &prms);
+		} else
+		{
+			ACELP_4t64_fx(dn, cn, h2, code, y2, 88, *ser_size, indice);
+
+			Parm_serial(indice[0], 11, &prms);
+			Parm_serial(indice[1], 11, &prms);
+			Parm_serial(indice[2], 11, &prms);
+			Parm_serial(indice[3], 11, &prms);
+			Parm_serial(indice[4], 11, &prms);
+			Parm_serial(indice[5], 11, &prms);
+			Parm_serial(indice[6], 11, &prms);
+			Parm_serial(indice[7], 11, &prms);
+		}
+		/*-------------------------------------------------------*
+		 * - Add the fixed-gain pitch contribution to code[].    *
+		 *-------------------------------------------------------*/
+		tmp = 0;
+		Preemph(code, st->tilt_code, L_SUBFR, &tmp);
+		Pit_shrp(code, T0, PIT_SHARP, L_SUBFR);
+		/*----------------------------------------------------------*
+		 *  - Compute the fixed codebook gain                       *
+		 *  - quantize fixed codebook gain                          *
+		 *----------------------------------------------------------*/
+		if(*ser_size <= NBBITS_9k)
+		{
+			index = Q_gain2(xn, y1, Q_new + shift, y2, code, g_coeff, L_SUBFR, 6,
+					&gain_pit, &L_gain_code, clip_gain, st->qua_gain);
+			Parm_serial(index, 6, &prms);
+		} else
+		{
+			index = Q_gain2(xn, y1, Q_new + shift, y2, code, g_coeff, L_SUBFR, 7,
+					&gain_pit, &L_gain_code, clip_gain, st->qua_gain);
+			Parm_serial(index, 7, &prms);
+		}
+		/* test quantized gain of pitch for pitch clipping algorithm */
+		Gp_clip_test_gain_pit(gain_pit, st->gp_clip);
+
+		L_tmp = L_shl(L_gain_code, Q_new);
+		gain_code = extract_h(L_add(L_tmp, 0x8000));
+
+		/*----------------------------------------------------------*
+		 * Update parameters for the next subframe.                 *
+		 * - tilt of code: 0.0 (unvoiced) to 0.5 (voiced)           *
+		 *----------------------------------------------------------*/
+		/* find voice factor in Q15 (1=voiced, -1=unvoiced) */
+		Copy(&exc[i_subfr], exc2, L_SUBFR);
+
+#ifdef ASM_OPT                           /* asm optimization branch */
+		Scale_sig_opt(exc2, L_SUBFR, shift);
+#else
+		Scale_sig(exc2, L_SUBFR, shift);
+#endif
+		voice_fac = voice_factor(exc2, shift, gain_pit, code, gain_code, L_SUBFR);
+		/* tilt of code for next subframe: 0.5=voiced, 0=unvoiced */
+		st->tilt_code = ((voice_fac >> 2) + 8192);
+		/*------------------------------------------------------*
+		 * - Update filter's memory "mem_w0" for finding the    *
+		 *   target vector in the next subframe.                *
+		 * - Find the total excitation                          *
+		 * - Find synthesis speech to update mem_syn[].         *
+		 *------------------------------------------------------*/
+
+		/* y2 in Q9, gain_pit in Q14 */
+		L_tmp = (gain_code * y2[L_SUBFR - 1])<<1;
+		L_tmp = L_shl(L_tmp, (5 + shift));
+		L_tmp = L_negate(L_tmp);
+		L_tmp += (xn[L_SUBFR - 1] * 16384)<<1;
+		L_tmp -= (y1[L_SUBFR - 1] * gain_pit)<<1;
+		L_tmp = L_shl(L_tmp, (1 - shift));
+		st->mem_w0 = extract_h(L_add(L_tmp, 0x8000));
+
+		if (*ser_size >= NBBITS_24k)
+			Copy(&exc[i_subfr], exc2, L_SUBFR);
+
+		for (i = 0; i < L_SUBFR; i++)
+		{
+			/* code in Q9, gain_pit in Q14 */
+			L_tmp = (gain_code * code[i])<<1;
+			L_tmp = (L_tmp << 5);
+			L_tmp += (exc[i + i_subfr] * gain_pit)<<1;
+			L_tmp = L_shl2(L_tmp, 1);
+			exc[i + i_subfr] = extract_h(L_add(L_tmp, 0x8000));
+		}
+
+		Syn_filt(p_Aq,&exc[i_subfr], synth, L_SUBFR, st->mem_syn, 1);
+
+		if(*ser_size >= NBBITS_24k)
+		{
+			/*------------------------------------------------------------*
+			 * phase dispersion to enhance noise in low bit rate          *
+			 *------------------------------------------------------------*/
+			/* L_gain_code in Q16 */
+			VO_L_Extract(L_gain_code, &gain_code, &gain_code_lo);
+
+			/*------------------------------------------------------------*
+			 * noise enhancer                                             *
+			 * ~~~~~~~~~~~~~~                                             *
+			 * - Enhance excitation on noise. (modify gain of code)       *
+			 *   If signal is noisy and LPC filter is stable, move gain   *
+			 *   of code 1.5 dB toward gain of code threshold.            *
+			 *   This decrease by 3 dB noise energy variation.            *
+			 *------------------------------------------------------------*/
+			tmp = (16384 - (voice_fac >> 1));        /* 1=unvoiced, 0=voiced */
+			fac = vo_mult(stab_fac, tmp);
+			L_tmp = L_gain_code;
+			if(L_tmp < st->L_gc_thres)
+			{
+				L_tmp = vo_L_add(L_tmp, Mpy_32_16(gain_code, gain_code_lo, 6226));
+				if(L_tmp > st->L_gc_thres)
+				{
+					L_tmp = st->L_gc_thres;
+				}
+			} else
+			{
+				L_tmp = Mpy_32_16(gain_code, gain_code_lo, 27536);
+				if(L_tmp < st->L_gc_thres)
+				{
+					L_tmp = st->L_gc_thres;
+				}
+			}
+			st->L_gc_thres = L_tmp;
+
+			L_gain_code = Mpy_32_16(gain_code, gain_code_lo, (32767 - fac));
+			VO_L_Extract(L_tmp, &gain_code, &gain_code_lo);
+			L_gain_code = vo_L_add(L_gain_code, Mpy_32_16(gain_code, gain_code_lo, fac));
+
+			/*------------------------------------------------------------*
+			 * pitch enhancer                                             *
+			 * ~~~~~~~~~~~~~~                                             *
+			 * - Enhance excitation on voice. (HP filtering of code)      *
+			 *   On voiced signal, filtering of code by a smooth fir HP   *
+			 *   filter to decrease energy of code in low frequency.      *
+			 *------------------------------------------------------------*/
+
+			tmp = ((voice_fac >> 3) + 4096); /* 0.25=voiced, 0=unvoiced */
+
+			L_tmp = L_deposit_h(code[0]);
+			L_tmp -= (code[1] * tmp)<<1;
+			code2[0] = vo_round(L_tmp);
+
+			for (i = 1; i < L_SUBFR - 1; i++)
+			{
+				L_tmp = L_deposit_h(code[i]);
+				L_tmp -= (code[i + 1] * tmp)<<1;
+				L_tmp -= (code[i - 1] * tmp)<<1;
+				code2[i] = vo_round(L_tmp);
+			}
+
+			L_tmp = L_deposit_h(code[L_SUBFR - 1]);
+			L_tmp -= (code[L_SUBFR - 2] * tmp)<<1;
+			code2[L_SUBFR - 1] = vo_round(L_tmp);
+
+			/* build excitation */
+			gain_code = vo_round(L_shl(L_gain_code, Q_new));
+
+			for (i = 0; i < L_SUBFR; i++)
+			{
+				L_tmp = (code2[i] * gain_code)<<1;
+				L_tmp = (L_tmp << 5);
+				L_tmp += (exc2[i] * gain_pit)<<1;
+				L_tmp = (L_tmp << 1);
+				exc2[i] = vo_round(L_tmp);
+			}
+
+			corr_gain = synthesis(p_Aq, exc2, Q_new, &speech16k[i_subfr * 5 / 4], st);
+			Parm_serial(corr_gain, 4, &prms);
+		}
+		p_A += (M + 1);
+		p_Aq += (M + 1);
+	}                                      /* end of subframe loop */
+
+	/*--------------------------------------------------*
+	 * Update signal for next frame.                    *
+	 * -> save past of speech[], wsp[] and exc[].       *
+	 *--------------------------------------------------*/
+	Copy(&old_speech[L_FRAME], st->old_speech, L_TOTAL - L_FRAME);
+	Copy(&old_wsp[L_FRAME / OPL_DECIM], st->old_wsp, PIT_MAX / OPL_DECIM);
+	Copy(&old_exc[L_FRAME], st->old_exc, PIT_MAX + L_INTERPOL);
+	return;
+}
+
+/*-----------------------------------------------------*
+* Function synthesis()                                *
+*                                                     *
+* Synthesis of signal at 16kHz with HF extension.     *
+*                                                     *
+*-----------------------------------------------------*/
+
+static Word16 synthesis(
+		Word16 Aq[],                          /* A(z)  : quantized Az               */
+		Word16 exc[],                         /* (i)   : excitation at 12kHz        */
+		Word16 Q_new,                         /* (i)   : scaling performed on exc   */
+		Word16 synth16k[],                    /* (o)   : 16kHz synthesis signal     */
+		Coder_State * st                      /* (i/o) : State structure            */
+		)
+{
+	Word16 fac, tmp, exp;
+	Word16 ener, exp_ener;
+	Word32 L_tmp, i;
+
+	Word16 synth_hi[M + L_SUBFR], synth_lo[M + L_SUBFR];
+	Word16 synth[L_SUBFR];
+	Word16 HF[L_SUBFR16k];                 /* High Frequency vector      */
+	Word16 Ap[M + 1];
+
+	Word16 HF_SP[L_SUBFR16k];              /* High Frequency vector (from original signal) */
+
+	Word16 HP_est_gain, HP_calc_gain, HP_corr_gain;
+	Word16 dist_min, dist;
+	Word16 HP_gain_ind = 0;
+	Word16 gain1, gain2;
+	Word16 weight1, weight2;
+
+	/*------------------------------------------------------------*
+	 * speech synthesis                                           *
+	 * ~~~~~~~~~~~~~~~~                                           *
+	 * - Find synthesis speech corresponding to exc2[].           *
+	 * - Perform fixed deemphasis and hp 50hz filtering.          *
+	 * - Oversampling from 12.8kHz to 16kHz.                      *
+	 *------------------------------------------------------------*/
+	Copy(st->mem_syn_hi, synth_hi, M);
+	Copy(st->mem_syn_lo, synth_lo, M);
+
+#ifdef ASM_OPT                 /* asm optimization branch */
+	Syn_filt_32_asm(Aq, M, exc, Q_new, synth_hi + M, synth_lo + M, L_SUBFR);
+#else
+	Syn_filt_32(Aq, M, exc, Q_new, synth_hi + M, synth_lo + M, L_SUBFR);
+#endif
+
+	Copy(synth_hi + L_SUBFR, st->mem_syn_hi, M);
+	Copy(synth_lo + L_SUBFR, st->mem_syn_lo, M);
+
+#ifdef ASM_OPT                 /* asm optimization branch */
+	Deemph_32_asm(synth_hi + M, synth_lo + M, synth, &(st->mem_deemph));
+#else
+	Deemph_32(synth_hi + M, synth_lo + M, synth, PREEMPH_FAC, L_SUBFR, &(st->mem_deemph));
+#endif
+
+	HP50_12k8(synth, L_SUBFR, st->mem_sig_out);
+
+	/* Original speech signal as reference for high band gain quantisation */
+	for (i = 0; i < L_SUBFR16k; i++)
+	{
+		HF_SP[i] = synth16k[i];
+	}
+
+	/*------------------------------------------------------*
+	 * HF noise synthesis                                   *
+	 * ~~~~~~~~~~~~~~~~~~                                   *
+	 * - Generate HF noise between 5.5 and 7.5 kHz.         *
+	 * - Set energy of noise according to synthesis tilt.   *
+	 *     tilt > 0.8 ==> - 14 dB (voiced)                  *
+	 *     tilt   0.5 ==> - 6 dB  (voiced or noise)         *
+	 *     tilt < 0.0 ==>   0 dB  (noise)                   *
+	 *------------------------------------------------------*/
+	/* generate white noise vector */
+	for (i = 0; i < L_SUBFR16k; i++)
+	{
+		HF[i] = Random(&(st->seed2))>>3;
+	}
+	/* energy of excitation */
+#ifdef ASM_OPT                    /* asm optimization branch */
+	Scale_sig_opt(exc, L_SUBFR, -3);
+	Q_new = Q_new - 3;
+	ener = extract_h(Dot_product12_asm(exc, exc, L_SUBFR, &exp_ener));
+#else
+	Scale_sig(exc, L_SUBFR, -3);
+	Q_new = Q_new - 3;
+	ener = extract_h(Dot_product12(exc, exc, L_SUBFR, &exp_ener));
+#endif
+
+	exp_ener = exp_ener - (Q_new + Q_new);
+	/* set energy of white noise to energy of excitation */
+#ifdef ASM_OPT              /* asm optimization branch */
+	tmp = extract_h(Dot_product12_asm(HF, HF, L_SUBFR16k, &exp));
+#else
+	tmp = extract_h(Dot_product12(HF, HF, L_SUBFR16k, &exp));
+#endif
+
+	if(tmp > ener)
+	{
+		tmp = (tmp >> 1);                 /* Be sure tmp < ener */
+		exp = (exp + 1);
+	}
+	L_tmp = L_deposit_h(div_s(tmp, ener)); /* result is normalized */
+	exp = (exp - exp_ener);
+	Isqrt_n(&L_tmp, &exp);
+	L_tmp = L_shl(L_tmp, (exp + 1));       /* L_tmp x 2, L_tmp in Q31 */
+	tmp = extract_h(L_tmp);                /* tmp = 2 x sqrt(ener_exc/ener_hf) */
+
+	for (i = 0; i < L_SUBFR16k; i++)
+	{
+		HF[i] = vo_mult(HF[i], tmp);
+	}
+
+	/* find tilt of synthesis speech (tilt: 1=voiced, -1=unvoiced) */
+	HP400_12k8(synth, L_SUBFR, st->mem_hp400);
+
+	L_tmp = 1L;
+	for (i = 0; i < L_SUBFR; i++)
+		L_tmp += (synth[i] * synth[i])<<1;
+
+	exp = norm_l(L_tmp);
+	ener = extract_h(L_tmp << exp);   /* ener = r[0] */
+
+	L_tmp = 1L;
+	for (i = 1; i < L_SUBFR; i++)
+		L_tmp +=(synth[i] * synth[i - 1])<<1;
+
+	tmp = extract_h(L_tmp << exp);    /* tmp = r[1] */
+
+	if (tmp > 0)
+	{
+		fac = div_s(tmp, ener);
+	} else
+	{
+		fac = 0;
+	}
+
+	/* modify energy of white noise according to synthesis tilt */
+	gain1 = 32767 - fac;
+	gain2 = vo_mult(gain1, 20480);
+	gain2 = shl(gain2, 1);
+
+	if (st->vad_hist > 0)
+	{
+		weight1 = 0;
+		weight2 = 32767;
+	} else
+	{
+		weight1 = 32767;
+		weight2 = 0;
+	}
+	tmp = vo_mult(weight1, gain1);
+	tmp = add1(tmp, vo_mult(weight2, gain2));
+
+	if (tmp != 0)
+	{
+		tmp = (tmp + 1);
+	}
+	HP_est_gain = tmp;
+
+	if(HP_est_gain < 3277)
+	{
+		HP_est_gain = 3277;                /* 0.1 in Q15 */
+	}
+	/* synthesis of noise: 4.8kHz..5.6kHz --> 6kHz..7kHz */
+	Weight_a(Aq, Ap, 19661, M);            /* fac=0.6 */
+
+#ifdef ASM_OPT                /* asm optimization branch */
+	Syn_filt_asm(Ap, HF, HF, st->mem_syn_hf);
+	/* noise High Pass filtering (1ms of delay) */
+	Filt_6k_7k_asm(HF, L_SUBFR16k, st->mem_hf);
+	/* filtering of the original signal */
+	Filt_6k_7k_asm(HF_SP, L_SUBFR16k, st->mem_hf2);
+
+	/* check the gain difference */
+	Scale_sig_opt(HF_SP, L_SUBFR16k, -1);
+	ener = extract_h(Dot_product12_asm(HF_SP, HF_SP, L_SUBFR16k, &exp_ener));
+	/* set energy of white noise to energy of excitation */
+	tmp = extract_h(Dot_product12_asm(HF, HF, L_SUBFR16k, &exp));
+#else
+	Syn_filt(Ap, HF, HF, L_SUBFR16k, st->mem_syn_hf, 1);
+	/* noise High Pass filtering (1ms of delay) */
+	Filt_6k_7k(HF, L_SUBFR16k, st->mem_hf);
+	/* filtering of the original signal */
+	Filt_6k_7k(HF_SP, L_SUBFR16k, st->mem_hf2);
+	/* check the gain difference */
+	Scale_sig(HF_SP, L_SUBFR16k, -1);
+	ener = extract_h(Dot_product12(HF_SP, HF_SP, L_SUBFR16k, &exp_ener));
+	/* set energy of white noise to energy of excitation */
+	tmp = extract_h(Dot_product12(HF, HF, L_SUBFR16k, &exp));
+#endif
+
+	if (tmp > ener)
+	{
+		tmp = (tmp >> 1);                 /* Be sure tmp < ener */
+		exp = (exp + 1);
+	}
+	L_tmp = L_deposit_h(div_s(tmp, ener)); /* result is normalized */
+	exp = vo_sub(exp, exp_ener);
+	Isqrt_n(&L_tmp, &exp);
+	L_tmp = L_shl(L_tmp, exp);             /* L_tmp, L_tmp in Q31 */
+	HP_calc_gain = extract_h(L_tmp);       /* tmp = sqrt(ener_input/ener_hf) */
+
+	/* st->gain_alpha *= st->dtx_encSt->dtxHangoverCount/7 */
+	L_tmp = (vo_L_mult(st->dtx_encSt->dtxHangoverCount, 4681) << 15);
+	st->gain_alpha = vo_mult(st->gain_alpha, extract_h(L_tmp));
+
+	if(st->dtx_encSt->dtxHangoverCount > 6)
+		st->gain_alpha = 32767;
+	HP_est_gain = HP_est_gain >> 1;     /* From Q15 to Q14 */
+	HP_corr_gain = add1(vo_mult(HP_calc_gain, st->gain_alpha), vo_mult((32767 - st->gain_alpha), HP_est_gain));
+
+	/* Quantise the correction gain */
+	dist_min = 32767;
+	for (i = 0; i < 16; i++)
+	{
+		dist = vo_mult((HP_corr_gain - HP_gain[i]), (HP_corr_gain - HP_gain[i]));
+		if (dist_min > dist)
+		{
+			dist_min = dist;
+			HP_gain_ind = i;
+		}
+	}
+	HP_corr_gain = HP_gain[HP_gain_ind];
+	/* return the quantised gain index when using the highest mode, otherwise zero */
+	return (HP_gain_ind);
+}
+
+/*************************************************
+*
+* Breif: Codec main function
+*
+**************************************************/
+
+int AMR_Enc_Encode(HAMRENC hCodec)
+{
+	Word32 i;
+	Coder_State *gData = (Coder_State*)hCodec;
+	Word16 *signal;
+	Word16 packed_size = 0;
+	Word16 prms[NB_BITS_MAX];
+	Word16 coding_mode = 0, nb_bits, allow_dtx, mode, reset_flag;
+	mode = gData->mode;
+	coding_mode = gData->mode;
+	nb_bits = nb_of_bits[mode];
+	signal = (Word16 *)gData->inputStream;
+	allow_dtx = gData->allow_dtx;
+
+	/* check for homing frame */
+	reset_flag = encoder_homing_frame_test(signal);
+
+	for (i = 0; i < L_FRAME16k; i++)   /* Delete the 2 LSBs (14-bit input) */
+	{
+		*(signal + i) = (Word16) (*(signal + i) & 0xfffC);
+	}
+
+	coder(&coding_mode, signal, prms, &nb_bits, gData, allow_dtx);
+	packed_size = PackBits(prms, coding_mode, mode, gData);
+	if (reset_flag != 0)
+	{
+		Reset_encoder(gData, 1);
+	}
+	return packed_size;
+}
+
+/***************************************************************************
+*
+*Brief: Codec API function --- Initialize the codec and return a codec handle
+*
+***************************************************************************/
+
+VO_U32 VO_API voAMRWB_Init(VO_HANDLE * phCodec,                   /* o: the audio codec handle */
+						   VO_AUDIO_CODINGTYPE vType,             /* i: Codec Type ID */
+						   VO_CODEC_INIT_USERDATA * pUserData     /* i: init Parameters */
+						   )
+{
+	Coder_State *st;
+	FrameStream *stream;
+#ifdef USE_DEAULT_MEM
+	VO_MEM_OPERATOR voMemoprator;
+#endif
+	VO_MEM_OPERATOR *pMemOP;
+	int interMem = 0;
+
+	if(pUserData == NULL || pUserData->memflag != VO_IMF_USERMEMOPERATOR || pUserData->memData == NULL )
+	{
+#ifdef USE_DEAULT_MEM
+		voMemoprator.Alloc = cmnMemAlloc;
+		voMemoprator.Copy = cmnMemCopy;
+		voMemoprator.Free = cmnMemFree;
+		voMemoprator.Set = cmnMemSet;
+		voMemoprator.Check = cmnMemCheck;
+		interMem = 1;
+		pMemOP = &voMemoprator;
+#else
+		*phCodec = NULL;
+		return VO_ERR_INVALID_ARG;
+#endif
+	}
+	else
+	{
+		pMemOP = (VO_MEM_OPERATOR *)pUserData->memData;
+	}
+	/*-------------------------------------------------------------------------*
+	 * Memory allocation for coder state.                                      *
+	 *-------------------------------------------------------------------------*/
+	if ((st = (Coder_State *)mem_malloc(pMemOP, sizeof(Coder_State), 32, VO_INDEX_ENC_AMRWB)) == NULL)
+	{
+		return VO_ERR_OUTOF_MEMORY;
+	}
+
+	st->vadSt = NULL;
+	st->dtx_encSt = NULL;
+	st->sid_update_counter = 3;
+	st->sid_handover_debt = 0;
+	st->prev_ft = TX_SPEECH;
+	st->inputStream = NULL;
+	st->inputSize = 0;
+
+	/* Default setting */
+	st->mode = VOAMRWB_MD2385;                        /* bit rate 23.85kbps */
+	st->frameType = VOAMRWB_RFC3267;                  /* frame type: RFC3267 */
+	st->allow_dtx = 0;                                /* disable DTX mode */
+
+	st->outputStream = NULL;
+	st->outputSize = 0;
+
+	st->stream = (FrameStream *)mem_malloc(pMemOP, sizeof(FrameStream), 32, VO_INDEX_ENC_AMRWB);
+	if(st->stream == NULL)
+		return VO_ERR_OUTOF_MEMORY;
+
+	st->stream->frame_ptr = (unsigned char *)mem_malloc(pMemOP, Frame_Maxsize, 32, VO_INDEX_ENC_AMRWB);
+	if(st->stream->frame_ptr == NULL)
+		return  VO_ERR_OUTOF_MEMORY;
+
+	stream = st->stream;
+	voAWB_InitFrameBuffer(stream);
+
+	wb_vad_init(&(st->vadSt), pMemOP);
+	dtx_enc_init(&(st->dtx_encSt), isf_init, pMemOP);
+
+	Reset_encoder((void *) st, 1);
+
+	if(interMem)
+	{
+		st->voMemoprator.Alloc = cmnMemAlloc;
+		st->voMemoprator.Copy = cmnMemCopy;
+		st->voMemoprator.Free = cmnMemFree;
+		st->voMemoprator.Set = cmnMemSet;
+		st->voMemoprator.Check = cmnMemCheck;
+		pMemOP = &st->voMemoprator;
+	}
+
+	st->pvoMemop = pMemOP;
+
+	*phCodec = (void *) st;
+
+	return VO_ERR_NONE;
+}
+
+/**********************************************************************************
+*
+* Brief: Codec API function: Input PCM data
+*
+***********************************************************************************/
+
+VO_U32 VO_API voAMRWB_SetInputData(
+		VO_HANDLE hCodec,                   /* i/o: The codec handle which was created by Init function */
+		VO_CODECBUFFER * pInput             /*   i: The input buffer parameter  */
+		)
+{
+	Coder_State  *gData;
+	FrameStream  *stream;
+
+	if(NULL == hCodec)
+	{
+		return VO_ERR_INVALID_ARG;
+	}
+
+	gData = (Coder_State *)hCodec;
+	stream = gData->stream;
+
+	if(NULL == pInput || NULL == pInput->Buffer || 0 > pInput->Length)
+	{
+		return VO_ERR_INVALID_ARG;
+	}
+
+	stream->set_ptr    = pInput->Buffer;
+	stream->set_len    = pInput->Length;
+	stream->frame_ptr  = stream->frame_ptr_bk;
+	stream->used_len   = 0;
+
+	return VO_ERR_NONE;
+}
+
+/**************************************************************************************
+*
+* Brief: Codec API function: Get the compression audio data frame by frame
+*
+***************************************************************************************/
+
+VO_U32 VO_API voAMRWB_GetOutputData(
+		VO_HANDLE hCodec,                    /* i: The Codec Handle which was created by Init function*/
+		VO_CODECBUFFER * pOutput,            /* o: The output audio data */
+		VO_AUDIO_OUTPUTINFO * pAudioFormat   /* o: The encoder module filled audio format and used the input size*/
+		)
+{
+	Coder_State* gData = (Coder_State*)hCodec;
+	VO_MEM_OPERATOR  *pMemOP;
+	FrameStream  *stream = (FrameStream *)gData->stream;
+	pMemOP = (VO_MEM_OPERATOR  *)gData->pvoMemop;
+
+	if(stream->framebuffer_len  < Frame_MaxByte)         /* check the work buffer len */
+	{
+		stream->frame_storelen = stream->framebuffer_len;
+		if(stream->frame_storelen)
+		{
+			pMemOP->Copy(VO_INDEX_ENC_AMRWB, stream->frame_ptr_bk , stream->frame_ptr , stream->frame_storelen);
+		}
+		if(stream->set_len > 0)
+		{
+			voAWB_UpdateFrameBuffer(stream, pMemOP);
+		}
+		if(stream->framebuffer_len < Frame_MaxByte)
+		{
+			if(pAudioFormat)
+				pAudioFormat->InputUsed = stream->used_len;
+			return VO_ERR_INPUT_BUFFER_SMALL;
+		}
+	}
+
+	gData->inputStream = stream->frame_ptr;
+	gData->outputStream = (unsigned short*)pOutput->Buffer;
+
+	gData->outputSize = AMR_Enc_Encode(gData);         /* encoder main function */
+
+	pOutput->Length = gData->outputSize;               /* get the output buffer length */
+	stream->frame_ptr += 640;                          /* update the work buffer ptr */
+	stream->framebuffer_len  -= 640;
+
+	if(pAudioFormat)                                   /* return output audio information */
+	{
+		pAudioFormat->Format.Channels = 1;
+		pAudioFormat->Format.SampleRate = 8000;
+		pAudioFormat->Format.SampleBits = 16;
+		pAudioFormat->InputUsed = stream->used_len;
+	}
+	return VO_ERR_NONE;
+}
+
+/*************************************************************************
+*
+* Brief: Codec API function---set the data by specified parameter ID
+*
+*************************************************************************/
+
+
+VO_U32 VO_API voAMRWB_SetParam(
+		VO_HANDLE hCodec,   /* i/o: The Codec Handle which was created by Init function */
+		VO_S32 uParamID,    /*   i: The param ID */
+		VO_PTR pData        /*   i: The param value depend on the ID */
+		)
+{
+	Coder_State* gData = (Coder_State*)hCodec;
+	FrameStream *stream = (FrameStream *)(gData->stream);
+	int *lValue = (int*)pData;
+
+	switch(uParamID)
+	{
+		/* setting AMR-WB frame type*/
+		case VO_PID_AMRWB_FRAMETYPE:
+			if(*lValue < VOAMRWB_DEFAULT || *lValue > VOAMRWB_RFC3267)
+				return VO_ERR_WRONG_PARAM_ID;
+			gData->frameType = *lValue;
+			break;
+		/* setting AMR-WB bit rate */
+		case VO_PID_AMRWB_MODE:
+			{
+				if(*lValue < VOAMRWB_MD66 || *lValue > VOAMRWB_MD2385)
+					return VO_ERR_WRONG_PARAM_ID;
+				gData->mode = *lValue;
+			}
+			break;
+		/* enable or disable DTX mode */
+		case VO_PID_AMRWB_DTX:
+			gData->allow_dtx = (Word16)(*lValue);
+			break;
+
+		case VO_PID_COMMON_HEADDATA:
+			break;
+        /* flush the work buffer */
+		case VO_PID_COMMON_FLUSH:
+			stream->set_ptr = NULL;
+			stream->frame_storelen = 0;
+			stream->framebuffer_len = 0;
+			stream->set_len = 0;
+			break;
+
+		default:
+			return VO_ERR_WRONG_PARAM_ID;
+	}
+	return VO_ERR_NONE;
+}
+
+/**************************************************************************
+*
+*Brief: Codec API function---Get the data by specified parameter ID
+*
+***************************************************************************/
+
+VO_U32 VO_API voAMRWB_GetParam(
+		VO_HANDLE hCodec,      /* i: The Codec Handle which was created by Init function */
+		VO_S32 uParamID,       /* i: The param ID */
+		VO_PTR pData           /* o: The param value depend on the ID */
+		)
+{
+	int    temp;
+	Coder_State* gData = (Coder_State*)hCodec;
+
+	if (gData==NULL)
+		return VO_ERR_INVALID_ARG;
+	switch(uParamID)
+	{
+		/* output audio format */
+		case VO_PID_AMRWB_FORMAT:
+			{
+				VO_AUDIO_FORMAT* fmt = (VO_AUDIO_FORMAT*)pData;
+				fmt->Channels   = 1;
+				fmt->SampleRate = 16000;
+				fmt->SampleBits = 16;
+				break;
+			}
+        /* output audio channel number */
+		case VO_PID_AMRWB_CHANNELS:
+			temp = 1;
+			pData = (void *)(&temp);
+			break;
+        /* output audio sample rate */
+		case VO_PID_AMRWB_SAMPLERATE:
+			temp = 16000;
+			pData = (void *)(&temp);
+			break;
+		/* output audio frame type */
+		case VO_PID_AMRWB_FRAMETYPE:
+			temp = gData->frameType;
+			pData = (void *)(&temp);
+			break;
+		/* output audio bit rate */
+		case VO_PID_AMRWB_MODE:
+			temp = gData->mode;
+			pData = (void *)(&temp);
+			break;
+		default:
+			return VO_ERR_WRONG_PARAM_ID;
+	}
+
+	return VO_ERR_NONE;
+}
+
+/***********************************************************************************
+*
+* Brief: Codec API function---Release the codec after all encoder operations are done
+*
+*************************************************************************************/
+
+VO_U32 VO_API voAMRWB_Uninit(VO_HANDLE hCodec           /* i/o: Codec handle pointer */
+							 )
+{
+	Coder_State* gData = (Coder_State*)hCodec;
+	VO_MEM_OPERATOR *pMemOP;
+	pMemOP = gData->pvoMemop;
+
+	if(hCodec)
+	{
+		if(gData->stream)
+		{
+			if(gData->stream->frame_ptr_bk)
+			{
+				mem_free(pMemOP, gData->stream->frame_ptr_bk, VO_INDEX_ENC_AMRWB);
+				gData->stream->frame_ptr_bk = NULL;
+			}
+			mem_free(pMemOP, gData->stream, VO_INDEX_ENC_AMRWB);
+			gData->stream = NULL;
+		}
+		wb_vad_exit(&(((Coder_State *) gData)->vadSt), pMemOP);
+		dtx_enc_exit(&(((Coder_State *) gData)->dtx_encSt), pMemOP);
+
+		mem_free(pMemOP, hCodec, VO_INDEX_ENC_AMRWB);
+		hCodec = NULL;
+	}
+
+	return VO_ERR_NONE;
+}
+
+/********************************************************************************
+*
+* Brief: voGetAMRWBEncAPI gets the API handle of the codec
+*
+********************************************************************************/
+
+VO_S32 VO_API voGetAMRWBEncAPI(
+							   VO_AUDIO_CODECAPI * pEncHandle      /* i/o: Codec handle pointer */
+							   )
+{
+	if(NULL == pEncHandle)
+		return VO_ERR_INVALID_ARG;
+	pEncHandle->Init = voAMRWB_Init;
+	pEncHandle->SetInputData = voAMRWB_SetInputData;
+	pEncHandle->GetOutputData = voAMRWB_GetOutputData;
+	pEncHandle->SetParam = voAMRWB_SetParam;
+	pEncHandle->GetParam = voAMRWB_GetParam;
+	pEncHandle->Uninit = voAMRWB_Uninit;
+
+	return VO_ERR_NONE;
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/media/libstagefright/codecs/amrwbenc/src/voicefac.c b/media/libstagefright/codecs/amrwbenc/src/voicefac.c
index 187d774..d890044 100644
--- a/media/libstagefright/codecs/amrwbenc/src/voicefac.c
+++ b/media/libstagefright/codecs/amrwbenc/src/voicefac.c
@@ -1,92 +1,92 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*   File: voicefac.c                                                   *

-*                                                                      *

-*   Description: Find the voicing factors (1 = voice to -1 = unvoiced) *

-*                                                                      *                                                 

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-#include "math_op.h"

-

-Word16 voice_factor(                                  /* (o) Q15   : factor (-1=unvoiced to 1=voiced) */

-		Word16 exc[],                         /* (i) Q_exc : pitch excitation                 */

-		Word16 Q_exc,                         /* (i)       : exc format                       */

-		Word16 gain_pit,                      /* (i) Q14   : gain of pitch                    */

-		Word16 code[],                        /* (i) Q9    : Fixed codebook excitation        */

-		Word16 gain_code,                     /* (i) Q0    : gain of code                     */

-		Word16 L_subfr                        /* (i)       : subframe length                  */

-		)

-{

-	Word16 tmp, exp, ener1, exp1, ener2, exp2;

-	Word32 i, L_tmp;

-

-#ifdef ASM_OPT               /* asm optimization branch */

-	ener1 = extract_h(Dot_product12_asm(exc, exc, L_subfr, &exp1));

-#else

-	ener1 = extract_h(Dot_product12(exc, exc, L_subfr, &exp1));

-#endif

-	exp1 = exp1 - (Q_exc + Q_exc);

-	L_tmp = vo_L_mult(gain_pit, gain_pit);

-	exp = norm_l(L_tmp);

-	tmp = extract_h(L_tmp << exp);

-	ener1 = vo_mult(ener1, tmp);

-	exp1 = exp1 - exp - 10;        /* 10 -> gain_pit Q14 to Q9 */

-

-#ifdef ASM_OPT                /* asm optimization branch */

-	ener2 = extract_h(Dot_product12_asm(code, code, L_subfr, &exp2));

-#else

-	ener2 = extract_h(Dot_product12(code, code, L_subfr, &exp2));

-#endif

-

-	exp = norm_s(gain_code);

-	tmp = gain_code << exp;

-	tmp = vo_mult(tmp, tmp);

-	ener2 = vo_mult(ener2, tmp);

-	exp2 = exp2 - (exp + exp);

-

-	i = exp1 - exp2;

-

-	if (i >= 0)

-	{

-		ener1 = ener1 >> 1;

-		ener2 = ener2 >> (i + 1);

-	} else

-	{

-		ener1 = ener1 >> (1 - i);

-		ener2 = ener2 >> 1;

-	}

-

-	tmp = vo_sub(ener1, ener2);

-	ener1 = add1(add1(ener1, ener2), 1);

-

-	if (tmp >= 0)

-	{

-		tmp = div_s(tmp, ener1);

-	} else

-	{

-		tmp = vo_negate(div_s(vo_negate(tmp), ener1));

-	}

-

-	return (tmp);

-}

-

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*   File: voicefac.c                                                   *
+*                                                                      *
+*   Description: Find the voicing factors (1 = voice to -1 = unvoiced) *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "math_op.h"
+
+Word16 voice_factor(                                  /* (o) Q15   : factor (-1=unvoiced to 1=voiced) */
+		Word16 exc[],                         /* (i) Q_exc : pitch excitation                 */
+		Word16 Q_exc,                         /* (i)       : exc format                       */
+		Word16 gain_pit,                      /* (i) Q14   : gain of pitch                    */
+		Word16 code[],                        /* (i) Q9    : Fixed codebook excitation        */
+		Word16 gain_code,                     /* (i) Q0    : gain of code                     */
+		Word16 L_subfr                        /* (i)       : subframe length                  */
+		)
+{
+	Word16 tmp, exp, ener1, exp1, ener2, exp2;
+	Word32 i, L_tmp;
+
+#ifdef ASM_OPT               /* asm optimization branch */
+	ener1 = extract_h(Dot_product12_asm(exc, exc, L_subfr, &exp1));
+#else
+	ener1 = extract_h(Dot_product12(exc, exc, L_subfr, &exp1));
+#endif
+	exp1 = exp1 - (Q_exc + Q_exc);
+	L_tmp = vo_L_mult(gain_pit, gain_pit);
+	exp = norm_l(L_tmp);
+	tmp = extract_h(L_tmp << exp);
+	ener1 = vo_mult(ener1, tmp);
+	exp1 = exp1 - exp - 10;        /* 10 -> gain_pit Q14 to Q9 */
+
+#ifdef ASM_OPT                /* asm optimization branch */
+	ener2 = extract_h(Dot_product12_asm(code, code, L_subfr, &exp2));
+#else
+	ener2 = extract_h(Dot_product12(code, code, L_subfr, &exp2));
+#endif
+
+	exp = norm_s(gain_code);
+	tmp = gain_code << exp;
+	tmp = vo_mult(tmp, tmp);
+	ener2 = vo_mult(ener2, tmp);
+	exp2 = exp2 - (exp + exp);
+
+	i = exp1 - exp2;
+
+	if (i >= 0)
+	{
+		ener1 = ener1 >> 1;
+		ener2 = ener2 >> (i + 1);
+	} else
+	{
+		ener1 = ener1 >> (1 - i);
+		ener2 = ener2 >> 1;
+	}
+
+	tmp = vo_sub(ener1, ener2);
+	ener1 = add1(add1(ener1, ener2), 1);
+
+	if (tmp >= 0)
+	{
+		tmp = div_s(tmp, ener1);
+	} else
+	{
+		tmp = vo_negate(div_s(vo_negate(tmp), ener1));
+	}
+
+	return (tmp);
+}
+
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/wb_vad.c b/media/libstagefright/codecs/amrwbenc/src/wb_vad.c
index 0126853..13dd2aa 100644
--- a/media/libstagefright/codecs/amrwbenc/src/wb_vad.c
+++ b/media/libstagefright/codecs/amrwbenc/src/wb_vad.c
@@ -1,808 +1,808 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*      File: wb_vad.c                                                  *

-*                                                                      *

-*      Description: Voice Activity Detection                           *

-*                                                                      *

-************************************************************************/

-

-#include <stdlib.h>

-#include <stdio.h>

-#include "cnst.h"

-#include "wb_vad.h"

-#include "typedef.h"

-#include "basic_op.h"

-#include "math_op.h"

-#include "wb_vad_c.h"

-#include "mem_align.h"

-

-/******************************************************************************

-*  Calculate Log2 and scale the signal:

-*

-*    ilog2(Word32 in) = -1024*log10(in * 2^-31)/log10(2), where in = [1, 2^31-1]

-*

-*  input   output

-*  32768   16384

-*  1       31744

-*

-* When input is in the range of [1,2^16], max error is 0.0380%.

-*********************************************************************************/

-

-static Word16 ilog2(                       /* return: output value of the log2 */

-		Word16 mant                        /* i: value to be converted */

-		)

-{

-	Word16 ex, ex2, res;

-	Word32 i, l_temp;

-

-	if (mant <= 0)

-	{

-		mant = 1;                         

-	}

-	ex = norm_s(mant);

-	mant = mant << ex;

-

-	for (i = 0; i < 3; i++)

-		mant = vo_mult(mant, mant);

-	l_temp = vo_L_mult(mant, mant);

-

-	ex2 = norm_l(l_temp);

-	mant = extract_h(l_temp << ex2);

-

-	res = (ex + 16) << 10;

-	res = add1(res, (ex2 << 6));

-	res = vo_sub(add1(res, 127), (mant >> 8));

-	return (res);

-}

-

-/******************************************************************************

-*

-*     Function     : filter5

-*     Purpose      : Fifth-order half-band lowpass/highpass filter pair with

-*                    decimation.

-*

-*******************************************************************************/

-

-static void filter5(

-		Word16 * in0,                         /* i/o : input values; output low-pass part  */

-		Word16 * in1,                         /* i/o : input values; output high-pass part */

-		Word16 data[]                         /* i/o : filter memory                       */

-		)

-{

-	Word16 temp0, temp1, temp2;

-

-	temp0 = vo_sub(*in0, vo_mult(COEFF5_1, data[0]));

-	temp1 = add1(data[0], vo_mult(COEFF5_1, temp0));

-	data[0] = temp0;                      

-

-	temp0 = vo_sub(*in1, vo_mult(COEFF5_2, data[1]));

-	temp2 = add1(data[1], vo_mult(COEFF5_2, temp0));

-	data[1] = temp0;                       

-

-	*in0 = extract_h((vo_L_add(temp1, temp2) << 15));   

-	*in1 = extract_h((vo_L_sub(temp1, temp2) << 15));  

-}

-

-/******************************************************************************

-*

-*     Function     : filter3

-*     Purpose      : Third-order half-band lowpass/highpass filter pair with

-*                    decimation.

-*

-*******************************************************************************/

-

-static void filter3(

-		Word16 * in0,                         /* i/o : input values; output low-pass part  */

-		Word16 * in1,                         /* i/o : input values; output high-pass part */

-		Word16 * data                         /* i/o : filter memory                       */

-		)

-{

-	Word16 temp1, temp2;

-

-	temp1 = vo_sub(*in1, vo_mult(COEFF3, *data));

-	temp2 = add1(*data, vo_mult(COEFF3, temp1));

-	*data = temp1;                        

-

-	*in1 = extract_h((vo_L_sub(*in0, temp2) << 15));   

-	*in0 = extract_h((vo_L_add(*in0, temp2) << 15));   

-}

-

-/******************************************************************************

-*

-*     Function   : level_calculation

-*     Purpose    : Calculate signal level in a sub-band. Level is calculated

-*                  by summing absolute values of the input data.

-*

-*                  Signal level calculated from of the end of the frame

-*                  (data[count1 - count2]) is stored to (*sub_level)

-*                  and added to the level of the next frame.

-*

-******************************************************************************/

-

-static Word16 level_calculation(                      /* return: signal level */

-		Word16 data[],                        /* i   : signal buffer                                    */

-		Word16 * sub_level,                   /* i   : level calculated at the end of the previous frame*/

-		                                      /* o   : level of signal calculated from the last         */

-		                                      /*       (count2 - count1) samples                        */

-		Word16 count1,                        /* i   : number of samples to be counted                  */

-		Word16 count2,                        /* i   : number of samples to be counted                  */

-		Word16 ind_m,                         /* i   : step size for the index of the data buffer       */

-		Word16 ind_a,                         /* i   : starting index of the data buffer                */

-		Word16 scale                          /* i   : scaling for the level calculation                */

-		)

-{

-	Word32 i, l_temp1, l_temp2;

-	Word16 level;

-

-	l_temp1 = 0L;                          

-	for (i = count1; i < count2; i++)

-	{

-		l_temp1 += (abs_s(data[ind_m * i + ind_a])<<1);

-	}

-

-	l_temp2 = vo_L_add(l_temp1, L_shl(*sub_level, 16 - scale));

-	*sub_level = extract_h(L_shl(l_temp1, scale));      

-

-	for (i = 0; i < count1; i++)

-	{

-		l_temp2 += (abs_s(data[ind_m * i + ind_a])<<1);

-	}

-	level = extract_h(L_shl2(l_temp2, scale));

-

-	return level;

-}

-

-/******************************************************************************

-*

-*     Function     : filter_bank

-*     Purpose      : Divide input signal into bands and calculate level of

-*                    the signal in each band

-*

-*******************************************************************************/

-

-static void filter_bank(

-		VadVars * st,                         /* i/o : State struct               */

-		Word16 in[],                          /* i   : input frame                */

-		Word16 level[]                        /* o   : signal levels at each band */

-		)

-{

-	Word32 i;

-	Word16 tmp_buf[FRAME_LEN];

-

-	/* shift input 1 bit down for safe scaling */

-	for (i = 0; i < FRAME_LEN; i++)

-	{

-		tmp_buf[i] = in[i] >> 1;       

-	}

-

-	/* run the filter bank */

-	for (i = 0; i < 128; i++)

-	{

-		filter5(&tmp_buf[2 * i], &tmp_buf[2 * i + 1], st->a_data5[0]);

-	}

-	for (i = 0; i < 64; i++)

-	{

-		filter5(&tmp_buf[4 * i], &tmp_buf[4 * i + 2], st->a_data5[1]);

-		filter5(&tmp_buf[4 * i + 1], &tmp_buf[4 * i + 3], st->a_data5[2]);

-	}

-	for (i = 0; i < 32; i++)

-	{

-		filter5(&tmp_buf[8 * i], &tmp_buf[8 * i + 4], st->a_data5[3]);

-		filter5(&tmp_buf[8 * i + 2], &tmp_buf[8 * i + 6], st->a_data5[4]);

-		filter3(&tmp_buf[8 * i + 3], &tmp_buf[8 * i + 7], &st->a_data3[0]);

-	}

-	for (i = 0; i < 16; i++)

-	{

-		filter3(&tmp_buf[16 * i + 0], &tmp_buf[16 * i + 8], &st->a_data3[1]);

-		filter3(&tmp_buf[16 * i + 4], &tmp_buf[16 * i + 12], &st->a_data3[2]);

-		filter3(&tmp_buf[16 * i + 6], &tmp_buf[16 * i + 14], &st->a_data3[3]);

-	}

-

-	for (i = 0; i < 8; i++)

-	{

-		filter3(&tmp_buf[32 * i + 0], &tmp_buf[32 * i + 16], &st->a_data3[4]);

-		filter3(&tmp_buf[32 * i + 8], &tmp_buf[32 * i + 24], &st->a_data3[5]);

-	}

-

-	/* calculate levels in each frequency band */

-

-	/* 4800 - 6400 Hz */

-	level[11] = level_calculation(tmp_buf, &st->sub_level[11], 16, 64, 4, 1, 14);   

-	/* 4000 - 4800 Hz */

-	level[10] = level_calculation(tmp_buf, &st->sub_level[10], 8, 32, 8, 7, 15);   

-	/* 3200 - 4000 Hz */

-	level[9] = level_calculation(tmp_buf, &st->sub_level[9],8, 32, 8, 3, 15);   

-	/* 2400 - 3200 Hz */

-	level[8] = level_calculation(tmp_buf, &st->sub_level[8],8, 32, 8, 2, 15);   

-	/* 2000 - 2400 Hz */

-	level[7] = level_calculation(tmp_buf, &st->sub_level[7],4, 16, 16, 14, 16);       

-	/* 1600 - 2000 Hz */

-	level[6] = level_calculation(tmp_buf, &st->sub_level[6],4, 16, 16, 6, 16);        

-	/* 1200 - 1600 Hz */

-	level[5] = level_calculation(tmp_buf, &st->sub_level[5],4, 16, 16, 4, 16);        

-	/* 800 - 1200 Hz */

-	level[4] = level_calculation(tmp_buf, &st->sub_level[4],4, 16, 16, 12, 16);       

-	/* 600 - 800 Hz */

-	level[3] = level_calculation(tmp_buf, &st->sub_level[3],2, 8, 32, 8, 17); 

-	/* 400 - 600 Hz */

-	level[2] = level_calculation(tmp_buf, &st->sub_level[2],2, 8, 32, 24, 17);        

-	/* 200 - 400 Hz */

-	level[1] = level_calculation(tmp_buf, &st->sub_level[1],2, 8, 32, 16, 17);        

-	/* 0 - 200 Hz */

-	level[0] = level_calculation(tmp_buf, &st->sub_level[0],2, 8, 32, 0, 17); 

-}

-

-/******************************************************************************

-*

-*     Function   : update_cntrl

-*     Purpose    : Control update of the background noise estimate.

-*

-*******************************************************************************/

-

-static void update_cntrl(

-		VadVars * st,                         /* i/o : State structure                    */

-		Word16 level[]                        /* i   : sub-band levels of the input frame */

-		)

-{

-	Word32 i;

-	Word16 num, temp, stat_rat, exp, denom;

-	Word16 alpha;

-

-	/* if a tone has been detected for a while, initialize stat_count */

-	if (sub((Word16) (st->tone_flag & 0x7c00), 0x7c00) == 0)

-	{

-		st->stat_count = STAT_COUNT;      

-	} else

-	{

-		/* if 8 last vad-decisions have been "0", reinitialize stat_count */

-		if ((st->vadreg & 0x7f80) == 0)

-		{

-			st->stat_count = STAT_COUNT;   

-		} else

-		{

-			stat_rat = 0;                  

-			for (i = 0; i < COMPLEN; i++)

-			{

-				if(level[i] > st->ave_level[i])

-				{

-					num = level[i];        

-					denom = st->ave_level[i];   

-				} else

-				{

-					num = st->ave_level[i];

-					denom = level[i];      

-				}

-				/* Limit nimimum value of num and denom to STAT_THR_LEVEL */

-				if(num < STAT_THR_LEVEL)

-				{

-					num = STAT_THR_LEVEL;  

-				}

-				if(denom < STAT_THR_LEVEL)

-				{

-					denom = STAT_THR_LEVEL;

-				}

-				exp = norm_s(denom);

-				denom = denom << exp;

-

-				/* stat_rat = num/denom * 64 */

-				temp = div_s(num >> 1, denom);

-				stat_rat = add1(stat_rat, shr(temp, (8 - exp)));

-			}

-

-			/* compare stat_rat with a threshold and update stat_count */

-			if(stat_rat > STAT_THR)

-			{

-				st->stat_count = STAT_COUNT;    

-			} else

-			{

-				if ((st->vadreg & 0x4000) != 0)

-				{

-

-					if (st->stat_count != 0)

-					{

-						st->stat_count = st->stat_count - 1;       

-					}

-				}

-			}

-		}

-	}

-

-	/* Update average amplitude estimate for stationarity estimation */

-	alpha = ALPHA4;                        

-	if(st->stat_count == STAT_COUNT)

-	{

-		alpha = 32767;                    

-	} else if ((st->vadreg & 0x4000) == 0)

-	{

-		alpha = ALPHA5;                   

-	}

-	for (i = 0; i < COMPLEN; i++)

-	{

-		st->ave_level[i] = add1(st->ave_level[i], vo_mult_r(alpha, vo_sub(level[i], st->ave_level[i])));   

-	}

-}

-

-/******************************************************************************

-*

-*     Function     : hangover_addition

-*     Purpose      : Add hangover after speech bursts

-*

-*******************************************************************************/

-

-static Word16 hangover_addition(                      /* return: VAD_flag indicating final VAD decision */

-		VadVars * st,                         /* i/o : State structure                     */

-		Word16 low_power,                     /* i   : flag power of the input frame    */

-		Word16 hang_len,                      /* i   : hangover length */

-		Word16 burst_len                      /* i   : minimum burst length for hangover addition */

-		)

-{

-	/* if the input power (pow_sum) is lower than a threshold, clear counters and set VAD_flag to "0"         */

-	if (low_power != 0)

-	{

-		st->burst_count = 0;               

-		st->hang_count = 0;                

-		return 0;

-	}

-	/* update the counters (hang_count, burst_count) */

-	if ((st->vadreg & 0x4000) != 0)

-	{

-		st->burst_count = st->burst_count + 1;    

-		if(st->burst_count >= burst_len)

-		{

-			st->hang_count = hang_len;     

-		}

-		return 1;

-	} else

-	{

-		st->burst_count = 0;               

-		if (st->hang_count > 0)

-		{

-			st->hang_count = st->hang_count - 1;    

-			return 1;

-		}

-	}

-	return 0;

-}

-

-/******************************************************************************

-*

-*     Function   : noise_estimate_update

-*     Purpose    : Update of background noise estimate

-*

-*******************************************************************************/

-

-static void noise_estimate_update(

-		VadVars * st,                         /* i/o : State structure                       */

-		Word16 level[]                        /* i   : sub-band levels of the input frame */

-		)

-{

-	Word32 i; 

-	Word16 alpha_up, alpha_down, bckr_add = 2;

-

-	/* Control update of bckr_est[] */

-	update_cntrl(st, level);

-

-	/* Choose update speed */

-	if ((0x7800 & st->vadreg) == 0)

-	{

-		alpha_up = ALPHA_UP1;              

-		alpha_down = ALPHA_DOWN1;          

-	} else

-	{

-		if ((st->stat_count == 0))

-		{

-			alpha_up = ALPHA_UP2;          

-			alpha_down = ALPHA_DOWN2;      

-		} else

-		{

-			alpha_up = 0;                  

-			alpha_down = ALPHA3;           

-			bckr_add = 0;                  

-		}

-	}

-

-	/* Update noise estimate (bckr_est) */

-	for (i = 0; i < COMPLEN; i++)

-	{

-		Word16 temp;

-		temp = (st->old_level[i] - st->bckr_est[i]);

-

-		if (temp < 0)

-		{                                  /* update downwards */

-			st->bckr_est[i] = add1(-2, add(st->bckr_est[i],vo_mult_r(alpha_down, temp))); 

-			/* limit minimum value of the noise estimate to NOISE_MIN */

-			if(st->bckr_est[i] < NOISE_MIN)

-			{

-				st->bckr_est[i] = NOISE_MIN;   

-			}

-		} else

-		{                                  /* update upwards */

-			st->bckr_est[i] = add1(bckr_add, add1(st->bckr_est[i],vo_mult_r(alpha_up, temp)));   

-

-			/* limit maximum value of the noise estimate to NOISE_MAX */

-			if(st->bckr_est[i] > NOISE_MAX)

-			{

-				st->bckr_est[i] = NOISE_MAX;    

-			}

-		}

-	}

-

-	/* Update signal levels of the previous frame (old_level) */

-	for (i = 0; i < COMPLEN; i++)

-	{

-		st->old_level[i] = level[i];      

-	}

-}

-

-/******************************************************************************

-*

-*     Function     : vad_decision

-*     Purpose      : Calculates VAD_flag

-*

-*******************************************************************************/

-

-static Word16 vad_decision(                           /* return value : VAD_flag */

-		VadVars * st,                         /* i/o : State structure                       */

-		Word16 level[COMPLEN],                /* i   : sub-band levels of the input frame */

-		Word32 pow_sum                        /* i   : power of the input frame           */

-		)

-{

-	Word32 i;

-	Word32 L_snr_sum;

-	Word32 L_temp;

-	Word16 vad_thr, temp, noise_level;

-	Word16 low_power_flag;

-	Word16 hang_len, burst_len;

-	Word16 ilog2_speech_level, ilog2_noise_level;

-	Word16 temp2;

-

-	/* Calculate squared sum of the input levels (level) divided by the background noise components

-	 * (bckr_est). */

-	L_snr_sum = 0;                        

-	for (i = 0; i < COMPLEN; i++)

-	{

-		Word16 exp;

-

-		exp = norm_s(st->bckr_est[i]);

-		temp = (st->bckr_est[i] << exp);

-		temp = div_s((level[i] >> 1), temp);

-		temp = shl(temp, (exp - (UNIRSHFT - 1)));

-		L_snr_sum = L_mac(L_snr_sum, temp, temp);

-	}

-

-	/* Calculate average level of estimated background noise */

-	L_temp = 0;                           

-	for (i = 1; i < COMPLEN; i++)          /* ignore lowest band */

-	{

-		L_temp = vo_L_add(L_temp, st->bckr_est[i]);

-	}

-

-	noise_level = extract_h((L_temp << 12));

-	/* if SNR is lower than a threshold (MIN_SPEECH_SNR), and increase speech_level */

-	temp = vo_mult(noise_level, MIN_SPEECH_SNR) << 3;

-

-	if(st->speech_level < temp)

-	{

-		st->speech_level = temp;          

-	}

-	ilog2_noise_level = ilog2(noise_level);

-

-	/* If SNR is very poor, speech_level is probably corrupted by noise level. This is correctred by

-	 * subtracting MIN_SPEECH_SNR*noise_level from speech level */

-	ilog2_speech_level = ilog2(st->speech_level - temp);

-

-	temp = add1(vo_mult(NO_SLOPE, (ilog2_noise_level - NO_P1)), THR_HIGH);

-

-	temp2 = add1(SP_CH_MIN, vo_mult(SP_SLOPE, (ilog2_speech_level - SP_P1)));

-	if (temp2 < SP_CH_MIN)

-	{

-		temp2 = SP_CH_MIN;                 

-	}

-	if (temp2 > SP_CH_MAX)

-	{

-		temp2 = SP_CH_MAX;                 

-	}

-	vad_thr = temp + temp2;

-

-	if(vad_thr < THR_MIN)

-	{

-		vad_thr = THR_MIN;                 

-	}

-	/* Shift VAD decision register */

-	st->vadreg = (st->vadreg >> 1);       

-

-	/* Make intermediate VAD decision */

-	if(L_snr_sum > vo_L_mult(vad_thr, (512 * COMPLEN)))

-	{

-		st->vadreg = (Word16) (st->vadreg | 0x4000); 

-	}

-	/* check if the input power (pow_sum) is lower than a threshold" */

-	if(pow_sum < VAD_POW_LOW)

-	{

-		low_power_flag = 1;               

-	} else

-	{

-		low_power_flag = 0;               

-	}

-	/* Update background noise estimates */

-	noise_estimate_update(st, level);

-

-	/* Calculate values for hang_len and burst_len based on vad_thr */

-	hang_len = add1(vo_mult(HANG_SLOPE, (vad_thr - HANG_P1)), HANG_HIGH);

-	if(hang_len < HANG_LOW)

-	{

-		hang_len = HANG_LOW;              

-	}

-	burst_len = add1(vo_mult(BURST_SLOPE, (vad_thr - BURST_P1)), BURST_HIGH);

-

-	return (hangover_addition(st, low_power_flag, hang_len, burst_len));

-}

-

-/******************************************************************************

-*

-*     Function : Estimate_Speech()

-*     Purpose  : Estimate speech level

-*

-* Maximum signal level is searched and stored to the variable sp_max.

-* The speech frames must locate within SP_EST_COUNT number of frames.

-* Thus, noisy frames having occasional VAD = "1" decisions will not

-* affect to the estimated speech_level.

-*

-*******************************************************************************/

-

-static void Estimate_Speech(

-		VadVars * st,                         /* i/o : State structure    */

-		Word16 in_level                       /* level of the input frame */

-		)

-{

-	Word16 alpha;

-

-	/* if the required activity count cannot be achieved, reset counters */

-	if((st->sp_est_cnt - st->sp_max_cnt) > (SP_EST_COUNT - SP_ACTIVITY_COUNT))

-	{

-		st->sp_est_cnt = 0;                

-		st->sp_max = 0;                    

-		st->sp_max_cnt = 0;                

-	}

-	st->sp_est_cnt += 1; 

-

-	if (((st->vadreg & 0x4000)||(in_level > st->speech_level)) && (in_level > MIN_SPEECH_LEVEL1))

-	{

-		/* update sp_max */

-		if(in_level > st->sp_max)

-		{

-			st->sp_max = in_level;         

-		}

-		st->sp_max_cnt += 1;        

-

-		if(st->sp_max_cnt >= SP_ACTIVITY_COUNT)

-		{

-			Word16 tmp;

-			/* update speech estimate */

-			tmp = (st->sp_max >> 1);      /* scale to get "average" speech level */

-

-			/* select update speed */

-			if(tmp > st->speech_level)

-			{

-				alpha = ALPHA_SP_UP;       

-			} else

-			{

-				alpha = ALPHA_SP_DOWN;    

-			}

-			if(tmp > MIN_SPEECH_LEVEL2)

-			{

-				st->speech_level = add1(st->speech_level, vo_mult_r(alpha, vo_sub(tmp, st->speech_level))); 

-			}

-			/* clear all counters used for speech estimation */

-			st->sp_max = 0;                

-			st->sp_max_cnt = 0;            

-			st->sp_est_cnt = 0;            

-		}

-	}

-}

-

-/******************************************************************************

-*

-*  Function:   wb_vad_init

-*  Purpose:    Allocates state memory and initializes state memory

-*

-*******************************************************************************/

-

-Word16 wb_vad_init(                        /* return: non-zero with error, zero for ok. */

-		VadVars ** state,                     /* i/o : State structure    */

-		VO_MEM_OPERATOR *pMemOP

-		)

-{

-	VadVars *s;

-

-	if (state == (VadVars **) NULL)

-	{

-		fprintf(stderr, "vad_init: invalid parameter\n");

-		return -1;

-	}

-	*state = NULL;

-

-	/* allocate memory */

-	if ((s = (VadVars *) mem_malloc(pMemOP, sizeof(VadVars), 32, VO_INDEX_ENC_AMRWB)) == NULL)

-	{

-		fprintf(stderr, "vad_init: can not malloc state structure\n");

-		return -1;

-	}

-	wb_vad_reset(s);

-

-	*state = s;

-

-	return 0;

-}

-

-/******************************************************************************

-*

-*  Function:   wb_vad_reset

-*  Purpose:    Initializes state memory

-*

-*******************************************************************************/

-

-Word16 wb_vad_reset(                       /* return: non-zero with error, zero for ok. */

-		VadVars * state                       /* i/o : State structure    */

-		)

-{

-	Word32 i, j;

-

-	if (state == (VadVars *) NULL)

-	{

-		fprintf(stderr, "vad_reset: invalid parameter\n");

-		return -1;

-	}

-	state->tone_flag = 0;

-	state->vadreg = 0;

-	state->hang_count = 0;

-	state->burst_count = 0;

-	state->hang_count = 0;

-

-	/* initialize memory used by the filter bank */

-	for (i = 0; i < F_5TH_CNT; i++)

-	{

-		for (j = 0; j < 2; j++)

-		{

-			state->a_data5[i][j] = 0;

-		}

-	}

-

-	for (i = 0; i < F_3TH_CNT; i++)

-	{

-		state->a_data3[i] = 0;

-	}

-

-	/* initialize the rest of the memory */

-	for (i = 0; i < COMPLEN; i++)

-	{

-		state->bckr_est[i] = NOISE_INIT;

-		state->old_level[i] = NOISE_INIT;

-		state->ave_level[i] = NOISE_INIT;

-		state->sub_level[i] = 0;

-	}

-

-	state->sp_est_cnt = 0;

-	state->sp_max = 0;

-	state->sp_max_cnt = 0;

-	state->speech_level = SPEECH_LEVEL_INIT;

-	state->prev_pow_sum = 0;

-	return 0;

-}

-

-/******************************************************************************

-*

-*  Function:   wb_vad_exit

-*  Purpose:    The memory used for state memory is freed

-*

-*******************************************************************************/

-

-void wb_vad_exit(

-		VadVars ** state,                      /* i/o : State structure    */

-		VO_MEM_OPERATOR *pMemOP

-		)

-{

-	if (state == NULL || *state == NULL)

-		return;

-	/* deallocate memory */

-	mem_free(pMemOP, *state, VO_INDEX_ENC_AMRWB);

-	*state = NULL;

-	return;

-}

-

-/******************************************************************************

-*

-*     Function     : wb_vad_tone_detection

-*     Purpose      : Search maximum pitch gain from a frame. Set tone flag if

-*                    pitch gain is high. This is used to detect

-*                    signaling tones and other signals with high pitch gain.

-*

-*******************************************************************************/

-

-void wb_vad_tone_detection(

-		VadVars * st,                         /* i/o : State struct            */

-		Word16 p_gain                         /* pitch gain      */

-		)

-{

-	/* update tone flag */

-	st->tone_flag = (st->tone_flag >> 1);

-

-	/* if (pitch_gain > TONE_THR) set tone flag */

-	if (p_gain > TONE_THR)

-	{

-		st->tone_flag = (Word16) (st->tone_flag | 0x4000);

-	}

-}

-

-/******************************************************************************

-*

-*     Function     : wb_vad

-*     Purpose      : Main program for Voice Activity Detection (VAD) for AMR

-*

-*******************************************************************************/

-

-Word16 wb_vad(                                /* Return value : VAD Decision, 1 = speech, 0 = noise */

-		VadVars * st,                         /* i/o : State structure                 */

-		Word16 in_buf[]                       /* i   : samples of the input frame   */

-	     )

-{

-	Word16 level[COMPLEN];

-	Word32 i;

-	Word16 VAD_flag, temp;

-	Word32 L_temp, pow_sum;

-

-	/* Calculate power of the input frame. */

-	L_temp = 0L;                           

-	for (i = 0; i < FRAME_LEN; i++)

-	{

-		L_temp = L_mac(L_temp, in_buf[i], in_buf[i]);

-	}

-

-	/* pow_sum = power of current frame and previous frame */

-	pow_sum = L_add(L_temp, st->prev_pow_sum);  

-

-	/* save power of current frame for next call */

-	st->prev_pow_sum = L_temp;             

-

-	/* If input power is very low, clear tone flag */

-	if (pow_sum < POW_TONE_THR)

-	{

-		st->tone_flag = (Word16) (st->tone_flag & 0x1fff);      

-	}

-	/* Run the filter bank and calculate signal levels at each band */

-	filter_bank(st, in_buf, level);

-

-	/* compute VAD decision */

-	VAD_flag = vad_decision(st, level, pow_sum);

-

-	/* Calculate input level */

-	L_temp = 0;                          

-	for (i = 1; i < COMPLEN; i++)          /* ignore lowest band */

-	{

-		L_temp = vo_L_add(L_temp, level[i]);

-	}

-

-	temp = extract_h(L_temp << 12);

-

-	Estimate_Speech(st, temp);             /* Estimate speech level */

-	return (VAD_flag);

-}

-

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*      File: wb_vad.c                                                  *
+*                                                                      *
+*      Description: Voice Activity Detection                           *
+*                                                                      *
+************************************************************************/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include "cnst.h"
+#include "wb_vad.h"
+#include "typedef.h"
+#include "basic_op.h"
+#include "math_op.h"
+#include "wb_vad_c.h"
+#include "mem_align.h"
+
+/******************************************************************************
+*  Calculate Log2 and scale the signal:
+*
+*    ilog2(Word32 in) = -1024*log10(in * 2^-31)/log10(2), where in = [1, 2^31-1]
+*
+*  input   output
+*  32768   16384
+*  1       31744
+*
+* When input is in the range of [1,2^16], max error is 0.0380%.
+*********************************************************************************/
+
+static Word16 ilog2(                       /* return: output value of the log2 */
+		Word16 mant                        /* i: value to be converted */
+		)
+{
+	Word16 ex, ex2, res;
+	Word32 i, l_temp;
+
+	if (mant <= 0)
+	{
+		mant = 1;
+	}
+	ex = norm_s(mant);
+	mant = mant << ex;
+
+	for (i = 0; i < 3; i++)
+		mant = vo_mult(mant, mant);
+	l_temp = vo_L_mult(mant, mant);
+
+	ex2 = norm_l(l_temp);
+	mant = extract_h(l_temp << ex2);
+
+	res = (ex + 16) << 10;
+	res = add1(res, (ex2 << 6));
+	res = vo_sub(add1(res, 127), (mant >> 8));
+	return (res);
+}
+
+/******************************************************************************
+*
+*     Function     : filter5
+*     Purpose      : Fifth-order half-band lowpass/highpass filter pair with
+*                    decimation.
+*
+*******************************************************************************/
+
+static void filter5(
+		Word16 * in0,                         /* i/o : input values; output low-pass part  */
+		Word16 * in1,                         /* i/o : input values; output high-pass part */
+		Word16 data[]                         /* i/o : filter memory                       */
+		)
+{
+	Word16 temp0, temp1, temp2;
+
+	temp0 = vo_sub(*in0, vo_mult(COEFF5_1, data[0]));
+	temp1 = add1(data[0], vo_mult(COEFF5_1, temp0));
+	data[0] = temp0;
+
+	temp0 = vo_sub(*in1, vo_mult(COEFF5_2, data[1]));
+	temp2 = add1(data[1], vo_mult(COEFF5_2, temp0));
+	data[1] = temp0;
+
+	*in0 = extract_h((vo_L_add(temp1, temp2) << 15));
+	*in1 = extract_h((vo_L_sub(temp1, temp2) << 15));
+}
+
+/******************************************************************************
+*
+*     Function     : filter3
+*     Purpose      : Third-order half-band lowpass/highpass filter pair with
+*                    decimation.
+*
+*******************************************************************************/
+
+static void filter3(
+		Word16 * in0,                         /* i/o : input values; output low-pass part  */
+		Word16 * in1,                         /* i/o : input values; output high-pass part */
+		Word16 * data                         /* i/o : filter memory                       */
+		)
+{
+	Word16 temp1, temp2;
+
+	temp1 = vo_sub(*in1, vo_mult(COEFF3, *data));
+	temp2 = add1(*data, vo_mult(COEFF3, temp1));
+	*data = temp1;
+
+	*in1 = extract_h((vo_L_sub(*in0, temp2) << 15));
+	*in0 = extract_h((vo_L_add(*in0, temp2) << 15));
+}
+
+/******************************************************************************
+*
+*     Function   : level_calculation
+*     Purpose    : Calculate signal level in a sub-band. Level is calculated
+*                  by summing absolute values of the input data.
+*
+*                  Signal level calculated from of the end of the frame
+*                  (data[count1 - count2]) is stored to (*sub_level)
+*                  and added to the level of the next frame.
+*
+******************************************************************************/
+
+static Word16 level_calculation(                      /* return: signal level */
+		Word16 data[],                        /* i   : signal buffer                                    */
+		Word16 * sub_level,                   /* i   : level calculated at the end of the previous frame*/
+		                                      /* o   : level of signal calculated from the last         */
+		                                      /*       (count2 - count1) samples                        */
+		Word16 count1,                        /* i   : number of samples to be counted                  */
+		Word16 count2,                        /* i   : number of samples to be counted                  */
+		Word16 ind_m,                         /* i   : step size for the index of the data buffer       */
+		Word16 ind_a,                         /* i   : starting index of the data buffer                */
+		Word16 scale                          /* i   : scaling for the level calculation                */
+		)
+{
+	Word32 i, l_temp1, l_temp2;
+	Word16 level;
+
+	l_temp1 = 0L;
+	for (i = count1; i < count2; i++)
+	{
+		l_temp1 += (abs_s(data[ind_m * i + ind_a])<<1);
+	}
+
+	l_temp2 = vo_L_add(l_temp1, L_shl(*sub_level, 16 - scale));
+	*sub_level = extract_h(L_shl(l_temp1, scale));
+
+	for (i = 0; i < count1; i++)
+	{
+		l_temp2 += (abs_s(data[ind_m * i + ind_a])<<1);
+	}
+	level = extract_h(L_shl2(l_temp2, scale));
+
+	return level;
+}
+
+/******************************************************************************
+*
+*     Function     : filter_bank
+*     Purpose      : Divide input signal into bands and calculate level of
+*                    the signal in each band
+*
+*******************************************************************************/
+
+static void filter_bank(
+		VadVars * st,                         /* i/o : State struct               */
+		Word16 in[],                          /* i   : input frame                */
+		Word16 level[]                        /* o   : signal levels at each band */
+		)
+{
+	Word32 i;
+	Word16 tmp_buf[FRAME_LEN];
+
+	/* shift input 1 bit down for safe scaling */
+	for (i = 0; i < FRAME_LEN; i++)
+	{
+		tmp_buf[i] = in[i] >> 1;
+	}
+
+	/* run the filter bank */
+	for (i = 0; i < 128; i++)
+	{
+		filter5(&tmp_buf[2 * i], &tmp_buf[2 * i + 1], st->a_data5[0]);
+	}
+	for (i = 0; i < 64; i++)
+	{
+		filter5(&tmp_buf[4 * i], &tmp_buf[4 * i + 2], st->a_data5[1]);
+		filter5(&tmp_buf[4 * i + 1], &tmp_buf[4 * i + 3], st->a_data5[2]);
+	}
+	for (i = 0; i < 32; i++)
+	{
+		filter5(&tmp_buf[8 * i], &tmp_buf[8 * i + 4], st->a_data5[3]);
+		filter5(&tmp_buf[8 * i + 2], &tmp_buf[8 * i + 6], st->a_data5[4]);
+		filter3(&tmp_buf[8 * i + 3], &tmp_buf[8 * i + 7], &st->a_data3[0]);
+	}
+	for (i = 0; i < 16; i++)
+	{
+		filter3(&tmp_buf[16 * i + 0], &tmp_buf[16 * i + 8], &st->a_data3[1]);
+		filter3(&tmp_buf[16 * i + 4], &tmp_buf[16 * i + 12], &st->a_data3[2]);
+		filter3(&tmp_buf[16 * i + 6], &tmp_buf[16 * i + 14], &st->a_data3[3]);
+	}
+
+	for (i = 0; i < 8; i++)
+	{
+		filter3(&tmp_buf[32 * i + 0], &tmp_buf[32 * i + 16], &st->a_data3[4]);
+		filter3(&tmp_buf[32 * i + 8], &tmp_buf[32 * i + 24], &st->a_data3[5]);
+	}
+
+	/* calculate levels in each frequency band */
+
+	/* 4800 - 6400 Hz */
+	level[11] = level_calculation(tmp_buf, &st->sub_level[11], 16, 64, 4, 1, 14);
+	/* 4000 - 4800 Hz */
+	level[10] = level_calculation(tmp_buf, &st->sub_level[10], 8, 32, 8, 7, 15);
+	/* 3200 - 4000 Hz */
+	level[9] = level_calculation(tmp_buf, &st->sub_level[9],8, 32, 8, 3, 15);
+	/* 2400 - 3200 Hz */
+	level[8] = level_calculation(tmp_buf, &st->sub_level[8],8, 32, 8, 2, 15);
+	/* 2000 - 2400 Hz */
+	level[7] = level_calculation(tmp_buf, &st->sub_level[7],4, 16, 16, 14, 16);
+	/* 1600 - 2000 Hz */
+	level[6] = level_calculation(tmp_buf, &st->sub_level[6],4, 16, 16, 6, 16);
+	/* 1200 - 1600 Hz */
+	level[5] = level_calculation(tmp_buf, &st->sub_level[5],4, 16, 16, 4, 16);
+	/* 800 - 1200 Hz */
+	level[4] = level_calculation(tmp_buf, &st->sub_level[4],4, 16, 16, 12, 16);
+	/* 600 - 800 Hz */
+	level[3] = level_calculation(tmp_buf, &st->sub_level[3],2, 8, 32, 8, 17);
+	/* 400 - 600 Hz */
+	level[2] = level_calculation(tmp_buf, &st->sub_level[2],2, 8, 32, 24, 17);
+	/* 200 - 400 Hz */
+	level[1] = level_calculation(tmp_buf, &st->sub_level[1],2, 8, 32, 16, 17);
+	/* 0 - 200 Hz */
+	level[0] = level_calculation(tmp_buf, &st->sub_level[0],2, 8, 32, 0, 17);
+}
+
+/******************************************************************************
+*
+*     Function   : update_cntrl
+*     Purpose    : Control update of the background noise estimate.
+*
+*******************************************************************************/
+
+static void update_cntrl(
+		VadVars * st,                         /* i/o : State structure                    */
+		Word16 level[]                        /* i   : sub-band levels of the input frame */
+		)
+{
+	Word32 i;
+	Word16 num, temp, stat_rat, exp, denom;
+	Word16 alpha;
+
+	/* if a tone has been detected for a while, initialize stat_count */
+	if (sub((Word16) (st->tone_flag & 0x7c00), 0x7c00) == 0)
+	{
+		st->stat_count = STAT_COUNT;
+	} else
+	{
+		/* if 8 last vad-decisions have been "0", reinitialize stat_count */
+		if ((st->vadreg & 0x7f80) == 0)
+		{
+			st->stat_count = STAT_COUNT;
+		} else
+		{
+			stat_rat = 0;
+			for (i = 0; i < COMPLEN; i++)
+			{
+				if(level[i] > st->ave_level[i])
+				{
+					num = level[i];
+					denom = st->ave_level[i];
+				} else
+				{
+					num = st->ave_level[i];
+					denom = level[i];
+				}
+				/* Limit nimimum value of num and denom to STAT_THR_LEVEL */
+				if(num < STAT_THR_LEVEL)
+				{
+					num = STAT_THR_LEVEL;
+				}
+				if(denom < STAT_THR_LEVEL)
+				{
+					denom = STAT_THR_LEVEL;
+				}
+				exp = norm_s(denom);
+				denom = denom << exp;
+
+				/* stat_rat = num/denom * 64 */
+				temp = div_s(num >> 1, denom);
+				stat_rat = add1(stat_rat, shr(temp, (8 - exp)));
+			}
+
+			/* compare stat_rat with a threshold and update stat_count */
+			if(stat_rat > STAT_THR)
+			{
+				st->stat_count = STAT_COUNT;
+			} else
+			{
+				if ((st->vadreg & 0x4000) != 0)
+				{
+
+					if (st->stat_count != 0)
+					{
+						st->stat_count = st->stat_count - 1;
+					}
+				}
+			}
+		}
+	}
+
+	/* Update average amplitude estimate for stationarity estimation */
+	alpha = ALPHA4;
+	if(st->stat_count == STAT_COUNT)
+	{
+		alpha = 32767;
+	} else if ((st->vadreg & 0x4000) == 0)
+	{
+		alpha = ALPHA5;
+	}
+	for (i = 0; i < COMPLEN; i++)
+	{
+		st->ave_level[i] = add1(st->ave_level[i], vo_mult_r(alpha, vo_sub(level[i], st->ave_level[i])));
+	}
+}
+
+/******************************************************************************
+*
+*     Function     : hangover_addition
+*     Purpose      : Add hangover after speech bursts
+*
+*******************************************************************************/
+
+static Word16 hangover_addition(                      /* return: VAD_flag indicating final VAD decision */
+		VadVars * st,                         /* i/o : State structure                     */
+		Word16 low_power,                     /* i   : flag power of the input frame    */
+		Word16 hang_len,                      /* i   : hangover length */
+		Word16 burst_len                      /* i   : minimum burst length for hangover addition */
+		)
+{
+	/* if the input power (pow_sum) is lower than a threshold, clear counters and set VAD_flag to "0"         */
+	if (low_power != 0)
+	{
+		st->burst_count = 0;
+		st->hang_count = 0;
+		return 0;
+	}
+	/* update the counters (hang_count, burst_count) */
+	if ((st->vadreg & 0x4000) != 0)
+	{
+		st->burst_count = st->burst_count + 1;
+		if(st->burst_count >= burst_len)
+		{
+			st->hang_count = hang_len;
+		}
+		return 1;
+	} else
+	{
+		st->burst_count = 0;
+		if (st->hang_count > 0)
+		{
+			st->hang_count = st->hang_count - 1;
+			return 1;
+		}
+	}
+	return 0;
+}
+
+/******************************************************************************
+*
+*     Function   : noise_estimate_update
+*     Purpose    : Update of background noise estimate
+*
+*******************************************************************************/
+
+static void noise_estimate_update(
+		VadVars * st,                         /* i/o : State structure                       */
+		Word16 level[]                        /* i   : sub-band levels of the input frame */
+		)
+{
+	Word32 i;
+	Word16 alpha_up, alpha_down, bckr_add = 2;
+
+	/* Control update of bckr_est[] */
+	update_cntrl(st, level);
+
+	/* Choose update speed */
+	if ((0x7800 & st->vadreg) == 0)
+	{
+		alpha_up = ALPHA_UP1;
+		alpha_down = ALPHA_DOWN1;
+	} else
+	{
+		if ((st->stat_count == 0))
+		{
+			alpha_up = ALPHA_UP2;
+			alpha_down = ALPHA_DOWN2;
+		} else
+		{
+			alpha_up = 0;
+			alpha_down = ALPHA3;
+			bckr_add = 0;
+		}
+	}
+
+	/* Update noise estimate (bckr_est) */
+	for (i = 0; i < COMPLEN; i++)
+	{
+		Word16 temp;
+		temp = (st->old_level[i] - st->bckr_est[i]);
+
+		if (temp < 0)
+		{                                  /* update downwards */
+			st->bckr_est[i] = add1(-2, add(st->bckr_est[i],vo_mult_r(alpha_down, temp)));
+			/* limit minimum value of the noise estimate to NOISE_MIN */
+			if(st->bckr_est[i] < NOISE_MIN)
+			{
+				st->bckr_est[i] = NOISE_MIN;
+			}
+		} else
+		{                                  /* update upwards */
+			st->bckr_est[i] = add1(bckr_add, add1(st->bckr_est[i],vo_mult_r(alpha_up, temp)));
+
+			/* limit maximum value of the noise estimate to NOISE_MAX */
+			if(st->bckr_est[i] > NOISE_MAX)
+			{
+				st->bckr_est[i] = NOISE_MAX;
+			}
+		}
+	}
+
+	/* Update signal levels of the previous frame (old_level) */
+	for (i = 0; i < COMPLEN; i++)
+	{
+		st->old_level[i] = level[i];
+	}
+}
+
+/******************************************************************************
+*
+*     Function     : vad_decision
+*     Purpose      : Calculates VAD_flag
+*
+*******************************************************************************/
+
+static Word16 vad_decision(                           /* return value : VAD_flag */
+		VadVars * st,                         /* i/o : State structure                       */
+		Word16 level[COMPLEN],                /* i   : sub-band levels of the input frame */
+		Word32 pow_sum                        /* i   : power of the input frame           */
+		)
+{
+	Word32 i;
+	Word32 L_snr_sum;
+	Word32 L_temp;
+	Word16 vad_thr, temp, noise_level;
+	Word16 low_power_flag;
+	Word16 hang_len, burst_len;
+	Word16 ilog2_speech_level, ilog2_noise_level;
+	Word16 temp2;
+
+	/* Calculate squared sum of the input levels (level) divided by the background noise components
+	 * (bckr_est). */
+	L_snr_sum = 0;
+	for (i = 0; i < COMPLEN; i++)
+	{
+		Word16 exp;
+
+		exp = norm_s(st->bckr_est[i]);
+		temp = (st->bckr_est[i] << exp);
+		temp = div_s((level[i] >> 1), temp);
+		temp = shl(temp, (exp - (UNIRSHFT - 1)));
+		L_snr_sum = L_mac(L_snr_sum, temp, temp);
+	}
+
+	/* Calculate average level of estimated background noise */
+	L_temp = 0;
+	for (i = 1; i < COMPLEN; i++)          /* ignore lowest band */
+	{
+		L_temp = vo_L_add(L_temp, st->bckr_est[i]);
+	}
+
+	noise_level = extract_h((L_temp << 12));
+	/* if SNR is lower than a threshold (MIN_SPEECH_SNR), and increase speech_level */
+	temp = vo_mult(noise_level, MIN_SPEECH_SNR) << 3;
+
+	if(st->speech_level < temp)
+	{
+		st->speech_level = temp;
+	}
+	ilog2_noise_level = ilog2(noise_level);
+
+	/* If SNR is very poor, speech_level is probably corrupted by noise level. This is correctred by
+	 * subtracting MIN_SPEECH_SNR*noise_level from speech level */
+	ilog2_speech_level = ilog2(st->speech_level - temp);
+
+	temp = add1(vo_mult(NO_SLOPE, (ilog2_noise_level - NO_P1)), THR_HIGH);
+
+	temp2 = add1(SP_CH_MIN, vo_mult(SP_SLOPE, (ilog2_speech_level - SP_P1)));
+	if (temp2 < SP_CH_MIN)
+	{
+		temp2 = SP_CH_MIN;
+	}
+	if (temp2 > SP_CH_MAX)
+	{
+		temp2 = SP_CH_MAX;
+	}
+	vad_thr = temp + temp2;
+
+	if(vad_thr < THR_MIN)
+	{
+		vad_thr = THR_MIN;
+	}
+	/* Shift VAD decision register */
+	st->vadreg = (st->vadreg >> 1);
+
+	/* Make intermediate VAD decision */
+	if(L_snr_sum > vo_L_mult(vad_thr, (512 * COMPLEN)))
+	{
+		st->vadreg = (Word16) (st->vadreg | 0x4000);
+	}
+	/* check if the input power (pow_sum) is lower than a threshold" */
+	if(pow_sum < VAD_POW_LOW)
+	{
+		low_power_flag = 1;
+	} else
+	{
+		low_power_flag = 0;
+	}
+	/* Update background noise estimates */
+	noise_estimate_update(st, level);
+
+	/* Calculate values for hang_len and burst_len based on vad_thr */
+	hang_len = add1(vo_mult(HANG_SLOPE, (vad_thr - HANG_P1)), HANG_HIGH);
+	if(hang_len < HANG_LOW)
+	{
+		hang_len = HANG_LOW;
+	}
+	burst_len = add1(vo_mult(BURST_SLOPE, (vad_thr - BURST_P1)), BURST_HIGH);
+
+	return (hangover_addition(st, low_power_flag, hang_len, burst_len));
+}
+
+/******************************************************************************
+*
+*     Function : Estimate_Speech()
+*     Purpose  : Estimate speech level
+*
+* Maximum signal level is searched and stored to the variable sp_max.
+* The speech frames must locate within SP_EST_COUNT number of frames.
+* Thus, noisy frames having occasional VAD = "1" decisions will not
+* affect to the estimated speech_level.
+*
+*******************************************************************************/
+
+static void Estimate_Speech(
+		VadVars * st,                         /* i/o : State structure    */
+		Word16 in_level                       /* level of the input frame */
+		)
+{
+	Word16 alpha;
+
+	/* if the required activity count cannot be achieved, reset counters */
+	if((st->sp_est_cnt - st->sp_max_cnt) > (SP_EST_COUNT - SP_ACTIVITY_COUNT))
+	{
+		st->sp_est_cnt = 0;
+		st->sp_max = 0;
+		st->sp_max_cnt = 0;
+	}
+	st->sp_est_cnt += 1;
+
+	if (((st->vadreg & 0x4000)||(in_level > st->speech_level)) && (in_level > MIN_SPEECH_LEVEL1))
+	{
+		/* update sp_max */
+		if(in_level > st->sp_max)
+		{
+			st->sp_max = in_level;
+		}
+		st->sp_max_cnt += 1;
+
+		if(st->sp_max_cnt >= SP_ACTIVITY_COUNT)
+		{
+			Word16 tmp;
+			/* update speech estimate */
+			tmp = (st->sp_max >> 1);      /* scale to get "average" speech level */
+
+			/* select update speed */
+			if(tmp > st->speech_level)
+			{
+				alpha = ALPHA_SP_UP;
+			} else
+			{
+				alpha = ALPHA_SP_DOWN;
+			}
+			if(tmp > MIN_SPEECH_LEVEL2)
+			{
+				st->speech_level = add1(st->speech_level, vo_mult_r(alpha, vo_sub(tmp, st->speech_level)));
+			}
+			/* clear all counters used for speech estimation */
+			st->sp_max = 0;
+			st->sp_max_cnt = 0;
+			st->sp_est_cnt = 0;
+		}
+	}
+}
+
+/******************************************************************************
+*
+*  Function:   wb_vad_init
+*  Purpose:    Allocates state memory and initializes state memory
+*
+*******************************************************************************/
+
+Word16 wb_vad_init(                        /* return: non-zero with error, zero for ok. */
+		VadVars ** state,                     /* i/o : State structure    */
+		VO_MEM_OPERATOR *pMemOP
+		)
+{
+	VadVars *s;
+
+	if (state == (VadVars **) NULL)
+	{
+		fprintf(stderr, "vad_init: invalid parameter\n");
+		return -1;
+	}
+	*state = NULL;
+
+	/* allocate memory */
+	if ((s = (VadVars *) mem_malloc(pMemOP, sizeof(VadVars), 32, VO_INDEX_ENC_AMRWB)) == NULL)
+	{
+		fprintf(stderr, "vad_init: can not malloc state structure\n");
+		return -1;
+	}
+	wb_vad_reset(s);
+
+	*state = s;
+
+	return 0;
+}
+
+/******************************************************************************
+*
+*  Function:   wb_vad_reset
+*  Purpose:    Initializes state memory
+*
+*******************************************************************************/
+
+Word16 wb_vad_reset(                       /* return: non-zero with error, zero for ok. */
+		VadVars * state                       /* i/o : State structure    */
+		)
+{
+	Word32 i, j;
+
+	if (state == (VadVars *) NULL)
+	{
+		fprintf(stderr, "vad_reset: invalid parameter\n");
+		return -1;
+	}
+	state->tone_flag = 0;
+	state->vadreg = 0;
+	state->hang_count = 0;
+	state->burst_count = 0;
+	state->hang_count = 0;
+
+	/* initialize memory used by the filter bank */
+	for (i = 0; i < F_5TH_CNT; i++)
+	{
+		for (j = 0; j < 2; j++)
+		{
+			state->a_data5[i][j] = 0;
+		}
+	}
+
+	for (i = 0; i < F_3TH_CNT; i++)
+	{
+		state->a_data3[i] = 0;
+	}
+
+	/* initialize the rest of the memory */
+	for (i = 0; i < COMPLEN; i++)
+	{
+		state->bckr_est[i] = NOISE_INIT;
+		state->old_level[i] = NOISE_INIT;
+		state->ave_level[i] = NOISE_INIT;
+		state->sub_level[i] = 0;
+	}
+
+	state->sp_est_cnt = 0;
+	state->sp_max = 0;
+	state->sp_max_cnt = 0;
+	state->speech_level = SPEECH_LEVEL_INIT;
+	state->prev_pow_sum = 0;
+	return 0;
+}
+
+/******************************************************************************
+*
+*  Function:   wb_vad_exit
+*  Purpose:    The memory used for state memory is freed
+*
+*******************************************************************************/
+
+void wb_vad_exit(
+		VadVars ** state,                      /* i/o : State structure    */
+		VO_MEM_OPERATOR *pMemOP
+		)
+{
+	if (state == NULL || *state == NULL)
+		return;
+	/* deallocate memory */
+	mem_free(pMemOP, *state, VO_INDEX_ENC_AMRWB);
+	*state = NULL;
+	return;
+}
+
+/******************************************************************************
+*
+*     Function     : wb_vad_tone_detection
+*     Purpose      : Search maximum pitch gain from a frame. Set tone flag if
+*                    pitch gain is high. This is used to detect
+*                    signaling tones and other signals with high pitch gain.
+*
+*******************************************************************************/
+
+void wb_vad_tone_detection(
+		VadVars * st,                         /* i/o : State struct            */
+		Word16 p_gain                         /* pitch gain      */
+		)
+{
+	/* update tone flag */
+	st->tone_flag = (st->tone_flag >> 1);
+
+	/* if (pitch_gain > TONE_THR) set tone flag */
+	if (p_gain > TONE_THR)
+	{
+		st->tone_flag = (Word16) (st->tone_flag | 0x4000);
+	}
+}
+
+/******************************************************************************
+*
+*     Function     : wb_vad
+*     Purpose      : Main program for Voice Activity Detection (VAD) for AMR
+*
+*******************************************************************************/
+
+Word16 wb_vad(                                /* Return value : VAD Decision, 1 = speech, 0 = noise */
+		VadVars * st,                         /* i/o : State structure                 */
+		Word16 in_buf[]                       /* i   : samples of the input frame   */
+	     )
+{
+	Word16 level[COMPLEN];
+	Word32 i;
+	Word16 VAD_flag, temp;
+	Word32 L_temp, pow_sum;
+
+	/* Calculate power of the input frame. */
+	L_temp = 0L;
+	for (i = 0; i < FRAME_LEN; i++)
+	{
+		L_temp = L_mac(L_temp, in_buf[i], in_buf[i]);
+	}
+
+	/* pow_sum = power of current frame and previous frame */
+	pow_sum = L_add(L_temp, st->prev_pow_sum);
+
+	/* save power of current frame for next call */
+	st->prev_pow_sum = L_temp;
+
+	/* If input power is very low, clear tone flag */
+	if (pow_sum < POW_TONE_THR)
+	{
+		st->tone_flag = (Word16) (st->tone_flag & 0x1fff);
+	}
+	/* Run the filter bank and calculate signal levels at each band */
+	filter_bank(st, in_buf, level);
+
+	/* compute VAD decision */
+	VAD_flag = vad_decision(st, level, pow_sum);
+
+	/* Calculate input level */
+	L_temp = 0;
+	for (i = 1; i < COMPLEN; i++)          /* ignore lowest band */
+	{
+		L_temp = vo_L_add(L_temp, level[i]);
+	}
+
+	temp = extract_h(L_temp << 12);
+
+	Estimate_Speech(st, temp);             /* Estimate speech level */
+	return (VAD_flag);
+}
+
+
+
+
diff --git a/media/libstagefright/codecs/amrwbenc/src/weight_a.c b/media/libstagefright/codecs/amrwbenc/src/weight_a.c
index d47be97..a02b48d 100644
--- a/media/libstagefright/codecs/amrwbenc/src/weight_a.c
+++ b/media/libstagefright/codecs/amrwbenc/src/weight_a.c
@@ -1,48 +1,48 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-

-/***********************************************************************

-*       File: weight_a.c                                               *

-*                                                                      *

-*       Description:Weighting of LPC coefficients                      *

-*	               ap[i] = a[i] * (gamma ** i)                     *

-*                                                                      * 

-************************************************************************/

-

-#include "typedef.h"

-#include "basic_op.h"

-

-void Weight_a(

-		Word16 a[],                           /* (i) Q12 : a[m+1]  LPC coefficients             */

-		Word16 ap[],                          /* (o) Q12 : Spectral expanded LPC coefficients   */

-		Word16 gamma,                         /* (i) Q15 : Spectral expansion factor.           */

-		Word16 m                              /* (i)     : LPC order.                           */

-	     )

-{

-	Word32 num = m - 1, fac;

-	*ap++ = *a++;

-	fac = gamma;

-	do{

-		*ap++ =(Word16)(((vo_L_mult((*a++), fac)) + 0x8000) >> 16);

-		fac = (vo_L_mult(fac, gamma) + 0x8000) >> 16;

-	}while(--num != 0);

-

-	*ap++ = (Word16)(((vo_L_mult((*a++), fac)) + 0x8000) >> 16);

-	return;

-}

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+/***********************************************************************
+*       File: weight_a.c                                               *
+*                                                                      *
+*       Description:Weighting of LPC coefficients                      *
+*	               ap[i] = a[i] * (gamma ** i)                     *
+*                                                                      *
+************************************************************************/
+
+#include "typedef.h"
+#include "basic_op.h"
+
+void Weight_a(
+		Word16 a[],                           /* (i) Q12 : a[m+1]  LPC coefficients             */
+		Word16 ap[],                          /* (o) Q12 : Spectral expanded LPC coefficients   */
+		Word16 gamma,                         /* (i) Q15 : Spectral expansion factor.           */
+		Word16 m                              /* (i)     : LPC order.                           */
+	     )
+{
+	Word32 num = m - 1, fac;
+	*ap++ = *a++;
+	fac = gamma;
+	do{
+		*ap++ =(Word16)(((vo_L_mult((*a++), fac)) + 0x8000) >> 16);
+		fac = (vo_L_mult(fac, gamma) + 0x8000) >> 16;
+	}while(--num != 0);
+
+	*ap++ = (Word16)(((vo_L_mult((*a++), fac)) + 0x8000) >> 16);
+	return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/common/Config.mk b/media/libstagefright/codecs/common/Config.mk
index 27a17c1..187f25c 100644
--- a/media/libstagefright/codecs/common/Config.mk
+++ b/media/libstagefright/codecs/common/Config.mk
@@ -1,24 +1,24 @@
-# 

-# This configure file is just for Linux projects against Android

-#

-

-VOPRJ := 

-VONJ :=

-

-# WARNING:

-# Using v7 breaks generic build

-ifeq ($(TARGET_ARCH),arm)

-VOTT := v5

-else

-VOTT := pc

-endif

-

-# Do we also need to check on ARCH_ARM_HAVE_ARMV7A? - probably not

-ifeq ($(ARCH_ARM_HAVE_NEON),true)

-VOTT := v7

-endif

-

-VOTEST := 0

-

-VO_CFLAGS:=-DLINUX 

-

+#
+# This configure file is just for Linux projects against Android
+#
+
+VOPRJ :=
+VONJ :=
+
+# WARNING:
+# Using v7 breaks generic build
+ifeq ($(TARGET_ARCH),arm)
+VOTT := v5
+else
+VOTT := pc
+endif
+
+# Do we also need to check on ARCH_ARM_HAVE_ARMV7A? - probably not
+ifeq ($(ARCH_ARM_HAVE_NEON),true)
+VOTT := v7
+endif
+
+VOTEST := 0
+
+VO_CFLAGS:=-DLINUX
+
diff --git a/media/libstagefright/codecs/common/cmnMemory.c b/media/libstagefright/codecs/common/cmnMemory.c
index c17264c..aa52bd9 100644
--- a/media/libstagefright/codecs/common/cmnMemory.c
+++ b/media/libstagefright/codecs/common/cmnMemory.c
@@ -1,73 +1,71 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		cmnMemory.c

-

-	Content:	sample code for memory operator implementation

-

-*******************************************************************************/

-#include "cmnMemory.h"

-

-#include <malloc.h>

-#if defined LINUX

-#include <string.h>

-#endif

-

-//VO_MEM_OPERATOR		g_memOP;

-

-VO_U32 cmnMemAlloc (VO_S32 uID,  VO_MEM_INFO * pMemInfo)

-{

-	if (!pMemInfo)

-		return VO_ERR_INVALID_ARG;

-

-	pMemInfo->VBuffer = malloc (pMemInfo->Size);

-	return 0;

-}

-

-VO_U32 cmnMemFree (VO_S32 uID, VO_PTR pMem)

-{

-	free (pMem);

-	return 0;

-}

-

-VO_U32	cmnMemSet (VO_S32 uID, VO_PTR pBuff, VO_U8 uValue, VO_U32 uSize)

-{

-	memset (pBuff, uValue, uSize);

-	return 0;

-}

-

-VO_U32	cmnMemCopy (VO_S32 uID, VO_PTR pDest, VO_PTR pSource, VO_U32 uSize)

-{

-	memcpy (pDest, pSource, uSize);

-	return 0;

-}

-

-VO_U32	cmnMemCheck (VO_S32 uID, VO_PTR pBuffer, VO_U32 uSize)

-{

-	return 0;

-}

-

-VO_S32 cmnMemCompare (VO_S32 uID, VO_PTR pBuffer1, VO_PTR pBuffer2, VO_U32 uSize)

-{

-	return memcmp(pBuffer1, pBuffer2, uSize);

-}

-

-VO_U32	cmnMemMove (VO_S32 uID, VO_PTR pDest, VO_PTR pSource, VO_U32 uSize)

-{

-	memmove (pDest, pSource, uSize);

-	return 0;

-}

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		cmnMemory.c
+
+	Content:	sample code for memory operator implementation
+
+*******************************************************************************/
+#include "cmnMemory.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+//VO_MEM_OPERATOR		g_memOP;
+
+VO_U32 cmnMemAlloc (VO_S32 uID,  VO_MEM_INFO * pMemInfo)
+{
+	if (!pMemInfo)
+		return VO_ERR_INVALID_ARG;
+
+	pMemInfo->VBuffer = malloc (pMemInfo->Size);
+	return 0;
+}
+
+VO_U32 cmnMemFree (VO_S32 uID, VO_PTR pMem)
+{
+	free (pMem);
+	return 0;
+}
+
+VO_U32	cmnMemSet (VO_S32 uID, VO_PTR pBuff, VO_U8 uValue, VO_U32 uSize)
+{
+	memset (pBuff, uValue, uSize);
+	return 0;
+}
+
+VO_U32	cmnMemCopy (VO_S32 uID, VO_PTR pDest, VO_PTR pSource, VO_U32 uSize)
+{
+	memcpy (pDest, pSource, uSize);
+	return 0;
+}
+
+VO_U32	cmnMemCheck (VO_S32 uID, VO_PTR pBuffer, VO_U32 uSize)
+{
+	return 0;
+}
+
+VO_S32 cmnMemCompare (VO_S32 uID, VO_PTR pBuffer1, VO_PTR pBuffer2, VO_U32 uSize)
+{
+	return memcmp(pBuffer1, pBuffer2, uSize);
+}
+
+VO_U32	cmnMemMove (VO_S32 uID, VO_PTR pDest, VO_PTR pSource, VO_U32 uSize)
+{
+	memmove (pDest, pSource, uSize);
+	return 0;
+}
+
diff --git a/media/libstagefright/codecs/common/include/cmnMemory.h b/media/libstagefright/codecs/common/include/cmnMemory.h
index 9315600..0308dfa 100644
--- a/media/libstagefright/codecs/common/include/cmnMemory.h
+++ b/media/libstagefright/codecs/common/include/cmnMemory.h
@@ -1,106 +1,106 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		cmnMemory.h

-

-	Content:	memory operator implementation header file

-

-*******************************************************************************/

-

-#ifndef __cmnMemory_H__

-#define __cmnMemory_H__

-

-#ifdef __cplusplus

-extern "C" {

-#endif /* __cplusplus */

-

-#include <voMem.h>

-

-//extern VO_MEM_OPERATOR	g_memOP;

-

-/**

- * Allocate memory

- * \param uID [in] module ID

- * \param uSize [in] size of memory

- * \return value is the allocated memory address. NULL is failed.

- */

-VO_U32	cmnMemAlloc (VO_S32 uID,  VO_MEM_INFO * pMemInfo);

-

-/**

- * Free up memory

- * \param uID [in] module ID

- * \param pMem [in] address of memory

- * \return value 0, if succeeded.

- */

-VO_U32	cmnMemFree (VO_S32 uID, VO_PTR pBuffer);

-

-/**

- * memory set function

- * \param uID [in] module ID

- * \param pBuff [in/out] address of memory

- * \param uValue [in] the value to be set

- * \param uSize [in] the size to be set

- * \return value 0, if succeeded.

- */

-VO_U32	cmnMemSet (VO_S32 uID, VO_PTR pBuff, VO_U8 uValue, VO_U32 uSize);

-

-/**

- * memory copy function

- * \param uID [in] module ID

- * \param pDest [in/out] address of destination memory

- * \param pSource [in] address of source memory

- * \param uSize [in] the size to be copied

- * \return value 0, if succeeded.

- */

-VO_U32	cmnMemCopy (VO_S32 uID, VO_PTR pDest, VO_PTR pSource, VO_U32 uSize);

-

-/**

- * memory check function

- * \param uID [in] module ID

- * \param pBuff [in] address of buffer to be checked

- * \param uSize [in] the size to be checked

- * \return value 0, if succeeded.

- */

-VO_U32	cmnMemCheck (VO_S32 uID, VO_PTR pBuffer, VO_U32 uSize);

-

-/**

- * memory compare function

- * \param uID [in] module ID

- * \param pBuffer1 [in] address of buffer 1 to be compared

- * \param pBuffer2 [in] address of buffer 2 to be compared

- * \param uSize [in] the size to be compared

- * \return value: same as standard C run-time memcmp() function.

- */

-VO_S32	cmnMemCompare (VO_S32 uID, VO_PTR pBuffer1, VO_PTR pBuffer2, VO_U32 uSize);

-

-/**

- * memory move function

- * \param uID [in] module ID

- * \param pDest [in/out] address of destination memory

- * \param pSource [in] address of source memory

- * \param uSize [in] the size to be moved

- * \return value 0, if succeeded.

- */

-VO_U32	cmnMemMove (VO_S32 uID, VO_PTR pDest, VO_PTR pSource, VO_U32 uSize);

-

-

-#ifdef __cplusplus

-}

-#endif /* __cplusplus */

-

-#endif // __cmnMemory_H__

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		cmnMemory.h
+
+	Content:	memory operator implementation header file
+
+*******************************************************************************/
+
+#ifndef __cmnMemory_H__
+#define __cmnMemory_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+#include <voMem.h>
+
+//extern VO_MEM_OPERATOR	g_memOP;
+
+/**
+ * Allocate memory
+ * \param uID [in] module ID
+ * \param uSize [in] size of memory
+ * \return value is the allocated memory address. NULL is failed.
+ */
+VO_U32	cmnMemAlloc (VO_S32 uID,  VO_MEM_INFO * pMemInfo);
+
+/**
+ * Free up memory
+ * \param uID [in] module ID
+ * \param pMem [in] address of memory
+ * \return value 0, if succeeded.
+ */
+VO_U32	cmnMemFree (VO_S32 uID, VO_PTR pBuffer);
+
+/**
+ * memory set function
+ * \param uID [in] module ID
+ * \param pBuff [in/out] address of memory
+ * \param uValue [in] the value to be set
+ * \param uSize [in] the size to be set
+ * \return value 0, if succeeded.
+ */
+VO_U32	cmnMemSet (VO_S32 uID, VO_PTR pBuff, VO_U8 uValue, VO_U32 uSize);
+
+/**
+ * memory copy function
+ * \param uID [in] module ID
+ * \param pDest [in/out] address of destination memory
+ * \param pSource [in] address of source memory
+ * \param uSize [in] the size to be copied
+ * \return value 0, if succeeded.
+ */
+VO_U32	cmnMemCopy (VO_S32 uID, VO_PTR pDest, VO_PTR pSource, VO_U32 uSize);
+
+/**
+ * memory check function
+ * \param uID [in] module ID
+ * \param pBuff [in] address of buffer to be checked
+ * \param uSize [in] the size to be checked
+ * \return value 0, if succeeded.
+ */
+VO_U32	cmnMemCheck (VO_S32 uID, VO_PTR pBuffer, VO_U32 uSize);
+
+/**
+ * memory compare function
+ * \param uID [in] module ID
+ * \param pBuffer1 [in] address of buffer 1 to be compared
+ * \param pBuffer2 [in] address of buffer 2 to be compared
+ * \param uSize [in] the size to be compared
+ * \return value: same as standard C run-time memcmp() function.
+ */
+VO_S32	cmnMemCompare (VO_S32 uID, VO_PTR pBuffer1, VO_PTR pBuffer2, VO_U32 uSize);
+
+/**
+ * memory move function
+ * \param uID [in] module ID
+ * \param pDest [in/out] address of destination memory
+ * \param pSource [in] address of source memory
+ * \param uSize [in] the size to be moved
+ * \return value 0, if succeeded.
+ */
+VO_U32	cmnMemMove (VO_S32 uID, VO_PTR pDest, VO_PTR pSource, VO_U32 uSize);
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif // __cmnMemory_H__
+
+
diff --git a/media/libstagefright/codecs/common/include/voAAC.h b/media/libstagefright/codecs/common/include/voAAC.h
index d11ed83..9ecb142 100644
--- a/media/libstagefright/codecs/common/include/voAAC.h
+++ b/media/libstagefright/codecs/common/include/voAAC.h
@@ -1,74 +1,74 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		voAAC.h

-

-	Content:	AAC codec APIs & data types

-

-*******************************************************************************/

-

-#ifndef __voAAC_H__

-#define __voAAC_H__

-

-#ifdef __cplusplus

-extern "C" {

-#endif /* __cplusplus */

-

-#include "voAudio.h"

-

-/*!

- * the frame type that the decoder supports

- */

-typedef enum {

-	VOAAC_RAWDATA			= 0,	/*!<contains only raw aac data in a frame*/

-	VOAAC_ADTS				= 1,	/*!<contains ADTS header + raw AAC data in a frame*/

-	VOAAC_FT_MAX			= VO_MAX_ENUM_VALUE

-} VOAACFRAMETYPE;

-

-/*!

- * the structure for AAC encoder input parameter

- */

-typedef  struct {

-  int	  sampleRate;          /*! audio file sample rate */

-  int	  bitRate;             /*! encoder bit rate in bits/sec */

-  short   nChannels;		   /*! number of channels on input (1,2) */

-  short   adtsUsed;			   /*! whether write adts header */

-} AACENC_PARAM;

-

-/* AAC Param ID */

-#define VO_PID_AAC_Mdoule				0x42211000

-#define VO_PID_AAC_ENCPARAM				VO_PID_AAC_Mdoule | 0x0040  /*!< get/set AAC encoder parameter, the parameter is a pointer to AACENC_PARAM */

-

-/* AAC decoder error ID */

-#define VO_ERR_AAC_Mdoule				0x82210000

-#define VO_ERR_AAC_UNSFILEFORMAT		(VO_ERR_AAC_Mdoule | 0xF001)

-#define VO_ERR_AAC_UNSPROFILE			(VO_ERR_AAC_Mdoule | 0xF002)

-

-/**

- * Get audio encoder API interface

- * \param pEncHandle [out] Return the AAC Encoder handle.

- * \retval VO_ERR_OK Succeeded.

- */

-VO_S32 VO_API voGetAACEncAPI (VO_AUDIO_CODECAPI * pEncHandle);

-

-#ifdef __cplusplus

-}

-#endif /* __cplusplus */

-

-#endif // __voAAC_H__

-

-

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		voAAC.h
+
+	Content:	AAC codec APIs & data types
+
+*******************************************************************************/
+
+#ifndef __voAAC_H__
+#define __voAAC_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+#include "voAudio.h"
+
+/*!
+ * the frame type that the decoder supports
+ */
+typedef enum {
+	VOAAC_RAWDATA			= 0,	/*!<contains only raw aac data in a frame*/
+	VOAAC_ADTS				= 1,	/*!<contains ADTS header + raw AAC data in a frame*/
+	VOAAC_FT_MAX			= VO_MAX_ENUM_VALUE
+} VOAACFRAMETYPE;
+
+/*!
+ * the structure for AAC encoder input parameter
+ */
+typedef  struct {
+  int	  sampleRate;          /*! audio file sample rate */
+  int	  bitRate;             /*! encoder bit rate in bits/sec */
+  short   nChannels;		   /*! number of channels on input (1,2) */
+  short   adtsUsed;			   /*! whether write adts header */
+} AACENC_PARAM;
+
+/* AAC Param ID */
+#define VO_PID_AAC_Mdoule				0x42211000
+#define VO_PID_AAC_ENCPARAM				VO_PID_AAC_Mdoule | 0x0040  /*!< get/set AAC encoder parameter, the parameter is a pointer to AACENC_PARAM */
+
+/* AAC decoder error ID */
+#define VO_ERR_AAC_Mdoule				0x82210000
+#define VO_ERR_AAC_UNSFILEFORMAT		(VO_ERR_AAC_Mdoule | 0xF001)
+#define VO_ERR_AAC_UNSPROFILE			(VO_ERR_AAC_Mdoule | 0xF002)
+
+/**
+ * Get audio encoder API interface
+ * \param pEncHandle [out] Return the AAC Encoder handle.
+ * \retval VO_ERR_OK Succeeded.
+ */
+VO_S32 VO_API voGetAACEncAPI (VO_AUDIO_CODECAPI * pEncHandle);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif // __voAAC_H__
+
+
+
diff --git a/media/libstagefright/codecs/common/include/voAMRWB.h b/media/libstagefright/codecs/common/include/voAMRWB.h
index 8a93eb8..d3eb537 100644
--- a/media/libstagefright/codecs/common/include/voAMRWB.h
+++ b/media/libstagefright/codecs/common/include/voAMRWB.h
@@ -1,87 +1,87 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		voAMRWB.h

-

-	Content:	AMR-WB codec APIs & data types

-

-*******************************************************************************/

-#ifndef  __VOAMRWB_H__

-#define  __VOAMRWB_H__

-

-#include  "voAudio.h"

-#ifdef __cplusplus

-extern "C" {

-#endif /* __cplusplus */

-#pragma pack(push, 4)

-

-/*!* the bit rate the codec supports*/

-typedef enum { 

-	VOAMRWB_MDNONE		= -1,	/*!< Invalid mode */

-	VOAMRWB_MD66		= 0,	/*!< 6.60kbps   */

-	VOAMRWB_MD885		= 1,    /*!< 8.85kbps   */       

-	VOAMRWB_MD1265		= 2,	/*!< 12.65kbps  */

-	VOAMRWB_MD1425		= 3,	/*!< 14.25kbps  */

-	VOAMRWB_MD1585		= 4,	/*!< 15.85bps   */

-	VOAMRWB_MD1825		= 5,	/*!< 18.25bps   */

-	VOAMRWB_MD1985		= 6,	/*!< 19.85kbps  */

-	VOAMRWB_MD2305		= 7,    /*!< 23.05kbps  */

-	VOAMRWB_MD2385          = 8,    /*!< 23.85kbps> */	

-	VOAMRWB_N_MODES 	= 9,	/*!< Invalid mode */

-	VOAMRWB_MODE_MAX    = VO_MAX_ENUM_VALUE

-	

-}VOAMRWBMODE;

-

-/*!* the frame format the codec supports*/

-typedef enum {

-	VOAMRWB_DEFAULT  	= 0,	/*!< the frame type is the header (defined in RFC3267) + rawdata*/

-	/*One word (2-byte) for sync word (0x6b21)*/

-	/*One word (2-byte) for frame length N.*/

-	/*N words (2-byte) containing N bits (bit 0 = 0x007f, bit 1 = 0x0081).*/

-	VOAMRWB_ITU         = 1, 

-	/*One word (2-byte) for sync word (0x6b21).*/

-	/*One word (2-byte) to indicate the frame type.*/	

-	/*One word (2-byte) to indicate the mode.*/

-	/*N words  (2-byte) containing N bits (bit 0 = 0xff81, bit 1 = 0x007f).*/

-	VOAMRWB_RFC3267		= 2,	/* see RFC 3267 */  

-    VOAMRWB_TMAX        = VO_MAX_ENUM_VALUE	

-}VOAMRWBFRAMETYPE;

-

-

-#define    VO_PID_AMRWB_Module							0x42261000 

-#define    VO_PID_AMRWB_FORMAT                          (VO_PID_AMRWB_Module | 0x0002)

-#define    VO_PID_AMRWB_CHANNELS                        (VO_PID_AMRWB_Module | 0x0003)

-#define    VO_PID_AMRWB_SAMPLERATE                      (VO_PID_AMRWB_Module | 0x0004)

-#define    VO_PID_AMRWB_FRAMETYPE                       (VO_PID_AMRWB_Module | 0x0005)

-#define    VO_PID_AMRWB_MODE                            (VO_PID_AMRWB_Module | 0x0006)

-#define    VO_PID_AMRWB_DTX                             (VO_PID_AMRWB_Module | 0x0007)

-

-/**

- * Get audio codec API interface

- * \param pEncHandle [out] Return the AMRWB Encoder handle.

- * \retval VO_ERR_OK Succeeded.

- */

-VO_S32 VO_API voGetAMRWBEncAPI(VO_AUDIO_CODECAPI *pEncHandle);

-

-

-#pragma pack(pop)

-#ifdef __cplusplus

-} /* extern "C" */

-#endif /* __cplusplus */

-

-

-#endif   //__VOAMRWB_H__

-

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		voAMRWB.h
+
+	Content:	AMR-WB codec APIs & data types
+
+*******************************************************************************/
+#ifndef  __VOAMRWB_H__
+#define  __VOAMRWB_H__
+
+#include  "voAudio.h"
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#pragma pack(push, 4)
+
+/*!* the bit rate the codec supports*/
+typedef enum {
+	VOAMRWB_MDNONE		= -1,	/*!< Invalid mode */
+	VOAMRWB_MD66		= 0,	/*!< 6.60kbps   */
+	VOAMRWB_MD885		= 1,    /*!< 8.85kbps   */
+	VOAMRWB_MD1265		= 2,	/*!< 12.65kbps  */
+	VOAMRWB_MD1425		= 3,	/*!< 14.25kbps  */
+	VOAMRWB_MD1585		= 4,	/*!< 15.85bps   */
+	VOAMRWB_MD1825		= 5,	/*!< 18.25bps   */
+	VOAMRWB_MD1985		= 6,	/*!< 19.85kbps  */
+	VOAMRWB_MD2305		= 7,    /*!< 23.05kbps  */
+	VOAMRWB_MD2385          = 8,    /*!< 23.85kbps> */
+	VOAMRWB_N_MODES 	= 9,	/*!< Invalid mode */
+	VOAMRWB_MODE_MAX    = VO_MAX_ENUM_VALUE
+
+}VOAMRWBMODE;
+
+/*!* the frame format the codec supports*/
+typedef enum {
+	VOAMRWB_DEFAULT  	= 0,	/*!< the frame type is the header (defined in RFC3267) + rawdata*/
+	/*One word (2-byte) for sync word (0x6b21)*/
+	/*One word (2-byte) for frame length N.*/
+	/*N words (2-byte) containing N bits (bit 0 = 0x007f, bit 1 = 0x0081).*/
+	VOAMRWB_ITU         = 1,
+	/*One word (2-byte) for sync word (0x6b21).*/
+	/*One word (2-byte) to indicate the frame type.*/
+	/*One word (2-byte) to indicate the mode.*/
+	/*N words  (2-byte) containing N bits (bit 0 = 0xff81, bit 1 = 0x007f).*/
+	VOAMRWB_RFC3267		= 2,	/* see RFC 3267 */
+    VOAMRWB_TMAX        = VO_MAX_ENUM_VALUE
+}VOAMRWBFRAMETYPE;
+
+
+#define    VO_PID_AMRWB_Module							0x42261000
+#define    VO_PID_AMRWB_FORMAT                          (VO_PID_AMRWB_Module | 0x0002)
+#define    VO_PID_AMRWB_CHANNELS                        (VO_PID_AMRWB_Module | 0x0003)
+#define    VO_PID_AMRWB_SAMPLERATE                      (VO_PID_AMRWB_Module | 0x0004)
+#define    VO_PID_AMRWB_FRAMETYPE                       (VO_PID_AMRWB_Module | 0x0005)
+#define    VO_PID_AMRWB_MODE                            (VO_PID_AMRWB_Module | 0x0006)
+#define    VO_PID_AMRWB_DTX                             (VO_PID_AMRWB_Module | 0x0007)
+
+/**
+ * Get audio codec API interface
+ * \param pEncHandle [out] Return the AMRWB Encoder handle.
+ * \retval VO_ERR_OK Succeeded.
+ */
+VO_S32 VO_API voGetAMRWBEncAPI(VO_AUDIO_CODECAPI *pEncHandle);
+
+
+#pragma pack(pop)
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+
+#endif   //__VOAMRWB_H__
+
diff --git a/media/libstagefright/codecs/common/include/voAudio.h b/media/libstagefright/codecs/common/include/voAudio.h
index 64c9dfb..d8628ee 100644
--- a/media/libstagefright/codecs/common/include/voAudio.h
+++ b/media/libstagefright/codecs/common/include/voAudio.h
@@ -1,173 +1,173 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		voAudio.h

-

-	Content:	Audio types and functions

-

-*******************************************************************************/

-

-#ifndef __voAudio_H__

-#define __voAudio_H__

-

-#ifdef __cplusplus

-extern "C" {

-#endif /* __cplusplus */

-

-#include "voIndex.h"

-#include "voMem.h"

-

-#define	VO_PID_AUDIO_BASE			 0x42000000							/*!< The base param ID for AUDIO codec */

-#define	VO_PID_AUDIO_FORMAT			(VO_PID_AUDIO_BASE | 0X0001)		/*!< The format data of audio in track */

-#define	VO_PID_AUDIO_SAMPLEREATE	(VO_PID_AUDIO_BASE | 0X0002)		/*!< The sample rate of audio  */

-#define	VO_PID_AUDIO_CHANNELS		(VO_PID_AUDIO_BASE | 0X0003)		/*!< The channel of audio */

-#define	VO_PID_AUDIO_BITRATE		(VO_PID_AUDIO_BASE | 0X0004)		/*!< The bit rate of audio */

-#define VO_PID_AUDIO_CHANNELMODE	(VO_PID_AUDIO_BASE | 0X0005)		/*!< The channel mode of audio */

-

-#define	VO_ERR_AUDIO_BASE			0x82000000

-#define VO_ERR_AUDIO_UNSCHANNEL		VO_ERR_AUDIO_BASE | 0x0001

-#define VO_ERR_AUDIO_UNSSAMPLERATE	VO_ERR_AUDIO_BASE | 0x0002

-#define VO_ERR_AUDIO_UNSFEATURE		VO_ERR_AUDIO_BASE | 0x0003

-

-

-/**

- *Enumeration used to define the possible audio coding formats.

- */

-typedef enum VO_AUDIO_CODINGTYPE {

-	VO_AUDIO_CodingUnused = 0,  /**< Placeholder value when coding is N/A  */

-	VO_AUDIO_CodingPCM,         /**< Any variant of PCM coding */

-	VO_AUDIO_CodingADPCM,       /**< Any variant of ADPCM encoded data */

-	VO_AUDIO_CodingAMRNB,       /**< Any variant of AMR encoded data */

-	VO_AUDIO_CodingAMRWB,       /**< Any variant of AMR encoded data */

-	VO_AUDIO_CodingAMRWBP,      /**< Any variant of AMR encoded data */

-	VO_AUDIO_CodingQCELP13,     /**< Any variant of QCELP 13kbps encoded data */

-	VO_AUDIO_CodingEVRC,        /**< Any variant of EVRC encoded data */

-	VO_AUDIO_CodingAAC,         /**< Any variant of AAC encoded data, 0xA106 - ISO/MPEG-4 AAC, 0xFF - AAC */

-	VO_AUDIO_CodingAC3,         /**< Any variant of AC3 encoded data */

-	VO_AUDIO_CodingFLAC,        /**< Any variant of FLAC encoded data */

-	VO_AUDIO_CodingMP1,			/**< Any variant of MP1 encoded data */

-	VO_AUDIO_CodingMP3,         /**< Any variant of MP3 encoded data */

-	VO_AUDIO_CodingOGG,         /**< Any variant of OGG encoded data */

-	VO_AUDIO_CodingWMA,         /**< Any variant of WMA encoded data */

-	VO_AUDIO_CodingRA,          /**< Any variant of RA encoded data */

-	VO_AUDIO_CodingMIDI,        /**< Any variant of MIDI encoded data */

-	VO_AUDIO_CodingDRA,         /**< Any variant of dra encoded data */

-	VO_AUDIO_CodingG729,        /**< Any variant of dra encoded data */

-	VO_AUDIO_Coding_MAX		= VO_MAX_ENUM_VALUE

-} VO_AUDIO_CODINGTYPE;

-

-/*!

-* the channel type value

-*/

-typedef enum {

-	VO_CHANNEL_CENTER				= 1,	/*!<center channel*/

-	VO_CHANNEL_FRONT_LEFT			= 1<<1,	/*!<front left channel*/

-	VO_CHANNEL_FRONT_RIGHT			= 1<<2,	/*!<front right channel*/

-	VO_CHANNEL_SIDE_LEFT  			= 1<<3, /*!<side left channel*/

-	VO_CHANNEL_SIDE_RIGHT			= 1<<4, /*!<side right channel*/

-	VO_CHANNEL_BACK_LEFT			= 1<<5,	/*!<back left channel*/

-	VO_CHANNEL_BACK_RIGHT			= 1<<6,	/*!<back right channel*/

-	VO_CHANNEL_BACK_CENTER			= 1<<7,	/*!<back center channel*/

-	VO_CHANNEL_LFE_BASS				= 1<<8,	/*!<low-frequency effects bass channel*/

-	VO_CHANNEL_ALL					= 0xffff,/*!<[default] include all channels */

-	VO_CHANNEL_MAX					= VO_MAX_ENUM_VALUE

-} VO_AUDIO_CHANNELTYPE;

-

-/**

- * General audio format info

- */

-typedef struct

-{

-	VO_S32	SampleRate;  /*!< Sample rate */

-	VO_S32	Channels;    /*!< Channel count */

-	VO_S32	SampleBits;  /*!< Bits per sample */

-} VO_AUDIO_FORMAT;

-

-/**

- * General audio output info

- */

-typedef struct

-{

-	VO_AUDIO_FORMAT	Format;			/*!< Sample rate */

-	VO_U32			InputUsed;		/*!< Channel count */

-	VO_U32			Resever;		/*!< Resevered */

-} VO_AUDIO_OUTPUTINFO;

-

-/**

- * General audio codec function set

- */

-typedef struct VO_AUDIO_CODECAPI

-{

-	/**

-	 * Init the audio codec module and return codec handle

-	 * \param phCodec [OUT] Return the video codec handle

-	 * \param vType	[IN] The codec type if the module support multi codec.

-	 * \param pUserData	[IN] The init param. It is either a memory operator or an allocated memory

-	 * \retval VO_ERR_NONE Succeeded.

-	 */

-	VO_U32 (VO_API * Init) (VO_HANDLE * phCodec, VO_AUDIO_CODINGTYPE vType, VO_CODEC_INIT_USERDATA * pUserData );

-

-	/**

-	 * Set input audio data.

-	 * \param hCodec [IN]] The codec handle which was created by Init function.

-	 * \param pInput [IN] The input buffer param.

-	 * \retval VO_ERR_NONE Succeeded.

-	 */

-	VO_U32 (VO_API * SetInputData) (VO_HANDLE hCodec, VO_CODECBUFFER * pInput);

-

-	/**

-	 * Get the outut audio data

-	 * \param hCodec [IN]] The codec handle which was created by Init function.

-	 * \param pOutBuffer [OUT] The output audio data

-	 * \param pOutInfo [OUT] The codec fills audio format and the input data size used in current call.

-	 *						 pOutInfo->InputUsed is total used input data size in byte.

-	 * \retval  VO_ERR_NONE Succeeded.

-	 *			VO_ERR_INPUT_BUFFER_SMALL. The input was finished or the input data was not enought. Continue to input 

-	 *										data before next call.

-	 */

-	VO_U32 (VO_API * GetOutputData) (VO_HANDLE hCodec, VO_CODECBUFFER * pOutBuffer, VO_AUDIO_OUTPUTINFO * pOutInfo);

-

-	/**

-	 * Set the parameter for the specified param ID.

-	 * \param hCodec [IN]] The codec handle which was created by Init function.

-	 * \param uParamID [IN] The param ID.

-	 * \param pData [IN] The param value.

-	 * \retval VO_ERR_NONE Succeeded.

-	 */

-	VO_U32 (VO_API * SetParam) (VO_HANDLE hCodec, VO_S32 uParamID, VO_PTR pData);

-

-	/**

-	 * Get the parameter for the specified param ID.

-	 * \param hCodec [IN]] The codec handle which was created by Init function.

-	 * \param uParamID [IN] The param ID.

-	 * \param pData [IN] The param value.

-	 * \retval VO_ERR_NONE Succeeded.

-	 */

-	VO_U32 (VO_API * GetParam) (VO_HANDLE hCodec, VO_S32 uParamID, VO_PTR pData);

-

-	/**

-	 * Uninit the Codec.

-	 * \param hCodec [IN]] The codec handle which was created by Init function.

-	 * \retval VO_ERR_NONE Succeeded.

-	 */

-	VO_U32 (VO_API * Uninit) (VO_HANDLE hCodec);

-} VO_AUDIO_CODECAPI;

-

-#ifdef __cplusplus

-}

-#endif /* __cplusplus */

-

-#endif // __voAudio_H__

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		voAudio.h
+
+	Content:	Audio types and functions
+
+*******************************************************************************/
+
+#ifndef __voAudio_H__
+#define __voAudio_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+#include "voIndex.h"
+#include "voMem.h"
+
+#define	VO_PID_AUDIO_BASE			 0x42000000							/*!< The base param ID for AUDIO codec */
+#define	VO_PID_AUDIO_FORMAT			(VO_PID_AUDIO_BASE | 0X0001)		/*!< The format data of audio in track */
+#define	VO_PID_AUDIO_SAMPLEREATE	(VO_PID_AUDIO_BASE | 0X0002)		/*!< The sample rate of audio  */
+#define	VO_PID_AUDIO_CHANNELS		(VO_PID_AUDIO_BASE | 0X0003)		/*!< The channel of audio */
+#define	VO_PID_AUDIO_BITRATE		(VO_PID_AUDIO_BASE | 0X0004)		/*!< The bit rate of audio */
+#define VO_PID_AUDIO_CHANNELMODE	(VO_PID_AUDIO_BASE | 0X0005)		/*!< The channel mode of audio */
+
+#define	VO_ERR_AUDIO_BASE			0x82000000
+#define VO_ERR_AUDIO_UNSCHANNEL		VO_ERR_AUDIO_BASE | 0x0001
+#define VO_ERR_AUDIO_UNSSAMPLERATE	VO_ERR_AUDIO_BASE | 0x0002
+#define VO_ERR_AUDIO_UNSFEATURE		VO_ERR_AUDIO_BASE | 0x0003
+
+
+/**
+ *Enumeration used to define the possible audio coding formats.
+ */
+typedef enum VO_AUDIO_CODINGTYPE {
+	VO_AUDIO_CodingUnused = 0,  /**< Placeholder value when coding is N/A  */
+	VO_AUDIO_CodingPCM,         /**< Any variant of PCM coding */
+	VO_AUDIO_CodingADPCM,       /**< Any variant of ADPCM encoded data */
+	VO_AUDIO_CodingAMRNB,       /**< Any variant of AMR encoded data */
+	VO_AUDIO_CodingAMRWB,       /**< Any variant of AMR encoded data */
+	VO_AUDIO_CodingAMRWBP,      /**< Any variant of AMR encoded data */
+	VO_AUDIO_CodingQCELP13,     /**< Any variant of QCELP 13kbps encoded data */
+	VO_AUDIO_CodingEVRC,        /**< Any variant of EVRC encoded data */
+	VO_AUDIO_CodingAAC,         /**< Any variant of AAC encoded data, 0xA106 - ISO/MPEG-4 AAC, 0xFF - AAC */
+	VO_AUDIO_CodingAC3,         /**< Any variant of AC3 encoded data */
+	VO_AUDIO_CodingFLAC,        /**< Any variant of FLAC encoded data */
+	VO_AUDIO_CodingMP1,			/**< Any variant of MP1 encoded data */
+	VO_AUDIO_CodingMP3,         /**< Any variant of MP3 encoded data */
+	VO_AUDIO_CodingOGG,         /**< Any variant of OGG encoded data */
+	VO_AUDIO_CodingWMA,         /**< Any variant of WMA encoded data */
+	VO_AUDIO_CodingRA,          /**< Any variant of RA encoded data */
+	VO_AUDIO_CodingMIDI,        /**< Any variant of MIDI encoded data */
+	VO_AUDIO_CodingDRA,         /**< Any variant of dra encoded data */
+	VO_AUDIO_CodingG729,        /**< Any variant of dra encoded data */
+	VO_AUDIO_Coding_MAX		= VO_MAX_ENUM_VALUE
+} VO_AUDIO_CODINGTYPE;
+
+/*!
+* the channel type value
+*/
+typedef enum {
+	VO_CHANNEL_CENTER				= 1,	/*!<center channel*/
+	VO_CHANNEL_FRONT_LEFT			= 1<<1,	/*!<front left channel*/
+	VO_CHANNEL_FRONT_RIGHT			= 1<<2,	/*!<front right channel*/
+	VO_CHANNEL_SIDE_LEFT  			= 1<<3, /*!<side left channel*/
+	VO_CHANNEL_SIDE_RIGHT			= 1<<4, /*!<side right channel*/
+	VO_CHANNEL_BACK_LEFT			= 1<<5,	/*!<back left channel*/
+	VO_CHANNEL_BACK_RIGHT			= 1<<6,	/*!<back right channel*/
+	VO_CHANNEL_BACK_CENTER			= 1<<7,	/*!<back center channel*/
+	VO_CHANNEL_LFE_BASS				= 1<<8,	/*!<low-frequency effects bass channel*/
+	VO_CHANNEL_ALL					= 0xffff,/*!<[default] include all channels */
+	VO_CHANNEL_MAX					= VO_MAX_ENUM_VALUE
+} VO_AUDIO_CHANNELTYPE;
+
+/**
+ * General audio format info
+ */
+typedef struct
+{
+	VO_S32	SampleRate;  /*!< Sample rate */
+	VO_S32	Channels;    /*!< Channel count */
+	VO_S32	SampleBits;  /*!< Bits per sample */
+} VO_AUDIO_FORMAT;
+
+/**
+ * General audio output info
+ */
+typedef struct
+{
+	VO_AUDIO_FORMAT	Format;			/*!< Sample rate */
+	VO_U32			InputUsed;		/*!< Channel count */
+	VO_U32			Resever;		/*!< Resevered */
+} VO_AUDIO_OUTPUTINFO;
+
+/**
+ * General audio codec function set
+ */
+typedef struct VO_AUDIO_CODECAPI
+{
+	/**
+	 * Init the audio codec module and return codec handle
+	 * \param phCodec [OUT] Return the video codec handle
+	 * \param vType	[IN] The codec type if the module support multi codec.
+	 * \param pUserData	[IN] The init param. It is either a memory operator or an allocated memory
+	 * \retval VO_ERR_NONE Succeeded.
+	 */
+	VO_U32 (VO_API * Init) (VO_HANDLE * phCodec, VO_AUDIO_CODINGTYPE vType, VO_CODEC_INIT_USERDATA * pUserData );
+
+	/**
+	 * Set input audio data.
+	 * \param hCodec [IN]] The codec handle which was created by Init function.
+	 * \param pInput [IN] The input buffer param.
+	 * \retval VO_ERR_NONE Succeeded.
+	 */
+	VO_U32 (VO_API * SetInputData) (VO_HANDLE hCodec, VO_CODECBUFFER * pInput);
+
+	/**
+	 * Get the outut audio data
+	 * \param hCodec [IN]] The codec handle which was created by Init function.
+	 * \param pOutBuffer [OUT] The output audio data
+	 * \param pOutInfo [OUT] The codec fills audio format and the input data size used in current call.
+	 *						 pOutInfo->InputUsed is total used input data size in byte.
+	 * \retval  VO_ERR_NONE Succeeded.
+	 *			VO_ERR_INPUT_BUFFER_SMALL. The input was finished or the input data was not enought. Continue to input
+	 *										data before next call.
+	 */
+	VO_U32 (VO_API * GetOutputData) (VO_HANDLE hCodec, VO_CODECBUFFER * pOutBuffer, VO_AUDIO_OUTPUTINFO * pOutInfo);
+
+	/**
+	 * Set the parameter for the specified param ID.
+	 * \param hCodec [IN]] The codec handle which was created by Init function.
+	 * \param uParamID [IN] The param ID.
+	 * \param pData [IN] The param value.
+	 * \retval VO_ERR_NONE Succeeded.
+	 */
+	VO_U32 (VO_API * SetParam) (VO_HANDLE hCodec, VO_S32 uParamID, VO_PTR pData);
+
+	/**
+	 * Get the parameter for the specified param ID.
+	 * \param hCodec [IN]] The codec handle which was created by Init function.
+	 * \param uParamID [IN] The param ID.
+	 * \param pData [IN] The param value.
+	 * \retval VO_ERR_NONE Succeeded.
+	 */
+	VO_U32 (VO_API * GetParam) (VO_HANDLE hCodec, VO_S32 uParamID, VO_PTR pData);
+
+	/**
+	 * Uninit the Codec.
+	 * \param hCodec [IN]] The codec handle which was created by Init function.
+	 * \retval VO_ERR_NONE Succeeded.
+	 */
+	VO_U32 (VO_API * Uninit) (VO_HANDLE hCodec);
+} VO_AUDIO_CODECAPI;
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif // __voAudio_H__
diff --git a/media/libstagefright/codecs/common/include/voIndex.h b/media/libstagefright/codecs/common/include/voIndex.h
index 541a0db..320a2f8 100644
--- a/media/libstagefright/codecs/common/include/voIndex.h
+++ b/media/libstagefright/codecs/common/include/voIndex.h
@@ -1,193 +1,193 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		voIndex.h

-

-	Content:	module and ID definition

-

-*******************************************************************************/

-

-#ifndef __voIndex_H__

-#define __voIndex_H__

-

-#ifdef __cplusplus

-extern "C" {

-#endif /* __cplusplus */

-

-#include "voType.h"

-

-/* Define the module ID */

-#define _MAKE_SOURCE_ID(id, name) \

-VO_INDEX_SRC_##name = _VO_INDEX_SOURCE | id,

-

-#define _MAKE_CODEC_ID(id, name) \

-VO_INDEX_DEC_##name = _VO_INDEX_DEC | id, \

-VO_INDEX_ENC_##name = _VO_INDEX_ENC | id,

-

-#define _MAKE_EFFECT_ID(id, name) \

-VO_INDEX_EFT_##name = _VO_INDEX_EFFECT | id,

-

-#define _MAKE_SINK_ID(id, name) \

-VO_INDEX_SNK_##name = _VO_INDEX_SINK | id,

-

-#define _MAKE_FILTER_ID(id, name) \

-VO_INDEX_FLT_##name = _VO_INDEX_FILTER | id,

-

-#define _MAKE_OMX_ID(id, name) \

-VO_INDEX_OMX_##name = _VO_INDEX_OMX | id,

-

-#define _MAKE_MFW_ID(id, name) \

-VO_INDEX_MFW_##name = _VO_INDEX_MFW | id,

-

-enum

-{

-	_VO_INDEX_SOURCE		= 0x01000000,

-	_VO_INDEX_DEC			= 0x02000000,

-	_VO_INDEX_ENC			= 0x03000000,

-	_VO_INDEX_EFFECT		= 0x04000000,

-	_VO_INDEX_SINK			= 0x05000000,

-	_VO_INDEX_FILTER		= 0x06000000,

-	_VO_INDEX_OMX			= 0x07000000,

-	_VO_INDEX_MFW			= 0x08000000,

-

-	// define file parser modules

-	_MAKE_SOURCE_ID (0x010000, MP4)

-	_MAKE_SOURCE_ID (0x020000, AVI)

-	_MAKE_SOURCE_ID (0x030000, ASF)

-	_MAKE_SOURCE_ID (0x040000, REAL)

-	_MAKE_SOURCE_ID (0x050000, AUDIO)

-	_MAKE_SOURCE_ID (0x060000, FLASH)

-	_MAKE_SOURCE_ID (0x070000, OGG)

-	_MAKE_SOURCE_ID (0x080000, MKV)

-

-	// define network source modules

-	_MAKE_SOURCE_ID (0x110000, RTSP)

-	_MAKE_SOURCE_ID (0x120000, HTTP)

-

-	// define CMMB source modules

-	_MAKE_SOURCE_ID (0x200000, CMMB)

-	_MAKE_SOURCE_ID (0x210000, CMMB_INNO)

-	_MAKE_SOURCE_ID (0x220000, CMMB_TELE)

-	_MAKE_SOURCE_ID (0x230000, CMMB_SIANO)

-

-	// define DVBT source modules

-	_MAKE_SOURCE_ID (0x300000, DVBT)

-	_MAKE_SOURCE_ID (0x310000, DVBT_DIBCOM)

-

-	// define other source modules

-	_MAKE_SOURCE_ID (0x400000, ID3)

-

-	// define video codec modules

-	_MAKE_CODEC_ID (0x010000, H264)

-	_MAKE_CODEC_ID (0x020000, MPEG4)

-	_MAKE_CODEC_ID (0x030000, H263)

-	_MAKE_CODEC_ID (0x040000, S263)

-	_MAKE_CODEC_ID (0x050000, RV)

-	_MAKE_CODEC_ID (0x060000, WMV)

-	_MAKE_CODEC_ID (0x070000, DIVX3)

-	_MAKE_CODEC_ID (0x080000, MJPEG)

-	_MAKE_CODEC_ID (0x090000, MPEG2)

-	_MAKE_CODEC_ID (0x0A0000, VP6)

-

-	// define audio codec modules

-	_MAKE_CODEC_ID (0x210000, AAC)

-	_MAKE_CODEC_ID (0x220000, MP3)

-	_MAKE_CODEC_ID (0x230000, WMA)

-	_MAKE_CODEC_ID (0x240000, RA)

-	_MAKE_CODEC_ID (0x250000, AMRNB)

-	_MAKE_CODEC_ID (0x260000, AMRWB)

-	_MAKE_CODEC_ID (0x270000, AMRWBP)

-	_MAKE_CODEC_ID (0x280000, QCELP)

-	_MAKE_CODEC_ID (0x290000, EVRC)

-	_MAKE_CODEC_ID (0x2A0000, ADPCM)

-	_MAKE_CODEC_ID (0x2B0000, MIDI)

-	_MAKE_CODEC_ID (0x2C0000, AC3)

-	_MAKE_CODEC_ID (0x2D0000, FLAC)

-	_MAKE_CODEC_ID (0x2E0000, DRA)

-	_MAKE_CODEC_ID (0x2F0000, OGG)

-	_MAKE_CODEC_ID (0x300000, G729)

-

-	// define image codec modules

-	_MAKE_CODEC_ID (0x410000, JPEG)

-	_MAKE_CODEC_ID (0x420000, GIF)

-	_MAKE_CODEC_ID (0x430000, PNG)

-	_MAKE_CODEC_ID (0x440000, TIF)

-

-	// define effect modules

-	_MAKE_EFFECT_ID (0x010000, EQ)

-

-	// define sink modules

-	_MAKE_SINK_ID (0x010000, VIDEO)

-	_MAKE_SINK_ID (0x020000, AUDIO)

-	_MAKE_SINK_ID (0x030000, CCRRR)

-	_MAKE_SINK_ID (0x040000, CCRRV)

-

-	_MAKE_SINK_ID (0x110000, MP4)

-	_MAKE_SINK_ID (0x120000, AVI)

-	_MAKE_SINK_ID (0x130000, AFW)

-

-	// define media frame module ID

-	_MAKE_MFW_ID (0x010000, VOMMPLAY)

-	_MAKE_MFW_ID (0x020000, VOMMREC)

-	_MAKE_MFW_ID (0x030000, VOME)

-};

-

-

-/* define the error ID */

-#define VO_ERR_NONE						0x00000000

-#define VO_ERR_FINISH					0x00000001

-#define VO_ERR_BASE						0X80000000

-#define VO_ERR_FAILED					0x80000001

-#define VO_ERR_OUTOF_MEMORY				0x80000002

-#define VO_ERR_NOT_IMPLEMENT			0x80000003

-#define VO_ERR_INVALID_ARG				0x80000004

-#define VO_ERR_INPUT_BUFFER_SMALL		0x80000005

-#define VO_ERR_OUTPUT_BUFFER_SMALL		0x80000006

-#define VO_ERR_WRONG_STATUS				0x80000007

-#define VO_ERR_WRONG_PARAM_ID			0x80000008

-#define VO_ERR_LICENSE_ERROR			0x80000009

-

-/* xxx is the module ID

-#define VO_ERR_FAILED					0x8xxx0001

-#define VO_ERR_OUTOF_MEMORY				0x8xxx0002

-#define VO_ERR_NOT_IMPLEMENT			0x8xxx0003

-#define VO_ERR_INVALID_ARG				0x8xxx0004

-#define VO_ERR_INPUT_BUFFER_SMALL		0x8xxx0005

-#define VO_ERR_OUTPUT_BUFFER_SMALL		0x8xxx0006

-#define VO_ERR_WRONG_STATUS				0x8xxx0007

-#define VO_ERR_WRONG_PARAM_ID			0x8xxx0008

-#define VO_ERR_LICENSE_ERROR			0x8xxx0009

-// Module own error ID

-#define VO_ERR_Module					0x8xxx0X00

-*/

- 

-#define	VO_PID_COMMON_BASE				 0x40000000						/*!< The base of common param ID */

-#define	VO_PID_COMMON_QUERYMEM			(VO_PID_COMMON_BASE | 0X0001)	/*!< Query the memory needed; Reserved. */

-#define	VO_PID_COMMON_INPUTTYPE			(VO_PID_COMMON_BASE | 0X0002)	/*!< Set or get the input buffer type. VO_INPUT_TYPE */

-#define	VO_PID_COMMON_HASRESOURCE		(VO_PID_COMMON_BASE | 0X0003)	/*!< Query it has resource to be used. VO_U32 *, 1 have, 0 No */

-#define	VO_PID_COMMON_HEADDATA			(VO_PID_COMMON_BASE | 0X0004)	/*!< Decoder track header data. VO_CODECBUFFER * */

-#define	VO_PID_COMMON_FLUSH				(VO_PID_COMMON_BASE | 0X0005)	/*!< Flush the codec buffer. VO_U32 *, 1 Flush, 0 No * */

-

-/*

-// Module Param ID

-#define VO_ID_Mdoule					0x0xxx1000

-*/

-

-#ifdef __cplusplus

-}

-#endif /* __cplusplus */

-

-#endif // __voIndex_H__

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		voIndex.h
+
+	Content:	module and ID definition
+
+*******************************************************************************/
+
+#ifndef __voIndex_H__
+#define __voIndex_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+#include "voType.h"
+
+/* Define the module ID */
+#define _MAKE_SOURCE_ID(id, name) \
+VO_INDEX_SRC_##name = _VO_INDEX_SOURCE | id,
+
+#define _MAKE_CODEC_ID(id, name) \
+VO_INDEX_DEC_##name = _VO_INDEX_DEC | id, \
+VO_INDEX_ENC_##name = _VO_INDEX_ENC | id,
+
+#define _MAKE_EFFECT_ID(id, name) \
+VO_INDEX_EFT_##name = _VO_INDEX_EFFECT | id,
+
+#define _MAKE_SINK_ID(id, name) \
+VO_INDEX_SNK_##name = _VO_INDEX_SINK | id,
+
+#define _MAKE_FILTER_ID(id, name) \
+VO_INDEX_FLT_##name = _VO_INDEX_FILTER | id,
+
+#define _MAKE_OMX_ID(id, name) \
+VO_INDEX_OMX_##name = _VO_INDEX_OMX | id,
+
+#define _MAKE_MFW_ID(id, name) \
+VO_INDEX_MFW_##name = _VO_INDEX_MFW | id,
+
+enum
+{
+	_VO_INDEX_SOURCE		= 0x01000000,
+	_VO_INDEX_DEC			= 0x02000000,
+	_VO_INDEX_ENC			= 0x03000000,
+	_VO_INDEX_EFFECT		= 0x04000000,
+	_VO_INDEX_SINK			= 0x05000000,
+	_VO_INDEX_FILTER		= 0x06000000,
+	_VO_INDEX_OMX			= 0x07000000,
+	_VO_INDEX_MFW			= 0x08000000,
+
+	// define file parser modules
+	_MAKE_SOURCE_ID (0x010000, MP4)
+	_MAKE_SOURCE_ID (0x020000, AVI)
+	_MAKE_SOURCE_ID (0x030000, ASF)
+	_MAKE_SOURCE_ID (0x040000, REAL)
+	_MAKE_SOURCE_ID (0x050000, AUDIO)
+	_MAKE_SOURCE_ID (0x060000, FLASH)
+	_MAKE_SOURCE_ID (0x070000, OGG)
+	_MAKE_SOURCE_ID (0x080000, MKV)
+
+	// define network source modules
+	_MAKE_SOURCE_ID (0x110000, RTSP)
+	_MAKE_SOURCE_ID (0x120000, HTTP)
+
+	// define CMMB source modules
+	_MAKE_SOURCE_ID (0x200000, CMMB)
+	_MAKE_SOURCE_ID (0x210000, CMMB_INNO)
+	_MAKE_SOURCE_ID (0x220000, CMMB_TELE)
+	_MAKE_SOURCE_ID (0x230000, CMMB_SIANO)
+
+	// define DVBT source modules
+	_MAKE_SOURCE_ID (0x300000, DVBT)
+	_MAKE_SOURCE_ID (0x310000, DVBT_DIBCOM)
+
+	// define other source modules
+	_MAKE_SOURCE_ID (0x400000, ID3)
+
+	// define video codec modules
+	_MAKE_CODEC_ID (0x010000, H264)
+	_MAKE_CODEC_ID (0x020000, MPEG4)
+	_MAKE_CODEC_ID (0x030000, H263)
+	_MAKE_CODEC_ID (0x040000, S263)
+	_MAKE_CODEC_ID (0x050000, RV)
+	_MAKE_CODEC_ID (0x060000, WMV)
+	_MAKE_CODEC_ID (0x070000, DIVX3)
+	_MAKE_CODEC_ID (0x080000, MJPEG)
+	_MAKE_CODEC_ID (0x090000, MPEG2)
+	_MAKE_CODEC_ID (0x0A0000, VP6)
+
+	// define audio codec modules
+	_MAKE_CODEC_ID (0x210000, AAC)
+	_MAKE_CODEC_ID (0x220000, MP3)
+	_MAKE_CODEC_ID (0x230000, WMA)
+	_MAKE_CODEC_ID (0x240000, RA)
+	_MAKE_CODEC_ID (0x250000, AMRNB)
+	_MAKE_CODEC_ID (0x260000, AMRWB)
+	_MAKE_CODEC_ID (0x270000, AMRWBP)
+	_MAKE_CODEC_ID (0x280000, QCELP)
+	_MAKE_CODEC_ID (0x290000, EVRC)
+	_MAKE_CODEC_ID (0x2A0000, ADPCM)
+	_MAKE_CODEC_ID (0x2B0000, MIDI)
+	_MAKE_CODEC_ID (0x2C0000, AC3)
+	_MAKE_CODEC_ID (0x2D0000, FLAC)
+	_MAKE_CODEC_ID (0x2E0000, DRA)
+	_MAKE_CODEC_ID (0x2F0000, OGG)
+	_MAKE_CODEC_ID (0x300000, G729)
+
+	// define image codec modules
+	_MAKE_CODEC_ID (0x410000, JPEG)
+	_MAKE_CODEC_ID (0x420000, GIF)
+	_MAKE_CODEC_ID (0x430000, PNG)
+	_MAKE_CODEC_ID (0x440000, TIF)
+
+	// define effect modules
+	_MAKE_EFFECT_ID (0x010000, EQ)
+
+	// define sink modules
+	_MAKE_SINK_ID (0x010000, VIDEO)
+	_MAKE_SINK_ID (0x020000, AUDIO)
+	_MAKE_SINK_ID (0x030000, CCRRR)
+	_MAKE_SINK_ID (0x040000, CCRRV)
+
+	_MAKE_SINK_ID (0x110000, MP4)
+	_MAKE_SINK_ID (0x120000, AVI)
+	_MAKE_SINK_ID (0x130000, AFW)
+
+	// define media frame module ID
+	_MAKE_MFW_ID (0x010000, VOMMPLAY)
+	_MAKE_MFW_ID (0x020000, VOMMREC)
+	_MAKE_MFW_ID (0x030000, VOME)
+};
+
+
+/* define the error ID */
+#define VO_ERR_NONE						0x00000000
+#define VO_ERR_FINISH					0x00000001
+#define VO_ERR_BASE						0X80000000
+#define VO_ERR_FAILED					0x80000001
+#define VO_ERR_OUTOF_MEMORY				0x80000002
+#define VO_ERR_NOT_IMPLEMENT			0x80000003
+#define VO_ERR_INVALID_ARG				0x80000004
+#define VO_ERR_INPUT_BUFFER_SMALL		0x80000005
+#define VO_ERR_OUTPUT_BUFFER_SMALL		0x80000006
+#define VO_ERR_WRONG_STATUS				0x80000007
+#define VO_ERR_WRONG_PARAM_ID			0x80000008
+#define VO_ERR_LICENSE_ERROR			0x80000009
+
+/* xxx is the module ID
+#define VO_ERR_FAILED					0x8xxx0001
+#define VO_ERR_OUTOF_MEMORY				0x8xxx0002
+#define VO_ERR_NOT_IMPLEMENT			0x8xxx0003
+#define VO_ERR_INVALID_ARG				0x8xxx0004
+#define VO_ERR_INPUT_BUFFER_SMALL		0x8xxx0005
+#define VO_ERR_OUTPUT_BUFFER_SMALL		0x8xxx0006
+#define VO_ERR_WRONG_STATUS				0x8xxx0007
+#define VO_ERR_WRONG_PARAM_ID			0x8xxx0008
+#define VO_ERR_LICENSE_ERROR			0x8xxx0009
+// Module own error ID
+#define VO_ERR_Module					0x8xxx0X00
+*/
+
+#define	VO_PID_COMMON_BASE				 0x40000000						/*!< The base of common param ID */
+#define	VO_PID_COMMON_QUERYMEM			(VO_PID_COMMON_BASE | 0X0001)	/*!< Query the memory needed; Reserved. */
+#define	VO_PID_COMMON_INPUTTYPE			(VO_PID_COMMON_BASE | 0X0002)	/*!< Set or get the input buffer type. VO_INPUT_TYPE */
+#define	VO_PID_COMMON_HASRESOURCE		(VO_PID_COMMON_BASE | 0X0003)	/*!< Query it has resource to be used. VO_U32 *, 1 have, 0 No */
+#define	VO_PID_COMMON_HEADDATA			(VO_PID_COMMON_BASE | 0X0004)	/*!< Decoder track header data. VO_CODECBUFFER * */
+#define	VO_PID_COMMON_FLUSH				(VO_PID_COMMON_BASE | 0X0005)	/*!< Flush the codec buffer. VO_U32 *, 1 Flush, 0 No * */
+
+/*
+// Module Param ID
+#define VO_ID_Mdoule					0x0xxx1000
+*/
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif // __voIndex_H__
diff --git a/media/libstagefright/codecs/common/include/voType.h b/media/libstagefright/codecs/common/include/voType.h
index 2669134..5f659ab 100644
--- a/media/libstagefright/codecs/common/include/voType.h
+++ b/media/libstagefright/codecs/common/include/voType.h
@@ -1,221 +1,221 @@
-/*

- ** Copyright 2003-2010, VisualOn, Inc.

- **

- ** Licensed under the Apache License, Version 2.0 (the "License");

- ** you may not use this file except in compliance with the License.

- ** You may obtain a copy of the License at

- **

- **     http://www.apache.org/licenses/LICENSE-2.0

- **

- ** Unless required by applicable law or agreed to in writing, software

- ** distributed under the License is distributed on an "AS IS" BASIS,

- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- ** See the License for the specific language governing permissions and

- ** limitations under the License.

- */

-/*******************************************************************************

-	File:		voType.h

-

-	Content:	data type definition

-

-*******************************************************************************/

-#ifndef __voType_H__

-#define __voType_H__

-

-#ifdef __cplusplus

-extern "C" {

-#endif /* __cplusplus */

-

-#ifdef _WIN32

-#	define VO_API __cdecl

-#	define VO_CBI __stdcall

-#else

-#	define VO_API

-#	define VO_CBI

-#endif //_WIN32

-

-/** VO_IN is used to identify inputs to an VO function.  This designation

-    will also be used in the case of a pointer that points to a parameter

-    that is used as an output. */

-#ifndef VO_IN

-#define VO_IN

-#endif

-

-/** VO_OUT is used to identify outputs from an VO function.  This

-    designation will also be used in the case of a pointer that points

-    to a parameter that is used as an input. */

-#ifndef VO_OUT

-#define VO_OUT

-#endif

-

-/** VO_INOUT is used to identify parameters that may be either inputs or

-    outputs from an VO function at the same time.  This designation will

-    also be used in the case of a pointer that  points to a parameter that

-    is used both as an input and an output. */

-#ifndef VO_INOUT

-#define VO_INOUT

-#endif

-

-#define VO_MAX_ENUM_VALUE	0X7FFFFFFF

-

-/** VO_VOID */

-typedef void VO_VOID;

-

-/** VO_U8 is an 8 bit unsigned quantity that is byte aligned */

-typedef unsigned char VO_U8;

-

-/** VO_BYTE is an 8 bit unsigned quantity that is byte aligned */

-typedef unsigned char VO_BYTE;

-

-/** VO_S8 is an 8 bit signed quantity that is byte aligned */

-typedef signed char VO_S8;

-

-/** VO_CHAR is an 8 bit signed quantity that is byte aligned */

-typedef char VO_CHAR;

-

-/** VO_U16 is a 16 bit unsigned quantity that is 16 bit word aligned */

-typedef unsigned short VO_U16;

-

-/** VO_WCHAR is a 16 bit unsigned quantity that is 16 bit word aligned */

-#if defined _WIN32

-typedef unsigned short VO_WCHAR;

-typedef unsigned short* VO_PWCHAR;

-#elif defined LINUX

-typedef unsigned char VO_WCHAR;

-typedef unsigned char* VO_PWCHAR;

-#endif

-

-/** VO_S16 is a 16 bit signed quantity that is 16 bit word aligned */

-typedef signed short VO_S16;

-

-/** VO_U32 is a 32 bit unsigned quantity that is 32 bit word aligned */

-typedef unsigned long VO_U32;

-

-/** VO_S32 is a 32 bit signed quantity that is 32 bit word aligned */

-typedef signed long VO_S32;

-

-/* Users with compilers that cannot accept the "long long" designation should

-   define the VO_SKIP64BIT macro.  It should be noted that this may cause

-   some components to fail to compile if the component was written to require

-   64 bit integral types.  However, these components would NOT compile anyway

-   since the compiler does not support the way the component was written.

-*/

-#ifndef VO_SKIP64BIT

-#ifdef _WIN32

-/** VO_U64 is a 64 bit unsigned quantity that is 64 bit word aligned */

-typedef unsigned __int64  VO_U64;

-/** VO_S64 is a 64 bit signed quantity that is 64 bit word aligned */

-typedef signed   __int64  VO_S64;

-#else // WIN32

-/** VO_U64 is a 64 bit unsigned quantity that is 64 bit word aligned */

-typedef unsigned long long VO_U64;

-/** VO_S64 is a 64 bit signed quantity that is 64 bit word aligned */

-typedef signed long long VO_S64;

-#endif // WIN32

-#endif // VO_SKIP64BIT

-

-/** The VO_BOOL type is intended to be used to represent a true or a false

-    value when passing parameters to and from the VO core and components.  The

-    VO_BOOL is a 32 bit quantity and is aligned on a 32 bit word boundary.

- */

-typedef enum VO_BOOL {

-    VO_FALSE = 0,

-    VO_TRUE = !VO_FALSE,

-	VO_BOOL_MAX = VO_MAX_ENUM_VALUE

-} VO_BOOL;

-

-/** The VO_PTR type is intended to be used to pass pointers between the VO

-    applications and the VO Core and components.  This is a 32 bit pointer and

-    is aligned on a 32 bit boundary.

- */

-typedef void* VO_PTR;

-

-/** The VO_HANDLE type is intended to be used to pass pointers between the VO

-    applications and the VO Core and components.  This is a 32 bit pointer and

-    is aligned on a 32 bit boundary.

- */

-typedef void* VO_HANDLE;

-

-/** The VO_STRING type is intended to be used to pass "C" type strings between

-    the application and the core and component.  The VO_STRING type is a 32

-    bit pointer to a zero terminated string.  The  pointer is word aligned and

-    the string is byte aligned.

- */

-typedef char* VO_PCHAR;

-

-/** The VO_PBYTE type is intended to be used to pass arrays of bytes such as

-    buffers between the application and the component and core.  The VO_PBYTE

-    type is a 32 bit pointer to a zero terminated string.  The  pointer is word

-    aligned and the string is byte aligned.

- */

-typedef unsigned char* VO_PBYTE;

-

-/** The VO_PTCHAR type is intended to be used to pass arrays of wchar such as

-    unicode char between the application and the component and core.  The VO_PTCHAR

-    type is a 32 bit pointer to a zero terminated string.  The  pointer is word

-    aligned and the string is byte aligned.

- */

-/*

-#if !defined LINUX

-typedef unsigned short* VO_PTCHAR;

-typedef unsigned short* VO_TCHAR;

-#else

-typedef char* VO_PTCHAR;

-typedef char VO_TCHAR;

-#endif

-*/

-

-#ifndef NULL

-#ifdef __cplusplus

-#define NULL    0

-#else

-#define NULL    ((void *)0)

-#endif

-#endif

-

-/**

- * Input stream format, Frame or Stream..

- */

-typedef enum {

-    VO_INPUT_FRAME	= 1,	/*!< Input contains completely frame(s) data. */

-    VO_INPUT_STREAM,		/*!< Input is stream data. */

-	VO_INPUT_STREAM_MAX = VO_MAX_ENUM_VALUE

-} VO_INPUT_TYPE;

-

-

-/**

- * General data buffer, used as input or output.

- */

-typedef struct {

-	VO_PBYTE	Buffer;		/*!< Buffer pointer */

-	VO_U32		Length;		/*!< Buffer size in byte */

-	VO_S64		Time;		/*!< The time of the buffer */

-} VO_CODECBUFFER;

-

-

-/**

- * The init memdata flag.

- */

-typedef enum{

-	VO_IMF_USERMEMOPERATOR		=0,	/*!< memData is  the pointer of memoperator function*/

-	VO_IMF_PREALLOCATEDBUFFER	=1,	/*!< memData is  preallocated memory*/

-	VO_IMF_MAX = VO_MAX_ENUM_VALUE

-}VO_INIT_MEM_FlAG;

-

-

-/**

- * The init memory structure..

- */

-typedef struct{

-	VO_INIT_MEM_FlAG			memflag;	/*!<memory flag  */

-	VO_PTR						memData;	/*!<a pointer to VO_MEM_OPERATOR or a preallocated buffer  */

-	VO_U32						reserved1;	/*!<reserved  */

-	VO_U32						reserved2;	/*!<reserved */

-}VO_CODEC_INIT_USERDATA;

-

-

-#ifdef __cplusplus

-}

-#endif /* __cplusplus */

-

-#endif // __voType_H__

+/*
+ ** Copyright 2003-2010, VisualOn, Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ **     http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+/*******************************************************************************
+	File:		voType.h
+
+	Content:	data type definition
+
+*******************************************************************************/
+#ifndef __voType_H__
+#define __voType_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+#ifdef _WIN32
+#	define VO_API __cdecl
+#	define VO_CBI __stdcall
+#else
+#	define VO_API
+#	define VO_CBI
+#endif //_WIN32
+
+/** VO_IN is used to identify inputs to an VO function.  This designation
+    will also be used in the case of a pointer that points to a parameter
+    that is used as an output. */
+#ifndef VO_IN
+#define VO_IN
+#endif
+
+/** VO_OUT is used to identify outputs from an VO function.  This
+    designation will also be used in the case of a pointer that points
+    to a parameter that is used as an input. */
+#ifndef VO_OUT
+#define VO_OUT
+#endif
+
+/** VO_INOUT is used to identify parameters that may be either inputs or
+    outputs from an VO function at the same time.  This designation will
+    also be used in the case of a pointer that  points to a parameter that
+    is used both as an input and an output. */
+#ifndef VO_INOUT
+#define VO_INOUT
+#endif
+
+#define VO_MAX_ENUM_VALUE	0X7FFFFFFF
+
+/** VO_VOID */
+typedef void VO_VOID;
+
+/** VO_U8 is an 8 bit unsigned quantity that is byte aligned */
+typedef unsigned char VO_U8;
+
+/** VO_BYTE is an 8 bit unsigned quantity that is byte aligned */
+typedef unsigned char VO_BYTE;
+
+/** VO_S8 is an 8 bit signed quantity that is byte aligned */
+typedef signed char VO_S8;
+
+/** VO_CHAR is an 8 bit signed quantity that is byte aligned */
+typedef char VO_CHAR;
+
+/** VO_U16 is a 16 bit unsigned quantity that is 16 bit word aligned */
+typedef unsigned short VO_U16;
+
+/** VO_WCHAR is a 16 bit unsigned quantity that is 16 bit word aligned */
+#if defined _WIN32
+typedef unsigned short VO_WCHAR;
+typedef unsigned short* VO_PWCHAR;
+#elif defined LINUX
+typedef unsigned char VO_WCHAR;
+typedef unsigned char* VO_PWCHAR;
+#endif
+
+/** VO_S16 is a 16 bit signed quantity that is 16 bit word aligned */
+typedef signed short VO_S16;
+
+/** VO_U32 is a 32 bit unsigned quantity that is 32 bit word aligned */
+typedef unsigned long VO_U32;
+
+/** VO_S32 is a 32 bit signed quantity that is 32 bit word aligned */
+typedef signed long VO_S32;
+
+/* Users with compilers that cannot accept the "long long" designation should
+   define the VO_SKIP64BIT macro.  It should be noted that this may cause
+   some components to fail to compile if the component was written to require
+   64 bit integral types.  However, these components would NOT compile anyway
+   since the compiler does not support the way the component was written.
+*/
+#ifndef VO_SKIP64BIT
+#ifdef _MSC_VER
+/** VO_U64 is a 64 bit unsigned quantity that is 64 bit word aligned */
+typedef unsigned __int64  VO_U64;
+/** VO_S64 is a 64 bit signed quantity that is 64 bit word aligned */
+typedef signed   __int64  VO_S64;
+#else // WIN32
+/** VO_U64 is a 64 bit unsigned quantity that is 64 bit word aligned */
+typedef unsigned long long VO_U64;
+/** VO_S64 is a 64 bit signed quantity that is 64 bit word aligned */
+typedef signed long long VO_S64;
+#endif // WIN32
+#endif // VO_SKIP64BIT
+
+/** The VO_BOOL type is intended to be used to represent a true or a false
+    value when passing parameters to and from the VO core and components.  The
+    VO_BOOL is a 32 bit quantity and is aligned on a 32 bit word boundary.
+ */
+typedef enum VO_BOOL {
+    VO_FALSE = 0,
+    VO_TRUE = !VO_FALSE,
+	VO_BOOL_MAX = VO_MAX_ENUM_VALUE
+} VO_BOOL;
+
+/** The VO_PTR type is intended to be used to pass pointers between the VO
+    applications and the VO Core and components.  This is a 32 bit pointer and
+    is aligned on a 32 bit boundary.
+ */
+typedef void* VO_PTR;
+
+/** The VO_HANDLE type is intended to be used to pass pointers between the VO
+    applications and the VO Core and components.  This is a 32 bit pointer and
+    is aligned on a 32 bit boundary.
+ */
+typedef void* VO_HANDLE;
+
+/** The VO_STRING type is intended to be used to pass "C" type strings between
+    the application and the core and component.  The VO_STRING type is a 32
+    bit pointer to a zero terminated string.  The  pointer is word aligned and
+    the string is byte aligned.
+ */
+typedef char* VO_PCHAR;
+
+/** The VO_PBYTE type is intended to be used to pass arrays of bytes such as
+    buffers between the application and the component and core.  The VO_PBYTE
+    type is a 32 bit pointer to a zero terminated string.  The  pointer is word
+    aligned and the string is byte aligned.
+ */
+typedef unsigned char* VO_PBYTE;
+
+/** The VO_PTCHAR type is intended to be used to pass arrays of wchar such as
+    unicode char between the application and the component and core.  The VO_PTCHAR
+    type is a 32 bit pointer to a zero terminated string.  The  pointer is word
+    aligned and the string is byte aligned.
+ */
+/*
+#if !defined LINUX
+typedef unsigned short* VO_PTCHAR;
+typedef unsigned short* VO_TCHAR;
+#else
+typedef char* VO_PTCHAR;
+typedef char VO_TCHAR;
+#endif
+*/
+
+#ifndef NULL
+#ifdef __cplusplus
+#define NULL    0
+#else
+#define NULL    ((void *)0)
+#endif
+#endif
+
+/**
+ * Input stream format, Frame or Stream..
+ */
+typedef enum {
+    VO_INPUT_FRAME	= 1,	/*!< Input contains completely frame(s) data. */
+    VO_INPUT_STREAM,		/*!< Input is stream data. */
+	VO_INPUT_STREAM_MAX = VO_MAX_ENUM_VALUE
+} VO_INPUT_TYPE;
+
+
+/**
+ * General data buffer, used as input or output.
+ */
+typedef struct {
+	VO_PBYTE	Buffer;		/*!< Buffer pointer */
+	VO_U32		Length;		/*!< Buffer size in byte */
+	VO_S64		Time;		/*!< The time of the buffer */
+} VO_CODECBUFFER;
+
+
+/**
+ * The init memdata flag.
+ */
+typedef enum{
+	VO_IMF_USERMEMOPERATOR		=0,	/*!< memData is  the pointer of memoperator function*/
+	VO_IMF_PREALLOCATEDBUFFER	=1,	/*!< memData is  preallocated memory*/
+	VO_IMF_MAX = VO_MAX_ENUM_VALUE
+}VO_INIT_MEM_FlAG;
+
+
+/**
+ * The init memory structure..
+ */
+typedef struct{
+	VO_INIT_MEM_FlAG			memflag;	/*!<memory flag  */
+	VO_PTR						memData;	/*!<a pointer to VO_MEM_OPERATOR or a preallocated buffer  */
+	VO_U32						reserved1;	/*!<reserved  */
+	VO_U32						reserved2;	/*!<reserved */
+}VO_CODEC_INIT_USERDATA;
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif // __voType_H__
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_header.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_header.cpp
index 8b0250a..d443b7c 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_header.cpp
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_header.cpp
@@ -121,9 +121,11 @@
     uint32  temp;
 
     /*
-     *  Verify that at least the header is complete
+     * Verify that at least the header is complete
+     * Note that SYNC_WORD_LNGTH is in unit of bits, but inputBufferCurrentLength
+     * is in unit of bytes.
      */
-    if (inputStream->inputBufferCurrentLength < (SYNC_WORD_LNGTH + 21))
+    if (inputStream->inputBufferCurrentLength < ((SYNC_WORD_LNGTH + 21) >> 3))
     {
         return NO_ENOUGH_MAIN_DATA_ERROR;
     }
diff --git a/media/libstagefright/include/NuCachedSource2.h b/media/libstagefright/include/NuCachedSource2.h
index 1fb2088..a836ad7 100644
--- a/media/libstagefright/include/NuCachedSource2.h
+++ b/media/libstagefright/include/NuCachedSource2.h
@@ -94,7 +94,7 @@
     status_t seekInternal_l(off_t offset);
 
     size_t approxDataRemaining_l(bool *eos);
-    void restartPrefetcherIfNecessary_l();
+    void restartPrefetcherIfNecessary_l(bool force = false);
 
     DISALLOW_EVIL_CONSTRUCTORS(NuCachedSource2);
 };
diff --git a/media/libstagefright/include/NuHTTPDataSource.h b/media/libstagefright/include/NuHTTPDataSource.h
index 3c88cc2..ad22807 100644
--- a/media/libstagefright/include/NuHTTPDataSource.h
+++ b/media/libstagefright/include/NuHTTPDataSource.h
@@ -1,3 +1,19 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 #ifndef NU_HTTP_DATA_SOURCE_H_
 
 #define NU_HTTP_DATA_SOURCE_H_
diff --git a/media/libstagefright/rtsp/AMPEG4ElementaryAssembler.cpp b/media/libstagefright/rtsp/AMPEG4ElementaryAssembler.cpp
index 13988cd..9f6bd29 100644
--- a/media/libstagefright/rtsp/AMPEG4ElementaryAssembler.cpp
+++ b/media/libstagefright/rtsp/AMPEG4ElementaryAssembler.cpp
@@ -104,7 +104,7 @@
       mNextExpectedSeqNoValid(false),
       mNextExpectedSeqNo(0),
       mAccessUnitDamaged(false) {
-    mIsGeneric = desc.startsWith("mpeg4-generic/");
+    mIsGeneric = !strncasecmp(desc.c_str(),"mpeg4-generic/", 14);
 
     if (mIsGeneric) {
         AString value;
diff --git a/media/libstagefright/rtsp/APacketSource.cpp b/media/libstagefright/rtsp/APacketSource.cpp
index 10cc88b..7f09248 100644
--- a/media/libstagefright/rtsp/APacketSource.cpp
+++ b/media/libstagefright/rtsp/APacketSource.cpp
@@ -627,7 +627,7 @@
 
         mFormat->setInt32(kKeyWidth, width);
         mFormat->setInt32(kKeyHeight, height);
-    } else if (!strncmp(desc.c_str(), "mpeg4-generic/", 14)) {
+    } else if (!strncasecmp(desc.c_str(), "mpeg4-generic/", 14)) {
         AString val;
         if (!GetAttribute(params.c_str(), "mode", &val)
                 || (strcasecmp(val.c_str(), "AAC-lbr")
diff --git a/media/libstagefright/rtsp/ARTPConnection.cpp b/media/libstagefright/rtsp/ARTPConnection.cpp
index 5a1ea5c..72943ff 100644
--- a/media/libstagefright/rtsp/ARTPConnection.cpp
+++ b/media/libstagefright/rtsp/ARTPConnection.cpp
@@ -123,7 +123,7 @@
         struct sockaddr_in addr;
         memset(addr.sin_zero, 0, sizeof(addr.sin_zero));
         addr.sin_family = AF_INET;
-        addr.sin_addr.s_addr = INADDR_ANY;
+        addr.sin_addr.s_addr = htonl(INADDR_ANY);
         addr.sin_port = htons(port);
 
         if (bind(*rtpSocket,
@@ -346,6 +346,8 @@
 }
 
 status_t ARTPConnection::receive(StreamInfo *s, bool receiveRTP) {
+    LOGV("receiving %s", receiveRTP ? "RTP" : "RTCP");
+
     CHECK(!s->mIsInjected);
 
     sp<ABuffer> buffer = new ABuffer(65536);
diff --git a/media/libstagefright/rtsp/ARTPSource.cpp b/media/libstagefright/rtsp/ARTPSource.cpp
index 5aae4e7..87b5a7e 100644
--- a/media/libstagefright/rtsp/ARTPSource.cpp
+++ b/media/libstagefright/rtsp/ARTPSource.cpp
@@ -67,7 +67,7 @@
     } else  if (!strncmp(desc.c_str(), "AMR-WB/", 7)) {
         mAssembler = new AAMRAssembler(notify, true /* isWide */, params);
     } else if (!strncmp(desc.c_str(), "MP4V-ES/", 8)
-            || !strncmp(desc.c_str(), "mpeg4-generic/", 14)) {
+            || !strncasecmp(desc.c_str(), "mpeg4-generic/", 14)) {
         mAssembler = new AMPEG4ElementaryAssembler(notify, desc, params);
         mIssueFIRRequests = true;
     } else {
diff --git a/media/libstagefright/rtsp/ARTSPConnection.cpp b/media/libstagefright/rtsp/ARTSPConnection.cpp
index e936923..0740515 100644
--- a/media/libstagefright/rtsp/ARTSPConnection.cpp
+++ b/media/libstagefright/rtsp/ARTSPConnection.cpp
@@ -545,6 +545,10 @@
     return buffer;
 }
 
+static bool IsRTSPVersion(const AString &s) {
+    return s == "RTSP/1.0";
+}
+
 bool ARTSPConnection::receiveRTSPReponse() {
     AString statusLine;
 
@@ -584,13 +588,27 @@
         return false;
     }
 
-    AString statusCodeStr(
-            response->mStatusLine, space1 + 1, space2 - space1 - 1);
+    bool isRequest = false;
 
-    if (!ParseSingleUnsignedLong(
-                statusCodeStr.c_str(), &response->mStatusCode)
-            || response->mStatusCode < 100 || response->mStatusCode > 999) {
-        return false;
+    if (!IsRTSPVersion(AString(response->mStatusLine, 0, space1))) {
+        CHECK(IsRTSPVersion(
+                    AString(
+                        response->mStatusLine,
+                        space2 + 1,
+                        response->mStatusLine.size() - space2 - 1)));
+
+        isRequest = true;
+
+        response->mStatusCode = 0;
+    } else {
+        AString statusCodeStr(
+                response->mStatusLine, space1 + 1, space2 - space1 - 1);
+
+        if (!ParseSingleUnsignedLong(
+                    statusCodeStr.c_str(), &response->mStatusCode)
+                || response->mStatusCode < 100 || response->mStatusCode > 999) {
+            return false;
+        }
     }
 
     AString line;
@@ -680,7 +698,63 @@
         }
     }
 
-    return notifyResponseListener(response);
+    return isRequest
+        ? handleServerRequest(response)
+        : notifyResponseListener(response);
+}
+
+bool ARTSPConnection::handleServerRequest(const sp<ARTSPResponse> &request) {
+    // Implementation of server->client requests is optional for all methods
+    // but we do need to respond, even if it's just to say that we don't
+    // support the method.
+
+    ssize_t space1 = request->mStatusLine.find(" ");
+    CHECK_GE(space1, 0);
+
+    AString response;
+    response.append("RTSP/1.0 501 Not Implemented\r\n");
+
+    ssize_t i = request->mHeaders.indexOfKey("cseq");
+
+    if (i >= 0) {
+        AString value = request->mHeaders.valueAt(i);
+
+        unsigned long cseq;
+        if (!ParseSingleUnsignedLong(value.c_str(), &cseq)) {
+            return false;
+        }
+
+        response.append("CSeq: ");
+        response.append(cseq);
+        response.append("\r\n");
+    }
+
+    response.append("\r\n");
+
+    size_t numBytesSent = 0;
+    while (numBytesSent < response.size()) {
+        ssize_t n =
+            send(mSocket, response.c_str() + numBytesSent,
+                 response.size() - numBytesSent, 0);
+
+        if (n == 0) {
+            // Server closed the connection.
+            LOGE("Server unexpectedly closed the connection.");
+
+            return false;
+        } else if (n < 0) {
+            if (errno == EINTR) {
+                continue;
+            }
+
+            LOGE("Error sending rtsp response.");
+            return false;
+        }
+
+        numBytesSent += (size_t)n;
+    }
+
+    return true;
 }
 
 // static
diff --git a/media/libstagefright/rtsp/ARTSPConnection.h b/media/libstagefright/rtsp/ARTSPConnection.h
index 19be2a6..0fecf3c 100644
--- a/media/libstagefright/rtsp/ARTSPConnection.h
+++ b/media/libstagefright/rtsp/ARTSPConnection.h
@@ -109,6 +109,8 @@
     status_t findPendingRequest(
             const sp<ARTSPResponse> &response, ssize_t *index) const;
 
+    bool handleServerRequest(const sp<ARTSPResponse> &request);
+
     static bool ParseSingleUnsignedLong(
             const char *from, unsigned long *x);
 
diff --git a/media/libstagefright/rtsp/ASessionDescription.cpp b/media/libstagefright/rtsp/ASessionDescription.cpp
index 3e710dc..f03f7a2 100644
--- a/media/libstagefright/rtsp/ASessionDescription.cpp
+++ b/media/libstagefright/rtsp/ASessionDescription.cpp
@@ -71,6 +71,11 @@
             line.setTo(desc, i, eolPos - i);
         }
 
+        if (line.empty()) {
+            i = eolPos + 1;
+            continue;
+        }
+
         if (line.size() < 2 || line.c_str()[1] != '=') {
             return false;
         }
diff --git a/media/libstagefright/rtsp/MyHandler.h b/media/libstagefright/rtsp/MyHandler.h
index 306a9c1..72a2fdb 100644
--- a/media/libstagefright/rtsp/MyHandler.h
+++ b/media/libstagefright/rtsp/MyHandler.h
@@ -38,6 +38,7 @@
 
 #include <arpa/inet.h>
 #include <sys/socket.h>
+#include <netdb.h>
 
 // If no access units are received within 3 secs, assume that the rtp
 // stream has ended and signal end of stream.
@@ -119,9 +120,10 @@
         // want to transmit user/pass in cleartext.
         AString host, path, user, pass;
         unsigned port;
-        if (ARTSPConnection::ParseURL(
-                    mSessionURL.c_str(), &host, &port, &path, &user, &pass)
-                && user.size() > 0) {
+        CHECK(ARTSPConnection::ParseURL(
+                    mSessionURL.c_str(), &host, &port, &path, &user, &pass));
+
+        if (user.size() > 0) {
             mSessionURL.clear();
             mSessionURL.append("rtsp://");
             mSessionURL.append(host);
@@ -131,6 +133,8 @@
 
             LOGI("rewritten session url: '%s'", mSessionURL.c_str());
         }
+
+        mSessionHost = host;
     }
 
     void connect(const sp<AMessage> &doneMsg) {
@@ -246,34 +250,64 @@
     // In case we're behind NAT, fire off two UDP packets to the remote
     // rtp/rtcp ports to poke a hole into the firewall for future incoming
     // packets. We're going to send an RR/SDES RTCP packet to both of them.
-    void pokeAHole(int rtpSocket, int rtcpSocket, const AString &transport) {
+    bool pokeAHole(int rtpSocket, int rtcpSocket, const AString &transport) {
+        struct sockaddr_in addr;
+        memset(addr.sin_zero, 0, sizeof(addr.sin_zero));
+        addr.sin_family = AF_INET;
+
         AString source;
         AString server_port;
         if (!GetAttribute(transport.c_str(),
                           "source",
-                          &source)
-                || !GetAttribute(transport.c_str(),
+                          &source)) {
+            LOGW("Missing 'source' field in Transport response. Using "
+                 "RTSP endpoint address.");
+
+            struct hostent *ent = gethostbyname(mSessionHost.c_str());
+            if (ent == NULL) {
+                LOGE("Failed to look up address of session host '%s'",
+                     mSessionHost.c_str());
+
+                return false;
+            }
+
+            addr.sin_addr.s_addr = *(in_addr_t *)ent->h_addr;
+        } else {
+            addr.sin_addr.s_addr = inet_addr(source.c_str());
+        }
+
+        if (!GetAttribute(transport.c_str(),
                                  "server_port",
                                  &server_port)) {
-            return;
+            LOGI("Missing 'server_port' field in Transport response.");
+            return false;
         }
 
         int rtpPort, rtcpPort;
         if (sscanf(server_port.c_str(), "%d-%d", &rtpPort, &rtcpPort) != 2
                 || rtpPort <= 0 || rtpPort > 65535
                 || rtcpPort <=0 || rtcpPort > 65535
-                || rtcpPort != rtpPort + 1
-                || (rtpPort & 1) != 0) {
-            return;
+                || rtcpPort != rtpPort + 1) {
+            LOGE("Server picked invalid RTP/RTCP port pair %s,"
+                 " RTP port must be even, RTCP port must be one higher.",
+                 server_port.c_str());
+
+            return false;
         }
 
-        struct sockaddr_in addr;
-        memset(addr.sin_zero, 0, sizeof(addr.sin_zero));
-        addr.sin_family = AF_INET;
-        addr.sin_addr.s_addr = inet_addr(source.c_str());
+        if (rtpPort & 1) {
+            LOGW("Server picked an odd RTP port, it should've picked an "
+                 "even one, we'll let it pass for now, but this may break "
+                 "in the future.");
+        }
 
         if (addr.sin_addr.s_addr == INADDR_NONE) {
-            return;
+            return true;
+        }
+
+        if (IN_LOOPBACK(ntohl(addr.sin_addr.s_addr))) {
+            // No firewalls to traverse on the loopback interface.
+            return true;
         }
 
         // Make up an RR/SDES RTCP packet.
@@ -287,16 +321,26 @@
         ssize_t n = sendto(
                 rtpSocket, buf->data(), buf->size(), 0,
                 (const sockaddr *)&addr, sizeof(addr));
-        CHECK_EQ(n, (ssize_t)buf->size());
+
+        if (n < (ssize_t)buf->size()) {
+            LOGE("failed to poke a hole for RTP packets");
+            return false;
+        }
 
         addr.sin_port = htons(rtcpPort);
 
         n = sendto(
                 rtcpSocket, buf->data(), buf->size(), 0,
                 (const sockaddr *)&addr, sizeof(addr));
-        CHECK_EQ(n, (ssize_t)buf->size());
+
+        if (n < (ssize_t)buf->size()) {
+            LOGE("failed to poke a hole for RTCP packets");
+            return false;
+        }
 
         LOGV("successfully poked holes.");
+
+        return true;
     }
 
     virtual void onMessageReceived(const sp<AMessage> &msg) {
@@ -379,6 +423,7 @@
                                 response->mContent->size());
 
                         if (!mSessionDesc->isValid()) {
+                            LOGE("Failed to parse session description.");
                             result = ERROR_MALFORMED;
                         } else {
                             ssize_t i = response->mHeaders.indexOfKey("content-base");
@@ -393,6 +438,25 @@
                                 }
                             }
 
+                            if (!mBaseURL.startsWith("rtsp://")) {
+                                // Some misbehaving servers specify a relative
+                                // URL in one of the locations above, combine
+                                // it with the absolute session URL to get
+                                // something usable...
+
+                                LOGW("Server specified a non-absolute base URL"
+                                     ", combining it with the session URL to "
+                                     "get something usable...");
+
+                                AString tmp;
+                                CHECK(MakeURL(
+                                            mSessionURL.c_str(),
+                                            mBaseURL.c_str(),
+                                            &tmp));
+
+                                mBaseURL = tmp;
+                            }
+
                             CHECK_GT(mSessionDesc->countTracks(), 1u);
                             setupTrack(1);
                         }
@@ -453,9 +517,12 @@
                         if (!track->mUsingInterleavedTCP) {
                             AString transport = response->mHeaders.valueAt(i);
 
-                            pokeAHole(track->mRTPSocket,
-                                      track->mRTCPSocket,
-                                      transport);
+                            // We are going to continue even if we were
+                            // unable to poke a hole into the firewall...
+                            pokeAHole(
+                                    track->mRTPSocket,
+                                    track->mRTCPSocket,
+                                    transport);
                         }
 
                         mRTPConn->addStream(
@@ -865,10 +932,7 @@
             case 'tiou':
             {
                 if (!mReceivedFirstRTCPPacket) {
-                    if (mTryFakeRTCP) {
-                        LOGW("Never received any data, disconnecting.");
-                        (new AMessage('abor', id()))->post();
-                    } else if (mTryTCPInterleaving && mReceivedFirstRTPPacket) {
+                    if (mReceivedFirstRTPPacket && !mTryFakeRTCP) {
                         LOGW("We received RTP packets but no RTCP packets, "
                              "using fake timestamps.");
 
@@ -876,7 +940,7 @@
 
                         mReceivedFirstRTCPPacket = true;
                         mRTPConn->fakeTimestamps();
-                    } else {
+                    } else if (!mReceivedFirstRTPPacket && !mTryTCPInterleaving) {
                         LOGW("Never received any data, switching transports.");
 
                         mTryTCPInterleaving = true;
@@ -884,6 +948,9 @@
                         sp<AMessage> msg = new AMessage('abor', id());
                         msg->setInt32("reconnect", true);
                         msg->post();
+                    } else {
+                        LOGW("Never received any data, disconnecting.");
+                        (new AMessage('abor', id()))->post();
                     }
                 }
                 break;
@@ -1010,6 +1077,7 @@
     sp<ASessionDescription> mSessionDesc;
     AString mOriginalSessionURL;  // This one still has user:pass@
     AString mSessionURL;
+    AString mSessionHost;
     AString mBaseURL;
     AString mSessionID;
     bool mSetupTracksSuccessful;
diff --git a/nfc-extras/Android.mk b/nfc-extras/Android.mk
new file mode 100644
index 0000000..131d898
--- /dev/null
+++ b/nfc-extras/Android.mk
@@ -0,0 +1,14 @@
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
+
+LOCAL_MODULE:= com.android.nfc_extras
+
+include $(BUILD_JAVA_LIBRARY)
+
+# put the classes.jar, with full class files instead of classes.dex inside, into the dist directory
+$(call dist-for-goals, droidcore, $(full_classes_jar):com.android.nfc_extras.jar)
diff --git a/nfc-extras/com.android.nfc_extras.xml b/nfc-extras/com.android.nfc_extras.xml
new file mode 100644
index 0000000..370145d
--- /dev/null
+++ b/nfc-extras/com.android.nfc_extras.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2011 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<permissions>
+    <library name="com.android.nfc_extras"
+            file="/system/framework/com.android.nfc_extras.jar" />
+</permissions>
diff --git a/nfc-extras/java/com/android/nfc_extras/NfcAdapterExtras.java b/nfc-extras/java/com/android/nfc_extras/NfcAdapterExtras.java
new file mode 100644
index 0000000..e0c38b1
--- /dev/null
+++ b/nfc-extras/java/com/android/nfc_extras/NfcAdapterExtras.java
@@ -0,0 +1,226 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.nfc_extras;
+
+import android.annotation.SdkConstant;
+import android.annotation.SdkConstant.SdkConstantType;
+import android.nfc.INfcAdapterExtras;
+import android.nfc.NfcAdapter;
+import android.os.RemoteException;
+import android.util.Log;
+
+/**
+ * Provides additional methods on an {@link NfcAdapter} for Card Emulation
+ * and management of {@link NfcExecutionEnvironment}'s.
+ *
+ * There is a 1-1 relationship between an {@link NfcAdapterExtras} object and
+ * a {@link NfcAdapter} object.
+ */
+public final class NfcAdapterExtras {
+    private static final String TAG = "NfcAdapterExtras";
+
+    /**
+     * Broadcast Action: an RF field ON has been detected.
+     *
+     * <p class="note">This is an unreliable signal, and will be removed.
+     * <p class="note">
+     * Requires the {@link android.Manifest.permission#WRITE_SECURE_SETTINGS} permission
+     * to receive.
+     */
+    public static final String ACTION_RF_FIELD_ON_DETECTED =
+            "com.android.nfc_extras.action.RF_FIELD_ON_DETECTED";
+
+    /**
+     * Broadcast Action: an RF field OFF has been detected.
+     *
+     * <p class="note">This is an unreliable signal, and will be removed.
+     * <p class="note">
+     * Requires the {@link android.Manifest.permission#WRITE_SECURE_SETTINGS} permission
+     * to receive.
+     */
+    public static final String ACTION_RF_FIELD_OFF_DETECTED =
+            "com.android.nfc_extras.action.RF_FIELD_OFF_DETECTED";
+
+    // protected by NfcAdapterExtras.class, and final after first construction,
+    // except for attemptDeadServiceRecovery() when NFC crashes - we accept a
+    // best effort recovery
+    private static NfcAdapter sAdapter;
+    private static INfcAdapterExtras sService;
+    private static NfcAdapterExtras sSingleton;
+    private static NfcExecutionEnvironment sEmbeddedEe;
+    private static CardEmulationRoute sRouteOff;
+    private static CardEmulationRoute sRouteOnWhenScreenOn;
+
+    /** get service handles */
+    private static void initService() {
+        sService = sAdapter.getNfcAdapterExtrasInterface();
+    }
+
+    /**
+     * Get the {@link NfcAdapterExtras} for the given {@link NfcAdapter}.
+     *
+     * <p class="note">
+     * Requires the {@link android.Manifest.permission#WRITE_SECURE_SETTINGS} permission.
+     *
+     * @param adapter a {@link NfcAdapter}, must not be null
+     * @return the {@link NfcAdapterExtras} object for the given {@link NfcAdapter}
+     */
+    public static NfcAdapterExtras get(NfcAdapter adapter) {
+        synchronized(NfcAdapterExtras.class) {
+            if (sSingleton == null) {
+                try {
+                    sAdapter = adapter;
+                    sRouteOff = new CardEmulationRoute(CardEmulationRoute.ROUTE_OFF, null);
+                    sSingleton = new NfcAdapterExtras();
+                    sEmbeddedEe = new NfcExecutionEnvironment(sSingleton);
+                    sRouteOnWhenScreenOn = new CardEmulationRoute(
+                            CardEmulationRoute.ROUTE_ON_WHEN_SCREEN_ON, sEmbeddedEe);
+                    initService();
+                } finally {
+                    if (sSingleton == null) {
+                        sService = null;
+                        sEmbeddedEe = null;
+                        sRouteOff = null;
+                        sRouteOnWhenScreenOn = null;
+                    }
+                }
+            }
+            return sSingleton;
+        }
+    }
+
+    private NfcAdapterExtras() {}
+
+    /**
+     * Immutable data class that describes a card emulation route.
+     */
+    public final static class CardEmulationRoute {
+        /**
+         * Card Emulation is turned off on this NfcAdapter.
+         * <p>This is the default routing state after boot.
+         */
+        public static final int ROUTE_OFF = 1;
+
+        /**
+         * Card Emulation is routed to {@link #nfcEe} only when the screen is on,
+         * otherwise it is turned off.
+         */
+        public static final int ROUTE_ON_WHEN_SCREEN_ON = 2;
+
+        /**
+         * A route such as {@link #ROUTE_OFF} or {@link #ROUTE_ON_WHEN_SCREEN_ON}.
+         */
+        public final int route;
+
+        /**
+         * The {@link NFcExecutionEnvironment} that is Card Emulation is routed to.
+         * <p>null if {@link #route} is {@link #ROUTE_OFF}, otherwise not null.
+         */
+        public final NfcExecutionEnvironment nfcEe;
+
+        public CardEmulationRoute(int route, NfcExecutionEnvironment nfcEe) {
+            if (route == ROUTE_OFF && nfcEe != null) {
+                throw new IllegalArgumentException("must not specifiy a NFC-EE with ROUTE_OFF");
+            } else if (route != ROUTE_OFF && nfcEe == null) {
+                throw new IllegalArgumentException("must specifiy a NFC-EE for this route");
+            }
+            this.route = route;
+            this.nfcEe = nfcEe;
+        }
+    }
+
+    /**
+     * NFC service dead - attempt best effort recovery
+     */
+    void attemptDeadServiceRecovery(Exception e) {
+        Log.e(TAG, "NFC Adapter Extras dead - attempting to recover");
+        sAdapter.attemptDeadServiceRecovery(e);
+        initService();
+    }
+
+    INfcAdapterExtras getService() {
+        return sService;
+    }
+
+    /**
+     * Get the routing state of this NFC EE.
+     *
+     * <p class="note">
+     * Requires the {@link android.Manifest.permission#WRITE_SECURE_SETTINGS} permission.
+     *
+     * @return
+     */
+    public CardEmulationRoute getCardEmulationRoute() {
+        try {
+            int route = sService.getCardEmulationRoute();
+            return route == CardEmulationRoute.ROUTE_OFF ?
+                    sRouteOff :
+                    sRouteOnWhenScreenOn;
+        } catch (RemoteException e) {
+            attemptDeadServiceRecovery(e);
+            return sRouteOff;
+        }
+    }
+
+    /**
+     * Set the routing state of this NFC EE.
+     *
+     * <p>This routing state is not persisted across reboot.
+     *
+     * <p class="note">
+     * Requires the {@link android.Manifest.permission#WRITE_SECURE_SETTINGS} permission.
+     *
+     * @param route a {@link #CardEmulationRoute}
+     */
+    public void setCardEmulationRoute(CardEmulationRoute route) {
+        try {
+            sService.setCardEmulationRoute(route.route);
+        } catch (RemoteException e) {
+            attemptDeadServiceRecovery(e);
+        }
+    }
+
+    /**
+     * Get the {@link NfcExecutionEnvironment} that is embedded with the
+     * {@link NFcAdapter}.
+     *
+     * <p class="note">
+     * Requires the {@link android.Manifest.permission#WRITE_SECURE_SETTINGS} permission.
+     *
+     * @return a {@link NfcExecutionEnvironment}, or null if there is no embedded NFC-EE
+     */
+    public NfcExecutionEnvironment getEmbeddedExecutionEnvironment() {
+        return sEmbeddedEe;
+    }
+
+    /**
+     * Authenticate the client application.
+     *
+     * Some implementations of NFC Adapter Extras may require applications
+     * to authenticate with a token, before using other methods.
+     *
+     * @param a implementation specific token
+     * @throws a {@link java.lang.SecurityException} if authentication failed
+     */
+    public void authenticate(byte[] token) {
+        try {
+            sService.authenticate(token);
+        } catch (RemoteException e) {
+            attemptDeadServiceRecovery(e);
+        }
+    }
+}
diff --git a/nfc-extras/java/com/android/nfc_extras/NfcExecutionEnvironment.java b/nfc-extras/java/com/android/nfc_extras/NfcExecutionEnvironment.java
new file mode 100644
index 0000000..eb2f6f8
--- /dev/null
+++ b/nfc-extras/java/com/android/nfc_extras/NfcExecutionEnvironment.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.nfc_extras;
+
+import java.io.IOException;
+
+import android.annotation.SdkConstant;
+import android.annotation.SdkConstant.SdkConstantType;
+import android.content.Context;
+import android.nfc.INfcAdapterExtras;
+import android.nfc.NfcAdapter;
+import android.os.Binder;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.RemoteException;
+
+public class NfcExecutionEnvironment {
+    private final NfcAdapterExtras mExtras;
+
+    /**
+     * Broadcast Action: An ISO-DEP AID was selected.
+     *
+     * <p>This happens as the result of a 'SELECT AID' command from an
+     * external NFC reader/writer.
+     *
+     * <p>Always contains the extra field {@link #EXTRA_AID}
+     *
+     * <p class="note">
+     * Requires the {@link android.Manifest.permission#WRITE_SECURE_SETTINGS} permission
+     * to receive.
+     */
+    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
+    public static final String ACTION_AID_SELECTED =
+        "com.android.nfc_extras.action.AID_SELECTED";
+
+    /**
+     * Mandatory byte array extra field in {@link #ACTION_AID_SELECTED}.
+     *
+     * <p>Contains the AID selected.
+     * @hide
+     */
+    public static final String EXTRA_AID = "com.android.nfc_extras.extra.AID";
+
+    NfcExecutionEnvironment(NfcAdapterExtras extras) {
+        mExtras = extras;
+    }
+
+    /**
+     * Open the NFC Execution Environment on its contact interface.
+     *
+     * <p>Only one process may open the secure element at a time. If it is
+     * already open, an {@link IOException} is thrown.
+     *
+     * <p>All other NFC functionality is disabled while the NFC-EE is open
+     * on its contact interface, so make sure to call {@link #close} once complete.
+     *
+     * <p class="note">
+     * Requires the {@link android.Manifest.permission#WRITE_SECURE_SETTINGS} permission.
+     *
+     * @throws IOException if the NFC-EE is already open, or some other error occurs
+     */
+    public void open() throws IOException {
+        try {
+            Bundle b = mExtras.getService().open(new Binder());
+            throwBundle(b);
+        } catch (RemoteException e) {
+            mExtras.attemptDeadServiceRecovery(e);
+            throw new IOException("NFC Service was dead, try again");
+        }
+    }
+
+    /**
+     * Close the NFC Execution Environment on its contact interface.
+     *
+     * <p class="note">
+     * Requires the {@link android.Manifest.permission#WRITE_SECURE_SETTINGS} permission.
+     *
+     * @throws IOException if the NFC-EE is already open, or some other error occurs
+     */
+    public void close() throws IOException {
+        try {
+            throwBundle(mExtras.getService().close());
+        } catch (RemoteException e) {
+            mExtras.attemptDeadServiceRecovery(e);
+            throw new IOException("NFC Service was dead");
+        }
+    }
+
+    /**
+     * Send raw commands to the NFC-EE and receive the response.
+     *
+     * <p class="note">
+     * Requires the {@link android.Manifest.permission#WRITE_SECURE_SETTINGS} permission.
+     *
+     * @throws IOException if the NFC-EE is not open, or some other error occurs
+     */
+    public byte[] transceive(byte[] in) throws IOException {
+        Bundle b;
+        try {
+            b = mExtras.getService().transceive(in);
+        } catch (RemoteException e) {
+            mExtras.attemptDeadServiceRecovery(e);
+            throw new IOException("NFC Service was dead, need to re-open");
+        }
+        throwBundle(b);
+        return b.getByteArray("out");
+    }
+
+    private static void throwBundle(Bundle b) throws IOException {
+        if (b.getInt("e") == -1) {
+            throw new IOException(b.getString("m"));
+        }
+    }
+}
diff --git a/obex/javax/obex/ClientSession.java b/obex/javax/obex/ClientSession.java
index 0935383..27d8976 100644
--- a/obex/javax/obex/ClientSession.java
+++ b/obex/javax/obex/ClientSession.java
@@ -449,8 +449,8 @@
                 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 (maxPacketSize > ObexHelper.MAX_CLIENT_PACKET_SIZE) {
+                    maxPacketSize = ObexHelper.MAX_CLIENT_PACKET_SIZE;
                 }
 
                 if (length > 7) {
diff --git a/obex/javax/obex/ObexHelper.java b/obex/javax/obex/ObexHelper.java
index 1b66662..7852fe9 100644
--- a/obex/javax/obex/ObexHelper.java
+++ b/obex/javax/obex/ObexHelper.java
@@ -70,6 +70,12 @@
      */
     public static final int MAX_PACKET_SIZE_INT = 0xFFFE;
 
+    /**
+     * Temporary workaround to be able to push files to Windows 7.
+     * TODO: Should be removed as soon as Microsoft updates their driver.
+     */
+    public static final int MAX_CLIENT_PACKET_SIZE = 0xFC00;
+
     public static final int OBEX_OPCODE_CONNECT = 0x80;
 
     public static final int OBEX_OPCODE_DISCONNECT = 0x81;
diff --git a/obex/javax/obex/PrivateOutputStream.java b/obex/javax/obex/PrivateOutputStream.java
index ca420af..713f4ae 100644
--- a/obex/javax/obex/PrivateOutputStream.java
+++ b/obex/javax/obex/PrivateOutputStream.java
@@ -107,18 +107,15 @@
 
         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);
-            }
+        while ((mArray.size() + remainLength) >= mMaxPacketSize) {
+            int bufferLeft = mMaxPacketSize - mArray.size();
+            mArray.write(buffer, offset1, bufferLeft);
+            offset1 += bufferLeft;
+            remainLength -= bufferLeft;
+            mParent.continueOperation(true, false);
+        }
+        if (remainLength > 0) {
+            mArray.write(buffer, offset1, remainLength);
         }
     }
 
diff --git a/packages/SystemUI/AndroidManifest.xml b/packages/SystemUI/AndroidManifest.xml
index 7995869..a979d65 100644
--- a/packages/SystemUI/AndroidManifest.xml
+++ b/packages/SystemUI/AndroidManifest.xml
@@ -5,6 +5,7 @@
         >
 
     <uses-permission android:name="android.permission.STATUS_BAR_SERVICE" />
+    <uses-permission android:name="android.permission.MANAGE_USB" />
 
     <application
         android:persistent="true"
@@ -25,5 +26,40 @@
                 android:excludeFromRecents="true">
         </activity>
 
+        <!-- started from UsbDeviceSettingsManager -->
+        <activity android:name=".usb.UsbConfirmActivity"
+            android:exported="true"
+            android:permission="android.permission.MANAGE_USB"
+            android:theme="@*android:style/Theme.Dialog.Alert"
+            android:finishOnCloseSystemDialogs="true"
+            android:excludeFromRecents="true">
+        </activity>
+
+        <!-- started from UsbDeviceSettingsManager -->
+        <activity android:name=".usb.UsbPermissionActivity"
+            android:exported="true"
+            android:permission="android.permission.MANAGE_USB"
+            android:theme="@*android:style/Theme.Dialog.Alert"
+            android:finishOnCloseSystemDialogs="true"
+            android:excludeFromRecents="true">
+        </activity>
+
+        <!-- started from UsbDeviceSettingsManager -->
+        <activity android:name=".usb.UsbResolverActivity"
+            android:exported="true"
+            android:permission="android.permission.MANAGE_USB"
+            android:theme="@*android:style/Theme.Dialog.Alert"
+            android:finishOnCloseSystemDialogs="true"
+            android:excludeFromRecents="true">
+        </activity>
+
+        <!-- started from UsbDeviceSettingsManager -->
+        <activity android:name=".usb.UsbAccessoryUriActivity"
+            android:exported="true"
+            android:permission="android.permission.MANAGE_USB"
+            android:theme="@*android:style/Theme.Dialog.Alert"
+            android:finishOnCloseSystemDialogs="true"
+            android:excludeFromRecents="true">
+        </activity>
     </application>
 </manifest>
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_connected_4g.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_connected_4g.png
new file mode 100644
index 0000000..1aea612
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_connected_4g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_fully_connected_4g.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_fully_connected_4g.png
new file mode 100644
index 0000000..425535e
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_fully_connected_4g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_fully_in_4g.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_fully_in_4g.png
new file mode 100644
index 0000000..fcad363
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_fully_in_4g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_fully_inandout_4g.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_fully_inandout_4g.png
new file mode 100644
index 0000000..4ff7db3
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_fully_inandout_4g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_fully_out_4g.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_fully_out_4g.png
new file mode 100644
index 0000000..2c4a07f
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_fully_out_4g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_in_4g.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_in_4g.png
new file mode 100644
index 0000000..879c703
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_in_4g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_inadnout_e.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_inadnout_e.png
new file mode 100644
index 0000000..61a7503
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_inadnout_e.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_inandout_4g.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_inandout_4g.png
new file mode 100644
index 0000000..c5edf2c
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_inandout_4g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_out_4g.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_out_4g.png
new file mode 100644
index 0000000..ddf88be
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_out_4g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_0.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_0.png
new file mode 100644
index 0000000..f24d801
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_0.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_0_fully.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_0_fully.png
new file mode 100644
index 0000000..66eb5db
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_0_fully.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_1.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_1.png
new file mode 100644
index 0000000..edff74a
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_1.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_1_fully.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_1_fully.png
new file mode 100644
index 0000000..1cdd4eb
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_1_fully.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_2.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_2.png
new file mode 100644
index 0000000..95fdaf9
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_2.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_2_fully.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_2_fully.png
new file mode 100644
index 0000000..8678e39
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_2_fully.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_3.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_3.png
new file mode 100644
index 0000000..1d2d290
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_3.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_3_fully.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_3_fully.png
new file mode 100644
index 0000000..c2e4b78
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_3_fully.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_disconnected.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_disconnected.png
new file mode 100644
index 0000000..51b839f
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_disconnected.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_idle.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_idle.png
new file mode 100644
index 0000000..b20c5c7
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_wimax_signal_idle.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_roaming_cdma_0.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_roaming_cdma_0.png
index adde938..c8ddfce 100644
--- a/packages/SystemUI/res/drawable-hdpi/stat_sys_roaming_cdma_0.png
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_roaming_cdma_0.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_roaming_cdma_flash_anim1.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_roaming_cdma_flash_anim1.png
index adde938..6b6a6df 100644
--- a/packages/SystemUI/res/drawable-hdpi/stat_sys_roaming_cdma_flash_anim1.png
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_roaming_cdma_flash_anim1.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_1x.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_1x.png
index 78ece9e..c77e61e 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_1x.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_1x.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_3g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_3g.png
index 31fc1b02..b9f721a 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_3g.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_3g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_4g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_4g.png
new file mode 100644
index 0000000..cff969e
--- /dev/null
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_4g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_e.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_e.png
index 19adb4b0..d2d7ab3 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_e.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_e.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_g.png
index fd419ea..83ce6d0 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_g.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_h.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_h.png
index 94e77ae..abe511f 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_h.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_connected_h.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_1x.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_1x.png
index 91328c0..d685af8 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_1x.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_1x.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_3g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_3g.png
index 2fee6924..8c697a1 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_3g.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_3g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_4g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_4g.png
new file mode 100644
index 0000000..9a4b807
--- /dev/null
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_4g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_e.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_e.png
index d0968aa..eb11d04 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_e.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_e.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_g.png
index 991228b..6e54de0 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_g.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_h.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_h.png
index ae03e38..5bfb33b 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_h.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_connected_h.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_1x.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_1x.png
index 97b011e..119067b 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_1x.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_1x.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_3g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_3g.png
index a826866..a70cc2e 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_3g.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_3g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_4g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_4g.png
new file mode 100644
index 0000000..ea3dba7
--- /dev/null
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_4g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_e.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_e.png
index f6a6891..53221b9 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_e.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_e.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_g.png
index 19b9816..11d44d0 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_g.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_h.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_h.png
index f8c0961..9defd79 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_h.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_in_h.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_1x.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_1x.png
index 22deb70..136576d 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_1x.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_1x.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_3g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_3g.png
index c7c1b49..26ca31f 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_3g.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_3g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_4g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_4g.png
new file mode 100644
index 0000000..de8c5ee
--- /dev/null
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_4g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_e.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_e.png
index d9a0702..64dbf3c 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_e.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_e.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_g.png
index 6beed8a..34923fb 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_g.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_h.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_h.png
index e4179c1..506b5c6 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_h.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_inandout_h.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_1x.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_1x.png
index 4b2f86d..163976f 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_1x.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_1x.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_3g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_3g.png
index 6779604..a6af649 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_3g.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_3g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_4g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_4g.png
new file mode 100644
index 0000000..0c08e52
--- /dev/null
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_4g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_e.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_e.png
index 1309a97..1d02edb 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_e.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_e.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_g.png
index 2fc1e8e..edc9536 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_g.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_h.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_h.png
index 0eef2c1..8376817 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_h.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_fully_out_h.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_1x.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_1x.png
index f8904e2..ecef547 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_1x.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_1x.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_3g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_3g.png
index 3ef306e..a7c48b6 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_3g.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_3g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_4g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_4g.png
new file mode 100644
index 0000000..f4bcd9a
--- /dev/null
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_4g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_e.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_e.png
index 2ff6d90..b46bb3a 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_e.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_e.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_g.png
index 8ff49b0..e8b70f2 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_g.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_h.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_h.png
index f416203..4e23c4e 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_h.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_in_h.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inadnout_e.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inadnout_e.png
new file mode 100644
index 0000000..ced9175
--- /dev/null
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inadnout_e.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inandout_1x.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inandout_1x.png
index 24b7daa..92d4a19 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inandout_1x.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inandout_1x.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inandout_3g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inandout_3g.png
index 5ea9142..a208736 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inandout_3g.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inandout_3g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inandout_4g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inandout_4g.png
new file mode 100644
index 0000000..f407bc9
--- /dev/null
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inandout_4g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inandout_g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inandout_g.png
index 002bf46..b8a65c2 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inandout_g.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inandout_g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inandout_h.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inandout_h.png
index 924b84f..a978b68 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inandout_h.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_inandout_h.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_1x.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_1x.png
index bd0d1ca..710dd52 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_1x.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_1x.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_3g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_3g.png
index f583eec..a7b35e4 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_3g.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_3g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_4g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_4g.png
new file mode 100644
index 0000000..bb05449
--- /dev/null
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_4g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_e.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_e.png
index 66940eaf..a144222 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_e.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_e.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_g.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_g.png
index 0381f52..b0eafb6 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_g.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_g.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_h.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_h.png
index 0b84fe8..f6b83d0 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_h.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_out_h.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_roaming_cdma_0.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_roaming_cdma_0.png
index c61cce7..827d84a 100755
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_roaming_cdma_0.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_roaming_cdma_0.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_roaming_cdma_flash_anim1.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_roaming_cdma_flash_anim1.png
index c61cce7..edc6023 100755
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_roaming_cdma_flash_anim1.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_roaming_cdma_flash_anim1.png
Binary files differ
diff --git a/packages/SystemUI/res/values-ar/strings.xml b/packages/SystemUI/res/values-ar/strings.xml
index 68b0b0a..dc6beb5 100644
--- a/packages/SystemUI/res/values-ar/strings.xml
+++ b/packages/SystemUI/res/values-ar/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"البطارية منخفضة:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"يتبقى <xliff:g id="NUMBER">%d%%</xliff:g> أو أقل."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"استخدام البطارية"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"لا يعمل أي تطبيق مثبت مع ملحق UEB هذا. تعرف على المزيد عن هذا الملحق على <xliff:g id="URL">%1$s</xliff:g>."</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"ملحق USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"عرض"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"الاستخدام بشكل افتراضي لملحق USB هذا"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-bg/strings.xml b/packages/SystemUI/res/values-bg/strings.xml
index 12a3f23..d9ee86a 100644
--- a/packages/SystemUI/res/values-bg/strings.xml
+++ b/packages/SystemUI/res/values-bg/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Батерията се изтощава:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"Остава <xliff:g id="NUMBER">%d%%</xliff:g> или по-малко."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Използване на батерията"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Инсталираните приложения не работят с този аксесоар за USB. Научете повече на адрес <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"Аксесоар за USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"Преглед"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Използване по подразб. за този аксесоар за USB"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-ca/strings.xml b/packages/SystemUI/res/values-ca/strings.xml
index 655cd63..debf301 100644
--- a/packages/SystemUI/res/values-ca/strings.xml
+++ b/packages/SystemUI/res/values-ca/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Comença a quedar poca bateria:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"En queda un <xliff:g id="NUMBER">%d%%</xliff:g> o menys."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Ús de la bateria"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Cap de les aplicacions instal·lades no funciona amb aquest accessori USB. Més informació a <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"Accessori USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"Mostra"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Utilitza de manera predet. per a l\'accessori USB"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-cs/strings.xml b/packages/SystemUI/res/values-cs/strings.xml
index 3e7136a..7095c34 100644
--- a/packages/SystemUI/res/values-cs/strings.xml
+++ b/packages/SystemUI/res/values-cs/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Baterie je vybitá:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"Zbývá <xliff:g id="NUMBER">%d%%</xliff:g> nebo méně."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Využití baterie"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"S tímto periferním zařízením USB nefunguje žádná nainstalovaná aplikace. Další informace naleznete na stránkách <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"Periferní zařízení USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"Zobrazit"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Pro toto periferní zařízení USB použít jako výchozí"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-da/strings.xml b/packages/SystemUI/res/values-da/strings.xml
index bf549fd..86185e1 100644
--- a/packages/SystemUI/res/values-da/strings.xml
+++ b/packages/SystemUI/res/values-da/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Batteriet er ved at være fladt:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"<xliff:g id="NUMBER">%d%%</xliff:g> eller mindre tilbage."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Batteriforbrug"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Ingen inst. programmer virker med USB-ekstraudstyret. Få oplysninger om ekstraudstyret på <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"USB-ekstraudstyr"</string>
+    <string name="label_view" msgid="6304565553218192990">"Vis"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Brug som standard til dette USB-tilbehør"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-de/strings.xml b/packages/SystemUI/res/values-de/strings.xml
index e534116..a88244b 100644
--- a/packages/SystemUI/res/values-de/strings.xml
+++ b/packages/SystemUI/res/values-de/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Akku ist fast leer."</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"<xliff:g id="NUMBER">%d%%</xliff:g> oder weniger verbleiben."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Akkuverbrauch"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Keine installierten Anwendungen für dieses USB-Zubehör. Weitere Informationen unter <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"USB-Zubehör"</string>
+    <string name="label_view" msgid="6304565553218192990">"Anzeigen"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Standardmäßig für dieses USB-Zubehör verwenden"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-el/strings.xml b/packages/SystemUI/res/values-el/strings.xml
index c96e403..8200a30 100644
--- a/packages/SystemUI/res/values-el/strings.xml
+++ b/packages/SystemUI/res/values-el/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Η στάθμη της μπαταρίας είναι χαμηλή:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"Απομένει <xliff:g id="NUMBER">%d%%</xliff:g> ή λιγότερο."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Χρήση μπαταρίας"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Καμία εγκατ. εφαρμ. δεν συνεργ. με το αξ. USB. Μάθετε περισ. για το αξ. στο <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"Αξεσουάρ USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"Προβολή"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Χρήση από προεπιλογή για αυτό το εξάρτημα USB"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-en-rGB/strings.xml b/packages/SystemUI/res/values-en-rGB/strings.xml
index 74343da..cb21a03 100644
--- a/packages/SystemUI/res/values-en-rGB/strings.xml
+++ b/packages/SystemUI/res/values-en-rGB/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"The battery is getting low:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"<xliff:g id="NUMBER">%d%%</xliff:g> or less remaining."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Battery use"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"No installed applications work with this USB accessory. Learn more about this accessory at <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"USB accessory"</string>
+    <string name="label_view" msgid="6304565553218192990">"View"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Use by default for this USB accessory"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-es-rUS/strings.xml b/packages/SystemUI/res/values-es-rUS/strings.xml
index 29a1f20..ce31628 100644
--- a/packages/SystemUI/res/values-es-rUS/strings.xml
+++ b/packages/SystemUI/res/values-es-rUS/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Hay poca batería:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"<xliff:g id="NUMBER">%d%%</xliff:g> o menos disponible."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Uso de la batería"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Las aplicaciones instaladas no funcionan con este accesorio USB. Obtener más información acerca de este accesorio en <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"Accesorio USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"Ver"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Se usa de forma predeterminada para este accesorio USB."</string>
 </resources>
diff --git a/packages/SystemUI/res/values-es/strings.xml b/packages/SystemUI/res/values-es/strings.xml
index 3c2b060..1f0fd16 100644
--- a/packages/SystemUI/res/values-es/strings.xml
+++ b/packages/SystemUI/res/values-es/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Se está agotando la batería:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"<xliff:g id="NUMBER">%d%%</xliff:g> o menos disponible"</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Uso de la batería"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Ninguna aplicación instalada funciona con este accesorio USB. Más información: <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"Accesorio USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"Ver"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Usar de forma predeterminada para este accesorio USB"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-fa/strings.xml b/packages/SystemUI/res/values-fa/strings.xml
index ff72480..fe85637 100644
--- a/packages/SystemUI/res/values-fa/strings.xml
+++ b/packages/SystemUI/res/values-fa/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"باتری در حال کم شدن است:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"<xliff:g id="NUMBER">%d%%</xliff:g> یا کمتر باقیمانده است."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"استفاده از باتری"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"برنامه های نصب شده با این وسیله جانبی USB کار می کنند. در <xliff:g id="URL">%1$s</xliff:g>راجع به این لوازم جانبی بیشتر بیاموزید"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"لوازم جانبی USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"مشاهده"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"استفاده به صورت پیش فرض برای این دستگاه USB"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-fi/strings.xml b/packages/SystemUI/res/values-fi/strings.xml
index 4e69881..ab43e71 100644
--- a/packages/SystemUI/res/values-fi/strings.xml
+++ b/packages/SystemUI/res/values-fi/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Akun virta on vähissä:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"jäljellä <xliff:g id="NUMBER">%d%%</xliff:g> tai vähemmän."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Akun käyttö"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Asennetut sov. eivät toimi tämän USB-lisälaitteen kanssa. Lisätietoja lisälaitteesta os. <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"USB-lisälaite"</string>
+    <string name="label_view" msgid="6304565553218192990">"Näytä"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Käytä oletuksena tällä USB-lisälaitteella"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-fr/strings.xml b/packages/SystemUI/res/values-fr/strings.xml
index b3aa6d9..8865e0f 100644
--- a/packages/SystemUI/res/values-fr/strings.xml
+++ b/packages/SystemUI/res/values-fr/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Le niveau de la batterie est bas :"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"Maximum <xliff:g id="NUMBER">%d%%</xliff:g> restants."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Utilisation de la batterie"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Aucune application installée n\'est compatible avec cet accessoire USB. En savoir plus sur <xliff:g id="URL">%1$s</xliff:g>."</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"Accessoire USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"Afficher"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Utiliser par défaut pour cet accessoire USB"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-hr/strings.xml b/packages/SystemUI/res/values-hr/strings.xml
index 9a6b95d..ab133f1 100644
--- a/packages/SystemUI/res/values-hr/strings.xml
+++ b/packages/SystemUI/res/values-hr/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Baterija će uskoro biti potrošena:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"Preostaje <xliff:g id="NUMBER">%d%%</xliff:g> ili manje."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Iskorištenost baterije"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Nijedna instalirana aplikacija ne radi s ovim USB dodatkom. Saznajte više o ovom dodatku na <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"USB pribor"</string>
+    <string name="label_view" msgid="6304565553218192990">"Prikaži"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Koristi se prema zadanim postavkama za ovaj USB pribor"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-hu/strings.xml b/packages/SystemUI/res/values-hu/strings.xml
index 2bddb7e..ff2f4bf 100644
--- a/packages/SystemUI/res/values-hu/strings.xml
+++ b/packages/SystemUI/res/values-hu/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Akkufeszültség alacsony:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"<xliff:g id="NUMBER">%d%%</xliff:g> vagy kevesebb maradt."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Akkumulátorhasználat"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"A telepített alkalmazások nem működnek ezzel az USB-kiegészítővel. Bővebben: <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"USB-kellék"</string>
+    <string name="label_view" msgid="6304565553218192990">"Megtekintés"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Alapértelmezett használat ehhez az USB-kiegészítőhöz"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-in/strings.xml b/packages/SystemUI/res/values-in/strings.xml
index c49accf..d51a51d 100644
--- a/packages/SystemUI/res/values-in/strings.xml
+++ b/packages/SystemUI/res/values-in/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Baterai kekurangan daya:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"<xliff:g id="NUMBER">%d%%</xliff:g> atau kurang yang tersisa."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Penggunaan baterai"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Tidak ada aplikasi terpasang yang bekerja dengan aksesori USB ini. Pelajari aksesori ini lebih lanjut di <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"Aksesori USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"Lihat"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Gunakan secara bawaan untuk aksesori USB ini"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-it/strings.xml b/packages/SystemUI/res/values-it/strings.xml
index f0003fc..7e75478 100644
--- a/packages/SystemUI/res/values-it/strings.xml
+++ b/packages/SystemUI/res/values-it/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Batteria quasi scarica:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"<xliff:g id="NUMBER">%d%%</xliff:g> rimanente o meno."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Utilizzo batteria"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Applicazioni installate non funzionano con accessorio USB. Altre informazioni su accessorio su <xliff:g id="URL">%1$s</xliff:g>."</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"Accessorio USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"Visualizza"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Usa per impostazione predef. per accessorio USB"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-iw/strings.xml b/packages/SystemUI/res/values-iw/strings.xml
index 6b6e628..3fe91b26 100644
--- a/packages/SystemUI/res/values-iw/strings.xml
+++ b/packages/SystemUI/res/values-iw/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"הסוללה נחלשת:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"נותרו עוד <xliff:g id="NUMBER">%d%%</xliff:g> או פחות."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"צריכת סוללה"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"אין יישומים מותקנים הפועלים עם אביזר ה-USB. למידע נוסף אודות אביזר זה בכתובת <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"עזרי USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"הצג"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"השתמש כברירת מחדל עבור אביזר USB זה"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-ja/strings.xml b/packages/SystemUI/res/values-ja/strings.xml
index 7ac8227..ee75d38 100644
--- a/packages/SystemUI/res/values-ja/strings.xml
+++ b/packages/SystemUI/res/values-ja/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"電池が残り少なくなっています:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"残り<xliff:g id="NUMBER">%d%%</xliff:g>未満です。"</string>
     <string name="battery_low_why" msgid="7279169609518386372">"電池使用量"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"このUSBアクセサリを扱うアプリはインストールされていません。詳細は <xliff:g id="URL">%1$s</xliff:g> をご覧ください。"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"USBアクセサリ"</string>
+    <string name="label_view" msgid="6304565553218192990">"表示"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"このUSBアクセサリにデフォルトで使用する"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-ko/strings.xml b/packages/SystemUI/res/values-ko/strings.xml
index fe76942b..56fc57d 100644
--- a/packages/SystemUI/res/values-ko/strings.xml
+++ b/packages/SystemUI/res/values-ko/strings.xml
@@ -25,7 +25,17 @@
     <string name="status_bar_ongoing_events_title" msgid="1682504513316879202">"진행 중"</string>
     <string name="status_bar_latest_events_title" msgid="6594767438577593172">"알림"</string>
     <string name="battery_low_title" msgid="7923774589611311406">"충전기를 연결하세요."</string>
-    <string name="battery_low_subtitle" msgid="7388781709819722764">"배터리 전원이 부족합니다."</string>
+    <string name="battery_low_subtitle" msgid="7388781709819722764">"배터리가 얼마 남지 않았습니다."</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"잔여 배터리가 <xliff:g id="NUMBER">%d%%</xliff:g> 이하입니다."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"배터리 사용량"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"이 USB와 호환되는 설치 애플리케이션이 없습니다. <xliff:g id="URL">%1$s</xliff:g>에서 세부정보를 참조하세요."</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"USB 액세서리"</string>
+    <string name="label_view" msgid="6304565553218192990">"보기"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"이 USB 액세서리에 기본값으로 사용"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-lt/strings.xml b/packages/SystemUI/res/values-lt/strings.xml
index c016922..47102c6 100644
--- a/packages/SystemUI/res/values-lt/strings.xml
+++ b/packages/SystemUI/res/values-lt/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Akumuliatorius senka:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"Liko <xliff:g id="NUMBER">%d%%</xliff:g> ar mažiau."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Akumuliatoriaus naudojimas"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Su šiuo USB pr. nev. jokios įdieg. pr. Suž. daugiau apie šį pr. šiuo adr.: <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"USB reikmuo"</string>
+    <string name="label_view" msgid="6304565553218192990">"Žiūrėti"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Šiam USB priedui naudoti pagal numat. nustatymus"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-lv/strings.xml b/packages/SystemUI/res/values-lv/strings.xml
index f462282..60f05fe 100644
--- a/packages/SystemUI/res/values-lv/strings.xml
+++ b/packages/SystemUI/res/values-lv/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Akumulatora uzlādes līmenis kļūst zems:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"Atlicis <xliff:g id="NUMBER">%d%%</xliff:g> vai mazāk."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Akumulatora lietojums"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Neinst. lietojumpr. darbojas ar šo USB pied. Uzz. vairāk par šo piederumu: <xliff:g id="URL">%1$s</xliff:g>."</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"USB piederums"</string>
+    <string name="label_view" msgid="6304565553218192990">"Skatīt"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Pēc noklusējuma izmantot šim USB piederumam"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-nb/strings.xml b/packages/SystemUI/res/values-nb/strings.xml
index 94d7e6a..9d6bddc 100644
--- a/packages/SystemUI/res/values-nb/strings.xml
+++ b/packages/SystemUI/res/values-nb/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Batteriet er nesten tomt:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"mindre enn <xliff:g id="NUMBER">%d%%</xliff:g> igjen."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Batteribruk"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Ingen installerte applikasjoner støtter dette USB-tilbehøret. Les mer om tilbehøret på <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"USB-enhet"</string>
+    <string name="label_view" msgid="6304565553218192990">"Vis"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Bruk som standard for dette USB-tilbehøret"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-nl/strings.xml b/packages/SystemUI/res/values-nl/strings.xml
index de4f5be..4671361 100644
--- a/packages/SystemUI/res/values-nl/strings.xml
+++ b/packages/SystemUI/res/values-nl/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"De accu raakt op:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"<xliff:g id="NUMBER">%d%%</xliff:g> of minder resterend."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Accugebruik"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Er zijn geen geïnstalleerde applicaties die werken met dit USB-accessoire. Meer informatie over dit accessoire vindt u op <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"USB-accessoire"</string>
+    <string name="label_view" msgid="6304565553218192990">"Weergeven"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Standaard gebruiken voor dit USB-accessoire"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-pl/strings.xml b/packages/SystemUI/res/values-pl/strings.xml
index b1770d6..af00198 100644
--- a/packages/SystemUI/res/values-pl/strings.xml
+++ b/packages/SystemUI/res/values-pl/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Bateria się rozładowuje:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"Pozostało: <xliff:g id="NUMBER">%d%%</xliff:g> lub mniej."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Użycie baterii"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Zainstalowane aplikacje nie działają z tym akcesorium USB. Więcej informacji: <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"Akcesorium USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"Wyświetl"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Używaj domyślnie dla tego akcesorium USB"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-pt-rPT/strings.xml b/packages/SystemUI/res/values-pt-rPT/strings.xml
index f80031c..383fc09 100644
--- a/packages/SystemUI/res/values-pt-rPT/strings.xml
+++ b/packages/SystemUI/res/values-pt-rPT/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"A bateria está a ficar fraca:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"Restam <xliff:g id="NUMBER">%d%%</xliff:g> ou menos."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Utilização da bateria"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Nenhuma das aplicações instaladas funciona com este acessório USB. Saiba mais sobre este acessório em <xliff:g id="URL">%1$s</xliff:g>."</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"Acessório USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"Ver"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Utilizar por predefinição para este acessório USB"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-pt/strings.xml b/packages/SystemUI/res/values-pt/strings.xml
index 3abf8e1..7c800c3 100644
--- a/packages/SystemUI/res/values-pt/strings.xml
+++ b/packages/SystemUI/res/values-pt/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"A bateria está ficando baixa:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"<xliff:g id="NUMBER">%d%%</xliff:g> ou menos restante(s)."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Uso da bateria"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Nenhum apl. instalado funciona com o acess. USB. Saiba mais sobre o acessório em <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"Acessório USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"Visualizar"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Usar por padrão para este acessório USB"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-rm/strings.xml b/packages/SystemUI/res/values-rm/strings.xml
index 0db8430..d6ceed5 100644
--- a/packages/SystemUI/res/values-rm/strings.xml
+++ b/packages/SystemUI/res/values-rm/strings.xml
@@ -29,4 +29,18 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"L\'accu è prest vid."</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"<xliff:g id="NUMBER">%d%%</xliff:g> u pli pauc restant."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Consum dad accu"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <!-- no translation found for usb_accessory_uri_prompt (6332150684964235705) -->
+    <skip />
+    <!-- no translation found for title_usb_accessory (4966265263465181372) -->
+    <skip />
+    <!-- no translation found for label_view (6304565553218192990) -->
+    <skip />
+    <!-- no translation found for always_use_accessory (1210954576979621596) -->
+    <skip />
 </resources>
diff --git a/packages/SystemUI/res/values-ro/strings.xml b/packages/SystemUI/res/values-ro/strings.xml
index 3587a03..0fac35df 100644
--- a/packages/SystemUI/res/values-ro/strings.xml
+++ b/packages/SystemUI/res/values-ro/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Bateria se termină:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"A rămas <xliff:g id="NUMBER">%d%%</xliff:g> sau mai puţin."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Utilizarea bateriei"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Aplic. instal. nu funcţ. cu acest acces. USB. Aflaţi despre acest acces. la <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"Accesoriu USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"Afişaţi"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Utiliz. în mod prestabilit pt. acest accesoriu USB"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-ru/strings.xml b/packages/SystemUI/res/values-ru/strings.xml
index e465767..24d3c04 100644
--- a/packages/SystemUI/res/values-ru/strings.xml
+++ b/packages/SystemUI/res/values-ru/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Батарея разряжена:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"Осталось <xliff:g id="NUMBER">%d%%</xliff:g> или меньше."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Расход заряда батареи"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Установленные приложения не поддерживают этот USB-аксессуар. Подробнее о нем читайте здесь: <xliff:g id="URL">%1$s</xliff:g>."</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"USB-устройство"</string>
+    <string name="label_view" msgid="6304565553218192990">"Просмотр"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Использовать по умолчанию для этого USB-аксессуара"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-sk/strings.xml b/packages/SystemUI/res/values-sk/strings.xml
index 929f774..cd25c8d 100644
--- a/packages/SystemUI/res/values-sk/strings.xml
+++ b/packages/SystemUI/res/values-sk/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Batéria je skoro vybitá:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"Zostáva <xliff:g id="NUMBER">%d%%</xliff:g> alebo menej."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Využitie batérie"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"S týmto periférnym zariad. USB nefunguje žiadna nainštalovaná aplikácia. Viac informácií nájdete na stránkach <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"Periférne zariadenie USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"Zobraziť"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Pre toto periférne zar. USB použiť ako predvolené"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-sl/strings.xml b/packages/SystemUI/res/values-sl/strings.xml
index 5ae3ab3..2737460 100644
--- a/packages/SystemUI/res/values-sl/strings.xml
+++ b/packages/SystemUI/res/values-sl/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Baterija je skoraj prazna:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"Preostalo <xliff:g id="NUMBER">%d%%</xliff:g> ali manj."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Uporaba baterije"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Noben nameščen program ne deluje s tem dodatkom USB. Več o tem dodatku: <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"Dodatek USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"Prikaži"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Privzeto uporabi za ta dodatek USB"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-sr/strings.xml b/packages/SystemUI/res/values-sr/strings.xml
index e6d8bde..cfccd5d 100644
--- a/packages/SystemUI/res/values-sr/strings.xml
+++ b/packages/SystemUI/res/values-sr/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Ниво напуњености батерије је низак:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"Преостало је <xliff:g id="NUMBER">%d%%</xliff:g> или мање."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Коришћење батерије"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Ниједна инстал. апликација не функционише са овим USB додатком. Сазнајте више о додатку на <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"USB помоћни уређај"</string>
+    <string name="label_view" msgid="6304565553218192990">"Прикажи"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Користи подразумевано за овај USB додатак"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-sv/strings.xml b/packages/SystemUI/res/values-sv/strings.xml
index 29147bd..df69140 100644
--- a/packages/SystemUI/res/values-sv/strings.xml
+++ b/packages/SystemUI/res/values-sv/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Batteriet håller på att ta slut:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"<xliff:g id="NUMBER">%d%%</xliff:g> eller mindre kvar."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Batteriförbrukning"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Inga program fungerar med det här USB-tillbehöret. Läs mer om det på <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"USB-tillbehör"</string>
+    <string name="label_view" msgid="6304565553218192990">"Visa"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Använd som standard för det här USB-tillbehöret"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-th/strings.xml b/packages/SystemUI/res/values-th/strings.xml
index e6922c2..2d9d23a 100644
--- a/packages/SystemUI/res/values-th/strings.xml
+++ b/packages/SystemUI/res/values-th/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"แบตเตอรี่เหลือน้อย"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"เหลือ <xliff:g id="NUMBER">%d%%</xliff:g> หรือน้อยกว่า"</string>
     <string name="battery_low_why" msgid="7279169609518386372">"การใช้แบตเตอรี่"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"แอปพลิเคชันที่ติดตั้งใช้กับอุปกรณ์ USB นี้ไม่ได้ เรียนรู้เพิ่มเติมที่ <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"อุปกรณ์เสริม USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"ดู"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"ใช้ค่าเริ่มต้นสำหรับอุปกรณ์เสริม USB นี้"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-tl/strings.xml b/packages/SystemUI/res/values-tl/strings.xml
index e54753b..3d9039c 100644
--- a/packages/SystemUI/res/values-tl/strings.xml
+++ b/packages/SystemUI/res/values-tl/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Humihina ang baterya:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"<xliff:g id="NUMBER">%d%%</xliff:g> o mas kaunti ang natitira."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Paggamit ng baterya"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Walang gumaganang mga naka-install na application sa USB accessory na ito <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"USB accessory"</string>
+    <string name="label_view" msgid="6304565553218192990">"Tingnan"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Gamitin bilang default sa USB accessory na ito"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-tr/strings.xml b/packages/SystemUI/res/values-tr/strings.xml
index 43808bc..eb0392d 100644
--- a/packages/SystemUI/res/values-tr/strings.xml
+++ b/packages/SystemUI/res/values-tr/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Pil tükeniyor:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"<xliff:g id="NUMBER">%d%%</xliff:g> veya daha az kaldı."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Pil kullanımı"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Hiçbir yüklü uyg bu USB aksesuarıyla çalışmıyor. Bu aksesuar hakknd daha fazla bilgi için: <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"USB aksesuarı"</string>
+    <string name="label_view" msgid="6304565553218192990">"Görüntüle"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Bu USB aksesuar için varsayılan olarak kullan"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-uk/strings.xml b/packages/SystemUI/res/values-uk/strings.xml
index 66bc927..449313c 100644
--- a/packages/SystemUI/res/values-uk/strings.xml
+++ b/packages/SystemUI/res/values-uk/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Батарея виснажується:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"Залиш-ся <xliff:g id="NUMBER">%d%%</xliff:g> або менше."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Викор. батареї"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Установлені прогр. не працюють із цим аксесуаром USB. Більше про цей аксесуар: <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"Пристрій USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"Переглянути"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Використовувати за умовчанням для аксесуара USB"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-vi/strings.xml b/packages/SystemUI/res/values-vi/strings.xml
index f0e6f9d..877c6e2 100644
--- a/packages/SystemUI/res/values-vi/strings.xml
+++ b/packages/SystemUI/res/values-vi/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"Pin đang yếu:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"còn <xliff:g id="NUMBER">%d%%</xliff:g> hoặc ít hơn."</string>
     <string name="battery_low_why" msgid="7279169609518386372">"Sử dụng pin"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"Không có ứng dụng được cài đặt nào hoạt động với phụ kiện USB này. Tìm hiểu thêm về phụ kiện này tại <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"Phụ kiện USB"</string>
+    <string name="label_view" msgid="6304565553218192990">"Xem"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"Sử dụng theo mặc định cho phụ kiện USB này"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-zh-rCN/strings.xml b/packages/SystemUI/res/values-zh-rCN/strings.xml
index 5ac5f97..96d0b03 100644
--- a/packages/SystemUI/res/values-zh-rCN/strings.xml
+++ b/packages/SystemUI/res/values-zh-rCN/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"电量所剩不多:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"电量剩余 <xliff:g id="NUMBER">%d%%</xliff:g> 或更少。"</string>
     <string name="battery_low_why" msgid="7279169609518386372">"电量使用情况"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"未安装此 USB 配件适用的应用程序。要了解关于此配件的详情,请访问:<xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"USB 配件"</string>
+    <string name="label_view" msgid="6304565553218192990">"查看"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"默认情况下用于该 USB 配件"</string>
 </resources>
diff --git a/packages/SystemUI/res/values-zh-rTW/strings.xml b/packages/SystemUI/res/values-zh-rTW/strings.xml
index ed6e02e..3cba543 100644
--- a/packages/SystemUI/res/values-zh-rTW/strings.xml
+++ b/packages/SystemUI/res/values-zh-rTW/strings.xml
@@ -28,4 +28,14 @@
     <string name="battery_low_subtitle" msgid="7388781709819722764">"電池電量即將不足:"</string>
     <string name="battery_low_percent_format" msgid="696154104579022959">"還剩 <xliff:g id="NUMBER">%d%%</xliff:g> 以下。"</string>
     <string name="battery_low_why" msgid="7279169609518386372">"電池使用狀況"</string>
+    <!-- no translation found for usb_accessory_permission_prompt (3969745913539898765) -->
+    <skip />
+    <!-- no translation found for usb_device_confirm_prompt (2727793581411868504) -->
+    <skip />
+    <!-- no translation found for usb_accessory_confirm_prompt (3947430407252730383) -->
+    <skip />
+    <string name="usb_accessory_uri_prompt" msgid="6332150684964235705">"已安裝的應用程式均無法存取這類 USB 配件,如要進一步瞭解這個配件,請造訪 <xliff:g id="URL">%1$s</xliff:g>"</string>
+    <string name="title_usb_accessory" msgid="4966265263465181372">"USB 配件"</string>
+    <string name="label_view" msgid="6304565553218192990">"查看"</string>
+    <string name="always_use_accessory" msgid="1210954576979621596">"預設用於這個 USB 配件"</string>
 </resources>
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index ba3a3d1..6334b2a 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -51,4 +51,25 @@
          power usage activity to find out what drained the battery. -->
     <string name="battery_low_why">Battery use</string>
 
+    <!-- Prompt for the USB accessory permission dialog [CHAR LIMIT=80] -->
+    <string name="usb_accessory_permission_prompt">Allow the application %1$s to access the USB accessory?</string>
+
+    <!-- Prompt for the USB device confirm dialog [CHAR LIMIT=80] -->
+    <string name="usb_device_confirm_prompt">Open %1$s when this USB device is connected?</string>
+
+    <!-- Prompt for the USB accessory confirm dialog [CHAR LIMIT=80] -->
+    <string name="usb_accessory_confirm_prompt">Open %1$s when this USB accessory is connected?</string>
+
+    <!-- Prompt for the USB accessory URI dialog [CHAR LIMIT=80] -->
+    <string name="usb_accessory_uri_prompt">No installed applications work with this USB accessory. Learn more about this accessory at <xliff:g id="url">%1$s</xliff:g></string>
+
+    <!-- Title for USB accessory dialog.  Used when the name of the accessory cannot be determined.  [CHAR LIMIT=50] -->
+    <string name="title_usb_accessory">USB accessory</string>
+
+    <!-- View button label for USB dialogs.  [CHAR LIMIT=15] -->
+    <string name="label_view">View</string>
+
+    <!-- Checkbox label for USB accessory dialogs.  [CHAR LIMIT=50] -->
+    <string name="always_use_accessory">Use by default for this USB accessory</string>
+
 </resources>
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarPolicy.java b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarPolicy.java
index 9ef6e6f..b30a043 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarPolicy.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarPolicy.java
@@ -74,6 +74,7 @@
 import com.android.server.am.BatteryStatsService;
 
 import com.android.systemui.R;
+import android.net.wimax.WimaxManagerConstants;
 
 /**
  * This class contains all of the policy about which icons are installed in the status
@@ -239,9 +240,165 @@
         R.drawable.stat_sys_roaming_cdma_0,
         R.drawable.stat_sys_roaming_cdma_0,
         R.drawable.stat_sys_roaming_cdma_0,
-        R.drawable.stat_sys_roaming_cdma_0 //83
+        R.drawable.stat_sys_roaming_cdma_0, //83
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0,
+        R.drawable.stat_sys_roaming_cdma_0 //239
 
-        // 128-255 Reserved
+        // 240-255 Reserved
     };
 
     //***** Data connection icons
@@ -311,6 +468,9 @@
     ServiceState mServiceState;
     SignalStrength mSignalStrength;
 
+    // flag for signal strength behavior
+    private boolean mAlwaysUseCdmaRssi;
+
     // data connection
     private boolean mDataIconVisible;
     private boolean mHspaDataDistinguishable;
@@ -341,6 +501,25 @@
     private int mLastWifiSignalLevel = -1;
     private boolean mIsWifiConnected = false;
 
+    //4G
+    private static final int[][] sWimaxSignalImages = {
+            { R.drawable.stat_sys_data_wimax_signal_0,
+              R.drawable.stat_sys_data_wimax_signal_1,
+              R.drawable.stat_sys_data_wimax_signal_2,
+              R.drawable.stat_sys_data_wimax_signal_3 },
+            { R.drawable.stat_sys_data_wimax_signal_0_fully,
+              R.drawable.stat_sys_data_wimax_signal_1_fully,
+              R.drawable.stat_sys_data_wimax_signal_2_fully,
+              R.drawable.stat_sys_data_wimax_signal_3_fully }
+        };
+    private static final int sWimaxDisconnectedImg =
+            R.drawable.stat_sys_data_wimax_signal_disconnected;
+    private static final int sWimaxIdleImg = R.drawable.stat_sys_data_wimax_signal_idle;
+    private boolean mIsWimaxEnabled = false;
+    private int mWimaxSignal = 0;
+    private int mWimaxState = 0;
+    private int mWimaxExtraState = 0;
+
     // state of inet connection - 0 not connected, 100 connected
     private int mInetCondition = 0;
 
@@ -398,6 +577,11 @@
                 // TODO - stop using other means to get wifi/mobile info
                 updateConnectivity(intent);
             }
+            else if (action.equals(WimaxManagerConstants.WIMAX_ENABLED_STATUS_CHANGED) ||
+                     action.equals(WimaxManagerConstants.SIGNAL_LEVEL_CHANGED_ACTION) ||
+                     action.equals(WimaxManagerConstants.WIMAX_STATE_CHANGED_ACTION)) {
+                updateWiMAX(intent);
+            }
         }
     };
 
@@ -419,6 +603,8 @@
         mPhone = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
         mPhoneSignalIconId = R.drawable.stat_sys_signal_null;
         mService.setIcon("phone_signal", mPhoneSignalIconId, 0);
+        mAlwaysUseCdmaRssi = mContext.getResources().getBoolean(
+            com.android.internal.R.bool.config_alwaysUseCdmaRssi);
 
         // register for phone state notifications.
         ((TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE))
@@ -438,6 +624,15 @@
         mService.setIconVisibility("wifi", false);
         // wifi will get updated by the sticky intents
 
+        // wimax
+        //enable/disable wimax depending on the value in config.xml
+        boolean isWimaxEnabled = mContext.getResources().getBoolean(
+                com.android.internal.R.bool.config_wimaxEnabled);
+        if (isWimaxEnabled) {
+            mService.setIcon("wimax", sWimaxDisconnectedImg, 0);
+            mService.setIconVisibility("wimax", false);
+        }
+
         // TTY status
         mService.setIcon("tty",  R.drawable.stat_sys_tty_mode, 0);
         mService.setIconVisibility("tty", false);
@@ -503,6 +698,10 @@
         filter.addAction(TtyIntent.TTY_ENABLED_CHANGE_ACTION);
         filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
         filter.addAction(ConnectivityManager.INET_CONDITION_ACTION);
+        filter.addAction(WimaxManagerConstants.WIMAX_STATE_CHANGED_ACTION);
+        filter.addAction(WimaxManagerConstants.SIGNAL_LEVEL_CHANGED_ACTION);
+        filter.addAction(WimaxManagerConstants.WIMAX_ENABLED_STATUS_CHANGED);
+
         mContext.registerReceiver(mIntentReceiver, filter, null, mHandler);
 
         // load config to determine if to distinguish Hspa data icon
@@ -744,6 +943,10 @@
             }
             updateSignalStrength(); // apply any change in mInetCondition
             break;
+        case ConnectivityManager.TYPE_WIMAX:
+            mInetCondition = inetCondition;
+            updateWiMAX(intent);
+            break;
         }
     }
 
@@ -880,7 +1083,8 @@
             // If 3G(EV) and 1x network are available than 3G should be
             // displayed, displayed RSSI should be from the EV side.
             // If a voice call is made then RSSI should switch to 1x.
-            if ((mPhoneState == TelephonyManager.CALL_STATE_IDLE) && isEvdo()){
+            if ((mPhoneState == TelephonyManager.CALL_STATE_IDLE) && isEvdo()
+                && !mAlwaysUseCdmaRssi) {
                 iconLevel = getEvdoLevel();
                 if (false) {
                     Slog.d(TAG, "use Evdo level=" + iconLevel + " to replace Cdma Level=" + getCdmaLevel());
@@ -1124,6 +1328,46 @@
         }
     }
 
+    private final void updateWiMAX(Intent intent) {
+        final String action = intent.getAction();
+        int iconId = sWimaxDisconnectedImg;
+
+        if (action.equals(WimaxManagerConstants.WIMAX_ENABLED_STATUS_CHANGED)) {
+            int wimaxStatus = intent.getIntExtra(WimaxManagerConstants.EXTRA_WIMAX_STATUS,
+                    WimaxManagerConstants.WIMAX_STATUS_DISABLED);
+            switch(wimaxStatus) {
+                case WimaxManagerConstants.WIMAX_STATUS_ENABLED:
+                    mIsWimaxEnabled = true;
+                    break;
+                case WimaxManagerConstants.WIMAX_STATUS_DISABLED:
+                    mIsWimaxEnabled = false;
+                    break;
+            }
+            mService.setIconVisibility("wimax", mIsWimaxEnabled);
+        } else if (action.equals(WimaxManagerConstants.SIGNAL_LEVEL_CHANGED_ACTION)) {
+            mWimaxSignal = intent.getIntExtra(WimaxManagerConstants.EXTRA_NEW_SIGNAL_LEVEL, 0);
+        } else if (action.equals(WimaxManagerConstants.WIMAX_STATE_CHANGED_ACTION)) {
+            mWimaxState = intent.getIntExtra(WimaxManagerConstants.EXTRA_WIMAX_STATE,
+                    WimaxManagerConstants.WIMAX_STATE_UNKNOWN);
+            mWimaxExtraState = intent.getIntExtra(
+                    WimaxManagerConstants.EXTRA_WIMAX_STATE_DETAIL,
+                    WimaxManagerConstants.WIMAX_DEREGISTRATION);
+        }
+        switch(mWimaxState) {
+            case WimaxManagerConstants.WIMAX_STATE_DISCONNECTED:
+                iconId = sWimaxDisconnectedImg;
+                break;
+            case WimaxManagerConstants.WIMAX_STATE_CONNECTED:
+                if(mWimaxExtraState == WimaxManagerConstants.WIMAX_IDLE) {
+                    iconId = sWimaxIdleImg;
+                } else {
+                    iconId = sWimaxSignalImages[mInetCondition][mWimaxSignal];
+                }
+                break;
+        }
+        if (mIsWimaxEnabled) mService.setIcon("wimax", iconId, 0);
+    }
+
     private final void updateGps(Intent intent) {
         final String action = intent.getAction();
         final boolean enabled = intent.getBooleanExtra(LocationManager.EXTRA_GPS_ENABLED, false);
@@ -1193,6 +1437,10 @@
 
         switch (iconMode) {
             case EriInfo.ROAMING_ICON_MODE_NORMAL:
+                if (iconIndex >= iconList.length) {
+                    Slog.e(TAG, "unknown iconIndex " + iconIndex + ", skipping ERI icon update");
+                    return;
+                }
                 mService.setIcon("cdma_eri", iconList[iconIndex], 0);
                 mService.setIconVisibility("cdma_eri", true);
                 break;
@@ -1205,7 +1453,6 @@
         mService.setIcon("phone_signal", mPhoneSignalIconId, 0);
     }
 
-
     private class StatusBarHandler extends Handler {
         @Override
         public void handleMessage(Message msg) {
diff --git a/packages/SystemUI/src/com/android/systemui/usb/UsbAccessoryUriActivity.java b/packages/SystemUI/src/com/android/systemui/usb/UsbAccessoryUriActivity.java
new file mode 100644
index 0000000..5007cf4
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/usb/UsbAccessoryUriActivity.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.systemui.usb;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.ActivityNotFoundException;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.net.Uri;
+import android.hardware.usb.UsbAccessory;
+import android.hardware.usb.UsbManager;
+import android.os.Bundle;
+import android.util.Log;
+
+import com.android.internal.app.AlertActivity;
+import com.android.internal.app.AlertController;
+
+import com.android.systemui.R;
+
+/**
+ * If the attached USB accessory has a URL associated with it, and that URL is valid,
+ * show this dialog to the user to allow them to optionally visit that URL for more
+ * information or software downloads.
+ * Otherwise (no valid URL) this activity does nothing at all, finishing immediately.
+ */
+public class UsbAccessoryUriActivity extends AlertActivity
+        implements DialogInterface.OnClickListener {
+
+    private static final String TAG = "UsbAccessoryUriActivity";
+
+    private UsbAccessory mAccessory;
+    private Uri mUri;
+
+    @Override
+    public void onCreate(Bundle icicle) {
+       super.onCreate(icicle);
+
+       Intent intent = getIntent();
+        mAccessory = (UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
+        String uriString = intent.getStringExtra("uri");
+        mUri = (uriString == null ? null : Uri.parse(uriString));
+
+        // sanity check before displaying dialog
+        if (mUri == null) {
+            Log.e(TAG, "could not parse Uri " + uriString);
+            finish();
+            return;
+        }
+        String scheme = mUri.getScheme();
+        if (!"http".equals(scheme) && !"https".equals(scheme)) {
+            Log.e(TAG, "Uri not http or https: " + mUri);
+            finish();
+            return;
+        }
+
+        final AlertController.AlertParams ap = mAlertParams;
+        ap.mTitle = mAccessory.getDescription();
+        if (ap.mTitle == null || ap.mTitle.length() == 0) {
+            ap.mTitle = getString(R.string.title_usb_accessory);
+        }
+        ap.mMessage = getString(R.string.usb_accessory_uri_prompt, mUri);
+        ap.mPositiveButtonText = getString(R.string.label_view);
+        ap.mNegativeButtonText = getString(android.R.string.cancel);
+        ap.mPositiveButtonListener = this;
+        ap.mNegativeButtonListener = this;
+
+        setupAlert();
+    }
+
+    public void onClick(DialogInterface dialog, int which) {
+        if (which == AlertDialog.BUTTON_POSITIVE) {
+            // launch the browser
+            Intent intent = new Intent(Intent.ACTION_VIEW, mUri);
+            intent.addCategory(Intent.CATEGORY_BROWSABLE);
+            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+            try {
+                startActivity(intent);
+            } catch (ActivityNotFoundException e) {
+                Log.e(TAG, "startActivity failed for " + mUri);
+            }
+        }
+        finish();
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/usb/UsbConfirmActivity.java b/packages/SystemUI/src/com/android/systemui/usb/UsbConfirmActivity.java
new file mode 100644
index 0000000..148bcb4
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/usb/UsbConfirmActivity.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.systemui.usb;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.hardware.usb.IUsbManager;
+import android.hardware.usb.UsbAccessory;
+import android.hardware.usb.UsbManager;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.widget.CheckBox;
+import android.widget.CompoundButton;
+import android.widget.TextView;
+
+import com.android.internal.app.AlertActivity;
+import com.android.internal.app.AlertController;
+
+import com.android.systemui.R;
+
+public class UsbConfirmActivity extends AlertActivity
+        implements DialogInterface.OnClickListener, CheckBox.OnCheckedChangeListener {
+
+    private static final String TAG = "UsbConfirmActivity";
+
+    private CheckBox mAlwaysUse;
+    private TextView mClearDefaultHint;
+    private UsbAccessory mAccessory;
+    private ResolveInfo mResolveInfo;
+    private boolean mPermissionGranted;
+    private UsbDisconnectedReceiver mDisconnectedReceiver;
+
+    @Override
+    public void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+
+        Intent intent = getIntent();
+        mAccessory = (UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
+        mDisconnectedReceiver = new UsbDisconnectedReceiver(this, mAccessory);
+        mResolveInfo = (ResolveInfo)intent.getParcelableExtra("rinfo");
+
+        PackageManager packageManager = getPackageManager();
+        String appName = mResolveInfo.loadLabel(packageManager).toString();
+
+        final AlertController.AlertParams ap = mAlertParams;
+        ap.mIcon = mResolveInfo.loadIcon(packageManager);
+        ap.mTitle = appName;
+        ap.mMessage = getString(R.string.usb_accessory_confirm_prompt, appName);
+        ap.mPositiveButtonText = getString(android.R.string.ok);
+        ap.mNegativeButtonText = getString(android.R.string.cancel);
+        ap.mPositiveButtonListener = this;
+        ap.mNegativeButtonListener = this;
+
+        // add "always use" checkbox
+        LayoutInflater inflater = (LayoutInflater)getSystemService(
+                Context.LAYOUT_INFLATER_SERVICE);
+        ap.mView = inflater.inflate(com.android.internal.R.layout.always_use_checkbox, null);
+        mAlwaysUse = (CheckBox)ap.mView.findViewById(com.android.internal.R.id.alwaysUse);
+        mAlwaysUse.setText(R.string.always_use_accessory);
+        mAlwaysUse.setOnCheckedChangeListener(this);
+        mClearDefaultHint = (TextView)ap.mView.findViewById(
+                                                    com.android.internal.R.id.clearDefaultHint);
+        mClearDefaultHint.setVisibility(View.GONE);
+
+        setupAlert();
+
+    }
+
+    @Override
+    protected void onDestroy() {
+        if (mDisconnectedReceiver != null) {
+            unregisterReceiver(mDisconnectedReceiver);
+        }
+        super.onDestroy();
+    }
+
+    public void onClick(DialogInterface dialog, int which) {
+        if (which == AlertDialog.BUTTON_POSITIVE) {
+            try {
+                IBinder b = ServiceManager.getService(USB_SERVICE);
+                IUsbManager service = IUsbManager.Stub.asInterface(b);
+                int uid = mResolveInfo.activityInfo.applicationInfo.uid;
+                boolean alwaysUse = mAlwaysUse.isChecked();
+                Intent intent = new Intent(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
+                intent.putExtra(UsbManager.EXTRA_ACCESSORY, mAccessory);
+                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+                intent.setComponent(
+                    new ComponentName(mResolveInfo.activityInfo.packageName,
+                            mResolveInfo.activityInfo.name));
+
+                // grant permission for the accessory
+                service.grantAccessoryPermission(mAccessory, uid);
+                // set or clear default setting
+                if (alwaysUse) {
+                    service.setAccessoryPackage(mAccessory,
+                            mResolveInfo.activityInfo.packageName);
+                } else {
+                    service.setAccessoryPackage(mAccessory, null);
+                }
+                startActivity(intent);
+            } catch (Exception e) {
+                Log.e(TAG, "Unable to start activity", e);
+            }
+        }
+        finish();
+    }
+
+    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+        if (mClearDefaultHint == null) return;
+
+        if(isChecked) {
+            mClearDefaultHint.setVisibility(View.VISIBLE);
+        } else {
+            mClearDefaultHint.setVisibility(View.GONE);
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/usb/UsbDisconnectedReceiver.java b/packages/SystemUI/src/com/android/systemui/usb/UsbDisconnectedReceiver.java
new file mode 100644
index 0000000..4fa3ad0
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/usb/UsbDisconnectedReceiver.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.usb;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.hardware.usb.UsbAccessory;
+import android.hardware.usb.UsbManager;
+
+// This class is used to close UsbPermissionsActivity and UsbResolverActivity
+// if their accessory is disconnected while the dialog is still open
+class UsbDisconnectedReceiver extends BroadcastReceiver {
+    private final Activity mActivity;
+    private UsbAccessory mAccessory;
+
+    public UsbDisconnectedReceiver(Activity activity, UsbAccessory accessory) {
+        mActivity = activity;
+        mAccessory = accessory;
+
+        IntentFilter filter = new IntentFilter(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
+        activity.registerReceiver(this, filter);
+    }
+
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        String action = intent.getAction();
+        if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
+            UsbAccessory accessory =
+                    (UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
+            if (accessory != null && accessory.equals(mAccessory)) {
+                mActivity.finish();
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/usb/UsbPermissionActivity.java b/packages/SystemUI/src/com/android/systemui/usb/UsbPermissionActivity.java
new file mode 100644
index 0000000..ec7c13a
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/usb/UsbPermissionActivity.java
@@ -0,0 +1,153 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.systemui.usb;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.hardware.usb.IUsbManager;
+import android.hardware.usb.UsbAccessory;
+import android.hardware.usb.UsbManager;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.widget.CheckBox;
+import android.widget.CompoundButton;
+import android.widget.TextView;
+
+import com.android.internal.app.AlertActivity;
+import com.android.internal.app.AlertController;
+
+import com.android.systemui.R;
+
+public class UsbPermissionActivity extends AlertActivity
+        implements DialogInterface.OnClickListener, CheckBox.OnCheckedChangeListener {
+
+    private static final String TAG = "UsbPermissionActivity";
+
+    private CheckBox mAlwaysUse;
+    private TextView mClearDefaultHint;
+    private UsbAccessory mAccessory;
+    private PendingIntent mPendingIntent;
+    private String mPackageName;
+    private int mUid;
+    private boolean mPermissionGranted;
+    private UsbDisconnectedReceiver mDisconnectedReceiver;
+
+    @Override
+    public void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+
+        Intent intent = getIntent();
+        mAccessory = (UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
+        mDisconnectedReceiver = new UsbDisconnectedReceiver(this, mAccessory);
+        mPendingIntent = (PendingIntent)intent.getParcelableExtra(Intent.EXTRA_INTENT);
+        mUid = intent.getIntExtra("uid", 0);
+        mPackageName = intent.getStringExtra("package");
+
+        PackageManager packageManager = getPackageManager();
+        ApplicationInfo aInfo;
+        try {
+            aInfo = packageManager.getApplicationInfo(mPackageName, 0);
+        } catch (PackageManager.NameNotFoundException e) {
+            Log.e(TAG, "unable to look up package name", e);
+            finish();
+            return;
+        }
+        String appName = aInfo.loadLabel(packageManager).toString();
+
+        final AlertController.AlertParams ap = mAlertParams;
+        ap.mIcon = aInfo.loadIcon(packageManager);
+        ap.mTitle = appName;
+        ap.mMessage = getString(R.string.usb_accessory_permission_prompt, appName);
+        ap.mPositiveButtonText = getString(android.R.string.ok);
+        ap.mNegativeButtonText = getString(android.R.string.cancel);
+        ap.mPositiveButtonListener = this;
+        ap.mNegativeButtonListener = this;
+
+        // add "always use" checkbox
+        LayoutInflater inflater = (LayoutInflater)getSystemService(
+                Context.LAYOUT_INFLATER_SERVICE);
+        ap.mView = inflater.inflate(com.android.internal.R.layout.always_use_checkbox, null);
+        mAlwaysUse = (CheckBox)ap.mView.findViewById(com.android.internal.R.id.alwaysUse);
+        mAlwaysUse.setText(R.string.always_use_accessory);
+        mAlwaysUse.setOnCheckedChangeListener(this);
+        mClearDefaultHint = (TextView)ap.mView.findViewById(
+                                                    com.android.internal.R.id.clearDefaultHint);
+        mClearDefaultHint.setVisibility(View.GONE);
+
+        setupAlert();
+
+    }
+
+    @Override
+    public void onDestroy() {
+        IBinder b = ServiceManager.getService(USB_SERVICE);
+        IUsbManager service = IUsbManager.Stub.asInterface(b);
+
+        // send response via pending intent
+        Intent intent = new Intent();
+        try {
+            if (mAccessory != null) {
+                intent.putExtra(UsbManager.EXTRA_ACCESSORY, mAccessory);
+                if (mPermissionGranted) {
+                    service.grantAccessoryPermission(mAccessory, mUid);
+                    if (mAlwaysUse.isChecked()) {
+                        service.setAccessoryPackage(mAccessory, mPackageName);
+                    }
+                }
+            }
+            intent.putExtra(UsbManager.EXTRA_PERMISSION_GRANTED, mPermissionGranted);
+            mPendingIntent.send(this, 0, intent);
+        } catch (PendingIntent.CanceledException e) {
+            Log.w(TAG, "PendingIntent was cancelled");
+        } catch (RemoteException e) {
+            Log.e(TAG, "IUsbService connection failed", e);
+        }
+
+        if (mDisconnectedReceiver != null) {
+            unregisterReceiver(mDisconnectedReceiver);
+        }
+        super.onDestroy();
+    }
+
+    public void onClick(DialogInterface dialog, int which) {
+        if (which == AlertDialog.BUTTON_POSITIVE) {
+            mPermissionGranted = true;
+        }
+        finish();
+    }
+
+    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+        if (mClearDefaultHint == null) return;
+
+        if(isChecked) {
+            mClearDefaultHint.setVisibility(View.VISIBLE);
+        } else {
+            mClearDefaultHint.setVisibility(View.GONE);
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/usb/UsbResolverActivity.java b/packages/SystemUI/src/com/android/systemui/usb/UsbResolverActivity.java
new file mode 100644
index 0000000..082c839
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/usb/UsbResolverActivity.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.systemui.usb;
+
+import com.android.internal.app.ResolverActivity;
+
+import android.content.ActivityNotFoundException;
+import android.content.Intent;
+import android.content.pm.ResolveInfo;
+import android.hardware.usb.IUsbManager;
+import android.hardware.usb.UsbAccessory;
+import android.hardware.usb.UsbManager;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.Parcelable;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.util.Log;
+import android.widget.CheckBox;
+
+import com.android.systemui.R;
+
+import java.util.ArrayList;
+
+/* Activity for choosing an application for a USB device or accessory */
+public class UsbResolverActivity extends ResolverActivity {
+    public static final String TAG = "UsbResolverActivity";
+    public static final String EXTRA_RESOLVE_INFOS = "rlist";
+
+    private UsbAccessory mAccessory;
+    private UsbDisconnectedReceiver mDisconnectedReceiver;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        Intent intent = getIntent();
+        Parcelable targetParcelable = intent.getParcelableExtra(Intent.EXTRA_INTENT);
+        if (!(targetParcelable instanceof Intent)) {
+            Log.w("UsbResolverActivity", "Target is not an intent: " + targetParcelable);
+            finish();
+            return;
+        }
+        Intent target = (Intent)targetParcelable;
+        ArrayList<ResolveInfo> rList = intent.getParcelableArrayListExtra(EXTRA_RESOLVE_INFOS);
+        CharSequence title = getResources().getText(com.android.internal.R.string.chooseUsbActivity);
+        super.onCreate(savedInstanceState, target, title, null, rList,
+                true /* Set alwaysUseOption to true to enable "always use this app" checkbox. */ );
+
+        CheckBox alwaysUse = (CheckBox)findViewById(com.android.internal.R.id.alwaysUse);
+        if (alwaysUse != null) {
+            alwaysUse.setText(R.string.always_use_accessory);
+        }
+
+        mAccessory = (UsbAccessory)target.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
+        if (mAccessory == null) {
+            Log.e(TAG, "accessory is null");
+            finish();
+            return;
+        }
+        mDisconnectedReceiver = new UsbDisconnectedReceiver(this, mAccessory);
+    }
+
+    @Override
+    protected void onDestroy() {
+        if (mDisconnectedReceiver != null) {
+            unregisterReceiver(mDisconnectedReceiver);
+        }
+        super.onDestroy();
+    }
+
+    protected void onIntentSelected(ResolveInfo ri, Intent intent, boolean alwaysCheck) {
+        try {
+            IBinder b = ServiceManager.getService(USB_SERVICE);
+            IUsbManager service = IUsbManager.Stub.asInterface(b);
+            int uid = ri.activityInfo.applicationInfo.uid;
+
+            // grant permission for the accessory
+            service.grantAccessoryPermission(mAccessory, uid);
+            // set or clear default setting
+            if (alwaysCheck) {
+                service.setAccessoryPackage(mAccessory, ri.activityInfo.packageName);
+            } else {
+                service.setAccessoryPackage(mAccessory, null);
+            }
+
+            try {
+                startActivity(intent);
+            } catch (ActivityNotFoundException e) {
+                Log.e(TAG, "startActivity failed", e);
+            }
+        } catch (RemoteException e) {
+            Log.e(TAG, "onIntentSelected failed", e);
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/usb/UsbStorageActivity.java b/packages/SystemUI/src/com/android/systemui/usb/UsbStorageActivity.java
index 5c52783..43dfb96 100644
--- a/packages/SystemUI/src/com/android/systemui/usb/UsbStorageActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/usb/UsbStorageActivity.java
@@ -30,7 +30,7 @@
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
-import android.hardware.Usb;
+import android.hardware.usb.UsbManager;
 import android.os.Bundle;
 import android.os.Environment;
 import android.os.Handler;
@@ -83,7 +83,7 @@
     private BroadcastReceiver mUsbStateReceiver = new BroadcastReceiver() {
         @Override
         public void onReceive(Context context, Intent intent) {
-            if (intent.getAction().equals(Usb.ACTION_USB_STATE)) {
+            if (intent.getAction().equals(UsbManager.ACTION_USB_STATE)) {
                 handleUsbStateChanged(intent);
             }
         }
@@ -175,7 +175,7 @@
         super.onResume();
 
         mStorageManager.registerListener(mStorageListener);
-        registerReceiver(mUsbStateReceiver, new IntentFilter(Usb.ACTION_USB_STATE));
+        registerReceiver(mUsbStateReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE));
         try {
             mAsyncStorageHandler.post(new Runnable() {
                 @Override
@@ -199,7 +199,7 @@
     }
 
     private void handleUsbStateChanged(Intent intent) {
-        boolean connected = intent.getExtras().getBoolean(Usb.USB_CONNECTED);
+        boolean connected = intent.getExtras().getBoolean(UsbManager.USB_CONNECTED);
         if (!connected) {
             // It was disconnected from the plug, so finish
             finish();
diff --git a/policy/src/com/android/internal/policy/impl/GlobalActions.java b/policy/src/com/android/internal/policy/impl/GlobalActions.java
index 5e33f05..dee275c 100644
--- a/policy/src/com/android/internal/policy/impl/GlobalActions.java
+++ b/policy/src/com/android/internal/policy/impl/GlobalActions.java
@@ -316,9 +316,10 @@
                 filteredPos++;
             }
 
-            throw new IllegalArgumentException("position " + position + " out of "
-                    + "range of showable actions, filtered count = "
-                    + "= " + getCount() + ", keyguardshowing=" + mKeyguardShowing
+            throw new IllegalArgumentException("position " + position
+                    + " out of range of showable actions"
+                    + ", filtered count=" + getCount()
+                    + ", keyguardshowing=" + mKeyguardShowing
                     + ", provisioned=" + mDeviceProvisioned);
         }
 
diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp
index 5935bf9..c68e20d 100644
--- a/services/audioflinger/AudioFlinger.cpp
+++ b/services/audioflinger/AudioFlinger.cpp
@@ -5808,10 +5808,10 @@
 
 // update this table when AudioSystem::audio_mode or audio_mode_e (in EffectApi.h) are modified
 const uint32_t AudioFlinger::EffectModule::sModeConvTable[] = {
-    AUDIO_MODE_NORMAL,   // AudioSystem::MODE_NORMAL
-    AUDIO_MODE_RINGTONE, // AudioSystem::MODE_RINGTONE
-    AUDIO_MODE_IN_CALL,  // AudioSystem::MODE_IN_CALL
-    AUDIO_MODE_IN_CALL   // AudioSystem::MODE_IN_COMMUNICATION, same conversion as for MODE_IN_CALL
+    AUDIO_EFFECT_MODE_NORMAL,   // AudioSystem::MODE_NORMAL
+    AUDIO_EFFECT_MODE_RINGTONE, // AudioSystem::MODE_RINGTONE
+    AUDIO_EFFECT_MODE_IN_CALL,  // AudioSystem::MODE_IN_CALL
+    AUDIO_EFFECT_MODE_IN_CALL   // AudioSystem::MODE_IN_COMMUNICATION, same conversion as for MODE_IN_CALL
 };
 
 int AudioFlinger::EffectModule::modeAudioSystemToEffectApi(uint32_t mode)
diff --git a/services/java/com/android/server/AlarmManagerService.java b/services/java/com/android/server/AlarmManagerService.java
index 4931cc7..cf3ecdc 100644
--- a/services/java/com/android/server/AlarmManagerService.java
+++ b/services/java/com/android/server/AlarmManagerService.java
@@ -281,10 +281,7 @@
             
             // Update the kernel timezone information
             // Kernel tracks time offsets as 'minutes west of GMT'
-            int gmtOffset = zone.getRawOffset();
-            if (zone.inDaylightTime(new Date(System.currentTimeMillis()))) {
-                gmtOffset += zone.getDSTSavings();
-            }
+            int gmtOffset = zone.getOffset(System.currentTimeMillis());
             setKernelTimezone(mDescriptor, -(gmtOffset / 60000));
         }
 
@@ -784,9 +781,8 @@
                 // based off of the current Zone gmt offset + userspace tracked
                 // daylight savings information.
                 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
-                int gmtOffset = (zone.getRawOffset() + zone.getDSTSavings()) / 60000;
-
-                setKernelTimezone(mDescriptor, -(gmtOffset));
+                int gmtOffset = zone.getOffset(System.currentTimeMillis());
+                setKernelTimezone(mDescriptor, -(gmtOffset / 60000));
             	scheduleDateChangedEvent();
             }
         }
diff --git a/services/java/com/android/server/ConnectivityService.java b/services/java/com/android/server/ConnectivityService.java
index 8560d16..6cd3e9e 100644
--- a/services/java/com/android/server/ConnectivityService.java
+++ b/services/java/com/android/server/ConnectivityService.java
@@ -18,10 +18,13 @@
 
 import android.app.Notification;
 import android.app.NotificationManager;
-import android.content.ContentResolver;
 import android.content.Context;
+import android.content.ContentResolver;
+import android.content.ContextWrapper;
 import android.content.Intent;
 import android.content.pm.PackageManager;
+import android.content.res.Resources;
+import android.content.res.Resources.NotFoundException;
 import android.net.ConnectivityManager;
 import android.net.IConnectivityManager;
 import android.net.MobileDataStateTracker;
@@ -29,11 +32,13 @@
 import android.net.NetworkStateTracker;
 import android.net.NetworkUtils;
 import android.net.wifi.WifiStateTracker;
+import android.net.wimax.WimaxManagerConstants;
 import android.os.Binder;
 import android.os.Handler;
 import android.os.IBinder;
 import android.os.Looper;
 import android.os.Message;
+import android.os.INetworkManagementService;
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.os.SystemProperties;
@@ -41,19 +46,23 @@
 import android.text.TextUtils;
 import android.util.EventLog;
 import android.util.Slog;
-
 import com.android.internal.telephony.Phone;
-
 import com.android.server.connectivity.Tethering;
-
+import dalvik.system.DexClassLoader;
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.InvocationTargetException;
 import java.util.ArrayList;
 import java.util.GregorianCalendar;
 import java.util.List;
 import java.net.InetAddress;
 import java.net.UnknownHostException;
 
+
+
 /**
  * @hide
  */
@@ -104,6 +113,8 @@
     private boolean mTestMode;
     private static ConnectivityService sServiceInstance;
 
+    private INetworkManagementService mNetd;
+
     private static final int ENABLED  = 1;
     private static final int DISABLED = 0;
 
@@ -381,6 +392,17 @@
                     mNetTrackers[netType].teardown();
                 }
                 break;
+            case ConnectivityManager.TYPE_WIMAX:
+                NetworkStateTracker nst = makeWimaxStateTracker();
+                if (nst != null) {
+                    nst.startMonitoring();
+                }
+                mNetTrackers[netType] = nst;
+                if (noMobileData) {
+                    if (DBG) Slog.d(TAG, "tearing down WiMAX networks due to setting");
+                    mNetTrackers[netType].teardown();
+                }
+                break;
             default:
                 Slog.e(TAG, "Trying to create a DataStateTracker for an unknown radio type " +
                         mNetAttributes[netType].mRadio);
@@ -400,6 +422,94 @@
         }
     }
 
+    private NetworkStateTracker makeWimaxStateTracker() {
+        //Initialize Wimax
+        DexClassLoader wimaxClassLoader;
+        Class wimaxStateTrackerClass = null;
+        Class wimaxServiceClass = null;
+        Class wimaxManagerClass;
+        String wimaxJarLocation;
+        String wimaxLibLocation;
+        String wimaxManagerClassName;
+        String wimaxServiceClassName;
+        String wimaxStateTrackerClassName;
+
+        NetworkStateTracker wimaxStateTracker = null;
+
+        boolean isWimaxEnabled = mContext.getResources().getBoolean(
+                com.android.internal.R.bool.config_wimaxEnabled);
+
+        if (isWimaxEnabled) {
+            try {
+                wimaxJarLocation = mContext.getResources().getString(
+                        com.android.internal.R.string.config_wimaxServiceJarLocation);
+                wimaxLibLocation = mContext.getResources().getString(
+                        com.android.internal.R.string.config_wimaxNativeLibLocation);
+                wimaxManagerClassName = mContext.getResources().getString(
+                        com.android.internal.R.string.config_wimaxManagerClassname);
+                wimaxServiceClassName = mContext.getResources().getString(
+                        com.android.internal.R.string.config_wimaxServiceClassname);
+                wimaxStateTrackerClassName = mContext.getResources().getString(
+                        com.android.internal.R.string.config_wimaxStateTrackerClassname);
+
+                wimaxClassLoader =  new DexClassLoader(wimaxJarLocation,
+                        new ContextWrapper(mContext).getCacheDir().getAbsolutePath(),
+                        wimaxLibLocation,ClassLoader.getSystemClassLoader());
+
+                try {
+                    wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
+                    wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
+                    wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
+                } catch (ClassNotFoundException ex) {
+                    ex.printStackTrace();
+                    return null;
+                }
+            } catch(Resources.NotFoundException ex) {
+                Slog.e(TAG, "Wimax Resources does not exist!!! ");
+                return null;
+            }
+
+            try {
+                Slog.v(TAG, "Starting Wimax Service... ");
+
+                Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
+                        (new Class[] {Context.class,Handler.class});
+                wimaxStateTracker = (NetworkStateTracker)wmxStTrkrConst.newInstance(mContext,mHandler);
+
+                Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
+                        (new Class[] {Context.class,wimaxStateTrackerClass});
+                wmxSrvConst.setAccessible(true);
+                IBinder svcInvoker = (IBinder) wmxSrvConst.newInstance(mContext,wimaxStateTracker);
+                wmxSrvConst.setAccessible(false);
+
+                ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
+
+            } catch(ClassCastException ex) {
+                ex.printStackTrace();
+                return null;
+            } catch (NoSuchMethodException ex) {
+                ex.printStackTrace();
+                return null;
+            } catch (InstantiationException ex) {
+                ex.printStackTrace();
+                return null;
+            } catch(IllegalAccessException ex) {
+                ex.printStackTrace();
+                return null;
+            } catch(InvocationTargetException ex) {
+                ex.printStackTrace();
+                return null;
+            } catch(Exception ex) {
+                ex.printStackTrace();
+                return null;
+            }
+        } else {
+            Slog.e(TAG, "Wimax is not enabled or not added to the network attributes!!! ");
+            return null;
+        }
+
+        return wimaxStateTracker;
+    }
 
     /**
      * Sets the preferred network.
@@ -492,18 +602,8 @@
      */
     public NetworkInfo getActiveNetworkInfo() {
         enforceAccessPermission();
-        for (int type=0; type <= ConnectivityManager.MAX_NETWORK_TYPE; type++) {
-            if (mNetAttributes[type] == null || !mNetAttributes[type].isDefault()) {
-                continue;
-            }
-            NetworkStateTracker t = mNetTrackers[type];
-            NetworkInfo info = t.getNetworkInfo();
-            if (info.isConnected()) {
-                if (DBG && type != mActiveDefaultNetwork) Slog.e(TAG,
-                        "connected default network is not " +
-                        "mActiveDefaultNetwork!");
-                return info;
-            }
+        if (mActiveDefaultNetwork != -1) {
+            return mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
         }
         return null;
     }
@@ -926,6 +1026,12 @@
                 }
                 mNetTrackers[ConnectivityManager.TYPE_MOBILE].reconnect();
             }
+            if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
+                if (DBG) {
+                    Slog.d(TAG, "starting up " + mNetTrackers[ConnectivityManager.TYPE_WIMAX]);
+                }
+                mNetTrackers[ConnectivityManager.TYPE_WIMAX].reconnect();
+            }
         } else {
             for (NetworkStateTracker nt : mNetTrackers) {
                 if (nt == null) continue;
@@ -935,6 +1041,9 @@
                     nt.teardown();
                 }
             }
+            if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
+                mNetTrackers[ConnectivityManager.TYPE_WIMAX].teardown();
+            }
         }
     }
 
@@ -1018,18 +1127,10 @@
                     info.getExtraInfo());
         }
 
-        NetworkStateTracker newNet = null;
         if (mNetAttributes[prevNetType].isDefault()) {
-            newNet = tryFailover(prevNetType);
-            if (newNet != null) {
-                NetworkInfo switchTo = newNet.getNetworkInfo();
-                if (!switchTo.isConnected()) {
-                    // if the other net is connected they've already reset this and perhaps even gotten
-                    // a positive report we don't want to overwrite, but if not we need to clear this now
-                    // to turn our cellular sig strength white
-                    mDefaultInetConditionPublished = 0;
-                    intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
-                }
+            tryFailover(prevNetType);
+            if (mActiveDefaultNetwork != -1) {
+                NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
                 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
             } else {
                 mDefaultInetConditionPublished = 0; // we're not connected anymore
@@ -1045,86 +1146,47 @@
          * If the failover network is already connected, then immediately send
          * out a followup broadcast indicating successful failover
          */
-        if (newNet != null && newNet.getNetworkInfo().isConnected()) {
-            sendConnectedBroadcast(newNet.getNetworkInfo());
+        if (mActiveDefaultNetwork != -1) {
+            sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
         }
     }
 
-    // returns null if no failover available
-    private NetworkStateTracker tryFailover(int prevNetType) {
+    private void tryFailover(int prevNetType) {
         /*
          * If this is a default network, check if other defaults are available
          * or active
          */
-        NetworkStateTracker newNet = null;
         if (mNetAttributes[prevNetType].isDefault()) {
             if (mActiveDefaultNetwork == prevNetType) {
                 mActiveDefaultNetwork = -1;
             }
 
-            int newType = -1;
-            int newPriority = -1;
             boolean noMobileData = !getMobileDataEnabled();
             for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
                 if (checkType == prevNetType) continue;
                 if (mNetAttributes[checkType] == null) continue;
+                if (mNetAttributes[checkType].isDefault() == false) continue;
                 if (mNetAttributes[checkType].mRadio == ConnectivityManager.TYPE_MOBILE &&
                         noMobileData) {
                     Slog.e(TAG, "not failing over to mobile type " + checkType +
                             " because Mobile Data Disabled");
                     continue;
                 }
-                if (mNetAttributes[checkType].isDefault()) {
-                    /* TODO - if we have multiple nets we could use
-                     * we may want to put more thought into which we choose
-                     */
-                    if (checkType == mNetworkPreference) {
-                        newType = checkType;
-                        break;
-                    }
-                    if (mNetAttributes[checkType].mPriority > newPriority) {
-                        newType = checkType;
-                        newPriority = mNetAttributes[newType].mPriority;
-                    }
+                if (mNetAttributes[checkType].mRadio == ConnectivityManager.TYPE_WIMAX &&
+                        noMobileData) {
+                    Slog.e(TAG, "not failing over to mobile type " + checkType +
+                            " because Mobile Data Disabled");
+                    continue;
                 }
-            }
-
-            if (newType != -1) {
-                newNet = mNetTrackers[newType];
-                /**
-                 * See if the other network is available to fail over to.
-                 * If is not available, we enable it anyway, so that it
-                 * will be able to connect when it does become available,
-                 * but we report a total loss of connectivity rather than
-                 * report that we are attempting to fail over.
-                 */
-                if (newNet.isAvailable()) {
-                    NetworkInfo switchTo = newNet.getNetworkInfo();
-                    switchTo.setFailover(true);
-                    if (!switchTo.isConnectedOrConnecting() ||
-                            newNet.isTeardownRequested()) {
-                        newNet.reconnect();
-                    }
-                    if (DBG) {
-                        if (switchTo.isConnected()) {
-                            Slog.v(TAG, "Switching to already connected " +
-                                    switchTo.getTypeName());
-                        } else {
-                            Slog.v(TAG, "Attempting to switch to " +
-                                    switchTo.getTypeName());
-                        }
-                    }
-                } else {
-                    newNet.reconnect();
-                    newNet = null; // not officially avail..  try anyway, but
-                                   // report no failover
+                NetworkStateTracker checkTracker = mNetTrackers[checkType];
+                NetworkInfo checkInfo = checkTracker.getNetworkInfo();
+                if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
+                    checkInfo.setFailover(true);
+                    checkTracker.reconnect();
                 }
-            } else {
-                Slog.e(TAG, "Network failover failing.");
+                if (DBG) Slog.d(TAG, "Attempting to switch to " + checkInfo.getTypeName());
             }
         }
-
-        return newNet;
     }
 
     private void sendConnectedBroadcast(NetworkInfo info) {
@@ -1187,17 +1249,10 @@
             info.setFailover(false);
         }
 
-        NetworkStateTracker newNet = null;
         if (mNetAttributes[info.getType()].isDefault()) {
-            newNet = tryFailover(info.getType());
-            if (newNet != null) {
-                NetworkInfo switchTo = newNet.getNetworkInfo();
-                if (!switchTo.isConnected()) {
-                    // if the other net is connected they've already reset this and perhaps
-                    // even gotten a positive report we don't want to overwrite, but if not
-                    // we need to clear this now to turn our cellular sig strength white
-                    mDefaultInetConditionPublished = 0;
-                }
+            tryFailover(info.getType());
+            if (mActiveDefaultNetwork != -1) {
+                NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
                 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
             } else {
                 mDefaultInetConditionPublished = 0;
@@ -1211,8 +1266,8 @@
          * If the failover network is already connected, then immediately send
          * out a followup broadcast indicating successful failover
          */
-        if (newNet != null && newNet.getNetworkInfo().isConnected()) {
-            sendConnectedBroadcast(newNet.getNetworkInfo());
+        if (mActiveDefaultNetwork != -1) {
+            sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
         }
     }
 
@@ -1227,6 +1282,9 @@
     }
 
     void systemReady() {
+        IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
+        mNetd = INetworkManagementService.Stub.asInterface(b);
+
         synchronized(this) {
             mSystemReady = true;
             if (mInitialBroadcast != null) {
@@ -1265,6 +1323,7 @@
                             " teardown");
                     if (!teardown(otherNet)) {
                         Slog.e(TAG, "Network declined teardown request");
+                        teardown(thisNet);
                         return;
                     }
                     if (isFailover) {
@@ -1327,6 +1386,15 @@
             if (mNetAttributes[netType].isDefault()) {
                 mNetTrackers[netType].addDefaultRoute();
             } else {
+                // many radios add a default route even when we don't want one.
+                // remove the default interface unless we need it for our active network
+                if (mActiveDefaultNetwork != -1) {
+                    String defaultIface = mNetTrackers[mActiveDefaultNetwork].getInterfaceName();
+                    if (defaultIface != null &&
+                            !defaultIface.equals(mNetTrackers[netType].getInterfaceName())) {
+                        mNetTrackers[netType].removeDefaultRoute();
+                    }
+                }
                 mNetTrackers[netType].addPrivateDnsRoutes();
             }
         } else {
@@ -1409,6 +1477,11 @@
         NetworkStateTracker nt = mNetTrackers[netType];
         if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
             String[] dnsList = nt.getNameServers();
+            try {
+                mNetd.setDnsServersForInterface(Integer.toString(netType), dnsList);
+            } catch (Exception e) {
+                Slog.e(TAG, "exception setting dns servers: " + e);
+            }
             if (mNetAttributes[netType].isDefault()) {
                 int j = 1;
                 for (String dns : dnsList) {
@@ -1420,6 +1493,10 @@
                         SystemProperties.set("net.dns" + j++, dns);
                     }
                 }
+                try {
+                    mNetd.setDefaultInterfaceForDns(Integer.toString(netType));
+                } catch (Exception e) {
+                    Slog.e(TAG, "exception setting default dns interface: " + e);}
                 for (int k=j ; k<mNumDnsEntries; k++) {
                     if (DBG) Slog.d(TAG, "erasing net.dns" + k);
                     SystemProperties.set("net.dns" + k, "");
diff --git a/services/java/com/android/server/NetworkManagementService.java b/services/java/com/android/server/NetworkManagementService.java
index f0acdc0..edc7c5a 100644
--- a/services/java/com/android/server/NetworkManagementService.java
+++ b/services/java/com/android/server/NetworkManagementService.java
@@ -784,4 +784,65 @@
     public int getInterfaceTxThrottle(String iface) {
         return getInterfaceThrottle(iface, false);
     }
+
+    public void setDefaultInterfaceForDns(String iface) throws IllegalStateException {
+        mContext.enforceCallingOrSelfPermission(
+                android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
+        try {
+            String cmd = "resolver setdefaultif " + iface;
+
+            mConnector.doCommand(cmd);
+        } catch (NativeDaemonConnectorException e) {
+            throw new IllegalStateException(
+                    "Error communicating with native daemon to set default interface", e);
+        }
+    }
+
+    public void setDnsServersForInterface(String iface, String[] servers)
+            throws IllegalStateException {
+        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE,
+                "NetworkManagementService");
+        try {
+            String cmd = "resolver setifdns " + iface;
+            for (String s : servers) {
+                if (s != null && !"0.0.0.0".equals(s) &&
+                        !"::".equals(s) && !"0:0:0:0:0:0:0:0".equals(s)) {
+                    cmd += " " + InetAddress.getByName(s).getHostAddress();
+                }
+            }
+
+            mConnector.doCommand(cmd);
+        } catch (UnknownHostException e) {
+            throw new IllegalStateException("failed to resolve dns address.", e);
+        } catch (NativeDaemonConnectorException e) {
+            throw new IllegalStateException(
+                    "Error communicating with native deamon to set dns for interface", e);
+        }
+    }
+
+    public void flushDefaultDnsCache() throws IllegalStateException {
+        mContext.enforceCallingOrSelfPermission(
+                android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
+        try {
+            String cmd = "resolver flushdefaultif";
+
+            mConnector.doCommand(cmd);
+        } catch (NativeDaemonConnectorException e) {
+            throw new IllegalStateException(
+                    "Error communicating with native deamon to flush default interface", e);
+        }
+    }
+
+    public void flushInterfaceDnsCache(String iface) throws IllegalStateException {
+        mContext.enforceCallingOrSelfPermission(
+                android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
+        try {
+            String cmd = "resolver flushif " + iface;
+
+            mConnector.doCommand(cmd);
+        } catch (NativeDaemonConnectorException e) {
+            throw new IllegalStateException(
+                    "Error communicating with native deamon to flush interface " + iface, e);
+        }
+    }
 }
diff --git a/services/java/com/android/server/NotificationManagerService.java b/services/java/com/android/server/NotificationManagerService.java
index 4da5eb2..f5caf7a 100755
--- a/services/java/com/android/server/NotificationManagerService.java
+++ b/services/java/com/android/server/NotificationManagerService.java
@@ -38,7 +38,7 @@
 import android.content.pm.PackageManager.NameNotFoundException;
 import android.content.res.Resources;
 import android.database.ContentObserver;
-import android.hardware.Usb;
+import android.hardware.usb.UsbManager;
 import android.media.AudioManager;
 import android.net.Uri;
 import android.os.BatteryManager;
@@ -352,14 +352,12 @@
                     mBatteryFull = batteryFull;
                     updateLights();
                 }
-            } else if (action.equals(Usb.ACTION_USB_STATE)) {
+            } else if (action.equals(UsbManager.ACTION_USB_STATE)) {
                 Bundle extras = intent.getExtras();
-                boolean usbConnected = extras.getBoolean(Usb.USB_CONNECTED);
-                boolean adbEnabled = (Usb.USB_FUNCTION_ENABLED.equals(
-                                    extras.getString(Usb.USB_FUNCTION_ADB)));
+                boolean usbConnected = extras.getBoolean(UsbManager.USB_CONNECTED);
+                boolean adbEnabled = (UsbManager.USB_FUNCTION_ENABLED.equals(
+                                    extras.getString(UsbManager.USB_FUNCTION_ADB)));
                 updateAdbNotification(usbConnected && adbEnabled);
-            } else if (action.equals(Usb.ACTION_USB_DISCONNECTED)) {
-                updateAdbNotification(false);
             } else if (action.equals(Intent.ACTION_PACKAGE_REMOVED)
                     || action.equals(Intent.ACTION_PACKAGE_RESTARTED)
                     || (queryRestart=action.equals(Intent.ACTION_QUERY_PACKAGE_RESTART))
@@ -475,7 +473,7 @@
         // register for battery changed notifications
         IntentFilter filter = new IntentFilter();
         filter.addAction(Intent.ACTION_BATTERY_CHANGED);
-        filter.addAction(Usb.ACTION_USB_STATE);
+        filter.addAction(UsbManager.ACTION_USB_STATE);
         filter.addAction(Intent.ACTION_SCREEN_ON);
         filter.addAction(Intent.ACTION_SCREEN_OFF);
         filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
@@ -521,6 +519,24 @@
                     record = mToastQueue.get(index);
                     record.update(duration);
                 } else {
+                    // Limit the number of toasts that any given package except the android
+                    // package can enqueue.  Prevents DOS attacks and deals with leaks.
+                    if (!"android".equals(pkg)) {
+                        int count = 0;
+                        final int N = mToastQueue.size();
+                        for (int i=0; i<N; i++) {
+                             final ToastRecord r = mToastQueue.get(i);
+                             if (r.pkg.equals(pkg)) {
+                                 count++;
+                                 if (count >= MAX_PACKAGE_NOTIFICATIONS) {
+                                     Slog.e(TAG, "Package has already posted " + count
+                                            + " toasts. Not showing more. Package=" + pkg);
+                                     return;
+                                 }
+                             }
+                        }
+                    }
+
                     record = new ToastRecord(callingPid, pkg, callback, duration);
                     mToastQueue.add(record);
                     index = mToastQueue.size() - 1;
diff --git a/services/java/com/android/server/PackageManagerService.java b/services/java/com/android/server/PackageManagerService.java
index 8c74566..29b9ee4 100644
--- a/services/java/com/android/server/PackageManagerService.java
+++ b/services/java/com/android/server/PackageManagerService.java
@@ -55,6 +55,8 @@
 import android.content.pm.PackageInfoLite;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageStats;
+import android.content.pm.ParceledListSlice;
+
 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
@@ -75,6 +77,7 @@
 import android.os.Looper;
 import android.os.Message;
 import android.os.Parcel;
+import android.os.Parcelable;
 import android.os.RemoteException;
 import android.os.Environment;
 import android.os.FileObserver;
@@ -2323,63 +2326,110 @@
         }
     }
 
-    public List<PackageInfo> getInstalledPackages(int flags) {
-        ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
-
-        synchronized (mPackages) {
-            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
-                Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
-                while (i.hasNext()) {
-                    final PackageSetting ps = i.next();
-                    PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
-                    if(psPkg != null) {
-                        finalList.add(psPkg);
-                    }
-                }
-            }
-            else {
-                Iterator<PackageParser.Package> i = mPackages.values().iterator();
-                while (i.hasNext()) {
-                    final PackageParser.Package p = i.next();
-                    if (p.applicationInfo != null) {
-                        PackageInfo pi = generatePackageInfo(p, flags);
-                        if(pi != null) {
-                            finalList.add(pi);
-                        }
-                    }
-                }
+    private static final int getContinuationPoint(final String[] keys, final String key) {
+        final int index;
+        if (key == null) {
+            index = 0;
+        } else {
+            final int insertPoint = Arrays.binarySearch(keys, key);
+            if (insertPoint < 0) {
+                index = -insertPoint;
+            } else {
+                index = insertPoint + 1;
             }
         }
-        return finalList;
+        return index;
     }
 
-    public List<ApplicationInfo> getInstalledApplications(int flags) {
-        ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
-        synchronized(mPackages) {
-            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
-                Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
-                while (i.hasNext()) {
-                    final PackageSetting ps = i.next();
-                    ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
-                    if(ai != null) {
-                        finalList.add(ai);
+    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, String lastRead) {
+        final ParceledListSlice<PackageInfo> list = new ParceledListSlice<PackageInfo>();
+        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
+        final String[] keys;
+
+        synchronized (mPackages) {
+            if (listUninstalled) {
+                keys = mSettings.mPackages.keySet().toArray(new String[mSettings.mPackages.size()]);
+            } else {
+                keys = mPackages.keySet().toArray(new String[mPackages.size()]);
+            }
+
+            Arrays.sort(keys);
+            int i = getContinuationPoint(keys, lastRead);
+            final int N = keys.length;
+
+            while (i < N) {
+                final String packageName = keys[i++];
+
+                PackageInfo pi = null;
+                if (listUninstalled) {
+                    final PackageSetting ps = mSettings.mPackages.get(packageName);
+                    if (ps != null) {
+                        pi = generatePackageInfoFromSettingsLP(ps.name, flags);
                     }
+                } else {
+                    final PackageParser.Package p = mPackages.get(packageName);
+                    if (p != null) {
+                        pi = generatePackageInfo(p, flags);
+                    }
+                }
+
+                if (pi != null && !list.append(pi)) {
+                    break;
                 }
             }
-            else {
-                Iterator<PackageParser.Package> i = mPackages.values().iterator();
-                while (i.hasNext()) {
-                    final PackageParser.Package p = i.next();
-                    if (p.applicationInfo != null) {
-                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
-                        if(ai != null) {
-                            finalList.add(ai);
-                        }
-                    }
-                }
+
+            if (i == N) {
+                list.setLastSlice(true);
             }
         }
-        return finalList;
+
+        return list;
+    }
+
+    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags,
+            String lastRead) {
+        final ParceledListSlice<ApplicationInfo> list = new ParceledListSlice<ApplicationInfo>();
+        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
+        final String[] keys;
+
+        synchronized (mPackages) {
+            if (listUninstalled) {
+                keys = mSettings.mPackages.keySet().toArray(new String[mSettings.mPackages.size()]);
+            } else {
+                keys = mPackages.keySet().toArray(new String[mPackages.size()]);
+            }
+
+            Arrays.sort(keys);
+            int i = getContinuationPoint(keys, lastRead);
+            final int N = keys.length;
+
+            while (i < N) {
+                final String packageName = keys[i++];
+
+                ApplicationInfo ai = null;
+                if (listUninstalled) {
+                    final PackageSetting ps = mSettings.mPackages.get(packageName);
+                    if (ps != null) {
+                        ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
+                    }
+                } else {
+                    final PackageParser.Package p = mPackages.get(packageName);
+                    if (p != null) {
+                        ai = PackageParser.generateApplicationInfo(p, flags);
+                    }
+                }
+
+                if (ai != null && !list.append(ai)) {
+                    break;
+                }
+            }
+
+            if (i == N) {
+                list.setLastSlice(true);
+            }
+        }
+
+        return list;
     }
 
     public List<ApplicationInfo> getPersistentApplications(int flags) {
@@ -9031,6 +9081,19 @@
             }
             mPendingPackages.clear();
 
+            /*
+             * Make sure all the updated system packages have their shared users
+             * associated with them.
+             */
+            final Iterator<PackageSetting> disabledIt = mDisabledSysPackages.values().iterator();
+            while (disabledIt.hasNext()) {
+                final PackageSetting disabledPs = disabledIt.next();
+                final Object id = getUserIdLP(disabledPs.userId);
+                if (id != null && id instanceof SharedUserSetting) {
+                  disabledPs.sharedUser = (SharedUserSetting) id;
+                }
+            }
+
             mReadMessages.append("Read completed successfully: "
                     + mPackages.size() + " packages, "
                     + mSharedUsers.size() + " shared uids\n");
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index df69b76..0f03f75 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -17,6 +17,7 @@
 package com.android.server;
 
 import com.android.server.am.ActivityManagerService;
+import com.android.server.usb.UsbService;
 import com.android.internal.app.ShutdownThread;
 import com.android.internal.os.BinderInternal;
 import com.android.internal.os.SamplingProfilerIntegration;
@@ -122,7 +123,7 @@
         BluetoothA2dpService bluetoothA2dp = null;
         HeadsetObserver headset = null;
         DockObserver dock = null;
-        UsbObserver usb = null;
+        UsbService usb = null;
         UiModeManagerService uiMode = null;
         RecognitionManagerService recognition = null;
         ThrottleService throttle = null;
@@ -397,11 +398,12 @@
             }
 
             try {
-                Slog.i(TAG, "USB Observer");
+                Slog.i(TAG, "USB Service");
                 // Listen for USB changes
-                usb = new UsbObserver(context);
+                usb = new UsbService(context);
+                ServiceManager.addService(Context.USB_SERVICE, usb);
             } catch (Throwable e) {
-                Slog.e(TAG, "Failure starting UsbObserver", e);
+                Slog.e(TAG, "Failure starting UsbService", e);
             }
 
             try {
@@ -493,7 +495,7 @@
         final BatteryService batteryF = battery;
         final ConnectivityService connectivityF = connectivity;
         final DockObserver dockF = dock;
-        final UsbObserver usbF = usb;
+        final UsbService usbF = usb;
         final ThrottleService throttleF = throttle;
         final UiModeManagerService uiModeF = uiMode;
         final AppWidgetService appWidgetF = appWidget;
diff --git a/services/java/com/android/server/UsbObserver.java b/services/java/com/android/server/UsbObserver.java
deleted file mode 100644
index d08fe9b..0000000
--- a/services/java/com/android/server/UsbObserver.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server;
-
-import android.content.ContentResolver;
-import android.content.Context;
-import android.content.Intent;
-import android.hardware.Usb;
-import android.net.Uri;
-import android.os.Handler;
-import android.os.Message;
-import android.os.UEventObserver;
-import android.provider.Settings;
-import android.util.Log;
-import android.util.Slog;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.util.ArrayList;
-
-/**
- * <p>UsbObserver monitors for changes to USB state.
- */
-class UsbObserver extends UEventObserver {
-    private static final String TAG = UsbObserver.class.getSimpleName();
-    private static final boolean LOG = false;
-
-    private static final String USB_CONFIGURATION_MATCH = "DEVPATH=/devices/virtual/switch/usb_configuration";
-    private static final String USB_FUNCTIONS_MATCH = "DEVPATH=/devices/virtual/usb_composite/";
-    private static final String USB_CONFIGURATION_PATH = "/sys/class/switch/usb_configuration/state";
-    private static final String USB_COMPOSITE_CLASS_PATH = "/sys/class/usb_composite";
-
-    private static final int MSG_UPDATE = 0;
-
-    private int mUsbConfig = 0;
-    private int mPreviousUsbConfig = 0;
-
-    // lists of enabled and disabled USB functions
-    private final ArrayList<String> mEnabledFunctions = new ArrayList<String>();
-    private final ArrayList<String> mDisabledFunctions = new ArrayList<String>();
-
-    private boolean mSystemReady;
-
-    private final Context mContext;
-
-    private PowerManagerService mPowerManager;
-
-    public UsbObserver(Context context) {
-        mContext = context;
-        init();  // set initial status
-
-        startObserving(USB_CONFIGURATION_MATCH);
-        startObserving(USB_FUNCTIONS_MATCH);
-    }
-
-    @Override
-    public void onUEvent(UEventObserver.UEvent event) {
-        if (Log.isLoggable(TAG, Log.VERBOSE)) {
-            Slog.v(TAG, "USB UEVENT: " + event.toString());
-        }
-
-        synchronized (this) {
-            String switchState = event.get("SWITCH_STATE");
-            if (switchState != null) {
-                try {
-                    int newConfig = Integer.parseInt(switchState);
-                    if (newConfig != mUsbConfig) {
-                        mPreviousUsbConfig = mUsbConfig;
-                        mUsbConfig = newConfig;
-                        // trigger an Intent broadcast
-                        if (mSystemReady) {
-                            update();
-                        }
-                    }
-                } catch (NumberFormatException e) {
-                    Slog.e(TAG, "Could not parse switch state from event " + event);
-                }
-            } else {
-                String function = event.get("FUNCTION");
-                String enabledStr = event.get("ENABLED");
-                if (function != null && enabledStr != null) {
-                    // Note: we do not broadcast a change when a function is enabled or disabled.
-                    // We just record the state change for the next broadcast.
-                    boolean enabled = "1".equals(enabledStr);
-                    if (enabled) {
-                        if (!mEnabledFunctions.contains(function)) {
-                            mEnabledFunctions.add(function);
-                        }
-                        mDisabledFunctions.remove(function);
-                    } else {
-                        if (!mDisabledFunctions.contains(function)) {
-                            mDisabledFunctions.add(function);
-                        }
-                        mEnabledFunctions.remove(function);
-                    }
-                }
-            }
-        }
-    }
-    private final void init() {
-        char[] buffer = new char[1024];
-
-        try {
-            FileReader file = new FileReader(USB_CONFIGURATION_PATH);
-            int len = file.read(buffer, 0, 1024);
-            mPreviousUsbConfig = mUsbConfig = Integer.valueOf((new String(buffer, 0, len)).trim());
-
-        } catch (FileNotFoundException e) {
-            Slog.w(TAG, "This kernel does not have USB configuration switch support");
-        } catch (Exception e) {
-            Slog.e(TAG, "" , e);
-        }
-
-        try {
-            File[] files = new File(USB_COMPOSITE_CLASS_PATH).listFiles();
-            for (int i = 0; i < files.length; i++) {
-                File file = new File(files[i], "enable");
-                FileReader reader = new FileReader(file);
-                int len = reader.read(buffer, 0, 1024);
-                int value = Integer.valueOf((new String(buffer, 0, len)).trim());
-                String functionName = files[i].getName();
-                if (value == 1) {
-                    mEnabledFunctions.add(functionName);
-                } else {
-                    mDisabledFunctions.add(functionName);
-                }
-            }
-        } catch (FileNotFoundException e) {
-            Slog.w(TAG, "This kernel does not have USB composite class support");
-        } catch (Exception e) {
-            Slog.e(TAG, "" , e);
-        }
-    }
-
-    void systemReady() {
-        synchronized (this) {
-            update();
-            mSystemReady = true;
-        }
-    }
-
-    private final void update() {
-        mHandler.sendEmptyMessage(MSG_UPDATE);
-    }
-
-    private final Handler mHandler = new Handler() {
-        private void addEnabledFunctions(Intent intent) {
-            // include state of all USB functions in our extras
-            for (int i = 0; i < mEnabledFunctions.size(); i++) {
-                intent.putExtra(mEnabledFunctions.get(i), Usb.USB_FUNCTION_ENABLED);
-            }
-            for (int i = 0; i < mDisabledFunctions.size(); i++) {
-                intent.putExtra(mDisabledFunctions.get(i), Usb.USB_FUNCTION_DISABLED);
-            }
-        }
-
-        @Override
-        public void handleMessage(Message msg) {
-            switch (msg.what) {
-                case MSG_UPDATE:
-                    synchronized (this) {
-                        final ContentResolver cr = mContext.getContentResolver();
-
-                        if (Settings.Secure.getInt(cr,
-                                Settings.Secure.DEVICE_PROVISIONED, 0) == 0) {
-                            Slog.i(TAG, "Device not provisioned, skipping USB broadcast");
-                            return;
-                        }
-                        // Send an Intent containing connected/disconnected state
-                        // and the enabled/disabled state of all USB functions
-                        Intent intent;
-                        boolean usbConnected = (mUsbConfig != 0);
-                        if (usbConnected) {
-                            intent = new Intent(Usb.ACTION_USB_CONNECTED);
-                            addEnabledFunctions(intent);
-                        } else {
-                            intent = new Intent(Usb.ACTION_USB_DISCONNECTED);
-                        }
-                        mContext.sendBroadcast(intent);
-
-                        // send a sticky broadcast for clients interested in both connect and disconnect
-                        intent = new Intent(Usb.ACTION_USB_STATE);
-                        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
-                        intent.putExtra(Usb.USB_CONNECTED, usbConnected);
-                        addEnabledFunctions(intent);
-                        mContext.sendStickyBroadcast(intent);
-                    }
-                    break;
-            }
-        }
-    };
-}
diff --git a/services/java/com/android/server/VibratorService.java b/services/java/com/android/server/VibratorService.java
index 86c30f8..71353911 100755
--- a/services/java/com/android/server/VibratorService.java
+++ b/services/java/com/android/server/VibratorService.java
@@ -379,6 +379,12 @@
             if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                 synchronized (mVibrations) {
                     doCancelVibrateLocked();
+
+                    int size = mVibrations.size();
+                    for(int i = 0; i < size; i++) {
+                        unlinkVibration(mVibrations.get(i));
+                    }
+
                     mVibrations.clear();
                 }
             }
diff --git a/services/java/com/android/server/WifiService.java b/services/java/com/android/server/WifiService.java
index 5aa0111..647f1153 100644
--- a/services/java/com/android/server/WifiService.java
+++ b/services/java/com/android/server/WifiService.java
@@ -53,6 +53,7 @@
 import android.net.DhcpInfo;
 import android.net.NetworkUtils;
 import android.os.Binder;
+import android.os.Environment;
 import android.os.Handler;
 import android.os.HandlerThread;
 import android.os.IBinder;
@@ -68,6 +69,17 @@
 import android.util.Slog;
 import android.text.TextUtils;
 
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.EOFException;
+import java.io.FileDescriptor;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.net.UnknownHostException;
 import java.util.ArrayList;
 import java.util.BitSet;
 import java.util.HashMap;
@@ -76,9 +88,7 @@
 import java.util.Map;
 import java.util.Set;
 import java.util.regex.Pattern;
-import java.io.FileDescriptor;
-import java.io.PrintWriter;
-import java.net.UnknownHostException;
+import java.util.UUID;
 
 import com.android.internal.app.IBatteryStats;
 import android.app.backup.IBackupManager;
@@ -176,6 +186,8 @@
     private static final int MESSAGE_START_SCAN         = 10;
     private static final int MESSAGE_REPORT_WORKSOURCE  = 11;
     private static final int MESSAGE_ENABLE_RSSI_POLLING = 12;
+    private static final int MESSAGE_WRITE_WIFI_AP_CONFIG = 13;
+    private static final int MESSAGE_READ_WIFI_AP_CONFIG = 14;
 
 
     private final  WifiHandler mWifiHandler;
@@ -218,6 +230,13 @@
     private static final String ACTION_DEVICE_IDLE =
             "com.android.server.WifiManager.action.DEVICE_IDLE";
 
+    private static final String WIFIAP_CONFIG_FILE = Environment.getDataDirectory() +
+            "/misc/wifi/softap.conf";
+
+    private static final int WIFIAP_CONFIG_VERSION = 1;
+    private WifiConfiguration mWifiApConfig = new WifiConfiguration();
+    private final Object mWifiApConfigLock = new Object();
+
     WifiService(Context context, WifiStateTracker tracker) {
         mContext = context;
         mWifiStateTracker = tracker;
@@ -281,6 +300,9 @@
 
                 }
             },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
+
+        //Initiate a read of Wifi Ap configuration
+        Message.obtain(mWifiHandler, MESSAGE_READ_WIFI_AP_CONFIG).sendToTarget();
     }
 
     /**
@@ -634,38 +656,103 @@
 
     public WifiConfiguration getWifiApConfiguration() {
         enforceAccessPermission();
-        final ContentResolver cr = mContext.getContentResolver();
-        WifiConfiguration wifiConfig = new WifiConfiguration();
-        int authType;
-        try {
-            wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
-            if (wifiConfig.SSID == null)
-                return null;
-            authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
-            wifiConfig.allowedKeyManagement.set(authType);
-            wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
-            return wifiConfig;
-        } catch (Settings.SettingNotFoundException e) {
-            Slog.e(TAG,"AP settings not found, returning");
-            return null;
+        synchronized (mWifiApConfigLock) {
+            WifiConfiguration config = new WifiConfiguration();
+            config.SSID = mWifiApConfig.SSID;
+            if (mWifiApConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
+                config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
+                config.preSharedKey = mWifiApConfig.preSharedKey;
+            } else {
+                config.allowedKeyManagement.set(KeyMgmt.NONE);
+            }
+            return config;
         }
     }
 
     public void setWifiApConfiguration(WifiConfiguration wifiConfig) {
         enforceChangePermission();
-        final ContentResolver cr = mContext.getContentResolver();
-        boolean isWpa;
         if (wifiConfig == null)
             return;
-        Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
-        isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
-        Settings.Secure.putInt(cr,
-                               Settings.Secure.WIFI_AP_SECURITY,
-                               isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
-        if (isWpa)
-            Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
+        Message.obtain(mWifiHandler, MESSAGE_WRITE_WIFI_AP_CONFIG, wifiConfig).sendToTarget();
     }
 
+    /* Generate a default WPA2 based configuration with a random password.
+
+       We are changing the Wifi Ap configuration storage from secure settings to a
+       flat file accessible only by the system. A WPA2 based default configuration
+       will keep the device secure after the update */
+    private void setDefaultWifiApConfiguration() {
+        synchronized (mWifiApConfigLock) {
+            mWifiApConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
+            mWifiApConfig.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
+            String randomUUID = UUID.randomUUID().toString();
+            //first 12 chars from xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
+            mWifiApConfig.preSharedKey = randomUUID.substring(0, 8) + randomUUID.substring(9,13);
+        }
+    }
+
+    private void writeWifiApConfigBlocked(WifiConfiguration wifiConfig) {
+        DataOutputStream out = null;
+        try {
+            out = new DataOutputStream(new BufferedOutputStream(
+                        new FileOutputStream(WIFIAP_CONFIG_FILE)));
+
+            out.writeInt(WIFIAP_CONFIG_VERSION);
+            out.writeUTF(wifiConfig.SSID);
+            if(wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
+                out.writeInt(KeyMgmt.WPA_PSK);
+                out.writeUTF(wifiConfig.preSharedKey);
+            } else {
+                out.writeInt(KeyMgmt.NONE);
+            }
+            synchronized (mWifiApConfigLock) {
+                mWifiApConfig = wifiConfig;
+            }
+        } catch (IOException e) {
+            Slog.e(TAG, "Error writing hotspot configuration" + e);
+        } finally {
+            if (out != null) {
+                try {
+                    out.close();
+                } catch (IOException e) {}
+            }
+        }
+    }
+
+    private void readWifiApConfigBlocked() {
+        DataInputStream in = null;
+        try {
+            WifiConfiguration config = new WifiConfiguration();
+            in = new DataInputStream(new BufferedInputStream(new FileInputStream(
+                            WIFIAP_CONFIG_FILE)));
+
+            int version = in.readInt();
+            if (version != 1) {
+                Slog.e(TAG, "Bad version on hotspot configuration file, set defaults");
+                setDefaultWifiApConfiguration();
+                return;
+            }
+            config.SSID = in.readUTF();
+            int authType = in.readInt();
+            config.allowedKeyManagement.set(authType);
+            if (authType != KeyMgmt.NONE) {
+                config.preSharedKey = in.readUTF();
+            }
+            synchronized (mWifiApConfigLock) {
+                mWifiApConfig = config;
+            }
+        } catch (IOException ignore) {
+            setDefaultWifiApConfiguration();
+        } finally {
+            if (in != null) {
+                try {
+                    in.close();
+                } catch (IOException e) {}
+            }
+        }
+    }
+
+
     /**
      * Enables/disables Wi-Fi AP synchronously. The driver is loaded
      * and soft access point configured as a single operation.
@@ -716,11 +803,7 @@
         if (enable) {
 
             /* Use default config if there is no existing config */
-            if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
-                wifiConfig = new WifiConfiguration();
-                wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
-                wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
-            }
+            if (wifiConfig == null) wifiConfig = getWifiApConfiguration();
 
             if (!mWifiStateTracker.loadDriver()) {
                 Slog.e(TAG, "Failed to load Wi-Fi driver for AP mode");
@@ -2038,6 +2121,12 @@
                 case MESSAGE_ENABLE_RSSI_POLLING:
                     mWifiStateTracker.enableRssiPolling(msg.arg1 == 1);
                     break;
+                case MESSAGE_WRITE_WIFI_AP_CONFIG:
+                    writeWifiApConfigBlocked((WifiConfiguration) msg.obj);
+                    break;
+                case MESSAGE_READ_WIFI_AP_CONFIG:
+                    readWifiApConfigBlocked();
+                    break;
             }
         }
     }
diff --git a/services/java/com/android/server/WindowManagerService.java b/services/java/com/android/server/WindowManagerService.java
index 667b544..26cf55f 100644
--- a/services/java/com/android/server/WindowManagerService.java
+++ b/services/java/com/android/server/WindowManagerService.java
@@ -929,6 +929,10 @@
                         && w.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING
                         && i > 0) {
                     WindowState wb = localmWindows.get(i-1);
+                    while (i > 1 && wb.mAppToken == w.mAppToken && !canBeImeTarget(wb)) {
+                        i--;
+                        wb = localmWindows.get(i-1);
+                    }
                     if (wb.mAppToken == w.mAppToken && canBeImeTarget(wb)) {
                         i--;
                         w = wb;
diff --git a/services/java/com/android/server/am/ActivityManagerService.java b/services/java/com/android/server/am/ActivityManagerService.java
old mode 100755
new mode 100644
index 0e38e10..d24ce7e
--- a/services/java/com/android/server/am/ActivityManagerService.java
+++ b/services/java/com/android/server/am/ActivityManagerService.java
@@ -6694,8 +6694,9 @@
 
         addErrorToDropBox("wtf", r, null, null, tag, null, null, crashInfo);
 
-        if (Settings.Secure.getInt(mContext.getContentResolver(),
-                Settings.Secure.WTF_IS_FATAL, 0) != 0) {
+        if (r != null && r.pid != Process.myPid() &&
+                Settings.Secure.getInt(mContext.getContentResolver(),
+                        Settings.Secure.WTF_IS_FATAL, 0) != 0) {
             crashApplication(r, crashInfo);
             return true;
         } else {
@@ -6733,18 +6734,25 @@
      * to append various headers to the dropbox log text.
      */
     private void appendDropBoxProcessHeaders(ProcessRecord process, StringBuilder sb) {
+        // Watchdog thread ends up invoking this function (with
+        // a null ProcessRecord) to add the stack file to dropbox.
+        // Do not acquire a lock on this (am) in such cases, as it
+        // could cause a potential deadlock, if and when watchdog
+        // is invoked due to unavailability of lock on am and it
+        // would prevent watchdog from killing system_server.
+        if (process == null) {
+            sb.append("Process: system_server\n");
+            return;
+        }
         // Note: ProcessRecord 'process' is guarded by the service
         // instance.  (notably process.pkgList, which could otherwise change
         // concurrently during execution of this method)
         synchronized (this) {
-            if (process == null || process.pid == MY_PID) {
+            if (process.pid == MY_PID) {
                 sb.append("Process: system_server\n");
             } else {
                 sb.append("Process: ").append(process.processName).append("\n");
             }
-            if (process == null) {
-                return;
-            }
             int flags = process.info.flags;
             IPackageManager pm = AppGlobals.getPackageManager();
             sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
diff --git a/services/java/com/android/server/connectivity/Tethering.java b/services/java/com/android/server/connectivity/Tethering.java
index a73a4ce..a430128 100644
--- a/services/java/com/android/server/connectivity/Tethering.java
+++ b/services/java/com/android/server/connectivity/Tethering.java
@@ -26,7 +26,7 @@
 import android.content.IntentFilter;
 import android.content.pm.PackageManager;
 import android.content.res.Resources;
-import android.hardware.Usb;
+import android.hardware.usb.UsbManager;
 import android.net.ConnectivityManager;
 import android.net.InterfaceConfiguration;
 import android.net.IConnectivityManager;
@@ -111,14 +111,6 @@
     private boolean mUsbMassStorageOff;  // track the status of USB Mass Storage
     private boolean mUsbConnected;       // track the status of USB connection
 
-    // mUsbHandler message
-    static final int USB_STATE_CHANGE = 1;
-    static final int USB_DISCONNECTED = 0;
-    static final int USB_CONNECTED = 1;
-
-    // Time to delay before processing USB disconnect events
-    static final long USB_DISCONNECT_DELAY = 1000;
-
     public Tethering(Context context, Looper looper) {
         mContext = context;
         mLooper = looper;
@@ -143,7 +135,7 @@
 
         mStateReceiver = new StateReceiver();
         IntentFilter filter = new IntentFilter();
-        filter.addAction(Usb.ACTION_USB_STATE);
+        filter.addAction(UsbManager.ACTION_USB_STATE);
         filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
         filter.addAction(Intent.ACTION_BOOT_COMPLETED);
         mContext.registerReceiver(mStateReceiver, filter);
@@ -429,25 +421,12 @@
         }
     }
 
-    private Handler mUsbHandler = new Handler() {
-        @Override
-        public void handleMessage(Message msg) {
-            mUsbConnected = (msg.arg1 == USB_CONNECTED);
-            updateUsbStatus();
-        }
-    };
-
     private class StateReceiver extends BroadcastReceiver {
         public void onReceive(Context content, Intent intent) {
             String action = intent.getAction();
-            if (action.equals(Usb.ACTION_USB_STATE)) {
-                // process connect events immediately, but delay handling disconnects
-                // to debounce USB configuration changes
-                boolean connected = intent.getExtras().getBoolean(Usb.USB_CONNECTED);
-                Message msg = Message.obtain(mUsbHandler, USB_STATE_CHANGE,
-                        (connected ? USB_CONNECTED : USB_DISCONNECTED), 0);
-                mUsbHandler.removeMessages(USB_STATE_CHANGE);
-                mUsbHandler.sendMessageDelayed(msg, connected ? 0 : USB_DISCONNECT_DELAY);
+            if (action.equals(UsbManager.ACTION_USB_STATE)) {
+                mUsbConnected = intent.getExtras().getBoolean(UsbManager.USB_CONNECTED);
+                updateUsbStatus();
             } else if (action.equals(Intent.ACTION_MEDIA_SHARED)) {
                 mUsbMassStorageOff = false;
                 updateUsbStatus();
@@ -1191,21 +1170,21 @@
                     return null;
                 }
 
-                for (String iface : ifaces) {
-                    for (String regex : mUpstreamIfaceRegexs) {
+                for (String regex : mUpstreamIfaceRegexs) {
+                    for (String iface : ifaces) {
                         if (iface.matches(regex)) {
-                            // verify it is up!
+                            // verify it is active
                             InterfaceConfiguration ifcg = null;
                             try {
                                 ifcg = service.getInterfaceConfig(iface);
+                                if (ifcg.isActive()) {
+                                    return iface;
+                                }
                             } catch (Exception e) {
                                 Log.e(TAG, "Error getting iface config :" + e);
                                 // ignore - try next
                                 continue;
                             }
-                            if (ifcg.interfaceFlags.contains("up")) {
-                                return iface;
-                            }
                         }
                     }
                 }
diff --git a/services/java/com/android/server/location/GpsLocationProvider.java b/services/java/com/android/server/location/GpsLocationProvider.java
index 3561862..53f08e1 100755
--- a/services/java/com/android/server/location/GpsLocationProvider.java
+++ b/services/java/com/android/server/location/GpsLocationProvider.java
@@ -47,30 +47,25 @@
 import android.os.WorkSource;
 import android.provider.Settings;
 import android.provider.Telephony.Sms.Intents;
+import android.telephony.SmsMessage;
 import android.telephony.TelephonyManager;
 import android.telephony.gsm.GsmCellLocation;
-import android.telephony.SmsMessage;
 import android.util.Log;
 import android.util.SparseIntArray;
 
 import com.android.internal.app.IBatteryStats;
-import com.android.internal.telephony.Phone;
 import com.android.internal.location.GpsNetInitiatedHandler;
 import com.android.internal.location.GpsNetInitiatedHandler.GpsNiNotification;
-import com.android.internal.telephony.GsmAlphabet;
-import com.android.internal.telephony.SmsHeader;
-import com.android.internal.util.HexDump;
+import com.android.internal.telephony.Phone;
 
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.StringBufferInputStream;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
 import java.util.ArrayList;
 import java.util.Date;
-import java.util.Properties;
 import java.util.Map.Entry;
+import java.util.Properties;
 import java.util.concurrent.CountDownLatch;
 
 /**
@@ -203,7 +198,7 @@
     // flags to trigger NTP or XTRA data download when network becomes available
     // initialized to true so we do NTP and XTRA when the network comes up after booting
     private boolean mInjectNtpTimePending = true;
-    private boolean mDownloadXtraDataPending = false;
+    private boolean mDownloadXtraDataPending = true;
 
     // true if GPS is navigating
     private boolean mNavigating;
@@ -258,6 +253,7 @@
 
     private String mAGpsApn;
     private int mAGpsDataConnectionState;
+    private int mAGpsDataConnectionIpAddr;
     private final ConnectivityManager mConnMgr;
     private final GpsNetInitiatedHandler mNIHandler; 
 
@@ -501,8 +497,21 @@
         if (info != null && info.getType() == ConnectivityManager.TYPE_MOBILE_SUPL
                 && mAGpsDataConnectionState == AGPS_DATA_CONNECTION_OPENING) {
             String apnName = info.getExtraInfo();
-            if (mNetworkAvailable && apnName != null && apnName.length() > 0) {
+            if (mNetworkAvailable) {
+                if (apnName == null) {
+                    /* Assign a dummy value in the case of C2K as otherwise we will have a runtime 
+                    exception in the following call to native_agps_data_conn_open*/
+                    apnName = "dummy-apn";
+                }
                 mAGpsApn = apnName;
+                if (DEBUG) Log.d(TAG, "mAGpsDataConnectionIpAddr " + mAGpsDataConnectionIpAddr);
+                if (mAGpsDataConnectionIpAddr != 0xffffffff) {
+                    boolean route_result;
+                    if (DEBUG) Log.d(TAG, "call requestRouteToHost");
+                    route_result = mConnMgr.requestRouteToHost(ConnectivityManager.TYPE_MOBILE_SUPL,
+                        mAGpsDataConnectionIpAddr);
+                    if (route_result == false) Log.d(TAG, "call requestRouteToHost failed");
+                }
                 if (DEBUG) Log.d(TAG, "call native_agps_data_conn_open");
                 native_agps_data_conn_open(apnName);
                 mAGpsDataConnectionState = AGPS_DATA_CONNECTION_OPEN;
@@ -1230,7 +1239,7 @@
     /**
      * called from native code to update AGPS status
      */
-    private void reportAGpsStatus(int type, int status) {
+    private void reportAGpsStatus(int type, int status, int ipaddr) {
         switch (status) {
             case GPS_REQUEST_AGPS_DATA_CONN:
                 if (DEBUG) Log.d(TAG, "GPS_REQUEST_AGPS_DATA_CONN");
@@ -1239,9 +1248,19 @@
                 mAGpsDataConnectionState = AGPS_DATA_CONNECTION_OPENING;
                 int result = mConnMgr.startUsingNetworkFeature(
                         ConnectivityManager.TYPE_MOBILE, Phone.FEATURE_ENABLE_SUPL);
+                mAGpsDataConnectionIpAddr = ipaddr;
                 if (result == Phone.APN_ALREADY_ACTIVE) {
                     if (DEBUG) Log.d(TAG, "Phone.APN_ALREADY_ACTIVE");
                     if (mAGpsApn != null) {
+                        Log.d(TAG, "mAGpsDataConnectionIpAddr " + mAGpsDataConnectionIpAddr);
+                        if (mAGpsDataConnectionIpAddr != 0xffffffff) {
+                            boolean route_result;
+                            if (DEBUG) Log.d(TAG, "call requestRouteToHost");
+                            route_result = mConnMgr.requestRouteToHost(
+                                ConnectivityManager.TYPE_MOBILE_SUPL,
+                                mAGpsDataConnectionIpAddr);
+                            if (route_result == false) Log.d(TAG, "call requestRouteToHost failed");
+                        }
                         native_agps_data_conn_open(mAGpsApn);
                         mAGpsDataConnectionState = AGPS_DATA_CONNECTION_OPEN;
                     } else {
diff --git a/services/java/com/android/server/usb/UsbDeviceSettingsManager.java b/services/java/com/android/server/usb/UsbDeviceSettingsManager.java
new file mode 100644
index 0000000..616bdca
--- /dev/null
+++ b/services/java/com/android/server/usb/UsbDeviceSettingsManager.java
@@ -0,0 +1,671 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.server.usb;
+
+import android.app.PendingIntent;
+import android.content.ActivityNotFoundException;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ActivityInfo;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.pm.ResolveInfo;
+import android.content.res.XmlResourceParser;
+import android.hardware.usb.UsbAccessory;
+import android.hardware.usb.UsbManager;
+import android.os.Binder;
+import android.os.FileUtils;
+import android.os.Process;
+import android.util.Log;
+import android.util.SparseBooleanArray;
+import android.util.Xml;
+
+import com.android.internal.content.PackageMonitor;
+import com.android.internal.util.FastXmlSerializer;
+import com.android.internal.util.XmlUtils;
+
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+import org.xmlpull.v1.XmlSerializer;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileDescriptor;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+class UsbDeviceSettingsManager {
+
+    private static final String TAG = "UsbDeviceSettingsManager";
+    private static final File sSettingsFile = new File("/data/system/usb_device_manager.xml");
+
+    private final Context mContext;
+    private final PackageManager mPackageManager;
+
+    // Temporary mapping UsbAccessory to list of UIDs with permissions for the accessory
+    private final HashMap<UsbAccessory, SparseBooleanArray> mAccessoryPermissionMap =
+            new HashMap<UsbAccessory, SparseBooleanArray>();
+    // Maps AccessoryFilter to user preferred application package
+    private final HashMap<AccessoryFilter, String> mAccessoryPreferenceMap =
+            new HashMap<AccessoryFilter, String>();
+
+    private final Object mLock = new Object();
+
+    // This class is used to describe a USB accessory.
+    // When used in HashMaps all values must be specified,
+    // but wildcards can be used for any of the fields in
+    // the package meta-data.
+    private static class AccessoryFilter {
+        // USB accessory manufacturer (or null for unspecified)
+        public final String mManufacturer;
+        // USB accessory model (or null for unspecified)
+        public final String mModel;
+        // USB accessory version (or null for unspecified)
+        public final String mVersion;
+
+        public AccessoryFilter(String manufacturer, String model, String version) {
+            mManufacturer = manufacturer;
+            mModel = model;
+            mVersion = version;
+        }
+
+        public AccessoryFilter(UsbAccessory accessory) {
+            mManufacturer = accessory.getManufacturer();
+            mModel = accessory.getModel();
+            mVersion = accessory.getVersion();
+        }
+
+        public static AccessoryFilter read(XmlPullParser parser)
+                throws XmlPullParserException, IOException {
+            String manufacturer = null;
+            String model = null;
+            String version = null;
+
+            int count = parser.getAttributeCount();
+            for (int i = 0; i < count; i++) {
+                String name = parser.getAttributeName(i);
+                String value = parser.getAttributeValue(i);
+
+                if ("manufacturer".equals(name)) {
+                    manufacturer = value;
+                } else if ("model".equals(name)) {
+                    model = value;
+                } else if ("version".equals(name)) {
+                    version = value;
+                }
+             }
+             return new AccessoryFilter(manufacturer, model, version);
+        }
+
+        public void write(XmlSerializer serializer)throws IOException {
+            serializer.startTag(null, "usb-accessory");
+            if (mManufacturer != null) {
+                serializer.attribute(null, "manufacturer", mManufacturer);
+            }
+            if (mModel != null) {
+                serializer.attribute(null, "model", mModel);
+            }
+            if (mVersion != null) {
+                serializer.attribute(null, "version", mVersion);
+            }
+            serializer.endTag(null, "usb-accessory");
+        }
+
+        public boolean matches(UsbAccessory acc) {
+            if (mManufacturer != null && !acc.getManufacturer().equals(mManufacturer)) return false;
+            if (mModel != null && !acc.getModel().equals(mModel)) return false;
+            if (mVersion != null && !acc.getVersion().equals(mVersion)) return false;
+            return true;
+        }
+
+        public boolean matches(AccessoryFilter f) {
+            if (mManufacturer != null && !f.mManufacturer.equals(mManufacturer)) return false;
+            if (mModel != null && !f.mModel.equals(mModel)) return false;
+            if (mVersion != null && !f.mVersion.equals(mVersion)) return false;
+            return true;
+        }
+
+        @Override
+        public boolean equals(Object obj) {
+            // can't compare if we have wildcard strings
+            if (mManufacturer == null || mModel == null || mVersion == null) {
+                return false;
+            }
+            if (obj instanceof AccessoryFilter) {
+                AccessoryFilter filter = (AccessoryFilter)obj;
+                return (mManufacturer.equals(filter.mManufacturer) &&
+                        mModel.equals(filter.mModel) &&
+                        mVersion.equals(filter.mVersion));
+            }
+            if (obj instanceof UsbAccessory) {
+                UsbAccessory accessory = (UsbAccessory)obj;
+                return (mManufacturer.equals(accessory.getManufacturer()) &&
+                        mModel.equals(accessory.getModel()) &&
+                        mVersion.equals(accessory.getVersion()));
+            }
+            return false;
+        }
+
+        @Override
+        public int hashCode() {
+            return ((mManufacturer == null ? 0 : mManufacturer.hashCode()) ^
+                    (mModel == null ? 0 : mModel.hashCode()) ^
+                    (mVersion == null ? 0 : mVersion.hashCode()));
+        }
+
+        @Override
+        public String toString() {
+            return "AccessoryFilter[mManufacturer=\"" + mManufacturer +
+                                "\", mModel=\"" + mModel +
+                                "\", mVersion=\"" + mVersion + "\"]";
+        }
+    }
+
+    private class MyPackageMonitor extends PackageMonitor {
+
+        public void onPackageAdded(String packageName, int uid) {
+            handlePackageUpdate(packageName);
+        }
+
+        public void onPackageChanged(String packageName, int uid, String[] components) {
+            handlePackageUpdate(packageName);
+        }
+
+        public void onPackageRemoved(String packageName, int uid) {
+            clearDefaults(packageName);
+        }
+    }
+    MyPackageMonitor mPackageMonitor = new MyPackageMonitor();
+
+    public UsbDeviceSettingsManager(Context context) {
+        mContext = context;
+        mPackageManager = context.getPackageManager();
+        synchronized (mLock) {
+            readSettingsLocked();
+        }
+        mPackageMonitor.register(context, true);
+    }
+
+    private void readPreference(XmlPullParser parser)
+            throws XmlPullParserException, IOException {
+        String packageName = null;
+        int count = parser.getAttributeCount();
+        for (int i = 0; i < count; i++) {
+            if ("package".equals(parser.getAttributeName(i))) {
+                packageName = parser.getAttributeValue(i);
+                break;
+            }
+        }
+        XmlUtils.nextElement(parser);
+        if ("usb-accessory".equals(parser.getName())) {
+            AccessoryFilter filter = AccessoryFilter.read(parser);
+            mAccessoryPreferenceMap.put(filter, packageName);
+        }
+        XmlUtils.nextElement(parser);
+    }
+
+    private void readSettingsLocked() {
+        FileInputStream stream = null;
+        try {
+            stream = new FileInputStream(sSettingsFile);
+            XmlPullParser parser = Xml.newPullParser();
+            parser.setInput(stream, null);
+
+            XmlUtils.nextElement(parser);
+            while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
+                String tagName = parser.getName();
+                if ("preference".equals(tagName)) {
+                    readPreference(parser);
+                 } else {
+                    XmlUtils.nextElement(parser);
+                }
+            }
+        } catch (FileNotFoundException e) {
+            Log.w(TAG, "settings file not found");
+        } catch (Exception e) {
+            Log.e(TAG, "error reading settings file, deleting to start fresh", e);
+            sSettingsFile.delete();
+        } finally {
+            if (stream != null) {
+                try {
+                    stream.close();
+                } catch (IOException e) {
+                }
+            }
+        }
+    }
+
+    private void writeSettingsLocked() {
+        FileOutputStream fos = null;
+        try {
+            FileOutputStream fstr = new FileOutputStream(sSettingsFile);
+            Log.d(TAG, "writing settings to " + fstr);
+            BufferedOutputStream str = new BufferedOutputStream(fstr);
+            FastXmlSerializer serializer = new FastXmlSerializer();
+            serializer.setOutput(str, "utf-8");
+            serializer.startDocument(null, true);
+            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
+            serializer.startTag(null, "settings");
+
+            for (AccessoryFilter filter : mAccessoryPreferenceMap.keySet()) {
+                serializer.startTag(null, "preference");
+                serializer.attribute(null, "package", mAccessoryPreferenceMap.get(filter));
+                filter.write(serializer);
+                serializer.endTag(null, "preference");
+            }
+
+            serializer.endTag(null, "settings");
+            serializer.endDocument();
+
+            str.flush();
+            FileUtils.sync(fstr);
+            str.close();
+        } catch (Exception e) {
+            Log.e(TAG, "error writing settings file, deleting to start fresh", e);
+            sSettingsFile.delete();
+        }
+    }
+
+    // Checks to see if a package matches an accessory.
+    private boolean packageMatchesLocked(ResolveInfo info, String metaDataName,
+            UsbAccessory accessory) {
+        ActivityInfo ai = info.activityInfo;
+
+        XmlResourceParser parser = null;
+        try {
+            parser = ai.loadXmlMetaData(mPackageManager, metaDataName);
+            if (parser == null) {
+                Log.w(TAG, "no meta-data for " + info);
+                return false;
+            }
+
+            XmlUtils.nextElement(parser);
+            while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
+                String tagName = parser.getName();
+                if (accessory != null && "usb-accessory".equals(tagName)) {
+                    AccessoryFilter filter = AccessoryFilter.read(parser);
+                    if (filter.matches(accessory)) {
+                        return true;
+                    }
+                }
+                XmlUtils.nextElement(parser);
+            }
+        } catch (Exception e) {
+            Log.w(TAG, "Unable to load component info " + info.toString(), e);
+        } finally {
+            if (parser != null) parser.close();
+        }
+        return false;
+    }
+
+    private final ArrayList<ResolveInfo> getAccessoryMatchesLocked(
+            UsbAccessory accessory, Intent intent) {
+        ArrayList<ResolveInfo> matches = new ArrayList<ResolveInfo>();
+        List<ResolveInfo> resolveInfos = mPackageManager.queryIntentActivities(intent,
+                PackageManager.GET_META_DATA);
+        int count = resolveInfos.size();
+        for (int i = 0; i < count; i++) {
+            ResolveInfo resolveInfo = resolveInfos.get(i);
+            if (packageMatchesLocked(resolveInfo, intent.getAction(), accessory)) {
+                matches.add(resolveInfo);
+            }
+        }
+        return matches;
+    }
+
+    public void accessoryAttached(UsbAccessory accessory) {
+        Intent intent = new Intent(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
+        intent.putExtra(UsbManager.EXTRA_ACCESSORY, accessory);
+        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
+        ArrayList<ResolveInfo> matches;
+        String defaultPackage;
+        synchronized (mLock) {
+            matches = getAccessoryMatchesLocked(accessory, intent);
+            // Launch our default activity directly, if we have one.
+            // Otherwise we will start the UsbResolverActivity to allow the user to choose.
+            defaultPackage = mAccessoryPreferenceMap.get(new AccessoryFilter(accessory));
+        }
+
+        resolveActivity(intent, matches, defaultPackage, accessory);
+    }
+
+    public void accessoryDetached(UsbAccessory accessory) {
+        // clear temporary permissions for the accessory
+        mAccessoryPermissionMap.remove(accessory);
+
+        Intent intent = new Intent(
+                UsbManager.ACTION_USB_ACCESSORY_DETACHED);
+        intent.putExtra(UsbManager.EXTRA_ACCESSORY, accessory);
+        mContext.sendBroadcast(intent);
+    }
+
+    private void resolveActivity(Intent intent, ArrayList<ResolveInfo> matches,
+            String defaultPackage, UsbAccessory accessory) {
+        int count = matches.size();
+
+        // don't show the resolver activity if there are no choices available
+        if (count == 0) {
+            if (accessory != null) {
+                String uri = accessory.getUri();
+                if (uri != null && uri.length() > 0) {
+                    // display URI to user
+                    // start UsbResolverActivity so user can choose an activity
+                    Intent dialogIntent = new Intent();
+                    dialogIntent.setClassName("com.android.systemui",
+                            "com.android.systemui.usb.UsbAccessoryUriActivity");
+                    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+                    dialogIntent.putExtra(UsbManager.EXTRA_ACCESSORY, accessory);
+                    dialogIntent.putExtra("uri", uri);
+                    try {
+                        mContext.startActivity(dialogIntent);
+                    } catch (ActivityNotFoundException e) {
+                        Log.e(TAG, "unable to start UsbAccessoryUriActivity");
+                    }
+                }
+            }
+
+            // do nothing
+            return;
+        }
+
+        ResolveInfo defaultRI = null;
+        if (count == 1 && defaultPackage == null) {
+            // Check to see if our single choice is on the system partition.
+            // If so, treat it as our default without calling UsbResolverActivity
+            ResolveInfo rInfo = matches.get(0);
+            if (rInfo.activityInfo != null &&
+                    rInfo.activityInfo.applicationInfo != null &&
+                    (rInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
+                defaultRI = rInfo;
+            }
+        }
+
+        if (defaultRI == null && defaultPackage != null) {
+            // look for default activity
+            for (int i = 0; i < count; i++) {
+                ResolveInfo rInfo = matches.get(i);
+                if (rInfo.activityInfo != null &&
+                        defaultPackage.equals(rInfo.activityInfo.packageName)) {
+                    defaultRI = rInfo;
+                    break;
+                }
+            }
+        }
+
+        if (defaultRI != null) {
+            // grant permission for default activity
+            grantAccessoryPermission(accessory, defaultRI.activityInfo.applicationInfo.uid);
+
+            // start default activity directly
+            try {
+                intent.setComponent(
+                        new ComponentName(defaultRI.activityInfo.packageName,
+                                defaultRI.activityInfo.name));
+                mContext.startActivity(intent);
+            } catch (ActivityNotFoundException e) {
+                Log.e(TAG, "startActivity failed", e);
+            }
+        } else {
+            Intent resolverIntent = new Intent();
+            resolverIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
+            if (count == 1) {
+                // start UsbConfirmActivity if there is only one choice
+                resolverIntent.setClassName("com.android.systemui",
+                        "com.android.systemui.usb.UsbConfirmActivity");
+                resolverIntent.putExtra("rinfo", matches.get(0));
+                resolverIntent.putExtra(UsbManager.EXTRA_ACCESSORY, accessory);
+            } else {
+                // start UsbResolverActivity so user can choose an activity
+                resolverIntent.setClassName("com.android.systemui",
+                        "com.android.systemui.usb.UsbResolverActivity");
+                resolverIntent.putParcelableArrayListExtra("rlist", matches);
+                resolverIntent.putExtra(Intent.EXTRA_INTENT, intent);
+            }
+            try {
+                mContext.startActivity(resolverIntent);
+            } catch (ActivityNotFoundException e) {
+                Log.e(TAG, "unable to start activity " + resolverIntent);
+            }
+        }
+    }
+
+    private boolean clearCompatibleMatchesLocked(String packageName, AccessoryFilter filter) {
+        boolean changed = false;
+        for (AccessoryFilter test : mAccessoryPreferenceMap.keySet()) {
+            if (filter.matches(test)) {
+                mAccessoryPreferenceMap.remove(test);
+                changed = true;
+            }
+        }
+        return changed;
+    }
+
+    private boolean handlePackageUpdateLocked(String packageName, ActivityInfo aInfo,
+            String metaDataName) {
+        XmlResourceParser parser = null;
+        boolean changed = false;
+
+        try {
+            parser = aInfo.loadXmlMetaData(mPackageManager, metaDataName);
+            if (parser == null) return false;
+
+            XmlUtils.nextElement(parser);
+            while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
+                String tagName = parser.getName();
+                if ("usb-accessory".equals(tagName)) {
+                    AccessoryFilter filter = AccessoryFilter.read(parser);
+                    if (clearCompatibleMatchesLocked(packageName, filter)) {
+                        changed = true;
+                    }
+                }
+                XmlUtils.nextElement(parser);
+            }
+        } catch (Exception e) {
+            Log.w(TAG, "Unable to load component info " + aInfo.toString(), e);
+        } finally {
+            if (parser != null) parser.close();
+        }
+        return changed;
+    }
+
+    // Check to see if the package supports any USB devices or accessories.
+    // If so, clear any non-matching preferences for matching devices/accessories.
+    private void handlePackageUpdate(String packageName) {
+        synchronized (mLock) {
+            PackageInfo info;
+            boolean changed = false;
+
+            try {
+                info = mPackageManager.getPackageInfo(packageName,
+                        PackageManager.GET_ACTIVITIES | PackageManager.GET_META_DATA);
+            } catch (NameNotFoundException e) {
+                Log.e(TAG, "handlePackageUpdate could not find package " + packageName, e);
+                return;
+            }
+
+            ActivityInfo[] activities = info.activities;
+            if (activities == null) return;
+            for (int i = 0; i < activities.length; i++) {
+                // check for meta-data, both for devices and accessories
+                if (handlePackageUpdateLocked(packageName, activities[i],
+                        UsbManager.ACTION_USB_ACCESSORY_ATTACHED)) {
+                    changed = true;
+                }
+            }
+
+            if (changed) {
+                writeSettingsLocked();
+            }
+        }
+    }
+
+    public boolean hasPermission(UsbAccessory accessory) {
+        synchronized (mLock) {
+            SparseBooleanArray uidList = mAccessoryPermissionMap.get(accessory);
+            if (uidList == null) {
+                return false;
+            }
+            return uidList.get(Binder.getCallingUid());
+        }
+    }
+
+    public void checkPermission(UsbAccessory accessory) {
+        if (!hasPermission(accessory)) {
+            throw new SecurityException("User has not given permission to accessory " + accessory);
+        }
+    }
+
+    private void requestPermissionDialog(Intent intent, String packageName, PendingIntent pi) {
+        int uid = Binder.getCallingUid();
+
+        // compare uid with packageName to foil apps pretending to be someone else
+        try {
+            ApplicationInfo aInfo = mPackageManager.getApplicationInfo(packageName, 0);
+            if (aInfo.uid != uid) {
+                throw new IllegalArgumentException("package " + packageName +
+                        " does not match caller's uid " + uid);
+            }
+        } catch (PackageManager.NameNotFoundException e) {
+            throw new IllegalArgumentException("package " + packageName + " not found");
+        }
+
+        long identity = Binder.clearCallingIdentity();
+        intent.setClassName("com.android.systemui",
+                "com.android.systemui.usb.UsbPermissionActivity");
+        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        intent.putExtra(Intent.EXTRA_INTENT, pi);
+        intent.putExtra("package", packageName);
+        intent.putExtra("uid", uid);
+        try {
+            mContext.startActivity(intent);
+        } catch (ActivityNotFoundException e) {
+            Log.e(TAG, "unable to start UsbPermissionActivity");
+        } finally {
+            Binder.restoreCallingIdentity(identity);
+        }
+    }
+
+    public void requestPermission(UsbAccessory accessory, String packageName, PendingIntent pi) {
+      Intent intent = new Intent();
+
+        // respond immediately if permission has already been granted
+        if (hasPermission(accessory)) {
+            intent.putExtra(UsbManager.EXTRA_ACCESSORY, accessory);
+            intent.putExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
+           try {
+                pi.send(mContext, 0, intent);
+            } catch (PendingIntent.CanceledException e) {
+                Log.w(TAG, "requestPermission PendingIntent was cancelled");
+            }
+            return;
+        }
+
+        intent.putExtra(UsbManager.EXTRA_ACCESSORY, accessory);
+        requestPermissionDialog(intent, packageName, pi);
+    }
+
+    public void setAccessoryPackage(UsbAccessory accessory, String packageName) {
+        AccessoryFilter filter = new AccessoryFilter(accessory);
+        boolean changed = false;
+        synchronized (mLock) {
+            if (packageName == null) {
+                changed = (mAccessoryPreferenceMap.remove(filter) != null);
+            } else {
+                changed = !packageName.equals(mAccessoryPreferenceMap.get(filter));
+                if (changed) {
+                    mAccessoryPreferenceMap.put(filter, packageName);
+                }
+            }
+            if (changed) {
+                writeSettingsLocked();
+            }
+        }
+    }
+
+    public void grantAccessoryPermission(UsbAccessory accessory, int uid) {
+        synchronized (mLock) {
+            SparseBooleanArray uidList = mAccessoryPermissionMap.get(accessory);
+            if (uidList == null) {
+                uidList = new SparseBooleanArray(1);
+                mAccessoryPermissionMap.put(accessory, uidList);
+            }
+            uidList.put(uid, true);
+        }
+    }
+
+    public boolean hasDefaults(String packageName) {
+        synchronized (mLock) {
+            return mAccessoryPreferenceMap.values().contains(packageName);
+        }
+    }
+
+    public void clearDefaults(String packageName) {
+        synchronized (mLock) {
+            if (clearPackageDefaultsLocked(packageName)) {
+                writeSettingsLocked();
+            }
+        }
+    }
+
+    private boolean clearPackageDefaultsLocked(String packageName) {
+        boolean cleared = false;
+        synchronized (mLock) {
+            if (mAccessoryPreferenceMap.containsValue(packageName)) {
+                // make a copy of the key set to avoid ConcurrentModificationException
+                Object[] keys = mAccessoryPreferenceMap.keySet().toArray();
+                for (int i = 0; i < keys.length; i++) {
+                    Object key = keys[i];
+                    if (packageName.equals(mAccessoryPreferenceMap.get(key))) {
+                        mAccessoryPreferenceMap.remove(key);
+                        cleared = true;
+                    }
+                }
+            }
+            return cleared;
+        }
+    }
+
+    public void dump(FileDescriptor fd, PrintWriter pw) {
+        synchronized (mLock) {
+            pw.println("  Accessory permissions:");
+            for (UsbAccessory accessory : mAccessoryPermissionMap.keySet()) {
+                pw.print("    " + accessory + ": ");
+                SparseBooleanArray uidList = mAccessoryPermissionMap.get(accessory);
+                int count = uidList.size();
+                for (int i = 0; i < count; i++) {
+                    pw.print(Integer.toString(uidList.keyAt(i)) + " ");
+                }
+                pw.println("");
+            }
+            pw.println("  Accessory preferences:");
+            for (AccessoryFilter filter : mAccessoryPreferenceMap.keySet()) {
+                pw.println("    " + filter + ": " + mAccessoryPreferenceMap.get(filter));
+            }
+        }
+    }
+}
diff --git a/services/java/com/android/server/usb/UsbService.java b/services/java/com/android/server/usb/UsbService.java
new file mode 100644
index 0000000..b4789e7
--- /dev/null
+++ b/services/java/com/android/server/usb/UsbService.java
@@ -0,0 +1,480 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.usb;
+
+import android.app.PendingIntent;
+import android.content.BroadcastReceiver;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.PackageManager;
+import android.hardware.usb.IUsbManager;
+import android.hardware.usb.UsbAccessory;
+import android.hardware.usb.UsbManager;
+import android.net.Uri;
+import android.os.Binder;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.os.Parcelable;
+import android.os.ParcelFileDescriptor;
+import android.os.UEventObserver;
+import android.provider.Settings;
+import android.util.Log;
+import android.util.Slog;
+
+import java.io.File;
+import java.io.FileDescriptor;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+/**
+ * UsbService monitors for changes to USB state.
+ * This includes code for both USB host support (where the android device is the host)
+ * as well as USB device support (android device is connected to a USB host).
+ * Accessory mode is a special case of USB device mode, where the android device is
+ * connected to a USB host that supports the android accessory protocol.
+ */
+public class UsbService extends IUsbManager.Stub {
+    private static final String TAG = UsbService.class.getSimpleName();
+    private static final boolean LOG = false;
+
+    private static final String USB_CONNECTED_MATCH =
+            "DEVPATH=/devices/virtual/switch/usb_connected";
+    private static final String USB_CONFIGURATION_MATCH =
+            "DEVPATH=/devices/virtual/switch/usb_configuration";
+    private static final String USB_FUNCTIONS_MATCH =
+            "DEVPATH=/devices/virtual/usb_composite/";
+    private static final String USB_CONNECTED_PATH =
+            "/sys/class/switch/usb_connected/state";
+    private static final String USB_CONFIGURATION_PATH =
+            "/sys/class/switch/usb_configuration/state";
+    private static final String USB_COMPOSITE_CLASS_PATH =
+            "/sys/class/usb_composite";
+
+    private static final int MSG_UPDATE_STATE = 0;
+    private static final int MSG_FUNCTION_ENABLED = 1;
+    private static final int MSG_FUNCTION_DISABLED = 2;
+
+    // Delay for debouncing USB disconnects.
+    // We often get rapid connect/disconnect events when enabling USB functions,
+    // which need debouncing.
+    private static final int UPDATE_DELAY = 1000;
+
+    // current connected and configuration state
+    private int mConnected;
+    private int mConfiguration;
+
+    // last broadcasted connected and configuration state
+    private int mLastConnected = -1;
+    private int mLastConfiguration = -1;
+
+    // lists of enabled and disabled USB functions (for USB device mode)
+    private final ArrayList<String> mEnabledFunctions = new ArrayList<String>();
+    private final ArrayList<String> mDisabledFunctions = new ArrayList<String>();
+
+    private boolean mSystemReady;
+
+    private UsbAccessory mCurrentAccessory;
+    // USB functions that are enabled by default, to restore after exiting accessory mode
+    private final ArrayList<String> mDefaultFunctions = new ArrayList<String>();
+
+    private final Context mContext;
+    private final Object mLock = new Object();
+    private final UsbDeviceSettingsManager mDeviceManager;
+    private final boolean mHasUsbAccessory;
+
+    private final void readCurrentAccessoryLocked() {
+        if (mHasUsbAccessory) {
+            String[] strings = nativeGetAccessoryStrings();
+            if (strings != null) {
+                mCurrentAccessory = new UsbAccessory(strings);
+                Log.d(TAG, "entering USB accessory mode: " + mCurrentAccessory);
+                if (mSystemReady) {
+                    mDeviceManager.accessoryAttached(mCurrentAccessory);
+                }
+            } else {
+                Log.e(TAG, "nativeGetAccessoryStrings failed");
+            }
+        }
+    }
+
+    /*
+     * Handles USB function enable/disable events (device mode)
+     */
+    private final void functionEnabledLocked(String function, boolean enabled) {
+        if (enabled) {
+            if (!mEnabledFunctions.contains(function)) {
+                mEnabledFunctions.add(function);
+            }
+            mDisabledFunctions.remove(function);
+
+            if (UsbManager.USB_FUNCTION_ACCESSORY.equals(function)) {
+                readCurrentAccessoryLocked();
+            }
+        } else {
+            if (!mDisabledFunctions.contains(function)) {
+                mDisabledFunctions.add(function);
+            }
+            mEnabledFunctions.remove(function);
+        }
+    }
+
+    /*
+     * Listens for uevent messages from the kernel to monitor the USB state (device mode)
+     */
+    private final UEventObserver mUEventObserver = new UEventObserver() {
+        @Override
+        public void onUEvent(UEventObserver.UEvent event) {
+            if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                Slog.v(TAG, "USB UEVENT: " + event.toString());
+            }
+
+            synchronized (mLock) {
+                String name = event.get("SWITCH_NAME");
+                String state = event.get("SWITCH_STATE");
+                if (name != null && state != null) {
+                    try {
+                        int intState = Integer.parseInt(state);
+                        if ("usb_connected".equals(name)) {
+                            mConnected = intState;
+                            // trigger an Intent broadcast
+                            if (mSystemReady) {
+                                // debounce disconnects to avoid problems bringing up USB tethering
+                                update(mConnected == 0);
+                            }
+                        } else if ("usb_configuration".equals(name)) {
+                            mConfiguration = intState;
+                            // trigger an Intent broadcast
+                            if (mSystemReady) {
+                                update(mConnected == 0);
+                            }
+                        }
+                    } catch (NumberFormatException e) {
+                        Slog.e(TAG, "Could not parse switch state from event " + event);
+                    }
+                } else {
+                    String function = event.get("FUNCTION");
+                    String enabledStr = event.get("ENABLED");
+                    if (function != null && enabledStr != null) {
+                        // Note: we do not broadcast a change when a function is enabled or disabled.
+                        // We just record the state change for the next broadcast.
+                        int what = ("1".equals(enabledStr) ?
+                                MSG_FUNCTION_ENABLED : MSG_FUNCTION_DISABLED);
+                        Message msg = Message.obtain(mHandler, what);
+                        msg.obj = function;
+                        mHandler.sendMessage(msg);
+                    }
+                }
+            }
+        }
+    };
+
+   private final BroadcastReceiver mBootCompletedReceiver = new BroadcastReceiver() {
+        public void onReceive(Context context, Intent intent) {
+            // handle accessories attached at boot time
+            synchronized (mLock) {
+                if (mCurrentAccessory != null) {
+                    mDeviceManager.accessoryAttached(mCurrentAccessory);
+                }
+            }
+        }
+    };
+
+    public UsbService(Context context) {
+        mContext = context;
+        mDeviceManager = new UsbDeviceSettingsManager(context);
+        PackageManager pm = mContext.getPackageManager();
+        mHasUsbAccessory = pm.hasSystemFeature(PackageManager.FEATURE_USB_ACCESSORY);
+
+        synchronized (mLock) {
+            init();  // set initial status
+
+            // Watch for USB configuration changes
+            if (mConfiguration >= 0) {
+                mUEventObserver.startObserving(USB_CONNECTED_MATCH);
+                mUEventObserver.startObserving(USB_CONFIGURATION_MATCH);
+                mUEventObserver.startObserving(USB_FUNCTIONS_MATCH);
+            }
+        }
+    }
+
+    private final void init() {
+        char[] buffer = new char[1024];
+        boolean inAccessoryMode = false;
+
+        // Read initial USB state (device mode)
+        mConfiguration = -1;
+        try {
+            FileReader file = new FileReader(USB_CONNECTED_PATH);
+            int len = file.read(buffer, 0, 1024);
+            file.close();
+            mConnected = Integer.valueOf((new String(buffer, 0, len)).trim());
+
+            file = new FileReader(USB_CONFIGURATION_PATH);
+            len = file.read(buffer, 0, 1024);
+            file.close();
+            mConfiguration = Integer.valueOf((new String(buffer, 0, len)).trim());
+
+        } catch (FileNotFoundException e) {
+            Slog.i(TAG, "This kernel does not have USB configuration switch support");
+        } catch (Exception e) {
+            Slog.e(TAG, "" , e);
+        }
+        if (mConfiguration < 0) {
+            // This may happen in the emulator or devices without USB device mode support
+            return;
+        }
+
+        // Read initial list of enabled and disabled functions (device mode)
+        try {
+            File[] files = new File(USB_COMPOSITE_CLASS_PATH).listFiles();
+            for (int i = 0; i < files.length; i++) {
+                File file = new File(files[i], "enable");
+                FileReader reader = new FileReader(file);
+                int len = reader.read(buffer, 0, 1024);
+                reader.close();
+                int value = Integer.valueOf((new String(buffer, 0, len)).trim());
+                String functionName = files[i].getName();
+                if (value == 1) {
+                    mEnabledFunctions.add(functionName);
+                if (UsbManager.USB_FUNCTION_ACCESSORY.equals(functionName)) {
+                        // The USB accessory driver is on by default, but it might have been
+                        // enabled before the USB service has initialized.
+                        inAccessoryMode = true;
+                    } else if (!UsbManager.USB_FUNCTION_ADB.equals(functionName)) {
+                        // adb is enabled/disabled automatically by the adbd daemon,
+                        // so don't treat it as a default function.
+                        mDefaultFunctions.add(functionName);
+                    }
+                } else {
+                    mDisabledFunctions.add(functionName);
+                }
+            }
+        } catch (FileNotFoundException e) {
+            Slog.w(TAG, "This kernel does not have USB composite class support");
+        } catch (Exception e) {
+            Slog.e(TAG, "" , e);
+        }
+
+        // handle the case where an accessory switched the driver to accessory mode
+        // before the framework finished booting
+        if (inAccessoryMode) {
+            readCurrentAccessoryLocked();
+
+            // FIXME - if we booted in accessory mode, then we have no way to figure out
+            // which functions are enabled by default.
+            // For now, assume that MTP or mass storage are the only possibilities
+            if (mDisabledFunctions.contains(UsbManager.USB_FUNCTION_MTP)) {
+                mDefaultFunctions.add(UsbManager.USB_FUNCTION_MTP);
+            } else if (mDisabledFunctions.contains(UsbManager.USB_FUNCTION_MASS_STORAGE)) {
+                mDefaultFunctions.add(UsbManager.USB_FUNCTION_MASS_STORAGE);
+            }
+        }
+    }
+
+    public void systemReady() {
+        synchronized (mLock) {
+            update(false);
+            if (mCurrentAccessory != null) {
+                Log.d(TAG, "accessoryAttached at systemReady");
+                // its still too early to handle accessories, so add a BOOT_COMPLETED receiver
+                // to handle this later.
+                mContext.registerReceiver(mBootCompletedReceiver,
+                        new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
+            }
+            mSystemReady = true;
+        }
+    }
+
+    /*
+     * Sends a message to update the USB connected and configured state (device mode).
+     * If delayed is true, then we add a small delay in sending the message to debounce
+     * the USB connection when enabling USB tethering.
+     */
+    private final void update(boolean delayed) {
+        mHandler.removeMessages(MSG_UPDATE_STATE);
+        mHandler.sendEmptyMessageDelayed(MSG_UPDATE_STATE, delayed ? UPDATE_DELAY : 0);
+    }
+
+    /* returns the currently attached USB accessory (device mode) */
+    public UsbAccessory getCurrentAccessory() {
+        return mCurrentAccessory;
+    }
+
+    /* opens the currently attached USB accessory (device mode) */
+    public ParcelFileDescriptor openAccessory(UsbAccessory accessory) {
+        synchronized (mLock) {
+            if (mCurrentAccessory == null) {
+                throw new IllegalArgumentException("no accessory attached");
+            }
+            if (!mCurrentAccessory.equals(accessory)) {
+                Log.e(TAG, accessory.toString() + " does not match current accessory "
+                        + mCurrentAccessory);
+                throw new IllegalArgumentException("accessory not attached");
+            }
+            mDeviceManager.checkPermission(mCurrentAccessory);
+            return nativeOpenAccessory();
+        }
+    }
+
+    public void setAccessoryPackage(UsbAccessory accessory, String packageName) {
+        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USB, null);
+        mDeviceManager.setAccessoryPackage(accessory, packageName);
+    }
+
+    public boolean hasAccessoryPermission(UsbAccessory accessory) {
+        return mDeviceManager.hasPermission(accessory);
+    }
+
+    public void requestAccessoryPermission(UsbAccessory accessory, String packageName,
+            PendingIntent pi) {
+        mDeviceManager.requestPermission(accessory, packageName, pi);
+    }
+
+    public void grantAccessoryPermission(UsbAccessory accessory, int uid) {
+        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USB, null);
+        mDeviceManager.grantAccessoryPermission(accessory, uid);
+    }
+
+    public boolean hasDefaults(String packageName) {
+        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USB, null);
+        return mDeviceManager.hasDefaults(packageName);
+    }
+
+    public void clearDefaults(String packageName) {
+        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USB, null);
+        mDeviceManager.clearDefaults(packageName);
+    }
+
+    /*
+     * This handler is for deferred handling of events related to device mode and accessories.
+     */
+    private final Handler mHandler = new Handler() {
+        private void addEnabledFunctionsLocked(Intent intent) {
+            // include state of all USB functions in our extras
+            for (int i = 0; i < mEnabledFunctions.size(); i++) {
+                intent.putExtra(mEnabledFunctions.get(i), UsbManager.USB_FUNCTION_ENABLED);
+            }
+            for (int i = 0; i < mDisabledFunctions.size(); i++) {
+                intent.putExtra(mDisabledFunctions.get(i), UsbManager.USB_FUNCTION_DISABLED);
+            }
+        }
+
+        @Override
+        public void handleMessage(Message msg) {
+            synchronized (mLock) {
+                switch (msg.what) {
+                    case MSG_UPDATE_STATE:
+                        if (mConnected != mLastConnected || mConfiguration != mLastConfiguration) {
+                            if (mConnected == 0) {
+                                if (UsbManager.isFunctionEnabled(
+                                            UsbManager.USB_FUNCTION_ACCESSORY)) {
+                                    // make sure accessory mode is off, and restore default functions
+                                    Log.d(TAG, "exited USB accessory mode");
+                                    if (!UsbManager.setFunctionEnabled
+                                            (UsbManager.USB_FUNCTION_ACCESSORY, false)) {
+                                        Log.e(TAG, "could not disable accessory function");
+                                    }
+                                    int count = mDefaultFunctions.size();
+                                    for (int i = 0; i < count; i++) {
+                                        String function = mDefaultFunctions.get(i);
+                                        if (!UsbManager.setFunctionEnabled(function, true)) {
+                                            Log.e(TAG, "could not reenable function " + function);
+                                        }
+                                    }
+
+                                    if (mCurrentAccessory != null) {
+                                        mDeviceManager.accessoryDetached(mCurrentAccessory);
+                                        mCurrentAccessory = null;
+                                    }
+                                }
+                            }
+
+                            final ContentResolver cr = mContext.getContentResolver();
+                            if (Settings.Secure.getInt(cr,
+                                    Settings.Secure.DEVICE_PROVISIONED, 0) == 0) {
+                                Slog.i(TAG, "Device not provisioned, skipping USB broadcast");
+                                return;
+                            }
+
+                            mLastConnected = mConnected;
+                            mLastConfiguration = mConfiguration;
+
+                            // send a sticky broadcast containing current USB state
+                            Intent intent = new Intent(UsbManager.ACTION_USB_STATE);
+                            intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
+                            intent.putExtra(UsbManager.USB_CONNECTED, mConnected != 0);
+                            intent.putExtra(UsbManager.USB_CONFIGURATION, mConfiguration);
+                            addEnabledFunctionsLocked(intent);
+                            mContext.sendStickyBroadcast(intent);
+                        }
+                        break;
+                    case MSG_FUNCTION_ENABLED:
+                    case MSG_FUNCTION_DISABLED:
+                        functionEnabledLocked((String)msg.obj, msg.what == MSG_FUNCTION_ENABLED);
+                        break;
+                }
+            }
+        }
+    };
+
+    @Override
+    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
+        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
+                != PackageManager.PERMISSION_GRANTED) {
+            pw.println("Permission Denial: can't dump UsbManager from from pid="
+                    + Binder.getCallingPid()
+                    + ", uid=" + Binder.getCallingUid());
+            return;
+        }
+
+        synchronized (mLock) {
+            pw.println("USB Manager State:");
+
+            pw.println("  USB Device State:");
+            pw.print("    Enabled Functions: ");
+            for (int i = 0; i < mEnabledFunctions.size(); i++) {
+                pw.print(mEnabledFunctions.get(i) + " ");
+            }
+            pw.println("");
+            pw.print("    Disabled Functions: ");
+            for (int i = 0; i < mDisabledFunctions.size(); i++) {
+                pw.print(mDisabledFunctions.get(i) + " ");
+            }
+            pw.println("");
+            pw.print("    Default Functions: ");
+            for (int i = 0; i < mDefaultFunctions.size(); i++) {
+                pw.print(mDefaultFunctions.get(i) + " ");
+            }
+            pw.println("");
+            pw.println("    mConnected: " + mConnected + ", mConfiguration: " + mConfiguration);
+            pw.println("    mCurrentAccessory: " + mCurrentAccessory);
+
+            mDeviceManager.dump(fd, pw);
+        }
+    }
+
+    // accessory support
+    private native String[] nativeGetAccessoryStrings();
+    private native ParcelFileDescriptor nativeOpenAccessory();
+}
diff --git a/services/jni/Android.mk b/services/jni/Android.mk
index c90879d..de8f158 100644
--- a/services/jni/Android.mk
+++ b/services/jni/Android.mk
@@ -8,6 +8,7 @@
     com_android_server_LightsService.cpp \
     com_android_server_PowerManagerService.cpp \
     com_android_server_SystemServer.cpp \
+    com_android_server_UsbService.cpp \
     com_android_server_VibratorService.cpp \
 	com_android_server_location_GpsLocationProvider.cpp \
     onload.cpp
diff --git a/services/jni/com_android_server_UsbService.cpp b/services/jni/com_android_server_UsbService.cpp
new file mode 100644
index 0000000..92c5008
--- /dev/null
+++ b/services/jni/com_android_server_UsbService.cpp
@@ -0,0 +1,141 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "UsbService"
+#include "utils/Log.h"
+
+#include "jni.h"
+#include "JNIHelp.h"
+#include "android_runtime/AndroidRuntime.h"
+#include "utils/Vector.h"
+
+#include <stdio.h>
+#include <asm/byteorder.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <linux/usb/f_accessory.h>
+
+#define DRIVER_NAME "/dev/usb_accessory"
+
+namespace android
+{
+
+static struct file_descriptor_offsets_t
+{
+    jclass mClass;
+    jmethodID mConstructor;
+    jfieldID mDescriptor;
+} gFileDescriptorOffsets;
+
+static struct parcel_file_descriptor_offsets_t
+{
+    jclass mClass;
+    jmethodID mConstructor;
+} gParcelFileDescriptorOffsets;
+
+static void checkAndClearExceptionFromCallback(JNIEnv* env, const char* methodName) {
+    if (env->ExceptionCheck()) {
+        LOGE("An exception was thrown by callback '%s'.", methodName);
+        LOGE_EX(env);
+        env->ExceptionClear();
+    }
+}
+
+static void set_accessory_string(JNIEnv *env, int fd, int cmd, jobjectArray strArray, int index)
+{
+    char buffer[256];
+
+    buffer[0] = 0;
+    int length = ioctl(fd, cmd, buffer);
+    if (buffer[0]) {
+        jstring obj = env->NewStringUTF(buffer);
+        env->SetObjectArrayElement(strArray, index, obj);
+        env->DeleteLocalRef(obj);
+    }
+}
+
+
+static jobjectArray android_server_UsbService_getAccessoryStrings(JNIEnv *env, jobject thiz)
+{
+    int fd = open(DRIVER_NAME, O_RDWR);
+    if (fd < 0) {
+        LOGE("could not open %s", DRIVER_NAME);
+        return NULL;
+    }
+    jclass stringClass = env->FindClass("java/lang/String");
+    jobjectArray strArray = env->NewObjectArray(6, stringClass, NULL);
+    if (!strArray) goto out;
+    set_accessory_string(env, fd, ACCESSORY_GET_STRING_MANUFACTURER, strArray, 0);
+    set_accessory_string(env, fd, ACCESSORY_GET_STRING_MODEL, strArray, 1);
+    set_accessory_string(env, fd, ACCESSORY_GET_STRING_DESCRIPTION, strArray, 2);
+    set_accessory_string(env, fd, ACCESSORY_GET_STRING_VERSION, strArray, 3);
+    set_accessory_string(env, fd, ACCESSORY_GET_STRING_URI, strArray, 4);
+    set_accessory_string(env, fd, ACCESSORY_GET_STRING_SERIAL, strArray, 5);
+
+out:
+    close(fd);
+    return strArray;
+}
+
+static jobject android_server_UsbService_openAccessory(JNIEnv *env, jobject thiz)
+{
+    int fd = open(DRIVER_NAME, O_RDWR);
+    if (fd < 0) {
+        LOGE("could not open %s", DRIVER_NAME);
+        return NULL;
+    }
+    jobject fileDescriptor = env->NewObject(gFileDescriptorOffsets.mClass,
+        gFileDescriptorOffsets.mConstructor);
+    if (fileDescriptor != NULL) {
+        env->SetIntField(fileDescriptor, gFileDescriptorOffsets.mDescriptor, fd);
+    } else {
+        return NULL;
+    }
+    return env->NewObject(gParcelFileDescriptorOffsets.mClass,
+        gParcelFileDescriptorOffsets.mConstructor, fileDescriptor);
+}
+
+static JNINativeMethod method_table[] = {
+    { "nativeGetAccessoryStrings", "()[Ljava/lang/String;",
+                                  (void*)android_server_UsbService_getAccessoryStrings },
+    { "nativeOpenAccessory","()Landroid/os/ParcelFileDescriptor;",
+                                  (void*)android_server_UsbService_openAccessory },
+};
+
+int register_android_server_UsbService(JNIEnv *env)
+{
+   jclass clazz = env->FindClass("java/io/FileDescriptor");
+    LOG_FATAL_IF(clazz == NULL, "Unable to find class java.io.FileDescriptor");
+    gFileDescriptorOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
+    gFileDescriptorOffsets.mConstructor = env->GetMethodID(clazz, "<init>", "()V");
+    gFileDescriptorOffsets.mDescriptor = env->GetFieldID(clazz, "descriptor", "I");
+    LOG_FATAL_IF(gFileDescriptorOffsets.mDescriptor == NULL,
+                 "Unable to find descriptor field in java.io.FileDescriptor");
+
+   clazz = env->FindClass("android/os/ParcelFileDescriptor");
+    LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.ParcelFileDescriptor");
+    gParcelFileDescriptorOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
+    gParcelFileDescriptorOffsets.mConstructor = env->GetMethodID(clazz, "<init>", "(Ljava/io/FileDescriptor;)V");
+    LOG_FATAL_IF(gParcelFileDescriptorOffsets.mConstructor == NULL,
+                 "Unable to find constructor for android.os.ParcelFileDescriptor");
+
+    return jniRegisterNativeMethods(env, "com/android/server/usb/UsbService",
+            method_table, NELEM(method_table));
+}
+
+};
diff --git a/services/jni/com_android_server_location_GpsLocationProvider.cpp b/services/jni/com_android_server_location_GpsLocationProvider.cpp
index 6d4ad9a..d0e8e57 100755
--- a/services/jni/com_android_server_location_GpsLocationProvider.cpp
+++ b/services/jni/com_android_server_location_GpsLocationProvider.cpp
@@ -154,8 +154,15 @@
 static void agps_status_callback(AGpsStatus* agps_status)
 {
     JNIEnv* env = AndroidRuntime::getJNIEnv();
+
+    uint32_t ipaddr;
+    // ipaddr field was not included in original AGpsStatus
+    if (agps_status->size >= sizeof(AGpsStatus))
+        ipaddr = agps_status->ipaddr;
+    else
+        ipaddr = 0xFFFFFFFF;
     env->CallVoidMethod(mCallbacksObj, method_reportAGpsStatus,
-                        agps_status->type, agps_status->status);
+                        agps_status->type, agps_status->status, ipaddr);
     checkAndClearExceptionFromCallback(env, __FUNCTION__);
 }
 
@@ -224,7 +231,7 @@
     method_reportLocation = env->GetMethodID(clazz, "reportLocation", "(IDDDFFFJ)V");
     method_reportStatus = env->GetMethodID(clazz, "reportStatus", "(I)V");
     method_reportSvStatus = env->GetMethodID(clazz, "reportSvStatus", "()V");
-    method_reportAGpsStatus = env->GetMethodID(clazz, "reportAGpsStatus", "(II)V");
+    method_reportAGpsStatus = env->GetMethodID(clazz, "reportAGpsStatus", "(III)V");
     method_reportNmea = env->GetMethodID(clazz, "reportNmea", "(J)V");
     method_setEngineCapabilities = env->GetMethodID(clazz, "setEngineCapabilities", "(I)V");
     method_xtraDownloadRequest = env->GetMethodID(clazz, "xtraDownloadRequest", "()V");
diff --git a/services/jni/onload.cpp b/services/jni/onload.cpp
index cd4f0a4..613683b 100644
--- a/services/jni/onload.cpp
+++ b/services/jni/onload.cpp
@@ -9,6 +9,7 @@
 int register_android_server_InputManager(JNIEnv* env);
 int register_android_server_LightsService(JNIEnv* env);
 int register_android_server_PowerManagerService(JNIEnv* env);
+int register_android_server_UsbService(JNIEnv* env);
 int register_android_server_VibratorService(JNIEnv* env);
 int register_android_server_SystemServer(JNIEnv* env);
 int register_android_server_location_GpsLocationProvider(JNIEnv* env);
@@ -32,6 +33,7 @@
     register_android_server_LightsService(env);
     register_android_server_AlarmManagerService(env);
     register_android_server_BatteryService(env);
+    register_android_server_UsbService(env);
     register_android_server_VibratorService(env);
     register_android_server_SystemServer(env);
     register_android_server_location_GpsLocationProvider(env);
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index c9dcef3..da06f61 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -60,6 +60,7 @@
         mWidth(0), mHeight(0), mNeedsScaling(false), mFixedSize(false),
         mBypassState(false)
 {
+    setDestroyer(this);
 }
 
 Layer::~Layer()
@@ -76,6 +77,10 @@
     }
 }
 
+void Layer::destroy(RefBase const* base) {
+    mFlinger->destroyLayer(static_cast<LayerBase const*>(base));
+}
+
 status_t Layer::setToken(const sp<UserClient>& userClient,
         SharedClient* sharedClient, int32_t token)
 {
@@ -123,22 +128,6 @@
     return mSurface;
 }
 
-status_t Layer::ditch()
-{
-    // NOTE: Called from the main UI thread
-
-    // the layer is not on screen anymore. free as much resources as possible
-    mFreezeLock.clear();
-
-    EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay());
-    mBufferManager.destroy(dpy);
-    mSurface.clear();
-
-    Mutex::Autolock _l(mLock);
-    mWidth = mHeight = 0;
-    return NO_ERROR;
-}
-
 status_t Layer::setBuffers( uint32_t w, uint32_t h,
                             PixelFormat format, uint32_t flags)
 {
@@ -874,8 +863,16 @@
     ssize_t index = mActiveBuffer;
     if (index >= 0) {
         if (!mFailover) {
-            Image& texture(mBufferData[index].texture);
-            err = mTextureManager.initEglImage(&texture, dpy, buffer);
+            {
+               // Without that lock, there is a chance of race condition
+               // where while composing a specific index, requestBuf
+               // with the same index can be executed and touch the same data
+               // that is being used in initEglImage.
+               // (e.g. dirty flag in texture)
+               Mutex::Autolock _l(mLock);
+               Image& texture(mBufferData[index].texture);
+               err = mTextureManager.initEglImage(&texture, dpy, buffer);
+            }
             // if EGLImage fails, we switch to regular texture mode, and we
             // free all resources associated with using EGLImages.
             if (err == NO_ERROR) {
diff --git a/services/surfaceflinger/Layer.h b/services/surfaceflinger/Layer.h
index 7bb207a..2c4f756 100644
--- a/services/surfaceflinger/Layer.h
+++ b/services/surfaceflinger/Layer.h
@@ -44,7 +44,7 @@
 
 // ---------------------------------------------------------------------------
 
-class Layer : public LayerBaseClient
+class Layer : public LayerBaseClient, private RefBase::Destroyer
 {
 public:
             Layer(SurfaceFlinger* flinger, DisplayID display,
@@ -78,7 +78,6 @@
     virtual bool needsFiltering() const;
     virtual bool isSecure() const           { return mSecure; }
     virtual sp<Surface> createSurface() const;
-    virtual status_t ditch();
     virtual void onRemoved();
     virtual bool setBypass(bool enable);
 
@@ -95,6 +94,7 @@
         return mFreezeLock; }
 
 protected:
+    virtual void destroy(RefBase const* base);
     virtual void dump(String8& result, char* scratch, size_t size) const;
 
 private:
diff --git a/services/surfaceflinger/LayerBase.cpp b/services/surfaceflinger/LayerBase.cpp
index 916d420..3986fdef 100644
--- a/services/surfaceflinger/LayerBase.cpp
+++ b/services/surfaceflinger/LayerBase.cpp
@@ -515,12 +515,6 @@
     result.append(buffer);
 }
 
-void LayerBase::shortDump(String8& result, char* scratch, size_t size) const
-{
-    LayerBase::dump(result, scratch, size);
-}
-
-
 // ---------------------------------------------------------------------------
 
 int32_t LayerBaseClient::sIdentity = 1;
@@ -572,12 +566,6 @@
     result.append(buffer);
 }
 
-
-void LayerBaseClient::shortDump(String8& result, char* scratch, size_t size) const
-{
-    LayerBaseClient::dump(result, scratch, size);
-}
-
 // ---------------------------------------------------------------------------
 
 LayerBaseClient::Surface::Surface(
@@ -595,10 +583,7 @@
      */
 
     // destroy client resources
-    sp<LayerBaseClient> layer = getOwner();
-    if (layer != 0) {
-        mFlinger->destroySurface(layer);
-    }
+    mFlinger->destroySurface(mOwner);
 }
 
 sp<LayerBaseClient> LayerBaseClient::Surface::getOwner() const {
diff --git a/services/surfaceflinger/LayerBase.h b/services/surfaceflinger/LayerBase.h
index 1470729..e69cb6a 100644
--- a/services/surfaceflinger/LayerBase.h
+++ b/services/surfaceflinger/LayerBase.h
@@ -196,17 +196,12 @@
      */
     virtual bool isSecure() const       { return false; }
 
-    /** Called from the main thread, when the surface is removed from the
-     * draw list */
-    virtual status_t ditch() { return NO_ERROR; }
-
     /** called with the state lock when the surface is removed from the
      *  current list */
     virtual void onRemoved() { };
     
     /** always call base class first */
     virtual void dump(String8& result, char* scratch, size_t size) const;
-    virtual void shortDump(String8& result, char* scratch, size_t size) const;
 
 
     enum { // flags for doTransaction()
@@ -265,7 +260,8 @@
     volatile    int32_t         mInvalidate;
                 
 
-protected:
+public:
+    // called from class SurfaceFlinger
     virtual ~LayerBase();
 
 private:
@@ -326,7 +322,6 @@
 
 protected:
     virtual void dump(String8& result, char* scratch, size_t size) const;
-    virtual void shortDump(String8& result, char* scratch, size_t size) const;
 
 private:
     mutable Mutex mLock;
diff --git a/services/surfaceflinger/LayerBuffer.cpp b/services/surfaceflinger/LayerBuffer.cpp
index 23506cf..55d859d 100644
--- a/services/surfaceflinger/LayerBuffer.cpp
+++ b/services/surfaceflinger/LayerBuffer.cpp
@@ -93,6 +93,9 @@
 }
 
 void LayerBuffer::setNeedsBlending(bool blending) {
+    if (mNeedsBlending != blending) {
+        mFlinger->invalidateLayerVisibility(this);
+    }
     mNeedsBlending = blending;
 }
 
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 4876946..a93d756 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -358,6 +358,9 @@
 {
     waitForEvent();
 
+    // call Layer's destructor
+    handleDestroyLayers();
+
     // check for transactions
     if (UNLIKELY(mConsoleSignals)) {
         handleConsoleEvents();
@@ -366,7 +369,7 @@
     if (LIKELY(mTransactionCount == 0)) {
         // if we're in a global transaction, don't do anything.
         const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
-        uint32_t transactionFlags = getTransactionFlags(mask);
+        uint32_t transactionFlags = peekTransactionFlags(mask);
         if (LIKELY(transactionFlags)) {
             handleTransaction(transactionFlags);
         }
@@ -467,37 +470,26 @@
 
 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
 {
-    Vector< sp<LayerBase> > ditchedLayers;
+    Mutex::Autolock _l(mStateLock);
+    const nsecs_t now = systemTime();
+    mDebugInTransaction = now;
 
-    /*
-     * Perform and commit the transaction
-     */
+    // Here we're guaranteed that some transaction flags are set
+    // so we can call handleTransactionLocked() unconditionally.
+    // We call getTransactionFlags(), which will also clear the flags,
+    // with mStateLock held to guarantee that mCurrentState won't change
+    // until the transaction is committed.
 
-    { // scope for the lock
-        Mutex::Autolock _l(mStateLock);
-        const nsecs_t now = systemTime();
-        mDebugInTransaction = now;
-        handleTransactionLocked(transactionFlags, ditchedLayers);
-        mLastTransactionTime = systemTime() - now;
-        mDebugInTransaction = 0;
-        // here the transaction has been committed
-    }
+    const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
+    transactionFlags = getTransactionFlags(mask);
+    handleTransactionLocked(transactionFlags);
 
-    /*
-     * Clean-up all layers that went away
-     * (do this without the lock held)
-     */
-    const size_t count = ditchedLayers.size();
-    for (size_t i=0 ; i<count ; i++) {
-        if (ditchedLayers[i] != 0) {
-            //LOGD("ditching layer %p", ditchedLayers[i].get());
-            ditchedLayers[i]->ditch();
-        }
-    }
+    mLastTransactionTime = systemTime() - now;
+    mDebugInTransaction = 0;
+    // here the transaction has been committed
 }
 
-void SurfaceFlinger::handleTransactionLocked(
-        uint32_t transactionFlags, Vector< sp<LayerBase> >& ditchedLayers)
+void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
 {
     const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
     const size_t count = currentLayers.size();
@@ -569,7 +561,6 @@
                 const sp<LayerBase>& layer(previousLayers[i]);
                 if (currentLayers.indexOf( layer ) < 0) {
                     // this layer is not visible anymore
-                    ditchedLayers.add(layer);
                     mDirtyRegionRemovedLayer.orSelf(layer->visibleRegionScreen);
                 }
             }
@@ -579,6 +570,31 @@
     commitTransaction();
 }
 
+void SurfaceFlinger::destroyLayer(LayerBase const* layer)
+{
+    Mutex::Autolock _l(mDestroyedLayerLock);
+    mDestroyedLayers.add(layer);
+    signalEvent();
+}
+
+void SurfaceFlinger::handleDestroyLayers()
+{
+    Vector<LayerBase const *> destroyedLayers;
+
+    { // scope for the lock
+        Mutex::Autolock _l(mDestroyedLayerLock);
+        destroyedLayers = mDestroyedLayers;
+        mDestroyedLayers.clear();
+    }
+
+    // call destructors without a lock held
+    const size_t count = destroyedLayers.size();
+    for (size_t i=0 ; i<count ; i++) {
+        //LOGD("destroying %s", destroyedLayers[i]->getName().string());
+        delete destroyedLayers[i];
+    }
+}
+
 sp<FreezeLock> SurfaceFlinger::getFreezeLock() const
 {
     return new FreezeLock(const_cast<SurfaceFlinger *>(this));
@@ -1030,15 +1046,15 @@
 ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
         const sp<LayerBaseClient>& lbc)
 {
-    Mutex::Autolock _l(mStateLock);
-
     // attach this layer to the client
-    ssize_t name = client->attachLayer(lbc);
+    size_t name = client->attachLayer(lbc);
+
+    Mutex::Autolock _l(mStateLock);
 
     // add this layer to the current state list
     addLayer_l(lbc);
 
-    return name;
+    return ssize_t(name);
 }
 
 status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
@@ -1066,12 +1082,8 @@
 
 status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
 {
-    // First add the layer to the purgatory list, which makes sure it won't
-    // go away, then remove it from the main list (through a transaction).
+    // remove the layer from the main list (through a transaction).
     ssize_t err = removeLayer_l(layerBase);
-    if (err >= 0) {
-        mLayerPurgatory.add(layerBase);
-    }
 
     layerBase->onRemoved();
 
@@ -1089,6 +1101,11 @@
     return NO_ERROR;
 }
 
+uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags)
+{
+    return android_atomic_release_load(&mTransactionFlags);
+}
+
 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
 {
     return android_atomic_and(~flags, &mTransactionFlags) & flags;
@@ -1318,51 +1335,18 @@
     return err;
 }
 
-status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer)
+status_t SurfaceFlinger::destroySurface(const wp<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);
-            if (err == NAME_NOT_FOUND) {
-                // The surface wasn't in the current list, which means it was
-                // removed already, which means it is in the purgatory,
-                // and need to be removed from there.
-                // This needs to happen from the main thread since its dtor
-                // must run from there (b/c of OpenGL ES). Additionally, we
-                // can't really acquire our internal lock from
-                // destroySurface() -- see postMessage() below.
-                ssize_t idx = flinger->mLayerPurgatory.remove(l);
-                LOGE_IF(idx < 0,
-                        "layer=%p is not in the purgatory list", l.get());
-            }
-
-            LOGE_IF(err<0 && err != NAME_NOT_FOUND,
-                    "error removing layer=%p (%s)", l.get(), strerror(-err));
-            return true;
-        }
-    };
-
-    postMessageAsync( new MessageDestroySurface(this, layer) );
-    return NO_ERROR;
+    status_t err = NO_ERROR;
+    sp<LayerBaseClient> l(layer.promote());
+    if (l != NULL) {
+        Mutex::Autolock _l(mStateLock);
+        err = removeLayer_l(l);
+        LOGE_IF(err<0 && err != NAME_NOT_FOUND,
+                "error removing layer=%p (%s)", l.get(), strerror(-err));
+    }
+    return err;
 }
 
 status_t SurfaceFlinger::setClientState(
@@ -1470,13 +1454,8 @@
             result.append(buffer);
         }
 
-        /*
-         * Dump the visible layer list
-         */
         const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
         const size_t count = currentLayers.size();
-        snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count);
-        result.append(buffer);
         for (size_t i=0 ; i<count ; i++) {
             const sp<LayerBase>& layer(currentLayers[i]);
             layer->dump(result, buffer, SIZE);
@@ -1486,24 +1465,6 @@
             layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
         }
 
-        /*
-         * Dump the layers in the purgatory
-         */
-
-        const size_t purgatorySize =  mLayerPurgatory.size();
-        snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize);
-        result.append(buffer);
-        for (size_t i=0 ; i<purgatorySize ; i++) {
-            const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
-            layer->shortDump(result, buffer, SIZE);
-        }
-
-        /*
-         * Dump SurfaceFlinger global state
-         */
-
-        snprintf(buffer, SIZE, "SurfaceFlinger global state\n");
-        result.append(buffer);
         mWormholeRegion.dump(result, "WormholeRegion");
         const DisplayHardware& hw(graphicPlane(0).displayHardware());
         snprintf(buffer, SIZE,
@@ -1529,9 +1490,6 @@
             result.append(buffer);
         }
 
-        /*
-         * Dump gralloc state
-         */
         const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
         alloc.dump(result);
 
@@ -2296,15 +2254,17 @@
     return NO_ERROR;
 }
 
-ssize_t Client::attachLayer(const sp<LayerBaseClient>& layer)
+size_t Client::attachLayer(const sp<LayerBaseClient>& layer)
 {
-    int32_t name = android_atomic_inc(&mNameGenerator);
+    Mutex::Autolock _l(mLock);
+    size_t name = mNameGenerator++;
     mLayers.add(name, layer);
     return name;
 }
 
 void Client::detachLayer(const LayerBaseClient* layer)
 {
+    Mutex::Autolock _l(mLock);
     // we do a linear search here, because this doesn't happen often
     const size_t count = mLayers.size();
     for (size_t i=0 ; i<count ; i++) {
@@ -2314,9 +2274,11 @@
         }
     }
 }
-sp<LayerBaseClient> Client::getLayerUser(int32_t i) const {
+sp<LayerBaseClient> Client::getLayerUser(int32_t i) const
+{
+    Mutex::Autolock _l(mLock);
     sp<LayerBaseClient> lbc;
-    const wp<LayerBaseClient>& layer(mLayers.valueFor(i));
+    wp<LayerBaseClient> layer(mLayers.valueFor(i));
     if (layer != 0) {
         lbc = layer.promote();
         LOGE_IF(lbc==0, "getLayerUser(name=%d) is dead", int(i));
@@ -2427,7 +2389,7 @@
             }
             break;
         }
-        if (++name > 31)
+        if (++name >= SharedBufferStack::NUM_LAYERS_MAX)
             name = NO_MEMORY;
     } while(name >= 0);
 
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index a023347..9fa98cf 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -66,7 +66,7 @@
     status_t initCheck() const;
 
     // protected by SurfaceFlinger::mStateLock
-    ssize_t attachLayer(const sp<LayerBaseClient>& layer);
+    size_t attachLayer(const sp<LayerBaseClient>& layer);
     void detachLayer(const LayerBaseClient* layer);
     sp<LayerBaseClient> getLayerUser(int32_t i) const;
 
@@ -82,9 +82,15 @@
     virtual status_t destroySurface(SurfaceID surfaceId);
     virtual status_t setState(int32_t count, const layer_state_t* states);
 
-    DefaultKeyedVector< size_t, wp<LayerBaseClient> > mLayers;
+    // constant
     sp<SurfaceFlinger> mFlinger;
-    int32_t mNameGenerator;
+
+    // protected by mLock
+    DefaultKeyedVector< size_t, wp<LayerBaseClient> > mLayers;
+    size_t mNameGenerator;
+
+    // thread-safe
+    mutable Mutex mLock;
 };
 
 class UserClient : public BnSurfaceComposerClient
@@ -212,6 +218,7 @@
     status_t removeLayer(const sp<LayerBase>& layer);
     status_t addLayer(const sp<LayerBase>& layer);
     status_t invalidateLayerVisibility(const sp<LayerBase>& layer);
+    void destroyLayer(LayerBase const* layer);
 
     sp<Layer> getLayer(const sp<ISurface>& sur) const;
 
@@ -249,7 +256,7 @@
             uint32_t w, uint32_t h, uint32_t flags);
 
     status_t removeSurface(const sp<Client>& client, SurfaceID sid);
-    status_t destroySurface(const sp<LayerBaseClient>& layer);
+    status_t destroySurface(const wp<LayerBaseClient>& layer);
     status_t setClientState(const sp<Client>& client,
             int32_t count, const layer_state_t* states);
 
@@ -294,9 +301,8 @@
 private:
             void        handleConsoleEvents();
             void        handleTransaction(uint32_t transactionFlags);
-            void        handleTransactionLocked(
-                            uint32_t transactionFlags, 
-                            Vector< sp<LayerBase> >& ditchedLayers);
+            void        handleTransactionLocked(uint32_t transactionFlags);
+            void        handleDestroyLayers();
 
             void        computeVisibleRegions(
                             LayerVector& currentLayers,
@@ -319,6 +325,7 @@
             status_t    purgatorizeLayer_l(const sp<LayerBase>& layer);
 
             uint32_t    getTransactionFlags(uint32_t flags);
+            uint32_t    peekTransactionFlags(uint32_t flags);
             uint32_t    setTransactionFlags(uint32_t flags);
             void        commitTransaction();
 
@@ -370,7 +377,6 @@
     volatile    int32_t                 mTransactionFlags;
     volatile    int32_t                 mTransactionCount;
                 Condition               mTransactionCV;
-                SortedVector< sp<LayerBase> > mLayerPurgatory;
                 bool                    mResizeTransationPending;
 
                 // protected by mStateLock (but we could use another lock)
@@ -416,6 +422,11 @@
                 // these are thread safe
     mutable     Barrier                     mReadyToRunBarrier;
 
+
+                // protected by mDestroyedLayerLock;
+    mutable     Mutex                       mDestroyedLayerLock;
+                Vector<LayerBase const *>   mDestroyedLayers;
+
                 // atomic variables
                 enum {
                     eConsoleReleased = 1,
diff --git a/services/surfaceflinger/TextureManager.cpp b/services/surfaceflinger/TextureManager.cpp
index c9a15f5..9e24f90 100644
--- a/services/surfaceflinger/TextureManager.cpp
+++ b/services/surfaceflinger/TextureManager.cpp
@@ -186,7 +186,7 @@
     if (texture->name == -1UL) {
         status_t err = initTexture(texture);
         LOGE_IF(err, "loadTexture failed in initTexture (%s)", strerror(err));
-        return err;
+        if (err != NO_ERROR) return err;
     }
 
     if (texture->target != Texture::TEXTURE_2D)
diff --git a/telephony/java/android/telephony/JapanesePhoneNumberFormatter.java b/telephony/java/android/telephony/JapanesePhoneNumberFormatter.java
index 6390d8e..f5e53ef 100644
--- a/telephony/java/android/telephony/JapanesePhoneNumberFormatter.java
+++ b/telephony/java/android/telephony/JapanesePhoneNumberFormatter.java
@@ -24,6 +24,7 @@
  *
  * 022-229-1234 0223-23-1234 022-301-9876 015-482-7849 0154-91-3478
  * 01547-5-4534 090-1234-1234 080-0123-6789
+ * 050-0000-0000 060-0000-0000
  * 0800-000-9999 0570-000-000 0276-00-0000
  *
  * As you can see, there is no straight-forward rule here.
@@ -31,7 +32,7 @@
  */
 /* package */ class JapanesePhoneNumberFormatter {
     private static short FORMAT_MAP[] = {
-    -100, 10, 220, -15, 410, 530, -15, 670, 780, 1060,
+    -100, 10, 220, -15, 410, 530, 1200, 670, 780, 1060,
     -100, -25, 20, 40, 70, 100, 150, 190, 200, 210,
     -36, -100, -100, -35, -35, -35, 30, -100, -100, -100,
     -35, -35, -35, -35, -35, -35, -35, -45, -35, -35,
@@ -84,7 +85,7 @@
     -35, -25, -25, -25, -25, -25, -25, -25, -25, -25,
     -25, -25, -25, -35, -35, -35, -25, -25, -25, 520,
     -100, -100, -45, -100, -45, -100, -45, -100, -45, -100,
-    -25, -100, -25, 540, 580, 590, 600, 610, 630, 640,
+    -26, -100, -25, 540, 580, 590, 600, 610, 630, 640,
     -25, -35, -35, -35, -25, -25, -35, -35, -35, 550,
     -35, -35, -25, -25, -25, -25, 560, 570, -25, -35,
     -35, -35, -35, -35, -25, -25, -25, -25, -25, -25,
@@ -150,7 +151,8 @@
     -35, 1170, -25, -35, 1180, -35, 1190, -35, -25, -25,
     -100, -100, -45, -45, -100, -100, -100, -100, -100, -100,
     -25, -35, -35, -35, -35, -35, -35, -25, -25, -35,
-    -35, -35, -35, -35, -35, -35, -35, -35, -35, -45};
+    -35, -35, -35, -35, -35, -35, -35, -35, -35, -45,
+    -26, -15, -15, -15, -15, -15, -15, -15, -15, -15};
 
     public static void format(Editable text) {
         // Here, "root" means the position of "'":
diff --git a/telephony/java/android/telephony/SmsCbConstants.java b/telephony/java/android/telephony/SmsCbConstants.java
new file mode 100644
index 0000000..a1b4adf
--- /dev/null
+++ b/telephony/java/android/telephony/SmsCbConstants.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.telephony;
+
+/**
+ * Constants used in SMS Cell Broadcast messages.
+ *
+ * {@hide}
+ */
+public interface SmsCbConstants {
+    /** Start of PWS Message Identifier range (includes ETWS and CMAS). */
+    public static final int MESSAGE_ID_PWS_FIRST_IDENTIFIER = 0x1100;
+
+    /** Bitmask for messages of ETWS type (including future extensions). */
+    public static final int MESSAGE_ID_ETWS_TYPE_MASK       = 0xFFF8;
+
+    /** Value for messages of ETWS type after applying {@link #MESSAGE_ID_ETWS_TYPE_MASK}. */
+    public static final int MESSAGE_ID_ETWS_TYPE            = 0x1100;
+
+    /** ETWS Message Identifier for earthquake warning message. */
+    public static final int MESSAGE_ID_ETWS_EARTHQUAKE_WARNING      = 0x1100;
+
+    /** ETWS Message Identifier for tsunami warning message. */
+    public static final int MESSAGE_ID_ETWS_TSUNAMI_WARNING         = 0x1101;
+
+    /** ETWS Message Identifier for earthquake and tsunami combined warning message. */
+    public static final int MESSAGE_ID_ETWS_EARTHQUAKE_AND_TSUNAMI_WARNING  = 0x1102;
+
+    /** ETWS Message Identifier for test message. */
+    public static final int MESSAGE_ID_ETWS_TEST_MESSAGE            = 0x1103;
+
+    /** ETWS Message Identifier for messages related to other emergency types. */
+    public static final int MESSAGE_ID_ETWS_OTHER_EMERGENCY_TYPE    = 0x1104;
+
+    /** Start of CMAS Message Identifier range. */
+    public static final int MESSAGE_ID_CMAS_FIRST_IDENTIFIER                = 0x1112;
+
+    /** CMAS Message Identifier for Presidential Level alerts. */
+    public static final int MESSAGE_ID_CMAS_ALERT_PRESIDENTIAL_LEVEL        = 0x1112;
+
+    /** CMAS Message Identifier for Extreme alerts, Urgency=Immediate, Certainty=Observed. */
+    public static final int MESSAGE_ID_CMAS_ALERT_EXTREME_IMMEDIATE_OBSERVED = 0x1113;
+
+    /** CMAS Message Identifier for Extreme alerts, Urgency=Immediate, Certainty=Likely. */
+    public static final int MESSAGE_ID_CMAS_ALERT_EXTREME_IMMEDIATE_LIKELY  = 0x1114;
+
+    /** CMAS Message Identifier for Extreme alerts, Urgency=Expected, Certainty=Observed. */
+    public static final int MESSAGE_ID_CMAS_ALERT_EXTREME_EXPECTED_OBSERVED = 0x1115;
+
+    /** CMAS Message Identifier for Extreme alerts, Urgency=Expected, Certainty=Likely. */
+    public static final int MESSAGE_ID_CMAS_ALERT_EXTREME_EXPECTED_LIKELY   = 0x1116;
+
+    /** CMAS Message Identifier for Severe alerts, Urgency=Immediate, Certainty=Observed. */
+    public static final int MESSAGE_ID_CMAS_ALERT_SEVERE_IMMEDIATE_OBSERVED = 0x1117;
+
+    /** CMAS Message Identifier for Severe alerts, Urgency=Immediate, Certainty=Likely. */
+    public static final int MESSAGE_ID_CMAS_ALERT_SEVERE_IMMEDIATE_LIKELY   = 0x1118;
+
+    /** CMAS Message Identifier for Severe alerts, Urgency=Expected, Certainty=Observed. */
+    public static final int MESSAGE_ID_CMAS_ALERT_SEVERE_EXPECTED_OBSERVED  = 0x1119;
+
+    /** CMAS Message Identifier for Severe alerts, Urgency=Expected, Certainty=Likely. */
+    public static final int MESSAGE_ID_CMAS_ALERT_SEVERE_EXPECTED_LIKELY    = 0x111A;
+
+    /** CMAS Message Identifier for Child Abduction Emergency (Amber Alert). */
+    public static final int MESSAGE_ID_CMAS_ALERT_CHILD_ABDUCTION_EMERGENCY = 0x111B;
+
+    /** CMAS Message Identifier for the Required Monthly Test. */
+    public static final int MESSAGE_ID_CMAS_ALERT_REQUIRED_MONTHLY_TEST     = 0x111C;
+
+    /** CMAS Message Identifier for CMAS Exercise. */
+    public static final int MESSAGE_ID_CMAS_ALERT_EXERCISE                  = 0x111D;
+
+    /** CMAS Message Identifier for operator defined use. */
+    public static final int MESSAGE_ID_CMAS_ALERT_OPERATOR_DEFINED_USE      = 0x111E;
+
+    /** End of CMAS Message Identifier range (including future extensions). */
+    public static final int MESSAGE_ID_CMAS_LAST_IDENTIFIER                 = 0x112F;
+
+    /** End of PWS Message Identifier range (includes ETWS, CMAS, and future extensions). */
+    public static final int MESSAGE_ID_PWS_LAST_IDENTIFIER                  = 0x18FF;
+
+    /** ETWS message code flag to activate the popup display. */
+    public static final int MESSAGE_CODE_ETWS_ACTIVATE_POPUP                = 0x100;
+
+    /** ETWS message code flag to activate the emergency user alert. */
+    public static final int MESSAGE_CODE_ETWS_EMERGENCY_USER_ALERT          = 0x200;
+
+    /** ETWS warning type value for earthquake. */
+    public static final int ETWS_WARNING_TYPE_EARTHQUAKE                    = 0x00;
+
+    /** ETWS warning type value for tsunami. */
+    public static final int ETWS_WARNING_TYPE_TSUNAMI                       = 0x01;
+
+    /** ETWS warning type value for earthquake and tsunami. */
+    public static final int ETWS_WARNING_TYPE_EARTHQUAKE_AND_TSUNAMI        = 0x02;
+
+    /** ETWS warning type value for test broadcast. */
+    public static final int ETWS_WARNING_TYPE_TEST                          = 0x03;
+
+    /** ETWS warning type value for other notifications. */
+    public static final int ETWS_WARNING_TYPE_OTHER                         = 0x04;
+}
diff --git a/telephony/java/android/telephony/SmsCbMessage.java b/telephony/java/android/telephony/SmsCbMessage.java
index 3543275..383e0f9 100644
--- a/telephony/java/android/telephony/SmsCbMessage.java
+++ b/telephony/java/android/telephony/SmsCbMessage.java
@@ -16,7 +16,11 @@
 
 package android.telephony;
 
+import android.text.format.Time;
+import android.util.Log;
+
 import com.android.internal.telephony.GsmAlphabet;
+import com.android.internal.telephony.IccUtils;
 import com.android.internal.telephony.gsm.SmsCbHeader;
 
 import java.io.UnsupportedEncodingException;
@@ -58,10 +62,13 @@
         try {
             return new SmsCbMessage(pdu);
         } catch (IllegalArgumentException e) {
+            Log.w(LOG_TAG, "Failed parsing SMS-CB pdu", e);
             return null;
         }
     }
 
+    private static final String LOG_TAG = "SMSCB";
+
     /**
      * Languages in the 0000xxxx DCS group as defined in 3GPP TS 23.038, section 5.
      */
@@ -80,15 +87,34 @@
 
     private static final char CARRIAGE_RETURN = 0x0d;
 
+    private static final int PDU_BODY_PAGE_LENGTH = 82;
+
     private SmsCbHeader mHeader;
 
     private String mLanguage;
 
     private String mBody;
 
+    /** Timestamp of ETWS primary notification with security. */
+    private long mPrimaryNotificationTimestamp;
+
+    /** 43 byte digital signature of ETWS primary notification with security. */
+    private byte[] mPrimaryNotificationDigitalSignature;
+
     private SmsCbMessage(byte[] pdu) throws IllegalArgumentException {
         mHeader = new SmsCbHeader(pdu);
-        parseBody(pdu);
+        if (mHeader.format == SmsCbHeader.FORMAT_ETWS_PRIMARY) {
+            mBody = "ETWS";
+            // ETWS primary notification with security is 56 octets in length
+            if (pdu.length >= SmsCbHeader.PDU_LENGTH_ETWS) {
+                mPrimaryNotificationTimestamp = getTimestampMillis(pdu);
+                mPrimaryNotificationDigitalSignature = new byte[43];
+                // digital signature starts after 6 byte header and 7 byte timestamp
+                System.arraycopy(pdu, 13, mPrimaryNotificationDigitalSignature, 0, 43);
+            }
+        } else {
+            parseBody(pdu);
+        }
     }
 
     /**
@@ -149,6 +175,62 @@
         return mHeader.updateNumber;
     }
 
+    /**
+     * Get the format of this message.
+     * @return {@link SmsCbHeader#FORMAT_GSM}, {@link SmsCbHeader#FORMAT_UMTS}, or
+     *         {@link SmsCbHeader#FORMAT_ETWS_PRIMARY}
+     */
+    public int getMessageFormat() {
+        return mHeader.format;
+    }
+
+    /**
+     * For ETWS primary notifications, return the emergency user alert flag.
+     * @return true to notify terminal to activate emergency user alert; false otherwise
+     */
+    public boolean getEtwsEmergencyUserAlert() {
+        return mHeader.etwsEmergencyUserAlert;
+    }
+
+    /**
+     * For ETWS primary notifications, return the popup flag.
+     * @return true to notify terminal to activate display popup; false otherwise
+     */
+    public boolean getEtwsPopup() {
+        return mHeader.etwsPopup;
+    }
+
+    /**
+     * For ETWS primary notifications, return the warning type.
+     * @return a value such as {@link SmsCbConstants#ETWS_WARNING_TYPE_EARTHQUAKE}
+     */
+    public int getEtwsWarningType() {
+        return mHeader.etwsWarningType;
+    }
+
+    /**
+     * For ETWS primary notifications, return the Warning-Security-Information timestamp.
+     * @return a timestamp in System.currentTimeMillis() format.
+     */
+    public long getEtwsSecurityTimestamp() {
+        return mPrimaryNotificationTimestamp;
+    }
+
+    /**
+     * For ETWS primary notifications, return the 43 byte digital signature.
+     * @return a byte array containing a copy of the digital signature
+     */
+    public byte[] getEtwsSecuritySignature() {
+        return mPrimaryNotificationDigitalSignature.clone();
+    }
+
+    /**
+     * Parse and unpack the body text according to the encoding in the DCS.
+     * After completing successfully this method will have assigned the body
+     * text into mBody, and optionally the language code into mLanguage
+     *
+     * @param pdu The pdu
+     */
     private void parseBody(byte[] pdu) {
         int encoding;
         boolean hasLanguageIndicator = false;
@@ -221,28 +303,81 @@
                 break;
         }
 
+        if (mHeader.format == SmsCbHeader.FORMAT_UMTS) {
+            // Payload may contain multiple pages
+            int nrPages = pdu[SmsCbHeader.PDU_HEADER_LENGTH];
+
+            if (pdu.length < SmsCbHeader.PDU_HEADER_LENGTH + 1 + (PDU_BODY_PAGE_LENGTH + 1)
+                    * nrPages) {
+                throw new IllegalArgumentException("Pdu length " + pdu.length + " does not match "
+                        + nrPages + " pages");
+            }
+
+            StringBuilder sb = new StringBuilder();
+
+            for (int i = 0; i < nrPages; i++) {
+                // Each page is 82 bytes followed by a length octet indicating
+                // the number of useful octets within those 82
+                int offset = SmsCbHeader.PDU_HEADER_LENGTH + 1 + (PDU_BODY_PAGE_LENGTH + 1) * i;
+                int length = pdu[offset + PDU_BODY_PAGE_LENGTH];
+
+                if (length > PDU_BODY_PAGE_LENGTH) {
+                    throw new IllegalArgumentException("Page length " + length
+                            + " exceeds maximum value " + PDU_BODY_PAGE_LENGTH);
+                }
+
+                sb.append(unpackBody(pdu, encoding, offset, length, hasLanguageIndicator));
+            }
+            mBody = sb.toString();
+        } else {
+            // Payload is one single page
+            int offset = SmsCbHeader.PDU_HEADER_LENGTH;
+            int length = pdu.length - offset;
+
+            mBody = unpackBody(pdu, encoding, offset, length, hasLanguageIndicator);
+        }
+    }
+
+    /**
+     * Unpack body text from the pdu using the given encoding, position and
+     * length within the pdu
+     *
+     * @param pdu The pdu
+     * @param encoding The encoding, as derived from the DCS
+     * @param offset Position of the first byte to unpack
+     * @param length Number of bytes to unpack
+     * @param hasLanguageIndicator true if the body text is preceded by a
+     *            language indicator. If so, this method will as a side-effect
+     *            assign the extracted language code into mLanguage
+     * @return Body text
+     */
+    private String unpackBody(byte[] pdu, int encoding, int offset, int length,
+            boolean hasLanguageIndicator) {
+        String body = null;
+
         switch (encoding) {
             case SmsMessage.ENCODING_7BIT:
-                mBody = GsmAlphabet.gsm7BitPackedToString(pdu, SmsCbHeader.PDU_HEADER_LENGTH,
-                        (pdu.length - SmsCbHeader.PDU_HEADER_LENGTH) * 8 / 7);
+                body = GsmAlphabet.gsm7BitPackedToString(pdu, offset, length * 8 / 7);
 
-                if (hasLanguageIndicator && mBody != null && mBody.length() > 2) {
-                    mLanguage = mBody.substring(0, 2);
-                    mBody = mBody.substring(3);
+                if (hasLanguageIndicator && body != null && body.length() > 2) {
+                    // Language is two GSM characters followed by a CR.
+                    // The actual body text is offset by 3 characters.
+                    mLanguage = body.substring(0, 2);
+                    body = body.substring(3);
                 }
                 break;
 
             case SmsMessage.ENCODING_16BIT:
-                int offset = SmsCbHeader.PDU_HEADER_LENGTH;
-
-                if (hasLanguageIndicator && pdu.length >= SmsCbHeader.PDU_HEADER_LENGTH + 2) {
-                    mLanguage = GsmAlphabet.gsm7BitPackedToString(pdu,
-                            SmsCbHeader.PDU_HEADER_LENGTH, 2);
+                if (hasLanguageIndicator && pdu.length >= offset + 2) {
+                    // Language is two GSM characters.
+                    // The actual body text is offset by 2 bytes.
+                    mLanguage = GsmAlphabet.gsm7BitPackedToString(pdu, offset, 2);
                     offset += 2;
+                    length -= 2;
                 }
 
                 try {
-                    mBody = new String(pdu, offset, (pdu.length & 0xfffe) - offset, "utf-16");
+                    body = new String(pdu, offset, (length & 0xfffe), "utf-16");
                 } catch (UnsupportedEncodingException e) {
                     // Eeeek
                 }
@@ -252,16 +387,73 @@
                 break;
         }
 
-        if (mBody != null) {
+        if (body != null) {
             // Remove trailing carriage return
-            for (int i = mBody.length() - 1; i >= 0; i--) {
-                if (mBody.charAt(i) != CARRIAGE_RETURN) {
-                    mBody = mBody.substring(0, i + 1);
+            for (int i = body.length() - 1; i >= 0; i--) {
+                if (body.charAt(i) != CARRIAGE_RETURN) {
+                    body = body.substring(0, i + 1);
                     break;
                 }
             }
         } else {
-            mBody = "";
+            body = "";
         }
+
+        return body;
+    }
+
+    /**
+     * Parses an ETWS primary notification timestamp and returns a currentTimeMillis()-style
+     * timestamp. Copied from com.android.internal.telephony.gsm.SmsMessage.
+     * @param pdu the ETWS primary notification PDU to decode
+     * @return the UTC timestamp from the Warning-Security-Information parameter
+     */
+    private long getTimestampMillis(byte[] pdu) {
+        // Timestamp starts after CB header, in pdu[6]
+        int year = IccUtils.gsmBcdByteToInt(pdu[6]);
+        int month = IccUtils.gsmBcdByteToInt(pdu[7]);
+        int day = IccUtils.gsmBcdByteToInt(pdu[8]);
+        int hour = IccUtils.gsmBcdByteToInt(pdu[9]);
+        int minute = IccUtils.gsmBcdByteToInt(pdu[10]);
+        int second = IccUtils.gsmBcdByteToInt(pdu[11]);
+
+        // For the timezone, the most significant bit of the
+        // least significant nibble is the sign byte
+        // (meaning the max range of this field is 79 quarter-hours,
+        // which is more than enough)
+
+        byte tzByte = pdu[12];
+
+        // Mask out sign bit.
+        int timezoneOffset = IccUtils.gsmBcdByteToInt((byte) (tzByte & (~0x08)));
+
+        timezoneOffset = ((tzByte & 0x08) == 0) ? timezoneOffset : -timezoneOffset;
+
+        Time time = new Time(Time.TIMEZONE_UTC);
+
+        // It's 2006.  Should I really support years < 2000?
+        time.year = year >= 90 ? year + 1900 : year + 2000;
+        time.month = month - 1;
+        time.monthDay = day;
+        time.hour = hour;
+        time.minute = minute;
+        time.second = second;
+
+        // Timezone offset is in quarter hours.
+        return time.toMillis(true) - (timezoneOffset * 15 * 60 * 1000);
+    }
+
+    /**
+     * Append text to the message body. This is used to concatenate multi-page GSM broadcasts.
+     * @param body the text to append to this message
+     */
+    public void appendToBody(String body) {
+        mBody = mBody + body;
+    }
+
+    @Override
+    public String toString() {
+        return "SmsCbMessage{" + mHeader.toString() + ", language=" + mLanguage +
+                ", body=\"" + mBody + "\"}";
     }
 }
diff --git a/telephony/java/android/telephony/SmsManager.java b/telephony/java/android/telephony/SmsManager.java
index 0ecd854..480186c 100644
--- a/telephony/java/android/telephony/SmsManager.java
+++ b/telephony/java/android/telephony/SmsManager.java
@@ -21,7 +21,6 @@
 import android.os.ServiceManager;
 import android.text.TextUtils;
 
-import com.android.internal.telephony.EncodeException;
 import com.android.internal.telephony.ISms;
 import com.android.internal.telephony.IccConstants;
 import com.android.internal.telephony.SmsRawData;
@@ -348,7 +347,7 @@
      * message identifier. Note that if two different clients enable the same
      * message identifier, they must both disable it for the device to stop
      * receiving those messages. All received messages will be broadcast in an
-     * intent with the action "android.provider.telephony.SMS_CB_RECEIVED".
+     * intent with the action "android.provider.Telephony.SMS_CB_RECEIVED".
      * Note: This call is blocking, callers may want to avoid calling it from
      * the main thread of an application.
      *
@@ -404,6 +403,68 @@
     }
 
     /**
+     * Enable reception of cell broadcast (SMS-CB) messages with the given
+     * message identifier range. Note that if two different clients enable the same
+     * message identifier, they must both disable it for the device to stop
+     * receiving those messages. All received messages will be broadcast in an
+     * intent with the action "android.provider.Telephony.SMS_CB_RECEIVED".
+     * Note: This call is blocking, callers may want to avoid calling it from
+     * the main thread of an application.
+     *
+     * @param startMessageId first message identifier as specified in TS 23.041
+     * @param endMessageId last message identifier as specified in TS 23.041
+     * @return true if successful, false otherwise
+     * @see #disableCellBroadcastRange(int, int)
+     *
+     * {@hide}
+     */
+    public boolean enableCellBroadcastRange(int startMessageId, int endMessageId) {
+        boolean success = false;
+
+        try {
+            ISms iccISms = ISms.Stub.asInterface(ServiceManager.getService("isms"));
+            if (iccISms != null) {
+                success = iccISms.enableCellBroadcastRange(startMessageId, endMessageId);
+            }
+        } catch (RemoteException ex) {
+            // ignore it
+        }
+
+        return success;
+    }
+
+    /**
+     * Disable reception of cell broadcast (SMS-CB) messages with the given
+     * message identifier range. Note that if two different clients enable the same
+     * message identifier, they must both disable it for the device to stop
+     * receiving those messages.
+     * Note: This call is blocking, callers may want to avoid calling it from
+     * the main thread of an application.
+     *
+     * @param startMessageId first message identifier as specified in TS 23.041
+     * @param endMessageId last message identifier as specified in TS 23.041
+     * @return true if successful, false otherwise
+     *
+     * @see #enableCellBroadcastRange(int, int)
+     *
+     * {@hide}
+     */
+    public boolean disableCellBroadcastRange(int startMessageId, int endMessageId) {
+        boolean success = false;
+
+        try {
+            ISms iccISms = ISms.Stub.asInterface(ServiceManager.getService("isms"));
+            if (iccISms != null) {
+                success = iccISms.disableCellBroadcastRange(startMessageId, endMessageId);
+            }
+        } catch (RemoteException ex) {
+            // ignore it
+        }
+
+        return success;
+    }
+
+    /**
      * Create a list of <code>SmsMessage</code>s from a list of RawSmsData
      * records returned by <code>getAllMessagesFromIcc()</code>
      *
diff --git a/telephony/java/android/telephony/SmsMessage.java b/telephony/java/android/telephony/SmsMessage.java
index a284ea5..34ca902 100644
--- a/telephony/java/android/telephony/SmsMessage.java
+++ b/telephony/java/android/telephony/SmsMessage.java
@@ -314,7 +314,8 @@
                     nextPos = pos + Math.min(limit, textLen - pos);
                 } else {
                     // For multi-segment messages, CDMA 7bit equals GSM 7bit encoding (EMS mode).
-                    nextPos = GsmAlphabet.findGsmSeptetLimitIndex(text, pos, limit);
+                    nextPos = GsmAlphabet.findGsmSeptetLimitIndex(text, pos, limit,
+                            ted.languageTable, ted.languageShiftTable);
                 }
             } else {  // Assume unicode.
                 nextPos = pos + Math.min(limit / 2, textLen - pos);
@@ -370,7 +371,8 @@
      */
 
     /**
-     * Get an SMS-SUBMIT PDU for a destination address and a message
+     * Get an SMS-SUBMIT PDU for a destination address and a message.
+     * This method will not attempt to use any GSM national language 7 bit encodings.
      *
      * @param scAddress Service Centre address.  Null means use default.
      * @return a <code>SubmitPdu</code> containing the encoded SC
@@ -397,7 +399,8 @@
     }
 
     /**
-     * Get an SMS-SUBMIT PDU for a destination address and a message
+     * Get an SMS-SUBMIT PDU for a destination address and a message.
+     * This method will not attempt to use any GSM national language 7 bit encodings.
      *
      * @param scAddress Service Centre address.  Null means use default.
      * @return a <code>SubmitPdu</code> containing the encoded SC
@@ -421,7 +424,8 @@
     }
 
     /**
-     * Get an SMS-SUBMIT PDU for a data message to a destination address &amp; port
+     * Get an SMS-SUBMIT PDU for a data message to a destination address &amp; port.
+     * This method will not attempt to use any GSM national language 7 bit encodings.
      *
      * @param scAddress Service Centre address. null == use default
      * @param destinationAddress the address of the destination for the message
diff --git a/telephony/java/android/telephony/gsm/SmsMessage.java b/telephony/java/android/telephony/gsm/SmsMessage.java
index 0c63c37..1b95cd4 100644
--- a/telephony/java/android/telephony/gsm/SmsMessage.java
+++ b/telephony/java/android/telephony/gsm/SmsMessage.java
@@ -297,37 +297,14 @@
      */
     @Deprecated
     public static int[] calculateLength(CharSequence messageBody, boolean use7bitOnly) {
+        SmsMessageBase.TextEncodingDetails ted =
+                com.android.internal.telephony.gsm.SmsMessage
+                        .calculateLength(messageBody, use7bitOnly);
         int ret[] = new int[4];
-
-        try {
-            // Try GSM alphabet
-            int septets = GsmAlphabet.countGsmSeptets(messageBody, !use7bitOnly);
-            ret[1] = septets;
-            if (septets > MAX_USER_DATA_SEPTETS) {
-                ret[0] = (septets + (MAX_USER_DATA_SEPTETS_WITH_HEADER - 1)) /
-                            MAX_USER_DATA_SEPTETS_WITH_HEADER;
-                ret[2] = (ret[0] * MAX_USER_DATA_SEPTETS_WITH_HEADER) - septets;
-            } else {
-                ret[0] = 1;
-                ret[2] = MAX_USER_DATA_SEPTETS - septets;
-            }
-            ret[3] = ENCODING_7BIT;
-        } catch (EncodeException ex) {
-            // fall back to UCS-2
-            int octets = messageBody.length() * 2;
-            ret[1] = messageBody.length();
-            if (octets > MAX_USER_DATA_BYTES) {
-                // 6 is the size of the user data header
-                ret[0] = (octets + (MAX_USER_DATA_BYTES_WITH_HEADER - 1)) /
-                            MAX_USER_DATA_BYTES_WITH_HEADER;
-                ret[2] = ((ret[0] * MAX_USER_DATA_BYTES_WITH_HEADER) - octets) / 2;
-            } else {
-                ret[0] = 1;
-                ret[2] = (MAX_USER_DATA_BYTES - octets)/2;
-            }
-            ret[3] = ENCODING_16BIT;
-        }
-
+        ret[0] = ted.msgCount;
+        ret[1] = ted.codeUnitCount;
+        ret[2] = ted.codeUnitsRemaining;
+        ret[3] = ted.codeUnitSize;
         return ret;
     }
 
diff --git a/telephony/java/com/android/internal/telephony/CommandsInterface.java b/telephony/java/com/android/internal/telephony/CommandsInterface.java
index 56c641b..b8bf8af 100644
--- a/telephony/java/com/android/internal/telephony/CommandsInterface.java
+++ b/telephony/java/com/android/internal/telephony/CommandsInterface.java
@@ -1350,11 +1350,15 @@
      *            the password for APN, or NULL
      * @param authType
      *            the PAP / CHAP auth type. Values is one of SETUP_DATA_AUTH_*
+     * @param protocol
+     *            one of the PDP_type values in TS 27.007 section 10.1.1.
+     *            For example, "IP", "IPV6", "IPV4V6", or "PPP".
      * @param result
      *            Callback message
      */
-    public void setupDataCall(String radioTechnology, String profile, String apn,
-            String user, String password, String authType, Message result);
+    public void setupDataCall(String radioTechnology, String profile,
+            String apn, String user, String password, String authType,
+            String protocol, Message result);
 
     /**
      * Deactivate packet data connection
diff --git a/telephony/java/com/android/internal/telephony/GsmAlphabet.java b/telephony/java/com/android/internal/telephony/GsmAlphabet.java
index 30ee77c..8ea1f8d 100644
--- a/telephony/java/com/android/internal/telephony/GsmAlphabet.java
+++ b/telephony/java/com/android/internal/telephony/GsmAlphabet.java
@@ -16,11 +16,20 @@
 
 package com.android.internal.telephony;
 
-import android.telephony.SmsMessage;
+import android.content.res.Resources;
 import android.util.SparseIntArray;
 
 import android.util.Log;
 
+import com.android.internal.R;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static android.telephony.SmsMessage.ENCODING_7BIT;
+import static android.telephony.SmsMessage.MAX_USER_DATA_SEPTETS;
+import static android.telephony.SmsMessage.MAX_USER_DATA_SEPTETS_WITH_HEADER;
+
 /**
  * This class implements the character set mapping between
  * the GSM SMS 7-bit alphabet specified in TS 23.038 6.2.1
@@ -29,29 +38,53 @@
  * {@hide}
  */
 public class GsmAlphabet {
-    static final String LOG_TAG = "GSM";
+    private static final String TAG = "GSM";
 
-
+    private GsmAlphabet() { }
 
     //***** Constants
 
     /**
      * This escapes extended characters, and when present indicates that the
-     * following character should
-     * be looked up in the "extended" table
+     * following character should be looked up in the "extended" table.
      *
      * gsmToChar(GSM_EXTENDED_ESCAPE) returns 0xffff
      */
-
     public static final byte GSM_EXTENDED_ESCAPE = 0x1B;
 
+    /**
+     * User data header requires one octet for length. Count as one septet, because
+     * all combinations of header elements below will have at least one free bit
+     * when padding to the nearest septet boundary.
+     */
+    private static final int UDH_SEPTET_COST_LENGTH = 1;
 
     /**
-     * char to GSM alphabet char
-     * Returns ' ' in GSM alphabet if there's no possible match
-     * Returns GSM_EXTENDED_ESCAPE if this character is in the extended table
-     * In this case, you must call charToGsmExtended() for the value that
-     * should follow GSM_EXTENDED_ESCAPE in the GSM alphabet string
+     * Using a non-default language locking shift table OR single shift table
+     * requires a user data header of 3 octets, or 4 septets, plus UDH length.
+     */
+    private static final int UDH_SEPTET_COST_ONE_SHIFT_TABLE = 4;
+
+    /**
+     * Using a non-default language locking shift table AND single shift table
+     * requires a user data header of 6 octets, or 7 septets, plus UDH length.
+     */
+    private static final int UDH_SEPTET_COST_TWO_SHIFT_TABLES = 7;
+
+    /**
+     * Multi-part messages require a user data header of 5 octets, or 6 septets,
+     * plus UDH length.
+     */
+    private static final int UDH_SEPTET_COST_CONCATENATED_MESSAGE = 6;
+
+    /**
+     * Converts a char to a GSM 7 bit table index.
+     * Returns ' ' in GSM alphabet if there's no possible match. Returns
+     * GSM_EXTENDED_ESCAPE if this character is in the extended table.
+     * In this case, you must call charToGsmExtended() for the value
+     * that should follow GSM_EXTENDED_ESCAPE in the GSM alphabet string.
+     * @param c the character to convert
+     * @return the GSM 7 bit table index for the specified character
      */
     public static int
     charToGsm(char c) {
@@ -59,34 +92,36 @@
             return charToGsm(c, false);
         } catch (EncodeException ex) {
             // this should never happen
-            return sGsmSpaceChar;
+            return sCharsToGsmTables[0].get(' ', ' ');
         }
     }
 
     /**
-     * char to GSM alphabet char
+     * Converts a char to a GSM 7 bit table index.
+     * Returns GSM_EXTENDED_ESCAPE if this character is in the extended table.
+     * In this case, you must call charToGsmExtended() for the value that
+     * should follow GSM_EXTENDED_ESCAPE in the GSM alphabet string.
+     *
+     * @param c the character to convert
      * @param throwException If true, throws EncodeException on invalid char.
      *   If false, returns GSM alphabet ' ' char.
-     *
-     * Returns GSM_EXTENDED_ESCAPE if this character is in the extended table
-     * In this case, you must call charToGsmExtended() for the value that
-     * should follow GSM_EXTENDED_ESCAPE in the GSM alphabet string
+     * @throws EncodeException encode error when throwException is true
+     * @return the GSM 7 bit table index for the specified character
      */
-
     public static int
     charToGsm(char c, boolean throwException) throws EncodeException {
         int ret;
 
-        ret = charToGsm.get(c, -1);
+        ret = sCharsToGsmTables[0].get(c, -1);
 
         if (ret == -1) {
-            ret = charToGsmExtended.get(c, -1);
+            ret = sCharsToShiftTables[0].get(c, -1);
 
             if (ret == -1) {
                 if (throwException) {
                     throw new EncodeException(c);
                 } else {
-                    return sGsmSpaceChar;
+                    return sCharsToGsmTables[0].get(' ', ' ');
                 }
             } else {
                 return GSM_EXTENDED_ESCAPE;
@@ -94,44 +129,47 @@
         }
 
         return ret;
-
     }
 
-
     /**
-     * char to extended GSM alphabet char
-     *
-     * Extended chars should be escaped with GSM_EXTENDED_ESCAPE
-     *
-     * Returns ' ' in GSM alphabet if there's no possible match
-     *
+     * Converts a char to an extended GSM 7 bit table index.
+     * Extended chars should be escaped with GSM_EXTENDED_ESCAPE.
+     * Returns ' ' in GSM alphabet if there's no possible match.
+     * @param c the character to convert
+     * @return the GSM 7 bit extended table index for the specified character
      */
     public static int
     charToGsmExtended(char c) {
         int ret;
 
-        ret = charToGsmExtended.get(c, -1);
+        ret = sCharsToShiftTables[0].get(c, -1);
 
         if (ret == -1) {
-            return sGsmSpaceChar;
+            return sCharsToGsmTables[0].get(' ', ' ');
         }
 
         return ret;
     }
 
     /**
-     * Converts a character in the GSM alphabet into a char
+     * Converts a character in the GSM alphabet into a char.
      *
-     * if GSM_EXTENDED_ESCAPE is passed, 0xffff is returned. In this case,
+     * If GSM_EXTENDED_ESCAPE is passed, 0xffff is returned. In this case,
      * the following character in the stream should be decoded with
-     * gsmExtendedToChar()
+     * gsmExtendedToChar().
      *
-     * If an unmappable value is passed (one greater than 127), ' ' is returned
+     * If an unmappable value is passed (one greater than 127), ' ' is returned.
+     *
+     * @param gsmChar the GSM 7 bit table index to convert
+     * @return the decoded character
      */
-
     public static char
     gsmToChar(int gsmChar) {
-        return (char)gsmToChar.get(gsmChar, ' ');
+        if (gsmChar >= 0 && gsmChar < 128) {
+            return sLanguageTables[0].charAt(gsmChar);
+        } else {
+            return ' ';
+        }
     }
 
     /**
@@ -141,20 +179,26 @@
      * extension page has yet been defined (see Note 1 in table 6.2.1.1 of
      * TS 23.038 v7.00)
      *
-     * If an unmappable value is passed , ' ' is returned
+     * If an unmappable value is passed, the character from the GSM 7 bit
+     * default table will be used (table 6.2.1.1 of TS 23.038).
+     *
+     * @param gsmChar the GSM 7 bit extended table index to convert
+     * @return the decoded character
      */
-
     public static char
     gsmExtendedToChar(int gsmChar) {
-        int ret;
-
-        ret = gsmExtendedToChar.get(gsmChar, -1);
-
-        if (ret == -1) {
+        if (gsmChar == GSM_EXTENDED_ESCAPE) {
             return ' ';
+        } else if (gsmChar >= 0 && gsmChar < 128) {
+            char c = sLanguageShiftTables[0].charAt(gsmChar);
+            if (c == ' ') {
+                return sLanguageTables[0].charAt(gsmChar);
+            } else {
+                return c;
+            }
+        } else {
+            return ' ';     // out of range
         }
-
-        return (char)ret;
     }
 
     /**
@@ -173,19 +217,24 @@
      * @param data The text string to encode.
      * @param header Optional header (including length byte) that precedes
      * the encoded data, padded to septet boundary.
+     * @param languageTable the 7 bit language table, or 0 for the default GSM alphabet
+     * @param languageShiftTable the 7 bit single shift language table, or 0 for the default
+     *     GSM extension table
      * @return Byte array containing header and encoded data.
+     * @throws EncodeException if String is too large to encode
      */
-    public static byte[] stringToGsm7BitPackedWithHeader(String data, byte[] header)
+    public static byte[] stringToGsm7BitPackedWithHeader(String data, byte[] header,
+            int languageTable, int languageShiftTable)
             throws EncodeException {
-
         if (header == null || header.length == 0) {
-            return stringToGsm7BitPacked(data);
+            return stringToGsm7BitPacked(data, languageTable, languageShiftTable);
         }
 
         int headerBits = (header.length + 1) * 8;
         int headerSeptets = (headerBits + 6) / 7;
 
-        byte[] ret = stringToGsm7BitPacked(data, headerSeptets, true);
+        byte[] ret = stringToGsm7BitPacked(data, headerSeptets, true, languageTable,
+                languageShiftTable);
 
         // Paste in the header
         ret[1] = (byte)header.length;
@@ -205,11 +254,36 @@
      * septets.
      *
      * @param data the data string to encode
+     * @return the encoded string
      * @throws EncodeException if String is too large to encode
      */
     public static byte[] stringToGsm7BitPacked(String data)
             throws EncodeException {
-        return stringToGsm7BitPacked(data, 0, true);
+        return stringToGsm7BitPacked(data, 0, true, 0, 0);
+    }
+
+    /**
+     * Converts a String into a byte array containing
+     * the 7-bit packed GSM Alphabet representation of the string.
+     *
+     * Unencodable chars are encoded as spaces
+     *
+     * Byte 0 in the returned byte array is the count of septets used
+     * The returned byte array is the minimum size required to store
+     * the packed septets. The returned array cannot contain more than 255
+     * septets.
+     *
+     * @param data the data string to encode
+     * @param languageTable the 7 bit language table, or 0 for the default GSM alphabet
+     * @param languageShiftTable the 7 bit single shift language table, or 0 for the default
+     *     GSM extension table
+     * @return the encoded string
+     * @throws EncodeException if String is too large to encode
+     */
+    public static byte[] stringToGsm7BitPacked(String data, int languageTable,
+            int languageShiftTable)
+            throws EncodeException {
+        return stringToGsm7BitPacked(data, 0, true, languageTable, languageShiftTable);
     }
 
     /**
@@ -226,28 +300,48 @@
      *  the character data at the beginning of the array
      * @param throwException If true, throws EncodeException on invalid char.
      *   If false, replaces unencodable char with GSM alphabet space char.
+     * @param languageTable the 7 bit language table, or 0 for the default GSM alphabet
+     * @param languageShiftTable the 7 bit single shift language table, or 0 for the default
+     *     GSM extension table
+     * @return the encoded message
      *
      * @throws EncodeException if String is too large to encode
      */
     public static byte[] stringToGsm7BitPacked(String data, int startingSeptetOffset,
-            boolean throwException) throws EncodeException {
+            boolean throwException, int languageTable, int languageShiftTable)
+            throws EncodeException {
         int dataLen = data.length();
-        int septetCount = countGsmSeptets(data, throwException) + startingSeptetOffset;
+        int septetCount = countGsmSeptetsUsingTables(data, !throwException,
+                languageTable, languageShiftTable);
+        if (septetCount == -1) {
+            throw new EncodeException("countGsmSeptetsUsingTables(): unencodable char");
+        }
+        septetCount += startingSeptetOffset;
         if (septetCount > 255) {
             throw new EncodeException("Payload cannot exceed 255 septets");
         }
         int byteCount = ((septetCount * 7) + 7) / 8;
         byte[] ret = new byte[byteCount + 1];  // Include space for one byte length prefix.
+        SparseIntArray charToLanguageTable = sCharsToGsmTables[languageTable];
+        SparseIntArray charToShiftTable = sCharsToShiftTables[languageShiftTable];
         for (int i = 0, septets = startingSeptetOffset, bitOffset = startingSeptetOffset * 7;
                  i < dataLen && septets < septetCount;
                  i++, bitOffset += 7) {
             char c = data.charAt(i);
-            int v = GsmAlphabet.charToGsm(c, throwException);
-            if (v == GSM_EXTENDED_ESCAPE) {
-                v = GsmAlphabet.charToGsmExtended(c);  // Lookup the extended char.
-                packSmsChar(ret, bitOffset, GSM_EXTENDED_ESCAPE);
-                bitOffset += 7;
-                septets++;
+            int v = charToLanguageTable.get(c, -1);
+            if (v == -1) {
+                v = charToShiftTable.get(c, -1);  // Lookup the extended char.
+                if (v == -1) {
+                    if (throwException) {
+                        throw new EncodeException("stringToGsm7BitPacked(): unencodable char");
+                    } else {
+                        v = charToLanguageTable.get(' ', ' ');   // should return ASCII space
+                    }
+                } else {
+                    packSmsChar(ret, bitOffset, GSM_EXTENDED_ESCAPE);
+                    bitOffset += 7;
+                    septets++;
+                }
             }
             packSmsChar(ret, bitOffset, v);
             septets++;
@@ -259,8 +353,10 @@
     /**
      * Pack a 7-bit char into its appropriate place in a byte array
      *
+     * @param packedChars the destination byte array
      * @param bitOffset the bit offset that the septet should be packed at
      *                  (septet index * 7)
+     * @param value the 7-bit character to store
      */
     private static void
     packSmsChar(byte[] packedChars, int bitOffset, int value) {
@@ -287,7 +383,7 @@
      */
     public static String gsm7BitPackedToString(byte[] pdu, int offset,
             int lengthSeptets) {
-        return gsm7BitPackedToString(pdu, offset, lengthSeptets, 0);
+        return gsm7BitPackedToString(pdu, offset, lengthSeptets, 0, 0, 0);
     }
 
     /**
@@ -301,15 +397,37 @@
      * @param lengthSeptets string length in septets, not bytes
      * @param numPaddingBits the number of padding bits before the start of the
      *  string in the first byte
+     * @param languageTable the 7 bit language table, or 0 for the default GSM alphabet
+     * @param shiftTable the 7 bit single shift language table, or 0 for the default
+     *     GSM extension table
      * @return String representation or null on decoding exception
      */
     public static String gsm7BitPackedToString(byte[] pdu, int offset,
-            int lengthSeptets, int numPaddingBits) {
+            int lengthSeptets, int numPaddingBits, int languageTable, int shiftTable) {
         StringBuilder ret = new StringBuilder(lengthSeptets);
-        boolean prevCharWasEscape;
+
+        if (languageTable < 0 || languageTable > sLanguageTables.length) {
+            Log.w(TAG, "unknown language table " + languageTable + ", using default");
+            languageTable = 0;
+        }
+        if (shiftTable < 0 || shiftTable > sLanguageShiftTables.length) {
+            Log.w(TAG, "unknown single shift table " + shiftTable + ", using default");
+            shiftTable = 0;
+        }
 
         try {
-            prevCharWasEscape = false;
+            boolean prevCharWasEscape = false;
+            String languageTableToChar = sLanguageTables[languageTable];
+            String shiftTableToChar = sLanguageShiftTables[shiftTable];
+
+            if (languageTableToChar.isEmpty()) {
+                Log.w(TAG, "no language table for code " + languageTable + ", using default");
+                languageTableToChar = sLanguageTables[0];
+            }
+            if (shiftTableToChar.isEmpty()) {
+                Log.w(TAG, "no single shift table for code " + shiftTable + ", using default");
+                shiftTableToChar = sLanguageShiftTables[0];
+            }
 
             for (int i = 0 ; i < lengthSeptets ; i++) {
                 int bitOffset = (7 * i) + numPaddingBits;
@@ -320,7 +438,7 @@
 
                 gsmVal = (0x7f & (pdu[offset + byteOffset] >> shift));
 
-                // if it crosses a byte boundry
+                // if it crosses a byte boundary
                 if (shift > 1) {
                     // set msb bits to 0
                     gsmVal &= 0x7f >> (shift - 1);
@@ -329,16 +447,25 @@
                 }
 
                 if (prevCharWasEscape) {
-                    ret.append(GsmAlphabet.gsmExtendedToChar(gsmVal));
+                    if (gsmVal == GSM_EXTENDED_ESCAPE) {
+                        ret.append(' ');    // display ' ' for reserved double escape sequence
+                    } else {
+                        char c = shiftTableToChar.charAt(gsmVal);
+                        if (c == ' ') {
+                            ret.append(languageTableToChar.charAt(gsmVal));
+                        } else {
+                            ret.append(c);
+                        }
+                    }
                     prevCharWasEscape = false;
                 } else if (gsmVal == GSM_EXTENDED_ESCAPE) {
                     prevCharWasEscape = true;
                 } else {
-                    ret.append(GsmAlphabet.gsmToChar(gsmVal));
+                    ret.append(languageTableToChar.charAt(gsmVal));
                 }
             }
         } catch (RuntimeException ex) {
-            Log.e(LOG_TAG, "Error GSM 7 bit packed: ", ex);
+            Log.e(TAG, "Error GSM 7 bit packed: ", ex);
             return null;
         }
 
@@ -352,13 +479,20 @@
      *
      * Field may be padded with trailing 0xff's. The decode stops
      * at the first 0xff encountered.
+     *
+     * @param data the byte array to decode
+     * @param offset array offset for the first character to decode
+     * @param length the number of bytes to decode
+     * @return the decoded string
      */
     public static String
     gsm8BitUnpackedToString(byte[] data, int offset, int length) {
-        boolean prevWasEscape;
-        StringBuilder ret = new StringBuilder(length);
+        // Always use GSM 7 bit default alphabet table for this method
+        String languageTableToChar = sLanguageTables[0];
+        String shiftTableToChar = sLanguageShiftTables[0];
 
-        prevWasEscape = false;
+        StringBuilder ret = new StringBuilder(length);
+        boolean prevWasEscape = false;
         for (int i = offset ; i < offset + length ; i++) {
             // Never underestimate the pain that can be caused
             // by signed bytes
@@ -378,9 +512,15 @@
                 }
             } else {
                 if (prevWasEscape) {
-                    ret.append((char)gsmExtendedToChar.get(c, ' '));
+                    char shiftChar = shiftTableToChar.charAt(c);
+                    if (shiftChar == ' ') {
+                        // display character from main table if not present in shift table
+                        ret.append(languageTableToChar.charAt(c));
+                    } else {
+                        ret.append(shiftChar);
+                    }
                 } else {
-                    ret.append((char)gsmToChar.get(c, ' '));
+                    ret.append(languageTableToChar.charAt(c));
                 }
                 prevWasEscape = false;
             }
@@ -390,16 +530,16 @@
     }
 
     /**
-     * Convert a string into an 8-bit unpacked GSM alphabet byte
-     * array
+     * Convert a string into an 8-bit unpacked GSM alphabet byte array.
+     * Always uses GSM default 7-bit alphabet and extension table.
+     * @param s the string to encode
+     * @return the 8-bit GSM encoded byte array for the string
      */
     public static byte[]
     stringToGsm8BitPacked(String s) {
         byte[] ret;
 
-        int septets = 0;
-
-        septets = countGsmSeptets(s);
+        int septets = countGsmSeptetsUsingTables(s, true, 0, 0);
 
         // Enough for all the septets and the length byte prefix
         ret = new byte[septets];
@@ -412,14 +552,18 @@
 
     /**
      * Write a String into a GSM 8-bit unpacked field of
-     * @param length size at @param offset in @param dest
-     *
      * Field is padded with 0xff's, string is truncated if necessary
+     *
+     * @param s the string to encode
+     * @param dest the destination byte array
+     * @param offset the starting offset for the encoded string
+     * @param length the maximum number of bytes to write
      */
-
     public static void
     stringToGsm8BitUnpackedField(String s, byte dest[], int offset, int length) {
         int outByteIndex = offset;
+        SparseIntArray charToLanguageTable = sCharsToGsmTables[0];
+        SparseIntArray charToShiftTable = sCharsToShiftTables[0];
 
         // Septets are stored in byte-aligned octets
         for (int i = 0, sz = s.length()
@@ -428,17 +572,20 @@
         ) {
             char c = s.charAt(i);
 
-            int v = GsmAlphabet.charToGsm(c);
+            int v = charToLanguageTable.get(c, -1);
 
-            if (v == GSM_EXTENDED_ESCAPE) {
-                // make sure we can fit an escaped char
-                if (! (outByteIndex + 1 - offset < length)) {
-                    break;
+            if (v == -1) {
+                v = charToShiftTable.get(c, -1);
+                if (v == -1) {
+                    v = charToLanguageTable.get(' ', ' ');  // fall back to ASCII space
+                } else {
+                    // make sure we can fit an escaped char
+                    if (! (outByteIndex + 1 - offset < length)) {
+                        break;
+                    }
+
+                    dest[outByteIndex++] = GSM_EXTENDED_ESCAPE;
                 }
-
-                dest[outByteIndex++] = GSM_EXTENDED_ESCAPE;
-
-                v = GsmAlphabet.charToGsmExtended(c);
             }
 
             dest[outByteIndex++] = (byte)v;
@@ -453,6 +600,8 @@
     /**
      * Returns the count of 7-bit GSM alphabet characters
      * needed to represent this character. Counts unencodable char as 1 septet.
+     * @param c the character to examine
+     * @return the number of septets for this character
      */
     public static int
     countGsmSeptets(char c) {
@@ -466,17 +615,20 @@
 
     /**
      * Returns the count of 7-bit GSM alphabet characters
-     * needed to represent this character
+     * needed to represent this character using the default 7 bit GSM alphabet.
+     * @param c the character to examine
      * @param throwsException If true, throws EncodeException if unencodable
-     * char. Otherwise, counts invalid char as 1 septet
+     * char. Otherwise, counts invalid char as 1 septet.
+     * @return the number of septets for this character
+     * @throws EncodeException the character can't be encoded and throwsException is true
      */
     public static int
     countGsmSeptets(char c, boolean throwsException) throws EncodeException {
-        if (charToGsm.get(c, -1) != -1) {
+        if (sCharsToGsmTables[0].get(c, -1) != -1) {
             return 1;
         }
 
-        if (charToGsmExtended.get(c, -1) != -1) {
+        if (sCharsToShiftTables[0].get(c, -1) != -1) {
             return 2;
         }
 
@@ -489,37 +641,196 @@
     }
 
     /**
-     * Returns the count of 7-bit GSM alphabet characters
-     * needed to represent this string. Counts unencodable char as 1 septet.
+     * Returns the count of 7-bit GSM alphabet characters needed
+     * to represent this string, using the specified 7-bit language table
+     * and extension table (0 for GSM default tables).
+     * @param s the Unicode string that will be encoded
+     * @param use7bitOnly allow using space in place of unencodable character if true,
+     *     otherwise, return -1 if any characters are unencodable
+     * @param languageTable the 7 bit language table, or 0 for the default GSM alphabet
+     * @param languageShiftTable the 7 bit single shift language table, or 0 for the default
+     *     GSM extension table
+     * @return the septet count for s using the specified language tables, or -1 if any
+     *     characters are unencodable and use7bitOnly is false
      */
-    public static int
-    countGsmSeptets(CharSequence s) {
-        try {
-            return countGsmSeptets(s, false);
-        } catch (EncodeException ex) {
-            // this should never happen
-            return 0;
+    public static int countGsmSeptetsUsingTables(CharSequence s, boolean use7bitOnly,
+            int languageTable, int languageShiftTable) {
+        int count = 0;
+        int sz = s.length();
+        SparseIntArray charToLanguageTable = sCharsToGsmTables[languageTable];
+        SparseIntArray charToShiftTable = sCharsToShiftTables[languageShiftTable];
+        for (int i = 0; i < sz; i++) {
+            char c = s.charAt(i);
+            if (c == GSM_EXTENDED_ESCAPE) {
+                Log.w(TAG, "countGsmSeptets() string contains Escape character, skipping.");
+                continue;
+            }
+            if (charToLanguageTable.get(c, -1) != -1) {
+                count++;
+            } else if (charToShiftTable.get(c, -1) != -1) {
+                count += 2; // escape + shift table index
+            } else if (use7bitOnly) {
+                count++;    // encode as space
+            } else {
+                return -1;  // caller must check for this case
+            }
         }
+        return count;
     }
 
     /**
      * Returns the count of 7-bit GSM alphabet characters
-     * needed to represent this string.
-     * @param throwsException If true, throws EncodeException if unencodable
-     * char. Otherwise, counts invalid char as 1 septet
+     * needed to represent this string, and the language table and
+     * language shift table used to achieve this result.
+     * For multi-part text messages, each message part may use its
+     * own language table encoding as specified in the message header
+     * for that message. However, this method will only return the
+     * optimal encoding for the message as a whole. When the individual
+     * pieces are encoded, a more optimal encoding may be chosen for each
+     * piece of the message, but the message will be split into pieces
+     * based on the encoding chosen for the message as a whole.
+     * @param s the Unicode string that will be encoded
+     * @param use7bitOnly allow using space in place of unencodable character if true,
+     *     using the language table pair with the fewest unencodable characters
+     * @return a TextEncodingDetails object containing the message and
+     *     character counts for the most efficient 7-bit encoding,
+     *     or null if there are no suitable language tables to encode the string.
      */
-    public static int
-    countGsmSeptets(CharSequence s, boolean throwsException) throws EncodeException {
-        int charIndex = 0;
-        int sz = s.length();
-        int count = 0;
-
-        while (charIndex < sz) {
-            count += countGsmSeptets(s.charAt(charIndex), throwsException);
-            charIndex++;
+    public static SmsMessageBase.TextEncodingDetails
+    countGsmSeptets(CharSequence s, boolean use7bitOnly) {
+        // fast path for common case where no national language shift tables are enabled
+        if (sEnabledSingleShiftTables.length + sEnabledLockingShiftTables.length == 0) {
+            SmsMessageBase.TextEncodingDetails ted = new SmsMessageBase.TextEncodingDetails();
+            int septets = GsmAlphabet.countGsmSeptetsUsingTables(s, use7bitOnly, 0, 0);
+            if (septets == -1) {
+                return null;
+            }
+            ted.codeUnitSize = ENCODING_7BIT;
+            ted.codeUnitCount = septets;
+            if (septets > MAX_USER_DATA_SEPTETS) {
+                ted.msgCount = (septets + (MAX_USER_DATA_SEPTETS_WITH_HEADER - 1)) /
+                        MAX_USER_DATA_SEPTETS_WITH_HEADER;
+                ted.codeUnitsRemaining = (ted.msgCount *
+                        MAX_USER_DATA_SEPTETS_WITH_HEADER) - septets;
+            } else {
+                ted.msgCount = 1;
+                ted.codeUnitsRemaining = MAX_USER_DATA_SEPTETS - septets;
+            }
+            ted.codeUnitSize = ENCODING_7BIT;
+            return ted;
         }
 
-        return count;
+        int maxSingleShiftCode = sHighestEnabledSingleShiftCode;
+        List<LanguagePairCount> lpcList = new ArrayList<LanguagePairCount>(
+                sEnabledLockingShiftTables.length + 1);
+
+        // Always add default GSM 7-bit alphabet table
+        lpcList.add(new LanguagePairCount(0));
+        for (int i : sEnabledLockingShiftTables) {
+            // Avoid adding default table twice in case 0 is in the list of allowed tables
+            if (i != 0 && !sLanguageTables[i].isEmpty()) {
+                lpcList.add(new LanguagePairCount(i));
+            }
+        }
+
+        int sz = s.length();
+        // calculate septet count for each valid table / shift table pair
+        for (int i = 0; i < sz && !lpcList.isEmpty(); i++) {
+            char c = s.charAt(i);
+            if (c == GSM_EXTENDED_ESCAPE) {
+                Log.w(TAG, "countGsmSeptets() string contains Escape character, ignoring!");
+                continue;
+            }
+            // iterate through enabled locking shift tables
+            for (LanguagePairCount lpc : lpcList) {
+                int tableIndex = sCharsToGsmTables[lpc.languageCode].get(c, -1);
+                if (tableIndex == -1) {
+                    // iterate through single shift tables for this locking table
+                    for (int table = 0; table <= maxSingleShiftCode; table++) {
+                        if (lpc.septetCounts[table] != -1) {
+                            int shiftTableIndex = sCharsToShiftTables[table].get(c, -1);
+                            if (shiftTableIndex == -1) {
+                                if (use7bitOnly) {
+                                    // can't encode char, use space instead
+                                    lpc.septetCounts[table]++;
+                                    lpc.unencodableCounts[table]++;
+                                } else {
+                                    // can't encode char, remove language pair from list
+                                    lpc.septetCounts[table] = -1;
+                                }
+                            } else {
+                                // encode as Escape + index into shift table
+                                lpc.septetCounts[table] += 2;
+                            }
+                        }
+                    }
+                } else {
+                    // encode as index into locking shift table for all pairs
+                    for (int table = 0; table <= maxSingleShiftCode; table++) {
+                        if (lpc.septetCounts[table] != -1) {
+                            lpc.septetCounts[table]++;
+                        }
+                    }
+                }
+            }
+        }
+
+        // find the least cost encoding (lowest message count and most code units remaining)
+        SmsMessageBase.TextEncodingDetails ted = new SmsMessageBase.TextEncodingDetails();
+        ted.msgCount = Integer.MAX_VALUE;
+        ted.codeUnitSize = ENCODING_7BIT;
+        int minUnencodableCount = Integer.MAX_VALUE;
+        for (LanguagePairCount lpc : lpcList) {
+            for (int shiftTable = 0; shiftTable <= maxSingleShiftCode; shiftTable++) {
+                int septets = lpc.septetCounts[shiftTable];
+                if (septets == -1) {
+                    continue;
+                }
+                int udhLength;
+                if (lpc.languageCode != 0 && shiftTable != 0) {
+                    udhLength = UDH_SEPTET_COST_LENGTH + UDH_SEPTET_COST_TWO_SHIFT_TABLES;
+                } else if (lpc.languageCode != 0 || shiftTable != 0) {
+                    udhLength = UDH_SEPTET_COST_LENGTH + UDH_SEPTET_COST_ONE_SHIFT_TABLE;
+                } else {
+                    udhLength = 0;
+                }
+                int msgCount;
+                int septetsRemaining;
+                if (septets + udhLength > MAX_USER_DATA_SEPTETS) {
+                    if (udhLength == 0) {
+                        udhLength = UDH_SEPTET_COST_LENGTH;
+                    }
+                    udhLength += UDH_SEPTET_COST_CONCATENATED_MESSAGE;
+                    int septetsPerMessage = MAX_USER_DATA_SEPTETS - udhLength;
+                    msgCount = (septets + septetsPerMessage - 1) / septetsPerMessage;
+                    septetsRemaining = (msgCount * septetsPerMessage) - septets;
+                } else {
+                    msgCount = 1;
+                    septetsRemaining = MAX_USER_DATA_SEPTETS - udhLength - septets;
+                }
+                // for 7-bit only mode, use language pair with the least unencodable chars
+                int unencodableCount = lpc.unencodableCounts[shiftTable];
+                if (use7bitOnly && unencodableCount > minUnencodableCount) {
+                    continue;
+                }
+                if ((use7bitOnly && unencodableCount < minUnencodableCount)
+                        || msgCount < ted.msgCount || (msgCount == ted.msgCount
+                        && septetsRemaining > ted.codeUnitsRemaining)) {
+                    minUnencodableCount = unencodableCount;
+                    ted.msgCount = msgCount;
+                    ted.codeUnitCount = septets;
+                    ted.codeUnitsRemaining = septetsRemaining;
+                    ted.languageTable = lpc.languageCode;
+                    ted.languageShiftTable = shiftTable;
+                }
+            }
+        }
+
+        if (ted.msgCount == Integer.MAX_VALUE) {
+            return null;
+        }
+
+        return ted;
     }
 
     /**
@@ -532,16 +843,31 @@
      * @param start index of where to start counting septets
      * @param limit maximum septets to include,
      *   e.g. <code>MAX_USER_DATA_SEPTETS</code>
+     * @param langTable the 7 bit character table to use (0 for default GSM 7-bit alphabet)
+     * @param langShiftTable the 7 bit shift table to use (0 for default GSM extension table)
      * @return index of first character that won't fit, or the length
      *   of the entire string if everything fits
      */
     public static int
-    findGsmSeptetLimitIndex(String s, int start, int limit) {
+    findGsmSeptetLimitIndex(String s, int start, int limit, int langTable, int langShiftTable) {
         int accumulator = 0;
         int size = s.length();
 
+        SparseIntArray charToLangTable = sCharsToGsmTables[langTable];
+        SparseIntArray charToLangShiftTable = sCharsToShiftTables[langShiftTable];
         for (int i = start; i < size; i++) {
-            accumulator += countGsmSeptets(s.charAt(i));
+            int encodedSeptet = charToLangTable.get(s.charAt(i), -1);
+            if (encodedSeptet == -1) {
+                encodedSeptet = charToLangShiftTable.get(s.charAt(i), -1);
+                if (encodedSeptet == -1) {
+                    // char not found, assume we're replacing with space
+                    accumulator++;
+                } else {
+                    accumulator += 2;  // escape character + shift table index
+                }
+            } else {
+                accumulator++;
+            }
             if (accumulator > limit) {
                 return i;
             }
@@ -549,178 +875,488 @@
         return size;
     }
 
-    // Set in the static initializer
-    private static int sGsmSpaceChar;
+    /**
+     * Modify the array of enabled national language single shift tables for SMS
+     * encoding. This is used for unit testing, but could also be used to
+     * modify the enabled encodings based on the active MCC/MNC, for example.
+     *
+     * @param tables the new list of enabled single shift tables
+     */
+    static synchronized void setEnabledSingleShiftTables(int[] tables) {
+        sEnabledSingleShiftTables = tables;
 
-    private static final SparseIntArray charToGsm = new SparseIntArray();
-    private static final SparseIntArray gsmToChar = new SparseIntArray();
-    private static final SparseIntArray charToGsmExtended = new SparseIntArray();
-    private static final SparseIntArray gsmExtendedToChar = new SparseIntArray();
-
-    static {
-        int i = 0;
-
-        charToGsm.put('@', i++);
-        charToGsm.put('\u00a3', i++);
-        charToGsm.put('$', i++);
-        charToGsm.put('\u00a5', i++);
-        charToGsm.put('\u00e8', i++);
-        charToGsm.put('\u00e9', i++);
-        charToGsm.put('\u00f9', i++);
-        charToGsm.put('\u00ec', i++);
-        charToGsm.put('\u00f2', i++);
-        charToGsm.put('\u00c7', i++);
-        charToGsm.put('\n', i++);
-        charToGsm.put('\u00d8', i++);
-        charToGsm.put('\u00f8', i++);
-        charToGsm.put('\r', i++);
-        charToGsm.put('\u00c5', i++);
-        charToGsm.put('\u00e5', i++);
-
-        charToGsm.put('\u0394', i++);
-        charToGsm.put('_', i++);
-        charToGsm.put('\u03a6', i++);
-        charToGsm.put('\u0393', i++);
-        charToGsm.put('\u039b', i++);
-        charToGsm.put('\u03a9', i++);
-        charToGsm.put('\u03a0', i++);
-        charToGsm.put('\u03a8', i++);
-        charToGsm.put('\u03a3', i++);
-        charToGsm.put('\u0398', i++);
-        charToGsm.put('\u039e', i++);
-        charToGsm.put('\uffff', i++);
-        charToGsm.put('\u00c6', i++);
-        charToGsm.put('\u00e6', i++);
-        charToGsm.put('\u00df', i++);
-        charToGsm.put('\u00c9', i++);
-
-        charToGsm.put(' ', i++);
-        charToGsm.put('!', i++);
-        charToGsm.put('"', i++);
-        charToGsm.put('#', i++);
-        charToGsm.put('\u00a4', i++);
-        charToGsm.put('%', i++);
-        charToGsm.put('&', i++);
-        charToGsm.put('\'', i++);
-        charToGsm.put('(', i++);
-        charToGsm.put(')', i++);
-        charToGsm.put('*', i++);
-        charToGsm.put('+', i++);
-        charToGsm.put(',', i++);
-        charToGsm.put('-', i++);
-        charToGsm.put('.', i++);
-        charToGsm.put('/', i++);
-
-        charToGsm.put('0', i++);
-        charToGsm.put('1', i++);
-        charToGsm.put('2', i++);
-        charToGsm.put('3', i++);
-        charToGsm.put('4', i++);
-        charToGsm.put('5', i++);
-        charToGsm.put('6', i++);
-        charToGsm.put('7', i++);
-        charToGsm.put('8', i++);
-        charToGsm.put('9', i++);
-        charToGsm.put(':', i++);
-        charToGsm.put(';', i++);
-        charToGsm.put('<', i++);
-        charToGsm.put('=', i++);
-        charToGsm.put('>', i++);
-        charToGsm.put('?', i++);
-
-        charToGsm.put('\u00a1', i++);
-        charToGsm.put('A', i++);
-        charToGsm.put('B', i++);
-        charToGsm.put('C', i++);
-        charToGsm.put('D', i++);
-        charToGsm.put('E', i++);
-        charToGsm.put('F', i++);
-        charToGsm.put('G', i++);
-        charToGsm.put('H', i++);
-        charToGsm.put('I', i++);
-        charToGsm.put('J', i++);
-        charToGsm.put('K', i++);
-        charToGsm.put('L', i++);
-        charToGsm.put('M', i++);
-        charToGsm.put('N', i++);
-        charToGsm.put('O', i++);
-
-        charToGsm.put('P', i++);
-        charToGsm.put('Q', i++);
-        charToGsm.put('R', i++);
-        charToGsm.put('S', i++);
-        charToGsm.put('T', i++);
-        charToGsm.put('U', i++);
-        charToGsm.put('V', i++);
-        charToGsm.put('W', i++);
-        charToGsm.put('X', i++);
-        charToGsm.put('Y', i++);
-        charToGsm.put('Z', i++);
-        charToGsm.put('\u00c4', i++);
-        charToGsm.put('\u00d6', i++);
-        charToGsm.put('\u00d1', i++);
-        charToGsm.put('\u00dc', i++);
-        charToGsm.put('\u00a7', i++);
-
-        charToGsm.put('\u00bf', i++);
-        charToGsm.put('a', i++);
-        charToGsm.put('b', i++);
-        charToGsm.put('c', i++);
-        charToGsm.put('d', i++);
-        charToGsm.put('e', i++);
-        charToGsm.put('f', i++);
-        charToGsm.put('g', i++);
-        charToGsm.put('h', i++);
-        charToGsm.put('i', i++);
-        charToGsm.put('j', i++);
-        charToGsm.put('k', i++);
-        charToGsm.put('l', i++);
-        charToGsm.put('m', i++);
-        charToGsm.put('n', i++);
-        charToGsm.put('o', i++);
-
-        charToGsm.put('p', i++);
-        charToGsm.put('q', i++);
-        charToGsm.put('r', i++);
-        charToGsm.put('s', i++);
-        charToGsm.put('t', i++);
-        charToGsm.put('u', i++);
-        charToGsm.put('v', i++);
-        charToGsm.put('w', i++);
-        charToGsm.put('x', i++);
-        charToGsm.put('y', i++);
-        charToGsm.put('z', i++);
-        charToGsm.put('\u00e4', i++);
-        charToGsm.put('\u00f6', i++);
-        charToGsm.put('\u00f1', i++);
-        charToGsm.put('\u00fc', i++);
-        charToGsm.put('\u00e0', i++);
-
-
-        charToGsmExtended.put('\f', 10);
-        charToGsmExtended.put('^', 20);
-        charToGsmExtended.put('{', 40);
-        charToGsmExtended.put('}', 41);
-        charToGsmExtended.put('\\', 47);
-        charToGsmExtended.put('[', 60);
-        charToGsmExtended.put('~', 61);
-        charToGsmExtended.put(']', 62);
-        charToGsmExtended.put('|', 64);
-        charToGsmExtended.put('\u20ac', 101);
-
-        int size = charToGsm.size();
-        for (int j=0; j<size; j++) {
-            gsmToChar.put(charToGsm.valueAt(j), charToGsm.keyAt(j));
+        if (tables.length > 0) {
+            sHighestEnabledSingleShiftCode = tables[tables.length - 1];
+        } else {
+            sHighestEnabledSingleShiftCode = 0;
         }
-
-        size = charToGsmExtended.size();
-        for (int j=0; j<size; j++) {
-            gsmExtendedToChar.put(charToGsmExtended.valueAt(j), charToGsmExtended.keyAt(j));
-        }
-
-
-        sGsmSpaceChar = charToGsm.get(' ');
     }
 
+    /**
+     * Modify the array of enabled national language locking shift tables for SMS
+     * encoding. This is used for unit testing, but could also be used to
+     * modify the enabled encodings based on the active MCC/MNC, for example.
+     *
+     * @param tables the new list of enabled locking shift tables
+     */
+    static synchronized void setEnabledLockingShiftTables(int[] tables) {
+        sEnabledLockingShiftTables = tables;
+    }
 
+    /**
+     * Return the array of enabled national language single shift tables for SMS
+     * encoding. This is used for unit testing. The returned array is not a copy, so
+     * the caller should be careful not to modify it.
+     *
+     * @return the list of enabled single shift tables
+     */
+    static synchronized int[] getEnabledSingleShiftTables() {
+        return sEnabledSingleShiftTables;
+    }
+
+    /**
+     * Return the array of enabled national language locking shift tables for SMS
+     * encoding. This is used for unit testing. The returned array is not a copy, so
+     * the caller should be careful not to modify it.
+     *
+     * @return the list of enabled locking shift tables
+     */
+    static synchronized int[] getEnabledLockingShiftTables() {
+        return sEnabledLockingShiftTables;
+    }
+
+    /** Reverse mapping from Unicode characters to indexes into language tables. */
+    private static final SparseIntArray[] sCharsToGsmTables;
+
+    /** Reverse mapping from Unicode characters to indexes into language shift tables. */
+    private static final SparseIntArray[] sCharsToShiftTables;
+
+    /** OEM configured list of enabled national language single shift tables for encoding. */
+    private static int[] sEnabledSingleShiftTables;
+
+    /** OEM configured list of enabled national language locking shift tables for encoding. */
+    private static int[] sEnabledLockingShiftTables;
+
+    /** Highest language code to include in array of single shift counters. */
+    private static int sHighestEnabledSingleShiftCode;
+
+    /**
+     * Septet counter for a specific locking shift table and all of
+     * the single shift tables that it can be paired with.
+     */
+    private static class LanguagePairCount {
+        final int languageCode;
+        final int[] septetCounts;
+        final int[] unencodableCounts;
+        LanguagePairCount(int code) {
+            this.languageCode = code;
+            int maxSingleShiftCode = sHighestEnabledSingleShiftCode;
+            septetCounts = new int[maxSingleShiftCode + 1];
+            unencodableCounts = new int[maxSingleShiftCode + 1];
+            // set counters for disabled single shift tables to -1
+            // (GSM default extension table index 0 is always enabled)
+            for (int i = 1, tableOffset = 0; i <= maxSingleShiftCode; i++) {
+                if (sEnabledSingleShiftTables[tableOffset] == i) {
+                    tableOffset++;
+                } else {
+                    septetCounts[i] = -1;   // disabled
+                }
+            }
+            // exclude Turkish locking + Turkish single shift table and
+            // Portuguese locking + Spanish single shift table (these
+            // combinations will never be optimal for any input).
+            if (code == 1 && maxSingleShiftCode >= 1) {
+                septetCounts[1] = -1;   // Turkish + Turkish
+            } else if (code == 3 && maxSingleShiftCode >= 2) {
+                septetCounts[2] = -1;   // Portuguese + Spanish
+            }
+        }
+    }
+
+    /**
+     * GSM default 7 bit alphabet plus national language locking shift character tables.
+     * Comment lines above strings indicate the lower four bits of the table position.
+     */
+    private static final String[] sLanguageTables = {
+        /* 3GPP TS 23.038 V9.1.1 section 6.2.1 - GSM 7 bit Default Alphabet
+         01.....23.....4.....5.....6.....7.....8.....9.....A.B.....C.....D.E.....F.....0.....1 */
+        "@\u00a3$\u00a5\u00e8\u00e9\u00f9\u00ec\u00f2\u00c7\n\u00d8\u00f8\r\u00c5\u00e5\u0394_"
+            // 2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....
+            + "\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e\uffff\u00c6\u00e6\u00df"
+            // F.....012.34.....56789ABCDEF0123456789ABCDEF0.....123456789ABCDEF0123456789A
+            + "\u00c9 !\"#\u00a4%&'()*+,-./0123456789:;<=>?\u00a1ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+            // B.....C.....D.....E.....F.....0.....123456789ABCDEF0123456789AB.....C.....D.....
+            + "\u00c4\u00d6\u00d1\u00dc\u00a7\u00bfabcdefghijklmnopqrstuvwxyz\u00e4\u00f6\u00f1"
+            // E.....F.....
+            + "\u00fc\u00e0",
+
+        /* A.3.1 Turkish National Language Locking Shift Table
+         01.....23.....4.....5.....6.....7.....8.....9.....A.B.....C.....D.E.....F.....0.....1 */
+        "@\u00a3$\u00a5\u20ac\u00e9\u00f9\u0131\u00f2\u00c7\n\u011e\u011f\r\u00c5\u00e5\u0394_"
+            // 2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....
+            + "\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e\uffff\u015e\u015f\u00df"
+            // F.....012.34.....56789ABCDEF0123456789ABCDEF0.....123456789ABCDEF0123456789A
+            + "\u00c9 !\"#\u00a4%&'()*+,-./0123456789:;<=>?\u0130ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+            // B.....C.....D.....E.....F.....0.....123456789ABCDEF0123456789AB.....C.....D.....
+            + "\u00c4\u00d6\u00d1\u00dc\u00a7\u00e7abcdefghijklmnopqrstuvwxyz\u00e4\u00f6\u00f1"
+            // E.....F.....
+            + "\u00fc\u00e0",
+
+        /* A.3.2 Void (no locking shift table for Spanish) */
+        "",
+
+        /* A.3.3 Portuguese National Language Locking Shift Table
+         01.....23.....4.....5.....6.....7.....8.....9.....A.B.....C.....D.E.....F.....0.....1 */
+        "@\u00a3$\u00a5\u00ea\u00e9\u00fa\u00ed\u00f3\u00e7\n\u00d4\u00f4\r\u00c1\u00e1\u0394_"
+            // 2.....3.....4.....5.....67.8.....9.....AB.....C.....D.....E.....F.....012.34.....
+            + "\u00aa\u00c7\u00c0\u221e^\\\u20ac\u00d3|\uffff\u00c2\u00e2\u00ca\u00c9 !\"#\u00ba"
+            // 56789ABCDEF0123456789ABCDEF0.....123456789ABCDEF0123456789AB.....C.....D.....E.....
+            + "%&'()*+,-./0123456789:;<=>?\u00cdABCDEFGHIJKLMNOPQRSTUVWXYZ\u00c3\u00d5\u00da\u00dc"
+            // F.....0123456789ABCDEF0123456789AB.....C.....DE.....F.....
+            + "\u00a7~abcdefghijklmnopqrstuvwxyz\u00e3\u00f5`\u00fc\u00e0",
+
+        /* A.3.4 Bengali National Language Locking Shift Table
+         0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....CD.EF.....0..... */
+        "\u0981\u0982\u0983\u0985\u0986\u0987\u0988\u0989\u098a\u098b\n\u098c \r \u098f\u0990"
+            // 123.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
+            + "  \u0993\u0994\u0995\u0996\u0997\u0998\u0999\u099a\uffff\u099b\u099c\u099d\u099e"
+            // 012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....0123456789ABC
+            + " !\u099f\u09a0\u09a1\u09a2\u09a3\u09a4)(\u09a5\u09a6,\u09a7.\u09a80123456789:; "
+            // D.....E.....F0.....1.....2.....3.....4.....56.....789A.....B.....C.....D.....
+            + "\u09aa\u09ab?\u09ac\u09ad\u09ae\u09af\u09b0 \u09b2   \u09b6\u09b7\u09b8\u09b9"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....789.....A.....BCD.....E.....
+            + "\u09bc\u09bd\u09be\u09bf\u09c0\u09c1\u09c2\u09c3\u09c4  \u09c7\u09c8  \u09cb\u09cc"
+            // F.....0.....123456789ABCDEF0123456789AB.....C.....D.....E.....F.....
+            + "\u09cd\u09ceabcdefghijklmnopqrstuvwxyz\u09d7\u09dc\u09dd\u09f0\u09f1",
+
+        /* A.3.5 Gujarati National Language Locking Shift Table
+         0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....C.....D.EF.....0.....*/
+        "\u0a81\u0a82\u0a83\u0a85\u0a86\u0a87\u0a88\u0a89\u0a8a\u0a8b\n\u0a8c\u0a8d\r \u0a8f\u0a90"
+            // 1.....23.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....
+            + "\u0a91 \u0a93\u0a94\u0a95\u0a96\u0a97\u0a98\u0a99\u0a9a\uffff\u0a9b\u0a9c\u0a9d"
+            // F.....012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....0123456789AB
+            + "\u0a9e !\u0a9f\u0aa0\u0aa1\u0aa2\u0aa3\u0aa4)(\u0aa5\u0aa6,\u0aa7.\u0aa80123456789:;"
+            // CD.....E.....F0.....1.....2.....3.....4.....56.....7.....89.....A.....B.....C.....
+            + " \u0aaa\u0aab?\u0aac\u0aad\u0aae\u0aaf\u0ab0 \u0ab2\u0ab3 \u0ab5\u0ab6\u0ab7\u0ab8"
+            // D.....E.....F.....0.....1.....2.....3.....4.....5.....6.....7.....89.....A.....
+            + "\u0ab9\u0abc\u0abd\u0abe\u0abf\u0ac0\u0ac1\u0ac2\u0ac3\u0ac4\u0ac5 \u0ac7\u0ac8"
+            // B.....CD.....E.....F.....0.....123456789ABCDEF0123456789AB.....C.....D.....E.....
+            + "\u0ac9 \u0acb\u0acc\u0acd\u0ad0abcdefghijklmnopqrstuvwxyz\u0ae0\u0ae1\u0ae2\u0ae3"
+            // F.....
+            + "\u0af1",
+
+        /* A.3.6 Hindi National Language Locking Shift Table
+         0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....C.....D.E.....F.....*/
+        "\u0901\u0902\u0903\u0905\u0906\u0907\u0908\u0909\u090a\u090b\n\u090c\u090d\r\u090e\u090f"
+            // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....
+            + "\u0910\u0911\u0912\u0913\u0914\u0915\u0916\u0917\u0918\u0919\u091a\uffff\u091b\u091c"
+            // E.....F.....012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....012345
+            + "\u091d\u091e !\u091f\u0920\u0921\u0922\u0923\u0924)(\u0925\u0926,\u0927.\u0928012345"
+            // 6789ABC.....D.....E.....F0.....1.....2.....3.....4.....5.....6.....7.....8.....
+            + "6789:;\u0929\u092a\u092b?\u092c\u092d\u092e\u092f\u0930\u0931\u0932\u0933\u0934"
+            // 9.....A.....B.....C.....D.....E.....F.....0.....1.....2.....3.....4.....5.....6.....
+            + "\u0935\u0936\u0937\u0938\u0939\u093c\u093d\u093e\u093f\u0940\u0941\u0942\u0943\u0944"
+            // 7.....8.....9.....A.....B.....C.....D.....E.....F.....0.....123456789ABCDEF012345678
+            + "\u0945\u0946\u0947\u0948\u0949\u094a\u094b\u094c\u094d\u0950abcdefghijklmnopqrstuvwx"
+            // 9AB.....C.....D.....E.....F.....
+            + "yz\u0972\u097b\u097c\u097e\u097f",
+
+        /* A.3.7 Kannada National Language Locking Shift Table
+           NOTE: TS 23.038 V9.1.1 shows code 0x24 as \u0caa, corrected to \u0ca1 (typo)
+         01.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....CD.E.....F.....0.....1 */
+        " \u0c82\u0c83\u0c85\u0c86\u0c87\u0c88\u0c89\u0c8a\u0c8b\n\u0c8c \r\u0c8e\u0c8f\u0c90 "
+            // 2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
+            + "\u0c92\u0c93\u0c94\u0c95\u0c96\u0c97\u0c98\u0c99\u0c9a\uffff\u0c9b\u0c9c\u0c9d\u0c9e"
+            // 012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....0123456789ABC
+            + " !\u0c9f\u0ca0\u0ca1\u0ca2\u0ca3\u0ca4)(\u0ca5\u0ca6,\u0ca7.\u0ca80123456789:; "
+            // D.....E.....F0.....1.....2.....3.....4.....5.....6.....7.....89.....A.....B.....
+            + "\u0caa\u0cab?\u0cac\u0cad\u0cae\u0caf\u0cb0\u0cb1\u0cb2\u0cb3 \u0cb5\u0cb6\u0cb7"
+            // C.....D.....E.....F.....0.....1.....2.....3.....4.....5.....6.....78.....9.....
+            + "\u0cb8\u0cb9\u0cbc\u0cbd\u0cbe\u0cbf\u0cc0\u0cc1\u0cc2\u0cc3\u0cc4 \u0cc6\u0cc7"
+            // A.....BC.....D.....E.....F.....0.....123456789ABCDEF0123456789AB.....C.....D.....
+            + "\u0cc8 \u0cca\u0ccb\u0ccc\u0ccd\u0cd5abcdefghijklmnopqrstuvwxyz\u0cd6\u0ce0\u0ce1"
+            // E.....F.....
+            + "\u0ce2\u0ce3",
+
+        /* A.3.8 Malayalam National Language Locking Shift Table
+         01.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....CD.E.....F.....0.....1 */
+        " \u0d02\u0d03\u0d05\u0d06\u0d07\u0d08\u0d09\u0d0a\u0d0b\n\u0d0c \r\u0d0e\u0d0f\u0d10 "
+            // 2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
+            + "\u0d12\u0d13\u0d14\u0d15\u0d16\u0d17\u0d18\u0d19\u0d1a\uffff\u0d1b\u0d1c\u0d1d\u0d1e"
+            // 012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....0123456789ABC
+            + " !\u0d1f\u0d20\u0d21\u0d22\u0d23\u0d24)(\u0d25\u0d26,\u0d27.\u0d280123456789:; "
+            // D.....E.....F0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.....
+            + "\u0d2a\u0d2b?\u0d2c\u0d2d\u0d2e\u0d2f\u0d30\u0d31\u0d32\u0d33\u0d34\u0d35\u0d36"
+            // B.....C.....D.....EF.....0.....1.....2.....3.....4.....5.....6.....78.....9.....
+            + "\u0d37\u0d38\u0d39 \u0d3d\u0d3e\u0d3f\u0d40\u0d41\u0d42\u0d43\u0d44 \u0d46\u0d47"
+            // A.....BC.....D.....E.....F.....0.....123456789ABCDEF0123456789AB.....C.....D.....
+            + "\u0d48 \u0d4a\u0d4b\u0d4c\u0d4d\u0d57abcdefghijklmnopqrstuvwxyz\u0d60\u0d61\u0d62"
+            // E.....F.....
+            + "\u0d63\u0d79",
+
+        /* A.3.9 Oriya National Language Locking Shift Table
+         0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....CD.EF.....0.....12 */
+        "\u0b01\u0b02\u0b03\u0b05\u0b06\u0b07\u0b08\u0b09\u0b0a\u0b0b\n\u0b0c \r \u0b0f\u0b10  "
+            // 3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....01
+            + "\u0b13\u0b14\u0b15\u0b16\u0b17\u0b18\u0b19\u0b1a\uffff\u0b1b\u0b1c\u0b1d\u0b1e !"
+            // 2.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....0123456789ABCD.....
+            + "\u0b1f\u0b20\u0b21\u0b22\u0b23\u0b24)(\u0b25\u0b26,\u0b27.\u0b280123456789:; \u0b2a"
+            // E.....F0.....1.....2.....3.....4.....56.....7.....89.....A.....B.....C.....D.....
+            + "\u0b2b?\u0b2c\u0b2d\u0b2e\u0b2f\u0b30 \u0b32\u0b33 \u0b35\u0b36\u0b37\u0b38\u0b39"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....789.....A.....BCD.....E.....
+            + "\u0b3c\u0b3d\u0b3e\u0b3f\u0b40\u0b41\u0b42\u0b43\u0b44  \u0b47\u0b48  \u0b4b\u0b4c"
+            // F.....0.....123456789ABCDEF0123456789AB.....C.....D.....E.....F.....
+            + "\u0b4d\u0b56abcdefghijklmnopqrstuvwxyz\u0b57\u0b60\u0b61\u0b62\u0b63",
+
+        /* A.3.10 Punjabi National Language Locking Shift Table
+         0.....1.....2.....3.....4.....5.....6.....7.....8.....9A.BCD.EF.....0.....123.....4.....*/
+        "\u0a01\u0a02\u0a03\u0a05\u0a06\u0a07\u0a08\u0a09\u0a0a \n  \r \u0a0f\u0a10  \u0a13\u0a14"
+            // 5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....012.....3.....
+            + "\u0a15\u0a16\u0a17\u0a18\u0a19\u0a1a\uffff\u0a1b\u0a1c\u0a1d\u0a1e !\u0a1f\u0a20"
+            // 4.....5.....6.....7.....89A.....B.....CD.....EF.....0123456789ABCD.....E.....F0.....
+            + "\u0a21\u0a22\u0a23\u0a24)(\u0a25\u0a26,\u0a27.\u0a280123456789:; \u0a2a\u0a2b?\u0a2c"
+            // 1.....2.....3.....4.....56.....7.....89.....A.....BC.....D.....E.....F0.....1.....
+            + "\u0a2d\u0a2e\u0a2f\u0a30 \u0a32\u0a33 \u0a35\u0a36 \u0a38\u0a39\u0a3c \u0a3e\u0a3f"
+            // 2.....3.....4.....56789.....A.....BCD.....E.....F.....0.....123456789ABCDEF012345678
+            + "\u0a40\u0a41\u0a42    \u0a47\u0a48  \u0a4b\u0a4c\u0a4d\u0a51abcdefghijklmnopqrstuvwx"
+            // 9AB.....C.....D.....E.....F.....
+            + "yz\u0a70\u0a71\u0a72\u0a73\u0a74",
+
+        /* A.3.11 Tamil National Language Locking Shift Table
+         01.....2.....3.....4.....5.....6.....7.....8.....9A.BCD.E.....F.....0.....12.....3..... */
+        " \u0b82\u0b83\u0b85\u0b86\u0b87\u0b88\u0b89\u0b8a \n  \r\u0b8e\u0b8f\u0b90 \u0b92\u0b93"
+            // 4.....5.....6789.....A.....B.....CD.....EF.....012.....3456.....7.....89ABCDEF.....
+            + "\u0b94\u0b95   \u0b99\u0b9a\uffff \u0b9c \u0b9e !\u0b9f   \u0ba3\u0ba4)(  , .\u0ba8"
+            // 0123456789ABC.....D.....EF012.....3.....4.....5.....6.....7.....8.....9.....A.....
+            + "0123456789:;\u0ba9\u0baa ?  \u0bae\u0baf\u0bb0\u0bb1\u0bb2\u0bb3\u0bb4\u0bb5\u0bb6"
+            // B.....C.....D.....EF0.....1.....2.....3.....4.....5678.....9.....A.....BC.....D.....
+            + "\u0bb7\u0bb8\u0bb9  \u0bbe\u0bbf\u0bc0\u0bc1\u0bc2   \u0bc6\u0bc7\u0bc8 \u0bca\u0bcb"
+            // E.....F.....0.....123456789ABCDEF0123456789AB.....C.....D.....E.....F.....
+            + "\u0bcc\u0bcd\u0bd0abcdefghijklmnopqrstuvwxyz\u0bd7\u0bf0\u0bf1\u0bf2\u0bf9",
+
+        /* A.3.12 Telugu National Language Locking Shift Table
+         0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....CD.E.....F.....0.....*/
+        "\u0c01\u0c02\u0c03\u0c05\u0c06\u0c07\u0c08\u0c09\u0c0a\u0c0b\n\u0c0c \r\u0c0e\u0c0f\u0c10"
+            // 12.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....
+            + " \u0c12\u0c13\u0c14\u0c15\u0c16\u0c17\u0c18\u0c19\u0c1a\uffff\u0c1b\u0c1c\u0c1d"
+            // F.....012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....0123456789AB
+            + "\u0c1e !\u0c1f\u0c20\u0c21\u0c22\u0c23\u0c24)(\u0c25\u0c26,\u0c27.\u0c280123456789:;"
+            // CD.....E.....F0.....1.....2.....3.....4.....5.....6.....7.....89.....A.....B.....
+            + " \u0c2a\u0c2b?\u0c2c\u0c2d\u0c2e\u0c2f\u0c30\u0c31\u0c32\u0c33 \u0c35\u0c36\u0c37"
+            // C.....D.....EF.....0.....1.....2.....3.....4.....5.....6.....78.....9.....A.....B
+            + "\u0c38\u0c39 \u0c3d\u0c3e\u0c3f\u0c40\u0c41\u0c42\u0c43\u0c44 \u0c46\u0c47\u0c48 "
+            // C.....D.....E.....F.....0.....123456789ABCDEF0123456789AB.....C.....D.....E.....
+            + "\u0c4a\u0c4b\u0c4c\u0c4d\u0c55abcdefghijklmnopqrstuvwxyz\u0c56\u0c60\u0c61\u0c62"
+            // F.....
+            + "\u0c63",
+
+        /* A.3.13 Urdu National Language Locking Shift Table
+         0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....C.....D.E.....F.....*/
+        "\u0627\u0622\u0628\u067b\u0680\u067e\u06a6\u062a\u06c2\u067f\n\u0679\u067d\r\u067a\u067c"
+            // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....
+            + "\u062b\u062c\u0681\u0684\u0683\u0685\u0686\u0687\u062d\u062e\u062f\uffff\u068c\u0688"
+            // E.....F.....012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....012345
+            + "\u0689\u068a !\u068f\u068d\u0630\u0631\u0691\u0693)(\u0699\u0632,\u0696.\u0698012345"
+            // 6789ABC.....D.....E.....F0.....1.....2.....3.....4.....5.....6.....7.....8.....
+            + "6789:;\u069a\u0633\u0634?\u0635\u0636\u0637\u0638\u0639\u0641\u0642\u06a9\u06aa"
+            // 9.....A.....B.....C.....D.....E.....F.....0.....1.....2.....3.....4.....5.....6.....
+            + "\u06ab\u06af\u06b3\u06b1\u0644\u0645\u0646\u06ba\u06bb\u06bc\u0648\u06c4\u06d5\u06c1"
+            // 7.....8.....9.....A.....B.....C.....D.....E.....F.....0.....123456789ABCDEF012345678
+            + "\u06be\u0621\u06cc\u06d0\u06d2\u064d\u0650\u064f\u0657\u0654abcdefghijklmnopqrstuvwx"
+            // 9AB.....C.....D.....E.....F.....
+            + "yz\u0655\u0651\u0653\u0656\u0670"
+    };
+
+    /**
+     * GSM default extension table plus national language single shift character tables.
+     */
+    private static final String[] sLanguageShiftTables = new String[]{
+        /* 6.2.1.1 GSM 7 bit Default Alphabet Extension Table
+         0123456789A.....BCDEF0123456789ABCDEF0123456789ABCDEF.0123456789ABCDEF0123456789ABCDEF */
+        "          \u000c         ^                   {}     \\            [~] |               "
+            // 0123456789ABCDEF012345.....6789ABCDEF0123456789ABCDEF
+            + "                     \u20ac                          ",
+
+        /* A.2.1 Turkish National Language Single Shift Table
+         0123456789A.....BCDEF0123456789ABCDEF0123456789ABCDEF.0123456789ABCDEF01234567.....8 */
+        "          \u000c         ^                   {}     \\            [~] |      \u011e "
+            // 9.....ABCDEF0123.....456789ABCDEF0123.....45.....67.....89.....ABCDEF0123.....
+            + "\u0130         \u015e               \u00e7 \u20ac \u011f \u0131         \u015f"
+            // 456789ABCDEF
+            + "            ",
+
+        /* A.2.2 Spanish National Language Single Shift Table
+         0123456789.....A.....BCDEF0123456789ABCDEF0123456789ABCDEF.0123456789ABCDEF01.....23 */
+        "         \u00e7\u000c         ^                   {}     \\            [~] |\u00c1  "
+            // 456789.....ABCDEF.....012345.....6789ABCDEF01.....2345.....6789.....ABCDEF.....012
+            + "     \u00cd     \u00d3     \u00da           \u00e1   \u20ac   \u00ed     \u00f3   "
+            // 345.....6789ABCDEF
+            + "  \u00fa          ",
+
+        /* A.2.3 Portuguese National Language Single Shift Table
+         012345.....6789.....A.....B.....C.....DE.....F.....012.....3.....45.....6.....7.....8....*/
+        "     \u00ea   \u00e7\u000c\u00d4\u00f4 \u00c1\u00e1  \u03a6\u0393^\u03a9\u03a0\u03a8\u03a3"
+            // 9.....ABCDEF.....0123456789ABCDEF.0123456789ABCDEF01.....23456789.....ABCDE
+            + "\u0398     \u00ca        {}     \\            [~] |\u00c0       \u00cd     "
+            // F.....012345.....6789AB.....C.....DEF01.....2345.....6789.....ABCDEF.....01234
+            + "\u00d3     \u00da     \u00c3\u00d5    \u00c2   \u20ac   \u00ed     \u00f3     "
+            // 5.....6789AB.....C.....DEF.....
+            + "\u00fa     \u00e3\u00f5  \u00e2",
+
+        /* A.2.4 Bengali National Language Single Shift Table
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789.....A.....BC.....D..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*\u09e6\u09e7 \u09e8\u09e9"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....
+            + "\u09ea\u09eb\u09ec\u09ed\u09ee\u09ef\u09df\u09e0\u09e1\u09e2{}\u09e3\u09f2\u09f3"
+            // D.....E.....F.0.....1.....2.....3.....4.....56789ABCDEF0123456789ABCDEF
+            + "\u09f4\u09f5\\\u09f6\u09f7\u09f8\u09f9\u09fa       [~] |ABCDEFGHIJKLMNO"
+            // 0123456789ABCDEF012345.....6789ABCDEF0123456789ABCDEF
+            + "PQRSTUVWXYZ          \u20ac                          ",
+
+        /* A.2.5 Gujarati National Language Single Shift Table
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789.....A.....BC.....D..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*\u0964\u0965 \u0ae6\u0ae7"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6789ABCDEF.0123456789ABCDEF
+            + "\u0ae8\u0ae9\u0aea\u0aeb\u0aec\u0aed\u0aee\u0aef  {}     \\            [~] "
+            // 0123456789ABCDEF0123456789ABCDEF012345.....6789ABCDEF0123456789ABCDEF
+            + "|ABCDEFGHIJKLMNOPQRSTUVWXYZ          \u20ac                          ",
+
+        /* A.2.6 Hindi National Language Single Shift Table
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789.....A.....BC.....D..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*\u0964\u0965 \u0966\u0967"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....
+            + "\u0968\u0969\u096a\u096b\u096c\u096d\u096e\u096f\u0951\u0952{}\u0953\u0954\u0958"
+            // D.....E.....F.0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.....
+            + "\u0959\u095a\\\u095b\u095c\u095d\u095e\u095f\u0960\u0961\u0962\u0963\u0970\u0971"
+            // BCDEF0123456789ABCDEF0123456789ABCDEF012345.....6789ABCDEF0123456789ABCDEF
+            + " [~] |ABCDEFGHIJKLMNOPQRSTUVWXYZ          \u20ac                          ",
+
+        /* A.2.7 Kannada National Language Single Shift Table
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789.....A.....BC.....D..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*\u0964\u0965 \u0ce6\u0ce7"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....7.....89A.....BCDEF.01234567
+            + "\u0ce8\u0ce9\u0cea\u0ceb\u0cec\u0ced\u0cee\u0cef\u0cde\u0cf1{}\u0cf2    \\        "
+            // 89ABCDEF0123456789ABCDEF0123456789ABCDEF012345.....6789ABCDEF0123456789ABCDEF
+            + "    [~] |ABCDEFGHIJKLMNOPQRSTUVWXYZ          \u20ac                          ",
+
+        /* A.2.8 Malayalam National Language Single Shift Table
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789.....A.....BC.....D..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*\u0964\u0965 \u0d66\u0d67"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....
+            + "\u0d68\u0d69\u0d6a\u0d6b\u0d6c\u0d6d\u0d6e\u0d6f\u0d70\u0d71{}\u0d72\u0d73\u0d74"
+            // D.....E.....F.0.....1.....2.....3.....4.....56789ABCDEF0123456789ABCDEF0123456789A
+            + "\u0d75\u0d7a\\\u0d7b\u0d7c\u0d7d\u0d7e\u0d7f       [~] |ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+            // BCDEF012345.....6789ABCDEF0123456789ABCDEF
+            + "          \u20ac                          ",
+
+        /* A.2.9 Oriya National Language Single Shift Table
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789.....A.....BC.....D..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*\u0964\u0965 \u0b66\u0b67"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....DE
+            + "\u0b68\u0b69\u0b6a\u0b6b\u0b6c\u0b6d\u0b6e\u0b6f\u0b5c\u0b5d{}\u0b5f\u0b70\u0b71  "
+            // F.0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF012345.....6789ABCDEF0123456789A
+            + "\\            [~] |ABCDEFGHIJKLMNOPQRSTUVWXYZ          \u20ac                     "
+            // BCDEF
+            + "     ",
+
+        /* A.2.10 Punjabi National Language Single Shift Table
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789.....A.....BC.....D..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*\u0964\u0965 \u0a66\u0a67"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....
+            + "\u0a68\u0a69\u0a6a\u0a6b\u0a6c\u0a6d\u0a6e\u0a6f\u0a59\u0a5a{}\u0a5b\u0a5c\u0a5e"
+            // D.....EF.0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF012345.....6789ABCDEF01
+            + "\u0a75 \\            [~] |ABCDEFGHIJKLMNOPQRSTUVWXYZ          \u20ac            "
+            // 23456789ABCDEF
+            + "              ",
+
+        /* A.2.11 Tamil National Language Single Shift Table
+           NOTE: TS 23.038 V9.1.1 shows code 0x24 as \u0bef, corrected to \u0bee (typo)
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789.....A.....BC.....D..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*\u0964\u0965 \u0be6\u0be7"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....
+            + "\u0be8\u0be9\u0bea\u0beb\u0bec\u0bed\u0bee\u0bef\u0bf3\u0bf4{}\u0bf5\u0bf6\u0bf7"
+            // D.....E.....F.0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF012345.....6789ABC
+            + "\u0bf8\u0bfa\\            [~] |ABCDEFGHIJKLMNOPQRSTUVWXYZ          \u20ac       "
+            // DEF0123456789ABCDEF
+            + "                   ",
+
+        /* A.2.12 Telugu National Language Single Shift Table
+           NOTE: TS 23.038 V9.1.1 shows code 0x22-0x23 as \u06cc\u06cd, corrected to \u0c6c\u0c6d
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789ABC.....D.....E.....F..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*   \u0c66\u0c67\u0c68\u0c69"
+            // 0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....D.....E.....F.
+            + "\u0c6a\u0c6b\u0c6c\u0c6d\u0c6e\u0c6f\u0c58\u0c59{}\u0c78\u0c79\u0c7a\u0c7b\u0c7c\\"
+            // 0.....1.....2.....3456789ABCDEF0123456789ABCDEF0123456789ABCDEF012345.....6789ABCD
+            + "\u0c7d\u0c7e\u0c7f         [~] |ABCDEFGHIJKLMNOPQRSTUVWXYZ          \u20ac        "
+            // EF0123456789ABCDEF
+            + "                  ",
+
+        /* A.2.13 Urdu National Language Single Shift Table
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789.....A.....BC.....D..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*\u0600\u0601 \u06f0\u06f1"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....
+            + "\u06f2\u06f3\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9\u060c\u060d{}\u060e\u060f\u0610"
+            // D.....E.....F.0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.....
+            + "\u0611\u0612\\\u0613\u0614\u061b\u061f\u0640\u0652\u0658\u066b\u066c\u0672\u0673"
+            // B.....CDEF.....0123456789ABCDEF0123456789ABCDEF012345.....6789ABCDEF0123456789ABCDEF
+            + "\u06cd[~]\u06d4|ABCDEFGHIJKLMNOPQRSTUVWXYZ          \u20ac                          "
+    };
+
+    static {
+        Resources r = Resources.getSystem();
+        // See comments in frameworks/base/core/res/res/values/config.xml for allowed values
+        sEnabledSingleShiftTables = r.getIntArray(R.array.config_sms_enabled_single_shift_tables);
+        sEnabledLockingShiftTables = r.getIntArray(R.array.config_sms_enabled_locking_shift_tables);
+        int numTables = sLanguageTables.length;
+        int numShiftTables = sLanguageShiftTables.length;
+        if (numTables != numShiftTables) {
+            Log.e(TAG, "Error: language tables array length " + numTables +
+                    " != shift tables array length " + numShiftTables);
+        }
+
+        if (sEnabledSingleShiftTables.length > 0) {
+            sHighestEnabledSingleShiftCode =
+                    sEnabledSingleShiftTables[sEnabledSingleShiftTables.length-1];
+        } else {
+            sHighestEnabledSingleShiftCode = 0;
+        }
+
+        sCharsToGsmTables = new SparseIntArray[numTables];
+        for (int i = 0; i < numTables; i++) {
+            String table = sLanguageTables[i];
+
+            int tableLen = table.length();
+            if (tableLen != 0 && tableLen != 128) {
+                Log.e(TAG, "Error: language tables index " + i +
+                        " length " + tableLen + " (expected 128 or 0)");
+            }
+
+            SparseIntArray charToGsmTable = new SparseIntArray(tableLen);
+            sCharsToGsmTables[i] = charToGsmTable;
+            for (int j = 0; j < tableLen; j++) {
+                char c = table.charAt(j);
+                charToGsmTable.put(c, j);
+            }
+        }
+
+        sCharsToShiftTables = new SparseIntArray[numTables];
+        for (int i = 0; i < numShiftTables; i++) {
+            String shiftTable = sLanguageShiftTables[i];
+
+            int shiftTableLen = shiftTable.length();
+            if (shiftTableLen != 0 && shiftTableLen != 128) {
+                Log.e(TAG, "Error: language shift tables index " + i +
+                        " length " + shiftTableLen + " (expected 128 or 0)");
+            }
+
+            SparseIntArray charToShiftTable = new SparseIntArray(shiftTableLen);
+            sCharsToShiftTables[i] = charToShiftTable;
+            for (int j = 0; j < shiftTableLen; j++) {
+                char c = shiftTable.charAt(j);
+                if (c != ' ') {
+                    charToShiftTable.put(c, j);
+                }
+            }
+        }
+    }
 }
diff --git a/telephony/java/com/android/internal/telephony/ISms.aidl b/telephony/java/com/android/internal/telephony/ISms.aidl
index 90de5e1..735f986 100644
--- a/telephony/java/com/android/internal/telephony/ISms.aidl
+++ b/telephony/java/com/android/internal/telephony/ISms.aidl
@@ -170,4 +170,32 @@
      */
     boolean disableCellBroadcast(int messageIdentifier);
 
+    /**
+     * Enable reception of cell broadcast (SMS-CB) messages with the given
+     * message identifier range. Note that if two different clients enable
+     * a message identifier range, they must both disable it for the device
+     * to stop receiving those messages.
+     *
+     * @param startMessageId first message identifier as specified in TS 23.041
+     * @param endMessageId last message identifier as specified in TS 23.041
+     * @return true if successful, false otherwise
+     *
+     * @see #disableCellBroadcastRange(int, int)
+     */
+    boolean enableCellBroadcastRange(int startMessageId, int endMessageId);
+
+    /**
+     * Disable reception of cell broadcast (SMS-CB) messages with the given
+     * message identifier range. Note that if two different clients enable
+     * a message identifier range, they must both disable it for the device
+     * to stop receiving those messages.
+     *
+     * @param startMessageId first message identifier as specified in TS 23.041
+     * @param endMessageId last message identifier as specified in TS 23.041
+     * @return true if successful, false otherwise
+     *
+     * @see #enableCellBroadcastRange(int, int)
+     */
+    boolean disableCellBroadcastRange(int startMessageId, int endMessageId);
+
 }
diff --git a/telephony/java/com/android/internal/telephony/IccPhoneBookInterfaceManager.java b/telephony/java/com/android/internal/telephony/IccPhoneBookInterfaceManager.java
index 2f22d74..45562ca9 100644
--- a/telephony/java/com/android/internal/telephony/IccPhoneBookInterfaceManager.java
+++ b/telephony/java/com/android/internal/telephony/IccPhoneBookInterfaceManager.java
@@ -24,6 +24,7 @@
 import android.os.ServiceManager;
 
 import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 /**
  * SimPhoneBookInterfaceManager to provide an inter-process communication to
@@ -63,14 +64,14 @@
                                     " total " + recordSize[1] +
                                     " #record " + recordSize[2]);
                         }
-                        mLock.notifyAll();
+                        notifyPending(ar);
                     }
                     break;
                 case EVENT_UPDATE_DONE:
                     ar = (AsyncResult) msg.obj;
                     synchronized (mLock) {
                         success = (ar.exception == null);
-                        mLock.notifyAll();
+                        notifyPending(ar);
                     }
                     break;
                 case EVENT_LOAD_DONE:
@@ -84,11 +85,20 @@
                                 records.clear();
                             }
                         }
-                        mLock.notifyAll();
+                        notifyPending(ar);
                     }
                     break;
             }
         }
+
+        private void notifyPending(AsyncResult ar) {
+            if (ar.userObj == null) {
+                return;
+            }
+            AtomicBoolean status = (AtomicBoolean) ar.userObj;
+            status.set(true);
+            mLock.notifyAll();
+        }
     };
 
     public IccPhoneBookInterfaceManager(PhoneBase phone) {
@@ -150,15 +160,12 @@
         synchronized(mLock) {
             checkThread();
             success = false;
-            Message response = mBaseHandler.obtainMessage(EVENT_UPDATE_DONE);
+            AtomicBoolean status = new AtomicBoolean(false);
+            Message response = mBaseHandler.obtainMessage(EVENT_UPDATE_DONE, status);
             AdnRecord oldAdn = new AdnRecord(oldTag, oldPhoneNumber);
             AdnRecord newAdn = new AdnRecord(newTag, newPhoneNumber);
             adnCache.updateAdnBySearch(efid, oldAdn, newAdn, pin2, response);
-            try {
-                mLock.wait();
-            } catch (InterruptedException e) {
-                logd("interrupted while trying to update by search");
-            }
+            waitForResult(status);
         }
         return success;
     }
@@ -197,14 +204,11 @@
         synchronized(mLock) {
             checkThread();
             success = false;
-            Message response = mBaseHandler.obtainMessage(EVENT_UPDATE_DONE);
+            AtomicBoolean status = new AtomicBoolean(false);
+            Message response = mBaseHandler.obtainMessage(EVENT_UPDATE_DONE, status);
             AdnRecord newAdn = new AdnRecord(newTag, newPhoneNumber);
             adnCache.updateAdnByIndex(efid, newAdn, index, pin2, response);
-            try {
-                mLock.wait();
-            } catch (InterruptedException e) {
-                logd("interrupted while trying to update by index");
-            }
+            waitForResult(status);
         }
         return success;
     }
@@ -243,15 +247,12 @@
 
         synchronized(mLock) {
             checkThread();
-            Message response = mBaseHandler.obtainMessage(EVENT_LOAD_DONE);
+            AtomicBoolean status = new AtomicBoolean(false);
+            Message response = mBaseHandler.obtainMessage(EVENT_LOAD_DONE, status);
             adnCache.requestLoadAllAdnLike(efid, adnCache.extensionEfForEf(efid), response);
-            try {
-                mLock.wait();
-            } catch (InterruptedException e) {
-                logd("interrupted while trying to load from the SIM");
-            }
+            waitForResult(status);
         }
-            return records;
+        return records;
     }
 
     protected void checkThread() {
@@ -265,6 +266,16 @@
         }
     }
 
+    protected void waitForResult(AtomicBoolean status) {
+        while (!status.get()) {
+            try {
+                mLock.wait();
+            } catch (InterruptedException e) {
+                logd("interrupted while trying to update by search");
+            }
+        }
+    }
+
     private int updateEfForIccType(int efid) {
         // Check if we are trying to read ADN records
         if (efid == IccConstants.EF_ADN) {
diff --git a/telephony/java/com/android/internal/telephony/IccSmsInterfaceManagerProxy.java b/telephony/java/com/android/internal/telephony/IccSmsInterfaceManagerProxy.java
index 5049249..54de508 100644
--- a/telephony/java/com/android/internal/telephony/IccSmsInterfaceManagerProxy.java
+++ b/telephony/java/com/android/internal/telephony/IccSmsInterfaceManagerProxy.java
@@ -76,4 +76,13 @@
         return mIccSmsInterfaceManager.disableCellBroadcast(messageIdentifier);
     }
 
+    public boolean enableCellBroadcastRange(int startMessageId, int endMessageId)
+            throws android.os.RemoteException {
+        return mIccSmsInterfaceManager.enableCellBroadcastRange(startMessageId, endMessageId);
+    }
+
+    public boolean disableCellBroadcastRange(int startMessageId, int endMessageId)
+            throws android.os.RemoteException {
+        return mIccSmsInterfaceManager.disableCellBroadcastRange(startMessageId, endMessageId);
+    }
 }
diff --git a/telephony/java/com/android/internal/telephony/IccUtils.java b/telephony/java/com/android/internal/telephony/IccUtils.java
index 5bd7523..2244ac4 100644
--- a/telephony/java/com/android/internal/telephony/IccUtils.java
+++ b/telephony/java/com/android/internal/telephony/IccUtils.java
@@ -446,7 +446,6 @@
         int colorNumber = data[valueIndex++] & 0xFF;
         int clutOffset = ((data[valueIndex++] & 0xFF) << 8)
                 | (data[valueIndex++] & 0xFF);
-        length = length - 6;
 
         int[] colorIndexArray = getCLUT(data, clutOffset, colorNumber);
         if (true == transparency) {
diff --git a/telephony/java/com/android/internal/telephony/IntRangeManager.java b/telephony/java/com/android/internal/telephony/IntRangeManager.java
new file mode 100644
index 0000000..970bc44
--- /dev/null
+++ b/telephony/java/com/android/internal/telephony/IntRangeManager.java
@@ -0,0 +1,568 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.telephony;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+
+/**
+ * Clients can enable reception of SMS-CB messages for specific ranges of
+ * message identifiers (channels). This class keeps track of the currently
+ * enabled message identifiers and calls abstract methods to update the
+ * radio when the range of enabled message identifiers changes.
+ *
+ * An update is a call to {@link #startUpdate} followed by zero or more
+ * calls to {@link #addRange} followed by a call to {@link #finishUpdate}.
+ * Calls to {@link #enableRange} and {@link #disableRange} will perform
+ * an incremental update operation if the enabled ranges have changed.
+ * A full update operation (i.e. after a radio reset) can be performed
+ * by a call to {@link #updateRanges}.
+ *
+ * Clients are identified by String (the name associated with the User ID
+ * of the caller) so that a call to remove a range can be mapped to the
+ * client that enabled that range (or else rejected).
+ */
+public abstract class IntRangeManager {
+
+    /**
+     * Initial capacity for IntRange clients array list. There will be
+     * few cell broadcast listeners on a typical device, so this can be small.
+     */
+    private static final int INITIAL_CLIENTS_ARRAY_SIZE = 4;
+
+    /**
+     * One or more clients forming the continuous range [startId, endId].
+     * <p>When a client is added, the IntRange may merge with one or more
+     * adjacent IntRanges to form a single combined IntRange.
+     * <p>When a client is removed, the IntRange may divide into several
+     * non-contiguous IntRanges.
+     */
+    private class IntRange {
+        int startId;
+        int endId;
+        // sorted by earliest start id
+        final ArrayList<ClientRange> clients;
+
+        /**
+         * Create a new IntRange with a single client.
+         * @param startId the first id included in the range
+         * @param endId the last id included in the range
+         * @param client the client requesting the enabled range
+         */
+        IntRange(int startId, int endId, String client) {
+            this.startId = startId;
+            this.endId = endId;
+            clients = new ArrayList<ClientRange>(INITIAL_CLIENTS_ARRAY_SIZE);
+            clients.add(new ClientRange(startId, endId, client));
+        }
+
+        /**
+         * Create a new IntRange for an existing ClientRange.
+         * @param clientRange the initial ClientRange to add
+         */
+        IntRange(ClientRange clientRange) {
+            startId = clientRange.startId;
+            endId = clientRange.endId;
+            clients = new ArrayList<ClientRange>(INITIAL_CLIENTS_ARRAY_SIZE);
+            clients.add(clientRange);
+        }
+
+        /**
+         * Create a new IntRange from an existing IntRange. This is used for
+         * removing a ClientRange, because new IntRanges may need to be created
+         * for any gaps that open up after the ClientRange is removed. A copy
+         * is made of the elements of the original IntRange preceding the element
+         * that is being removed. The following elements will be added to this
+         * IntRange or to a new IntRange when a gap is found.
+         * @param intRange the original IntRange to copy elements from
+         * @param numElements the number of elements to copy from the original
+         */
+        IntRange(IntRange intRange, int numElements) {
+            this.startId = intRange.startId;
+            this.endId = intRange.endId;
+            this.clients = new ArrayList<ClientRange>(intRange.clients.size());
+            for (int i=0; i < numElements; i++) {
+                this.clients.add(intRange.clients.get(i));
+            }
+        }
+
+        /**
+         * Insert new ClientRange in order by start id.
+         * <p>If the new ClientRange is known to be sorted before or after the
+         * existing ClientRanges, or at a particular index, it can be added
+         * to the clients array list directly, instead of via this method.
+         * <p>Note that this can be changed from linear to binary search if the
+         * number of clients grows large enough that it would make a difference.
+         * @param range the new ClientRange to insert
+         */
+        void insert(ClientRange range) {
+            int len = clients.size();
+            for (int i=0; i < len; i++) {
+                ClientRange nextRange = clients.get(i);
+                if (range.startId <= nextRange.startId) {
+                    // ignore duplicate ranges from the same client
+                    if (!range.equals(nextRange)) {
+                        clients.add(i, range);
+                    }
+                    return;
+                }
+            }
+            clients.add(range);    // append to end of list
+        }
+    }
+
+    /**
+     * The message id range for a single client.
+     */
+    private class ClientRange {
+        final int startId;
+        final int endId;
+        final String client;
+
+        ClientRange(int startId, int endId, String client) {
+            this.startId = startId;
+            this.endId = endId;
+            this.client = client;
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (o != null && o instanceof ClientRange) {
+                ClientRange other = (ClientRange) o;
+                return startId == other.startId &&
+                        endId == other.endId &&
+                        client.equals(other.client);
+            } else {
+                return false;
+            }
+        }
+
+        @Override
+        public int hashCode() {
+            return (startId * 31 + endId) * 31 + client.hashCode();
+        }
+    }
+
+    /**
+     * List of integer ranges, one per client, sorted by start id.
+     */
+    private ArrayList<IntRange> mRanges = new ArrayList<IntRange>();
+
+    protected IntRangeManager() {}
+
+    /**
+     * Enable a range for the specified client and update ranges
+     * if necessary. If {@link #finishUpdate} returns failure,
+     * false is returned and the range is not added.
+     *
+     * @param startId the first id included in the range
+     * @param endId the last id included in the range
+     * @param client the client requesting the enabled range
+     * @return true if successful, false otherwise
+     */
+    public synchronized boolean enableRange(int startId, int endId, String client) {
+        int len = mRanges.size();
+
+        // empty range list: add the initial IntRange
+        if (len == 0) {
+            if (tryAddSingleRange(startId, endId, true)) {
+                mRanges.add(new IntRange(startId, endId, client));
+                return true;
+            } else {
+                return false;   // failed to update radio
+            }
+        }
+
+        for (int startIndex = 0; startIndex < len; startIndex++) {
+            IntRange range = mRanges.get(startIndex);
+            if (startId < range.startId) {
+                // test if new range completely precedes this range
+                // note that [1, 4] and [5, 6] coalesce to [1, 6]
+                if ((endId + 1) < range.startId) {
+                    // insert new int range before previous first range
+                    if (tryAddSingleRange(startId, endId, true)) {
+                        mRanges.add(startIndex, new IntRange(startId, endId, client));
+                        return true;
+                    } else {
+                        return false;   // failed to update radio
+                    }
+                } else if (endId <= range.endId) {
+                    // extend the start of this range
+                    if (tryAddSingleRange(startId, range.startId - 1, true)) {
+                        range.startId = startId;
+                        range.clients.add(0, new ClientRange(startId, endId, client));
+                        return true;
+                    } else {
+                        return false;   // failed to update radio
+                    }
+                } else {
+                    // find last range that can coalesce into the new combined range
+                    for (int endIndex = startIndex+1; endIndex < len; endIndex++) {
+                        IntRange endRange = mRanges.get(endIndex);
+                        if ((endId + 1) < endRange.startId) {
+                            // try to add entire new range
+                            if (tryAddSingleRange(startId, endId, true)) {
+                                range.startId = startId;
+                                range.endId = endId;
+                                // insert new ClientRange before existing ranges
+                                range.clients.add(0, new ClientRange(startId, endId, client));
+                                // coalesce range with following ranges up to endIndex-1
+                                // remove each range after adding its elements, so the index
+                                // of the next range to join is always startIndex+1.
+                                // i is the index if no elements were removed: we only care
+                                // about the number of loop iterations, not the value of i.
+                                int joinIndex = startIndex + 1;
+                                for (int i = joinIndex; i < endIndex; i++) {
+                                    IntRange joinRange = mRanges.get(joinIndex);
+                                    range.clients.addAll(joinRange.clients);
+                                    mRanges.remove(joinRange);
+                                }
+                                return true;
+                            } else {
+                                return false;   // failed to update radio
+                            }
+                        } else if (endId <= endRange.endId) {
+                            // add range from start id to start of last overlapping range,
+                            // values from endRange.startId to endId are already enabled
+                            if (tryAddSingleRange(startId, endRange.startId - 1, true)) {
+                                range.startId = startId;
+                                range.endId = endRange.endId;
+                                // insert new ClientRange before existing ranges
+                                range.clients.add(0, new ClientRange(startId, endId, client));
+                                // coalesce range with following ranges up to endIndex
+                                // remove each range after adding its elements, so the index
+                                // of the next range to join is always startIndex+1.
+                                // i is the index if no elements were removed: we only care
+                                // about the number of loop iterations, not the value of i.
+                                int joinIndex = startIndex + 1;
+                                for (int i = joinIndex; i <= endIndex; i++) {
+                                    IntRange joinRange = mRanges.get(joinIndex);
+                                    range.clients.addAll(joinRange.clients);
+                                    mRanges.remove(joinRange);
+                                }
+                                return true;
+                            } else {
+                                return false;   // failed to update radio
+                            }
+                        }
+                    }
+
+                    // endId extends past all existing IntRanges: combine them all together
+                    if (tryAddSingleRange(startId, endId, true)) {
+                        range.startId = startId;
+                        range.endId = endId;
+                        // insert new ClientRange before existing ranges
+                        range.clients.add(0, new ClientRange(startId, endId, client));
+                        // coalesce range with following ranges up to len-1
+                        // remove each range after adding its elements, so the index
+                        // of the next range to join is always startIndex+1.
+                        // i is the index if no elements were removed: we only care
+                        // about the number of loop iterations, not the value of i.
+                        int joinIndex = startIndex + 1;
+                        for (int i = joinIndex; i < len; i++) {
+                            IntRange joinRange = mRanges.get(joinIndex);
+                            range.clients.addAll(joinRange.clients);
+                            mRanges.remove(joinRange);
+                        }
+                        return true;
+                    } else {
+                        return false;   // failed to update radio
+                    }
+                }
+            } else if ((startId + 1) <= range.endId) {
+                if (endId <= range.endId) {
+                    // completely contained in existing range; no radio changes
+                    range.insert(new ClientRange(startId, endId, client));
+                    return true;
+                } else {
+                    // find last range that can coalesce into the new combined range
+                    int endIndex = startIndex;
+                    for (int testIndex = startIndex+1; testIndex < len; testIndex++) {
+                        IntRange testRange = mRanges.get(testIndex);
+                        if ((endId + 1) < testRange.startId) {
+                            break;
+                        } else {
+                            endIndex = testIndex;
+                        }
+                    }
+                    // no adjacent IntRanges to combine
+                    if (endIndex == startIndex) {
+                        // add range from range.endId+1 to endId,
+                        // values from startId to range.endId are already enabled
+                        if (tryAddSingleRange(range.endId + 1, endId, true)) {
+                            range.endId = endId;
+                            range.insert(new ClientRange(startId, endId, client));
+                            return true;
+                        } else {
+                            return false;   // failed to update radio
+                        }
+                    }
+                    // get last range to coalesce into start range
+                    IntRange endRange = mRanges.get(endIndex);
+                    // Values from startId to range.endId have already been enabled.
+                    // if endId > endRange.endId, then enable range from range.endId+1 to endId,
+                    // else enable range from range.endId+1 to endRange.startId-1, because
+                    // values from endRange.startId to endId have already been added.
+                    int newRangeEndId = (endId <= endRange.endId) ? endRange.startId - 1 : endId;
+                    if (tryAddSingleRange(range.endId + 1, newRangeEndId, true)) {
+                        range.endId = endId;
+                        // insert new ClientRange in place
+                        range.insert(new ClientRange(startId, endId, client));
+                        // coalesce range with following ranges up to endIndex-1
+                        // remove each range after adding its elements, so the index
+                        // of the next range to join is always startIndex+1 (joinIndex).
+                        // i is the index if no elements had been removed: we only care
+                        // about the number of loop iterations, not the value of i.
+                        int joinIndex = startIndex + 1;
+                        for (int i = joinIndex; i < endIndex; i++) {
+                            IntRange joinRange = mRanges.get(joinIndex);
+                            range.clients.addAll(joinRange.clients);
+                            mRanges.remove(joinRange);
+                        }
+                        return true;
+                    } else {
+                        return false;   // failed to update radio
+                    }
+                }
+            }
+        }
+
+        // append new range after existing IntRanges
+        if (tryAddSingleRange(startId, endId, true)) {
+            mRanges.add(new IntRange(startId, endId, client));
+            return true;
+        } else {
+            return false;   // failed to update radio
+        }
+    }
+
+    /**
+     * Disable a range for the specified client and update ranges
+     * if necessary. If {@link #finishUpdate} returns failure,
+     * false is returned and the range is not removed.
+     *
+     * @param startId the first id included in the range
+     * @param endId the last id included in the range
+     * @param client the client requesting to disable the range
+     * @return true if successful, false otherwise
+     */
+    public synchronized boolean disableRange(int startId, int endId, String client) {
+        int len = mRanges.size();
+
+        for (int i=0; i < len; i++) {
+            IntRange range = mRanges.get(i);
+            if (startId < range.startId) {
+                return false;   // not found
+            } else if (endId <= range.endId) {
+                // found the IntRange that encloses the client range, if any
+                // search for it in the clients list
+                ArrayList<ClientRange> clients = range.clients;
+
+                // handle common case of IntRange containing one ClientRange
+                int crLength = clients.size();
+                if (crLength == 1) {
+                    ClientRange cr = clients.get(0);
+                    if (cr.startId == startId && cr.endId == endId && cr.client.equals(client)) {
+                        // disable range in radio then remove the entire IntRange
+                        if (tryAddSingleRange(startId, endId, false)) {
+                            mRanges.remove(i);
+                            return true;
+                        } else {
+                            return false;   // failed to update radio
+                        }
+                    } else {
+                        return false;   // not found
+                    }
+                }
+
+                // several ClientRanges: remove one, potentially splitting into many IntRanges.
+                // Save the original start and end id for the original IntRange
+                // in case the radio update fails and we have to revert it. If the
+                // update succeeds, we remove the client range and insert the new IntRanges.
+                int largestEndId = Integer.MIN_VALUE;  // largest end identifier found
+                boolean updateStarted = false;
+
+                for (int crIndex=0; crIndex < crLength; crIndex++) {
+                    ClientRange cr = clients.get(crIndex);
+                    if (cr.startId == startId && cr.endId == endId && cr.client.equals(client)) {
+                        // found the ClientRange to remove, check if it's the last in the list
+                        if (crIndex == crLength - 1) {
+                            if (range.endId == largestEndId) {
+                                // no channels to remove from radio; return success
+                                clients.remove(crIndex);
+                                return true;
+                            } else {
+                                // disable the channels at the end and lower the end id
+                                if (tryAddSingleRange(largestEndId + 1, range.endId, false)) {
+                                    clients.remove(crIndex);
+                                    range.endId = largestEndId;
+                                    return true;
+                                } else {
+                                    return false;
+                                }
+                            }
+                        }
+
+                        // copy the IntRange so that we can remove elements and modify the
+                        // start and end id's in the copy, leaving the original unmodified
+                        // until after the radio update succeeds
+                        IntRange rangeCopy = new IntRange(range, crIndex);
+
+                        if (crIndex == 0) {
+                            // removing the first ClientRange, so we may need to increase
+                            // the start id of the IntRange.
+                            // We know there are at least two ClientRanges in the list,
+                            // so clients.get(1) should always succeed.
+                            int nextStartId = clients.get(1).startId;
+                            if (nextStartId != range.startId) {
+                                startUpdate();
+                                updateStarted = true;
+                                addRange(range.startId, nextStartId - 1, false);
+                                rangeCopy.startId = nextStartId;
+                            }
+                            // init largestEndId
+                            largestEndId = clients.get(1).endId;
+                        }
+
+                        // go through remaining ClientRanges, creating new IntRanges when
+                        // there is a gap in the sequence. After radio update succeeds,
+                        // remove the original IntRange and append newRanges to mRanges.
+                        // Otherwise, leave the original IntRange in mRanges and return false.
+                        ArrayList<IntRange> newRanges = new ArrayList<IntRange>();
+
+                        IntRange currentRange = rangeCopy;
+                        for (int nextIndex = crIndex + 1; nextIndex < crLength; nextIndex++) {
+                            ClientRange nextCr = clients.get(nextIndex);
+                            if (nextCr.startId > largestEndId + 1) {
+                                if (!updateStarted) {
+                                    startUpdate();
+                                    updateStarted = true;
+                                }
+                                addRange(largestEndId + 1, nextCr.startId - 1, false);
+                                currentRange.endId = largestEndId;
+                                newRanges.add(currentRange);
+                                currentRange = new IntRange(nextCr);
+                            } else {
+                                currentRange.clients.add(nextCr);
+                            }
+                            if (nextCr.endId > largestEndId) {
+                                largestEndId = nextCr.endId;
+                            }
+                        }
+
+                        // remove any channels between largestEndId and endId
+                        if (largestEndId < endId) {
+                            if (!updateStarted) {
+                                startUpdate();
+                                updateStarted = true;
+                            }
+                            addRange(largestEndId + 1, endId, false);
+                            currentRange.endId = largestEndId;
+                        }
+                        newRanges.add(currentRange);
+
+                        if (updateStarted && !finishUpdate()) {
+                            return false;   // failed to update radio
+                        }
+
+                        // replace the original IntRange with newRanges
+                        mRanges.remove(i);
+                        mRanges.addAll(i, newRanges);
+                        return true;
+                    } else {
+                        // not the ClientRange to remove; save highest end ID seen so far
+                        if (cr.endId > largestEndId) {
+                            largestEndId = cr.endId;
+                        }
+                    }
+                }
+            }
+        }
+
+        return false;   // not found
+    }
+
+    /**
+     * Perform a complete update operation (enable all ranges). Useful
+     * after a radio reset. Calls {@link #startUpdate}, followed by zero or
+     * more calls to {@link #addRange}, followed by {@link #finishUpdate}.
+     * @return true if successful, false otherwise
+     */
+    public boolean updateRanges() {
+        startUpdate();
+        Iterator<IntRange> iterator = mRanges.iterator();
+        if (iterator.hasNext()) {
+            IntRange range = iterator.next();
+            int start = range.startId;
+            int end = range.endId;
+            // accumulate ranges of [startId, endId]
+            while (iterator.hasNext()) {
+                IntRange nextNode = iterator.next();
+                // [startIdA, endIdA], [endIdA + 1, endIdB] -> [startIdA, endIdB]
+                if (nextNode.startId <= (end + 1)) {
+                    if (nextNode.endId > end) {
+                        end = nextNode.endId;
+                    }
+                } else {
+                    addRange(start, end, true);
+                    start = nextNode.startId;
+                    end = nextNode.endId;
+                }
+            }
+            // add final range
+            addRange(start, end, true);
+        }
+        return finishUpdate();
+    }
+
+    /**
+     * Enable or disable a single range of message identifiers.
+     * @param startId the first id included in the range
+     * @param endId the last id included in the range
+     * @param selected true to enable range, false to disable range
+     * @return true if successful, false otherwise
+     */
+    private boolean tryAddSingleRange(int startId, int endId, boolean selected) {
+        startUpdate();
+        addRange(startId, endId, selected);
+        return finishUpdate();
+    }
+
+    /**
+     * Called when the list of enabled ranges has changed. This will be
+     * followed by zero or more calls to {@link #addRange} followed by
+     * a call to {@link #finishUpdate}.
+     */
+    protected abstract void startUpdate();
+
+    /**
+     * Called after {@link #startUpdate} to indicate a range of enabled
+     * or disabled values.
+     *
+     * @param startId the first id included in the range
+     * @param endId the last id included in the range
+     * @param selected true to enable range, false to disable range
+     */
+    protected abstract void addRange(int startId, int endId, boolean selected);
+
+    /**
+     * Called to indicate the end of a range update started by the
+     * previous call to {@link #startUpdate}.
+     * @return true if successful, false otherwise
+     */
+    protected abstract boolean finishUpdate();
+}
diff --git a/telephony/java/com/android/internal/telephony/RIL.java b/telephony/java/com/android/internal/telephony/RIL.java
index f5490016..e059555 100644
--- a/telephony/java/com/android/internal/telephony/RIL.java
+++ b/telephony/java/com/android/internal/telephony/RIL.java
@@ -1315,7 +1315,8 @@
                 : RILConstants.SETUP_DATA_AUTH_NONE;
 
         setupDataCall(Integer.toString(radioTechnology), profile, apn, user,
-                password, Integer.toString(authType), result);
+                password, Integer.toString(authType),
+                RILConstants.SETUP_DATA_PROTOCOL_IP, result);
 
     }
 
@@ -1327,18 +1328,14 @@
         deactivateDataCall(cid, result);
     }
 
-    /**
-     * The preferred new alternative to setupDefaultPDP that is
-     * CDMA-compatible.
-     *
-     */
     public void
     setupDataCall(String radioTechnology, String profile, String apn,
-            String user, String password, String authType, Message result) {
+            String user, String password, String authType, String protocol,
+            Message result) {
         RILRequest rr
                 = RILRequest.obtain(RIL_REQUEST_SETUP_DATA_CALL, result);
 
-        rr.mp.writeInt(6);
+        rr.mp.writeInt(7);
 
         rr.mp.writeString(radioTechnology);
         rr.mp.writeString(profile);
@@ -1346,11 +1343,12 @@
         rr.mp.writeString(user);
         rr.mp.writeString(password);
         rr.mp.writeString(authType);
+        rr.mp.writeString(protocol);
 
         if (RILJ_LOGD) riljLog(rr.serialString() + "> "
                 + requestToString(rr.mRequest) + " " + radioTechnology + " "
                 + profile + " " + apn + " " + user + " "
-                + password + " " + authType);
+                + password + " " + authType + " " + protocol);
 
         send(rr);
     }
@@ -2980,7 +2978,11 @@
             dataCall.active = p.readInt();
             dataCall.type = p.readString();
             dataCall.apn = p.readString();
-            dataCall.address = p.readString();
+            String address = p.readString();
+            if (address != null) {
+                address = address.split(" ")[0];
+            }
+            dataCall.address = address;
 
             response.add(dataCall);
         }
diff --git a/telephony/java/com/android/internal/telephony/RILConstants.java b/telephony/java/com/android/internal/telephony/RILConstants.java
index 888f721..0686791 100644
--- a/telephony/java/com/android/internal/telephony/RILConstants.java
+++ b/telephony/java/com/android/internal/telephony/RILConstants.java
@@ -91,11 +91,16 @@
     /* Setup a packet data connection. See ril.h RIL_REQUEST_SETUP_DATA_CALL */
     int SETUP_DATA_TECH_CDMA      = 0;
     int SETUP_DATA_TECH_GSM       = 1;
+
     int SETUP_DATA_AUTH_NONE      = 0;
     int SETUP_DATA_AUTH_PAP       = 1;
     int SETUP_DATA_AUTH_CHAP      = 2;
     int SETUP_DATA_AUTH_PAP_CHAP  = 3;
 
+    String SETUP_DATA_PROTOCOL_IP     = "IP";
+    String SETUP_DATA_PROTOCOL_IPV6   = "IPV6";
+    String SETUP_DATA_PROTOCOL_IPV4V6 = "IPV4V6";
+
 /*
 cat include/telephony/ril.h | \
    egrep '^#define' | \
diff --git a/telephony/java/com/android/internal/telephony/SMSDispatcher.java b/telephony/java/com/android/internal/telephony/SMSDispatcher.java
old mode 100755
new mode 100644
index ad34550..69dd029
--- a/telephony/java/com/android/internal/telephony/SMSDispatcher.java
+++ b/telephony/java/com/android/internal/telephony/SMSDispatcher.java
@@ -32,11 +32,9 @@
 import android.database.SQLException;
 import android.net.Uri;
 import android.os.AsyncResult;
-import android.os.Environment;
 import android.os.Handler;
 import android.os.Message;
 import android.os.PowerManager;
-import android.os.StatFs;
 import android.provider.Telephony;
 import android.provider.Telephony.Sms.Intents;
 import android.provider.Settings;
@@ -878,37 +876,6 @@
     protected abstract void sendMultipartSms (SmsTracker tracker);
 
     /**
-     * Activate or deactivate cell broadcast SMS.
-     *
-     * @param activate
-     *            0 = activate, 1 = deactivate
-     * @param response
-     *            Callback message is empty on completion
-     */
-    protected abstract void activateCellBroadcastSms(int activate, Message response);
-
-    /**
-     * Query the current configuration of cell broadcast SMS.
-     *
-     * @param response
-     *            Callback message contains the configuration from the modem on completion
-     *            @see #setCellBroadcastConfig
-     */
-    protected abstract void getCellBroadcastSmsConfig(Message response);
-
-    /**
-     * Configure cell broadcast SMS.
-     *
-     * @param configValuesArray
-     *          The first element defines the number of triples that follow.
-     *          A triple is made up of the service category, the language identifier
-     *          and a boolean that specifies whether the category is set active.
-     * @param response
-     *            Callback message is empty on completion
-     */
-    protected abstract void setCellBroadcastConfig(int[] configValuesArray, Message response);
-
-    /**
      * Send an acknowledge message.
      * @param success indicates that last message was successfully received.
      * @param result result code indicating any error
@@ -1014,14 +981,21 @@
 
     protected abstract void handleBroadcastSms(AsyncResult ar);
 
-    protected void dispatchBroadcastPdus(byte[][] pdus) {
-        Intent intent = new Intent("android.provider.telephony.SMS_CB_RECEIVED");
-        intent.putExtra("pdus", pdus);
+    protected void dispatchBroadcastPdus(byte[][] pdus, boolean isEmergencyMessage) {
+        if (isEmergencyMessage) {
+            Intent intent = new Intent(Intents.SMS_EMERGENCY_CB_RECEIVED_ACTION);
+            intent.putExtra("pdus", pdus);
+            if (Config.LOGD)
+                Log.d(TAG, "Dispatching " + pdus.length + " emergency SMS CB pdus");
 
-        if (Config.LOGD)
-            Log.d(TAG, "Dispatching " + pdus.length + " SMS CB pdus");
+            dispatch(intent, "android.permission.RECEIVE_EMERGENCY_BROADCAST");
+        } else {
+            Intent intent = new Intent(Intents.SMS_CB_RECEIVED_ACTION);
+            intent.putExtra("pdus", pdus);
+            if (Config.LOGD)
+                Log.d(TAG, "Dispatching " + pdus.length + " SMS CB pdus");
 
-        dispatch(intent, "android.permission.RECEIVE_SMS");
+            dispatch(intent, "android.permission.RECEIVE_SMS");
+        }
     }
-
 }
diff --git a/telephony/java/com/android/internal/telephony/SmsHeader.java b/telephony/java/com/android/internal/telephony/SmsHeader.java
index 7872eec..9492e0e 100644
--- a/telephony/java/com/android/internal/telephony/SmsHeader.java
+++ b/telephony/java/com/android/internal/telephony/SmsHeader.java
@@ -30,7 +30,7 @@
  */
 public class SmsHeader {
 
-    // TODO(cleanup): this datastructure is generally referred to as
+    // TODO(cleanup): this data structure is generally referred to as
     // the 'user data header' or UDH, and so the class name should
     // change to reflect this...
 
@@ -66,6 +66,8 @@
     public static final int ELT_ID_HYPERLINK_FORMAT_ELEMENT           = 0x21;
     public static final int ELT_ID_REPLY_ADDRESS_ELEMENT              = 0x22;
     public static final int ELT_ID_ENHANCED_VOICE_MAIL_INFORMATION    = 0x23;
+    public static final int ELT_ID_NATIONAL_LANGUAGE_SINGLE_SHIFT     = 0x24;
+    public static final int ELT_ID_NATIONAL_LANGUAGE_LOCKING_SHIFT    = 0x25;
 
     public static final int PORT_WAP_PUSH = 2948;
     public static final int PORT_WAP_WSP  = 9200;
@@ -96,6 +98,12 @@
     public ConcatRef concatRef;
     public ArrayList<MiscElt> miscEltList = new ArrayList<MiscElt>();
 
+    /** 7 bit national language locking shift table, or 0 for GSM default 7 bit alphabet. */
+    public int languageTable;
+
+    /** 7 bit national language single shift table, or 0 for GSM default 7 bit extension table. */
+    public int languageShiftTable;
+
     public SmsHeader() {}
 
     /**
@@ -157,6 +165,12 @@
                 portAddrs.areEightBits = false;
                 smsHeader.portAddrs = portAddrs;
                 break;
+            case ELT_ID_NATIONAL_LANGUAGE_SINGLE_SHIFT:
+                smsHeader.languageShiftTable = inStream.read();
+                break;
+            case ELT_ID_NATIONAL_LANGUAGE_LOCKING_SHIFT:
+                smsHeader.languageTable = inStream.read();
+                break;
             default:
                 MiscElt miscElt = new MiscElt();
                 miscElt.id = id;
@@ -212,6 +226,16 @@
                 outStream.write(portAddrs.origPort & 0x00FF);
             }
         }
+        if (smsHeader.languageShiftTable != 0) {
+            outStream.write(ELT_ID_NATIONAL_LANGUAGE_SINGLE_SHIFT);
+            outStream.write(1);
+            outStream.write(smsHeader.languageShiftTable);
+        }
+        if (smsHeader.languageTable != 0) {
+            outStream.write(ELT_ID_NATIONAL_LANGUAGE_LOCKING_SHIFT);
+            outStream.write(1);
+            outStream.write(smsHeader.languageTable);
+        }
         for (MiscElt miscElt : smsHeader.miscEltList) {
             outStream.write(miscElt.id);
             outStream.write(miscElt.data.length);
@@ -243,6 +267,12 @@
             builder.append(", areEightBits=" + portAddrs.areEightBits);
             builder.append(" }");
         }
+        if (languageShiftTable != 0) {
+            builder.append(", languageShiftTable=" + languageShiftTable);
+        }
+        if (languageTable != 0) {
+            builder.append(", languageTable=" + languageTable);
+        }
         for (MiscElt miscElt : miscEltList) {
             builder.append(", MiscElt ");
             builder.append("{ id=" + miscElt.id);
diff --git a/telephony/java/com/android/internal/telephony/SmsMessageBase.java b/telephony/java/com/android/internal/telephony/SmsMessageBase.java
index af6c5f8..9f9d203 100644
--- a/telephony/java/com/android/internal/telephony/SmsMessageBase.java
+++ b/telephony/java/com/android/internal/telephony/SmsMessageBase.java
@@ -118,6 +118,16 @@
          */
         public int codeUnitSize;
 
+        /**
+         * The GSM national language table to use, or 0 for the default 7-bit alphabet.
+         */
+        public int languageTable;
+
+        /**
+         * The GSM national language shift table to use, or 0 for the default 7-bit extension table.
+         */
+        public int languageShiftTable;
+
         @Override
         public String toString() {
             return "TextEncodingDetails " +
@@ -125,6 +135,8 @@
                     ", codeUnitCount=" + codeUnitCount +
                     ", codeUnitsRemaining=" + codeUnitsRemaining +
                     ", codeUnitSize=" + codeUnitSize +
+                    ", languageTable=" + languageTable +
+                    ", languageShiftTable=" + languageShiftTable +
                     " }";
         }
     }
diff --git a/telephony/java/com/android/internal/telephony/WapPushOverSms.java b/telephony/java/com/android/internal/telephony/WapPushOverSms.java
old mode 100644
new mode 100755
diff --git a/telephony/java/com/android/internal/telephony/WspTypeDecoder.java b/telephony/java/com/android/internal/telephony/WspTypeDecoder.java
old mode 100644
new mode 100755
index c8dd718..73260fb
--- a/telephony/java/com/android/internal/telephony/WspTypeDecoder.java
+++ b/telephony/java/com/android/internal/telephony/WspTypeDecoder.java
@@ -194,6 +194,7 @@
 
     public static final String CONTENT_TYPE_B_PUSH_CO = "application/vnd.wap.coc";
     public static final String CONTENT_TYPE_B_MMS = "application/vnd.wap.mms-message";
+    public static final String CONTENT_TYPE_B_PUSH_SYNCML_NOTI = "application/vnd.syncml.notification";
 
     byte[] wspData;
     int    dataLength;
diff --git a/telephony/java/com/android/internal/telephony/cat/ResponseData.java b/telephony/java/com/android/internal/telephony/cat/ResponseData.java
index 677d66b..95f0399 100644
--- a/telephony/java/com/android/internal/telephony/cat/ResponseData.java
+++ b/telephony/java/com/android/internal/telephony/cat/ResponseData.java
@@ -111,7 +111,7 @@
                     int size = mInData.length();
 
                     byte[] tempData = GsmAlphabet
-                            .stringToGsm7BitPacked(mInData);
+                            .stringToGsm7BitPacked(mInData, 0, 0);
                     data = new byte[size];
                     // Since stringToGsm7BitPacked() set byte 0 in the
                     // returned byte array to the count of septets used...
diff --git a/telephony/java/com/android/internal/telephony/cdma/CDMAPhone.java b/telephony/java/com/android/internal/telephony/cdma/CDMAPhone.java
index 0865d6f..1efae21 100755
--- a/telephony/java/com/android/internal/telephony/cdma/CDMAPhone.java
+++ b/telephony/java/com/android/internal/telephony/cdma/CDMAPhone.java
@@ -737,7 +737,14 @@
         String number = null;
         SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
         // TODO: The default value of voicemail number should be read from a system property
-        number = sp.getString(VM_NUMBER_CDMA, "*86");
+
+        // Read platform settings for dynamic voicemail number
+        if (getContext().getResources().getBoolean(com.android.internal
+                .R.bool.config_telephony_use_own_number_for_voicemail)) {
+            number = sp.getString(VM_NUMBER_CDMA, getLine1Number());
+        } else {
+            number = sp.getString(VM_NUMBER_CDMA, "*86");
+        }
         return number;
     }
 
@@ -1156,7 +1163,8 @@
      * @param response Callback message is empty on completion
      */
     public void activateCellBroadcastSms(int activate, Message response) {
-        mSMS.activateCellBroadcastSms(activate, response);
+        Log.e(LOG_TAG, "[CDMAPhone] activateCellBroadcastSms() is obsolete; use SmsManager");
+        response.sendToTarget();
     }
 
     /**
@@ -1165,7 +1173,8 @@
      * @param response Callback message is empty on completion
      */
     public void getCellBroadcastSmsConfig(Message response) {
-        mSMS.getCellBroadcastSmsConfig(response);
+        Log.e(LOG_TAG, "[CDMAPhone] getCellBroadcastSmsConfig() is obsolete; use SmsManager");
+        response.sendToTarget();
     }
 
     /**
@@ -1174,7 +1183,8 @@
      * @param response Callback message is empty on completion
      */
     public void setCellBroadcastSmsConfig(int[] configValuesArray, Message response) {
-        mSMS.setCellBroadcastConfig(configValuesArray, response);
+        Log.e(LOG_TAG, "[CDMAPhone] setCellBroadcastSmsConfig() is obsolete; use SmsManager");
+        response.sendToTarget();
     }
 
     private static final String IS683A_FEATURE_CODE = "*228";
diff --git a/telephony/java/com/android/internal/telephony/cdma/CdmaDataConnection.java b/telephony/java/com/android/internal/telephony/cdma/CdmaDataConnection.java
index 95cb1c6..66f35e41 100644
--- a/telephony/java/com/android/internal/telephony/cdma/CdmaDataConnection.java
+++ b/telephony/java/com/android/internal/telephony/cdma/CdmaDataConnection.java
@@ -85,9 +85,12 @@
         // msg.obj will be returned in AsyncResult.userObj;
         Message msg = obtainMessage(EVENT_SETUP_DATA_CONNECTION_DONE, cp);
         msg.obj = cp;
-        phone.mCM.setupDataCall(Integer.toString(RILConstants.SETUP_DATA_TECH_CDMA),
-                Integer.toString(dataProfile), null, null,
-                null, Integer.toString(RILConstants.SETUP_DATA_AUTH_PAP_CHAP), msg);
+        phone.mCM.setupDataCall(
+                Integer.toString(RILConstants.SETUP_DATA_TECH_CDMA),
+                Integer.toString(dataProfile),
+                null, null, null,
+                Integer.toString(RILConstants.SETUP_DATA_AUTH_PAP_CHAP),
+                RILConstants.SETUP_DATA_PROTOCOL_IP, msg);
     }
 
     @Override
diff --git a/telephony/java/com/android/internal/telephony/cdma/CdmaDataConnectionTracker.java b/telephony/java/com/android/internal/telephony/cdma/CdmaDataConnectionTracker.java
index 9f2a44b..fa80063 100644
--- a/telephony/java/com/android/internal/telephony/cdma/CdmaDataConnectionTracker.java
+++ b/telephony/java/com/android/internal/telephony/cdma/CdmaDataConnectionTracker.java
@@ -432,7 +432,8 @@
         } else {
             types = mDefaultApnTypes;
         }
-        mActiveApn = new ApnSetting(0, "", "", "", "", "", "", "", "", "", "", 0, types);
+        mActiveApn = new ApnSetting(0, "", "", "", "", "", "", "", "", "", "",
+                                    0, types, "IP", "IP");
 
         Message msg = obtainMessage();
         msg.what = EVENT_DATA_SETUP_COMPLETE;
diff --git a/telephony/java/com/android/internal/telephony/cdma/CdmaSMSDispatcher.java b/telephony/java/com/android/internal/telephony/cdma/CdmaSMSDispatcher.java
old mode 100644
new mode 100755
index d6fc134..a04cafc
--- a/telephony/java/com/android/internal/telephony/cdma/CdmaSMSDispatcher.java
+++ b/telephony/java/com/android/internal/telephony/cdma/CdmaSMSDispatcher.java
@@ -42,6 +42,7 @@
 import com.android.internal.telephony.SmsMessageBase;
 import com.android.internal.telephony.SmsMessageBase.TextEncodingDetails;
 import com.android.internal.telephony.TelephonyProperties;
+import com.android.internal.telephony.WspTypeDecoder;
 import com.android.internal.telephony.cdma.sms.SmsEnvelope;
 import com.android.internal.telephony.cdma.sms.UserData;
 import com.android.internal.util.HexDump;
@@ -51,6 +52,8 @@
 import java.util.Arrays;
 import java.util.HashMap;
 
+import android.content.res.Resources;
+
 
 final class CdmaSMSDispatcher extends SMSDispatcher {
     private static final String TAG = "CDMA";
@@ -58,6 +61,9 @@
     private byte[] mLastDispatchedSmsFingerprint;
     private byte[] mLastAcknowledgedSmsFingerprint;
 
+    private boolean mCheckForDuplicatePortsInOmadmWapPush = Resources.getSystem().getBoolean(
+            com.android.internal.R.bool.config_duplicate_port_omadm_wappush);
+
     CdmaSMSDispatcher(CDMAPhone phone) {
         super(phone);
     }
@@ -245,6 +251,13 @@
             sourcePort |= 0xFF & pdu[index++];
             destinationPort = (0xFF & pdu[index++]) << 8;
             destinationPort |= 0xFF & pdu[index++];
+            // Some carriers incorrectly send duplicate port fields in omadm wap pushes.
+            // If configured, check for that here
+            if (mCheckForDuplicatePortsInOmadmWapPush) {
+                if (checkDuplicatePortOmadmWappush(pdu,index)) {
+                    index = index + 4; // skip duplicate port fields
+                }
+            }
         }
 
         // Lookup all other related parts
@@ -265,7 +278,7 @@
             if (cursorCount != totalSegments - 1) {
                 // We don't have all the parts yet, store this one away
                 ContentValues values = new ContentValues();
-                values.put("date", new Long(0));
+                values.put("date", (long) 0);
                 values.put("pdu", HexDump.toHexString(pdu, index, pdu.length - index));
                 values.put("address", address);
                 values.put("reference_number", referenceNumber);
@@ -468,21 +481,6 @@
         }
     }
 
-    /** {@inheritDoc} */
-    protected void activateCellBroadcastSms(int activate, Message response) {
-        mCm.setCdmaBroadcastActivation((activate == 0), response);
-    }
-
-    /** {@inheritDoc} */
-    protected void getCellBroadcastSmsConfig(Message response) {
-        mCm.getCdmaBroadcastConfig(response);
-    }
-
-    /** {@inheritDoc} */
-    protected void setCellBroadcastConfig(int[] configValuesArray, Message response) {
-        mCm.setCdmaBroadcastConfig(configValuesArray, response);
-    }
-
     protected void handleBroadcastSms(AsyncResult ar) {
         // Not supported
         Log.e(TAG, "Error! Not implemented for CDMA.");
@@ -503,4 +501,42 @@
             return CommandsInterface.CDMA_SMS_FAIL_CAUSE_ENCODING_PROBLEM;
         }
     }
+
+    /**
+     * Optional check to see if the received WapPush is an OMADM notification with erroneous
+     * extra port fields.
+     * - Some carriers make this mistake.
+     * ex: MSGTYPE-TotalSegments-CurrentSegment
+     *       -SourcePortDestPort-SourcePortDestPort-OMADM PDU
+     * @param origPdu The WAP-WDP PDU segment
+     * @param index Current Index while parsing the PDU.
+     * @return True if OrigPdu is OmaDM Push Message which has duplicate ports.
+     *         False if OrigPdu is NOT OmaDM Push Message which has duplicate ports.
+     */
+    private boolean checkDuplicatePortOmadmWappush(byte[] origPdu, int index) {
+        index += 4;
+        byte[] omaPdu = new byte[origPdu.length - index];
+        System.arraycopy(origPdu, index, omaPdu, 0, omaPdu.length);
+
+        WspTypeDecoder pduDecoder = new WspTypeDecoder(omaPdu);
+        int wspIndex = 2;
+
+        // Process header length field
+        if (pduDecoder.decodeUintvarInteger(wspIndex) == false) {
+            return false;
+        }
+
+        wspIndex += pduDecoder.getDecodedDataLength(); // advance to next field
+
+        // Process content type field
+        if (pduDecoder.decodeContentType(wspIndex) == false) {
+            return false;
+        }
+
+        String mimeType = pduDecoder.getValueString();
+        if (mimeType != null && mimeType.equals(WspTypeDecoder.CONTENT_TYPE_B_PUSH_SYNCML_NOTI)) {
+            return true;
+        }
+        return false;
+    }
 }
diff --git a/telephony/java/com/android/internal/telephony/cdma/RuimPhoneBookInterfaceManager.java b/telephony/java/com/android/internal/telephony/cdma/RuimPhoneBookInterfaceManager.java
index 6e12f24a..dd1efdf 100644
--- a/telephony/java/com/android/internal/telephony/cdma/RuimPhoneBookInterfaceManager.java
+++ b/telephony/java/com/android/internal/telephony/cdma/RuimPhoneBookInterfaceManager.java
@@ -16,6 +16,8 @@
 
 package com.android.internal.telephony.cdma;
 
+import java.util.concurrent.atomic.AtomicBoolean;
+
 import android.os.Message;
 import android.util.Log;
 
@@ -56,14 +58,11 @@
             recordSize = new int[3];
 
             //Using mBaseHandler, no difference in EVENT_GET_SIZE_DONE handling
-            Message response = mBaseHandler.obtainMessage(EVENT_GET_SIZE_DONE);
+            AtomicBoolean status = new AtomicBoolean(false);
+            Message response = mBaseHandler.obtainMessage(EVENT_GET_SIZE_DONE, status);
 
             phone.getIccFileHandler().getEFLinearRecordSize(efid, response);
-            try {
-                mLock.wait();
-            } catch (InterruptedException e) {
-                logd("interrupted while trying to load from the RUIM");
-            }
+            waitForResult(status);
         }
 
         return recordSize;
diff --git a/telephony/java/com/android/internal/telephony/cdma/RuimRecords.java b/telephony/java/com/android/internal/telephony/cdma/RuimRecords.java
old mode 100644
new mode 100755
index 87b0c60..3429099
--- a/telephony/java/com/android/internal/telephony/cdma/RuimRecords.java
+++ b/telephony/java/com/android/internal/telephony/cdma/RuimRecords.java
@@ -16,10 +16,13 @@
 
 package com.android.internal.telephony.cdma;
 
+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.os.AsyncResult;
 import android.os.Handler;
 import android.os.Message;
 import android.os.Registrant;
+import android.os.SystemProperties;
 import android.util.Log;
 
 import com.android.internal.telephony.AdnRecord;
@@ -59,6 +62,7 @@
 
     private static final int EVENT_RUIM_READY = 1;
     private static final int EVENT_RADIO_OFF_OR_NOT_AVAILABLE = 2;
+    private static final int EVENT_GET_IMSI_DONE = 3;
     private static final int EVENT_GET_DEVICE_IDENTITY_DONE = 4;
     private static final int EVENT_GET_ICCID_DONE = 5;
     private static final int EVENT_GET_CDMA_SUBSCRIPTION_DONE = 10;
@@ -114,6 +118,9 @@
 
         adnCache.reset();
 
+        phone.setSystemProperty(PROPERTY_ICC_OPERATOR_NUMERIC, null);
+        phone.setSystemProperty(PROPERTY_ICC_OPERATOR_ISO_COUNTRY, null);
+
         // recordsRequested is set to false indicating that the SIM
         // read requests made so far are not valid. This is set to
         // true only when fresh set of read requests are made.
@@ -201,6 +208,33 @@
             break;
 
             /* IO events */
+            case EVENT_GET_IMSI_DONE:
+                isRecordLoadResponse = true;
+
+                ar = (AsyncResult)msg.obj;
+                if (ar.exception != null) {
+                    Log.e(LOG_TAG, "Exception querying IMSI, Exception:" + ar.exception);
+                    break;
+                }
+
+                mImsi = (String) ar.result;
+
+                // IMSI (MCC+MNC+MSIN) is at least 6 digits, but not more
+                // than 15 (and usually 15).
+                if (mImsi != null && (mImsi.length() < 6 || mImsi.length() > 15)) {
+                    Log.e(LOG_TAG, "invalid IMSI " + mImsi);
+                    mImsi = null;
+                }
+
+                Log.d(LOG_TAG, "IMSI: " + mImsi.substring(0, 6) + "xxxxxxxxx");
+
+                String operatorNumeric = getRUIMOperatorNumeric();
+                if (operatorNumeric != null) {
+                    if(operatorNumeric.length() <= 6){
+                        MccTable.updateMccMncConfiguration(phone, operatorNumeric);
+                    }
+                }
+            break;
 
             case EVENT_GET_CDMA_SUBSCRIPTION_DONE:
                 ar = (AsyncResult)msg.obj;
@@ -291,6 +325,13 @@
 
         // Further records that can be inserted are Operator/OEM dependent
 
+        String operator = getRUIMOperatorNumeric();
+        SystemProperties.set(PROPERTY_ICC_OPERATOR_NUMERIC, operator);
+
+        if (mImsi != null) {
+            SystemProperties.set(PROPERTY_ICC_OPERATOR_ISO_COUNTRY,
+                    MccTable.countryCodeForMcc(Integer.parseInt(mImsi.substring(0,3))));
+        }
         recordsLoadedRegistrants.notifyRegistrants(
             new AsyncResult(null, null, null));
         ((CDMAPhone) phone).mRuimCard.broadcastIccStateChangedIntent(
@@ -317,6 +358,9 @@
 
         Log.v(LOG_TAG, "RuimRecords:fetchRuimRecords " + recordsToLoad);
 
+        phone.mCM.getIMSI(obtainMessage(EVENT_GET_IMSI_DONE));
+        recordsToLoad++;
+
         phone.getIccFileHandler().loadEFTransparent(EF_ICCID,
                 obtainMessage(EVENT_GET_ICCID_DONE));
         recordsToLoad++;
diff --git a/telephony/java/com/android/internal/telephony/cdma/RuimSmsInterfaceManager.java b/telephony/java/com/android/internal/telephony/cdma/RuimSmsInterfaceManager.java
index f4a6d11..7b42b06 100644
--- a/telephony/java/com/android/internal/telephony/cdma/RuimSmsInterfaceManager.java
+++ b/telephony/java/com/android/internal/telephony/cdma/RuimSmsInterfaceManager.java
@@ -204,6 +204,18 @@
         return false;
     }
 
+    public boolean enableCellBroadcastRange(int startMessageId, int endMessageId) {
+        // Not implemented
+        Log.e(LOG_TAG, "Error! Not implemented for CDMA.");
+        return false;
+    }
+
+    public boolean disableCellBroadcastRange(int startMessageId, int endMessageId) {
+        // Not implemented
+        Log.e(LOG_TAG, "Error! Not implemented for CDMA.");
+        return false;
+    }
+
     protected void log(String msg) {
         Log.d(LOG_TAG, "[RuimSmsInterfaceManager] " + msg);
     }
diff --git a/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java b/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java
index 54cf612..676a828 100644
--- a/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java
+++ b/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java
@@ -18,6 +18,7 @@
 
 import android.os.Parcel;
 import android.os.SystemProperties;
+import android.telephony.PhoneNumberUtils;
 import android.text.format.Time;
 import android.util.Config;
 import android.util.Log;
@@ -811,7 +812,12 @@
          * mechanism, and avoid null pointer exceptions.
          */
 
-        CdmaSmsAddress destAddr = CdmaSmsAddress.parse(destAddrStr);
+        /**
+         * North America Plus Code :
+         * Convert + code to 011 and dial out for international SMS
+         */
+        CdmaSmsAddress destAddr = CdmaSmsAddress.parse(
+                PhoneNumberUtils.cdmaCheckAndProcessPlusCode(destAddrStr));
         if (destAddr == null) return null;
 
         BearerData bearerData = new BearerData();
diff --git a/telephony/java/com/android/internal/telephony/cdma/sms/BearerData.java b/telephony/java/com/android/internal/telephony/cdma/sms/BearerData.java
old mode 100644
new mode 100755
index ebe6467..58b0355
--- a/telephony/java/com/android/internal/telephony/cdma/sms/BearerData.java
+++ b/telephony/java/com/android/internal/telephony/cdma/sms/BearerData.java
@@ -21,7 +21,6 @@
 import static android.telephony.SmsMessage.MAX_USER_DATA_BYTES_WITH_HEADER;
 
 import android.util.Log;
-import android.util.SparseIntArray;
 
 import android.telephony.SmsMessage;
 
@@ -30,13 +29,14 @@
 import com.android.internal.telephony.IccUtils;
 import com.android.internal.telephony.GsmAlphabet;
 import com.android.internal.telephony.SmsHeader;
-import com.android.internal.telephony.cdma.sms.UserData;
 import com.android.internal.telephony.SmsMessageBase.TextEncodingDetails;
 
-import com.android.internal.util.HexDump;
 import com.android.internal.util.BitwiseInputStream;
 import com.android.internal.util.BitwiseOutputStream;
 
+import android.content.res.Resources;
+
+
 
 /**
  * An object to encode and decode CDMA SMS bearer data.
@@ -501,7 +501,7 @@
              * stringToGsm7BitPacked, and potentially directly support
              * access to the main bitwise stream from encode/decode.
              */
-            byte[] fullData = GsmAlphabet.stringToGsm7BitPacked(msg, septetOffset, !force);
+            byte[] fullData = GsmAlphabet.stringToGsm7BitPacked(msg, septetOffset, !force, 0, 0);
             Gsm7bitCodingResult result = new Gsm7bitCodingResult();
             result.data = new byte[fullData.length - 1];
             System.arraycopy(fullData, 1, result.data, 0, fullData.length - 1);
@@ -911,10 +911,20 @@
         return true;
     }
 
+    private static String decodeUtf8(byte[] data, int offset, int numFields)
+        throws CodingException
+    {
+        try {
+            return new String(data, offset, numFields, "UTF-8");
+        } catch (java.io.UnsupportedEncodingException ex) {
+            throw new CodingException("UTF-8 decode failed: " + ex);
+        }
+    }
+
     private static String decodeUtf16(byte[] data, int offset, int numFields)
         throws CodingException
     {
-        // Start reading from the next 16-bit aligned boundry after offset.
+        // Start reading from the next 16-bit aligned boundary after offset.
         int padding = offset % 2;
         numFields -= (offset + padding) / 2;
         try {
@@ -960,12 +970,13 @@
     private static String decode7bitGsm(byte[] data, int offset, int numFields)
         throws CodingException
     {
-        // Start reading from the next 7-bit aligned boundry after offset.
+        // Start reading from the next 7-bit aligned boundary after offset.
         int offsetBits = offset * 8;
         int offsetSeptets = (offsetBits + 6) / 7;
         numFields -= offsetSeptets;
         int paddingBits = (offsetSeptets * 7) - offsetBits;
-        String result = GsmAlphabet.gsm7BitPackedToString(data, offset, numFields, paddingBits);
+        String result = GsmAlphabet.gsm7BitPackedToString(data, offset, numFields, paddingBits,
+                0, 0);
         if (result == null) {
             throw new CodingException("7bit GSM decoding failed");
         }
@@ -995,9 +1006,15 @@
         }
         switch (userData.msgEncoding) {
         case UserData.ENCODING_OCTET:
+            /*
+            *  Octet decoding depends on the carrier service.
+            */
+            boolean decodingtypeUTF8 = Resources.getSystem()
+                    .getBoolean(com.android.internal.R.bool.config_sms_utf8_support);
+
             // 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.
+            // 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;
@@ -1005,9 +1022,13 @@
             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);
+            if (!decodingtypeUTF8) {
+                // 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);
+            } else {
+                userData.payloadStr = decodeUtf8(userData.payload, offset, userData.numFields);
+            }
             break;
         case UserData.ENCODING_IA5:
         case UserData.ENCODING_7BIT_ASCII:
diff --git a/telephony/java/com/android/internal/telephony/gsm/ApnSetting.java b/telephony/java/com/android/internal/telephony/gsm/ApnSetting.java
index 05527af..e96ad72 100644
--- a/telephony/java/com/android/internal/telephony/gsm/ApnSetting.java
+++ b/telephony/java/com/android/internal/telephony/gsm/ApnSetting.java
@@ -22,6 +22,8 @@
  */
 public class ApnSetting {
 
+    static final String V2_FORMAT_REGEX = "^\\[ApnSettingV2\\]\\s*";
+
     String carrier;
     String apn;
     String proxy;
@@ -35,11 +37,14 @@
     public String[] types;
     int id;
     String numeric;
+    String protocol;
+    String roamingProtocol;
 
-
-    public ApnSetting(int id, String numeric, String carrier, String apn, String proxy, String port,
+    public ApnSetting(int id, String numeric, String carrier, String apn,
+            String proxy, String port,
             String mmsc, String mmsProxy, String mmsPort,
-            String user, String password, int authType, String[] types) {
+            String user, String password, int authType, String[] types,
+            String protocol, String roamingProtocol) {
         this.id = id;
         this.numeric = numeric;
         this.carrier = carrier;
@@ -53,40 +58,81 @@
         this.password = password;
         this.authType = authType;
         this.types = types;
+        this.protocol = protocol;
+        this.roamingProtocol = roamingProtocol;
     }
 
-    // data[0] = name
-    // data[1] = apn
-    // data[2] = proxy
-    // data[3] = port
-    // data[4] = username
-    // data[5] = password
-    // data[6] = server
-    // data[7] = mmsc
-    // data[8] = mmsproxy
-    // data[9] = mmsport
-    // data[10] = mcc
-    // data[11] = mnc
-    // data[12] = auth
-    // data[13] = first type...
+    /**
+     * Creates an ApnSetting object from a string.
+     *
+     * @param data the string to read.
+     *
+     * The string must be in one of two formats (newlines added for clarity,
+     * spaces are optional):
+     *
+     * v1 format:
+     *   <carrier>, <apn>, <proxy>, <port>, <mmsc>, <mmsproxy>,
+     *   <mmsport>, <user>, <password>, <authtype>, <mcc>,<mnc>,
+     *   <type>[, <type>...]
+     *
+     * v2 format:
+     *   [ApnSettingV2] <carrier>, <apn>, <proxy>, <port>, <mmsc>, <mmsproxy>,
+     *   <mmsport>, <user>, <password, <authtype>, <mcc>, <mnc>,
+     *   <type>[| <type>...], <protocol>, <roaming_protocol>
+     *
+     * Note that the strings generated by toString() do not contain the username
+     * and password and thus cannot be read by this method.
+     *
+     * @see ApnSettingTest
+     */
     public static ApnSetting fromString(String data) {
         if (data == null) return null;
+
+        int version;
+        // matches() operates on the whole string, so append .* to the regex.
+        if (data.matches(V2_FORMAT_REGEX + ".*")) {
+            version = 2;
+            data = data.replaceFirst(V2_FORMAT_REGEX, "");
+        } else {
+            version = 1;
+        }
+
         String[] a = data.split("\\s*,\\s*");
-        if (a.length < 14) return null;
-        int authType = 0;
+        if (a.length < 14) {
+            return null;
+        }
+
+        int authType;
         try {
             authType = Integer.parseInt(a[12]);
         } catch (Exception e) {
+            authType = 0;
         }
-        String[] typeArray = new String[a.length - 13];
-        System.arraycopy(a, 13, typeArray, 0, a.length - 13);
+
+        String[] typeArray;
+        String protocol, roamingProtocol;
+        if (version == 1) {
+            typeArray = new String[a.length - 13];
+            System.arraycopy(a, 13, typeArray, 0, a.length - 13);
+            protocol = RILConstants.SETUP_DATA_PROTOCOL_IP;
+            roamingProtocol = RILConstants.SETUP_DATA_PROTOCOL_IP;
+        } else {
+            if (a.length < 16) {
+                return null;
+            }
+            typeArray = a[13].split("\\s*\\|\\s*");
+            protocol = a[14];
+            roamingProtocol = a[15];
+        }
+
         return new ApnSetting(-1,a[10]+a[11],a[0],a[1],a[2],a[3],a[7],a[8],
-                a[9],a[4],a[5],authType,typeArray);
+                a[9],a[4],a[5],authType,typeArray,protocol,roamingProtocol);
     }
 
     public String toString() {
         StringBuilder sb = new StringBuilder();
-        sb.append(carrier)
+        sb.append("[ApnSettingV2] ")
+        .append(carrier)
         .append(", ").append(id)
         .append(", ").append(numeric)
         .append(", ").append(apn)
@@ -95,10 +141,15 @@
         .append(", ").append(mmsProxy)
         .append(", ").append(mmsPort)
         .append(", ").append(port)
-        .append(", ").append(authType);
-        for (String t : types) {
-            sb.append(", ").append(t);
+        .append(", ").append(authType).append(", ");
+        for (int i = 0; i < types.length; i++) {
+            sb.append(types[i]);
+            if (i < types.length - 1) {
+                sb.append(" | ");
+            }
         }
+        sb.append(", ").append(protocol);
+        sb.append(", ").append(roamingProtocol);
         return sb.toString();
     }
 
diff --git a/telephony/java/com/android/internal/telephony/gsm/GSMPhone.java b/telephony/java/com/android/internal/telephony/gsm/GSMPhone.java
index 3959c67..c5be856 100644
--- a/telephony/java/com/android/internal/telephony/gsm/GSMPhone.java
+++ b/telephony/java/com/android/internal/telephony/gsm/GSMPhone.java
@@ -1471,16 +1471,35 @@
         return this.mIccFileHandler;
     }
 
+    /**
+     * Activate or deactivate cell broadcast SMS.
+     *
+     * @param activate 0 = activate, 1 = deactivate
+     * @param response Callback message is empty on completion
+     */
     public void activateCellBroadcastSms(int activate, Message response) {
-        Log.e(LOG_TAG, "Error! This functionality is not implemented for GSM.");
+        Log.e(LOG_TAG, "[GSMPhone] activateCellBroadcastSms() is obsolete; use SmsManager");
+        response.sendToTarget();
     }
 
+    /**
+     * Query the current configuration of cdma cell broadcast SMS.
+     *
+     * @param response Callback message is empty on completion
+     */
     public void getCellBroadcastSmsConfig(Message response) {
-        Log.e(LOG_TAG, "Error! This functionality is not implemented for GSM.");
+        Log.e(LOG_TAG, "[GSMPhone] getCellBroadcastSmsConfig() is obsolete; use SmsManager");
+        response.sendToTarget();
     }
 
-    public void setCellBroadcastSmsConfig(int[] configValuesArray, Message response){
-        Log.e(LOG_TAG, "Error! This functionality is not implemented for GSM.");
+    /**
+     * Configure cdma cell broadcast SMS.
+     *
+     * @param response Callback message is empty on completion
+     */
+    public void setCellBroadcastSmsConfig(int[] configValuesArray, Message response) {
+        Log.e(LOG_TAG, "[GSMPhone] setCellBroadcastSmsConfig() is obsolete; use SmsManager");
+        response.sendToTarget();
     }
 
     public boolean isCspPlmnEnabled() {
diff --git a/telephony/java/com/android/internal/telephony/gsm/GsmDataConnection.java b/telephony/java/com/android/internal/telephony/gsm/GsmDataConnection.java
index 09d46dd..3de4c27 100644
--- a/telephony/java/com/android/internal/telephony/gsm/GsmDataConnection.java
+++ b/telephony/java/com/android/internal/telephony/gsm/GsmDataConnection.java
@@ -104,9 +104,19 @@
             authType = (apn.user != null) ? RILConstants.SETUP_DATA_AUTH_PAP_CHAP :
                 RILConstants.SETUP_DATA_AUTH_NONE;
         }
-        phone.mCM.setupDataCall(Integer.toString(RILConstants.SETUP_DATA_TECH_GSM),
-                Integer.toString(RILConstants.DATA_PROFILE_DEFAULT), apn.apn, apn.user,
-                apn.password, Integer.toString(authType), msg);
+
+        String protocol;
+        if (phone.getServiceState().getRoaming()) {
+            protocol = apn.roamingProtocol;
+        } else {
+            protocol = apn.protocol;
+        }
+
+        phone.mCM.setupDataCall(
+                Integer.toString(RILConstants.SETUP_DATA_TECH_GSM),
+                Integer.toString(RILConstants.DATA_PROFILE_DEFAULT),
+                apn.apn, apn.user, apn.password, Integer.toString(authType),
+                protocol, msg);
     }
 
     @Override
diff --git a/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java b/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java
index ab9cf2a..96005f0 100644
--- a/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java
+++ b/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java
@@ -361,6 +361,12 @@
     @Override
     protected boolean isApnTypeActive(String type) {
         // TODO: support simultaneous with List instead
+        if (Phone.APN_TYPE_DUN.equals(type)) {
+            ApnSetting dunApn = fetchDunApn();
+            if (dunApn != null) {
+                return ((mActiveApn != null) && (dunApn.toString().equals(mActiveApn.toString())));
+            }
+        }
         return mActiveApn != null && mActiveApn.canHandleType(type);
     }
 
@@ -559,7 +565,10 @@
                         cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.USER)),
                         cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PASSWORD)),
                         cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.AUTH_TYPE)),
-                        types);
+                        types,
+                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PROTOCOL)),
+                        cursor.getString(cursor.getColumnIndexOrThrow(
+                                Telephony.Carriers.ROAMING_PROTOCOL)));
                 result.add(apn);
             } while (cursor.moveToNext());
         }
diff --git a/telephony/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java b/telephony/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java
old mode 100755
new mode 100644
index 8355046..de769d1
--- a/telephony/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java
+++ b/telephony/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java
@@ -69,9 +69,8 @@
         String pduString = (String) ar.result;
         SmsMessage sms = SmsMessage.newFromCDS(pduString);
 
-        int tpStatus = sms.getStatus();
-
         if (sms != null) {
+            int tpStatus = sms.getStatus();
             int messageRef = sms.messageRef;
             for (int i = 0, count = deliveryPendingList.size(); i < count; i++) {
                 SmsTracker tracker = deliveryPendingList.get(i);
@@ -190,6 +189,7 @@
 
         mRemainingMessages = msgCount;
 
+        TextEncodingDetails[] encodingForParts = new TextEncodingDetails[msgCount];
         for (int i = 0; i < msgCount; i++) {
             TextEncodingDetails details = SmsMessage.calculateLength(parts.get(i), false);
             if (encoding != details.codeUnitSize
@@ -197,6 +197,7 @@
                             || encoding == android.telephony.SmsMessage.ENCODING_7BIT)) {
                 encoding = details.codeUnitSize;
             }
+            encodingForParts[i] = details;
         }
 
         for (int i = 0; i < msgCount; i++) {
@@ -213,6 +214,10 @@
             concatRef.isEightBits = true;
             SmsHeader smsHeader = new SmsHeader();
             smsHeader.concatRef = concatRef;
+            if (encoding == android.telephony.SmsMessage.ENCODING_7BIT) {
+                smsHeader.languageTable = encodingForParts[i].languageTable;
+                smsHeader.languageShiftTable = encodingForParts[i].languageShiftTable;
+            }
 
             PendingIntent sentIntent = null;
             if (sentIntents != null && sentIntents.size() > i) {
@@ -226,7 +231,7 @@
 
             SmsMessage.SubmitPdu pdus = SmsMessage.getSubmitPdu(scAddress, destinationAddress,
                     parts.get(i), deliveryIntent != null, SmsHeader.toByteArray(smsHeader),
-                    encoding);
+                    encoding, smsHeader.languageTable, smsHeader.languageShiftTable);
 
             sendRawPdu(pdus.encodedScAddress, pdus.encodedMessage, sentIntent, deliveryIntent);
         }
@@ -281,6 +286,7 @@
 
         mRemainingMessages = msgCount;
 
+        TextEncodingDetails[] encodingForParts = new TextEncodingDetails[msgCount];
         for (int i = 0; i < msgCount; i++) {
             TextEncodingDetails details = SmsMessage.calculateLength(parts.get(i), false);
             if (encoding != details.codeUnitSize
@@ -288,6 +294,7 @@
                             || encoding == android.telephony.SmsMessage.ENCODING_7BIT)) {
                 encoding = details.codeUnitSize;
             }
+            encodingForParts[i] = details;
         }
 
         for (int i = 0; i < msgCount; i++) {
@@ -298,6 +305,10 @@
             concatRef.isEightBits = false;
             SmsHeader smsHeader = new SmsHeader();
             smsHeader.concatRef = concatRef;
+            if (encoding == android.telephony.SmsMessage.ENCODING_7BIT) {
+                smsHeader.languageTable = encodingForParts[i].languageTable;
+                smsHeader.languageShiftTable = encodingForParts[i].languageShiftTable;
+            }
 
             PendingIntent sentIntent = null;
             if (sentIntents != null && sentIntents.size() > i) {
@@ -311,7 +322,7 @@
 
             SmsMessage.SubmitPdu pdus = SmsMessage.getSubmitPdu(scAddress, destinationAddress,
                     parts.get(i), deliveryIntent != null, SmsHeader.toByteArray(smsHeader),
-                    encoding);
+                    encoding, smsHeader.languageTable, smsHeader.languageShiftTable);
 
             HashMap<String, Object> map = new HashMap<String, Object>();
             map.put("smsc", pdus.encodedScAddress);
@@ -339,6 +350,7 @@
      *
      * @param tracker holds the multipart Sms tracker ready to be sent
      */
+    @Override
     protected void sendMultipartSms (SmsTracker tracker) {
         ArrayList<String> parts;
         ArrayList<PendingIntent> sentIntents;
@@ -359,6 +371,7 @@
     }
 
     /** {@inheritDoc} */
+    @Override
     protected void acknowledgeLastIncomingSms(boolean success, int result, Message response){
         // FIXME unit test leaves cm == null. this should change
         if (mCm != null) {
@@ -366,27 +379,6 @@
         }
     }
 
-    /** {@inheritDoc} */
-    protected void activateCellBroadcastSms(int activate, Message response) {
-        // Unless CBS is implemented for GSM, this point should be unreachable.
-        Log.e(TAG, "Error! The functionality cell broadcast sms is not implemented for GSM.");
-        response.recycle();
-    }
-
-    /** {@inheritDoc} */
-    protected void getCellBroadcastSmsConfig(Message response){
-        // Unless CBS is implemented for GSM, this point should be unreachable.
-        Log.e(TAG, "Error! The functionality cell broadcast sms is not implemented for GSM.");
-        response.recycle();
-    }
-
-    /** {@inheritDoc} */
-    protected  void setCellBroadcastConfig(int[] configValuesArray, Message response) {
-        // Unless CBS is implemented for GSM, this point should be unreachable.
-        Log.e(TAG, "Error! The functionality cell broadcast sms is not implemented for GSM.");
-        response.recycle();
-    }
-
     private int resultToCause(int rc) {
         switch (rc) {
             case Activity.RESULT_OK:
@@ -478,9 +470,10 @@
     }
 
     // This map holds incomplete concatenated messages waiting for assembly
-    private HashMap<SmsCbConcatInfo, byte[][]> mSmsCbPageMap =
+    private final HashMap<SmsCbConcatInfo, byte[][]> mSmsCbPageMap =
             new HashMap<SmsCbConcatInfo, byte[][]>();
 
+    @Override
     protected void handleBroadcastSms(AsyncResult ar) {
         try {
             byte[][] pdus = null;
@@ -492,9 +485,9 @@
                     for (int j = i; j < i + 8 && j < receivedPdu.length; j++) {
                         int b = receivedPdu[j] & 0xff;
                         if (b < 0x10) {
-                            sb.append("0");
+                            sb.append('0');
                         }
-                        sb.append(Integer.toHexString(b)).append(" ");
+                        sb.append(Integer.toHexString(b)).append(' ');
                     }
                     Log.d(TAG, sb.toString());
                 }
@@ -539,7 +532,8 @@
                 pdus[0] = receivedPdu;
             }
 
-            dispatchBroadcastPdus(pdus);
+            boolean isEmergencyMessage = SmsCbHeader.isEmergencyMessage(header.messageIdentifier);
+            dispatchBroadcastPdus(pdus, isEmergencyMessage);
 
             // Remove messages that are out of scope to prevent the map from
             // growing indefinitely, containing incomplete messages that were
diff --git a/telephony/java/com/android/internal/telephony/gsm/SimPhoneBookInterfaceManager.java b/telephony/java/com/android/internal/telephony/gsm/SimPhoneBookInterfaceManager.java
index feb508a..001e1bd 100644
--- a/telephony/java/com/android/internal/telephony/gsm/SimPhoneBookInterfaceManager.java
+++ b/telephony/java/com/android/internal/telephony/gsm/SimPhoneBookInterfaceManager.java
@@ -16,6 +16,8 @@
 
 package com.android.internal.telephony.gsm;
 
+import java.util.concurrent.atomic.AtomicBoolean;
+
 import android.os.Message;
 import android.util.Log;
 
@@ -56,14 +58,11 @@
             recordSize = new int[3];
 
             //Using mBaseHandler, no difference in EVENT_GET_SIZE_DONE handling
-            Message response = mBaseHandler.obtainMessage(EVENT_GET_SIZE_DONE);
+            AtomicBoolean status = new AtomicBoolean(false);
+            Message response = mBaseHandler.obtainMessage(EVENT_GET_SIZE_DONE, status);
 
             phone.getIccFileHandler().getEFLinearRecordSize(efid, response);
-            try {
-                mLock.wait();
-            } catch (InterruptedException e) {
-                logd("interrupted while trying to load from the SIM");
-            }
+            waitForResult(status);
         }
 
         return recordSize;
diff --git a/telephony/java/com/android/internal/telephony/gsm/SimSmsInterfaceManager.java b/telephony/java/com/android/internal/telephony/gsm/SimSmsInterfaceManager.java
index e55596b..6e87f21 100644
--- a/telephony/java/com/android/internal/telephony/gsm/SimSmsInterfaceManager.java
+++ b/telephony/java/com/android/internal/telephony/gsm/SimSmsInterfaceManager.java
@@ -27,6 +27,7 @@
 import com.android.internal.telephony.IccConstants;
 import com.android.internal.telephony.IccSmsInterfaceManager;
 import com.android.internal.telephony.IccUtils;
+import com.android.internal.telephony.IntRangeManager;
 import com.android.internal.telephony.SMSDispatcher;
 import com.android.internal.telephony.SmsRawData;
 
@@ -53,6 +54,9 @@
     private HashMap<Integer, HashSet<String>> mCellBroadcastSubscriptions =
             new HashMap<Integer, HashSet<String>>();
 
+    private CellBroadcastRangeManager mCellBroadcastRangeManager =
+            new CellBroadcastRangeManager();
+
     private static final int EVENT_LOAD_DONE = 1;
     private static final int EVENT_UPDATE_DONE = 2;
     private static final int EVENT_SET_BROADCAST_ACTIVATION_DONE = 3;
@@ -212,7 +216,15 @@
     }
 
     public boolean enableCellBroadcast(int messageIdentifier) {
-        if (DBG) log("enableCellBroadcast");
+        return enableCellBroadcastRange(messageIdentifier, messageIdentifier);
+    }
+
+    public boolean disableCellBroadcast(int messageIdentifier) {
+        return disableCellBroadcastRange(messageIdentifier, messageIdentifier);
+    }
+
+    public boolean enableCellBroadcastRange(int startMessageId, int endMessageId) {
+        if (DBG) log("enableCellBroadcastRange");
 
         Context context = mPhone.getContext();
 
@@ -222,30 +234,22 @@
 
         String client = context.getPackageManager().getNameForUid(
                 Binder.getCallingUid());
-        HashSet<String> clients = mCellBroadcastSubscriptions.get(messageIdentifier);
 
-        if (clients == null) {
-            // This is a new message identifier
-            clients = new HashSet<String>();
-            mCellBroadcastSubscriptions.put(messageIdentifier, clients);
-
-            if (!updateCellBroadcastConfig()) {
-                mCellBroadcastSubscriptions.remove(messageIdentifier);
-                return false;
-            }
+        if (!mCellBroadcastRangeManager.enableRange(startMessageId, endMessageId, client)) {
+            log("Failed to add cell broadcast subscription for MID range " + startMessageId
+                    + " to " + endMessageId + " from client " + client);
+            return false;
         }
 
-        clients.add(client);
-
         if (DBG)
-            log("Added cell broadcast subscription for MID " + messageIdentifier
-                    + " from client " + client);
+            log("Added cell broadcast subscription for MID range " + startMessageId
+                    + " to " + endMessageId + " from client " + client);
 
         return true;
     }
 
-    public boolean disableCellBroadcast(int messageIdentifier) {
-        if (DBG) log("disableCellBroadcast");
+    public boolean disableCellBroadcastRange(int startMessageId, int endMessageId) {
+        if (DBG) log("disableCellBroadcastRange");
 
         Context context = mPhone.getContext();
 
@@ -255,39 +259,56 @@
 
         String client = context.getPackageManager().getNameForUid(
                 Binder.getCallingUid());
-        HashSet<String> clients = mCellBroadcastSubscriptions.get(messageIdentifier);
 
-        if (clients != null && clients.remove(client)) {
-            if (DBG)
-                log("Removed cell broadcast subscription for MID " + messageIdentifier
-                        + " from client " + client);
-
-            if (clients.isEmpty()) {
-                mCellBroadcastSubscriptions.remove(messageIdentifier);
-                updateCellBroadcastConfig();
-            }
-            return true;
+        if (!mCellBroadcastRangeManager.disableRange(startMessageId, endMessageId, client)) {
+            log("Failed to remove cell broadcast subscription for MID range " + startMessageId
+                    + " to " + endMessageId + " from client " + client);
+            return false;
         }
 
-        return false;
+        if (DBG)
+            log("Removed cell broadcast subscription for MID range " + startMessageId
+                    + " to " + endMessageId + " from client " + client);
+
+        return true;
     }
 
-    private boolean updateCellBroadcastConfig() {
-        Set<Integer> messageIdentifiers = mCellBroadcastSubscriptions.keySet();
+    class CellBroadcastRangeManager extends IntRangeManager {
+        private ArrayList<SmsBroadcastConfigInfo> mConfigList =
+                new ArrayList<SmsBroadcastConfigInfo>();
 
-        if (messageIdentifiers.size() > 0) {
-            SmsBroadcastConfigInfo[] configs =
-                    new SmsBroadcastConfigInfo[messageIdentifiers.size()];
-            int i = 0;
+        /**
+         * Called when the list of enabled ranges has changed. This will be
+         * followed by zero or more calls to {@link #addRange} followed by
+         * a call to {@link #finishUpdate}.
+         */
+        protected void startUpdate() {
+            mConfigList.clear();
+        }
 
-            for (int messageIdentifier : messageIdentifiers) {
-                configs[i++] = new SmsBroadcastConfigInfo(messageIdentifier, messageIdentifier,
-                        SMS_CB_CODE_SCHEME_MIN, SMS_CB_CODE_SCHEME_MAX, true);
+        /**
+         * Called after {@link #startUpdate} to indicate a range of enabled
+         * values.
+         * @param startId the first id included in the range
+         * @param endId the last id included in the range
+         */
+        protected void addRange(int startId, int endId, boolean selected) {
+            mConfigList.add(new SmsBroadcastConfigInfo(startId, endId,
+                        SMS_CB_CODE_SCHEME_MIN, SMS_CB_CODE_SCHEME_MAX, selected));
+        }
+
+        /**
+         * Called to indicate the end of a range update started by the
+         * previous call to {@link #startUpdate}.
+         */
+        protected boolean finishUpdate() {
+            if (mConfigList.isEmpty()) {
+                return setCellBroadcastActivation(false);
+            } else {
+                SmsBroadcastConfigInfo[] configs =
+                        mConfigList.toArray(new SmsBroadcastConfigInfo[mConfigList.size()]);
+                return setCellBroadcastConfig(configs) && setCellBroadcastActivation(true);
             }
-
-            return setCellBroadcastConfig(configs) && setCellBroadcastActivation(true);
-        } else {
-            return setCellBroadcastActivation(false);
         }
     }
 
@@ -313,7 +334,7 @@
 
     private boolean setCellBroadcastActivation(boolean activate) {
         if (DBG)
-            log("Calling setCellBroadcastActivation(" + activate + ")");
+            log("Calling setCellBroadcastActivation(" + activate + ')');
 
         synchronized (mLock) {
             Message response = mHandler.obtainMessage(EVENT_SET_BROADCAST_ACTIVATION_DONE);
@@ -331,6 +352,7 @@
         return mSuccess;
     }
 
+    @Override
     protected void log(String msg) {
         Log.d(LOG_TAG, "[SimSmsInterfaceManager] " + msg);
     }
diff --git a/telephony/java/com/android/internal/telephony/gsm/SmsBroadcastConfigInfo.java b/telephony/java/com/android/internal/telephony/gsm/SmsBroadcastConfigInfo.java
index 45f50bc4..66e7ce0 100644
--- a/telephony/java/com/android/internal/telephony/gsm/SmsBroadcastConfigInfo.java
+++ b/telephony/java/com/android/internal/telephony/gsm/SmsBroadcastConfigInfo.java
@@ -30,11 +30,11 @@
  * and 9.4.4.2.3 for UMTS.
  * All other values can be treated as empty CBM data coding scheme.
  *
- * selected false means message types specified in <fromServiceId, toServiceId>
- * and <fromCodeScheme, toCodeScheme>are not accepted, while true means accepted.
+ * selected false means message types specified in {@code <fromServiceId, toServiceId>}
+ * and {@code <fromCodeScheme, toCodeScheme>} are not accepted, while true means accepted.
  *
  */
-public class SmsBroadcastConfigInfo {
+public final class SmsBroadcastConfigInfo {
     private int fromServiceId;
     private int toServiceId;
     private int fromCodeScheme;
@@ -46,11 +46,11 @@
      */
     public SmsBroadcastConfigInfo(int fromId, int toId, int fromScheme,
             int toScheme, boolean selected) {
-        setFromServiceId(fromId);
-        setToServiceId(toId);
-        setFromCodeScheme(fromScheme);
-        setToCodeScheme(toScheme);
-        this.setSelected(selected);
+        fromServiceId = fromId;
+        toServiceId = toId;
+        fromCodeScheme = fromScheme;
+        toCodeScheme = toScheme;
+        this.selected = selected;
     }
 
     /**
@@ -126,8 +126,8 @@
     @Override
     public String toString() {
         return "SmsBroadcastConfigInfo: Id [" +
-            getFromServiceId() + "," + getToServiceId() + "] Code [" +
-            getFromCodeScheme() + "," + getToCodeScheme() + "] " +
-            (isSelected() ? "ENABLED" : "DISABLED");
+                fromServiceId + ',' + toServiceId + "] Code [" +
+                fromCodeScheme + ',' + toCodeScheme + "] " +
+            (selected ? "ENABLED" : "DISABLED");
     }
-}
\ No newline at end of file
+}
diff --git a/telephony/java/com/android/internal/telephony/gsm/SmsCbHeader.java b/telephony/java/com/android/internal/telephony/gsm/SmsCbHeader.java
index 5f27cfc..8e6b79b 100644
--- a/telephony/java/com/android/internal/telephony/gsm/SmsCbHeader.java
+++ b/telephony/java/com/android/internal/telephony/gsm/SmsCbHeader.java
@@ -16,9 +16,44 @@
 
 package com.android.internal.telephony.gsm;
 
-public class SmsCbHeader {
+import android.telephony.SmsCbConstants;
+
+public class SmsCbHeader implements SmsCbConstants {
+    /**
+     * Length of SMS-CB header
+     */
     public static final int PDU_HEADER_LENGTH = 6;
 
+    /**
+     * GSM pdu format, as defined in 3gpp TS 23.041, section 9.4.1
+     */
+    public static final int FORMAT_GSM = 1;
+
+    /**
+     * UMTS pdu format, as defined in 3gpp TS 23.041, section 9.4.2
+     */
+    public static final int FORMAT_UMTS = 2;
+
+    /**
+     * GSM pdu format, as defined in 3gpp TS 23.041, section 9.4.1.3
+     */
+    public static final int FORMAT_ETWS_PRIMARY = 3;
+
+    /**
+     * Message type value as defined in 3gpp TS 25.324, section 11.1.
+     */
+    private static final int MESSAGE_TYPE_CBS_MESSAGE = 1;
+
+    /**
+     * Length of GSM pdus
+     */
+    public static final int PDU_LENGTH_GSM = 88;
+
+    /**
+     * Maximum length of ETWS primary message GSM pdus
+     */
+    public static final int PDU_LENGTH_ETWS = 56;
+
     public final int geographicalScope;
 
     public final int messageCode;
@@ -33,27 +68,147 @@
 
     public final int nrOfPages;
 
+    public final int format;
+
+    public final boolean etwsEmergencyUserAlert;
+
+    public final boolean etwsPopup;
+
+    public final int etwsWarningType;
+
     public SmsCbHeader(byte[] pdu) throws IllegalArgumentException {
         if (pdu == null || pdu.length < PDU_HEADER_LENGTH) {
             throw new IllegalArgumentException("Illegal PDU");
         }
 
-        geographicalScope = (pdu[0] & 0xc0) >> 6;
-        messageCode = ((pdu[0] & 0x3f) << 4) | ((pdu[1] & 0xf0) >> 4);
-        updateNumber = pdu[1] & 0x0f;
-        messageIdentifier = (pdu[2] << 8) | pdu[3];
-        dataCodingScheme = pdu[4];
+        if (pdu.length <= PDU_LENGTH_ETWS) {
+            format = FORMAT_ETWS_PRIMARY;
+            geographicalScope = -1; //not applicable
+            messageCode = -1;
+            updateNumber = -1;
+            messageIdentifier = ((pdu[2] & 0xff) << 8) | (pdu[3] & 0xff);
+            dataCodingScheme = -1;
+            pageIndex = -1;
+            nrOfPages = -1;
+            etwsEmergencyUserAlert = (pdu[4] & 0x1) != 0;
+            etwsPopup = (pdu[5] & 0x80) != 0;
+            etwsWarningType = (pdu[4] & 0xfe) >> 1;
+        } else if (pdu.length <= PDU_LENGTH_GSM) {
+            // GSM pdus are no more than 88 bytes
+            format = FORMAT_GSM;
+            geographicalScope = (pdu[0] & 0xc0) >> 6;
+            messageCode = ((pdu[0] & 0x3f) << 4) | ((pdu[1] & 0xf0) >> 4);
+            updateNumber = pdu[1] & 0x0f;
+            messageIdentifier = ((pdu[2] & 0xff) << 8) | (pdu[3] & 0xff);
+            dataCodingScheme = pdu[4] & 0xff;
 
-        // Check for invalid page parameter
-        int pageIndex = (pdu[5] & 0xf0) >> 4;
-        int nrOfPages = pdu[5] & 0x0f;
+            // Check for invalid page parameter
+            int pageIndex = (pdu[5] & 0xf0) >> 4;
+            int nrOfPages = pdu[5] & 0x0f;
 
-        if (pageIndex == 0 || nrOfPages == 0 || pageIndex > nrOfPages) {
+            if (pageIndex == 0 || nrOfPages == 0 || pageIndex > nrOfPages) {
+                pageIndex = 1;
+                nrOfPages = 1;
+            }
+
+            this.pageIndex = pageIndex;
+            this.nrOfPages = nrOfPages;
+            etwsEmergencyUserAlert = false;
+            etwsPopup = false;
+            etwsWarningType = -1;
+        } else {
+            // UMTS pdus are always at least 90 bytes since the payload includes
+            // a number-of-pages octet and also one length octet per page
+            format = FORMAT_UMTS;
+
+            int messageType = pdu[0];
+
+            if (messageType != MESSAGE_TYPE_CBS_MESSAGE) {
+                throw new IllegalArgumentException("Unsupported message type " + messageType);
+            }
+
+            messageIdentifier = ((pdu[1] & 0xff) << 8) | pdu[2] & 0xff;
+            geographicalScope = (pdu[3] & 0xc0) >> 6;
+            messageCode = ((pdu[3] & 0x3f) << 4) | ((pdu[4] & 0xf0) >> 4);
+            updateNumber = pdu[4] & 0x0f;
+            dataCodingScheme = pdu[5] & 0xff;
+
+            // We will always consider a UMTS message as having one single page
+            // since there's only one instance of the header, even though the
+            // actual payload may contain several pages.
             pageIndex = 1;
             nrOfPages = 1;
+            etwsEmergencyUserAlert = false;
+            etwsPopup = false;
+            etwsWarningType = -1;
         }
+    }
 
-        this.pageIndex = pageIndex;
-        this.nrOfPages = nrOfPages;
+    /**
+     * Return whether the specified message ID is an emergency (PWS) message type.
+     * This method is static and takes an argument so that it can be used by
+     * CellBroadcastReceiver, which stores message ID's in SQLite rather than PDU.
+     * @param id the message identifier to check
+     * @return true if the message is emergency type; false otherwise
+     */
+    public static boolean isEmergencyMessage(int id) {
+        return id >= MESSAGE_ID_PWS_FIRST_IDENTIFIER && id <= MESSAGE_ID_PWS_LAST_IDENTIFIER;
+    }
+
+    /**
+     * Return whether the specified message ID is an ETWS emergency message type.
+     * This method is static and takes an argument so that it can be used by
+     * CellBroadcastReceiver, which stores message ID's in SQLite rather than PDU.
+     * @param id the message identifier to check
+     * @return true if the message is ETWS emergency type; false otherwise
+     */
+    public static boolean isEtwsMessage(int id) {
+        return (id & MESSAGE_ID_ETWS_TYPE_MASK) == MESSAGE_ID_ETWS_TYPE;
+    }
+
+    /**
+     * Return whether the specified message ID is a CMAS emergency message type.
+     * This method is static and takes an argument so that it can be used by
+     * CellBroadcastReceiver, which stores message ID's in SQLite rather than PDU.
+     * @param id the message identifier to check
+     * @return true if the message is CMAS emergency type; false otherwise
+     */
+    public static boolean isCmasMessage(int id) {
+        return id >= MESSAGE_ID_CMAS_FIRST_IDENTIFIER && id <= MESSAGE_ID_CMAS_LAST_IDENTIFIER;
+    }
+
+    /**
+     * Return whether the specified message code indicates an ETWS popup alert.
+     * This method is static and takes an argument so that it can be used by
+     * CellBroadcastReceiver, which stores message codes in SQLite rather than PDU.
+     * This method assumes that the message ID has already been checked for ETWS type.
+     *
+     * @param messageCode the message code to check
+     * @return true if the message code indicates a popup alert should be displayed
+     */
+    public static boolean isEtwsPopupAlert(int messageCode) {
+        return (messageCode & MESSAGE_CODE_ETWS_ACTIVATE_POPUP) != 0;
+    }
+
+    /**
+     * Return whether the specified message code indicates an ETWS emergency user alert.
+     * This method is static and takes an argument so that it can be used by
+     * CellBroadcastReceiver, which stores message codes in SQLite rather than PDU.
+     * This method assumes that the message ID has already been checked for ETWS type.
+     *
+     * @param messageCode the message code to check
+     * @return true if the message code indicates an emergency user alert
+     */
+    public static boolean isEtwsEmergencyUserAlert(int messageCode) {
+        return (messageCode & MESSAGE_CODE_ETWS_EMERGENCY_USER_ALERT) != 0;
+    }
+
+    @Override
+    public String toString() {
+        return "SmsCbHeader{GS=" + geographicalScope + ", messageCode=0x" +
+                Integer.toHexString(messageCode) + ", updateNumber=" + updateNumber +
+                ", messageIdentifier=0x" + Integer.toHexString(messageIdentifier) +
+                ", DCS=0x" + Integer.toHexString(dataCodingScheme) +
+                ", page " + pageIndex + " of " + nrOfPages + '}';
     }
 }
diff --git a/telephony/java/com/android/internal/telephony/gsm/SmsMessage.java b/telephony/java/com/android/internal/telephony/gsm/SmsMessage.java
index f4c5e6c..0be9466 100644
--- a/telephony/java/com/android/internal/telephony/gsm/SmsMessage.java
+++ b/telephony/java/com/android/internal/telephony/gsm/SmsMessage.java
@@ -27,7 +27,6 @@
 import com.android.internal.telephony.SimRegionCache;
 import com.android.internal.telephony.SmsHeader;
 import com.android.internal.telephony.SmsMessageBase;
-import com.android.internal.telephony.SmsMessageBase.TextEncodingDetails;
 
 import java.io.ByteArrayOutputStream;
 import java.io.UnsupportedEncodingException;
@@ -39,7 +38,6 @@
 import static android.telephony.SmsMessage.MAX_USER_DATA_BYTES;
 import static android.telephony.SmsMessage.MAX_USER_DATA_BYTES_WITH_HEADER;
 import static android.telephony.SmsMessage.MAX_USER_DATA_SEPTETS;
-import static android.telephony.SmsMessage.MAX_USER_DATA_SEPTETS_WITH_HEADER;
 import static android.telephony.SmsMessage.MessageClass;
 
 /**
@@ -221,9 +219,7 @@
      */
     public static int getTPLayerLengthForPDU(String pdu) {
         int len = pdu.length() / 2;
-        int smscLen = 0;
-
-        smscLen = Integer.parseInt(pdu.substring(0, 2), 16);
+        int smscLen = Integer.parseInt(pdu.substring(0, 2), 16);
 
         return len - smscLen - 1;
     }
@@ -241,7 +237,7 @@
             String destinationAddress, String message,
             boolean statusReportRequested, byte[] header) {
         return getSubmitPdu(scAddress, destinationAddress, message, statusReportRequested, header,
-                ENCODING_UNKNOWN);
+                ENCODING_UNKNOWN, 0, 0);
     }
 
 
@@ -251,6 +247,8 @@
      *
      * @param scAddress Service Centre address.  Null means use default.
      * @param encoding Encoding defined by constants in android.telephony.SmsMessage.ENCODING_*
+     * @param languageTable
+     * @param languageShiftTable
      * @return a <code>SubmitPdu</code> containing the encoded SC
      *         address, if applicable, and the encoded message.
      *         Returns null on encode error.
@@ -258,7 +256,8 @@
      */
     public static SubmitPdu getSubmitPdu(String scAddress,
             String destinationAddress, String message,
-            boolean statusReportRequested, byte[] header, int encoding) {
+            boolean statusReportRequested, byte[] header, int encoding,
+            int languageTable, int languageShiftTable) {
 
         // Perform null parameter checks.
         if (message == null || destinationAddress == null) {
@@ -279,7 +278,8 @@
         }
         try {
             if (encoding == ENCODING_7BIT) {
-                userData = GsmAlphabet.stringToGsm7BitPackedWithHeader(message, header);
+                userData = GsmAlphabet.stringToGsm7BitPackedWithHeader(message, header,
+                        languageTable, languageShiftTable);
             } else { //assume UCS-2
                 try {
                     userData = encodeUCS2(message, header);
@@ -384,7 +384,7 @@
      * @param destinationAddress the address of the destination for the message
      * @param destinationPort the port to deliver the message to at the
      *        destination
-     * @param data the dat for the message
+     * @param data the data for the message
      * @return a <code>SubmitPdu</code> containing the encoded SC
      *         address, if applicable, and the encoded message.
      *         Returns null on encode error.
@@ -580,7 +580,7 @@
             int second = IccUtils.gsmBcdByteToInt(pdu[cur++]);
 
             // For the timezone, the most significant bit of the
-            // least signficant nibble is the sign byte
+            // least significant nibble is the sign byte
             // (meaning the max range of this field is 79 quarter-hours,
             // which is more than enough)
 
@@ -639,7 +639,7 @@
                 /*
                  * Here we just create the user data length to be the remainder of
                  * the pdu minus the user data header, since userDataLength means
-                 * the number of uncompressed sepets.
+                 * the number of uncompressed septets.
                  */
                 bufferLen = pdu.length - offset;
             } else {
@@ -697,70 +697,19 @@
             return userDataHeader;
         }
 
-/*
-        XXX Not sure what this one is supposed to be doing, and no one is using
-        it.
-        String getUserDataGSM8bit() {
-            // System.out.println("remainder of pud:" +
-            // HexDump.dumpHexString(pdu, cur, pdu.length - cur));
-            int count = pdu[cur++] & 0xff;
-            int size = pdu[cur++];
-
-            // skip over header for now
-            cur += size;
-
-            if (pdu[cur - 1] == 0x01) {
-                int tid = pdu[cur++] & 0xff;
-                int type = pdu[cur++] & 0xff;
-
-                size = pdu[cur++] & 0xff;
-
-                int i = cur;
-
-                while (pdu[i++] != '\0') {
-                }
-
-                int length = i - cur;
-                String mimeType = new String(pdu, cur, length);
-
-                cur += length;
-
-                if (false) {
-                    System.out.println("tid = 0x" + HexDump.toHexString(tid));
-                    System.out.println("type = 0x" + HexDump.toHexString(type));
-                    System.out.println("header size = " + size);
-                    System.out.println("mimeType = " + mimeType);
-                    System.out.println("remainder of header:" +
-                     HexDump.dumpHexString(pdu, cur, (size - mimeType.length())));
-                }
-
-                cur += size - mimeType.length();
-
-                // System.out.println("data count = " + count + " cur = " + cur
-                // + " :" + HexDump.dumpHexString(pdu, cur, pdu.length - cur));
-
-                MMSMessage msg = MMSMessage.parseEncoding(mContext, pdu, cur,
-                        pdu.length - cur);
-            } else {
-                System.out.println(new String(pdu, cur, pdu.length - cur - 1));
-            }
-
-            return IccUtils.bytesToHexString(pdu);
-        }
-*/
-
         /**
-         * Interprets the user data payload as pack GSM 7bit characters, and
+         * Interprets the user data payload as packed GSM 7bit characters, and
          * decodes them into a String.
          *
          * @param septetCount the number of septets in the user data payload
          * @return a String with the decoded characters
          */
-        String getUserDataGSM7Bit(int septetCount) {
+        String getUserDataGSM7Bit(int septetCount, int languageTable,
+                int languageShiftTable) {
             String ret;
 
             ret = GsmAlphabet.gsm7BitPackedToString(pdu, cur, septetCount,
-                    mUserDataSeptetPadding);
+                    mUserDataSeptetPadding, languageTable, languageShiftTable);
 
             cur += (septetCount * 7) / 8;
 
@@ -824,21 +773,9 @@
      */
     public static TextEncodingDetails calculateLength(CharSequence msgBody,
             boolean use7bitOnly) {
-        TextEncodingDetails ted = new TextEncodingDetails();
-        try {
-            int septets = GsmAlphabet.countGsmSeptets(msgBody, !use7bitOnly);
-            ted.codeUnitCount = septets;
-            if (septets > MAX_USER_DATA_SEPTETS) {
-                ted.msgCount = (septets + (MAX_USER_DATA_SEPTETS_WITH_HEADER - 1)) /
-                        MAX_USER_DATA_SEPTETS_WITH_HEADER;
-                ted.codeUnitsRemaining = (ted.msgCount *
-                        MAX_USER_DATA_SEPTETS_WITH_HEADER) - septets;
-            } else {
-                ted.msgCount = 1;
-                ted.codeUnitsRemaining = MAX_USER_DATA_SEPTETS - septets;
-            }
-            ted.codeUnitSize = ENCODING_7BIT;
-        } catch (EncodeException ex) {
+        TextEncodingDetails ted = GsmAlphabet.countGsmSeptets(msgBody, use7bitOnly);
+        if (ted == null) {
+            ted = new TextEncodingDetails();
             int octets = msgBody.length() * 2;
             ted.codeUnitCount = msgBody.length();
             if (octets > MAX_USER_DATA_BYTES) {
@@ -875,7 +812,7 @@
 
     /** {@inheritDoc} */
     public boolean isMWIClearMessage() {
-        if (isMwi && (mwiSense == false)) {
+        if (isMwi && !mwiSense) {
             return true;
         }
 
@@ -885,7 +822,7 @@
 
     /** {@inheritDoc} */
     public boolean isMWISetMessage() {
-        if (isMwi && (mwiSense == true)) {
+        if (isMwi && mwiSense) {
             return true;
         }
 
@@ -931,13 +868,13 @@
      * TS 27.005 3.1, <pdu> definition "In the case of SMS: 3GPP TS 24.011 [6]
      * SC address followed by 3GPP TS 23.040 [3] TPDU in hexadecimal format:
      * ME/TA converts each octet of TP data unit into two IRA character long
-     * hexad number (e.g. octet with integer value 42 is presented to TE as two
+     * hex number (e.g. octet with integer value 42 is presented to TE as two
      * characters 2A (IRA 50 and 65))" ...in the case of cell broadcast,
      * something else...
      */
     private void parsePdu(byte[] pdu) {
         mPdu = pdu;
-        // Log.d(LOG_TAG, "raw sms mesage:");
+        // Log.d(LOG_TAG, "raw sms message:");
         // Log.d(LOG_TAG, s);
 
         PduParser p = new PduParser(pdu);
@@ -1158,7 +1095,9 @@
             break;
 
         case ENCODING_7BIT:
-            messageBody = p.getUserDataGSM7Bit(count);
+            messageBody = p.getUserDataGSM7Bit(count,
+                    hasUserDataHeader ? userDataHeader.languageTable : 0,
+                    hasUserDataHeader ? userDataHeader.languageShiftTable : 0);
             break;
 
         case ENCODING_16BIT:
diff --git a/telephony/java/com/android/internal/telephony/gsm/UsimPhoneBookManager.java b/telephony/java/com/android/internal/telephony/gsm/UsimPhoneBookManager.java
index b642541..ec3d20a 100755
--- a/telephony/java/com/android/internal/telephony/gsm/UsimPhoneBookManager.java
+++ b/telephony/java/com/android/internal/telephony/gsm/UsimPhoneBookManager.java
@@ -307,8 +307,15 @@
         fileIds = mPbrFile.mFileIds.get(recNum);
         if (fileIds == null || fileIds.isEmpty()) return;
 
+
+        int extEf = 0;
+        // Only call fileIds.get while EFEXT1_TAG is available
+        if (fileIds.containsKey(USIM_EFEXT1_TAG)) {
+            extEf = fileIds.get(USIM_EFEXT1_TAG);
+        }
+
         mAdnCache.requestLoadAllAdnLike(fileIds.get(USIM_EFADN_TAG),
-            fileIds.get(USIM_EFEXT1_TAG), obtainMessage(EVENT_USIM_ADN_LOAD_DONE));
+            extEf, obtainMessage(EVENT_USIM_ADN_LOAD_DONE));
         try {
             mLock.wait();
         } catch (InterruptedException e) {
diff --git a/telephony/java/com/android/internal/telephony/sip/SipCommandInterface.java b/telephony/java/com/android/internal/telephony/sip/SipCommandInterface.java
index ed578c8..ad43c30 100644
--- a/telephony/java/com/android/internal/telephony/sip/SipCommandInterface.java
+++ b/telephony/java/com/android/internal/telephony/sip/SipCommandInterface.java
@@ -193,7 +193,7 @@
 
     public void setupDataCall(String radioTechnology, String profile,
             String apn, String user, String password, String authType,
-            Message result) {
+            String protcol, Message result) {
     }
 
     public void deactivateDataCall(int cid, Message result) {
diff --git a/telephony/java/com/android/internal/telephony/test/SimulatedCommands.java b/telephony/java/com/android/internal/telephony/test/SimulatedCommands.java
index beec177..1fc09ab 100644
--- a/telephony/java/com/android/internal/telephony/test/SimulatedCommands.java
+++ b/telephony/java/com/android/internal/telephony/test/SimulatedCommands.java
@@ -960,8 +960,9 @@
         unimplemented(result);
     }
 
-    public void setupDataCall(String radioTechnology, String profile, String apn, String user,
-            String password, String authType, Message result) {
+    public void setupDataCall(String radioTechnology, String profile,
+            String apn, String user, String password, String authType,
+            String protocol, Message result) {
         unimplemented(result);
     }
 
diff --git a/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmAlphabetTest.java b/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmAlphabetTest.java
index 3a9c511..e83a822 100644
--- a/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmAlphabetTest.java
+++ b/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmAlphabetTest.java
@@ -20,7 +20,6 @@
 
 import android.test.suitebuilder.annotation.LargeTest;
 import android.test.suitebuilder.annotation.SmallTest;
-import android.test.suitebuilder.annotation.Suppress;
 
 public class GsmAlphabetTest extends TestCase {
 
@@ -38,20 +37,21 @@
 
         String message = "aaaaaaaaaabbbbbbbbbbcccccccccc";
         byte[] userData = GsmAlphabet.stringToGsm7BitPackedWithHeader(message,
-                SmsHeader.toByteArray(header));
-        int septetCount = GsmAlphabet.countGsmSeptets(message, false);
+                SmsHeader.toByteArray(header), 0, 0);
+        int septetCount = GsmAlphabet.countGsmSeptetsUsingTables(message, true, 0, 0);
         String parsedMessage = GsmAlphabet.gsm7BitPackedToString(
-                userData, SmsHeader.toByteArray(header).length+2, septetCount, 1);
+                userData, SmsHeader.toByteArray(header).length+2, septetCount, 1, 0, 0);
         assertEquals(message, parsedMessage);
     }
 
     // TODO: This method should *really* be a series of individual test methods.
-    @LargeTest
+    // However, it's a SmallTest because it executes quickly.
+    @SmallTest
     public void testBasic() throws Exception {
         // '@' maps to char 0
         assertEquals(0, GsmAlphabet.charToGsm('@'));
 
-        // `a (a with grave accent) maps to last GSM charater
+        // `a (a with grave accent) maps to last GSM character
         assertEquals(0x7f, GsmAlphabet.charToGsm('\u00e0'));
 
         //
@@ -97,7 +97,7 @@
 
         assertEquals('@', GsmAlphabet.gsmToChar(0));
 
-        // `a (a with grave accent) maps to last GSM charater
+        // `a (a with grave accent) maps to last GSM character
         assertEquals('\u00e0', GsmAlphabet.gsmToChar(0x7f));
 
         assertEquals('\uffff',
@@ -116,8 +116,12 @@
         assertEquals(' ', GsmAlphabet.gsmExtendedToChar(
                 GsmAlphabet.GSM_EXTENDED_ESCAPE));
 
-        // Unmappable
-        assertEquals(' ', GsmAlphabet.gsmExtendedToChar(0));
+        // Reserved for extension to extension table (mapped to space)
+        assertEquals(' ', GsmAlphabet.gsmExtendedToChar(GsmAlphabet.GSM_EXTENDED_ESCAPE));
+
+        // Unmappable (mapped to character in default or national locking shift table)
+        assertEquals('@', GsmAlphabet.gsmExtendedToChar(0));
+        assertEquals('\u00e0', GsmAlphabet.gsmExtendedToChar(0x7f));
 
         //
         // stringTo7BitPacked, gsm7BitPackedToString
@@ -128,7 +132,7 @@
 
         // Check all alignment cases
         for (int i = 0; i < 9; i++, testString.append('@')) {
-            packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString());
+            packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString(), 0, 0);
             assertEquals(testString.toString(),
                     GsmAlphabet.gsm7BitPackedToString(packed, 1, 0xff & packed[0]));
         }
@@ -149,7 +153,7 @@
             assertEquals(1, GsmAlphabet.countGsmSeptets(c));
         }
 
-        packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString());
+        packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString(), 0, 0);
         assertEquals(testString.toString(),
                 GsmAlphabet.gsm7BitPackedToString(packed, 1, 0xff & packed[0]));
 
@@ -164,7 +168,7 @@
 
         }
 
-        packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString());
+        packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString(), 0, 0);
         assertEquals(testString.toString(),
                 GsmAlphabet.gsm7BitPackedToString(packed, 1, 0xff & packed[0]));
 
@@ -175,7 +179,7 @@
             testString.append('@');
         }
 
-        packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString());
+        packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString(), 0, 0);
         assertEquals(testString.toString(),
                 GsmAlphabet.gsm7BitPackedToString(packed, 1, 0xff & packed[0]));
 
@@ -183,7 +187,7 @@
         testString.append('@');
 
         try {
-            GsmAlphabet.stringToGsm7BitPacked(testString.toString());
+            GsmAlphabet.stringToGsm7BitPacked(testString.toString(), 0, 0);
             fail("expected exception");
         } catch (EncodeException ex) {
             // exception expected
@@ -196,7 +200,7 @@
             testString.append('{');
         }
 
-        packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString());
+        packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString(), 0, 0);
         assertEquals(testString.toString(),
                 GsmAlphabet.gsm7BitPackedToString(packed, 1, 0xff & packed[0]));
 
@@ -204,17 +208,29 @@
         testString.append('{');
 
         try {
-            GsmAlphabet.stringToGsm7BitPacked(testString.toString());
+            GsmAlphabet.stringToGsm7BitPacked(testString.toString(), 0, 0);
             fail("expected exception");
         } catch (EncodeException ex) {
             // exception expected
         }
 
+        // Reserved for extension to extension table (mapped to space)
+        packed = new byte[]{(byte)(0x1b | 0x80), 0x1b >> 1};
+        assertEquals(" ", GsmAlphabet.gsm7BitPackedToString(packed, 0, 2));
+
+        // Unmappable (mapped to character in default alphabet table)
+        packed[0] = 0x1b;
+        packed[1] = 0x00;
+        assertEquals("@", GsmAlphabet.gsm7BitPackedToString(packed, 0, 2));
+        packed[0] = (byte)(0x1b | 0x80);
+        packed[1] = (byte)(0x7f >> 1);
+        assertEquals("\u00e0", GsmAlphabet.gsm7BitPackedToString(packed, 0, 2));
+
         //
         // 8 bit unpacked format
         //
         // Note: we compare hex strings here
-        // because Assert doesnt have array-comparisons
+        // because Assert doesn't have array comparisons
 
         byte unpacked[];
 
@@ -306,5 +322,16 @@
 
         assertEquals("a",
                 GsmAlphabet.gsm8BitUnpackedToString(unpacked, 1, unpacked.length - 1));
+
+        // Reserved for extension to extension table (mapped to space)
+        unpacked[0] = 0x1b;
+        unpacked[1] = 0x1b;
+        assertEquals(" ", GsmAlphabet.gsm8BitUnpackedToString(unpacked, 0, 2));
+
+        // Unmappable (mapped to character in default or national locking shift table)
+        unpacked[1] = 0x00;
+        assertEquals("@", GsmAlphabet.gsm8BitUnpackedToString(unpacked, 0, 2));
+        unpacked[1] = 0x7f;
+        assertEquals("\u00e0", GsmAlphabet.gsm8BitUnpackedToString(unpacked, 0, 2));
     }
 }
diff --git a/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmSmsCbTest.java b/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmSmsCbTest.java
index 7136ea0..417aac4 100644
--- a/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmSmsCbTest.java
+++ b/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmSmsCbTest.java
@@ -18,6 +18,7 @@
 
 import android.telephony.SmsCbMessage;
 import android.test.AndroidTestCase;
+import android.util.Log;
 
 /**
  * Test cases for basic SmsCbMessage operations
@@ -69,6 +70,36 @@
         doTestGeographicalScopeValue(pdu, (byte)0xC0, SmsCbMessage.GEOGRAPHICAL_SCOPE_CELL_WIDE);
     }
 
+    public void testGetGeographicalScopeUmts() {
+        byte[] pdu = {
+                (byte)0x01, (byte)0x00, (byte)0x32, (byte)0xC0, (byte)0x00, (byte)0x40,
+
+                (byte)0x01,
+
+                (byte)0x41, (byte)0xD0, (byte)0x71, (byte)0xDA, (byte)0x04, (byte)0x91,
+                (byte)0xCB, (byte)0xE6, (byte)0x70, (byte)0x9D, (byte)0x4D, (byte)0x07,
+                (byte)0x85, (byte)0xD9, (byte)0x70, (byte)0x74, (byte)0x58, (byte)0x5C,
+                (byte)0xA6, (byte)0x83, (byte)0xDA, (byte)0xE5, (byte)0xF9, (byte)0x3C,
+                (byte)0x7C, (byte)0x2E, (byte)0x83, (byte)0xEE, (byte)0x69, (byte)0x3A,
+                (byte)0x1A, (byte)0x34, (byte)0x0E, (byte)0xCB, (byte)0xE5, (byte)0xE9,
+                (byte)0xF0, (byte)0xB9, (byte)0x0C, (byte)0x92, (byte)0x97, (byte)0xE9,
+                (byte)0x75, (byte)0xB9, (byte)0x1B, (byte)0x04, (byte)0x0F, (byte)0x93,
+                (byte)0xC9, (byte)0x69, (byte)0xF7, (byte)0xB9, (byte)0xD1, (byte)0x68,
+                (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3, (byte)0xD1,
+                (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3,
+                (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46,
+                (byte)0xA3, (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D,
+                (byte)0x46, (byte)0xA3, (byte)0xD1, (byte)0x00,
+
+                (byte)0x34
+        };
+
+        SmsCbMessage msg = SmsCbMessage.createFromPdu(pdu);
+
+        assertEquals("Unexpected geographical scope decoded",
+                SmsCbMessage.GEOGRAPHICAL_SCOPE_CELL_WIDE, msg.getGeographicalScope());
+    }
+
     public void testGetMessageBody7Bit() {
         byte[] pdu = {
                 (byte)0xC0, (byte)0x00, (byte)0x00, (byte)0x32, (byte)0x40, (byte)0x11, (byte)0x41,
@@ -92,6 +123,83 @@
                 msg.getMessageBody());
     }
 
+    public void testGetMessageBody7BitUmts() {
+        byte[] pdu = {
+                (byte)0x01, (byte)0x00, (byte)0x32, (byte)0xC0, (byte)0x00, (byte)0x40,
+
+                (byte)0x01,
+
+                (byte)0x41, (byte)0xD0, (byte)0x71, (byte)0xDA, (byte)0x04, (byte)0x91,
+                (byte)0xCB, (byte)0xE6, (byte)0x70, (byte)0x9D, (byte)0x4D, (byte)0x07,
+                (byte)0x85, (byte)0xD9, (byte)0x70, (byte)0x74, (byte)0x58, (byte)0x5C,
+                (byte)0xA6, (byte)0x83, (byte)0xDA, (byte)0xE5, (byte)0xF9, (byte)0x3C,
+                (byte)0x7C, (byte)0x2E, (byte)0x83, (byte)0xEE, (byte)0x69, (byte)0x3A,
+                (byte)0x1A, (byte)0x34, (byte)0x0E, (byte)0xCB, (byte)0xE5, (byte)0xE9,
+                (byte)0xF0, (byte)0xB9, (byte)0x0C, (byte)0x92, (byte)0x97, (byte)0xE9,
+                (byte)0x75, (byte)0xB9, (byte)0x1B, (byte)0x04, (byte)0x0F, (byte)0x93,
+                (byte)0xC9, (byte)0x69, (byte)0xF7, (byte)0xB9, (byte)0xD1, (byte)0x68,
+                (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3, (byte)0xD1,
+                (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3,
+                (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46,
+                (byte)0xA3, (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D,
+                (byte)0x46, (byte)0xA3, (byte)0xD1, (byte)0x00,
+
+                (byte)0x34
+        };
+        SmsCbMessage msg = SmsCbMessage.createFromPdu(pdu);
+
+        assertEquals("Unexpected 7-bit string decoded",
+                "A GSM default alphabet message with carriage return padding",
+                msg.getMessageBody());
+    }
+
+    public void testGetMessageBody7BitMultipageUmts() {
+        byte[] pdu = {
+                (byte)0x01, (byte)0x00, (byte)0x01, (byte)0xC0, (byte)0x00, (byte)0x40,
+
+                (byte)0x02,
+
+                (byte)0xC6, (byte)0xB4, (byte)0x7C, (byte)0x4E, (byte)0x07, (byte)0xC1,
+                (byte)0xC3, (byte)0xE7, (byte)0xF2, (byte)0xAA, (byte)0xD1, (byte)0x68,
+                (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3, (byte)0xD1,
+                (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3,
+                (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46,
+                (byte)0xA3, (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D,
+                (byte)0x46, (byte)0xA3, (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A,
+                (byte)0x8D, (byte)0x46, (byte)0xA3, (byte)0xD1, (byte)0x68, (byte)0x34,
+                (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3, (byte)0xD1, (byte)0x68,
+                (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3, (byte)0xD1,
+                (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3,
+                (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46,
+                (byte)0xA3, (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D,
+                (byte)0x46, (byte)0xA3, (byte)0xD1, (byte)0x00,
+
+                (byte)0x0A,
+
+                (byte)0xD3, (byte)0xF2, (byte)0xF8, (byte)0xED, (byte)0x26, (byte)0x83,
+                (byte)0xE0, (byte)0xE1, (byte)0x73, (byte)0xB9, (byte)0xD1, (byte)0x68,
+                (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3, (byte)0xD1,
+                (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3,
+                (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46,
+                (byte)0xA3, (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D,
+                (byte)0x46, (byte)0xA3, (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A,
+                (byte)0x8D, (byte)0x46, (byte)0xA3, (byte)0xD1, (byte)0x68, (byte)0x34,
+                (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3, (byte)0xD1, (byte)0x68,
+                (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3, (byte)0xD1,
+                (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3,
+                (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46,
+                (byte)0xA3, (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D,
+                (byte)0x46, (byte)0xA3, (byte)0xD1, (byte)0x00,
+
+                (byte)0x0A
+        };
+        SmsCbMessage msg = SmsCbMessage.createFromPdu(pdu);
+
+        assertEquals("Unexpected multipage 7-bit string decoded",
+                "First page+Second page",
+                msg.getMessageBody());
+    }
+
     public void testGetMessageBody7BitFull() {
         byte[] pdu = {
                 (byte)0xC0, (byte)0x00, (byte)0x00, (byte)0x32, (byte)0x40, (byte)0x11, (byte)0x41,
@@ -117,6 +225,38 @@
                 msg.getMessageBody());
     }
 
+    public void testGetMessageBody7BitFullUmts() {
+        byte[] pdu = {
+                (byte)0x01, (byte)0x00, (byte)0x32, (byte)0xC0, (byte)0x00, (byte)0x40,
+
+                (byte)0x01,
+
+                (byte)0x41, (byte)0xD0, (byte)0x71, (byte)0xDA, (byte)0x04, (byte)0x91,
+                (byte)0xCB, (byte)0xE6, (byte)0x70, (byte)0x9D, (byte)0x4D, (byte)0x07,
+                (byte)0x85, (byte)0xD9, (byte)0x70, (byte)0x74, (byte)0x58, (byte)0x5C,
+                (byte)0xA6, (byte)0x83, (byte)0xDA, (byte)0xE5, (byte)0xF9, (byte)0x3C,
+                (byte)0x7C, (byte)0x2E, (byte)0x83, (byte)0xC4, (byte)0xE5, (byte)0xB4,
+                (byte)0xFB, (byte)0x0C, (byte)0x2A, (byte)0xE3, (byte)0xC3, (byte)0x63,
+                (byte)0x3A, (byte)0x3B, (byte)0x0F, (byte)0xCA, (byte)0xCD, (byte)0x40,
+                (byte)0x63, (byte)0x74, (byte)0x58, (byte)0x1E, (byte)0x1E, (byte)0xD3,
+                (byte)0xCB, (byte)0xF2, (byte)0x39, (byte)0x88, (byte)0xFD, (byte)0x76,
+                (byte)0x9F, (byte)0x59, (byte)0xA0, (byte)0x76, (byte)0x39, (byte)0xEC,
+                (byte)0x4E, (byte)0xBB, (byte)0xCF, (byte)0x20, (byte)0x3A, (byte)0xBA,
+                (byte)0x2C, (byte)0x2F, (byte)0x83, (byte)0xD2, (byte)0x73, (byte)0x90,
+                (byte)0xFB, (byte)0x0D, (byte)0x82, (byte)0x87, (byte)0xC9, (byte)0xE4,
+                (byte)0xB4, (byte)0xFB, (byte)0x1C, (byte)0x02,
+
+                (byte)0x52
+        };
+        SmsCbMessage msg = SmsCbMessage.createFromPdu(pdu);
+
+        assertEquals(
+                "Unexpected 7-bit string decoded",
+                "A GSM default alphabet message being exactly 93 characters long, " +
+                "meaning there is no padding!",
+                msg.getMessageBody());
+    }
+
     public void testGetMessageBody7BitWithLanguage() {
         byte[] pdu = {
                 (byte)0xC0, (byte)0x00, (byte)0x00, (byte)0x32, (byte)0x04, (byte)0x11, (byte)0x41,
@@ -167,6 +307,38 @@
         assertEquals("Unexpected language indicator decoded", "sv", msg.getLanguageCode());
     }
 
+    public void testGetMessageBody7BitWithLanguageInBodyUmts() {
+        byte[] pdu = {
+                (byte)0x01, (byte)0x00, (byte)0x32, (byte)0xC0, (byte)0x00, (byte)0x10,
+
+                (byte)0x01,
+
+                (byte)0x73, (byte)0x7B, (byte)0x23, (byte)0x08, (byte)0x3A, (byte)0x4E,
+                (byte)0x9B, (byte)0x20, (byte)0x72, (byte)0xD9, (byte)0x1C, (byte)0xAE,
+                (byte)0xB3, (byte)0xE9, (byte)0xA0, (byte)0x30, (byte)0x1B, (byte)0x8E,
+                (byte)0x0E, (byte)0x8B, (byte)0xCB, (byte)0x74, (byte)0x50, (byte)0xBB,
+                (byte)0x3C, (byte)0x9F, (byte)0x87, (byte)0xCF, (byte)0x65, (byte)0xD0,
+                (byte)0x3D, (byte)0x4D, (byte)0x47, (byte)0x83, (byte)0xC6, (byte)0x61,
+                (byte)0xB9, (byte)0x3C, (byte)0x1D, (byte)0x3E, (byte)0x97, (byte)0x41,
+                (byte)0xF2, (byte)0x32, (byte)0xBD, (byte)0x2E, (byte)0x77, (byte)0x83,
+                (byte)0xE0, (byte)0x61, (byte)0x32, (byte)0x39, (byte)0xED, (byte)0x3E,
+                (byte)0x37, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3, (byte)0xD1,
+                (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3,
+                (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46,
+                (byte)0xA3, (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D,
+                (byte)0x46, (byte)0xA3, (byte)0xD1, (byte)0x00,
+
+                (byte)0x37
+        };
+        SmsCbMessage msg = SmsCbMessage.createFromPdu(pdu);
+
+        assertEquals("Unexpected 7-bit string decoded",
+                "A GSM default alphabet message with carriage return padding",
+                msg.getMessageBody());
+
+        assertEquals("Unexpected language indicator decoded", "sv", msg.getLanguageCode());
+    }
+
     public void testGetMessageBody8Bit() {
         byte[] pdu = {
                 (byte)0xC0, (byte)0x00, (byte)0x00, (byte)0x32, (byte)0x44, (byte)0x11, (byte)0x41,
@@ -210,6 +382,81 @@
                 "A UCS2 message containing a \u0434 character", msg.getMessageBody());
     }
 
+    public void testGetMessageBodyUcs2Umts() {
+        byte[] pdu = {
+                (byte)0x01, (byte)0x00, (byte)0x32, (byte)0xC0, (byte)0x00, (byte)0x48,
+
+                (byte)0x01,
+
+                (byte)0x00, (byte)0x41, (byte)0x00, (byte)0x20, (byte)0x00, (byte)0x55,
+                (byte)0x00, (byte)0x43, (byte)0x00, (byte)0x53, (byte)0x00, (byte)0x32,
+                (byte)0x00, (byte)0x20, (byte)0x00, (byte)0x6D, (byte)0x00, (byte)0x65,
+                (byte)0x00, (byte)0x73, (byte)0x00, (byte)0x73, (byte)0x00, (byte)0x61,
+                (byte)0x00, (byte)0x67, (byte)0x00, (byte)0x65, (byte)0x00, (byte)0x20,
+                (byte)0x00, (byte)0x63, (byte)0x00, (byte)0x6F, (byte)0x00, (byte)0x6E,
+                (byte)0x00, (byte)0x74, (byte)0x00, (byte)0x61, (byte)0x00, (byte)0x69,
+                (byte)0x00, (byte)0x6E, (byte)0x00, (byte)0x69, (byte)0x00, (byte)0x6E,
+                (byte)0x00, (byte)0x67, (byte)0x00, (byte)0x20, (byte)0x00, (byte)0x61,
+                (byte)0x00, (byte)0x20, (byte)0x04, (byte)0x34, (byte)0x00, (byte)0x20,
+                (byte)0x00, (byte)0x63, (byte)0x00, (byte)0x68, (byte)0x00, (byte)0x61,
+                (byte)0x00, (byte)0x72, (byte)0x00, (byte)0x61, (byte)0x00, (byte)0x63,
+                (byte)0x00, (byte)0x74, (byte)0x00, (byte)0x65, (byte)0x00, (byte)0x72,
+                (byte)0x00, (byte)0x0D, (byte)0x00, (byte)0x0D,
+
+                (byte)0x4E
+        };
+        SmsCbMessage msg = SmsCbMessage.createFromPdu(pdu);
+
+        assertEquals("Unexpected 7-bit string decoded",
+                "A UCS2 message containing a \u0434 character", msg.getMessageBody());
+    }
+
+    public void testGetMessageBodyUcs2MultipageUmts() {
+        byte[] pdu = {
+                (byte)0x01, (byte)0x00, (byte)0x32, (byte)0xC0, (byte)0x00, (byte)0x48,
+
+                (byte)0x02,
+
+                (byte)0x00, (byte)0x41, (byte)0x00, (byte)0x41, (byte)0x00, (byte)0x41,
+                (byte)0x00, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+
+                (byte)0x06,
+
+                (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x42,
+                (byte)0x00, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+                (byte)0x0D, (byte)0x0D, (byte)0x0D, (byte)0x0D,
+
+                (byte)0x06
+        };
+        SmsCbMessage msg = SmsCbMessage.createFromPdu(pdu);
+
+        assertEquals("Unexpected multipage UCS2 string decoded",
+                "AAABBB", msg.getMessageBody());
+    }
+
     public void testGetMessageBodyUcs2WithLanguageInBody() {
         byte[] pdu = {
                 (byte)0xC0, (byte)0x00, (byte)0x00, (byte)0x32, (byte)0x11, (byte)0x11, (byte)0x78,
@@ -234,6 +481,37 @@
         assertEquals("Unexpected language indicator decoded", "xx", msg.getLanguageCode());
     }
 
+    public void testGetMessageBodyUcs2WithLanguageInBodyUmts() {
+        byte[] pdu = {
+                (byte)0x01, (byte)0x00, (byte)0x32, (byte)0xC0, (byte)0x00, (byte)0x11,
+
+                (byte)0x01,
+
+                (byte)0x78, (byte)0x3C, (byte)0x00, (byte)0x41, (byte)0x00, (byte)0x20,
+                (byte)0x00, (byte)0x55, (byte)0x00, (byte)0x43, (byte)0x00, (byte)0x53,
+                (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x20, (byte)0x00, (byte)0x6D,
+                (byte)0x00, (byte)0x65, (byte)0x00, (byte)0x73, (byte)0x00, (byte)0x73,
+                (byte)0x00, (byte)0x61, (byte)0x00, (byte)0x67, (byte)0x00, (byte)0x65,
+                (byte)0x00, (byte)0x20, (byte)0x00, (byte)0x63, (byte)0x00, (byte)0x6F,
+                (byte)0x00, (byte)0x6E, (byte)0x00, (byte)0x74, (byte)0x00, (byte)0x61,
+                (byte)0x00, (byte)0x69, (byte)0x00, (byte)0x6E, (byte)0x00, (byte)0x69,
+                (byte)0x00, (byte)0x6E, (byte)0x00, (byte)0x67, (byte)0x00, (byte)0x20,
+                (byte)0x00, (byte)0x61, (byte)0x00, (byte)0x20, (byte)0x04, (byte)0x34,
+                (byte)0x00, (byte)0x20, (byte)0x00, (byte)0x63, (byte)0x00, (byte)0x68,
+                (byte)0x00, (byte)0x61, (byte)0x00, (byte)0x72, (byte)0x00, (byte)0x61,
+                (byte)0x00, (byte)0x63, (byte)0x00, (byte)0x74, (byte)0x00, (byte)0x65,
+                (byte)0x00, (byte)0x72, (byte)0x00, (byte)0x0D,
+
+                (byte)0x50
+        };
+        SmsCbMessage msg = SmsCbMessage.createFromPdu(pdu);
+
+        assertEquals("Unexpected 7-bit string decoded",
+                "A UCS2 message containing a \u0434 character", msg.getMessageBody());
+
+        assertEquals("Unexpected language indicator decoded", "xx", msg.getLanguageCode());
+    }
+
     public void testGetMessageIdentifier() {
         byte[] pdu = {
                 (byte)0xC0, (byte)0x00, (byte)0x30, (byte)0x39, (byte)0x40, (byte)0x11, (byte)0x41,
@@ -256,6 +534,35 @@
         assertEquals("Unexpected message identifier decoded", 12345, msg.getMessageIdentifier());
     }
 
+    public void testGetMessageIdentifierUmts() {
+        byte[] pdu = {
+                (byte)0x01, (byte)0x30, (byte)0x39, (byte)0x2A, (byte)0xA5, (byte)0x40,
+
+                (byte)0x01,
+
+                (byte)0x41, (byte)0xD0, (byte)0x71, (byte)0xDA, (byte)0x04, (byte)0x91,
+                (byte)0xCB, (byte)0xE6, (byte)0x70, (byte)0x9D, (byte)0x4D, (byte)0x07,
+                (byte)0x85, (byte)0xD9, (byte)0x70, (byte)0x74, (byte)0x58, (byte)0x5C,
+                (byte)0xA6, (byte)0x83, (byte)0xDA, (byte)0xE5, (byte)0xF9, (byte)0x3C,
+                (byte)0x7C, (byte)0x2E, (byte)0x83, (byte)0xEE, (byte)0x69, (byte)0x3A,
+                (byte)0x1A, (byte)0x34, (byte)0x0E, (byte)0xCB, (byte)0xE5, (byte)0xE9,
+                (byte)0xF0, (byte)0xB9, (byte)0x0C, (byte)0x92, (byte)0x97, (byte)0xE9,
+                (byte)0x75, (byte)0xB9, (byte)0x1B, (byte)0x04, (byte)0x0F, (byte)0x93,
+                (byte)0xC9, (byte)0x69, (byte)0xF7, (byte)0xB9, (byte)0xD1, (byte)0x68,
+                (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3, (byte)0xD1,
+                (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3,
+                (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46,
+                (byte)0xA3, (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D,
+                (byte)0x46, (byte)0xA3, (byte)0xD1, (byte)0x00,
+
+                (byte)0x34
+        };
+
+        SmsCbMessage msg = SmsCbMessage.createFromPdu(pdu);
+
+        assertEquals("Unexpected message identifier decoded", 12345, msg.getMessageIdentifier());
+    }
+
     public void testGetMessageCode() {
         byte[] pdu = {
                 (byte)0x2A, (byte)0xA5, (byte)0x30, (byte)0x39, (byte)0x40, (byte)0x11, (byte)0x41,
@@ -278,6 +585,35 @@
         assertEquals("Unexpected message code decoded", 682, msg.getMessageCode());
     }
 
+    public void testGetMessageCodeUmts() {
+        byte[] pdu = {
+                (byte)0x01, (byte)0x30, (byte)0x39, (byte)0x2A, (byte)0xA5, (byte)0x40,
+
+                (byte)0x01,
+
+                (byte)0x41, (byte)0xD0, (byte)0x71, (byte)0xDA, (byte)0x04, (byte)0x91,
+                (byte)0xCB, (byte)0xE6, (byte)0x70, (byte)0x9D, (byte)0x4D, (byte)0x07,
+                (byte)0x85, (byte)0xD9, (byte)0x70, (byte)0x74, (byte)0x58, (byte)0x5C,
+                (byte)0xA6, (byte)0x83, (byte)0xDA, (byte)0xE5, (byte)0xF9, (byte)0x3C,
+                (byte)0x7C, (byte)0x2E, (byte)0x83, (byte)0xEE, (byte)0x69, (byte)0x3A,
+                (byte)0x1A, (byte)0x34, (byte)0x0E, (byte)0xCB, (byte)0xE5, (byte)0xE9,
+                (byte)0xF0, (byte)0xB9, (byte)0x0C, (byte)0x92, (byte)0x97, (byte)0xE9,
+                (byte)0x75, (byte)0xB9, (byte)0x1B, (byte)0x04, (byte)0x0F, (byte)0x93,
+                (byte)0xC9, (byte)0x69, (byte)0xF7, (byte)0xB9, (byte)0xD1, (byte)0x68,
+                (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3, (byte)0xD1,
+                (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3,
+                (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46,
+                (byte)0xA3, (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D,
+                (byte)0x46, (byte)0xA3, (byte)0xD1, (byte)0x00,
+
+                (byte)0x34
+        };
+
+        SmsCbMessage msg = SmsCbMessage.createFromPdu(pdu);
+
+        assertEquals("Unexpected message code decoded", 682, msg.getMessageCode());
+    }
+
     public void testGetUpdateNumber() {
         byte[] pdu = {
                 (byte)0x2A, (byte)0xA5, (byte)0x30, (byte)0x39, (byte)0x40, (byte)0x11, (byte)0x41,
@@ -299,4 +635,78 @@
 
         assertEquals("Unexpected update number decoded", 5, msg.getUpdateNumber());
     }
+
+    public void testGetUpdateNumberUmts() {
+        byte[] pdu = {
+                (byte)0x01, (byte)0x30, (byte)0x39, (byte)0x2A, (byte)0xA5, (byte)0x40,
+
+                (byte)0x01,
+
+                (byte)0x41, (byte)0xD0, (byte)0x71, (byte)0xDA, (byte)0x04, (byte)0x91,
+                (byte)0xCB, (byte)0xE6, (byte)0x70, (byte)0x9D, (byte)0x4D, (byte)0x07,
+                (byte)0x85, (byte)0xD9, (byte)0x70, (byte)0x74, (byte)0x58, (byte)0x5C,
+                (byte)0xA6, (byte)0x83, (byte)0xDA, (byte)0xE5, (byte)0xF9, (byte)0x3C,
+                (byte)0x7C, (byte)0x2E, (byte)0x83, (byte)0xEE, (byte)0x69, (byte)0x3A,
+                (byte)0x1A, (byte)0x34, (byte)0x0E, (byte)0xCB, (byte)0xE5, (byte)0xE9,
+                (byte)0xF0, (byte)0xB9, (byte)0x0C, (byte)0x92, (byte)0x97, (byte)0xE9,
+                (byte)0x75, (byte)0xB9, (byte)0x1B, (byte)0x04, (byte)0x0F, (byte)0x93,
+                (byte)0xC9, (byte)0x69, (byte)0xF7, (byte)0xB9, (byte)0xD1, (byte)0x68,
+                (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3, (byte)0xD1,
+                (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46, (byte)0xA3,
+                (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D, (byte)0x46,
+                (byte)0xA3, (byte)0xD1, (byte)0x68, (byte)0x34, (byte)0x1A, (byte)0x8D,
+                (byte)0x46, (byte)0xA3, (byte)0xD1, (byte)0x00,
+
+                (byte)0x34
+        };
+
+        SmsCbMessage msg = SmsCbMessage.createFromPdu(pdu);
+
+        assertEquals("Unexpected update number decoded", 5, msg.getUpdateNumber());
+    }
+
+    /* ETWS Test message including header */
+    private static final byte[] etwsMessageNormal = IccUtils.hexStringToBytes("000011001101" +
+            "0D0A5BAE57CE770C531790E85C716CBF3044573065B930675730" +
+            "9707767A751F30025F37304463FA308C306B5099304830664E0B30553044FF086C178C615E81FF09" +
+            "0000000000000000000000000000");
+
+    private static final byte[] etwsMessageCancel = IccUtils.hexStringToBytes("000011001101" +
+            "0D0A5148307B3069002800310030003A0035" +
+            "00320029306E7DCA602557309707901F5831309253D66D883057307E3059FF086C178C615E81FF09" +
+            "00000000000000000000000000000000000000000000");
+
+    private static final byte[] etwsMessageTest = IccUtils.hexStringToBytes("000011031101" +
+            "0D0A5BAE57CE770C531790E85C716CBF3044" +
+            "573065B9306757309707300263FA308C306B5099304830664E0B30553044FF086C178C615E81FF09" +
+            "00000000000000000000000000000000000000000000");
+
+    // FIXME: add example of ETWS primary notification PDU
+
+    public void testEtwsMessageNormal() {
+        SmsCbMessage msg = SmsCbMessage.createFromPdu(etwsMessageNormal);
+        Log.d("GsmSmsCbTest", msg.toString());
+        assertEquals("GS mismatch", 0, msg.getGeographicalScope());
+        assertEquals("message code mismatch", 0, msg.getMessageCode());
+        assertEquals("update number mismatch", 0, msg.getUpdateNumber());
+        assertEquals("message ID mismatch", 0x1100, msg.getMessageIdentifier());
+    }
+
+    public void testEtwsMessageCancel() {
+        SmsCbMessage msg = SmsCbMessage.createFromPdu(etwsMessageCancel);
+        Log.d("GsmSmsCbTest", msg.toString());
+        assertEquals("GS mismatch", 0, msg.getGeographicalScope());
+        assertEquals("message code mismatch", 0, msg.getMessageCode());
+        assertEquals("update number mismatch", 0, msg.getUpdateNumber());
+        assertEquals("message ID mismatch", 0x1100, msg.getMessageIdentifier());
+    }
+
+    public void testEtwsMessageTest() {
+        SmsCbMessage msg = SmsCbMessage.createFromPdu(etwsMessageTest);
+        Log.d("GsmSmsCbTest", msg.toString());
+        assertEquals("GS mismatch", 0, msg.getGeographicalScope());
+        assertEquals("message code mismatch", 0, msg.getMessageCode());
+        assertEquals("update number mismatch", 0, msg.getUpdateNumber());
+        assertEquals("message ID mismatch", 0x1103, msg.getMessageIdentifier());
+    }
 }
diff --git a/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmSmsTest.java b/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmSmsTest.java
index 3103fc1..41a719e 100644
--- a/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmSmsTest.java
+++ b/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmSmsTest.java
@@ -16,16 +16,12 @@
 
 package com.android.internal.telephony;
 
-import com.android.internal.telephony.GsmAlphabet;
-import com.android.internal.telephony.SmsHeader;
 import com.android.internal.telephony.gsm.SmsMessage;
 import com.android.internal.util.HexDump;
 
 import android.test.AndroidTestCase;
 import android.test.suitebuilder.annotation.SmallTest;
 
-import android.util.Log;
-
 public class GsmSmsTest extends AndroidTestCase {
 
     @SmallTest
@@ -211,8 +207,38 @@
                 sms.getMessageBody());
     }
 
+    // GSM 7 bit tables in String form, Escape (0x1B) replaced with '@'
+    private static final String[] sBasicTables = {
+        // GSM 7 bit default alphabet
+        "@\u00a3$\u00a5\u00e8\u00e9\u00f9\u00ec\u00f2\u00c7\n\u00d8\u00f8\r\u00c5\u00e5\u0394_"
+            + "\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e@\u00c6\u00e6\u00df\u00c9"
+            + " !\"#\u00a4%&'()*+,-./0123456789:;<=>?\u00a1ABCDEFGHIJKLMNOPQRSTUVWXYZ\u00c4\u00d6"
+            + "\u00d1\u00dc\u00a7\u00bfabcdefghijklmnopqrstuvwxyz\u00e4\u00f6\u00f1\u00fc\u00e0",
+
+        // Turkish locking shift table
+        "@\u00a3$\u00a5\u20ac\u00e9\u00f9\u0131\u00f2\u00c7\n\u011e\u011f\r\u00c5\u00e5\u0394_"
+            + "\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e@\u015e\u015f\u00df\u00c9"
+            + " !\"#\u00a4%&'()*+,-./0123456789:;<=>?\u0130ABCDEFGHIJKLMNOPQRSTUVWXYZ\u00c4\u00d6"
+            + "\u00d1\u00dc\u00a7\u00e7abcdefghijklmnopqrstuvwxyz\u00e4\u00f6\u00f1\u00fc\u00e0",
+
+        // no locking shift table defined for Spanish
+        "",
+
+        // Portuguese locking shift table
+        "@\u00a3$\u00a5\u00ea\u00e9\u00fa\u00ed\u00f3\u00e7\n\u00d4\u00f4\r\u00c1\u00e1\u0394_"
+            + "\u00aa\u00c7\u00c0\u221e^\\\u20ac\u00d3|@\u00c2\u00e2\u00ca\u00c9 !\"#\u00ba%&'()"
+            + "*+,-./0123456789:;<=>?\u00cdABCDEFGHIJKLMNOPQRSTUVWXYZ\u00c3\u00d5\u00da\u00dc"
+            + "\u00a7~abcdefghijklmnopqrstuvwxyz\u00e3\u00f5`\u00fc\u00e0"
+    };
+
     @SmallTest
     public void testDecode() throws Exception {
+        decodeSingle(0);    // default table
+        decodeSingle(1);    // Turkish locking shift table
+        decodeSingle(3);    // Portuguese locking shift table
+    }
+
+    private void decodeSingle(int language) throws Exception {
         byte[] septets = new byte[(7 * 128 + 7) / 8];
 
         int bitOffset = 0;
@@ -238,15 +264,168 @@
             bitOffset += 7;
         }
 
-        String decoded = GsmAlphabet.gsm7BitPackedToString(septets, 0, 128);
-        byte[] reEncoded = GsmAlphabet.stringToGsm7BitPacked(decoded);
+        String decoded = GsmAlphabet.gsm7BitPackedToString(septets, 0, 128, 0, language, 0);
+        byte[] reEncoded = GsmAlphabet.stringToGsm7BitPacked(decoded, language, 0);
+
+        assertEquals(sBasicTables[language], decoded);
 
         // reEncoded has the count septets byte at the front
-        assertEquals(reEncoded.length, septets.length + 1);
+        assertEquals(septets.length + 1, reEncoded.length);
 
         for (int i = 0; i < septets.length; i++) {
-            assertEquals(reEncoded[i + 1], septets[i]);
+            assertEquals(septets[i], reEncoded[i + 1]);
         }
     }
 
+    private static final int GSM_ESCAPE_CHARACTER = 0x1b;
+
+    private static final String[] sExtendedTables = {
+        // GSM 7 bit default alphabet extension table
+        "\f^{}\\[~]|\u20ac",
+
+        // Turkish single shift extension table
+        "\f^{}\\[~]|\u011e\u0130\u015e\u00e7\u20ac\u011f\u0131\u015f",
+
+        // Spanish single shift extension table
+        "\u00e7\f^{}\\[~]|\u00c1\u00cd\u00d3\u00da\u00e1\u20ac\u00ed\u00f3\u00fa",
+
+        // Portuguese single shift extension table
+        "\u00ea\u00e7\f\u00d4\u00f4\u00c1\u00e1\u03a6\u0393^\u03a9\u03a0\u03a8\u03a3\u0398\u00ca"
+            + "{}\\[~]|\u00c0\u00cd\u00d3\u00da\u00c3\u00d5\u00c2\u20ac\u00ed\u00f3\u00fa\u00e3"
+            + "\u00f5\u00e2"
+    };
+
+    private static final int[][] sExtendedTableIndexes = {
+        {0x0a, 0x14, 0x28, 0x29, 0x2f, 0x3c, 0x3d, 0x3e, 0x40, 0x65},
+        {0x0a, 0x14, 0x28, 0x29, 0x2f, 0x3c, 0x3d, 0x3e, 0x40, 0x47, 0x49, 0x53, 0x63,
+                0x65, 0x67, 0x69, 0x73},
+        {0x09, 0x0a, 0x14, 0x28, 0x29, 0x2f, 0x3c, 0x3d, 0x3e, 0x40, 0x41, 0x49, 0x4f,
+                0x55, 0x61, 0x65, 0x69, 0x6f, 0x75},
+        {0x05, 0x09, 0x0a, 0x0b, 0x0c, 0x0e, 0x0f, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
+                0x18, 0x19, 0x1f, 0x28, 0x29, 0x2f, 0x3c, 0x3d, 0x3e, 0x40, 0x41, 0x49,
+                0x4f, 0x55, 0x5b, 0x5c, 0x61, 0x65, 0x69, 0x6f, 0x75, 0x7b, 0x7c, 0x7f}
+    };
+
+    @SmallTest
+    public void testDecodeExtended() throws Exception {
+        for (int language = 0; language < 3; language++) {
+            int[] tableIndex = sExtendedTableIndexes[language];
+            int numSeptets = tableIndex.length * 2;  // two septets per extended char
+            byte[] septets = new byte[(7 * numSeptets + 7) / 8];
+
+            int bitOffset = 0;
+
+            for (int v : tableIndex) {
+                // escape character
+                int byteOffset = bitOffset / 8;
+                int shift = bitOffset % 8;
+
+                septets[byteOffset] |= GSM_ESCAPE_CHARACTER << shift;
+
+                if (shift > 1) {
+                    septets[byteOffset + 1] = (byte) (GSM_ESCAPE_CHARACTER >> (8 - shift));
+                }
+
+                bitOffset += 7;
+
+                // extended table index
+                byteOffset = bitOffset / 8;
+                shift = bitOffset % 8;
+
+                septets[byteOffset] |= v << shift;
+
+                if (shift > 1) {
+                    septets[byteOffset + 1] = (byte) (v >> (8 - shift));
+                }
+
+                bitOffset += 7;
+            }
+
+            String decoded = GsmAlphabet.gsm7BitPackedToString(septets, 0, numSeptets, 0,
+                    0, language);
+            byte[] reEncoded = GsmAlphabet.stringToGsm7BitPacked(decoded, 0, language);
+
+            assertEquals(sExtendedTables[language], decoded);
+
+            // reEncoded has the count septets byte at the front
+            assertEquals(septets.length + 1, reEncoded.length);
+
+            for (int i = 0; i < septets.length; i++) {
+                assertEquals(septets[i], reEncoded[i + 1]);
+            }
+        }
+    }
+
+    @SmallTest
+    public void testDecodeExtendedFallback() throws Exception {
+        // verify that unmapped characters in extension table fall back to locking shift table
+        for (int language = 0; language < 3; language++) {
+            int[] tableIndex = sExtendedTableIndexes[language];
+            int numChars = 128 - tableIndex.length;
+            int numSeptets = numChars * 2;  // two septets per extended char
+            byte[] septets = new byte[(7 * numSeptets + 7) / 8];
+
+            int tableOffset = 0;
+            int bitOffset = 0;
+
+            StringBuilder defaultTable = new StringBuilder(128);
+            StringBuilder turkishTable = new StringBuilder(128);
+            StringBuilder portugueseTable = new StringBuilder(128);
+
+            for (char c = 0; c < 128; c++) {
+                // skip characters that are present in the current extension table
+                if (tableOffset < tableIndex.length && tableIndex[tableOffset] == c) {
+                    tableOffset++;
+                    continue;
+                }
+
+                // escape character
+                int byteOffset = bitOffset / 8;
+                int shift = bitOffset % 8;
+
+                septets[byteOffset] |= GSM_ESCAPE_CHARACTER << shift;
+
+                if (shift > 1) {
+                    septets[byteOffset + 1] = (byte) (GSM_ESCAPE_CHARACTER >> (8 - shift));
+                }
+
+                bitOffset += 7;
+
+                // extended table index
+                byteOffset = bitOffset / 8;
+                shift = bitOffset % 8;
+
+                septets[byteOffset] |= c << shift;
+
+                if (shift > 1) {
+                    septets[byteOffset + 1] = (byte) (c >> (8 - shift));
+                }
+
+                bitOffset += 7;
+
+                if (c == GsmAlphabet.GSM_EXTENDED_ESCAPE) {
+                    // double Escape maps to space character
+                    defaultTable.append(' ');
+                    turkishTable.append(' ');
+                    portugueseTable.append(' ');
+                } else {
+                    // other unmapped chars map to the default or locking shift table
+                    defaultTable.append(sBasicTables[0].charAt(c));
+                    turkishTable.append(sBasicTables[1].charAt(c));
+                    portugueseTable.append(sBasicTables[3].charAt(c));
+                }
+            }
+
+            String decoded = GsmAlphabet.gsm7BitPackedToString(septets, 0, numSeptets, 0,
+                    0, language);
+
+            assertEquals(defaultTable.toString(), decoded);
+
+            decoded = GsmAlphabet.gsm7BitPackedToString(septets, 0, numSeptets, 0, 1, language);
+            assertEquals(turkishTable.toString(), decoded);
+
+            decoded = GsmAlphabet.gsm7BitPackedToString(septets, 0, numSeptets, 0, 3, language);
+            assertEquals(portugueseTable.toString(), decoded);
+        }
+    }
 }
diff --git a/telephony/tests/telephonytests/src/com/android/internal/telephony/IntRangeManagerTest.java b/telephony/tests/telephonytests/src/com/android/internal/telephony/IntRangeManagerTest.java
new file mode 100644
index 0000000..79dca39
--- /dev/null
+++ b/telephony/tests/telephonytests/src/com/android/internal/telephony/IntRangeManagerTest.java
@@ -0,0 +1,374 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.telephony;
+
+import android.test.AndroidTestCase;
+
+import com.android.internal.telephony.gsm.SmsBroadcastConfigInfo;
+
+import java.util.ArrayList;
+
+/**
+ * Test cases for the IntRangeManager class.
+ */
+public class IntRangeManagerTest extends AndroidTestCase {
+
+    private static final int SMS_CB_CODE_SCHEME_MIN = 0;
+    private static final int SMS_CB_CODE_SCHEME_MAX = 255;
+
+    private static final int FLAG_START_UPDATE_CALLED   = 0x01;
+    private static final int FLAG_ADD_RANGE_CALLED      = 0x02;
+    private static final int FLAG_FINISH_UPDATE_CALLED  = 0x04;
+
+    private static final int ALL_FLAGS_SET = FLAG_START_UPDATE_CALLED | FLAG_ADD_RANGE_CALLED |
+            FLAG_FINISH_UPDATE_CALLED;
+
+    /** Dummy IntRangeManager for testing. */
+    class TestIntRangeManager extends IntRangeManager {
+        ArrayList<SmsBroadcastConfigInfo> mConfigList =
+                new ArrayList<SmsBroadcastConfigInfo>();
+
+        int flags;
+        boolean finishUpdateReturnValue = true;
+
+        /**
+         * Called when the list of enabled ranges has changed. This will be
+         * followed by zero or more calls to {@link #addRange} followed by
+         * a call to {@link #finishUpdate}.
+         */
+        protected void startUpdate() {
+            mConfigList.clear();
+            flags |= FLAG_START_UPDATE_CALLED;
+        }
+
+        /**
+         * Called after {@link #startUpdate} to indicate a range of enabled
+         * values.
+         * @param startId the first id included in the range
+         * @param endId the last id included in the range
+         */
+        protected void addRange(int startId, int endId, boolean selected) {
+            mConfigList.add(new SmsBroadcastConfigInfo(startId, endId,
+                        SMS_CB_CODE_SCHEME_MIN, SMS_CB_CODE_SCHEME_MAX, selected));
+            flags |= FLAG_ADD_RANGE_CALLED;
+        }
+
+        /**
+         * Called to indicate the end of a range update started by the
+         * previous call to {@link #startUpdate}.
+         */
+        protected boolean finishUpdate() {
+            flags |= FLAG_FINISH_UPDATE_CALLED;
+            return finishUpdateReturnValue;
+        }
+
+        /** Reset the object for the next test case. */
+        void reset() {
+            flags = 0;
+            mConfigList.clear();
+        }
+    }
+
+    public void testEmptyRangeManager() {
+        TestIntRangeManager testManager = new TestIntRangeManager();
+        assertEquals("expecting empty configlist", 0, testManager.mConfigList.size());
+    }
+
+    private void checkConfigInfo(SmsBroadcastConfigInfo info, int fromServiceId,
+            int toServiceId, int fromCodeScheme, int toCodeScheme, boolean selected) {
+        assertEquals("fromServiceId", fromServiceId, info.getFromServiceId());
+        assertEquals("toServiceId", toServiceId, info.getToServiceId());
+        assertEquals("fromCodeScheme", fromCodeScheme, info.getFromCodeScheme());
+        assertEquals("toCodeScheme", toCodeScheme, info.getToCodeScheme());
+        assertEquals("selected", selected, info.isSelected());
+    }
+
+    public void testAddSingleChannel() {
+        TestIntRangeManager testManager = new TestIntRangeManager();
+        assertEquals("flags before test", 0, testManager.flags);
+        assertTrue("enabling range", testManager.enableRange(123, 123, "client1"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 123, 123, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        testManager.reset();
+        assertTrue("updating ranges", testManager.updateRanges());
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 123, 123, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+    }
+
+    public void testRemoveSingleChannel() {
+        TestIntRangeManager testManager = new TestIntRangeManager();
+        assertTrue("enabling range", testManager.enableRange(123, 123, "client1"));
+        assertEquals("flags after enable", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        testManager.reset();
+        assertTrue("disabling range", testManager.disableRange(123, 123, "client1"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 123, 123, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, false);
+        testManager.reset();
+        assertTrue("updating ranges", testManager.updateRanges());
+        assertEquals("flags after test", FLAG_START_UPDATE_CALLED | FLAG_FINISH_UPDATE_CALLED,
+                testManager.flags);
+        assertEquals("configlist size", 0, testManager.mConfigList.size());
+    }
+
+    public void testRemoveBadChannel() {
+        TestIntRangeManager testManager = new TestIntRangeManager();
+        assertFalse("disabling missing range", testManager.disableRange(123, 123, "client1"));
+        assertEquals("flags after test", 0, testManager.flags);
+        assertEquals("configlist size", 0, testManager.mConfigList.size());
+    }
+
+    public void testAddTwoChannels() {
+        TestIntRangeManager testManager = new TestIntRangeManager();
+        assertEquals("flags before test", 0, testManager.flags);
+        assertTrue("enabling range 1", testManager.enableRange(100, 120, "client1"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 100, 120, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        testManager.reset();
+        assertTrue("enabling range 2", testManager.enableRange(200, 250, "client2"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 200, 250, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        testManager.reset();
+        assertTrue("updating ranges", testManager.updateRanges());
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 2, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 100, 120, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        checkConfigInfo(testManager.mConfigList.get(1), 200, 250, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+    }
+
+    public void testOverlappingChannels() {
+        TestIntRangeManager testManager = new TestIntRangeManager();
+        assertEquals("flags before test", 0, testManager.flags);
+        assertTrue("enabling range 1", testManager.enableRange(100, 200, "client1"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 100, 200, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        testManager.reset();
+        assertTrue("enabling range 2", testManager.enableRange(150, 250, "client2"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 201, 250, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        testManager.reset();
+        assertTrue("updating ranges", testManager.updateRanges());
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 100, 250, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        testManager.reset();
+        assertTrue("disabling range 1", testManager.disableRange(100, 200, "client1"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 100, 149, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, false);
+        testManager.reset();
+        assertTrue("disabling range 2", testManager.disableRange(150, 250, "client2"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 150, 250, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, false);
+        testManager.reset();
+        assertTrue("updating ranges", testManager.updateRanges());
+        assertEquals("flags after test", FLAG_START_UPDATE_CALLED | FLAG_FINISH_UPDATE_CALLED,
+                testManager.flags);
+        assertEquals("configlist size", 0, testManager.mConfigList.size());
+    }
+
+    public void testOverlappingChannels2() {
+        TestIntRangeManager testManager = new TestIntRangeManager();
+        assertEquals("flags before test", 0, testManager.flags);
+        assertTrue("enabling range 1", testManager.enableRange(100, 200, "client1"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 100, 200, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        testManager.reset();
+        assertTrue("enabling range 2", testManager.enableRange(150, 250, "client2"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 201, 250, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        testManager.reset();
+        assertTrue("disabling range 2", testManager.disableRange(150, 250, "client2"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 201, 250, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, false);
+        testManager.reset();
+        assertTrue("updating ranges", testManager.updateRanges());
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 100, 200, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        testManager.reset();
+        assertTrue("disabling range 1", testManager.disableRange(100, 200, "client1"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 100, 200, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, false);
+    }
+
+    public void testMultipleOverlappingChannels() {
+        TestIntRangeManager testManager = new TestIntRangeManager();
+        assertEquals("flags before test", 0, testManager.flags);
+        assertTrue("enabling range 1", testManager.enableRange(67, 9999, "client1"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 67, 9999, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        testManager.reset();
+        assertTrue("enabling range 2", testManager.enableRange(150, 250, "client2"));
+        assertEquals("flags after test", 0, testManager.flags);
+        assertEquals("configlist size", 0, testManager.mConfigList.size());
+        testManager.reset();
+        assertTrue("enabling range 3", testManager.enableRange(25, 75, "client3"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 25, 66, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        testManager.reset();
+        assertTrue("enabling range 4", testManager.enableRange(12, 500, "client4"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 12, 24, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        testManager.reset();
+        assertTrue("enabling range 5", testManager.enableRange(8000, 9998, "client5"));
+        assertEquals("flags after test", 0, testManager.flags);
+        assertEquals("configlist size", 0, testManager.mConfigList.size());
+        testManager.reset();
+        assertTrue("enabling range 6", testManager.enableRange(50000, 65535, "client6"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 50000, 65535, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        testManager.reset();
+        assertTrue("updating ranges", testManager.updateRanges());
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 2, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 12, 9999, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        checkConfigInfo(testManager.mConfigList.get(1), 50000, 65535, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        testManager.reset();
+        assertTrue("disabling range 1", testManager.disableRange(67, 9999, "client1"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 2, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 501, 7999, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, false);
+        checkConfigInfo(testManager.mConfigList.get(1), 9999, 9999, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, false);
+        testManager.reset();
+        assertTrue("updating ranges", testManager.updateRanges());
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 3, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 12, 500, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        checkConfigInfo(testManager.mConfigList.get(1), 8000, 9998, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        checkConfigInfo(testManager.mConfigList.get(2), 50000, 65535, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        testManager.reset();
+        assertTrue("disabling range 4", testManager.disableRange(12, 500, "client4"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 3, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 12, 24, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, false);
+        checkConfigInfo(testManager.mConfigList.get(1), 76, 149, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, false);
+        checkConfigInfo(testManager.mConfigList.get(2), 251, 500, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, false);
+        testManager.reset();
+        assertTrue("updating ranges", testManager.updateRanges());
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 4, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 25, 75, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        checkConfigInfo(testManager.mConfigList.get(1), 150, 250, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        checkConfigInfo(testManager.mConfigList.get(2), 8000, 9998, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        checkConfigInfo(testManager.mConfigList.get(3), 50000, 65535, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        testManager.reset();
+        assertTrue("disabling range 5", testManager.disableRange(8000, 9998, "client5"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 8000, 9998, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, false);
+        testManager.reset();
+        assertTrue("updating ranges", testManager.updateRanges());
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 3, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 25, 75, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        checkConfigInfo(testManager.mConfigList.get(1), 150, 250, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        checkConfigInfo(testManager.mConfigList.get(2), 50000, 65535, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        testManager.reset();
+        assertTrue("disabling range 6", testManager.disableRange(50000, 65535, "client6"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 50000, 65535, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, false);
+        testManager.reset();
+        assertTrue("updating ranges", testManager.updateRanges());
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 2, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 25, 75, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        checkConfigInfo(testManager.mConfigList.get(1), 150, 250, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        testManager.reset();
+        assertTrue("disabling range 2", testManager.disableRange(150, 250, "client2"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 150, 250, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, false);
+        testManager.reset();
+        assertTrue("updating ranges", testManager.updateRanges());
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 25, 75, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, true);
+        testManager.reset();
+        assertTrue("disabling range 3", testManager.disableRange(25, 75, "client3"));
+        assertEquals("flags after test", ALL_FLAGS_SET, testManager.flags);
+        assertEquals("configlist size", 1, testManager.mConfigList.size());
+        checkConfigInfo(testManager.mConfigList.get(0), 25, 75, SMS_CB_CODE_SCHEME_MIN,
+                SMS_CB_CODE_SCHEME_MAX, false);
+        testManager.reset();
+        assertTrue("updating ranges", testManager.updateRanges());
+        assertEquals("flags after test", FLAG_START_UPDATE_CALLED | FLAG_FINISH_UPDATE_CALLED,
+                testManager.flags);
+        assertEquals("configlist size", 0, testManager.mConfigList.size());
+    }
+}
diff --git a/telephony/tests/telephonytests/src/com/android/internal/telephony/SmsMessageBodyTest.java b/telephony/tests/telephonytests/src/com/android/internal/telephony/SmsMessageBodyTest.java
index b214887..170bd9b 100644
--- a/telephony/tests/telephonytests/src/com/android/internal/telephony/SmsMessageBodyTest.java
+++ b/telephony/tests/telephonytests/src/com/android/internal/telephony/SmsMessageBodyTest.java
@@ -19,21 +19,57 @@
 import android.telephony.SmsMessage;
 import android.telephony.TelephonyManager;
 import android.test.AndroidTestCase;
+import android.test.suitebuilder.annotation.LargeTest;
+import android.test.suitebuilder.annotation.MediumTest;
 import android.test.suitebuilder.annotation.SmallTest;
+import android.util.Log;
 
+import java.util.Random;
+
+import static android.telephony.SmsMessage.MAX_USER_DATA_BYTES;
+import static android.telephony.SmsMessage.MAX_USER_DATA_BYTES_WITH_HEADER;
 import static android.telephony.SmsMessage.MAX_USER_DATA_SEPTETS;
+import static android.telephony.SmsMessage.MAX_USER_DATA_SEPTETS_WITH_HEADER;
 
+/**
+ * Test cases to verify selection of the optimal 7 bit encoding tables
+ * (for all combinations of enabled national language tables) for messages
+ * containing Turkish, Spanish, Portuguese, Greek, and other symbols
+ * present in the GSM default and national language tables defined in
+ * 3GPP TS 23.038. Also verifies correct SMS encoding for CDMA, which only
+ * supports the GSM 7 bit default alphabet, ASCII 8 bit, and UCS-2.
+ * Tests both encoding variations: unsupported characters mapped to space,
+ * and unsupported characters force entire message to UCS-2.
+ */
 public class SmsMessageBodyTest extends AndroidTestCase {
+    private static final String TAG = "SmsMessageBodyTest";
 
+    // ASCII chars in the GSM 7 bit default alphabet
     private static final String sAsciiChars = "@$_ !\"#%&'()*+,-./0123456789" +
             ":;<=>?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\n\r";
-    private static final String sGsmBasicChars = "\u00a3\u00a5\u00e8\u00e9" +
-            "\u00f9\u00ec\u00f2\u00c7\u00d8\u00f8\u00c5\u00e5\u0394\u03a6" +
-            "\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u00c6\u00e6" +
-            "\u00df\u00c9\u00a4\u00a1\u00c4\u00d6\u00d1\u00dc\u00a7\u00bf" +
-            "\u00e4\u00f6\u00f1\u00fc\u00e0";
-    private static final String sGsmExtendedAsciiChars = "{|}\\[~]^\f";
+
+    // Unicode chars in the GSM 7 bit default alphabet and both locking shift tables
+    private static final String sGsmDefaultChars = "\u00a3\u00a5\u00e9\u00c7\u0394\u00c9" +
+            "\u00dc\u00a7\u00fc\u00e0";
+
+    // Unicode chars in the GSM 7 bit default table and Turkish locking shift tables
+    private static final String sGsmDefaultAndTurkishTables = "\u00f9\u00f2\u00c5\u00e5\u00df" +
+            "\u00a4\u00c4\u00d6\u00d1\u00e4\u00f6\u00f1";
+
+    // Unicode chars in the GSM 7 bit default table but not the locking shift tables
+    private static final String sGsmDefaultTableOnly = "\u00e8\u00ec\u00d8\u00f8\u00c6\u00e6" +
+            "\u00a1\u00bf";
+
+    // ASCII chars in the GSM default extension table
+    private static final String sGsmExtendedAsciiChars = "{}[]\f";
+
+    // chars in GSM default extension table and Portuguese locking shift table
+    private static final String sGsmExtendedPortugueseLocking = "^\\|~";
+
+    // Euro currency symbol
     private static final String sGsmExtendedEuroSymbol = "\u20ac";
+
+    // CJK ideographs, Hiragana, Katakana, full width letters, Cyrillic, etc.
     private static final String sUnicodeChars = "\u4e00\u4e01\u4e02\u4e03" +
             "\u4e04\u4e05\u4e06\u4e07\u4e08\u4e09\u4e0a\u4e0b\u4e0c\u4e0d" +
             "\u4e0e\u4e0f\u3041\u3042\u3043\u3044\u3045\u3046\u3047\u3048" +
@@ -43,6 +79,86 @@
             "\u0400\u0401\u0402\u0403\u0404\u0405\u0406\u0407\u0408" +
             "\u00a2\u00a9\u00ae\u2122";
 
+    // chars in Turkish single shift and locking shift tables
+    private static final String sTurkishChars = "\u0131\u011e\u011f\u015e\u015f\u0130";
+
+    // chars in Spanish single shift table and Portuguese single and locking shift tables
+    private static final String sPortugueseAndSpanishChars = "\u00c1\u00e1\u00cd\u00ed"
+            + "\u00d3\u00f3\u00da\u00fa";
+
+    // chars in all national language tables but not in the standard GSM alphabets
+    private static final String sNationalLanguageTablesOnly = "\u00e7";
+
+    // chars in Portuguese single shift and locking shift tables
+    private static final String sPortugueseChars = "\u00ea\u00d4\u00f4\u00c0\u00c2\u00e2"
+            + "\u00ca\u00c3\u00d5\u00e3\u00f5";
+
+    // chars in Portuguese locking shift table only
+    private static final String sPortugueseLockingShiftChars = "\u00aa\u221e\u00ba`";
+
+    // Greek letters in GSM alphabet missing from Portuguese locking and single shift tables
+    private static final String sGreekLettersNotInPortugueseTables = "\u039b\u039e";
+
+    // Greek letters in GSM alphabet and Portuguese single shift (but not locking shift) table
+    private static final String sGreekLettersInPortugueseShiftTable =
+            "\u03a6\u0393\u03a9\u03a0\u03a8\u03a3\u0398";
+
+    // List of classes of characters in SMS tables
+    private static final String[] sCharacterClasses = {
+            sGsmExtendedAsciiChars,
+            sGsmExtendedPortugueseLocking,
+            sGsmDefaultChars,
+            sGsmDefaultAndTurkishTables,
+            sGsmDefaultTableOnly,
+            sGsmExtendedEuroSymbol,
+            sUnicodeChars,
+            sTurkishChars,
+            sPortugueseChars,
+            sPortugueseLockingShiftChars,
+            sPortugueseAndSpanishChars,
+            sGreekLettersNotInPortugueseTables,
+            sGreekLettersInPortugueseShiftTable,
+            sNationalLanguageTablesOnly,
+            sAsciiChars
+    };
+
+    private static final int sNumCharacterClasses = sCharacterClasses.length;
+
+    // For each character class, whether it is present in a particular char table.
+    // First three entries are locking shift tables, followed by four single shift tables
+    private static final boolean[][] sCharClassPresenceInTables = {
+            // ASCII chars in all GSM extension tables
+            {false, false, false, true, true, true, true},
+            // ASCII chars in all GSM extension tables and Portuguese locking shift table
+            {false, false, true, true, true, true, true},
+            // non-ASCII chars in GSM default alphabet and all locking tables
+            {true, true, true, false, false, false, false},
+            // non-ASCII chars in GSM default alphabet and Turkish locking shift table
+            {true, true, false, false, false, false, false},
+            // non-ASCII chars in GSM default alphabet table only
+            {true, false, false, false, false, false, false},
+            // Euro symbol is present in several tables
+            {false, true, true, true, true, true, true},
+            // Unicode characters not present in any 7 bit tables
+            {false, false, false, false, false, false, false},
+            // Characters specific to Turkish language
+            {false, true, false, false, true, false, false},
+            // Characters in Portuguese single shift and locking shift tables
+            {false, false, true, false, false, false, true},
+            // Characters in Portuguese locking shift table only
+            {false, false, true, false, false, false, false},
+            // Chars in Spanish single shift and Portuguese single and locking shift tables
+            {false, false, true, false, false, true, true},
+            // Greek letters in GSM default alphabet missing from Portuguese tables
+            {true, true, false, false, false, false, false},
+            // Greek letters in GSM alphabet and Portuguese single shift table
+            {true, true, false, false, false, false, true},
+            // Chars in all national language tables but not the standard GSM tables
+            {false, true, true, false, true, true, true},
+            // ASCII chars in GSM default alphabet
+            {true, true, true, false, false, false, false}
+    };
+
     private static final int sTestLengthCount = 12;
 
     private static final int[] sSeptetTestLengths =
@@ -60,11 +176,92 @@
     private static final int[] sUnicodeUnitsRemaining =
             { 70,  69,  68, 35,   1,   0,  63,  34,   1,   0,  66,  41};
 
+    // Combinations of enabled GSM national language single shift tables
+    private static final int[][] sEnabledSingleShiftTables = {
+            {},         // GSM default alphabet only
+            {1},        // Turkish (single shift only)
+            {1},        // Turkish (single and locking shift)
+            {2},        // Spanish
+            {3},        // Portuguese (single shift only)
+            {3},        // Portuguese (single and locking shift)
+            {1, 2},     // Turkish + Spanish (single shift only)
+            {1, 2},     // Turkish + Spanish (single and locking shift)
+            {1, 3},     // Turkish + Portuguese (single shift only)
+            {1, 3},     // Turkish + Portuguese (single and locking shift)
+            {2, 3},     // Spanish + Portuguese (single shift only)
+            {2, 3},     // Spanish + Portuguese (single and locking shift)
+            {1, 2, 3},  // Turkish, Spanish, Portuguese (single shift only)
+            {1, 2, 3},  // Turkish, Spanish, Portuguese (single and locking shift)
+            {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} // all language tables
+    };
+
+    // Combinations of enabled GSM national language locking shift tables
+    private static final int[][] sEnabledLockingShiftTables = {
+            {},         // GSM default alphabet only
+            {},         // Turkish (single shift only)
+            {1},        // Turkish (single and locking shift)
+            {},         // Spanish (no locking shift table)
+            {},         // Portuguese (single shift only)
+            {3},        // Portuguese (single and locking shift)
+            {},         // Turkish + Spanish (single shift only)
+            {1},        // Turkish + Spanish (single and locking shift)
+            {},         // Turkish + Portuguese (single shift only)
+            {1, 3},     // Turkish + Portuguese (single and locking shift)
+            {},         // Spanish + Portuguese (single shift only)
+            {3},        // Spanish + Portuguese (single and locking shift)
+            {},         // Turkish, Spanish, Portuguese (single shift only)
+            {1, 3},     // Turkish, Spanish, Portuguese (single and locking shift)
+            {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} // all language tables
+    };
+
+    // LanguagePair counter indexes to check for each entry above
+    private static final int[][] sLanguagePairIndexesByEnabledIndex = {
+            {0},                            // default tables only
+            {0, 1},                         // Turkish (single shift only)
+            {0, 1, 4, 5},                   // Turkish (single and locking shift)
+            {0, 2},                         // Spanish
+            {0, 3},                         // Portuguese (single shift only)
+            {0, 3, 8, 11},                  // Portuguese (single and locking shift)
+            {0, 1, 2},                      // Turkish + Spanish (single shift only)
+            {0, 1, 2, 4, 5, 6},             // Turkish + Spanish (single and locking shift)
+            {0, 1, 3},                      // Turkish + Portuguese (single shift only)
+            {0, 1, 3, 4, 5, 7, 8, 9, 11},   // Turkish + Portuguese (single and locking shift)
+            {0, 2, 3},                      // Spanish + Portuguese (single shift only)
+            {0, 2, 3, 8, 10, 11},           // Spanish + Portuguese (single and locking shift)
+            {0, 1, 2, 3},                   // all languages (single shift only)
+            {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, // all languages (single and locking shift)
+            {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}  // all languages (no Indic chars in test)
+    };
+
+    /**
+     * User data header requires one octet for length. Count as one septet, because
+     * all combinations of header elements below will have at least one free bit
+     * when padding to the nearest septet boundary.
+     */
+    private static final int UDH_SEPTET_COST_LENGTH = 1;
+
+    /**
+     * Using a non-default language locking shift table OR single shift table
+     * requires a user data header of 3 octets, or 4 septets, plus UDH length.
+     */
+    private static final int UDH_SEPTET_COST_ONE_SHIFT_TABLE = 4;
+
+    /**
+     * Using a non-default language locking shift table AND single shift table
+     * requires a user data header of 6 octets, or 7 septets, plus UDH length.
+     */
+    private static final int UDH_SEPTET_COST_TWO_SHIFT_TABLES = 7;
+
+    /**
+     * Multi-part messages require a user data header of 5 octets, or 6 septets,
+     * plus UDH length.
+     */
+    private static final int UDH_SEPTET_COST_CONCATENATED_MESSAGE = 6;
 
     @SmallTest
     public void testCalcLengthAscii() throws Exception {
         StringBuilder sb = new StringBuilder(320);
-        int[] values = {0, 0, 0, SmsMessage.ENCODING_7BIT};
+        int[] values = {0, 0, 0, SmsMessage.ENCODING_7BIT, 0, 0};
         int startPos = 0;
         int asciiCharsLen = sAsciiChars.length();
 
@@ -94,20 +291,10 @@
     }
 
     @SmallTest
-    public void testCalcLength7bitGsm() throws Exception {
-        // TODO
-    }
-
-    @SmallTest
-    public void testCalcLength7bitGsmExtended() throws Exception {
-        // TODO
-    }
-
-    @SmallTest
     public void testCalcLengthUnicode() throws Exception {
         StringBuilder sb = new StringBuilder(160);
-        int[] values = {0, 0, 0, SmsMessage.ENCODING_16BIT};
-        int[] values7bit = {1, 0, 0, SmsMessage.ENCODING_7BIT};
+        int[] values = {0, 0, 0, SmsMessage.ENCODING_16BIT, 0, 0};
+        int[] values7bit = {1, 0, 0, SmsMessage.ENCODING_7BIT, 0, 0};
         int startPos = 0;
         int unicodeCharsLen = sUnicodeChars.length();
 
@@ -139,6 +326,229 @@
         }
     }
 
+    private static class LanguagePair {
+        // index is 2 for Portuguese locking shift because there is no Spanish locking shift table
+        private final int langTableIndex;
+        private final int langShiftTableIndex;
+        int length;
+        int missingChars7bit;
+
+        LanguagePair(int langTable, int langShiftTable) {
+            langTableIndex = langTable;
+            langShiftTableIndex = langShiftTable;
+        }
+
+        void clear() {
+            length = 0;
+            missingChars7bit = 0;
+        }
+
+        void addChar(boolean[] charClassTableRow) {
+            if (charClassTableRow[langTableIndex]) {
+                length++;
+            } else if (charClassTableRow[3 + langShiftTableIndex]) {
+                length += 2;
+            } else {
+                length++;    // use ' ' for unmapped char in 7 bit only mode
+                missingChars7bit++;
+            }
+        }
+    }
+
+    private static class CounterHelper {
+        LanguagePair[] mCounters;
+        int[] mStatsCounters;
+        int mUnicodeCounter;
+
+        CounterHelper() {
+            mCounters = new LanguagePair[12];
+            mStatsCounters = new int[12];
+            for (int i = 0; i < 12; i++) {
+                mCounters[i] = new LanguagePair(i/4, i%4);
+            }
+        }
+
+        void clear() {
+            // Note: don't clear stats counters
+            for (int i = 0; i < 12; i++) {
+                mCounters[i].clear();
+            }
+        }
+
+        void addChar(int charClass) {
+            boolean[] charClassTableRow = sCharClassPresenceInTables[charClass];
+            for (int i = 0; i < 12; i++) {
+                mCounters[i].addChar(charClassTableRow);
+            }
+        }
+
+        void fillData(int enabledLangsIndex, boolean use7bitOnly, int[] values, int length) {
+            int[] languagePairs = sLanguagePairIndexesByEnabledIndex[enabledLangsIndex];
+            int minNumSeptets = Integer.MAX_VALUE;
+            int minNumSeptetsWithHeader = Integer.MAX_VALUE;
+            int minNumMissingChars = Integer.MAX_VALUE;
+            int langIndex = -1;
+            int langShiftIndex = -1;
+            for (int i : languagePairs) {
+                LanguagePair pair = mCounters[i];
+                int udhLength = 0;
+                if (i != 0) {
+                    udhLength = UDH_SEPTET_COST_LENGTH;
+                    if (i < 4 || i % 4 == 0) {
+                        udhLength += UDH_SEPTET_COST_ONE_SHIFT_TABLE;
+                    } else {
+                        udhLength += UDH_SEPTET_COST_TWO_SHIFT_TABLES;
+                    }
+                }
+                int numSeptetsWithHeader;
+                if (pair.length > (MAX_USER_DATA_SEPTETS - udhLength)) {
+                    if (udhLength == 0) {
+                        udhLength = UDH_SEPTET_COST_LENGTH;
+                    }
+                    udhLength += UDH_SEPTET_COST_CONCATENATED_MESSAGE;
+                    int septetsPerPart = MAX_USER_DATA_SEPTETS - udhLength;
+                    int msgCount = (pair.length + septetsPerPart - 1) / septetsPerPart;
+                    numSeptetsWithHeader = udhLength * msgCount + pair.length;
+                } else {
+                    numSeptetsWithHeader = udhLength + pair.length;
+                }
+
+                if (use7bitOnly) {
+                    if (pair.missingChars7bit < minNumMissingChars || (pair.missingChars7bit ==
+                            minNumMissingChars && numSeptetsWithHeader < minNumSeptetsWithHeader)) {
+                        minNumSeptets = pair.length;
+                        minNumSeptetsWithHeader = numSeptetsWithHeader;
+                        minNumMissingChars = pair.missingChars7bit;
+                        langIndex = pair.langTableIndex;
+                        langShiftIndex = pair.langShiftTableIndex;
+                    }
+                } else {
+                    if (pair.missingChars7bit == 0 && numSeptetsWithHeader < minNumSeptetsWithHeader) {
+                        minNumSeptets = pair.length;
+                        minNumSeptetsWithHeader = numSeptetsWithHeader;
+                        langIndex = pair.langTableIndex;
+                        langShiftIndex = pair.langShiftTableIndex;
+                    }
+                }
+            }
+            if (langIndex == -1) {
+                // nothing matches, use values for Unicode
+                int byteCount = length * 2;
+                if (byteCount > MAX_USER_DATA_BYTES) {
+                    values[0] = (byteCount + MAX_USER_DATA_BYTES_WITH_HEADER - 1) /
+                            MAX_USER_DATA_BYTES_WITH_HEADER;
+                    values[2] = ((values[0] * MAX_USER_DATA_BYTES_WITH_HEADER) - byteCount) / 2;
+                } else {
+                    values[0] = 1;
+                    values[2] = (MAX_USER_DATA_BYTES - byteCount) / 2;
+                }
+                values[1] = length;
+                values[3] = SmsMessage.ENCODING_16BIT;
+                values[4] = 0;
+                values[5] = 0;
+                mUnicodeCounter++;
+            } else {
+                int udhLength = 0;
+                if (langIndex != 0 || langShiftIndex != 0) {
+                    udhLength = UDH_SEPTET_COST_LENGTH;
+                    if (langIndex == 0 || langShiftIndex == 0) {
+                        udhLength += UDH_SEPTET_COST_ONE_SHIFT_TABLE;
+                    } else {
+                        udhLength += UDH_SEPTET_COST_TWO_SHIFT_TABLES;
+                    }
+                }
+                int msgCount;
+                if (minNumSeptets > (MAX_USER_DATA_SEPTETS - udhLength)) {
+                    if (udhLength == 0) {
+                        udhLength = UDH_SEPTET_COST_LENGTH;
+                    }
+                    udhLength += UDH_SEPTET_COST_CONCATENATED_MESSAGE;
+                    int septetsPerPart = MAX_USER_DATA_SEPTETS - udhLength;
+                    msgCount = (minNumSeptets + septetsPerPart - 1) / septetsPerPart;
+                } else {
+                    msgCount = 1;
+                }
+                values[0] = msgCount;
+                values[1] = minNumSeptets;
+                values[2] = (values[0] * (MAX_USER_DATA_SEPTETS - udhLength)) - minNumSeptets;
+                values[3] = SmsMessage.ENCODING_7BIT;
+                values[4] = (langIndex == 2 ? 3 : langIndex); // Portuguese is code 3, index 2
+                values[5] = langShiftIndex;
+                assertEquals("minNumSeptetsWithHeader", minNumSeptetsWithHeader,
+                        udhLength * msgCount + minNumSeptets);
+                mStatsCounters[langIndex * 4 + langShiftIndex]++;
+            }
+        }
+
+        void printStats() {
+            Log.d(TAG, "Unicode selection count: " + mUnicodeCounter);
+            for (int i = 0; i < 12; i++) {
+                Log.d(TAG, "Language pair index " + i + " count: " + mStatsCounters[i]);
+            }
+        }
+    }
+
+    @LargeTest
+    public void testCalcLengthMixed7bit() throws Exception {
+        StringBuilder sb = new StringBuilder(320);
+        CounterHelper ch = new CounterHelper();
+        Random r = new Random(0x4321);  // use the same seed for reproducibility
+        int[] expectedValues = new int[6];
+        int[] origLockingShiftTables = GsmAlphabet.getEnabledLockingShiftTables();
+        int[] origSingleShiftTables = GsmAlphabet.getEnabledSingleShiftTables();
+        int enabledLanguagesTestCases = sEnabledSingleShiftTables.length;
+        long startTime = System.currentTimeMillis();
+
+        // Repeat for 10 test runs
+        for (int run = 0; run < 10; run++) {
+            sb.setLength(0);
+            ch.clear();
+            int unicodeOnlyCount = 0;
+
+            // Test incrementally from 1 to 320 character random messages
+            for (int i = 1; i < 320; i++) {
+                // 1% chance to add from each special character class, else add an ASCII char
+                int charClass = r.nextInt(100);
+                if (charClass >= sNumCharacterClasses) {
+                    charClass = sNumCharacterClasses - 1;   // last class is ASCII
+                }
+                int classLength = sCharacterClasses[charClass].length();
+                char nextChar = sCharacterClasses[charClass].charAt(r.nextInt(classLength));
+                sb.append(nextChar);
+                ch.addChar(charClass);
+
+//                if (i % 20 == 0) {
+//                    Log.d(TAG, "test string: " + sb);
+//                }
+
+                // Test string against all combinations of enabled languages
+                boolean unicodeOnly = true;
+                for (int j = 0; j < enabledLanguagesTestCases; j++) {
+                    GsmAlphabet.setEnabledSingleShiftTables(sEnabledSingleShiftTables[j]);
+                    GsmAlphabet.setEnabledLockingShiftTables(sEnabledLockingShiftTables[j]);
+                    ch.fillData(j, false, expectedValues, i);
+                    if (expectedValues[3] == SmsMessage.ENCODING_7BIT) {
+                        unicodeOnly = false;
+                    }
+                    callGsmLengthMethods(sb, false, expectedValues);
+                    // test 7 bit only mode
+                    ch.fillData(j, true, expectedValues, i);
+                    callGsmLengthMethods(sb, true, expectedValues);
+                }
+                // after 10 iterations with a Unicode-only string, skip to next test string
+                // so we can spend more time testing strings that do encode into 7 bits.
+                if (unicodeOnly && ++unicodeOnlyCount == 10) {
+//                    Log.d(TAG, "Unicode only: skipping to next test string");
+                    break;
+                }
+            }
+        }
+        ch.printStats();
+        Log.d(TAG, "Completed in " + (System.currentTimeMillis() - startTime) + " ms");
+        GsmAlphabet.setEnabledLockingShiftTables(origLockingShiftTables);
+        GsmAlphabet.setEnabledSingleShiftTables(origSingleShiftTables);
+    }
+
     private void callGsmLengthMethods(CharSequence msgBody, boolean use7bitOnly,
             int[] expectedValues)
     {
@@ -164,6 +574,8 @@
         assertEquals("codeUnitCount",      expectedValues[1], ted.codeUnitCount);
         assertEquals("codeUnitsRemaining", expectedValues[2], ted.codeUnitsRemaining);
         assertEquals("codeUnitSize",       expectedValues[3], ted.codeUnitSize);
+        assertEquals("languageTable",      expectedValues[4], ted.languageTable);
+        assertEquals("languageShiftTable", expectedValues[5], ted.languageShiftTable);
     }
 
     private void callCdmaLengthMethods(CharSequence msgBody, boolean use7bitOnly,
diff --git a/telephony/tests/telephonytests/src/com/android/internal/telephony/gsm/ApnSettingTest.java b/telephony/tests/telephonytests/src/com/android/internal/telephony/gsm/ApnSettingTest.java
new file mode 100644
index 0000000..15cb3b8
--- /dev/null
+++ b/telephony/tests/telephonytests/src/com/android/internal/telephony/gsm/ApnSettingTest.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.telephony.gsm;
+
+import junit.framework.TestCase;
+
+import android.test.suitebuilder.annotation.SmallTest;
+
+public class ApnSettingTest extends TestCase {
+
+    public static final String[] TYPES = {"default", "*"};
+
+    public static void assertApnSettingEqual(ApnSetting a1, ApnSetting a2) {
+        assertEquals(a1.carrier,  a2.carrier);
+        assertEquals(a1.apn,      a2.apn);
+        assertEquals(a1.proxy,    a2.proxy);
+        assertEquals(a1.port,     a2.port);
+        assertEquals(a1.mmsc,     a2.mmsc);
+        assertEquals(a1.mmsProxy, a2.mmsProxy);
+        assertEquals(a1.mmsPort,  a2.mmsPort);
+        assertEquals(a1.user,     a2.user);
+        assertEquals(a1.password, a2.password);
+        assertEquals(a1.authType, a2.authType);
+        assertEquals(a1.id,       a2.id);
+        assertEquals(a1.numeric,  a2.numeric);
+        assertEquals(a1.protocol, a2.protocol);
+        assertEquals(a1.roamingProtocol, a2.roamingProtocol);
+        assertEquals(a1.types.length, a2.types.length);
+        int i;
+        for (i = 0; i < a1.types.length; i++) {
+            assertEquals(a1.types[i], a2.types[i]);
+        }
+    }
+
+    @SmallTest
+    public void testFromString() throws Exception {
+        String[] dunTypes = {"DUN"};
+        String[] mmsTypes = {"mms", "*"};
+
+        ApnSetting expected_apn;
+        String testString;
+
+        // A real-world v1 example string.
+        testString = "Vodafone IT,web.omnitel.it,,,,,,,,,222,10,,DUN";
+        expected_apn =  new ApnSetting(
+                -1, "22210", "Vodafone IT", "web.omnitel.it", "", "",
+                "", "", "", "", "", 0, dunTypes, "IP", "IP");
+        assertApnSettingEqual(expected_apn, ApnSetting.fromString(testString));
+
+        // A v2 string.
+        testString = "[ApnSettingV2] Name,apn,,,,,,,,,123,45,,mms|*,IPV6,IP";
+        expected_apn =  new ApnSetting(
+                -1, "12345", "Name", "apn", "", "",
+                "", "", "", "", "", 0, mmsTypes, "IPV6", "IP");
+        assertApnSettingEqual(expected_apn, ApnSetting.fromString(testString));
+
+        // A v2 string with spaces.
+        testString = "[ApnSettingV2] Name,apn, ,,,,,,,,123,45,,mms|*,IPV4V6, IP";
+        expected_apn =  new ApnSetting(
+                -1, "12345", "Name", "apn", "", "",
+                "", "", "", "", "", 0, mmsTypes, "IPV4V6", "IP");
+        assertApnSettingEqual(expected_apn, ApnSetting.fromString(testString));
+
+        // Return null if insufficient fields given.
+        testString = "[ApnSettingV2] Name,apn,,,,,,,,,123, 45,,mms|*";
+        assertEquals(null, ApnSetting.fromString(testString));
+
+        testString = "Name,apn,,,,,,,,,123, 45,";
+        assertEquals(null, ApnSetting.fromString(testString));
+
+        // Parse (incorrect) V2 format without the tag as V1.
+        testString = "Name,apn,,,,,,,,,123, 45,,mms|*,IPV6";
+        String[] incorrectTypes = {"mms|*", "IPV6"};
+        expected_apn =  new ApnSetting(
+                -1, "12345", "Name", "apn", "", "",
+                "", "", "", "", "", 0, incorrectTypes, "IP", "IP");
+        assertApnSettingEqual(expected_apn, ApnSetting.fromString(testString));
+    }
+
+
+    @SmallTest
+    public void testToString() throws Exception {
+        String[] types = {"default", "*"};
+        ApnSetting apn =  new ApnSetting(
+                99, "12345", "Name", "apn", "proxy", "port",
+                "mmsc", "mmsproxy", "mmsport", "user", "password", 0,
+                types, "IPV4V6", "IP");
+        String expected = "[ApnSettingV2] Name, 99, 12345, apn, proxy, " +
+                "mmsc, mmsproxy, mmsport, port, 0, default | *, " +
+                "IPV4V6, IP";
+        assertEquals(expected, apn.toString());
+    }
+}
+
diff --git a/tools/aapt/AaptAssets.cpp b/tools/aapt/AaptAssets.cpp
index 2b2ec7b..864d47e 100644
--- a/tools/aapt/AaptAssets.cpp
+++ b/tools/aapt/AaptAssets.cpp
@@ -1393,10 +1393,10 @@
 }
 
 ssize_t AaptDir::slurpFullTree(Bundle* bundle, const String8& srcDir,
-                            const AaptGroupEntry& kind, const String8& resType)
+                            const AaptGroupEntry& kind, const String8& resType,
+                            sp<FilePathStore>& fullResPaths)
 {
     Vector<String8> fileNames;
-
     {
         DIR* dir = NULL;
 
@@ -1419,9 +1419,14 @@
             if (isHidden(srcDir.string(), entry->d_name))
                 continue;
 
-            fileNames.add(String8(entry->d_name));
+            String8 name(entry->d_name);
+            fileNames.add(name);
+            // Add fully qualified path for dependency purposes
+            // if we're collecting them
+            if (fullResPaths != NULL) {
+                fullResPaths->add(srcDir.appendPathCopy(name));
+            }
         }
-
         closedir(dir);
     }
 
@@ -1448,7 +1453,7 @@
                 notAdded = true;
             }
             ssize_t res = subdir->slurpFullTree(bundle, pathName, kind,
-                                                resType);
+                                                resType, fullResPaths);
             if (res < NO_ERROR) {
                 return res;
             }
@@ -1680,7 +1685,7 @@
         sp<AaptDir> assetAaptDir = makeDir(String8(kAssetDir));
         AaptGroupEntry group;
         count = assetAaptDir->slurpFullTree(bundle, assetRoot, group,
-                                            String8());
+                                            String8(), mFullAssetPaths);
         if (count < 0) {
             totalCount = count;
             goto bail;
@@ -1711,6 +1716,7 @@
                     sp<AaptAssets> nextOverlay = new AaptAssets();
                     current->setOverlay(nextOverlay);
                     current = nextOverlay;
+                    current->setFullResPaths(mFullResPaths);
                 }
                 count = current->slurpResourceTree(bundle, String8(res));
 
@@ -1753,7 +1759,7 @@
          * guarantees about ordering, so we're okay with an inorder search
          * using whatever order the OS happens to hand back to us.
          */
-        count = slurpFullTree(bundle, assetRoot, AaptGroupEntry(), String8());
+        count = slurpFullTree(bundle, assetRoot, AaptGroupEntry(), String8(), mFullAssetPaths);
         if (count < 0) {
             /* failure; report error and remove archive */
             totalCount = count;
@@ -1779,9 +1785,10 @@
 
 ssize_t AaptAssets::slurpFullTree(Bundle* bundle, const String8& srcDir,
                                     const AaptGroupEntry& kind,
-                                    const String8& resType)
+                                    const String8& resType,
+                                    sp<FilePathStore>& fullResPaths)
 {
-    ssize_t res = AaptDir::slurpFullTree(bundle, srcDir, kind, resType);
+    ssize_t res = AaptDir::slurpFullTree(bundle, srcDir, kind, resType, fullResPaths);
     if (res > 0) {
         mGroupEntries.add(kind);
     }
@@ -1843,7 +1850,7 @@
         if (type == kFileTypeDirectory) {
             sp<AaptDir> dir = makeDir(String8(entry->d_name));
             ssize_t res = dir->slurpFullTree(bundle, subdirName, group,
-                                                resType);
+                                                resType, mFullResPaths);
             if (res < 0) {
                 count = res;
                 goto bail;
diff --git a/tools/aapt/AaptAssets.h b/tools/aapt/AaptAssets.h
index eeb00c0..9fafab4 100644
--- a/tools/aapt/AaptAssets.h
+++ b/tools/aapt/AaptAssets.h
@@ -130,6 +130,7 @@
 }
 
 class AaptGroup;
+class FilePathStore;
 
 /**
  * A single asset file we know about.
@@ -259,7 +260,8 @@
     virtual ssize_t slurpFullTree(Bundle* bundle,
                                   const String8& srcDir,
                                   const AaptGroupEntry& kind,
-                                  const String8& resType);
+                                  const String8& resType,
+                                  sp<FilePathStore>& fullResPaths);
 
     /*
      * Perform some sanity checks on the names of files and directories here.
@@ -474,6 +476,14 @@
     ResourceTypeSet();
 };
 
+// Storage for lists of fully qualified paths for
+// resources encountered during slurping.
+class FilePathStore : public RefBase,
+                      public Vector<String8>
+{
+public:
+    FilePathStore();
+};
 
 /**
  * Asset hierarchy being operated on.
@@ -507,7 +517,8 @@
     virtual ssize_t slurpFullTree(Bundle* bundle,
                                   const String8& srcDir,
                                   const AaptGroupEntry& kind,
-                                  const String8& resType);
+                                  const String8& resType,
+                                  sp<FilePathStore>& fullResPaths);
 
     ssize_t slurpResourceTree(Bundle* bundle, const String8& srcDir);
     ssize_t slurpResourceZip(Bundle* bundle, const char* filename);
@@ -535,6 +546,14 @@
     inline void 
         setResources(KeyedVector<String8, sp<ResourceTypeSet> >* res) { delete mRes; mRes = res; }
 
+    inline sp<FilePathStore>& getFullResPaths() { return mFullResPaths; }
+    inline void
+        setFullResPaths(sp<FilePathStore>& res) { mFullResPaths = res; }
+
+    inline sp<FilePathStore>& getFullAssetPaths() { return mFullAssetPaths; }
+    inline void
+        setFullAssetPaths(sp<FilePathStore>& res) { mFullAssetPaths = res; }
+
 private:
     String8 mPackage;
     SortedVector<AaptGroupEntry> mGroupEntries;
@@ -548,6 +567,9 @@
 
     sp<AaptAssets> mOverlay;
     KeyedVector<String8, sp<ResourceTypeSet> >* mRes;
+
+    sp<FilePathStore> mFullResPaths;
+    sp<FilePathStore> mFullAssetPaths;
 };
 
 #endif // __AAPT_ASSETS_H
diff --git a/tools/aapt/Android.mk b/tools/aapt/Android.mk
index 094b7db..e507fb9 100644
--- a/tools/aapt/Android.mk
+++ b/tools/aapt/Android.mk
@@ -13,6 +13,8 @@
 LOCAL_SRC_FILES := \
 	AaptAssets.cpp \
 	Command.cpp \
+	CrunchCache.cpp \
+	FileFinder.cpp \
 	Main.cpp \
 	Package.cpp \
 	StringPool.cpp \
diff --git a/tools/aapt/Bundle.h b/tools/aapt/Bundle.h
index fa84e93..539c312 100644
--- a/tools/aapt/Bundle.h
+++ b/tools/aapt/Bundle.h
@@ -25,6 +25,7 @@
     kCommandAdd,
     kCommandRemove,
     kCommandPackage,
+    kCommandCrunch,
 } Command;
 
 /*
@@ -41,13 +42,15 @@
           mCompressionMethod(0), mOutputAPKFile(NULL),
           mManifestPackageNameOverride(NULL), mInstrumentationPackageNameOverride(NULL),
           mIsOverlayPackage(false),
-          mAutoAddOverlay(false), mAssetSourceDir(NULL), mProguardFile(NULL),
+          mAutoAddOverlay(false), mGenDependencies(false),
+          mAssetSourceDir(NULL), 
+          mCrunchedOutputDir(NULL), mProguardFile(NULL),
           mAndroidManifestFile(NULL), mPublicOutputFile(NULL),
           mRClassDir(NULL), mResourceIntermediatesDir(NULL), mManifestMinSdkVersion(NULL),
           mMinSdkVersion(NULL), mTargetSdkVersion(NULL), mMaxSdkVersion(NULL),
-          mVersionCode(NULL), mVersionName(NULL), mCustomPackage(NULL),
+          mVersionCode(NULL), mVersionName(NULL), mCustomPackage(NULL), mExtraPackages(NULL),
           mMaxResVersion(NULL), mDebugMode(false), mNonConstantId(false), mProduct(NULL),
-          mArgc(0), mArgv(NULL)
+          mUseCrunchCache(false), mArgc(0), mArgv(NULL)
         {}
     ~Bundle(void) {}
 
@@ -97,12 +100,16 @@
     void setIsOverlayPackage(bool val) { mIsOverlayPackage = val; }
     bool getAutoAddOverlay() { return mAutoAddOverlay; }
     void setAutoAddOverlay(bool val) { mAutoAddOverlay = val; }
+    bool getGenDependencies() { return mGenDependencies; }
+    void setGenDependencies(bool val) { mGenDependencies = val; }
 
     /*
      * Input options.
      */
     const char* getAssetSourceDir() const { return mAssetSourceDir; }
     void setAssetSourceDir(const char* dir) { mAssetSourceDir = dir; }
+    const char* getCrunchedOutputDir() const { return mCrunchedOutputDir; }
+    void setCrunchedOutputDir(const char* dir) { mCrunchedOutputDir = dir; }
     const char* getProguardFile() const { return mProguardFile; }
     void setProguardFile(const char* file) { mProguardFile = file; }
     const android::Vector<const char*>& getResourceSourceDirs() const { return mResourceSourceDirs; }
@@ -138,6 +145,8 @@
     void setVersionName(const char* val) { mVersionName = val; }
     const char* getCustomPackage() const { return mCustomPackage; }
     void setCustomPackage(const char* val) { mCustomPackage = val; }
+    const char* getExtraPackages() const { return mExtraPackages; }
+    void setExtraPackages(const char* val) { mExtraPackages = val; }
     const char* getMaxResVersion() const { return mMaxResVersion; }
     void setMaxResVersion(const char * val) { mMaxResVersion = val; }
     bool getDebugMode() { return mDebugMode; }
@@ -146,6 +155,8 @@
     void setNonConstantId(bool val) { mNonConstantId = val; }
     const char* getProduct() const { return mProduct; }
     void setProduct(const char * val) { mProduct = val; }
+    void setUseCrunchCache(bool val) { mUseCrunchCache = val; }
+    bool getUseCrunchCache() { return mUseCrunchCache; }
 
     /*
      * Set and get the file specification.
@@ -224,7 +235,9 @@
     const char* mInstrumentationPackageNameOverride;
     bool        mIsOverlayPackage;
     bool        mAutoAddOverlay;
+    bool        mGenDependencies;
     const char* mAssetSourceDir;
+    const char* mCrunchedOutputDir;
     const char* mProguardFile;
     const char* mAndroidManifestFile;
     const char* mPublicOutputFile;
@@ -243,10 +256,12 @@
     const char* mVersionCode;
     const char* mVersionName;
     const char* mCustomPackage;
+    const char* mExtraPackages;
     const char* mMaxResVersion;
     bool        mDebugMode;
     bool        mNonConstantId;
     const char* mProduct;
+    bool        mUseCrunchCache;
 
     /* file specification */
     int         mArgc;
diff --git a/tools/aapt/CacheUpdater.h b/tools/aapt/CacheUpdater.h
new file mode 100644
index 0000000..0e65589
--- /dev/null
+++ b/tools/aapt/CacheUpdater.h
@@ -0,0 +1,107 @@
+//
+// Copyright 2011 The Android Open Source Project
+//
+// Abstraction of calls to system to make directories and delete files and
+// wrapper to image processing.
+
+#ifndef CACHE_UPDATER_H
+#define CACHE_UPDATER_H
+
+#include <utils/String8.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <stdio.h>
+#include "Images.h"
+
+using namespace android;
+
+/** CacheUpdater
+ *  This is a pure virtual class that declares abstractions of functions useful
+ *  for managing a cache files. This manager is set up to be used in a
+ *  mirror cache where the source tree is duplicated and filled with processed
+ *  images. This class is abstracted to allow for dependency injection during
+ *  unit testing.
+ *  Usage:
+ *      To update/add a file to the cache, call processImage
+ *      To remove a file from the cache, call deleteFile
+ */
+class CacheUpdater {
+public:
+    // Make sure all the directories along this path exist
+    virtual void ensureDirectoriesExist(String8 path) = 0;
+
+    // Delete a file
+    virtual void deleteFile(String8 path) = 0;
+
+    // Process an image from source out to dest
+    virtual void processImage(String8 source, String8 dest) = 0;
+private:
+};
+
+/** SystemCacheUpdater
+ * This is an implementation of the above virtual cache updater specification.
+ * This implementations hits the filesystem to manage a cache and calls out to
+ * the PNG crunching in images.h to process images out to its cache components.
+ */
+class SystemCacheUpdater : public CacheUpdater {
+public:
+    // Constructor to set bundle to pass to preProcessImage
+    SystemCacheUpdater (Bundle* b)
+        : bundle(b) { };
+
+    // Make sure all the directories along this path exist
+    virtual void ensureDirectoriesExist(String8 path)
+    {
+        // Check to see if we're dealing with a fully qualified path
+        String8 existsPath;
+        String8 toCreate;
+        String8 remains;
+        struct stat s;
+
+        // Check optomistically to see if all directories exist.
+        // If something in the path doesn't exist, then walk the path backwards
+        // and find the place to start creating directories forward.
+        if (stat(path.string(),&s) == -1) {
+            // Walk backwards to find place to start creating directories
+            existsPath = path;
+            do {
+                // As we remove the end of existsPath add it to
+                // the string of paths to create.
+                toCreate = existsPath.getPathLeaf().appendPath(toCreate);
+                existsPath = existsPath.getPathDir();
+            } while (stat(existsPath.string(),&s) == -1);
+
+            // Walk forwards and build directories as we go
+            do {
+                // Advance to the next segment of the path
+                existsPath.appendPath(toCreate.walkPath(&remains));
+                toCreate = remains;
+#ifdef HAVE_MS_C_RUNTIME
+                _mkdir(existsPath.string());
+#else
+                mkdir(existsPath.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
+#endif
+            } while (remains.length() > 0);
+        } //if
+    };
+
+    // Delete a file
+    virtual void deleteFile(String8 path)
+    {
+        if (remove(path.string()) != 0)
+            fprintf(stderr,"ERROR DELETING %s\n",path.string());
+    };
+
+    // Process an image from source out to dest
+    virtual void processImage(String8 source, String8 dest)
+    {
+        // Make sure we're trying to write to a directory that is extant
+        ensureDirectoriesExist(dest.getPathDir());
+
+        preProcessImageToCache(bundle, source, dest);
+    };
+private:
+    Bundle* bundle;
+};
+
+#endif // CACHE_UPDATER_H
\ No newline at end of file
diff --git a/tools/aapt/Command.cpp b/tools/aapt/Command.cpp
index 739763e..3bc5fa1 100644
--- a/tools/aapt/Command.cpp
+++ b/tools/aapt/Command.cpp
@@ -1353,6 +1353,8 @@
     status_t err;
     sp<AaptAssets> assets;
     int N;
+    FILE* fp;
+    String8 dependencyFile;
 
     // -c zz_ZZ means do pseudolocalization
     ResourceFilter filter;
@@ -1387,6 +1389,16 @@
 
     // Load the assets.
     assets = new AaptAssets();
+
+    // Set up the resource gathering in assets if we're going to generate
+    // dependency files
+    if (bundle->getGenDependencies()) {
+        sp<FilePathStore> resPathStore = new FilePathStore;
+        assets->setFullResPaths(resPathStore);
+        sp<FilePathStore> assetPathStore = new FilePathStore;
+        assets->setFullAssetPaths(assetPathStore);
+    }
+
     err = assets->slurpFromArgs(bundle);
     if (err < 0) {
         goto bail;
@@ -1396,7 +1408,7 @@
         assets->print();
     }
 
-    // If they asked for any files that need to be compiled, do so.
+    // If they asked for any fileAs that need to be compiled, do so.
     if (bundle->getResourceSourceDirs().size() || bundle->getAndroidManifestFile()) {
         err = buildResources(bundle, assets);
         if (err != 0) {
@@ -1410,10 +1422,36 @@
         goto bail;
     }
 
+    if (bundle->getGenDependencies()) {
+        if (outputAPKFile) {
+            dependencyFile = String8(outputAPKFile);
+            // Strip the extension and add new one
+            dependencyFile = dependencyFile.getBasePath();
+            dependencyFile.append(".d");
+        } else {
+            dependencyFile = String8(bundle->getRClassDir());
+            dependencyFile.appendPath("R.d");
+        }
+        // Make sure we have a clean dependency file to start with
+        fp = fopen(dependencyFile, "w");
+        fclose(fp);
+    }
+
     // Write out R.java constants
     if (assets->getPackage() == assets->getSymbolsPrivatePackage()) {
         if (bundle->getCustomPackage() == NULL) {
             err = writeResourceSymbols(bundle, assets, assets->getPackage(), true);
+            // Copy R.java for libraries
+            if (bundle->getExtraPackages() != NULL) {
+                // Split on colon
+                String8 libs(bundle->getExtraPackages());
+                char* packageString = strtok(libs.lockBuffer(libs.length()), ":");
+                while (packageString != NULL) {
+                    err = writeResourceSymbols(bundle, assets, String8(packageString), true);
+                    packageString = strtok(NULL, ":");
+                }
+                libs.unlockBuffer();
+            }
         } else {
             const String8 customPkg(bundle->getCustomPackage());
             err = writeResourceSymbols(bundle, assets, customPkg, true);
@@ -1447,6 +1485,18 @@
         }
     }
 
+    if (bundle->getGenDependencies()) {
+        // Now that writeResourceSymbols or writeAPK has taken care of writing
+        // the targets to our dependency file, we'll write the prereqs
+        fp = fopen(dependencyFile, "a+");
+        fprintf(fp, " : ");
+        bool includeRaw = (outputAPKFile != NULL);
+        err = writeDependencyPreReqs(bundle, assets, fp, includeRaw);
+        // Also manually add the AndroidManifeset since it's a non-asset
+        fprintf(fp, "%s \\\n", bundle->getAndroidManifestFile());
+        fclose(fp);
+    }
+
     retVal = 0;
 bail:
     if (SourcePos::hasErrors()) {
@@ -1454,3 +1504,25 @@
     }
     return retVal;
 }
+
+/*
+ * Do PNG Crunching
+ * PRECONDITIONS
+ *  -S flag points to a source directory containing drawable* folders
+ *  -C flag points to destination directory. The folder structure in the
+ *     source directory will be mirrored to the destination (cache) directory
+ *
+ * POSTCONDITIONS
+ *  Destination directory will be updated to match the PNG files in
+ *  the source directory. 
+ */
+int doCrunch(Bundle* bundle)
+{
+    fprintf(stdout, "Crunching PNG Files in ");
+    fprintf(stdout, "source dir: %s\n", bundle->getResourceSourceDirs()[0]);
+    fprintf(stdout, "To destination dir: %s\n", bundle->getCrunchedOutputDir());
+
+    updatePreProcessedCache(bundle);
+
+    return NO_ERROR;
+}
diff --git a/tools/aapt/CrunchCache.cpp b/tools/aapt/CrunchCache.cpp
new file mode 100644
index 0000000..c4cf6bc
--- /dev/null
+++ b/tools/aapt/CrunchCache.cpp
@@ -0,0 +1,104 @@
+//
+// Copyright 2011 The Android Open Source Project
+//
+// Implementation file for CrunchCache
+// This file defines functions laid out and documented in
+// CrunchCache.h
+
+#include <utils/Vector.h>
+#include <utils/String8.h>
+
+#include "DirectoryWalker.h"
+#include "FileFinder.h"
+#include "CacheUpdater.h"
+#include "CrunchCache.h"
+
+using namespace android;
+
+CrunchCache::CrunchCache(String8 sourcePath, String8 destPath, FileFinder* ff)
+    : mSourcePath(sourcePath), mDestPath(destPath), mSourceFiles(0), mDestFiles(0), mFileFinder(ff)
+{
+    // We initialize the default value to return to 0 so if a file doesn't exist
+    // then all files are automatically "newer" than it.
+
+    // Set file extensions to look for. Right now just pngs.
+    mExtensions.push(String8(".png"));
+
+    // Load files into our data members
+    loadFiles();
+}
+
+size_t CrunchCache::crunch(CacheUpdater* cu, bool forceOverwrite)
+{
+    size_t numFilesUpdated = 0;
+
+    // Iterate through the source files and compare to cache.
+    // After processing a file, remove it from the source files and
+    // from the dest files.
+    // We're done when we're out of files in source.
+    String8 relativePath;
+    while (mSourceFiles.size() > 0) {
+        // Get the full path to the source file, then convert to a c-string
+        // and offset our beginning pointer to the length of the sourcePath
+        // This efficiently strips the source directory prefix from our path.
+        // Also, String8 doesn't have a substring method so this is what we've
+        // got to work with.
+        const char* rPathPtr = mSourceFiles.keyAt(0).string()+mSourcePath.length();
+        // Strip leading slash if present
+        int offset = 0;
+        if (rPathPtr[0] == OS_PATH_SEPARATOR)
+            offset = 1;
+        relativePath = String8(rPathPtr + offset);
+
+        if (forceOverwrite || needsUpdating(relativePath)) {
+            cu->processImage(mSourcePath.appendPathCopy(relativePath),
+                             mDestPath.appendPathCopy(relativePath));
+            numFilesUpdated++;
+            // crunchFile(relativePath);
+        }
+        // Delete this file from the source files and (if it exists) from the
+        // dest files.
+        mSourceFiles.removeItemsAt(0);
+        mDestFiles.removeItem(mDestPath.appendPathCopy(relativePath));
+    }
+
+    // Iterate through what's left of destFiles and delete leftovers
+    while (mDestFiles.size() > 0) {
+        cu->deleteFile(mDestFiles.keyAt(0));
+        mDestFiles.removeItemsAt(0);
+    }
+
+    // Update our knowledge of the files cache
+    // both source and dest should be empty by now.
+    loadFiles();
+
+    return numFilesUpdated;
+}
+
+void CrunchCache::loadFiles()
+{
+    // Clear out our data structures to avoid putting in duplicates
+    mSourceFiles.clear();
+    mDestFiles.clear();
+
+    // Make a directory walker that points to the system.
+    DirectoryWalker* dw = new SystemDirectoryWalker();
+
+    // Load files in the source directory
+    mFileFinder->findFiles(mSourcePath, mExtensions, mSourceFiles,dw);
+
+    // Load files in the destination directory
+    mFileFinder->findFiles(mDestPath,mExtensions,mDestFiles,dw);
+
+    delete dw;
+}
+
+bool CrunchCache::needsUpdating(String8 relativePath) const
+{
+    // Retrieve modification dates for this file entry under the source and
+    // cache directory trees. The vectors will return a modification date of 0
+    // if the file doesn't exist.
+    time_t sourceDate = mSourceFiles.valueFor(mSourcePath.appendPathCopy(relativePath));
+    time_t destDate = mDestFiles.valueFor(mDestPath.appendPathCopy(relativePath));
+    return sourceDate > destDate;
+}
\ No newline at end of file
diff --git a/tools/aapt/CrunchCache.h b/tools/aapt/CrunchCache.h
new file mode 100644
index 0000000..be3da5c
--- /dev/null
+++ b/tools/aapt/CrunchCache.h
@@ -0,0 +1,102 @@
+//
+// Copyright 2011 The Android Open Source Project
+//
+// Cache manager for pre-processed PNG files.
+// Contains code for managing which PNG files get processed
+// at build time.
+//
+
+#ifndef CRUNCHCACHE_H
+#define CRUNCHCACHE_H
+
+#include <utils/KeyedVector.h>
+#include <utils/String8.h>
+#include "FileFinder.h"
+#include "CacheUpdater.h"
+
+using namespace android;
+
+/** CrunchCache
+ *  This class is a cache manager which can pre-process PNG files and store
+ *  them in a mirror-cache. It's capable of doing incremental updates to its
+ *  cache.
+ *
+ *  Usage:
+ *      Create an instance initialized with the root of the source tree, the
+ *      root location to store the cache files, and an instance of a file finder.
+ *      Then update the cache by calling crunch.
+ */
+class CrunchCache {
+public:
+    // Constructor
+    CrunchCache(String8 sourcePath, String8 destPath, FileFinder* ff);
+
+    // Nobody should be calling the default constructor
+    // So this space is intentionally left blank
+
+    // Default Copy Constructor and Destructor are fine
+
+    /** crunch is the workhorse of this class.
+     * It goes through all the files found in the sourcePath and compares
+     * them to the cached versions in the destPath. If the optional
+     * argument forceOverwrite is set to true, then all source files are
+     * re-crunched even if they have not been modified recently. Otherwise,
+     * source files are only crunched when they needUpdating. Afterwards,
+     * we delete any leftover files in the cache that are no longer present
+     * in source.
+     *
+     * PRECONDITIONS:
+     *      No setup besides construction is needed
+     * POSTCONDITIONS:
+     *      The cache is updated to fully reflect all changes in source.
+     *      The function then returns the number of files changed in cache
+     *      (counting deletions).
+     */
+    size_t crunch(CacheUpdater* cu, bool forceOverwrite=false);
+
+private:
+    /** loadFiles is a wrapper to the FileFinder that places matching
+     * files into mSourceFiles and mDestFiles.
+     *
+     *  POSTCONDITIONS
+     *      mDestFiles and mSourceFiles are refreshed to reflect the current
+     *      state of the files in the source and dest directories.
+     *      Any previous contents of mSourceFiles and mDestFiles are cleared.
+     */
+    void loadFiles();
+
+    /** needsUpdating takes a file path
+     * and returns true if the file represented by this path is newer in the
+     * sourceFiles than in the cache (mDestFiles).
+     *
+     * PRECONDITIONS:
+     *      mSourceFiles and mDestFiles must be initialized and filled.
+     * POSTCONDITIONS:
+     *      returns true if and only if source file's modification time
+     *      is greater than the cached file's mod-time. Otherwise returns false.
+     *
+     * USAGE:
+     *      Should be used something like the following:
+     *      if (needsUpdating(filePath))
+     *          // Recrunch sourceFile out to destFile.
+     *
+     */
+    bool needsUpdating(String8 relativePath) const;
+
+    // DATA MEMBERS ====================================================
+
+    String8 mSourcePath;
+    String8 mDestPath;
+
+    Vector<String8> mExtensions;
+
+    // Each vector of paths contains one entry per PNG file encountered.
+    // Each entry consists of a path pointing to that PNG.
+    DefaultKeyedVector<String8,time_t> mSourceFiles;
+    DefaultKeyedVector<String8,time_t> mDestFiles;
+
+    // Pointer to a FileFinder to use
+    FileFinder* mFileFinder;
+};
+
+#endif // CRUNCHCACHE_H
diff --git a/tools/aapt/DirectoryWalker.h b/tools/aapt/DirectoryWalker.h
new file mode 100644
index 0000000..88031d0
--- /dev/null
+++ b/tools/aapt/DirectoryWalker.h
@@ -0,0 +1,98 @@
+//
+// Copyright 2011 The Android Open Source Project
+//
+// Defines an abstraction for opening a directory on the filesystem and
+// iterating through it.
+
+#ifndef DIRECTORYWALKER_H
+#define DIRECTORYWALKER_H
+
+#include <dirent.h>
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <utils/String8.h>
+
+#include <stdio.h>
+
+using namespace android;
+
+// Directory Walker
+// This is an abstraction for walking through a directory and getting files
+// and descriptions.
+
+class DirectoryWalker {
+public:
+    virtual ~DirectoryWalker() {};
+    virtual bool openDir(String8 path) = 0;
+    virtual bool openDir(const char* path) = 0;
+    // Advance to next directory entry
+    virtual struct dirent* nextEntry() = 0;
+    // Get the stats for the current entry
+    virtual struct stat*   entryStats() = 0;
+    // Clean Up
+    virtual void closeDir() = 0;
+    // This class is able to replicate itself on the heap
+    virtual DirectoryWalker* clone() = 0;
+
+    // DATA MEMBERS
+    // Current directory entry
+    struct dirent mEntry;
+    // Stats for that directory entry
+    struct stat mStats;
+    // Base path
+    String8 mBasePath;
+};
+
+// System Directory Walker
+// This is an implementation of the above abstraction that calls
+// real system calls and is fully functional.
+// functions are inlined since they're very short and simple
+
+class SystemDirectoryWalker : public DirectoryWalker {
+
+    // Default constructor, copy constructor, and destructor are fine
+public:
+    virtual bool openDir(String8 path) {
+        mBasePath = path;
+        dir = NULL;
+        dir = opendir(mBasePath.string() );
+
+        if (dir == NULL)
+            return false;
+
+        return true;
+    };
+    virtual bool openDir(const char* path) {
+        String8 p(path);
+        openDir(p);
+        return true;
+    };
+    // Advance to next directory entry
+    virtual struct dirent* nextEntry() {
+        struct dirent* entryPtr = readdir(dir);
+        if (entryPtr == NULL)
+            return NULL;
+
+        mEntry = *entryPtr;
+        // Get stats
+        String8 fullPath = mBasePath.appendPathCopy(mEntry.d_name);
+        stat(fullPath.string(),&mStats);
+        return &mEntry;
+    };
+    // Get the stats for the current entry
+    virtual struct stat*   entryStats() {
+        return &mStats;
+    };
+    virtual void closeDir() {
+        closedir(dir);
+    };
+    virtual DirectoryWalker* clone() {
+        return new SystemDirectoryWalker(*this);
+    };
+private:
+    DIR* dir;
+};
+
+#endif // DIRECTORYWALKER_H
diff --git a/tools/aapt/FileFinder.cpp b/tools/aapt/FileFinder.cpp
new file mode 100644
index 0000000..18775c0
--- /dev/null
+++ b/tools/aapt/FileFinder.cpp
@@ -0,0 +1,98 @@
+//
+// Copyright 2011 The Android Open Source Project
+//
+
+// File Finder implementation.
+// Implementation for the functions declared and documented in FileFinder.h
+
+#include <utils/Vector.h>
+#include <utils/String8.h>
+#include <utils/KeyedVector.h>
+
+#include <dirent.h>
+#include <sys/stat.h>
+
+#include "DirectoryWalker.h"
+#include "FileFinder.h"
+
+//#define DEBUG
+
+using android::String8;
+
+// Private function to check whether a file is a directory or not
+bool isDirectory(const char* filename) {
+    struct stat fileStat;
+    if (stat(filename, &fileStat) == -1) {
+        return false;
+    }
+    return(S_ISDIR(fileStat.st_mode));
+}
+
+
+// Private function to check whether a file is a regular file or not
+bool isFile(const char* filename) {
+    struct stat fileStat;
+    if (stat(filename, &fileStat) == -1) {
+        return false;
+    }
+    return(S_ISREG(fileStat.st_mode));
+}
+
+bool SystemFileFinder::findFiles(String8 basePath, Vector<String8>& extensions,
+                                 KeyedVector<String8,time_t>& fileStore,
+                                 DirectoryWalker* dw)
+{
+    // Scan the directory pointed to by basePath
+    // check files and recurse into subdirectories.
+    if (!dw->openDir(basePath)) {
+        return false;
+    }
+    /*
+     *  Go through all directory entries. Check each file using checkAndAddFile
+     *  and recurse into sub-directories.
+     */
+    struct dirent* entry;
+    while ((entry = dw->nextEntry()) != NULL) {
+        String8 entryName(entry->d_name);
+        if (entry->d_name[0] == '.') // Skip hidden files and directories
+            continue;
+
+        String8 fullPath = basePath.appendPathCopy(entryName);
+        // If this entry is a directory we'll recurse into it
+        if (isDirectory(fullPath.string()) ) {
+            DirectoryWalker* copy = dw->clone();
+            findFiles(fullPath, extensions, fileStore,copy);
+            delete copy;
+        }
+
+        // If this entry is a file, we'll pass it over to checkAndAddFile
+        if (isFile(fullPath.string()) ) {
+            checkAndAddFile(fullPath,dw->entryStats(),extensions,fileStore);
+        }
+    }
+
+    // Clean up
+    dw->closeDir();
+
+    return true;
+}
+
+void SystemFileFinder::checkAndAddFile(String8 path, const struct stat* stats,
+                                       Vector<String8>& extensions,
+                                       KeyedVector<String8,time_t>& fileStore)
+{
+    // Loop over the extensions, checking for a match
+    bool done = false;
+    String8 ext(path.getPathExtension());
+    ext.toLower();
+    for (size_t i = 0; i < extensions.size() && !done; ++i) {
+        String8 ext2 = extensions[i].getPathExtension();
+        ext2.toLower();
+        // Compare the extensions. If a match is found, add to storage.
+        if (ext == ext2) {
+            done = true;
+            fileStore.add(path,stats->st_mtime);
+        }
+    }
+}
+
diff --git a/tools/aapt/FileFinder.h b/tools/aapt/FileFinder.h
new file mode 100644
index 0000000..6974aee
--- /dev/null
+++ b/tools/aapt/FileFinder.h
@@ -0,0 +1,80 @@
+//
+// Copyright 2011 The Android Open Source Project
+//
+
+// File Finder.
+// This is a collection of useful functions for finding paths and modification
+// times of files that match an extension pattern in a directory tree.
+// and finding files in it.
+
+#ifndef FILEFINDER_H
+#define FILEFINDER_H
+
+#include <utils/Vector.h>
+#include <utils/KeyedVector.h>
+#include <utils/String8.h>
+
+#include "DirectoryWalker.h"
+
+using namespace android;
+
+// Abstraction to allow for dependency injection. See MockFileFinder.h
+// for the testing implementation.
+class FileFinder {
+public:
+    virtual bool findFiles(String8 basePath, Vector<String8>& extensions,
+                           KeyedVector<String8,time_t>& fileStore,
+                           DirectoryWalker* dw) = 0;
+
+    virtual ~FileFinder() {};
+};
+
+class SystemFileFinder : public FileFinder {
+public:
+
+    /* findFiles takes a path, a Vector of extensions, and a destination KeyedVector
+     *           and places path/modification date key/values pointing to
+     *          all files with matching extensions found into the KeyedVector
+     * PRECONDITIONS
+     *     path is a valid system path
+     *     extensions should include leading "."
+     *                This is not necessary, but the comparison directly
+     *                compares the end of the path string so if the "."
+     *                is excluded there is a small chance you could have
+     *                a false positive match. (For example: extension "png"
+     *                would match a file called "blahblahpng")
+     *
+     * POSTCONDITIONS
+     *     fileStore contains (in no guaranteed order) paths to all
+     *                matching files encountered in subdirectories of path
+     *                as keys in the KeyedVector. Each key has the modification time
+     *                of the file as its value.
+     *
+     * Calls checkAndAddFile on each file encountered in the directory tree
+     * Recursively descends into subdirectories.
+     */
+    virtual bool findFiles(String8 basePath, Vector<String8>& extensions,
+                           KeyedVector<String8,time_t>& fileStore,
+                           DirectoryWalker* dw);
+
+private:
+    /**
+     * checkAndAddFile looks at a single file path and stat combo
+     * to determine whether it is a matching file (by looking at
+     * the extension)
+     *
+     * PRECONDITIONS
+     *    no setup is needed
+     *
+     * POSTCONDITIONS
+     *    If the given file has a matching extension then a new entry
+     *    is added to the KeyedVector with the path as the key and the modification
+     *    time as the value.
+     *
+     */
+    static void checkAndAddFile(String8 path, const struct stat* stats,
+                                Vector<String8>& extensions,
+                                KeyedVector<String8,time_t>& fileStore);
+
+};
+#endif // FILEFINDER_H
diff --git a/tools/aapt/Images.cpp b/tools/aapt/Images.cpp
index 3c471ca..311ceea 100644
--- a/tools/aapt/Images.cpp
+++ b/tools/aapt/Images.cpp
@@ -1080,7 +1080,128 @@
     return error;
 }
 
+status_t preProcessImageToCache(Bundle* bundle, String8 source, String8 dest)
+{
+    png_structp read_ptr = NULL;
+    png_infop read_info = NULL;
 
+    FILE* fp;
+
+    image_info imageInfo;
+
+    png_structp write_ptr = NULL;
+    png_infop write_info = NULL;
+
+    status_t error = UNKNOWN_ERROR;
+
+    // Get a file handler to read from
+    fp = fopen(source.string(),"rb");
+    if (fp == NULL) {
+        fprintf(stderr, "%s ERROR: Unable to open PNG file\n", source.string());
+        return error;
+    }
+
+    // Call libpng to get a struct to read image data into
+    read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+    if (!read_ptr) {
+        fclose(fp);
+        png_destroy_read_struct(&read_ptr, &read_info,NULL);
+        return error;
+    }
+
+    // Call libpng to get a struct to read image info into
+    read_info = png_create_info_struct(read_ptr);
+    if (!read_info) {
+        fclose(fp);
+        png_destroy_read_struct(&read_ptr, &read_info,NULL);
+        return error;
+    }
+
+    // Set a jump point for libpng to long jump back to on error
+    if (setjmp(png_jmpbuf(read_ptr))) {
+        fclose(fp);
+        png_destroy_read_struct(&read_ptr, &read_info,NULL);
+        return error;
+    }
+
+    // Set up libpng to read from our file.
+    png_init_io(read_ptr,fp);
+
+    // Actually read data from the file
+    read_png(source.string(), read_ptr, read_info, &imageInfo);
+
+    // We're done reading so we can clean up
+    // Find old file size before releasing handle
+    fseek(fp, 0, SEEK_END);
+    size_t oldSize = (size_t)ftell(fp);
+    fclose(fp);
+    png_destroy_read_struct(&read_ptr, &read_info,NULL);
+
+    // Check to see if we're dealing with a 9-patch
+    // If we are, process appropriately
+    if (source.getBasePath().getPathExtension() == ".9")  {
+        if (do_9patch(source.string(), &imageInfo) != NO_ERROR) {
+            return error;
+        }
+    }
+
+    // Call libpng to create a structure to hold the processed image data
+    // that can be written to disk
+    write_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+    if (!write_ptr) {
+        png_destroy_write_struct(&write_ptr, &write_info);
+        return error;
+    }
+
+    // Call libpng to create a structure to hold processed image info that can
+    // be written to disk
+    write_info = png_create_info_struct(write_ptr);
+    if (!write_info) {
+        png_destroy_write_struct(&write_ptr, &write_info);
+        return error;
+    }
+
+    // Open up our destination file for writing
+    fp = fopen(dest.string(), "wb");
+    if (!fp) {
+        fprintf(stderr, "%s ERROR: Unable to open PNG file\n", dest.string());
+        png_destroy_write_struct(&write_ptr, &write_info);
+        return error;
+    }
+
+    // Set up libpng to write to our file
+    png_init_io(write_ptr, fp);
+
+    // Set up a jump for libpng to long jump back on on errors
+    if (setjmp(png_jmpbuf(write_ptr))) {
+        fclose(fp);
+        png_destroy_write_struct(&write_ptr, &write_info);
+        return error;
+    }
+
+    // Actually write out to the new png
+    write_png(dest.string(), write_ptr, write_info, imageInfo,
+              bundle->getGrayscaleTolerance());
+
+    if (bundle->getVerbose()) {
+        // Find the size of our new file
+        FILE* reader = fopen(dest.string(), "rb");
+        fseek(reader, 0, SEEK_END);
+        size_t newSize = (size_t)ftell(reader);
+        fclose(reader);
+
+        float factor = ((float)newSize)/oldSize;
+        int percent = (int)(factor*100);
+        printf("  (processed image to cache entry %s: %d%% size of source)\n",
+               dest.string(), percent);
+    }
+
+    //Clean up
+    fclose(fp);
+    png_destroy_write_struct(&write_ptr, &write_info);
+
+    return NO_ERROR;
+}
 
 status_t postProcessImage(const sp<AaptAssets>& assets,
                           ResourceTable* table, const sp<AaptFile>& file)
diff --git a/tools/aapt/Images.h b/tools/aapt/Images.h
index 168e22f..4816905 100644
--- a/tools/aapt/Images.h
+++ b/tools/aapt/Images.h
@@ -8,11 +8,19 @@
 #define IMAGES_H
 
 #include "ResourceTable.h"
+#include "Bundle.h"
+
+#include <utils/String8.h>
+#include <utils/RefBase.h>
+
+using android::String8;
 
 status_t preProcessImage(Bundle* bundle, const sp<AaptAssets>& assets,
                          const sp<AaptFile>& file, String8* outNewLeafName);
 
+status_t preProcessImageToCache(Bundle* bundle, String8 source, String8 dest);
+
 status_t postProcessImage(const sp<AaptAssets>& assets,
-						  ResourceTable* table, const sp<AaptFile>& file);
+                          ResourceTable* table, const sp<AaptFile>& file);
 
 #endif
diff --git a/tools/aapt/Main.cpp b/tools/aapt/Main.cpp
index 1e63131..5135787 100644
--- a/tools/aapt/Main.cpp
+++ b/tools/aapt/Main.cpp
@@ -83,6 +83,9 @@
         " %s a[dd] [-v] file.{zip,jar,apk} file1 [file2 ...]\n"
         "   Add specified files to Zip-compatible archive.\n\n", gProgName);
     fprintf(stderr,
+        " %s c[runch] [-v] -S resource-sources ... -C output-folder ...\n"
+        "   Do PNG preprocessing and store the results in output folder.\n\n", gProgName);
+    fprintf(stderr,
         " %s v[ersion]\n"
         "   Print program version.\n\n", gProgName);
     fprintf(stderr,
@@ -145,6 +148,10 @@
         "       inserts android:versionName in to manifest.\n"
         "   --custom-package\n"
         "       generates R.java into a different package.\n"
+        "   --extra-packages\n"
+        "       generate R.java for libraries. Separate libraries with ':'.\n"
+        "   --generate-dependencies\n"
+        "       generate dependency files in the same directories for R.java and resource package\n"
         "   --auto-add-overlay\n"
         "       Automatically add resources that are only in overlays.\n"
         "   --rename-manifest-package\n"
@@ -186,6 +193,7 @@
     case kCommandAdd:       return doAdd(bundle);
     case kCommandRemove:    return doRemove(bundle);
     case kCommandPackage:   return doPackage(bundle);
+    case kCommandCrunch:    return doCrunch(bundle);
     default:
         fprintf(stderr, "%s: requested command not yet supported\n", gProgName);
         return 1;
@@ -223,6 +231,8 @@
         bundle.setCommand(kCommandRemove);
     else if (argv[1][0] == 'p')
         bundle.setCommand(kCommandPackage);
+    else if (argv[1][0] == 'c')
+        bundle.setCommand(kCommandCrunch);
     else {
         fprintf(stderr, "ERROR: Unknown command '%s'\n", argv[1]);
         wantUsage = true;
@@ -393,6 +403,17 @@
                 convertPath(argv[0]);
                 bundle.addResourceSourceDir(argv[0]);
                 break;
+            case 'C':
+                argc--;
+                argv++;
+                if (!argc) {
+                    fprintf(stderr, "ERROR: No argument supplied for '-C' option\n");
+                    wantUsage = true;
+                    goto bail;
+                }
+                convertPath(argv[0]);
+                bundle.setCrunchedOutputDir(argv[0]);
+                break;
             case '0':
                 argc--;
                 argv++;
@@ -475,6 +496,17 @@
                         goto bail;
                     }
                     bundle.setCustomPackage(argv[0]);
+                } else if (strcmp(cp, "-extra-packages") == 0) {
+                    argc--;
+                    argv++;
+                    if (!argc) {
+                        fprintf(stderr, "ERROR: No argument supplied for '--extra-packages' option\n");
+                        wantUsage = true;
+                        goto bail;
+                    }
+                    bundle.setExtraPackages(argv[0]);
+                } else if (strcmp(cp, "-generate-dependencies") == 0) {
+                    bundle.setGenDependencies(true);
                 } else if (strcmp(cp, "-utf16") == 0) {
                     bundle.setWantUTF16(true);
                 } else if (strcmp(cp, "-rename-manifest-package") == 0) {
@@ -508,7 +540,9 @@
                     bundle.setProduct(argv[0]);
                 } else if (strcmp(cp, "-non-constant-id") == 0) {
                     bundle.setNonConstantId(true);
-                } else {
+                } else if (strcmp(cp, "-no-crunch") == 0) {
+                    bundle.setUseCrunchCache(true);
+                }else {
                     fprintf(stderr, "ERROR: Unknown option '-%s'\n", cp);
                     wantUsage = true;
                     goto bail;
diff --git a/tools/aapt/Main.h b/tools/aapt/Main.h
index 3ba4f39..d20c601 100644
--- a/tools/aapt/Main.h
+++ b/tools/aapt/Main.h
@@ -14,12 +14,21 @@
 #include "AaptAssets.h"
 #include "ZipFile.h"
 
+
+/* Benchmarking Flag */
+//#define BENCHMARK 1
+
+#if BENCHMARK
+    #include <time.h>
+#endif /* BENCHMARK */
+
 extern int doVersion(Bundle* bundle);
 extern int doList(Bundle* bundle);
 extern int doDump(Bundle* bundle);
 extern int doAdd(Bundle* bundle);
 extern int doRemove(Bundle* bundle);
 extern int doPackage(Bundle* bundle);
+extern int doCrunch(Bundle* bundle);
 
 extern int calcPercent(long uncompressedLen, long compressedLen);
 
@@ -27,6 +36,8 @@
     const sp<AaptAssets>& assets,
     const android::String8& outputFile);
 
+extern android::status_t updatePreProcessedCache(Bundle* bundle);
+
 extern android::status_t buildResources(Bundle* bundle,
     const sp<AaptAssets>& assets);
 
@@ -46,4 +57,6 @@
 String8 getAttribute(const ResXMLTree& tree, const char* ns,
                             const char* attr, String8* outError);
 
+status_t writeDependencyPreReqs(Bundle* bundle, const sp<AaptAssets>& assets,
+                                FILE* fp, bool includeRaw);
 #endif // __MAIN_H
diff --git a/tools/aapt/Package.cpp b/tools/aapt/Package.cpp
index 999a5cf..62af30e 100644
--- a/tools/aapt/Package.cpp
+++ b/tools/aapt/Package.cpp
@@ -50,6 +50,11 @@
 status_t writeAPK(Bundle* bundle, const sp<AaptAssets>& assets,
                        const String8& outputFile)
 {
+    #if BENCHMARK
+    fprintf(stdout, "BENCHMARK: Starting APK Bundling \n");
+    long startAPKTime = clock();
+    #endif /* BENCHMARK */
+
     status_t result = NO_ERROR;
     ZipFile* zip = NULL;
     int count;
@@ -172,6 +177,16 @@
         }
     }
 
+    if (bundle->getGenDependencies()) {
+        // Add this file to the dependency file
+        String8 dependencyFile = outputFile.getBasePath();
+        dependencyFile.append(".d");
+
+        FILE* fp = fopen(dependencyFile.string(), "a");
+        fprintf(fp, "%s \\\n", outputFile.string());
+        fclose(fp);
+    }
+
     assert(result == NO_ERROR);
 
 bail:
@@ -187,6 +202,10 @@
 
     if (result == NO_ERROR && bundle->getVerbose())
         printf("Done!\n");
+
+    #if BENCHMARK
+    fprintf(stdout, "BENCHMARK: End APK Bundling. Time Elapsed: %f ms \n",(clock() - startAPKTime)/1000.0);
+    #endif /* BENCHMARK */
     return result;
 }
 
diff --git a/tools/aapt/Resource.cpp b/tools/aapt/Resource.cpp
index 0a4f24f..5152d3b 100644
--- a/tools/aapt/Resource.cpp
+++ b/tools/aapt/Resource.cpp
@@ -10,6 +10,10 @@
 #include "ResourceTable.h"
 #include "Images.h"
 
+#include "CrunchCache.h"
+#include "FileFinder.h"
+#include "CacheUpdater.h"
+
 #define NOISY(x) // x
 
 // ==========================================================================
@@ -51,6 +55,12 @@
 {
 }
 
+FilePathStore::FilePathStore()
+    :RefBase(),
+     Vector<String8>()
+{
+}
+
 class ResourceDirIterator
 {
 public:
@@ -286,18 +296,19 @@
 static status_t preProcessImages(Bundle* bundle, const sp<AaptAssets>& assets,
                           const sp<ResourceTypeSet>& set)
 {
-    ResourceDirIterator it(set, String8("drawable"));
-    Vector<sp<AaptFile> > newNameFiles;
-    Vector<String8> newNamePaths;
     bool hasErrors = false;
-    ssize_t res;
-    while ((res=it.next()) == NO_ERROR) {
-        res = preProcessImage(bundle, assets, it.getFile(), NULL);
-        if (res < NO_ERROR) {
-            hasErrors = true;
+    ssize_t res = NO_ERROR;
+    if (bundle->getUseCrunchCache() == false) {
+        ResourceDirIterator it(set, String8("drawable"));
+        Vector<sp<AaptFile> > newNameFiles;
+        Vector<String8> newNamePaths;
+        while ((res=it.next()) == NO_ERROR) {
+            res = preProcessImage(bundle, assets, it.getFile(), NULL);
+            if (res < NO_ERROR) {
+                hasErrors = true;
+            }
         }
     }
-
     return (hasErrors || (res < NO_ERROR)) ? UNKNOWN_ERROR : NO_ERROR;
 }
 
@@ -747,6 +758,35 @@
             } \
         } while (0)
 
+status_t updatePreProcessedCache(Bundle* bundle)
+{
+    #if BENCHMARK
+    fprintf(stdout, "BENCHMARK: Starting PNG PreProcessing \n");
+    long startPNGTime = clock();
+    #endif /* BENCHMARK */
+
+    String8 source(bundle->getResourceSourceDirs()[0]);
+    String8 dest(bundle->getCrunchedOutputDir());
+
+    FileFinder* ff = new SystemFileFinder();
+    CrunchCache cc(source,dest,ff);
+
+    CacheUpdater* cu = new SystemCacheUpdater(bundle);
+    size_t numFiles = cc.crunch(cu);
+
+    if (bundle->getVerbose())
+        fprintf(stdout, "Crunched %d PNG files to update cache\n", (int)numFiles);
+
+    delete ff;
+    delete cu;
+
+    #if BENCHMARK
+    fprintf(stdout, "BENCHMARK: End PNG PreProcessing. Time Elapsed: %f ms \n"
+            ,(clock() - startPNGTime)/1000.0);
+    #endif /* BENCHMARK */
+    return 0;
+}
+
 status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets)
 {
     // First, look for a package file to parse.  This is required to
@@ -1849,6 +1889,16 @@
             return err;
         }
         fclose(fp);
+
+        if (bundle->getGenDependencies()) {
+            // Add this R.java to the dependency file
+            String8 dependencyFile(bundle->getRClassDir());
+            dependencyFile.appendPath("R.d");
+
+            fp = fopen(dependencyFile.string(), "a");
+            fprintf(fp,"%s \\\n", dest.string());
+            fclose(fp);
+        }
     }
 
     return NO_ERROR;
@@ -2170,3 +2220,27 @@
 
     return err;
 }
+
+// Loops through the string paths and writes them to the file pointer
+// Each file path is written on its own line with a terminating backslash.
+status_t writePathsToFile(const sp<FilePathStore>& files, FILE* fp)
+{
+    status_t deps = -1;
+    for (size_t file_i = 0; file_i < files->size(); ++file_i) {
+        // Add the full file path to the dependency file
+        fprintf(fp, "%s \\\n", files->itemAt(file_i).string());
+        deps++;
+    }
+    return deps;
+}
+
+status_t
+writeDependencyPreReqs(Bundle* bundle, const sp<AaptAssets>& assets, FILE* fp, bool includeRaw)
+{
+    status_t deps = -1;
+    deps += writePathsToFile(assets->getFullResPaths(), fp);
+    if (includeRaw) {
+        deps += writePathsToFile(assets->getFullAssetPaths(), fp);
+    }
+    return deps;
+}
diff --git a/tools/aapt/XMLNode.cpp b/tools/aapt/XMLNode.cpp
index c0d7427..19248bf 100644
--- a/tools/aapt/XMLNode.cpp
+++ b/tools/aapt/XMLNode.cpp
@@ -504,7 +504,8 @@
             namespaces.pop();
         } else if (code == ResXMLTree::TEXT) {
             size_t len;
-            printf("%sC: \"%s\"\n", prefix.string(), String8(block->getText(&len)).string());
+            printf("%sC: \"%s\"\n", prefix.string(), ResTable::normalizeForOutput(
+                        String8(block->getText(&len)).string()).string());
         }
     }
 
diff --git a/tools/aapt/tests/CrunchCache_test.cpp b/tools/aapt/tests/CrunchCache_test.cpp
new file mode 100644
index 0000000..20b5022
--- /dev/null
+++ b/tools/aapt/tests/CrunchCache_test.cpp
@@ -0,0 +1,97 @@
+//
+// Copyright 2011 The Android Open Source Project
+//
+#include <utils/String8.h>
+#include <iostream>
+#include <errno.h>
+
+#include "CrunchCache.h"
+#include "FileFinder.h"
+#include "MockFileFinder.h"
+#include "CacheUpdater.h"
+#include "MockCacheUpdater.h"
+
+using namespace android;
+using std::cout;
+using std::endl;
+
+void expectEqual(int got, int expected, const char* desc) {
+    cout << "Checking " << desc << ": ";
+    cout << "Got " << got << ", expected " << expected << "...";
+    cout << ( (got == expected) ? "PASSED" : "FAILED") << endl;
+    errno += ((got == expected) ? 0 : 1);
+}
+
+int main() {
+
+    errno = 0;
+
+    String8 source("res");
+    String8 dest("res2");
+
+    // Create data for MockFileFinder to feed to the cache
+    KeyedVector<String8, time_t> sourceData;
+    // This shouldn't be updated
+    sourceData.add(String8("res/drawable/hello.png"),3);
+    // This should be updated
+    sourceData.add(String8("res/drawable/world.png"),5);
+    // This should cause make directory to be called
+    sourceData.add(String8("res/drawable-cool/hello.png"),3);
+
+    KeyedVector<String8, time_t> destData;
+    destData.add(String8("res2/drawable/hello.png"),3);
+    destData.add(String8("res2/drawable/world.png"),3);
+    // this should call delete
+    destData.add(String8("res2/drawable/dead.png"),3);
+
+    // Package up data and create mock file finder
+    KeyedVector<String8, KeyedVector<String8,time_t> > data;
+    data.add(source,sourceData);
+    data.add(dest,destData);
+    FileFinder* ff = new MockFileFinder(data);
+    CrunchCache cc(source,dest,ff);
+
+    MockCacheUpdater* mcu = new MockCacheUpdater();
+    CacheUpdater* cu(mcu);
+
+    cout << "Running Crunch...";
+    int result = cc.crunch(cu);
+    cout << ((result > 0) ? "PASSED" : "FAILED") << endl;
+    errno += ((result > 0) ? 0 : 1);
+
+    const int EXPECTED_RESULT = 2;
+    expectEqual(result, EXPECTED_RESULT, "number of files touched");
+
+    cout << "Checking calls to deleteFile and processImage:" << endl;
+    const int EXPECTED_DELETES = 1;
+    const int EXPECTED_PROCESSED = 2;
+    // Deletes
+    expectEqual(mcu->deleteCount, EXPECTED_DELETES, "deleteFile");
+    // processImage
+    expectEqual(mcu->processCount, EXPECTED_PROCESSED, "processImage");
+
+    const int EXPECTED_OVERWRITES = 3;
+    result = cc.crunch(cu, true);
+    expectEqual(result, EXPECTED_OVERWRITES, "number of files touched with overwrite");
+    \
+
+    if (errno == 0)
+        cout << "ALL TESTS PASSED!" << endl;
+    else
+        cout << errno << " TESTS FAILED" << endl;
+
+    delete ff;
+    delete cu;
+
+    // TESTS BELOW WILL GO AWAY SOON
+
+    String8 source2("ApiDemos/res");
+    String8 dest2("ApiDemos/res2");
+
+    FileFinder* sff = new SystemFileFinder();
+    CacheUpdater* scu = new SystemCacheUpdater();
+
+    CrunchCache scc(source2,dest2,sff);
+
+    scc.crunch(scu);
+}
\ No newline at end of file
diff --git a/tools/aapt/tests/FileFinder_test.cpp b/tools/aapt/tests/FileFinder_test.cpp
new file mode 100644
index 0000000..07bd665
--- /dev/null
+++ b/tools/aapt/tests/FileFinder_test.cpp
@@ -0,0 +1,101 @@
+//
+// Copyright 2011 The Android Open Source Project
+//
+#include <utils/Vector.h>
+#include <utils/KeyedVector.h>
+#include <iostream>
+#include <cassert>
+#include <utils/String8.h>
+#include <utility>
+
+#include "DirectoryWalker.h"
+#include "MockDirectoryWalker.h"
+#include "FileFinder.h"
+
+using namespace android;
+
+using std::pair;
+using std::cout;
+using std::endl;
+
+
+
+int main()
+{
+
+    cout << "\n\n STARTING FILE FINDER TESTS" << endl;
+    String8 path("ApiDemos");
+
+    // Storage to pass to findFiles()
+    KeyedVector<String8,time_t> testStorage;
+
+    // Mock Directory Walker initialization. First data, then sdw
+    Vector< pair<String8,time_t> > data;
+    data.push( pair<String8,time_t>(String8("hello.png"),3) );
+    data.push( pair<String8,time_t>(String8("world.PNG"),3) );
+    data.push( pair<String8,time_t>(String8("foo.pNg"),3) );
+    // Neither of these should be found
+    data.push( pair<String8,time_t>(String8("hello.jpg"),3) );
+    data.push( pair<String8,time_t>(String8(".hidden.png"),3));
+
+    DirectoryWalker* sdw = new StringDirectoryWalker(path,data);
+
+    // Extensions to look for
+    Vector<String8> exts;
+    exts.push(String8(".png"));
+
+    errno = 0;
+
+    // Make sure we get a valid mock directory walker
+    // Make sure we finish without errors
+    cout << "Checking DirectoryWalker...";
+    assert(sdw != NULL);
+    cout << "PASSED" << endl;
+
+    // Make sure we finish without errors
+    cout << "Running findFiles()...";
+    bool findStatus = FileFinder::findFiles(path,exts, testStorage, sdw);
+    assert(findStatus);
+    cout << "PASSED" << endl;
+
+    const size_t SIZE_EXPECTED = 3;
+    // Check to make sure we have the right number of things in our storage
+    cout << "Running size comparison: Size is " << testStorage.size() << ", ";
+    cout << "Expected " << SIZE_EXPECTED << "...";
+    if(testStorage.size() == SIZE_EXPECTED)
+        cout << "PASSED" << endl;
+    else {
+        cout << "FAILED" << endl;
+        errno++;
+    }
+
+    // Check to make sure that each of our found items has the right extension
+    cout << "Checking Returned Extensions...";
+    bool extsOkay = true;
+    String8 wrongExts;
+    for (size_t i = 0; i < SIZE_EXPECTED; ++i) {
+        String8 testExt(testStorage.keyAt(i).getPathExtension());
+        testExt.toLower();
+        if (testExt != ".png") {
+            wrongExts += testStorage.keyAt(i);
+            wrongExts += "\n";
+            extsOkay = false;
+        }
+    }
+    if (extsOkay)
+        cout << "PASSED" << endl;
+    else {
+        cout << "FAILED" << endl;
+        cout << "The following extensions didn't check out" << endl << wrongExts;
+    }
+
+    // Clean up
+    delete sdw;
+
+    if(errno == 0) {
+        cout << "ALL TESTS PASSED" << endl;
+    } else {
+        cout << errno << " TESTS FAILED" << endl;
+    }
+    return errno;
+}
\ No newline at end of file
diff --git a/tools/aapt/tests/MockCacheUpdater.h b/tools/aapt/tests/MockCacheUpdater.h
new file mode 100644
index 0000000..c7f4bd7
--- /dev/null
+++ b/tools/aapt/tests/MockCacheUpdater.h
@@ -0,0 +1,40 @@
+//
+// Copyright 2011 The Android Open Source Project
+//
+#ifndef MOCKCACHEUPDATER_H
+#define MOCKCACHEUPDATER_H
+
+#include <utils/String8.h>
+#include "CacheUpdater.h"
+
+using namespace android;
+
+class MockCacheUpdater : public CacheUpdater {
+public:
+
+    MockCacheUpdater()
+        : deleteCount(0), processCount(0) { };
+
+    // Make sure all the directories along this path exist
+    virtual void ensureDirectoriesExist(String8 path)
+    {
+        // Nothing to do
+    };
+
+    // Delete a file
+    virtual void deleteFile(String8 path) {
+        deleteCount++;
+    };
+
+    // Process an image from source out to dest
+    virtual void processImage(String8 source, String8 dest) {
+        processCount++;
+    };
+
+    // DATA MEMBERS
+    int deleteCount;
+    int processCount;
+private:
+};
+
+#endif // MOCKCACHEUPDATER_H
\ No newline at end of file
diff --git a/tools/aapt/tests/MockDirectoryWalker.h b/tools/aapt/tests/MockDirectoryWalker.h
new file mode 100644
index 0000000..5900cf3
--- /dev/null
+++ b/tools/aapt/tests/MockDirectoryWalker.h
@@ -0,0 +1,85 @@
+//
+// Copyright 2011 The Android Open Source Project
+//
+#ifndef MOCKDIRECTORYWALKER_H
+#define MOCKDIRECTORYWALKER_H
+
+#include <utils/Vector.h>
+#include <utils/String8.h>
+#include <utility>
+#include "DirectoryWalker.h"
+
+using namespace android;
+using std::pair;
+
+// String8 Directory Walker
+// This is an implementation of the Directory Walker abstraction that is built
+// for testing.
+// Instead of system calls it queries a private data structure for the directory
+// entries. It takes a path and a map of filenames and their modification times.
+// functions are inlined since they are short and simple
+
+class StringDirectoryWalker : public DirectoryWalker {
+public:
+    StringDirectoryWalker(String8& path, Vector< pair<String8,time_t> >& data)
+        :  mPos(0), mBasePath(path), mData(data) {
+        //fprintf(stdout,"StringDW built to mimic %s with %d files\n",
+        //       mBasePath.string());
+    };
+    // Default copy constructor, and destructor are fine
+
+    virtual bool openDir(String8 path) {
+        // If the user is trying to query the "directory" that this
+        // walker was initialized with, then return success. Else fail.
+        return path == mBasePath;
+    };
+    virtual bool openDir(const char* path) {
+        String8 p(path);
+        openDir(p);
+        return true;
+    };
+    // Advance to next entry in the Vector
+    virtual struct dirent* nextEntry() {
+        // Advance position and check to see if we're done
+        if (mPos >= mData.size())
+            return NULL;
+
+        // Place data in the entry descriptor. This class only returns files.
+        mEntry.d_type = DT_REG;
+        mEntry.d_ino = mPos;
+        // Copy chars from the string name to the entry name
+        size_t i = 0;
+        for (i; i < mData[mPos].first.size(); ++i)
+            mEntry.d_name[i] = mData[mPos].first[i];
+        mEntry.d_name[i] = '\0';
+
+        // Place data in stats
+        mStats.st_ino = mPos;
+        mStats.st_mtime = mData[mPos].second;
+
+        // Get ready to move to the next entry
+        mPos++;
+
+        return &mEntry;
+    };
+    // Get the stats for the current entry
+    virtual struct stat*   entryStats() {
+        return &mStats;
+    };
+    // Nothing to do in clean up
+    virtual void closeDir() {
+        // Nothing to do
+    };
+    virtual DirectoryWalker* clone() {
+        return new StringDirectoryWalker(*this);
+    };
+private:
+    // Current position in the Vector
+    size_t mPos;
+    // Base path
+    String8 mBasePath;
+    // Data to simulate a directory full of files.
+    Vector< pair<String8,time_t> > mData;
+};
+
+#endif // MOCKDIRECTORYWALKER_H
\ No newline at end of file
diff --git a/tools/aapt/tests/MockFileFinder.h b/tools/aapt/tests/MockFileFinder.h
new file mode 100644
index 0000000..da5ea4f
--- /dev/null
+++ b/tools/aapt/tests/MockFileFinder.h
@@ -0,0 +1,55 @@
+//
+// Copyright 2011 The Android Open Source Project
+//
+
+#ifndef MOCKFILEFINDER_H
+#define MOCKFILEFINDER_H
+
+#include <utils/Vector.h>
+#include <utils/KeyedVector.h>
+#include <utils/String8.h>
+
+#include "DirectoryWalker.h"
+
+using namespace android;
+
+class MockFileFinder : public FileFinder {
+public:
+    MockFileFinder (KeyedVector<String8, KeyedVector<String8,time_t> >& files)
+        : mFiles(files)
+    {
+        // Nothing left to do
+    };
+
+    /**
+     * findFiles implementation for the abstraction.
+     * PRECONDITIONS:
+     *  No checking is done, so there MUST be an entry in mFiles with
+     *  path matching basePath.
+     *
+     * POSTCONDITIONS:
+     *  fileStore is filled with a copy of the data in mFiles corresponding
+     *  to the basePath.
+     */
+
+    virtual bool findFiles(String8 basePath, Vector<String8>& extensions,
+                           KeyedVector<String8,time_t>& fileStore,
+                           DirectoryWalker* dw)
+    {
+        const KeyedVector<String8,time_t>* payload(&mFiles.valueFor(basePath));
+        // Since KeyedVector doesn't implement swap
+        // (who doesn't use swap??) we loop and add one at a time.
+        for (size_t i = 0; i < payload->size(); ++i) {
+            fileStore.add(payload->keyAt(i),payload->valueAt(i));
+        }
+        return true;
+    }
+
+private:
+    // Virtual mapping between "directories" and the "files" contained
+    // in them
+    KeyedVector<String8, KeyedVector<String8,time_t> > mFiles;
+};
+
+
+#endif // MOCKFILEFINDER_H
\ No newline at end of file
diff --git a/tools/layoutlib/.gitignore b/tools/layoutlib/.gitignore
index 0ec5000..c5e82d7 100644
--- a/tools/layoutlib/.gitignore
+++ b/tools/layoutlib/.gitignore
@@ -1,2 +1 @@
-bridge/bin
-create/bin
+bin
\ No newline at end of file
diff --git a/tools/layoutlib/README b/tools/layoutlib/README
new file mode 100644
index 0000000..0fea9bd
--- /dev/null
+++ b/tools/layoutlib/README
@@ -0,0 +1,4 @@
+Layoutlib is a custom version of the android View framework designed to run inside Eclipse.
+The goal of the library is to provide layout rendering in Eclipse that are very very close to their rendering on devices.
+
+None of the com.android.* or android.* classes in layoutlib run on devices.
\ No newline at end of file
diff --git a/tools/layoutlib/bridge/.classpath b/tools/layoutlib/bridge/.classpath
index 70140d8..9fb000e 100644
--- a/tools/layoutlib/bridge/.classpath
+++ b/tools/layoutlib/bridge/.classpath
@@ -1,12 +1,11 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <classpath>
 	<classpathentry excluding="org/kxml2/io/" kind="src" path="src"/>
-	<classpathentry kind="src" path="tests"/>
 	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
-	<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/3"/>
-	<classpathentry kind="var" path="ANDROID_SRC/prebuilt/common/layoutlib_api/layoutlib_api-prebuilt.jar"/>
-	<classpathentry kind="var" path="ANDROID_SRC/prebuilt/common/kxml2/kxml2-2.3.0.jar" sourcepath="/ANDROID_SRC/dalvik/libcore/xml/src/main/java"/>
-	<classpathentry kind="var" path="ANDROID_OUT_FRAMEWORK/layoutlib.jar" sourcepath="/ANDROID_SRC/frameworks/base/core/java"/>
-	<classpathentry kind="var" path="ANDROID_OUT_FRAMEWORK/ninepatch.jar" sourcepath="/ANDROID_SRC/development/tools/ninepatch/src"/>
+	<classpathentry kind="var" path="ANDROID_PLAT_SRC/prebuilt/common/layoutlib_api/layoutlib_api-prebuilt.jar"/>
+	<classpathentry kind="var" path="ANDROID_PLAT_SRC/prebuilt/common/kxml2/kxml2-2.3.0.jar" sourcepath="/ANDROID_PLAT_SRC/dalvik/libcore/xml/src/main/java"/>
+	<classpathentry kind="var" path="ANDROID_PLAT_SRC/out/host/common/obj/JAVA_LIBRARIES/temp_layoutlib_intermediates/javalib.jar" sourcepath="/ANDROID_PLAT_SRC/frameworks/base"/>
+	<classpathentry kind="var" path="ANDROID_PLAT_SRC/prebuilt/common/ninepatch/ninepatch-prebuilt.jar"/>
+	<classpathentry kind="var" path="ANDROID_PLAT_SRC/prebuilt/common/tools-common/tools-common-prebuilt.jar"/>
 	<classpathentry kind="output" path="bin"/>
 </classpath>
diff --git a/tools/layoutlib/bridge/Android.mk b/tools/layoutlib/bridge/Android.mk
index b7a602a..687a91f 100644
--- a/tools/layoutlib/bridge/Android.mk
+++ b/tools/layoutlib/bridge/Android.mk
@@ -17,15 +17,22 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES := $(call all-java-files-under,src)
+LOCAL_JAVA_RESOURCE_DIRS := resources
+
 
 LOCAL_JAVA_LIBRARIES := \
 	kxml2-2.3.0 \
 	layoutlib_api-prebuilt \
-	ninepatch
+	tools-common-prebuilt
 
-LOCAL_STATIC_JAVA_LIBRARIES := temp_layoutlib
+LOCAL_STATIC_JAVA_LIBRARIES := \
+	temp_layoutlib \
+	ninepatch-prebuilt
 
 LOCAL_MODULE := layoutlib
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
+# Build all sub-directories
+include $(call all-makefiles-under,$(LOCAL_PATH))
+
diff --git a/tools/layoutlib/bridge/resources/bars/hdpi/stat_sys_wifi_signal_4_fully.png b/tools/layoutlib/bridge/resources/bars/hdpi/stat_sys_wifi_signal_4_fully.png
new file mode 100644
index 0000000..bd44b52
--- /dev/null
+++ b/tools/layoutlib/bridge/resources/bars/hdpi/stat_sys_wifi_signal_4_fully.png
Binary files differ
diff --git a/tools/layoutlib/bridge/resources/bars/hdpi/status_bar_background.9.png b/tools/layoutlib/bridge/resources/bars/hdpi/status_bar_background.9.png
new file mode 100644
index 0000000..a4be298
--- /dev/null
+++ b/tools/layoutlib/bridge/resources/bars/hdpi/status_bar_background.9.png
Binary files differ
diff --git a/tools/layoutlib/bridge/resources/bars/mdpi/stat_sys_wifi_signal_4_fully.png b/tools/layoutlib/bridge/resources/bars/mdpi/stat_sys_wifi_signal_4_fully.png
new file mode 100644
index 0000000..c629387
--- /dev/null
+++ b/tools/layoutlib/bridge/resources/bars/mdpi/stat_sys_wifi_signal_4_fully.png
Binary files differ
diff --git a/tools/layoutlib/bridge/resources/bars/mdpi/status_bar_background.9.png b/tools/layoutlib/bridge/resources/bars/mdpi/status_bar_background.9.png
new file mode 100644
index 0000000..eb7c1a4
--- /dev/null
+++ b/tools/layoutlib/bridge/resources/bars/mdpi/status_bar_background.9.png
Binary files differ
diff --git a/tools/layoutlib/bridge/resources/bars/phone_system_bar.xml b/tools/layoutlib/bridge/resources/bars/phone_system_bar.xml
new file mode 100644
index 0000000..d3c492e
--- /dev/null
+++ b/tools/layoutlib/bridge/resources/bars/phone_system_bar.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8"?>
+<merge xmlns:android="http://schemas.android.com/apk/res/android">
+	<TextView
+			android:layout_width="wrap_content"
+			android:layout_height="wrap_content"
+			android:layout_weight="1"/>
+	<ImageView
+			android:layout_height="wrap_content"
+			android:layout_width="wrap_content"/>
+	<ImageView
+			android:layout_height="wrap_content"
+			android:layout_width="wrap_content"
+			android:layout_marginLeft="3dip"
+			android:layout_marginRight="5dip"/>
+</merge>
diff --git a/tools/layoutlib/bridge/resources/bars/title_bar.xml b/tools/layoutlib/bridge/resources/bars/title_bar.xml
new file mode 100644
index 0000000..76d78d9
--- /dev/null
+++ b/tools/layoutlib/bridge/resources/bars/title_bar.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<merge xmlns:android="http://schemas.android.com/apk/res/android">
+	<TextView
+			android:layout_width="wrap_content"
+			android:layout_height="wrap_content"/>
+</merge>
diff --git a/tools/layoutlib/bridge/src/android/content/res/Resources_Theme_Delegate.java b/tools/layoutlib/bridge/src/android/content/res/Resources_Theme_Delegate.java
new file mode 100644
index 0000000..413894b
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/content/res/Resources_Theme_Delegate.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.res;
+
+import com.android.layoutlib.bridge.impl.RenderSessionImpl;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import android.content.res.Resources.NotFoundException;
+import android.content.res.Resources.Theme;
+import android.util.AttributeSet;
+import android.util.TypedValue;
+
+/**
+ * Delegate used to provide new implementation of a select few methods of {@link Theme}
+ *
+ * Through the layoutlib_create tool, the original  methods of Theme have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ */
+public class Resources_Theme_Delegate {
+
+    @LayoutlibDelegate
+    /*package*/ static TypedArray obtainStyledAttributes(
+            Resources thisResources, Theme thisTheme,
+            int[] attrs) {
+        return RenderSessionImpl.getCurrentContext().obtainStyledAttributes(attrs);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static TypedArray obtainStyledAttributes(
+            Resources thisResources, Theme thisTheme,
+            int resid, int[] attrs)
+            throws NotFoundException {
+        return RenderSessionImpl.getCurrentContext().obtainStyledAttributes(resid, attrs);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static TypedArray obtainStyledAttributes(
+            Resources thisResources, Theme thisTheme,
+            AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes) {
+        return RenderSessionImpl.getCurrentContext().obtainStyledAttributes(
+                set, attrs, defStyleAttr, defStyleRes);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean resolveAttribute(
+            Resources thisResources, Theme thisTheme,
+            int resid, TypedValue outValue,
+            boolean resolveRefs) {
+        return RenderSessionImpl.getCurrentContext().resolveThemeAttribute(
+                resid, outValue, resolveRefs);
+    }
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/AvoidXfermode_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/AvoidXfermode_Delegate.java
new file mode 100644
index 0000000..a50a2bd
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/AvoidXfermode_Delegate.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import java.awt.Composite;
+
+/**
+ * Delegate implementing the native methods of android.graphics.AvoidXfermode
+ *
+ * Through the layoutlib_create tool, the original native methods of AvoidXfermode have been
+ * replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original AvoidXfermode class.
+ *
+ * Because this extends {@link Xfermode_Delegate}, there's no need to use a
+ * {@link DelegateManager}, as all the PathEffect classes will be added to the manager owned by
+ * {@link Xfermode_Delegate}.
+ *
+ */
+public class AvoidXfermode_Delegate extends Xfermode_Delegate {
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public Composite getComposite(int alpha) {
+        // FIXME
+        return null;
+    }
+
+    @Override
+    public boolean isSupported() {
+        return false;
+    }
+
+    @Override
+    public String getSupportMessage() {
+        return "Avoid Xfermodes are not supported in Layout Preview mode.";
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeCreate(int opColor, int tolerance, int nativeMode) {
+        AvoidXfermode_Delegate newDelegate = new AvoidXfermode_Delegate();
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    // ---- Private delegate/helper methods ----
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Bitmap.java b/tools/layoutlib/bridge/src/android/graphics/Bitmap.java
deleted file mode 100644
index 35f022e..0000000
--- a/tools/layoutlib/bridge/src/android/graphics/Bitmap.java
+++ /dev/null
@@ -1,278 +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.graphics;
-
-
-import java.awt.image.BufferedImage;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-
-import javax.imageio.ImageIO;
-
-public final class Bitmap extends _Original_Bitmap {
-
-    private BufferedImage mImage;
-
-    public Bitmap(File input) throws IOException {
-        super(1, true, null, -1);
-
-        mImage = ImageIO.read(input);
-    }
-
-    public Bitmap(InputStream is) throws IOException {
-        super(1, true, null, -1);
-
-        mImage = ImageIO.read(is);
-    }
-
-    Bitmap(BufferedImage image) {
-        super(1, true, null, -1);
-        mImage = image;
-    }
-
-    public BufferedImage getImage() {
-        return mImage;
-    }
-
-    // ----- overriden methods
-
-    public enum Config {
-        // these native values must match up with the enum in SkBitmap.h
-        ALPHA_8     (2),
-        RGB_565     (4),
-        ARGB_4444   (5),
-        ARGB_8888   (6);
-
-        Config(int ni) {
-            this.nativeInt = ni;
-        }
-        final int nativeInt;
-
-        /* package */ static Config nativeToConfig(int ni) {
-            return sConfigs[ni];
-        }
-
-        private static Config sConfigs[] = {
-            null, null, ALPHA_8, null, RGB_565, ARGB_4444, ARGB_8888
-        };
-    }
-
-    @Override
-    public int getWidth() {
-        return mImage.getWidth();
-    }
-
-    @Override
-    public int getHeight() {
-        return mImage.getHeight();
-    }
-
-    /**
-     * Returns an immutable bitmap from the source bitmap. The new bitmap may
-     * be the same object as source, or a copy may have been made.
-     */
-    public static Bitmap createBitmap(Bitmap src) {
-        return createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), null, false);
-    }
-
-    /**
-     * Returns an immutable bitmap from the specified subset of the source
-     * bitmap. The new bitmap may be the same object as source, or a copy may
-     * have been made.
-     *
-     * @param source   The bitmap we are subsetting
-     * @param x        The x coordinate of the first pixel in source
-     * @param y        The y coordinate of the first pixel in source
-     * @param width    The number of pixels in each row
-     * @param height   The number of rows
-     */
-    public static Bitmap createBitmap(Bitmap source, int x, int y,
-                                      int width, int height) {
-        return new Bitmap(source.mImage.getSubimage(x, y, width, height));
-    }
-
-    /**
-     * Returns an immutable bitmap from subset of the source bitmap,
-     * transformed by the optional matrix.
-     *
-     * @param source   The bitmap we are subsetting
-     * @param x        The x coordinate of the first pixel in source
-     * @param y        The y coordinate of the first pixel in source
-     * @param width    The number of pixels in each row
-     * @param height   The number of rows
-     * @param m        Option matrix to be applied to the pixels
-     * @param filter   true if the source should be filtered.
-     *                   Only applies if the matrix contains more than just
-     *                   translation.
-     * @return A bitmap that represents the specified subset of source
-     * @throws IllegalArgumentException if the x, y, width, height values are
-     *         outside of the dimensions of the source bitmap.
-     */
-    public static Bitmap createBitmap(Bitmap source, int x, int y, int width,
-                                      int height, Matrix m, boolean filter) {
-        checkXYSign(x, y);
-        checkWidthHeight(width, height);
-        if (x + width > source.getWidth()) {
-            throw new IllegalArgumentException(
-                    "x + width must be <= bitmap.width()");
-        }
-        if (y + height > source.getHeight()) {
-            throw new IllegalArgumentException(
-                    "y + height must be <= bitmap.height()");
-        }
-
-        // check if we can just return our argument unchanged
-        if (!source.isMutable() && x == 0 && y == 0
-                && width == source.getWidth() && height == source.getHeight()
-                && (m == null || m.isIdentity())) {
-            return source;
-        }
-
-        if (m == null || m.isIdentity()) {
-            return new Bitmap(source.mImage.getSubimage(x, y, width, height));
-        }
-
-        int neww = width;
-        int newh = height;
-        Paint paint;
-
-        Rect srcR = new Rect(x, y, x + width, y + height);
-        RectF dstR = new RectF(0, 0, width, height);
-
-        /*  the dst should have alpha if the src does, or if our matrix
-            doesn't preserve rectness
-        */
-        boolean hasAlpha = source.hasAlpha() || !m.rectStaysRect();
-        RectF deviceR = new RectF();
-        m.mapRect(deviceR, dstR);
-        neww = Math.round(deviceR.width());
-        newh = Math.round(deviceR.height());
-
-        Canvas canvas = new Canvas(neww, newh);
-
-        canvas.translate(-deviceR.left, -deviceR.top);
-        canvas.concat(m);
-        paint = new Paint();
-        paint.setFilterBitmap(filter);
-        if (!m.rectStaysRect()) {
-            paint.setAntiAlias(true);
-        }
-
-        canvas.drawBitmap(source, srcR, dstR, paint);
-
-        return new Bitmap(canvas.getImage());
-    }
-
-    /**
-     * Returns a mutable bitmap with the specified width and height.
-     *
-     * @param width    The width of the bitmap
-     * @param height   The height of the bitmap
-     * @param config   The bitmap config to create.
-     * @throws IllegalArgumentException if the width or height are <= 0
-     */
-    public static Bitmap createBitmap(int width, int height, Config config) {
-        return new Bitmap(new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB));
-    }
-
-    /**
-     * Returns a immutable bitmap with the specified width and height, with each
-     * pixel value set to the corresponding value in the colors array.
-     *
-     * @param colors   Array of {@link Color} used to initialize the pixels.
-     * @param offset   Number of values to skip before the first color in the
-     *                 array of colors.
-     * @param stride   Number of colors in the array between rows (must be >=
-     *                 width or <= -width).
-     * @param width    The width of the bitmap
-     * @param height   The height of the bitmap
-     * @param config   The bitmap config to create. If the config does not
-     *                 support per-pixel alpha (e.g. RGB_565), then the alpha
-     *                 bytes in the colors[] will be ignored (assumed to be FF)
-     * @throws IllegalArgumentException if the width or height are <= 0, or if
-     *         the color array's length is less than the number of pixels.
-     */
-    public static Bitmap createBitmap(int colors[], int offset, int stride,
-                                      int width, int height, Config config) {
-        checkWidthHeight(width, height);
-        if (Math.abs(stride) < width) {
-            throw new IllegalArgumentException("abs(stride) must be >= width");
-        }
-        int lastScanline = offset + (height - 1) * stride;
-        int length = colors.length;
-        if (offset < 0 || (offset + width > length)
-            || lastScanline < 0
-            || (lastScanline + width > length)) {
-            throw new ArrayIndexOutOfBoundsException();
-        }
-
-        // TODO: create an immutable bitmap...
-        throw new UnsupportedOperationException();
-    }
-
-    /**
-     * Returns a immutable bitmap with the specified width and height, with each
-     * pixel value set to the corresponding value in the colors array.
-     *
-     * @param colors   Array of {@link Color} used to initialize the pixels.
-     *                 This array must be at least as large as width * height.
-     * @param width    The width of the bitmap
-     * @param height   The height of the bitmap
-     * @param config   The bitmap config to create. If the config does not
-     *                 support per-pixel alpha (e.g. RGB_565), then the alpha
-     *                 bytes in the colors[] will be ignored (assumed to be FF)
-     * @throws IllegalArgumentException if the width or height are <= 0, or if
-     *         the color array's length is less than the number of pixels.
-     */
-    public static Bitmap createBitmap(int colors[], int width, int height,
-                                      Config config) {
-        return createBitmap(colors, 0, width, width, height, config);
-    }
-
-    public static Bitmap createScaledBitmap(Bitmap src, int dstWidth,
-            int dstHeight, boolean filter) {
-        Matrix m;
-        synchronized (Bitmap.class) {
-            // small pool of just 1 matrix
-            m = sScaleMatrix;
-            sScaleMatrix = null;
-        }
-
-        if (m == null) {
-            m = new Matrix();
-        }
-
-        final int width = src.getWidth();
-        final int height = src.getHeight();
-        final float sx = dstWidth  / (float)width;
-        final float sy = dstHeight / (float)height;
-        m.setScale(sx, sy);
-        Bitmap b = Bitmap.createBitmap(src, 0, 0, width, height, m, filter);
-
-        synchronized (Bitmap.class) {
-            // do we need to check for null? why not just assign everytime?
-            if (sScaleMatrix == null) {
-                sScaleMatrix = m;
-            }
-        }
-
-        return b;
-    }
-
-
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/BitmapFactory.java b/tools/layoutlib/bridge/src/android/graphics/BitmapFactory.java
deleted file mode 100644
index e978fe8..0000000
--- a/tools/layoutlib/bridge/src/android/graphics/BitmapFactory.java
+++ /dev/null
@@ -1,566 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import android.content.res.AssetManager;
-import android.content.res.Resources;
-import android.util.DisplayMetrics;
-import android.util.TypedValue;
-
-import java.io.BufferedInputStream;
-import java.io.FileDescriptor;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * Creates Bitmap objects from various sources, including files, streams,
- * and byte-arrays.
- */
-public class BitmapFactory {
-    public static class Options {
-        /**
-         * Create a default Options object, which if left unchanged will give
-         * the same result from the decoder as if null were passed.
-         */
-        public Options() {
-            inDither = true;
-            inScaled = true;
-        }
-
-        /**
-         * If set to true, the decoder will return null (no bitmap), but
-         * the out... fields will still be set, allowing the caller to query
-         * the bitmap without having to allocate the memory for its pixels.
-         */
-        public boolean inJustDecodeBounds;
-
-        /**
-         * If set to a value > 1, requests the decoder to subsample the original
-         * image, returning a smaller image to save memory. The sample size is
-         * the number of pixels in either dimension that correspond to a single
-         * pixel in the decoded bitmap. For example, inSampleSize == 4 returns
-         * an image that is 1/4 the width/height of the original, and 1/16 the
-         * number of pixels. Any value <= 1 is treated the same as 1. Note: the
-         * decoder will try to fulfill this request, but the resulting bitmap
-         * may have different dimensions that precisely what has been requested.
-         * Also, powers of 2 are often faster/easier for the decoder to honor.
-         */
-        public int inSampleSize;
-
-        /**
-         * If this is non-null, the decoder will try to decode into this
-         * internal configuration. If it is null, or the request cannot be met,
-         * the decoder will try to pick the best matching config based on the
-         * system's screen depth, and characteristics of the original image such
-         * as if it has per-pixel alpha (requiring a config that also does).
-         */
-        public Bitmap.Config inPreferredConfig;
-
-        /**
-         * If dither is true, the decoder will attempt to dither the decoded
-         * image.
-         */
-        public boolean inDither;
-
-        /**
-         * The pixel density to use for the bitmap.  This will always result
-         * in the returned bitmap having a density set for it (see
-         * {@link Bitmap#setDensity(int) Bitmap.setDensity(int)).  In addition,
-         * if {@link #inScaled} is set (which it is by default} and this
-         * density does not match {@link #inTargetDensity}, then the bitmap
-         * will be scaled to the target density before being returned.
-         *
-         * <p>If this is 0,
-         * {@link BitmapFactory#decodeResource(Resources, int)},
-         * {@link BitmapFactory#decodeResource(Resources, int, android.graphics.BitmapFactory.Options)},
-         * and {@link BitmapFactory#decodeResourceStream}
-         * will fill in the density associated with the resource.  The other
-         * functions will leave it as-is and no density will be applied.
-         *
-         * @see #inTargetDensity
-         * @see #inScreenDensity
-         * @see #inScaled
-         * @see Bitmap#setDensity(int)
-         * @see android.util.DisplayMetrics#densityDpi
-         */
-        public int inDensity;
-
-        /**
-         * The pixel density of the destination this bitmap will be drawn to.
-         * This is used in conjunction with {@link #inDensity} and
-         * {@link #inScaled} to determine if and how to scale the bitmap before
-         * returning it.
-         *
-         * <p>If this is 0,
-         * {@link BitmapFactory#decodeResource(Resources, int)},
-         * {@link BitmapFactory#decodeResource(Resources, int, android.graphics.BitmapFactory.Options)},
-         * and {@link BitmapFactory#decodeResourceStream}
-         * will fill in the density associated the Resources object's
-         * DisplayMetrics.  The other
-         * functions will leave it as-is and no scaling for density will be
-         * performed.
-         *
-         * @see #inDensity
-         * @see #inScreenDensity
-         * @see #inScaled
-         * @see android.util.DisplayMetrics#densityDpi
-         */
-        public int inTargetDensity;
-
-        /**
-         * The pixel density of the actual screen that is being used.  This is
-         * purely for applications running in density compatibility code, where
-         * {@link #inTargetDensity} is actually the density the application
-         * sees rather than the real screen density.
-         *
-         * <p>By setting this, you
-         * allow the loading code to avoid scaling a bitmap that is currently
-         * in the screen density up/down to the compatibility density.  Instead,
-         * if {@link #inDensity} is the same as {@link #inScreenDensity}, the
-         * bitmap will be left as-is.  Anything using the resulting bitmap
-         * must also used {@link Bitmap#getScaledWidth(int)
-         * Bitmap.getScaledWidth} and {@link Bitmap#getScaledHeight
-         * Bitmap.getScaledHeight} to account for any different between the
-         * bitmap's density and the target's density.
-         *
-         * <p>This is never set automatically for the caller by
-         * {@link BitmapFactory} itself.  It must be explicitly set, since the
-         * caller must deal with the resulting bitmap in a density-aware way.
-         *
-         * @see #inDensity
-         * @see #inTargetDensity
-         * @see #inScaled
-         * @see android.util.DisplayMetrics#densityDpi
-         */
-        public int inScreenDensity;
-
-        /**
-         * When this flag is set, if {@link #inDensity} and
-         * {@link #inTargetDensity} are not 0, the
-         * bitmap will be scaled to match {@link #inTargetDensity} when loaded,
-         * rather than relying on the graphics system scaling it each time it
-         * is drawn to a Canvas.
-         *
-         * <p>This flag is turned on by default and should be turned off if you need
-         * a non-scaled version of the bitmap.  Nine-patch bitmaps ignore this
-         * flag and are always scaled.
-         */
-        public boolean inScaled;
-
-        /**
-         * If this is set to true, then the resulting bitmap will allocate its
-         * pixels such that they can be purged if the system needs to reclaim
-         * memory. In that instance, when the pixels need to be accessed again
-         * (e.g. the bitmap is drawn, getPixels() is called), they will be
-         * automatically re-decoded.
-         *
-         * For the re-decode to happen, the bitmap must have access to the
-         * encoded data, either by sharing a reference to the input
-         * or by making a copy of it. This distinction is controlled by
-         * inInputShareable. If this is true, then the bitmap may keep a shallow
-         * reference to the input. If this is false, then the bitmap will
-         * explicitly make a copy of the input data, and keep that. Even if
-         * sharing is allowed, the implementation may still decide to make a
-         * deep copy of the input data.
-         */
-        public boolean inPurgeable;
-
-        /**
-         * This field works in conjuction with inPurgeable. If inPurgeable is
-         * false, then this field is ignored. If inPurgeable is true, then this
-         * field determines whether the bitmap can share a reference to the
-         * input data (inputstream, array, etc.) or if it must make a deep copy.
-         */
-        public boolean inInputShareable;
-
-        /**
-         * Normally bitmap allocations count against the dalvik heap, which
-         * means they help trigger GCs when a lot have been allocated. However,
-         * in rare cases, the caller may want to allocate the bitmap outside of
-         * that heap. To request that, set inNativeAlloc to true. In these
-         * rare instances, it is solely up to the caller to ensure that OOM is
-         * managed explicitly by calling bitmap.recycle() as soon as such a
-         * bitmap is no longer needed.
-         *
-         * @hide pending API council approval
-         */
-        public boolean inNativeAlloc;
-
-        /**
-         * The resulting width of the bitmap, set independent of the state of
-         * inJustDecodeBounds. However, if there is an error trying to decode,
-         * outWidth will be set to -1.
-         */
-        public int outWidth;
-
-        /**
-         * The resulting height of the bitmap, set independent of the state of
-         * inJustDecodeBounds. However, if there is an error trying to decode,
-         * outHeight will be set to -1.
-         */
-        public int outHeight;
-
-        /**
-         * If known, this string is set to the mimetype of the decoded image.
-         * If not know, or there is an error, it is set to null.
-         */
-        public String outMimeType;
-
-        /**
-         * Temp storage to use for decoding.  Suggest 16K or so.
-         */
-        public byte[] inTempStorage;
-
-        private native void requestCancel();
-
-        /**
-         * Flag to indicate that cancel has been called on this object.  This
-         * is useful if there's an intermediary that wants to first decode the
-         * bounds and then decode the image.  In that case the intermediary
-         * can check, inbetween the bounds decode and the image decode, to see
-         * if the operation is canceled.
-         */
-        public boolean mCancel;
-
-        /**
-         *  This can be called from another thread while this options object is
-         *  inside a decode... call. Calling this will notify the decoder that
-         *  it should cancel its operation. This is not guaranteed to cancel
-         *  the decode, but if it does, the decoder... operation will return
-         *  null, or if inJustDecodeBounds is true, will set outWidth/outHeight
-         *  to -1
-         */
-        public void requestCancelDecode() {
-            mCancel = true;
-            requestCancel();
-        }
-    }
-
-    /**
-     * Decode a file path into a bitmap. If the specified file name is null,
-     * or cannot be decoded into a bitmap, the function returns null.
-     *
-     * @param pathName complete path name for the file to be decoded.
-     * @param opts null-ok; Options that control downsampling and whether the
-     *             image should be completely decoded, or just is size returned.
-     * @return The decoded bitmap, or null if the image data could not be
-     *         decoded, or, if opts is non-null, if opts requested only the
-     *         size be returned (in opts.outWidth and opts.outHeight)
-     */
-    public static Bitmap decodeFile(String pathName, Options opts) {
-        Bitmap bm = null;
-        InputStream stream = null;
-        try {
-            stream = new FileInputStream(pathName);
-            bm = decodeStream(stream, null, opts);
-        } catch (Exception e) {
-            /*  do nothing.
-                If the exception happened on open, bm will be null.
-            */
-        } finally {
-            if (stream != null) {
-                try {
-                    stream.close();
-                } catch (IOException e) {
-                    // do nothing here
-                }
-            }
-        }
-        return bm;
-    }
-
-    /**
-     * Decode a file path into a bitmap. If the specified file name is null,
-     * or cannot be decoded into a bitmap, the function returns null.
-     *
-     * @param pathName complete path name for the file to be decoded.
-     * @return the resulting decoded bitmap, or null if it could not be decoded.
-     */
-    public static Bitmap decodeFile(String pathName) {
-        return decodeFile(pathName, null);
-    }
-
-    /**
-     * Decode a new Bitmap from an InputStream. This InputStream was obtained from
-     * resources, which we pass to be able to scale the bitmap accordingly.
-     */
-    public static Bitmap decodeResourceStream(Resources res, TypedValue value,
-            InputStream is, Rect pad, Options opts) {
-
-        if (opts == null) {
-            opts = new Options();
-        }
-
-        if (opts.inDensity == 0 && value != null) {
-            final int density = value.density;
-            if (density == TypedValue.DENSITY_DEFAULT) {
-                opts.inDensity = DisplayMetrics.DENSITY_DEFAULT;
-            } else if (density != TypedValue.DENSITY_NONE) {
-                opts.inDensity = density;
-            }
-        }
-
-        if (opts.inTargetDensity == 0 && res != null) {
-            opts.inTargetDensity = res.getDisplayMetrics().densityDpi;
-        }
-
-        return decodeStream(is, pad, opts);
-    }
-
-    /**
-     * Synonym for opening the given resource and calling
-     * {@link #decodeResourceStream}.
-     *
-     * @param res   The resources object containing the image data
-     * @param id The resource id of the image data
-     * @param opts null-ok; Options that control downsampling and whether the
-     *             image should be completely decoded, or just is size returned.
-     * @return The decoded bitmap, or null if the image data could not be
-     *         decoded, or, if opts is non-null, if opts requested only the
-     *         size be returned (in opts.outWidth and opts.outHeight)
-     */
-    public static Bitmap decodeResource(Resources res, int id, Options opts) {
-        Bitmap bm = null;
-        InputStream is = null;
-
-        try {
-            final TypedValue value = new TypedValue();
-            is = res.openRawResource(id, value);
-
-            bm = decodeResourceStream(res, value, is, null, opts);
-        } catch (Exception e) {
-            /*  do nothing.
-                If the exception happened on open, bm will be null.
-                If it happened on close, bm is still valid.
-            */
-        } finally {
-            try {
-                if (is != null) is.close();
-            } catch (IOException e) {
-                // Ignore
-            }
-        }
-
-        return bm;
-    }
-
-    /**
-     * Synonym for {@link #decodeResource(Resources, int, android.graphics.BitmapFactory.Options)}
-     * will null Options.
-     *
-     * @param res The resources object containing the image data
-     * @param id The resource id of the image data
-     * @return The decoded bitmap, or null if the image could not be decode.
-     */
-    public static Bitmap decodeResource(Resources res, int id) {
-        return decodeResource(res, id, null);
-    }
-
-    /**
-     * Decode an immutable bitmap from the specified byte array.
-     *
-     * @param data byte array of compressed image data
-     * @param offset offset into imageData for where the decoder should begin
-     *               parsing.
-     * @param length the number of bytes, beginning at offset, to parse
-     * @param opts null-ok; Options that control downsampling and whether the
-     *             image should be completely decoded, or just is size returned.
-     * @return The decoded bitmap, or null if the image data could not be
-     *         decoded, or, if opts is non-null, if opts requested only the
-     *         size be returned (in opts.outWidth and opts.outHeight)
-     */
-    public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts) {
-        if ((offset | length) < 0 || data.length < offset + length) {
-            throw new ArrayIndexOutOfBoundsException();
-        }
-
-        // FIXME: implement as needed, but it's unlikely that this is needed in the context of the bridge.
-        return null;
-        //return nativeDecodeByteArray(data, offset, length, opts);
-    }
-
-    /**
-     * Decode an immutable bitmap from the specified byte array.
-     *
-     * @param data byte array of compressed image data
-     * @param offset offset into imageData for where the decoder should begin
-     *               parsing.
-     * @param length the number of bytes, beginning at offset, to parse
-     * @return The decoded bitmap, or null if the image could not be decode.
-     */
-    public static Bitmap decodeByteArray(byte[] data, int offset, int length) {
-        return decodeByteArray(data, offset, length, null);
-    }
-
-    /**
-     * Decode an input stream into a bitmap. If the input stream is null, or
-     * cannot be used to decode a bitmap, the function returns null.
-     * The stream's position will be where ever it was after the encoded data
-     * was read.
-     *
-     * @param is The input stream that holds the raw data to be decoded into a
-     *           bitmap.
-     * @param outPadding If not null, return the padding rect for the bitmap if
-     *                   it exists, otherwise set padding to [-1,-1,-1,-1]. If
-     *                   no bitmap is returned (null) then padding is
-     *                   unchanged.
-     * @param opts null-ok; Options that control downsampling and whether the
-     *             image should be completely decoded, or just is size returned.
-     * @return The decoded bitmap, or null if the image data could not be
-     *         decoded, or, if opts is non-null, if opts requested only the
-     *         size be returned (in opts.outWidth and opts.outHeight)
-     */
-    public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts) {
-        // we don't throw in this case, thus allowing the caller to only check
-        // the cache, and not force the image to be decoded.
-        if (is == null) {
-            return null;
-        }
-
-        // we need mark/reset to work properly
-
-        if (!is.markSupported()) {
-            is = new BufferedInputStream(is, 16 * 1024);
-        }
-
-        // so we can call reset() if a given codec gives up after reading up to
-        // this many bytes. FIXME: need to find out from the codecs what this
-        // value should be.
-        is.mark(1024);
-
-        Bitmap  bm;
-
-        if (is instanceof AssetManager.AssetInputStream) {
-            // FIXME: log this.
-            return null;
-        } else {
-            // pass some temp storage down to the native code. 1024 is made up,
-            // but should be large enough to avoid too many small calls back
-            // into is.read(...) This number is not related to the value passed
-            // to mark(...) above.
-            try {
-                bm = new Bitmap(is);
-            } catch (IOException e) {
-                return null;
-            }
-        }
-
-        return finishDecode(bm, outPadding, opts);
-    }
-
-    private static Bitmap finishDecode(Bitmap bm, Rect outPadding, Options opts) {
-        if (bm == null || opts == null) {
-            return bm;
-        }
-
-        final int density = opts.inDensity;
-        if (density == 0) {
-            return bm;
-        }
-
-        bm.setDensity(density);
-        final int targetDensity = opts.inTargetDensity;
-        if (targetDensity == 0 || density == targetDensity
-                || density == opts.inScreenDensity) {
-            return bm;
-        }
-
-        byte[] np = bm.getNinePatchChunk();
-        final boolean isNinePatch = false; //np != null && NinePatch.isNinePatchChunk(np);
-        if (opts.inScaled || isNinePatch) {
-            float scale = targetDensity / (float)density;
-            // TODO: This is very inefficient and should be done in native by Skia
-            final Bitmap oldBitmap = bm;
-            bm = Bitmap.createScaledBitmap(oldBitmap, (int) (bm.getWidth() * scale + 0.5f),
-                    (int) (bm.getHeight() * scale + 0.5f), true);
-            oldBitmap.recycle();
-
-            if (isNinePatch) {
-                //np = nativeScaleNinePatch(np, scale, outPadding);
-                bm.setNinePatchChunk(np);
-            }
-            bm.setDensity(targetDensity);
-        }
-
-        return bm;
-    }
-
-    /**
-     * Decode an input stream into a bitmap. If the input stream is null, or
-     * cannot be used to decode a bitmap, the function returns null.
-     * The stream's position will be where ever it was after the encoded data
-     * was read.
-     *
-     * @param is The input stream that holds the raw data to be decoded into a
-     *           bitmap.
-     * @return The decoded bitmap, or null if the image data could not be
-     *         decoded, or, if opts is non-null, if opts requested only the
-     *         size be returned (in opts.outWidth and opts.outHeight)
-     */
-    public static Bitmap decodeStream(InputStream is) {
-        return decodeStream(is, null, null);
-    }
-
-    /**
-     * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded
-     * return null. The position within the descriptor will not be changed when
-     * this returns, so the descriptor can be used again as-is.
-     *
-     * @param fd The file descriptor containing the bitmap data to decode
-     * @param outPadding If not null, return the padding rect for the bitmap if
-     *                   it exists, otherwise set padding to [-1,-1,-1,-1]. If
-     *                   no bitmap is returned (null) then padding is
-     *                   unchanged.
-     * @param opts null-ok; Options that control downsampling and whether the
-     *             image should be completely decoded, or just is size returned.
-     * @return the decoded bitmap, or null
-     */
-    public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) {
-        return null;
-
-        /* FIXME: implement as needed
-        try {
-            if (MemoryFile.isMemoryFile(fd)) {
-                int mappedlength = MemoryFile.getMappedSize(fd);
-                MemoryFile file = new MemoryFile(fd, mappedlength, "r");
-                InputStream is = file.getInputStream();
-                Bitmap bm = decodeStream(is, outPadding, opts);
-                return finishDecode(bm, outPadding, opts);
-            }
-        } catch (IOException ex) {
-            // invalid filedescriptor, no need to call nativeDecodeFileDescriptor()
-            return null;
-        }
-        //Bitmap bm = nativeDecodeFileDescriptor(fd, outPadding, opts);
-        //return finishDecode(bm, outPadding, opts);
-        */
-    }
-
-    /**
-     * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded
-     * return null. The position within the descriptor will not be changed when
-     * this returns, so the descriptor can be used again as is.
-     *
-     * @param fd The file descriptor containing the bitmap data to decode
-     * @return the decoded bitmap, or null
-     */
-    public static Bitmap decodeFileDescriptor(FileDescriptor fd) {
-        return decodeFileDescriptor(fd, null, null);
-    }
-}
-
diff --git a/tools/layoutlib/bridge/src/android/graphics/BitmapFactory_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/BitmapFactory_Delegate.java
new file mode 100644
index 0000000..9c86e80
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/BitmapFactory_Delegate.java
@@ -0,0 +1,159 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.graphics;
+
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.android.BridgeResources.NinePatchInputStream;
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.ninepatch.NinePatchChunk;
+import com.android.resources.Density;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import android.graphics.BitmapFactory.Options;
+
+import java.io.FileDescriptor;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Delegate implementing the native methods of android.graphics.BitmapFactory
+ *
+ * Through the layoutlib_create tool, the original native methods of BitmapFactory have been
+ * replaced by calls to methods of the same name in this delegate class.
+ *
+ * Because it's a stateless class to start with, there's no need to keep a {@link DelegateManager}
+ * around to map int to instance of the delegate.
+ *
+ */
+/*package*/ class BitmapFactory_Delegate {
+
+    // ------ Java delegates ------
+
+    @LayoutlibDelegate
+    /*package*/ static Bitmap finishDecode(Bitmap bm, Rect outPadding, Options opts) {
+        if (bm == null || opts == null) {
+            return bm;
+        }
+
+        final int density = opts.inDensity;
+        if (density == 0) {
+            return bm;
+        }
+
+        bm.setDensity(density);
+        final int targetDensity = opts.inTargetDensity;
+        if (targetDensity == 0 || density == targetDensity || density == opts.inScreenDensity) {
+            return bm;
+        }
+
+        byte[] np = bm.getNinePatchChunk();
+        final boolean isNinePatch = np != null && NinePatch.isNinePatchChunk(np);
+        // DELEGATE CHANGE: never scale 9-patch
+        if (opts.inScaled && isNinePatch == false) {
+            float scale = targetDensity / (float)density;
+            // TODO: This is very inefficient and should be done in native by Skia
+            final Bitmap oldBitmap = bm;
+            bm = Bitmap.createScaledBitmap(oldBitmap, (int) (bm.getWidth() * scale + 0.5f),
+                    (int) (bm.getHeight() * scale + 0.5f), true);
+            oldBitmap.recycle();
+
+            if (isNinePatch) {
+                np = nativeScaleNinePatch(np, scale, outPadding);
+                bm.setNinePatchChunk(np);
+            }
+            bm.setDensity(targetDensity);
+        }
+
+        return bm;
+    }
+
+
+    // ------ Native Delegates ------
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeSetDefaultConfig(int nativeConfig) {
+        // pass
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static Bitmap nativeDecodeStream(InputStream is, byte[] storage,
+            Rect padding, Options opts) {
+        Bitmap bm = null;
+
+        Density density = Density.MEDIUM;
+        if (opts != null) {
+            density = Density.getEnum(opts.inDensity);
+        }
+
+        try {
+            if (is instanceof NinePatchInputStream) {
+                NinePatchInputStream npis = (NinePatchInputStream) is;
+                npis.disableFakeMarkSupport();
+
+                // load the bitmap as a nine patch
+                com.android.ninepatch.NinePatch ninePatch = com.android.ninepatch.NinePatch.load(
+                        npis, true /*is9Patch*/, false /*convert*/);
+
+                // get the bitmap and chunk objects.
+                bm = Bitmap_Delegate.createBitmap(ninePatch.getImage(), true /*isMutable*/,
+                        density);
+                NinePatchChunk chunk = ninePatch.getChunk();
+
+                // put the chunk in the bitmap
+                bm.setNinePatchChunk(NinePatch_Delegate.serialize(chunk));
+
+                // read the padding
+                int[] paddingarray = chunk.getPadding();
+                padding.left = paddingarray[0];
+                padding.top = paddingarray[1];
+                padding.right = paddingarray[2];
+                padding.bottom = paddingarray[3];
+            } else {
+                // load the bitmap directly.
+                bm = Bitmap_Delegate.createBitmap(is, true, density);
+            }
+        } catch (IOException e) {
+            Bridge.getLog().error(null,"Failed to load image" , e, null);
+        }
+
+        return bm;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static Bitmap nativeDecodeFileDescriptor(FileDescriptor fd,
+            Rect padding, Options opts) {
+        return null;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static Bitmap nativeDecodeAsset(int asset, Rect padding, Options opts) {
+        return null;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static Bitmap nativeDecodeByteArray(byte[] data, int offset,
+            int length, Options opts) {
+        return null;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static byte[] nativeScaleNinePatch(byte[] chunk, float scale, Rect pad) {
+        // don't scale for now. This should not be called anyway since we re-implement
+        // BitmapFactory.finishDecode();
+        return chunk;
+    }
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/BitmapShader.java b/tools/layoutlib/bridge/src/android/graphics/BitmapShader.java
deleted file mode 100644
index ad3974c..0000000
--- a/tools/layoutlib/bridge/src/android/graphics/BitmapShader.java
+++ /dev/null
@@ -1,48 +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.graphics;
-
-import java.awt.Paint;
-
-public class BitmapShader extends Shader {
-
-    // we hold on just for the GC, since our native counterpart is using it
-    private final Bitmap mBitmap;
-
-    /**
-     * Call this to create a new shader that will draw with a bitmap.
-     *
-     * @param bitmap            The bitmap to use inside the shader
-     * @param tileX             The tiling mode for x to draw the bitmap in.
-     * @param tileY             The tiling mode for y to draw the bitmap in.
-     */
-    public BitmapShader(Bitmap bitmap, TileMode tileX, TileMode tileY) {
-        mBitmap = bitmap;
-    }
-
-    //---------- Custom methods
-
-    public Bitmap getBitmap() {
-        return mBitmap;
-    }
-
-    @Override
-    Paint getJavaPaint() {
-        return null;
-    }
-}
-
diff --git a/tools/layoutlib/bridge/src/android/graphics/BitmapShader_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/BitmapShader_Delegate.java
new file mode 100644
index 0000000..8eb0693
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/BitmapShader_Delegate.java
@@ -0,0 +1,240 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import android.graphics.Shader.TileMode;
+
+/**
+ * Delegate implementing the native methods of android.graphics.BitmapShader
+ *
+ * Through the layoutlib_create tool, the original native methods of BitmapShader have been
+ * replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original BitmapShader class.
+ *
+ * Because this extends {@link Shader_Delegate}, there's no need to use a {@link DelegateManager},
+ * as all the Shader classes will be added to the manager owned by {@link Shader_Delegate}.
+ *
+ * @see Shader_Delegate
+ *
+ */
+public class BitmapShader_Delegate extends Shader_Delegate {
+
+    // ---- delegate data ----
+    private java.awt.Paint mJavaPaint;
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public java.awt.Paint getJavaPaint() {
+        return mJavaPaint;
+    }
+
+    @Override
+    public boolean isSupported() {
+        return true;
+    }
+
+    @Override
+    public String getSupportMessage() {
+        // no message since isSupported returns true;
+        return null;
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeCreate(int native_bitmap, int shaderTileModeX,
+            int shaderTileModeY) {
+        Bitmap_Delegate bitmap = Bitmap_Delegate.getDelegate(native_bitmap);
+        if (bitmap == null) {
+            return 0;
+        }
+
+        BitmapShader_Delegate newDelegate = new BitmapShader_Delegate(
+                bitmap.getImage(),
+                Shader_Delegate.getTileMode(shaderTileModeX),
+                Shader_Delegate.getTileMode(shaderTileModeY));
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    // ---- Private delegate/helper methods ----
+
+    private BitmapShader_Delegate(java.awt.image.BufferedImage image,
+            TileMode tileModeX, TileMode tileModeY) {
+        mJavaPaint = new BitmapShaderPaint(image, tileModeX, tileModeY);
+    }
+
+    private class BitmapShaderPaint implements java.awt.Paint {
+        private final java.awt.image.BufferedImage mImage;
+        private final TileMode mTileModeX;
+        private final TileMode mTileModeY;
+
+        BitmapShaderPaint(java.awt.image.BufferedImage image,
+                TileMode tileModeX, TileMode tileModeY) {
+            mImage = image;
+            mTileModeX = tileModeX;
+            mTileModeY = tileModeY;
+        }
+
+        public java.awt.PaintContext createContext(
+                java.awt.image.ColorModel      colorModel,
+                java.awt.Rectangle             deviceBounds,
+                java.awt.geom.Rectangle2D      userBounds,
+                java.awt.geom.AffineTransform  xform,
+                java.awt.RenderingHints        hints) {
+
+            java.awt.geom.AffineTransform canvasMatrix;
+            try {
+                canvasMatrix = xform.createInverse();
+            } catch (java.awt.geom.NoninvertibleTransformException e) {
+                Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
+                        "Unable to inverse matrix in BitmapShader", e, null /*data*/);
+                canvasMatrix = new java.awt.geom.AffineTransform();
+            }
+
+            java.awt.geom.AffineTransform localMatrix = getLocalMatrix();
+            try {
+                localMatrix = localMatrix.createInverse();
+            } catch (java.awt.geom.NoninvertibleTransformException e) {
+                Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
+                        "Unable to inverse matrix in BitmapShader", e, null /*data*/);
+                localMatrix = new java.awt.geom.AffineTransform();
+            }
+
+            return new BitmapShaderContext(canvasMatrix, localMatrix, colorModel);
+        }
+
+        private class BitmapShaderContext implements java.awt.PaintContext {
+
+            private final java.awt.geom.AffineTransform mCanvasMatrix;
+            private final java.awt.geom.AffineTransform mLocalMatrix;
+            private final java.awt.image.ColorModel mColorModel;
+
+            public BitmapShaderContext(
+                    java.awt.geom.AffineTransform canvasMatrix,
+                    java.awt.geom.AffineTransform localMatrix,
+                    java.awt.image.ColorModel colorModel) {
+                mCanvasMatrix = canvasMatrix;
+                mLocalMatrix = localMatrix;
+                mColorModel = colorModel;
+            }
+
+            public void dispose() {
+            }
+
+            public java.awt.image.ColorModel getColorModel() {
+                return mColorModel;
+            }
+
+            public java.awt.image.Raster getRaster(int x, int y, int w, int h) {
+                java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(w, h,
+                        java.awt.image.BufferedImage.TYPE_INT_ARGB);
+
+                int[] data = new int[w*h];
+
+                int index = 0;
+                float[] pt1 = new float[2];
+                float[] pt2 = new float[2];
+                for (int iy = 0 ; iy < h ; iy++) {
+                    for (int ix = 0 ; ix < w ; ix++) {
+                        // handle the canvas transform
+                        pt1[0] = x + ix;
+                        pt1[1] = y + iy;
+                        mCanvasMatrix.transform(pt1, 0, pt2, 0, 1);
+
+                        // handle the local matrix.
+                        pt1[0] = pt2[0];
+                        pt1[1] = pt2[1];
+                        mLocalMatrix.transform(pt1, 0, pt2, 0, 1);
+
+                        data[index++] = getColor(pt2[0], pt2[1]);
+                    }
+                }
+
+                image.setRGB(0 /*startX*/, 0 /*startY*/, w, h, data, 0 /*offset*/, w /*scansize*/);
+
+                return image.getRaster();
+            }
+        }
+
+        /**
+         * Returns a color for an arbitrary point.
+         */
+        private int getColor(float fx, float fy) {
+            int x = getCoordinate(Math.round(fx), mImage.getWidth(), mTileModeX);
+            int y = getCoordinate(Math.round(fy), mImage.getHeight(), mTileModeY);
+
+            return mImage.getRGB(x, y);
+        }
+
+        private int getCoordinate(int i, int size, TileMode mode) {
+            if (i < 0) {
+                switch (mode) {
+                    case CLAMP:
+                        i = 0;
+                        break;
+                    case REPEAT:
+                        i = size - 1 - (-i % size);
+                        break;
+                    case MIRROR:
+                        // this is the same as the positive side, just make the value positive
+                        // first.
+                        i = -i;
+                        int count = i / size;
+                        i = i % size;
+
+                        if ((count % 2) == 1) {
+                            i = size - 1 - i;
+                        }
+                        break;
+                }
+            } else if (i >= size) {
+                switch (mode) {
+                    case CLAMP:
+                        i = size - 1;
+                        break;
+                    case REPEAT:
+                        i = i % size;
+                        break;
+                    case MIRROR:
+                        int count = i / size;
+                        i = i % size;
+
+                        if ((count % 2) == 1) {
+                            i = size - 1 - i;
+                        }
+                        break;
+                }
+            }
+
+            return i;
+        }
+
+
+        public int getTransparency() {
+            return java.awt.Paint.TRANSLUCENT;
+        }
+    }
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Bitmap_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Bitmap_Delegate.java
new file mode 100644
index 0000000..87c3eb6
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/Bitmap_Delegate.java
@@ -0,0 +1,542 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.resources.Density;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import android.graphics.Bitmap;
+import android.graphics.Bitmap.Config;
+import android.os.Parcel;
+
+import java.awt.Graphics2D;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.Buffer;
+import java.util.Arrays;
+
+import javax.imageio.ImageIO;
+
+/**
+ * Delegate implementing the native methods of android.graphics.Bitmap
+ *
+ * Through the layoutlib_create tool, the original native methods of Bitmap have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original Bitmap class.
+ *
+ * @see DelegateManager
+ *
+ */
+public final class Bitmap_Delegate {
+
+    // ---- delegate manager ----
+    private static final DelegateManager<Bitmap_Delegate> sManager =
+            new DelegateManager<Bitmap_Delegate>(Bitmap_Delegate.class);
+
+    // ---- delegate helper data ----
+
+    // ---- delegate data ----
+    private final Config mConfig;
+    private BufferedImage mImage;
+    private boolean mHasAlpha = true;
+
+    // ---- Public Helper methods ----
+
+    /**
+     * Returns the native delegate associated to a given {@link Bitmap_Delegate} object.
+     */
+    public static Bitmap_Delegate getDelegate(Bitmap bitmap) {
+        return sManager.getDelegate(bitmap.mNativeBitmap);
+    }
+
+    /**
+     * Returns the native delegate associated to a given an int referencing a {@link Bitmap} object.
+     */
+    public static Bitmap_Delegate getDelegate(int native_bitmap) {
+        return sManager.getDelegate(native_bitmap);
+    }
+
+    /**
+     * Creates and returns a {@link Bitmap} initialized with the given file content.
+     *
+     * @param input the file from which to read the bitmap content
+     * @param isMutable whether the bitmap is mutable
+     * @param density the density associated with the bitmap
+     *
+     * @see Bitmap#isMutable()
+     * @see Bitmap#getDensity()
+     */
+    public static Bitmap createBitmap(File input, boolean isMutable, Density density)
+            throws IOException {
+        // create a delegate with the content of the file.
+        Bitmap_Delegate delegate = new Bitmap_Delegate(ImageIO.read(input), Config.ARGB_8888);
+
+        return createBitmap(delegate, isMutable, density.getDpiValue());
+    }
+
+    /**
+     * Creates and returns a {@link Bitmap} initialized with the given stream content.
+     *
+     * @param input the stream from which to read the bitmap content
+     * @param isMutable whether the bitmap is mutable
+     * @param density the density associated with the bitmap
+     *
+     * @see Bitmap#isMutable()
+     * @see Bitmap#getDensity()
+     */
+    public static Bitmap createBitmap(InputStream input, boolean isMutable, Density density)
+            throws IOException {
+        // create a delegate with the content of the stream.
+        Bitmap_Delegate delegate = new Bitmap_Delegate(ImageIO.read(input), Config.ARGB_8888);
+
+        return createBitmap(delegate, isMutable, density.getDpiValue());
+    }
+
+    /**
+     * Creates and returns a {@link Bitmap} initialized with the given {@link BufferedImage}
+     *
+     * @param image the bitmap content
+     * @param isMutable whether the bitmap is mutable
+     * @param density the density associated with the bitmap
+     *
+     * @see Bitmap#isMutable()
+     * @see Bitmap#getDensity()
+     */
+    public static Bitmap createBitmap(BufferedImage image, boolean isMutable,
+            Density density) throws IOException {
+        // create a delegate with the given image.
+        Bitmap_Delegate delegate = new Bitmap_Delegate(image, Config.ARGB_8888);
+
+        return createBitmap(delegate, isMutable, density.getDpiValue());
+    }
+
+    /**
+     * Returns the {@link BufferedImage} used by the delegate of the given {@link Bitmap}.
+     */
+    public static BufferedImage getImage(Bitmap bitmap) {
+        // get the delegate from the native int.
+        Bitmap_Delegate delegate = sManager.getDelegate(bitmap.mNativeBitmap);
+        if (delegate == null) {
+            return null;
+        }
+
+        return delegate.mImage;
+    }
+
+    public static int getBufferedImageType(int nativeBitmapConfig) {
+        switch (Config.sConfigs[nativeBitmapConfig]) {
+            case ALPHA_8:
+                return BufferedImage.TYPE_INT_ARGB;
+            case RGB_565:
+                return BufferedImage.TYPE_INT_ARGB;
+            case ARGB_4444:
+                return BufferedImage.TYPE_INT_ARGB;
+            case ARGB_8888:
+                return BufferedImage.TYPE_INT_ARGB;
+        }
+
+        return BufferedImage.TYPE_INT_ARGB;
+    }
+
+    /**
+     * Returns the {@link BufferedImage} used by the delegate of the given {@link Bitmap}.
+     */
+    public BufferedImage getImage() {
+        return mImage;
+    }
+
+    /**
+     * Returns the Android bitmap config. Note that this not the config of the underlying
+     * Java2D bitmap.
+     */
+    public Config getConfig() {
+        return mConfig;
+    }
+
+    /**
+     * Returns the hasAlpha rendering hint
+     * @return true if the bitmap alpha should be used at render time
+     */
+    public boolean hasAlpha() {
+        return mHasAlpha && mConfig != Config.RGB_565;
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static Bitmap nativeCreate(int[] colors, int offset, int stride, int width,
+            int height, int nativeConfig, boolean mutable) {
+        int imageType = getBufferedImageType(nativeConfig);
+
+        // create the image
+        BufferedImage image = new BufferedImage(width, height, imageType);
+
+        if (colors != null) {
+            image.setRGB(0, 0, width, height, colors, offset, stride);
+        }
+
+        // create a delegate with the content of the stream.
+        Bitmap_Delegate delegate = new Bitmap_Delegate(image, Config.sConfigs[nativeConfig]);
+
+        return createBitmap(delegate, mutable, Bitmap.getDefaultDensity());
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static Bitmap nativeCopy(int srcBitmap, int nativeConfig, boolean isMutable) {
+        Bitmap_Delegate srcBmpDelegate = sManager.getDelegate(srcBitmap);
+        if (srcBmpDelegate == null) {
+            return null;
+        }
+
+        BufferedImage srcImage = srcBmpDelegate.getImage();
+
+        int width = srcImage.getWidth();
+        int height = srcImage.getHeight();
+
+        int imageType = getBufferedImageType(nativeConfig);
+
+        // create the image
+        BufferedImage image = new BufferedImage(width, height, imageType);
+
+        // copy the source image into the image.
+        int[] argb = new int[width * height];
+        srcImage.getRGB(0, 0, width, height, argb, 0, width);
+        image.setRGB(0, 0, width, height, argb, 0, width);
+
+        // create a delegate with the content of the stream.
+        Bitmap_Delegate delegate = new Bitmap_Delegate(image, Config.sConfigs[nativeConfig]);
+
+        return createBitmap(delegate, isMutable, Bitmap.getDefaultDensity());
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeDestructor(int nativeBitmap) {
+        sManager.removeJavaReferenceFor(nativeBitmap);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeRecycle(int nativeBitmap) {
+        sManager.removeJavaReferenceFor(nativeBitmap);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean nativeCompress(int nativeBitmap, int format, int quality,
+            OutputStream stream, byte[] tempStorage) {
+        Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
+                "Bitmap.compress() is not supported", null /*data*/);
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeErase(int nativeBitmap, int color) {
+        // get the delegate from the native int.
+        Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
+        if (delegate == null) {
+            return;
+        }
+
+        BufferedImage image = delegate.mImage;
+
+        Graphics2D g = image.createGraphics();
+        try {
+            g.setColor(new java.awt.Color(color, true));
+
+            g.fillRect(0, 0, image.getWidth(), image.getHeight());
+        } finally {
+            g.dispose();
+        }
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeWidth(int nativeBitmap) {
+        // get the delegate from the native int.
+        Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
+        if (delegate == null) {
+            return 0;
+        }
+
+        return delegate.mImage.getWidth();
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeHeight(int nativeBitmap) {
+        // get the delegate from the native int.
+        Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
+        if (delegate == null) {
+            return 0;
+        }
+
+        return delegate.mImage.getHeight();
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeRowBytes(int nativeBitmap) {
+        // get the delegate from the native int.
+        Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
+        if (delegate == null) {
+            return 0;
+        }
+
+        return delegate.mImage.getWidth();
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeConfig(int nativeBitmap) {
+        // get the delegate from the native int.
+        Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
+        if (delegate == null) {
+            return 0;
+        }
+
+        return delegate.mConfig.nativeInt;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean nativeHasAlpha(int nativeBitmap) {
+        // get the delegate from the native int.
+        Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
+        if (delegate == null) {
+            return true;
+        }
+
+        return delegate.mHasAlpha;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeGetPixel(int nativeBitmap, int x, int y) {
+        // get the delegate from the native int.
+        Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
+        if (delegate == null) {
+            return 0;
+        }
+
+        return delegate.mImage.getRGB(x, y);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeGetPixels(int nativeBitmap, int[] pixels, int offset,
+            int stride, int x, int y, int width, int height) {
+        Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
+        if (delegate == null) {
+            return;
+        }
+
+        delegate.getImage().getRGB(x, y, width, height, pixels, offset, stride);
+    }
+
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeSetPixel(int nativeBitmap, int x, int y, int color) {
+        Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
+        if (delegate == null) {
+            return;
+        }
+
+        delegate.getImage().setRGB(x, y, color);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeSetPixels(int nativeBitmap, int[] colors, int offset,
+            int stride, int x, int y, int width, int height) {
+        Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
+        if (delegate == null) {
+            return;
+        }
+
+        delegate.getImage().setRGB(x, y, width, height, colors, offset, stride);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeCopyPixelsToBuffer(int nativeBitmap, Buffer dst) {
+        // FIXME implement native delegate
+        Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
+                "Bitmap.copyPixelsToBuffer is not supported.", null, null /*data*/);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeCopyPixelsFromBuffer(int nb, Buffer src) {
+        // FIXME implement native delegate
+        Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
+                "Bitmap.copyPixelsFromBuffer is not supported.", null, null /*data*/);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static Bitmap nativeCreateFromParcel(Parcel p) {
+        // This is only called by Bitmap.CREATOR (Parcelable.Creator<Bitmap>), which is only
+        // used during aidl call so really this should not be called.
+        Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
+                "AIDL is not suppored, and therefore Bitmaps cannot be created from parcels.",
+                null /*data*/);
+        return null;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean nativeWriteToParcel(int nativeBitmap, boolean isMutable,
+            int density, Parcel p) {
+        // This is only called when sending a bitmap through aidl, so really this should not
+        // be called.
+        Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
+                "AIDL is not suppored, and therefore Bitmaps cannot be written to parcels.",
+                null /*data*/);
+        return false;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static Bitmap nativeExtractAlpha(int nativeBitmap, int nativePaint,
+            int[] offsetXY) {
+        Bitmap_Delegate bitmap = sManager.getDelegate(nativeBitmap);
+        if (bitmap == null) {
+            return null;
+        }
+
+        // get the paint which can be null if nativePaint is 0.
+        Paint_Delegate paint = Paint_Delegate.getDelegate(nativePaint);
+
+        if (paint != null && paint.getMaskFilter() != null) {
+            Bridge.getLog().fidelityWarning(LayoutLog.TAG_MASKFILTER,
+                    "MaskFilter not supported in Bitmap.extractAlpha",
+                    null, null /*data*/);
+        }
+
+        int alpha = paint != null ? paint.getAlpha() : 0xFF;
+        BufferedImage image = createCopy(bitmap.getImage(), BufferedImage.TYPE_INT_ARGB, alpha);
+
+        // create the delegate. The actual Bitmap config is only an alpha channel
+        Bitmap_Delegate delegate = new Bitmap_Delegate(image, Config.ALPHA_8);
+
+        // the density doesn't matter, it's set by the Java method.
+        return createBitmap(delegate, false /*isMutable*/,
+                Density.DEFAULT_DENSITY /*density*/);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativePrepareToDraw(int nativeBitmap) {
+        // nothing to be done here.
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeSetHasAlpha(int nativeBitmap, boolean hasAlpha) {
+        // get the delegate from the native int.
+        Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
+        if (delegate == null) {
+            return;
+        }
+
+        delegate.mHasAlpha = hasAlpha;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean nativeSameAs(int nb0, int nb1) {
+        Bitmap_Delegate delegate1 = sManager.getDelegate(nb0);
+        if (delegate1 == null) {
+            return false;
+        }
+
+        Bitmap_Delegate delegate2 = sManager.getDelegate(nb1);
+        if (delegate2 == null) {
+            return false;
+        }
+
+        BufferedImage image1 = delegate1.getImage();
+        BufferedImage image2 = delegate2.getImage();
+        if (delegate1.mConfig != delegate2.mConfig ||
+                image1.getWidth() != image2.getWidth() ||
+                image1.getHeight() != image2.getHeight()) {
+            return false;
+        }
+
+        // get the internal data
+        int w = image1.getWidth();
+        int h = image2.getHeight();
+        int[] argb1 = new int[w*h];
+        int[] argb2 = new int[w*h];
+
+        image1.getRGB(0, 0, w, h, argb1, 0, w);
+        image2.getRGB(0, 0, w, h, argb2, 0, w);
+
+        // compares
+        if (delegate1.mConfig == Config.ALPHA_8) {
+            // in this case we have to manually compare the alpha channel as the rest is garbage.
+            final int length = w*h;
+            for (int i = 0 ; i < length ; i++) {
+                if ((argb1[i] & 0xFF000000) != (argb2[i] & 0xFF000000)) {
+                    return false;
+                }
+            }
+            return true;
+        }
+
+        return Arrays.equals(argb1, argb2);
+    }
+
+    // ---- Private delegate/helper methods ----
+
+    private Bitmap_Delegate(BufferedImage image, Config config) {
+        mImage = image;
+        mConfig = config;
+    }
+
+    private static Bitmap createBitmap(Bitmap_Delegate delegate, boolean isMutable, int density) {
+        // get its native_int
+        int nativeInt = sManager.addNewDelegate(delegate);
+
+        // and create/return a new Bitmap with it
+        return new Bitmap(nativeInt, isMutable, null /*ninePatchChunk*/, density);
+    }
+
+    /**
+     * Creates and returns a copy of a given BufferedImage.
+     * <p/>
+     * if alpha is different than 255, then it is applied to the alpha channel of each pixel.
+     *
+     * @param image the image to copy
+     * @param imageType the type of the new image
+     * @param alpha an optional alpha modifier
+     * @return a new BufferedImage
+     */
+    /*package*/ static BufferedImage createCopy(BufferedImage image, int imageType, int alpha) {
+        int w = image.getWidth();
+        int h = image.getHeight();
+
+        BufferedImage result = new BufferedImage(w, h, imageType);
+
+        int[] argb = new int[w * h];
+        image.getRGB(0, 0, image.getWidth(), image.getHeight(), argb, 0, image.getWidth());
+
+        if (alpha != 255) {
+            final int length = argb.length;
+            for (int i = 0 ; i < length; i++) {
+                int a = (argb[i] >>> 24 * alpha) / 255;
+                argb[i] = (a << 24) | (argb[i] & 0x00FFFFFF);
+            }
+        }
+
+        result.setRGB(0, 0, w, h, argb, 0, w);
+
+        return result;
+    }
+
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/BlurMaskFilter_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/BlurMaskFilter_Delegate.java
new file mode 100644
index 0000000..4becba1
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/BlurMaskFilter_Delegate.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+/**
+ * Delegate implementing the native methods of android.graphics.BlurMaskFilter
+ *
+ * Through the layoutlib_create tool, the original native methods of BlurMaskFilter have
+ * been replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original BlurMaskFilter class.
+ *
+ * Because this extends {@link MaskFilter_Delegate}, there's no need to use a
+ * {@link DelegateManager}, as all the Shader classes will be added to the manager
+ * owned by {@link MaskFilter_Delegate}.
+ *
+ * @see MaskFilter_Delegate
+ *
+ */
+public class BlurMaskFilter_Delegate extends MaskFilter_Delegate {
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public boolean isSupported() {
+        return false;
+    }
+
+    @Override
+    public String getSupportMessage() {
+        return "Blur Mask Filters are not supported.";
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeConstructor(float radius, int style) {
+        BlurMaskFilter_Delegate newDelegate = new BlurMaskFilter_Delegate();
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    // ---- Private delegate/helper methods ----
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Canvas.java b/tools/layoutlib/bridge/src/android/graphics/Canvas.java
deleted file mode 100644
index d5d315e..0000000
--- a/tools/layoutlib/bridge/src/android/graphics/Canvas.java
+++ /dev/null
@@ -1,1279 +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.graphics;
-
-import com.android.layoutlib.api.ILayoutLog;
-
-import android.graphics.DrawFilter;
-import android.graphics.Picture;
-import android.graphics.PorterDuff;
-import android.graphics.Rect;
-import android.graphics.RectF;
-import android.graphics.Region;
-import android.graphics.Xfermode;
-import android.graphics.Paint.Align;
-import android.graphics.Paint.FontInfo;
-import android.graphics.Paint.Style;
-import android.graphics.Region.Op;
-
-import java.awt.AlphaComposite;
-import java.awt.BasicStroke;
-import java.awt.Color;
-import java.awt.Composite;
-import java.awt.Graphics2D;
-import java.awt.Rectangle;
-import java.awt.RenderingHints;
-import java.awt.geom.AffineTransform;
-import java.awt.image.BufferedImage;
-import java.util.List;
-import java.util.Stack;
-
-import javax.microedition.khronos.opengles.GL;
-
-/**
- * Re-implementation of the Canvas, 100% in java on top of a BufferedImage.
- */
-public class Canvas extends _Original_Canvas {
-
-    private BufferedImage mBufferedImage;
-    private final Stack<Graphics2D> mGraphicsStack = new Stack<Graphics2D>();
-    private final ILayoutLog mLogger;
-
-    public Canvas() {
-        mLogger = null;
-        // the mBufferedImage will be taken from a bitmap in #setBitmap()
-    }
-
-    public Canvas(Bitmap bitmap) {
-        mLogger = null;
-        mBufferedImage = bitmap.getImage();
-        mGraphicsStack.push(mBufferedImage.createGraphics());
-    }
-
-    public Canvas(int nativeCanvas) {
-        mLogger = null;
-        throw new UnsupportedOperationException("Can't create Canvas(int)");
-    }
-
-    public Canvas(javax.microedition.khronos.opengles.GL gl) {
-        mLogger = null;
-        throw new UnsupportedOperationException("Can't create Canvas(javax.microedition.khronos.opengles.GL)");
-    }
-
-    // custom constructors for our use.
-    public Canvas(int width, int height, ILayoutLog logger) {
-        mLogger = logger;
-        mBufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
-        mGraphicsStack.push(mBufferedImage.createGraphics());
-    }
-
-    public Canvas(int width, int height) {
-        this(width, height, null /* logger*/);
-    }
-
-    // custom mehtods
-    public BufferedImage getImage() {
-        return mBufferedImage;
-    }
-
-    public Graphics2D getGraphics2d() {
-        return mGraphicsStack.peek();
-    }
-
-    public void dispose() {
-        while (mGraphicsStack.size() > 0) {
-            mGraphicsStack.pop().dispose();
-        }
-    }
-
-    /**
-     * Creates a new {@link Graphics2D} based on the {@link Paint} parameters.
-     * <p/>The object must be disposed ({@link Graphics2D#dispose()}) after being used.
-     */
-    private Graphics2D getCustomGraphics(Paint paint) {
-        // make new one
-        Graphics2D g = getGraphics2d();
-        g = (Graphics2D)g.create();
-
-        // configure it
-        g.setColor(new Color(paint.getColor()));
-        int alpha = paint.getAlpha();
-        float falpha = alpha / 255.f;
-
-        Style style = paint.getStyle();
-        if (style == Style.STROKE || style == Style.FILL_AND_STROKE) {
-            PathEffect e = paint.getPathEffect();
-            if (e instanceof DashPathEffect) {
-                DashPathEffect dpe = (DashPathEffect)e;
-                g.setStroke(new BasicStroke(
-                        paint.getStrokeWidth(),
-                        paint.getStrokeCap().getJavaCap(),
-                        paint.getStrokeJoin().getJavaJoin(),
-                        paint.getStrokeMiter(),
-                        dpe.getIntervals(),
-                        dpe.getPhase()));
-            } else {
-                g.setStroke(new BasicStroke(
-                        paint.getStrokeWidth(),
-                        paint.getStrokeCap().getJavaCap(),
-                        paint.getStrokeJoin().getJavaJoin(),
-                        paint.getStrokeMiter()));
-            }
-        }
-
-        Xfermode xfermode = paint.getXfermode();
-        if (xfermode instanceof PorterDuffXfermode) {
-            PorterDuff.Mode mode = ((PorterDuffXfermode)xfermode).getMode();
-
-            setModeInGraphics(mode, g, falpha);
-        } else {
-            if (mLogger != null && xfermode != null) {
-                mLogger.warning(String.format(
-                        "Xfermode '%1$s' is not supported in the Layout Editor.",
-                        xfermode.getClass().getCanonicalName()));
-            }
-            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, falpha));
-        }
-
-        Shader shader = paint.getShader();
-        if (shader != null) {
-            java.awt.Paint shaderPaint = shader.getJavaPaint();
-            if (shaderPaint != null) {
-                g.setPaint(shaderPaint);
-            } else {
-                if (mLogger != null) {
-                    mLogger.warning(String.format(
-                            "Shader '%1$s' is not supported in the Layout Editor.",
-                            shader.getClass().getCanonicalName()));
-                }
-            }
-        }
-
-        return g;
-    }
-
-    private void setModeInGraphics(PorterDuff.Mode mode, Graphics2D g, float falpha) {
-        switch (mode) {
-            case CLEAR:
-                g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, falpha));
-                break;
-            case DARKEN:
-                break;
-            case DST:
-                g.setComposite(AlphaComposite.getInstance(AlphaComposite.DST, falpha));
-                break;
-            case DST_ATOP:
-                g.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_ATOP, falpha));
-                break;
-            case DST_IN:
-                g.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_IN, falpha));
-                break;
-            case DST_OUT:
-                g.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_OUT, falpha));
-                break;
-            case DST_OVER:
-                g.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_OVER, falpha));
-                break;
-            case LIGHTEN:
-                break;
-            case MULTIPLY:
-                break;
-            case SCREEN:
-                break;
-            case SRC:
-                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, falpha));
-                break;
-            case SRC_ATOP:
-                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, falpha));
-                break;
-            case SRC_IN:
-                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, falpha));
-                break;
-            case SRC_OUT:
-                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OUT, falpha));
-                break;
-            case SRC_OVER:
-                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, falpha));
-                break;
-            case XOR:
-                g.setComposite(AlphaComposite.getInstance(AlphaComposite.XOR, falpha));
-                break;
-        }
-    }
-
-
-    // --------------------
-    // OVERRIDEN ENUMS
-    // This is needed since we rename Canvas into _Original_Canvas
-    // --------------------
-
-    public enum EdgeType {
-        BW(0),  //!< treat edges by just rounding to nearest pixel boundary
-        AA(1);  //!< treat edges by rounding-out, since they may be antialiased
-
-        EdgeType(int nativeInt) {
-            this.nativeInt = nativeInt;
-        }
-        final int nativeInt;
-    }
-
-
-    // --------------------
-    // OVERRIDEN METHODS
-    // --------------------
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#setBitmap(android.graphics.Bitmap)
-     */
-    @Override
-    public void setBitmap(Bitmap bitmap) {
-        mBufferedImage = bitmap.getImage();
-        mGraphicsStack.push(mBufferedImage.createGraphics());
-    }
-
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#translate(float, float)
-     */
-    @Override
-    public void translate(float dx, float dy) {
-        getGraphics2d().translate(dx, dy);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#save()
-     */
-    @Override
-    public int save() {
-        // get the current save count
-        int count = mGraphicsStack.size();
-
-        // create a new graphics and add it to the stack
-        Graphics2D g = (Graphics2D)getGraphics2d().create();
-        mGraphicsStack.push(g);
-
-        // return the old save count
-        return count;
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#save(int)
-     */
-    @Override
-    public int save(int saveFlags) {
-        // For now we ignore saveFlags
-        return save();
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#restore()
-     */
-    @Override
-    public void restore() {
-        mGraphicsStack.pop();
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#restoreToCount(int)
-     */
-    @Override
-    public void restoreToCount(int saveCount) {
-        while (mGraphicsStack.size() > saveCount) {
-            mGraphicsStack.pop();
-        }
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#getSaveCount()
-     */
-    @Override
-    public int getSaveCount() {
-        return mGraphicsStack.size();
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#clipRect(float, float, float, float, android.graphics.Region.Op)
-     */
-    @Override
-    public boolean clipRect(float left, float top, float right, float bottom, Op op) {
-        return clipRect(left, top, right, bottom);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#clipRect(float, float, float, float)
-     */
-    @Override
-    public boolean clipRect(float left, float top, float right, float bottom) {
-        getGraphics2d().clipRect((int)left, (int)top, (int)(right-left), (int)(bottom-top));
-        return true;
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#clipRect(int, int, int, int)
-     */
-    @Override
-    public boolean clipRect(int left, int top, int right, int bottom) {
-        getGraphics2d().clipRect(left, top, right-left, bottom-top);
-        return true;
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#clipRect(android.graphics.Rect, android.graphics.Region.Op)
-     */
-    @Override
-    public boolean clipRect(Rect rect, Op op) {
-        return clipRect(rect.left, rect.top, rect.right, rect.bottom);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#clipRect(android.graphics.Rect)
-     */
-    @Override
-    public boolean clipRect(Rect rect) {
-        return clipRect(rect.left, rect.top, rect.right, rect.bottom);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#clipRect(android.graphics.RectF, android.graphics.Region.Op)
-     */
-    @Override
-    public boolean clipRect(RectF rect, Op op) {
-        return clipRect(rect.left, rect.top, rect.right, rect.bottom);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#clipRect(android.graphics.RectF)
-     */
-    @Override
-    public boolean clipRect(RectF rect) {
-        return clipRect(rect.left, rect.top, rect.right, rect.bottom);
-    }
-
-    public boolean quickReject(RectF rect, EdgeType type) {
-        return false;
-    }
-
-    @Override
-    public boolean quickReject(RectF rect, _Original_Canvas.EdgeType type) {
-        throw new UnsupportedOperationException("CALL TO PARENT FORBIDDEN");
-    }
-
-    public boolean quickReject(Path path, EdgeType type) {
-        return false;
-    }
-
-    @Override
-    public boolean quickReject(Path path, _Original_Canvas.EdgeType type) {
-        throw new UnsupportedOperationException("CALL TO PARENT FORBIDDEN");
-    }
-
-    public boolean quickReject(float left, float top, float right, float bottom,
-                               EdgeType type) {
-        return false;
-    }
-
-    @Override
-    public boolean quickReject(float left, float top, float right, float bottom,
-                               _Original_Canvas.EdgeType type) {
-        throw new UnsupportedOperationException("CALL TO PARENT FORBIDDEN");
-    }
-
-    /**
-     * Retrieve the clip bounds, returning true if they are non-empty.
-     *
-     * @param bounds Return the clip bounds here. If it is null, ignore it but
-     *               still return true if the current clip is non-empty.
-     * @return true if the current clip is non-empty.
-     */
-    @Override
-    public boolean getClipBounds(Rect bounds) {
-        Rectangle rect = getGraphics2d().getClipBounds();
-        if (rect != null) {
-            bounds.left = rect.x;
-            bounds.top = rect.y;
-            bounds.right = rect.x + rect.width;
-            bounds.bottom = rect.y + rect.height;
-            return true;
-        }
-        return false;
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawColor(int, android.graphics.PorterDuff.Mode)
-     */
-    @Override
-    public void drawColor(int color, PorterDuff.Mode mode) {
-        Graphics2D g = getGraphics2d();
-
-        // save old color
-        Color c = g.getColor();
-
-        Composite composite = g.getComposite();
-
-        // get the alpha from the color
-        int alpha = color >>> 24;
-        float falpha = alpha / 255.f;
-
-        setModeInGraphics(mode, g, falpha);
-
-        g.setColor(new Color(color));
-
-        g.fillRect(0, 0, getWidth(), getHeight());
-
-        g.setComposite(composite);
-
-        // restore color
-        g.setColor(c);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawColor(int)
-     */
-    @Override
-    public void drawColor(int color) {
-        drawColor(color, PorterDuff.Mode.SRC_OVER);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawARGB(int, int, int, int)
-     */
-    @Override
-    public void drawARGB(int a, int r, int g, int b) {
-        drawColor(a << 24 | r << 16 | g << 8 | b, PorterDuff.Mode.SRC_OVER);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawRGB(int, int, int)
-     */
-    @Override
-    public void drawRGB(int r, int g, int b) {
-        drawColor(0xFF << 24 | r << 16 | g << 8 | b, PorterDuff.Mode.SRC_OVER);
-    }
-
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#getWidth()
-     */
-    @Override
-    public int getWidth() {
-        return mBufferedImage.getWidth();
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#getHeight()
-     */
-    @Override
-    public int getHeight() {
-        return mBufferedImage.getHeight();
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawPaint(android.graphics.Paint)
-     */
-    @Override
-    public void drawPaint(Paint paint) {
-        drawColor(paint.getColor());
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawBitmap(android.graphics.Bitmap, float, float, android.graphics.Paint)
-     */
-    @Override
-    public void drawBitmap(Bitmap bitmap, float left, float top, Paint paint) {
-        drawBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
-                (int)left, (int)top,
-                (int)left+bitmap.getWidth(), (int)top+bitmap.getHeight(), paint);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawBitmap(android.graphics.Bitmap, android.graphics.Matrix, android.graphics.Paint)
-     */
-    @Override
-    public void drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint) {
-        boolean needsRestore = false;
-        if (matrix.isIdentity() == false) {
-            // create a new graphics and apply the matrix to it
-            save(); // this creates a new Graphics2D, and stores it for children call to use
-            needsRestore = true;
-            Graphics2D g = getGraphics2d(); // get the newly create Graphics2D
-
-            // get the Graphics2D current matrix
-            AffineTransform currentTx = g.getTransform();
-            // get the AffineTransform from the matrix
-            AffineTransform matrixTx = matrix.getTransform();
-
-            // combine them so that the matrix is applied after.
-            currentTx.preConcatenate(matrixTx);
-
-            // give it to the graphics as a new matrix replacing all previous transform
-            g.setTransform(currentTx);
-        }
-
-        // draw the bitmap
-        drawBitmap(bitmap, 0, 0, paint);
-
-        if (needsRestore) {
-            // remove the new graphics
-            restore();
-        }
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawBitmap(android.graphics.Bitmap, android.graphics.Rect, android.graphics.Rect, android.graphics.Paint)
-     */
-    @Override
-    public void drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint) {
-        if (src == null) {
-            drawBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
-                    dst.left, dst.top, dst.right, dst.bottom, paint);
-        } else {
-            drawBitmap(bitmap, src.left, src.top, src.width(), src.height(),
-                    dst.left, dst.top, dst.right, dst.bottom, paint);
-        }
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawBitmap(android.graphics.Bitmap, android.graphics.Rect, android.graphics.RectF, android.graphics.Paint)
-     */
-    @Override
-    public void drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint) {
-        if (src == null) {
-            drawBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
-                    (int)dst.left, (int)dst.top, (int)dst.right, (int)dst.bottom, paint);
-        } else {
-            drawBitmap(bitmap, src.left, src.top, src.width(), src.height(),
-                    (int)dst.left, (int)dst.top, (int)dst.right, (int)dst.bottom, paint);
-        }
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawBitmap(int[], int, int, int, int, int, int, boolean, android.graphics.Paint)
-     */
-    @Override
-    public void drawBitmap(int[] colors, int offset, int stride, int x, int y, int width,
-            int height, boolean hasAlpha, Paint paint) {
-        throw new UnsupportedOperationException();
-    }
-
-    private void drawBitmap(Bitmap bitmap, int sleft, int stop, int sright, int sbottom, int dleft,
-            int dtop, int dright, int dbottom, Paint paint) {
-        BufferedImage image = bitmap.getImage();
-
-        Graphics2D g = getGraphics2d();
-
-        Composite c = null;
-
-        if (paint != null) {
-            if (paint.isFilterBitmap()) {
-                g = (Graphics2D)g.create();
-                g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
-                        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
-            }
-
-            if (paint.getAlpha() != 0xFF) {
-                c = g.getComposite();
-                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
-                        paint.getAlpha()/255.f));
-            }
-        }
-
-        g.drawImage(image, dleft, dtop, dright, dbottom,
-                sleft, stop, sright, sbottom, null);
-
-        if (paint != null) {
-            if (paint.isFilterBitmap()) {
-                g.dispose();
-            }
-            if (c != null) {
-                g.setComposite(c);
-            }
-        }
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#rotate(float, float, float)
-     */
-    @Override
-    public void rotate(float degrees, float px, float py) {
-        if (degrees != 0) {
-            Graphics2D g = getGraphics2d();
-            g.translate(px, py);
-            g.rotate(Math.toRadians(degrees));
-            g.translate(-px, -py);
-        }
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#rotate(float)
-     */
-    @Override
-    public void rotate(float degrees) {
-        getGraphics2d().rotate(Math.toRadians(degrees));
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#scale(float, float, float, float)
-     */
-    @Override
-    public void scale(float sx, float sy, float px, float py) {
-        Graphics2D g = getGraphics2d();
-        g.translate(px, py);
-        g.scale(sx, sy);
-        g.translate(-px, -py);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#scale(float, float)
-     */
-    @Override
-    public void scale(float sx, float sy) {
-        getGraphics2d().scale(sx, sy);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawText(char[], int, int, float, float, android.graphics.Paint)
-     */
-    @Override
-    public void drawText(char[] text, int index, int count, float x, float y, Paint paint) {
-        // WARNING: the logic in this method is similar to Paint.measureText.
-        // Any change to this method should be reflected in Paint.measureText
-        Graphics2D g = getGraphics2d();
-
-        g = (Graphics2D)g.create();
-        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
-
-        // set the color. because this only handles RGB, the alpha channel is handled
-        // as a composite.
-        g.setColor(new Color(paint.getColor()));
-        int alpha = paint.getAlpha();
-        float falpha = alpha / 255.f;
-        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, falpha));
-
-
-        // Paint.TextAlign indicates how the text is positioned relative to X.
-        // LEFT is the default and there's nothing to do.
-        if (paint.getTextAlign() != Align.LEFT) {
-            float m = paint.measureText(text, index, count);
-            if (paint.getTextAlign() == Align.CENTER) {
-                x -= m / 2;
-            } else if (paint.getTextAlign() == Align.RIGHT) {
-                x -= m;
-            }
-        }
-
-        List<FontInfo> fonts = paint.getFonts();
-        try {
-            if (fonts.size() > 0) {
-                FontInfo mainFont = fonts.get(0);
-                int i = index;
-                int lastIndex = index + count;
-                while (i < lastIndex) {
-                    // always start with the main font.
-                    int upTo = mainFont.mFont.canDisplayUpTo(text, i, lastIndex);
-                    if (upTo == -1) {
-                        // draw all the rest and exit.
-                        g.setFont(mainFont.mFont);
-                        g.drawChars(text, i, lastIndex - i, (int)x, (int)y);
-                        return;
-                    } else if (upTo > 0) {
-                        // draw what's possible
-                        g.setFont(mainFont.mFont);
-                        g.drawChars(text, i, upTo - i, (int)x, (int)y);
-
-                        // compute the width that was drawn to increase x
-                        x += mainFont.mMetrics.charsWidth(text, i, upTo - i);
-
-                        // move index to the first non displayed char.
-                        i = upTo;
-
-                        // don't call continue at this point. Since it is certain the main font
-                        // cannot display the font a index upTo (now ==i), we move on to the
-                        // fallback fonts directly.
-                    }
-
-                    // no char supported, attempt to read the next char(s) with the
-                    // fallback font. In this case we only test the first character
-                    // and then go back to test with the main font.
-                    // Special test for 2-char characters.
-                    boolean foundFont = false;
-                    for (int f = 1 ; f < fonts.size() ; f++) {
-                        FontInfo fontInfo = fonts.get(f);
-
-                        // need to check that the font can display the character. We test
-                        // differently if the char is a high surrogate.
-                        int charCount = Character.isHighSurrogate(text[i]) ? 2 : 1;
-                        upTo = fontInfo.mFont.canDisplayUpTo(text, i, i + charCount);
-                        if (upTo == -1) {
-                            // draw that char
-                            g.setFont(fontInfo.mFont);
-                            g.drawChars(text, i, charCount, (int)x, (int)y);
-
-                            // update x
-                            x += fontInfo.mMetrics.charsWidth(text, i, charCount);
-
-                            // update the index in the text, and move on
-                            i += charCount;
-                            foundFont = true;
-                            break;
-
-                        }
-                    }
-
-                    // in case no font can display the char, display it with the main font.
-                    // (it'll put a square probably)
-                    if (foundFont == false) {
-                        int charCount = Character.isHighSurrogate(text[i]) ? 2 : 1;
-
-                        g.setFont(mainFont.mFont);
-                        g.drawChars(text, i, charCount, (int)x, (int)y);
-
-                        // measure it to advance x
-                        x += mainFont.mMetrics.charsWidth(text, i, charCount);
-
-                        // and move to the next chars.
-                        i += charCount;
-                    }
-                }
-            }
-        } finally {
-            g.dispose();
-        }
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawText(java.lang.CharSequence, int, int, float, float, android.graphics.Paint)
-     */
-    @Override
-    public void drawText(CharSequence text, int start, int end, float x, float y, Paint paint) {
-        drawText(text.toString().toCharArray(), start, end - start, x, y, paint);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawText(java.lang.String, float, float, android.graphics.Paint)
-     */
-    @Override
-    public void drawText(String text, float x, float y, Paint paint) {
-        drawText(text.toCharArray(), 0, text.length(), x, y, paint);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawText(java.lang.String, int, int, float, float, android.graphics.Paint)
-     */
-    @Override
-    public void drawText(String text, int start, int end, float x, float y, Paint paint) {
-        drawText(text.toCharArray(), start, end - start, x, y, paint);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawRect(android.graphics.RectF, android.graphics.Paint)
-     */
-    @Override
-    public void drawRect(RectF rect, Paint paint) {
-        doDrawRect((int)rect.left, (int)rect.top, (int)rect.width(), (int)rect.height(), paint);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawRect(float, float, float, float, android.graphics.Paint)
-     */
-    @Override
-    public void drawRect(float left, float top, float right, float bottom, Paint paint) {
-        doDrawRect((int)left, (int)top, (int)(right-left), (int)(bottom-top), paint);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawRect(android.graphics.Rect, android.graphics.Paint)
-     */
-    @Override
-    public void drawRect(Rect r, Paint paint) {
-        doDrawRect(r.left, r.top, r.width(), r.height(), paint);
-    }
-
-    private final void doDrawRect(int left, int top, int width, int height, Paint paint) {
-        if (width > 0 && height > 0) {
-            // get a Graphics2D object configured with the drawing parameters.
-            Graphics2D g = getCustomGraphics(paint);
-
-            Style style = paint.getStyle();
-
-            // draw
-            if (style == Style.FILL || style == Style.FILL_AND_STROKE) {
-                g.fillRect(left, top, width, height);
-            }
-
-            if (style == Style.STROKE || style == Style.FILL_AND_STROKE) {
-                g.drawRect(left, top, width, height);
-            }
-
-            // dispose Graphics2D object
-            g.dispose();
-        }
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawRoundRect(android.graphics.RectF, float, float, android.graphics.Paint)
-     */
-    @Override
-    public void drawRoundRect(RectF rect, float rx, float ry, Paint paint) {
-        if (rect.width() > 0 && rect.height() > 0) {
-            // get a Graphics2D object configured with the drawing parameters.
-            Graphics2D g = getCustomGraphics(paint);
-
-            Style style = paint.getStyle();
-
-            // draw
-
-            int arcWidth = (int)(rx * 2);
-            int arcHeight = (int)(ry * 2);
-
-            if (style == Style.FILL || style == Style.FILL_AND_STROKE) {
-                g.fillRoundRect((int)rect.left, (int)rect.top, (int)rect.width(), (int)rect.height(),
-                        arcWidth, arcHeight);
-            }
-
-            if (style == Style.STROKE || style == Style.FILL_AND_STROKE) {
-                g.drawRoundRect((int)rect.left, (int)rect.top, (int)rect.width(), (int)rect.height(),
-                        arcWidth, arcHeight);
-            }
-
-            // dispose Graphics2D object
-            g.dispose();
-        }
-    }
-
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawLine(float, float, float, float, android.graphics.Paint)
-     */
-    @Override
-    public void drawLine(float startX, float startY, float stopX, float stopY, Paint paint) {
-        // get a Graphics2D object configured with the drawing parameters.
-        Graphics2D g = getCustomGraphics(paint);
-
-        g.drawLine((int)startX, (int)startY, (int)stopX, (int)stopY);
-
-        // dispose Graphics2D object
-        g.dispose();
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawLines(float[], int, int, android.graphics.Paint)
-     */
-    @Override
-    public void drawLines(float[] pts, int offset, int count, Paint paint) {
-        // get a Graphics2D object configured with the drawing parameters.
-        Graphics2D g = getCustomGraphics(paint);
-
-        for (int i = 0 ; i < count ; i += 4) {
-            g.drawLine((int)pts[i + offset], (int)pts[i + offset + 1],
-                    (int)pts[i + offset + 2], (int)pts[i + offset + 3]);
-        }
-
-        // dispose Graphics2D object
-        g.dispose();
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawLines(float[], android.graphics.Paint)
-     */
-    @Override
-    public void drawLines(float[] pts, Paint paint) {
-        drawLines(pts, 0, pts.length, paint);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawCircle(float, float, float, android.graphics.Paint)
-     */
-    @Override
-    public void drawCircle(float cx, float cy, float radius, Paint paint) {
-        // get a Graphics2D object configured with the drawing parameters.
-        Graphics2D g = getCustomGraphics(paint);
-
-        Style style = paint.getStyle();
-
-        int size = (int)(radius * 2);
-
-        // draw
-        if (style == Style.FILL || style == Style.FILL_AND_STROKE) {
-            g.fillOval((int)(cx - radius), (int)(cy - radius), size, size);
-        }
-
-        if (style == Style.STROKE || style == Style.FILL_AND_STROKE) {
-            g.drawOval((int)(cx - radius), (int)(cy - radius), size, size);
-        }
-
-        // dispose Graphics2D object
-        g.dispose();
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawOval(android.graphics.RectF, android.graphics.Paint)
-     */
-    @Override
-    public void drawOval(RectF oval, Paint paint) {
-        // get a Graphics2D object configured with the drawing parameters.
-        Graphics2D g = getCustomGraphics(paint);
-
-        Style style = paint.getStyle();
-
-        // draw
-        if (style == Style.FILL || style == Style.FILL_AND_STROKE) {
-            g.fillOval((int)oval.left, (int)oval.top, (int)oval.width(), (int)oval.height());
-        }
-
-        if (style == Style.STROKE || style == Style.FILL_AND_STROKE) {
-            g.drawOval((int)oval.left, (int)oval.top, (int)oval.width(), (int)oval.height());
-        }
-
-        // dispose Graphics2D object
-        g.dispose();
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawPath(android.graphics.Path, android.graphics.Paint)
-     */
-    @Override
-    public void drawPath(Path path, Paint paint) {
-        // get a Graphics2D object configured with the drawing parameters.
-        Graphics2D g = getCustomGraphics(paint);
-
-        Style style = paint.getStyle();
-
-        // draw
-        if (style == Style.FILL || style == Style.FILL_AND_STROKE) {
-            g.fill(path.getAwtShape());
-        }
-
-        if (style == Style.STROKE || style == Style.FILL_AND_STROKE) {
-            g.draw(path.getAwtShape());
-        }
-
-        // dispose Graphics2D object
-        g.dispose();
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#setMatrix(android.graphics.Matrix)
-     */
-    @Override
-    public void setMatrix(Matrix matrix) {
-        // get the new current graphics
-        Graphics2D g = getGraphics2d();
-
-        // and apply the matrix
-        g.setTransform(matrix.getTransform());
-
-        if (mLogger != null && matrix.hasPerspective()) {
-            mLogger.warning("android.graphics.Canvas#setMatrix(android.graphics.Matrix) only supports affine transformations in the Layout Editor.");
-        }
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#concat(android.graphics.Matrix)
-     */
-    @Override
-    public void concat(Matrix matrix) {
-        // get the current top graphics2D object.
-        Graphics2D g = getGraphics2d();
-
-        // get its current matrix
-        AffineTransform currentTx = g.getTransform();
-        // get the AffineTransform of the given matrix
-        AffineTransform matrixTx = matrix.getTransform();
-
-        // combine them so that the given matrix is applied after.
-        currentTx.preConcatenate(matrixTx);
-
-        // give it to the graphics2D as a new matrix replacing all previous transform
-        g.setTransform(currentTx);
-    }
-
-
-    // --------------------
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#clipPath(android.graphics.Path, android.graphics.Region.Op)
-     */
-    @Override
-    public boolean clipPath(Path path, Op op) {
-        // TODO Auto-generated method stub
-        return super.clipPath(path, op);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#clipPath(android.graphics.Path)
-     */
-    @Override
-    public boolean clipPath(Path path) {
-        // TODO Auto-generated method stub
-        return super.clipPath(path);
-    }
-
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#clipRegion(android.graphics.Region, android.graphics.Region.Op)
-     */
-    @Override
-    public boolean clipRegion(Region region, Op op) {
-        // TODO Auto-generated method stub
-        return super.clipRegion(region, op);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#clipRegion(android.graphics.Region)
-     */
-    @Override
-    public boolean clipRegion(Region region) {
-        // TODO Auto-generated method stub
-        return super.clipRegion(region);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawArc(android.graphics.RectF, float, float, boolean, android.graphics.Paint)
-     */
-    @Override
-    public void drawArc(RectF oval, float startAngle, float sweepAngle, boolean useCenter,
-            Paint paint) {
-        // TODO Auto-generated method stub
-        super.drawArc(oval, startAngle, sweepAngle, useCenter, paint);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawBitmapMesh(android.graphics.Bitmap, int, int, float[], int, int[], int, android.graphics.Paint)
-     */
-    @Override
-    public void drawBitmapMesh(Bitmap bitmap, int meshWidth, int meshHeight, float[] verts,
-            int vertOffset, int[] colors, int colorOffset, Paint paint) {
-        // TODO Auto-generated method stub
-        super.drawBitmapMesh(bitmap, meshWidth, meshHeight, verts, vertOffset, colors, colorOffset, paint);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawPicture(android.graphics.Picture, android.graphics.Rect)
-     */
-    @Override
-    public void drawPicture(Picture picture, Rect dst) {
-        // TODO Auto-generated method stub
-        super.drawPicture(picture, dst);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawPicture(android.graphics.Picture, android.graphics.RectF)
-     */
-    @Override
-    public void drawPicture(Picture picture, RectF dst) {
-        // TODO Auto-generated method stub
-        super.drawPicture(picture, dst);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawPicture(android.graphics.Picture)
-     */
-    @Override
-    public void drawPicture(Picture picture) {
-        // TODO Auto-generated method stub
-        super.drawPicture(picture);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawPoint(float, float, android.graphics.Paint)
-     */
-    @Override
-    public void drawPoint(float x, float y, Paint paint) {
-        // TODO Auto-generated method stub
-        super.drawPoint(x, y, paint);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawPoints(float[], int, int, android.graphics.Paint)
-     */
-    @Override
-    public void drawPoints(float[] pts, int offset, int count, Paint paint) {
-        // TODO Auto-generated method stub
-        super.drawPoints(pts, offset, count, paint);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawPoints(float[], android.graphics.Paint)
-     */
-    @Override
-    public void drawPoints(float[] pts, Paint paint) {
-        // TODO Auto-generated method stub
-        super.drawPoints(pts, paint);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawPosText(char[], int, int, float[], android.graphics.Paint)
-     */
-    @Override
-    public void drawPosText(char[] text, int index, int count, float[] pos, Paint paint) {
-        // TODO Auto-generated method stub
-        super.drawPosText(text, index, count, pos, paint);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawPosText(java.lang.String, float[], android.graphics.Paint)
-     */
-    @Override
-    public void drawPosText(String text, float[] pos, Paint paint) {
-        // TODO Auto-generated method stub
-        super.drawPosText(text, pos, paint);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawTextOnPath(char[], int, int, android.graphics.Path, float, float, android.graphics.Paint)
-     */
-    @Override
-    public void drawTextOnPath(char[] text, int index, int count, Path path, float offset,
-            float offset2, Paint paint) {
-        // TODO Auto-generated method stub
-        super.drawTextOnPath(text, index, count, path, offset, offset2, paint);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawTextOnPath(java.lang.String, android.graphics.Path, float, float, android.graphics.Paint)
-     */
-    @Override
-    public void drawTextOnPath(String text, Path path, float offset, float offset2, Paint paint) {
-        // TODO Auto-generated method stub
-        super.drawTextOnPath(text, path, offset, offset2, paint);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#drawVertices(android.graphics.Canvas.VertexMode, int, float[], int, float[], int, int[], int, short[], int, int, android.graphics.Paint)
-     */
-    @Override
-    public void drawVertices(VertexMode mode, int vertexCount, float[] verts, int vertOffset,
-            float[] texs, int texOffset, int[] colors, int colorOffset, short[] indices,
-            int indexOffset, int indexCount, Paint paint) {
-        // TODO Auto-generated method stub
-        super.drawVertices(mode, vertexCount, verts, vertOffset, texs, texOffset, colors, colorOffset,
-                indices, indexOffset, indexCount, paint);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#getDrawFilter()
-     */
-    @Override
-    public DrawFilter getDrawFilter() {
-        // TODO Auto-generated method stub
-        return super.getDrawFilter();
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#getGL()
-     */
-    @Override
-    public GL getGL() {
-        // TODO Auto-generated method stub
-        return super.getGL();
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#getMatrix()
-     */
-    @Override
-    public Matrix getMatrix() {
-        // TODO Auto-generated method stub
-        return super.getMatrix();
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#getMatrix(android.graphics.Matrix)
-     */
-    @Override
-    public void getMatrix(Matrix ctm) {
-        // TODO Auto-generated method stub
-        super.getMatrix(ctm);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#isOpaque()
-     */
-    @Override
-    public boolean isOpaque() {
-        // TODO Auto-generated method stub
-        return super.isOpaque();
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#saveLayer(float, float, float, float, android.graphics.Paint, int)
-     */
-    @Override
-    public int saveLayer(float left, float top, float right, float bottom, Paint paint,
-            int saveFlags) {
-        // TODO Auto-generated method stub
-        return super.saveLayer(left, top, right, bottom, paint, saveFlags);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#saveLayer(android.graphics.RectF, android.graphics.Paint, int)
-     */
-    @Override
-    public int saveLayer(RectF bounds, Paint paint, int saveFlags) {
-        // TODO Auto-generated method stub
-        return super.saveLayer(bounds, paint, saveFlags);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#saveLayerAlpha(float, float, float, float, int, int)
-     */
-    @Override
-    public int saveLayerAlpha(float left, float top, float right, float bottom, int alpha,
-            int saveFlags) {
-        // TODO Auto-generated method stub
-        return super.saveLayerAlpha(left, top, right, bottom, alpha, saveFlags);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#saveLayerAlpha(android.graphics.RectF, int, int)
-     */
-    @Override
-    public int saveLayerAlpha(RectF bounds, int alpha, int saveFlags) {
-        // TODO Auto-generated method stub
-        return super.saveLayerAlpha(bounds, alpha, saveFlags);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#setDrawFilter(android.graphics.DrawFilter)
-     */
-    @Override
-    public void setDrawFilter(DrawFilter filter) {
-        // TODO Auto-generated method stub
-        super.setDrawFilter(filter);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#setViewport(int, int)
-     */
-    @Override
-    public void setViewport(int width, int height) {
-        // TODO Auto-generated method stub
-        super.setViewport(width, height);
-    }
-
-    /* (non-Javadoc)
-     * @see android.graphics.Canvas#skew(float, float)
-     */
-    @Override
-    public void skew(float sx, float sy) {
-        // TODO Auto-generated method stub
-        super.skew(sx, sy);
-    }
-
-
-
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Canvas_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Canvas_Delegate.java
new file mode 100644
index 0000000..5623526
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/Canvas_Delegate.java
@@ -0,0 +1,1357 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.layoutlib.bridge.impl.GcSnapshot;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import android.graphics.Bitmap.Config;
+import android.graphics.Paint_Delegate.FontInfo;
+import android.text.TextUtils;
+
+import java.awt.Color;
+import java.awt.Composite;
+import java.awt.Graphics2D;
+import java.awt.Rectangle;
+import java.awt.RenderingHints;
+import java.awt.Shape;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Arc2D;
+import java.awt.image.BufferedImage;
+import java.util.List;
+
+
+/**
+ * Delegate implementing the native methods of android.graphics.Canvas
+ *
+ * Through the layoutlib_create tool, the original native methods of Canvas have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original Canvas class.
+ *
+ * @see DelegateManager
+ *
+ */
+public final class Canvas_Delegate {
+
+    // ---- delegate manager ----
+    private static final DelegateManager<Canvas_Delegate> sManager =
+            new DelegateManager<Canvas_Delegate>(Canvas_Delegate.class);
+
+    // ---- delegate helper data ----
+
+    private final static boolean[] sBoolOut = new boolean[1];
+
+    // ---- delegate data ----
+    private Bitmap_Delegate mBitmap;
+    private GcSnapshot mSnapshot;
+
+    private DrawFilter_Delegate mDrawFilter = null;
+
+    // ---- Public Helper methods ----
+
+    /**
+     * Returns the native delegate associated to a given {@link Canvas} object.
+     */
+    public static Canvas_Delegate getDelegate(Canvas canvas) {
+        return sManager.getDelegate(canvas.mNativeCanvas);
+    }
+
+    /**
+     * Returns the native delegate associated to a given an int referencing a {@link Canvas} object.
+     */
+    public static Canvas_Delegate getDelegate(int native_canvas) {
+        return sManager.getDelegate(native_canvas);
+    }
+
+    /**
+     * Returns the current {@link Graphics2D} used to draw.
+     */
+    public GcSnapshot getSnapshot() {
+        return mSnapshot;
+    }
+
+    /**
+     * Returns the {@link DrawFilter} delegate or null if none have been set.
+     *
+     * @return the delegate or null.
+     */
+    public DrawFilter_Delegate getDrawFilter() {
+        return mDrawFilter;
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static boolean isOpaque(Canvas thisCanvas) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(thisCanvas.mNativeCanvas);
+        if (canvasDelegate == null) {
+            return false;
+        }
+
+        return canvasDelegate.mBitmap.getConfig() == Config.RGB_565;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int getWidth(Canvas thisCanvas) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(thisCanvas.mNativeCanvas);
+        if (canvasDelegate == null) {
+            return 0;
+        }
+
+        return canvasDelegate.mBitmap.getImage().getWidth();
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int getHeight(Canvas thisCanvas) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(thisCanvas.mNativeCanvas);
+        if (canvasDelegate == null) {
+            return 0;
+        }
+
+        return canvasDelegate.mBitmap.getImage().getHeight();
+    }
+
+    @LayoutlibDelegate
+   /*package*/ static void translate(Canvas thisCanvas, float dx, float dy) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(thisCanvas.mNativeCanvas);
+        if (canvasDelegate == null) {
+            return;
+        }
+
+        canvasDelegate.getSnapshot().translate(dx, dy);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void rotate(Canvas thisCanvas, float degrees) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(thisCanvas.mNativeCanvas);
+        if (canvasDelegate == null) {
+            return;
+        }
+
+        canvasDelegate.getSnapshot().rotate(Math.toRadians(degrees));
+    }
+
+    @LayoutlibDelegate
+   /*package*/ static void scale(Canvas thisCanvas, float sx, float sy) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(thisCanvas.mNativeCanvas);
+        if (canvasDelegate == null) {
+            return;
+        }
+
+        canvasDelegate.getSnapshot().scale(sx, sy);
+    }
+
+    @LayoutlibDelegate
+   /*package*/ static void skew(Canvas thisCanvas, float kx, float ky) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(thisCanvas.mNativeCanvas);
+        if (canvasDelegate == null) {
+            return;
+        }
+
+        // get the current top graphics2D object.
+        GcSnapshot g = canvasDelegate.getSnapshot();
+
+        // get its current matrix
+        AffineTransform currentTx = g.getTransform();
+        // get the AffineTransform for the given skew.
+        float[] mtx = Matrix_Delegate.getSkew(kx, ky);
+        AffineTransform matrixTx = Matrix_Delegate.getAffineTransform(mtx);
+
+        // combine them so that the given matrix is applied after.
+        currentTx.preConcatenate(matrixTx);
+
+        // give it to the graphics2D as a new matrix replacing all previous transform
+        g.setTransform(currentTx);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean clipRect(Canvas thisCanvas, RectF rect) {
+        return clipRect(thisCanvas, rect.left, rect.top, rect.right, rect.bottom);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean clipRect(Canvas thisCanvas, Rect rect) {
+        return clipRect(thisCanvas, (float) rect.left, (float) rect.top,
+                (float) rect.right, (float) rect.bottom);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean clipRect(Canvas thisCanvas, float left, float top, float right,
+            float bottom) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(thisCanvas.mNativeCanvas);
+        if (canvasDelegate == null) {
+            return false;
+        }
+
+        return canvasDelegate.clipRect(left, top, right, bottom, Region.Op.INTERSECT.nativeInt);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean clipRect(Canvas thisCanvas, int left, int top, int right,
+            int bottom) {
+
+        return clipRect(thisCanvas, (float) left, (float) top, (float) right, (float) bottom);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int save(Canvas thisCanvas) {
+        return save(thisCanvas, Canvas.MATRIX_SAVE_FLAG | Canvas.CLIP_SAVE_FLAG);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int save(Canvas thisCanvas, int saveFlags) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(thisCanvas.mNativeCanvas);
+        if (canvasDelegate == null) {
+            return 0;
+        }
+
+        return canvasDelegate.save(saveFlags);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void restore(Canvas thisCanvas) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(thisCanvas.mNativeCanvas);
+        if (canvasDelegate == null) {
+            return;
+        }
+
+        canvasDelegate.restore();
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int getSaveCount(Canvas thisCanvas) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(thisCanvas.mNativeCanvas);
+        if (canvasDelegate == null) {
+            return 0;
+        }
+
+        return canvasDelegate.getSnapshot().size();
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void restoreToCount(Canvas thisCanvas, int saveCount) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(thisCanvas.mNativeCanvas);
+        if (canvasDelegate == null) {
+            return;
+        }
+
+        canvasDelegate.restoreTo(saveCount);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void drawText(Canvas thisCanvas,
+            String text, float x, float y, Paint paint) {
+        native_drawText(thisCanvas.mNativeCanvas, text, 0, text.length(), x, y,
+                paint.mNativePaint);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void drawPoints(Canvas thisCanvas, float[] pts, int offset, int count,
+            Paint paint) {
+        // FIXME
+        Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
+                "Canvas.drawPoint is not supported.", null, null /*data*/);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void drawPoint(Canvas thisCanvas, float x, float y, Paint paint) {
+        // FIXME
+        Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
+                "Canvas.drawPoint is not supported.", null, null /*data*/);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void drawLines(Canvas thisCanvas,
+            final float[] pts, final int offset, final int count,
+            Paint paint) {
+        draw(thisCanvas.mNativeCanvas, paint.mNativePaint, false /*compositeOnly*/,
+                false /*forceSrcMode*/, new GcSnapshot.Drawable() {
+                    public void draw(Graphics2D graphics, Paint_Delegate paintDelegate) {
+                        for (int i = 0 ; i < count ; i += 4) {
+                            graphics.drawLine((int)pts[i + offset], (int)pts[i + offset + 1],
+                                    (int)pts[i + offset + 2], (int)pts[i + offset + 3]);
+                        }
+                    }
+                });
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void freeCaches() {
+        // nothing to be done here.
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int initRaster(int nativeBitmapOrZero) {
+        if (nativeBitmapOrZero > 0) {
+            // get the Bitmap from the int
+            Bitmap_Delegate bitmapDelegate = Bitmap_Delegate.getDelegate(nativeBitmapOrZero);
+
+            // create a new Canvas_Delegate with the given bitmap and return its new native int.
+            Canvas_Delegate newDelegate = new Canvas_Delegate(bitmapDelegate);
+
+            return sManager.addNewDelegate(newDelegate);
+        }
+
+        // create a new Canvas_Delegate and return its new native int.
+        Canvas_Delegate newDelegate = new Canvas_Delegate();
+
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int initGL() {
+        // not supported.
+        return 0;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_setBitmap(int nativeCanvas, int bitmap) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(nativeCanvas);
+        if (canvasDelegate == null) {
+            return;
+        }
+
+        // get the delegate from the native int.
+        Bitmap_Delegate bitmapDelegate = Bitmap_Delegate.getDelegate(bitmap);
+        if (bitmapDelegate == null) {
+            return;
+        }
+
+        canvasDelegate.setBitmap(bitmapDelegate);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeSetViewport(int nCanvas, int w, int h) {
+        // only useful in GL which is not supported, so no need to do anything.
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_saveLayer(int nativeCanvas, RectF bounds,
+                                               int paint, int layerFlags) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(nativeCanvas);
+        if (canvasDelegate == null) {
+            return 0;
+        }
+
+        Paint_Delegate paintDelegate = Paint_Delegate.getDelegate(paint);
+        if (paintDelegate == null) {
+            return 0;
+        }
+
+        return canvasDelegate.saveLayer(bounds, paintDelegate, layerFlags);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_saveLayer(int nativeCanvas, float l,
+                                               float t, float r, float b,
+                                               int paint, int layerFlags) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(nativeCanvas);
+        if (canvasDelegate == null) {
+            return 0;
+        }
+
+        Paint_Delegate paintDelegate = Paint_Delegate.getDelegate(paint);
+        if (paintDelegate == null) {
+            return 0;
+        }
+
+        return canvasDelegate.saveLayer(new RectF(l, t, r, b),
+                paintDelegate, layerFlags);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_saveLayerAlpha(int nativeCanvas,
+                                                    RectF bounds, int alpha,
+                                                    int layerFlags) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(nativeCanvas);
+        if (canvasDelegate == null) {
+            return 0;
+        }
+
+        return canvasDelegate.saveLayerAlpha(bounds, alpha, layerFlags);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_saveLayerAlpha(int nativeCanvas, float l,
+                                                    float t, float r, float b,
+                                                    int alpha, int layerFlags) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(nativeCanvas);
+        if (canvasDelegate == null) {
+            return 0;
+        }
+
+        return canvasDelegate.saveLayerAlpha(new RectF(l, t, r, b), alpha, layerFlags);
+    }
+
+
+    @LayoutlibDelegate
+    /*package*/ static void native_concat(int nCanvas, int nMatrix) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(nCanvas);
+        if (canvasDelegate == null) {
+            return;
+        }
+
+        Matrix_Delegate matrixDelegate = Matrix_Delegate.getDelegate(nMatrix);
+        if (matrixDelegate == null) {
+            return;
+        }
+
+        // get the current top graphics2D object.
+        GcSnapshot snapshot = canvasDelegate.getSnapshot();
+
+        // get its current matrix
+        AffineTransform currentTx = snapshot.getTransform();
+        // get the AffineTransform of the given matrix
+        AffineTransform matrixTx = matrixDelegate.getAffineTransform();
+
+        // combine them so that the given matrix is applied after.
+        currentTx.concatenate(matrixTx);
+
+        // give it to the graphics2D as a new matrix replacing all previous transform
+        snapshot.setTransform(currentTx);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_setMatrix(int nCanvas, int nMatrix) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(nCanvas);
+        if (canvasDelegate == null) {
+            return;
+        }
+
+        Matrix_Delegate matrixDelegate = Matrix_Delegate.getDelegate(nMatrix);
+        if (matrixDelegate == null) {
+            return;
+        }
+
+        // get the current top graphics2D object.
+        GcSnapshot snapshot = canvasDelegate.getSnapshot();
+
+        // get the AffineTransform of the given matrix
+        AffineTransform matrixTx = matrixDelegate.getAffineTransform();
+
+        // give it to the graphics2D as a new matrix replacing all previous transform
+        snapshot.setTransform(matrixTx);
+
+        if (matrixDelegate.hasPerspective()) {
+            assert false;
+            Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_AFFINE,
+                    "android.graphics.Canvas#setMatrix(android.graphics.Matrix) only " +
+                    "supports affine transformations.", null, null /*data*/);
+        }
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_clipRect(int nCanvas,
+                                                  float left, float top,
+                                                  float right, float bottom,
+                                                  int regionOp) {
+
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(nCanvas);
+        if (canvasDelegate == null) {
+            return false;
+        }
+
+        return canvasDelegate.clipRect(left, top, right, bottom, regionOp);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_clipPath(int nativeCanvas,
+                                                  int nativePath,
+                                                  int regionOp) {
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(nativeCanvas);
+        if (canvasDelegate == null) {
+            return true;
+        }
+
+        Path_Delegate pathDelegate = Path_Delegate.getDelegate(nativePath);
+        if (pathDelegate == null) {
+            return true;
+        }
+
+        return canvasDelegate.mSnapshot.clip(pathDelegate.getJavaShape(), regionOp);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_clipRegion(int nativeCanvas,
+                                                    int nativeRegion,
+                                                    int regionOp) {
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(nativeCanvas);
+        if (canvasDelegate == null) {
+            return true;
+        }
+
+        Region_Delegate region = Region_Delegate.getDelegate(nativeRegion);
+        if (region == null) {
+            return true;
+        }
+
+        return canvasDelegate.mSnapshot.clip(region.getJavaArea(), regionOp);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeSetDrawFilter(int nativeCanvas, int nativeFilter) {
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(nativeCanvas);
+        if (canvasDelegate == null) {
+            return;
+        }
+
+        canvasDelegate.mDrawFilter = DrawFilter_Delegate.getDelegate(nativeFilter);
+
+        if (canvasDelegate.mDrawFilter != null &&
+                canvasDelegate.mDrawFilter.isSupported() == false) {
+            Bridge.getLog().fidelityWarning(LayoutLog.TAG_DRAWFILTER,
+                    canvasDelegate.mDrawFilter.getSupportMessage(), null, null /*data*/);
+        }
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_getClipBounds(int nativeCanvas,
+                                                       Rect bounds) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(nativeCanvas);
+        if (canvasDelegate == null) {
+            return false;
+        }
+
+        Rectangle rect = canvasDelegate.getSnapshot().getClip().getBounds();
+        if (rect != null && rect.isEmpty() == false) {
+            bounds.left = rect.x;
+            bounds.top = rect.y;
+            bounds.right = rect.x + rect.width;
+            bounds.bottom = rect.y + rect.height;
+            return true;
+        }
+
+        return false;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_getCTM(int canvas, int matrix) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(canvas);
+        if (canvasDelegate == null) {
+            return;
+        }
+
+        Matrix_Delegate matrixDelegate = Matrix_Delegate.getDelegate(matrix);
+        if (matrixDelegate == null) {
+            return;
+        }
+
+        AffineTransform transform = canvasDelegate.getSnapshot().getTransform();
+        matrixDelegate.set(Matrix_Delegate.makeValues(transform));
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_quickReject(int nativeCanvas,
+                                                     RectF rect,
+                                                     int native_edgeType) {
+        // FIXME properly implement quickReject
+        return false;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_quickReject(int nativeCanvas,
+                                                     int path,
+                                                     int native_edgeType) {
+        // FIXME properly implement quickReject
+        return false;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_quickReject(int nativeCanvas,
+                                                     float left, float top,
+                                                     float right, float bottom,
+                                                     int native_edgeType) {
+        // FIXME properly implement quickReject
+        return false;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawRGB(int nativeCanvas, int r, int g, int b) {
+        native_drawColor(nativeCanvas, 0xFF000000 | r << 16 | (g&0xFF) << 8 | (b&0xFF),
+                PorterDuff.Mode.SRC_OVER.nativeInt);
+
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawARGB(int nativeCanvas, int a, int r, int g, int b) {
+        native_drawColor(nativeCanvas, a << 24 | (r&0xFF) << 16 | (g&0xFF) << 8 | (b&0xFF),
+                PorterDuff.Mode.SRC_OVER.nativeInt);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawColor(int nativeCanvas, int color) {
+        native_drawColor(nativeCanvas, color, PorterDuff.Mode.SRC_OVER.nativeInt);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawColor(int nativeCanvas, final int color, final int mode) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(nativeCanvas);
+        if (canvasDelegate == null) {
+            return;
+        }
+
+        final int w = canvasDelegate.mBitmap.getImage().getWidth();
+        final int h = canvasDelegate.mBitmap.getImage().getHeight();
+        draw(nativeCanvas, new GcSnapshot.Drawable() {
+
+            public void draw(Graphics2D graphics, Paint_Delegate paint) {
+                // reset its transform just in case
+                graphics.setTransform(new AffineTransform());
+
+                // set the color
+                graphics.setColor(new Color(color, true /*alpha*/));
+
+                Composite composite = PorterDuffXfermode_Delegate.getComposite(
+                        PorterDuffXfermode_Delegate.getPorterDuffMode(mode), 0xFF);
+                if (composite != null) {
+                    graphics.setComposite(composite);
+                }
+
+                graphics.fillRect(0, 0, w, h);
+            }
+        });
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawPaint(int nativeCanvas, int paint) {
+        // FIXME
+        Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
+                "Canvas.drawPaint is not supported.", null, null /*data*/);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawLine(int nativeCanvas,
+            final float startX, final float startY, final float stopX, final float stopY,
+            int paint) {
+
+        draw(nativeCanvas, paint, false /*compositeOnly*/, false /*forceSrcMode*/,
+                new GcSnapshot.Drawable() {
+                    public void draw(Graphics2D graphics, Paint_Delegate paintDelegate) {
+                        graphics.drawLine((int)startX, (int)startY, (int)stopX, (int)stopY);
+                    }
+        });
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawRect(int nativeCanvas, RectF rect,
+                                               int paint) {
+        native_drawRect(nativeCanvas, rect.left, rect.top, rect.right, rect.bottom, paint);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawRect(int nativeCanvas,
+            final float left, final float top, final float right, final float bottom, int paint) {
+
+        draw(nativeCanvas, paint, false /*compositeOnly*/, false /*forceSrcMode*/,
+                new GcSnapshot.Drawable() {
+                    public void draw(Graphics2D graphics, Paint_Delegate paintDelegate) {
+                        int style = paintDelegate.getStyle();
+
+                        // draw
+                        if (style == Paint.Style.FILL.nativeInt ||
+                                style == Paint.Style.FILL_AND_STROKE.nativeInt) {
+                            graphics.fillRect((int)left, (int)top,
+                                    (int)(right-left), (int)(bottom-top));
+                        }
+
+                        if (style == Paint.Style.STROKE.nativeInt ||
+                                style == Paint.Style.FILL_AND_STROKE.nativeInt) {
+                            graphics.drawRect((int)left, (int)top,
+                                    (int)(right-left), (int)(bottom-top));
+                        }
+                    }
+        });
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawOval(int nativeCanvas, final RectF oval, int paint) {
+        if (oval.right > oval.left && oval.bottom > oval.top) {
+            draw(nativeCanvas, paint, false /*compositeOnly*/, false /*forceSrcMode*/,
+                    new GcSnapshot.Drawable() {
+                        public void draw(Graphics2D graphics, Paint_Delegate paintDelegate) {
+                            int style = paintDelegate.getStyle();
+
+                            // draw
+                            if (style == Paint.Style.FILL.nativeInt ||
+                                    style == Paint.Style.FILL_AND_STROKE.nativeInt) {
+                                graphics.fillOval((int)oval.left, (int)oval.top,
+                                        (int)oval.width(), (int)oval.height());
+                            }
+
+                            if (style == Paint.Style.STROKE.nativeInt ||
+                                    style == Paint.Style.FILL_AND_STROKE.nativeInt) {
+                                graphics.drawOval((int)oval.left, (int)oval.top,
+                                        (int)oval.width(), (int)oval.height());
+                            }
+                        }
+            });
+        }
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawCircle(int nativeCanvas,
+            float cx, float cy, float radius, int paint) {
+        native_drawOval(nativeCanvas,
+                new RectF(cx - radius, cy - radius, radius, radius),
+                paint);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawArc(int nativeCanvas,
+            final RectF oval, final float startAngle, final float sweep,
+            final boolean useCenter, int paint) {
+        if (oval.right > oval.left && oval.bottom > oval.top) {
+            draw(nativeCanvas, paint, false /*compositeOnly*/, false /*forceSrcMode*/,
+                    new GcSnapshot.Drawable() {
+                        public void draw(Graphics2D graphics, Paint_Delegate paintDelegate) {
+                            int style = paintDelegate.getStyle();
+
+                            Arc2D.Float arc = new Arc2D.Float(
+                                    oval.left, oval.top, oval.width(), oval.height(),
+                                    -startAngle, -sweep,
+                                    useCenter ? Arc2D.PIE : Arc2D.OPEN);
+
+                            // draw
+                            if (style == Paint.Style.FILL.nativeInt ||
+                                    style == Paint.Style.FILL_AND_STROKE.nativeInt) {
+                                graphics.fill(arc);
+                            }
+
+                            if (style == Paint.Style.STROKE.nativeInt ||
+                                    style == Paint.Style.FILL_AND_STROKE.nativeInt) {
+                                graphics.draw(arc);
+                            }
+                        }
+            });
+        }
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawRoundRect(int nativeCanvas,
+            final RectF rect, final float rx, final float ry, int paint) {
+
+        draw(nativeCanvas, paint, false /*compositeOnly*/, false /*forceSrcMode*/,
+                new GcSnapshot.Drawable() {
+                    public void draw(Graphics2D graphics, Paint_Delegate paintDelegate) {
+                        int style = paintDelegate.getStyle();
+
+                        // draw
+                        if (style == Paint.Style.FILL.nativeInt ||
+                                style == Paint.Style.FILL_AND_STROKE.nativeInt) {
+                            graphics.fillRoundRect(
+                                    (int)rect.left, (int)rect.top,
+                                    (int)rect.width(), (int)rect.height(),
+                                    (int)rx, (int)ry);
+                        }
+
+                        if (style == Paint.Style.STROKE.nativeInt ||
+                                style == Paint.Style.FILL_AND_STROKE.nativeInt) {
+                            graphics.drawRoundRect(
+                                    (int)rect.left, (int)rect.top,
+                                    (int)rect.width(), (int)rect.height(),
+                                    (int)rx, (int)ry);
+                        }
+                    }
+        });
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawPath(int nativeCanvas, int path, int paint) {
+        final Path_Delegate pathDelegate = Path_Delegate.getDelegate(path);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        draw(nativeCanvas, paint, false /*compositeOnly*/, false /*forceSrcMode*/,
+                new GcSnapshot.Drawable() {
+                    public void draw(Graphics2D graphics, Paint_Delegate paintDelegate) {
+                        Shape shape = pathDelegate.getJavaShape();
+                        int style = paintDelegate.getStyle();
+
+                        if (style == Paint.Style.FILL.nativeInt ||
+                                style == Paint.Style.FILL_AND_STROKE.nativeInt) {
+                            graphics.fill(shape);
+                        }
+
+                        if (style == Paint.Style.STROKE.nativeInt ||
+                                style == Paint.Style.FILL_AND_STROKE.nativeInt) {
+                            graphics.draw(shape);
+                        }
+                    }
+        });
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawBitmap(Canvas thisCanvas, int nativeCanvas, int bitmap,
+                                                 float left, float top,
+                                                 int nativePaintOrZero,
+                                                 int canvasDensity,
+                                                 int screenDensity,
+                                                 int bitmapDensity) {
+        // get the delegate from the native int.
+        Bitmap_Delegate bitmapDelegate = Bitmap_Delegate.getDelegate(bitmap);
+        if (bitmapDelegate == null) {
+            return;
+        }
+
+        BufferedImage image = bitmapDelegate.getImage();
+        float right = left + image.getWidth();
+        float bottom = top + image.getHeight();
+
+        drawBitmap(nativeCanvas, bitmapDelegate, nativePaintOrZero,
+                0, 0, image.getWidth(), image.getHeight(),
+                (int)left, (int)top, (int)right, (int)bottom);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawBitmap(Canvas thisCanvas, int nativeCanvas, int bitmap,
+                                                 Rect src, RectF dst,
+                                                 int nativePaintOrZero,
+                                                 int screenDensity,
+                                                 int bitmapDensity) {
+        // get the delegate from the native int.
+        Bitmap_Delegate bitmapDelegate = Bitmap_Delegate.getDelegate(bitmap);
+        if (bitmapDelegate == null) {
+            return;
+        }
+
+        BufferedImage image = bitmapDelegate.getImage();
+
+        if (src == null) {
+            drawBitmap(nativeCanvas, bitmapDelegate, nativePaintOrZero,
+                    0, 0, image.getWidth(), image.getHeight(),
+                    (int)dst.left, (int)dst.top, (int)dst.right, (int)dst.bottom);
+        } else {
+            drawBitmap(nativeCanvas, bitmapDelegate, nativePaintOrZero,
+                    src.left, src.top, src.width(), src.height(),
+                    (int)dst.left, (int)dst.top, (int)dst.right, (int)dst.bottom);
+        }
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawBitmap(int nativeCanvas, int bitmap,
+                                                 Rect src, Rect dst,
+                                                 int nativePaintOrZero,
+                                                 int screenDensity,
+                                                 int bitmapDensity) {
+        // get the delegate from the native int.
+        Bitmap_Delegate bitmapDelegate = Bitmap_Delegate.getDelegate(bitmap);
+        if (bitmapDelegate == null) {
+            return;
+        }
+
+        BufferedImage image = bitmapDelegate.getImage();
+
+        if (src == null) {
+            drawBitmap(nativeCanvas, bitmapDelegate, nativePaintOrZero,
+                    0, 0, image.getWidth(), image.getHeight(),
+                    dst.left, dst.top, dst.right, dst.bottom);
+        } else {
+            drawBitmap(nativeCanvas, bitmapDelegate, nativePaintOrZero,
+                    src.left, src.top, src.width(), src.height(),
+                    dst.left, dst.top, dst.right, dst.bottom);
+        }
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawBitmap(int nativeCanvas, int[] colors,
+                                                int offset, int stride, final float x,
+                                                 final float y, int width, int height,
+                                                 boolean hasAlpha,
+                                                 int nativePaintOrZero) {
+
+        // create a temp BufferedImage containing the content.
+        final BufferedImage image = new BufferedImage(width, height,
+                hasAlpha ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB);
+        image.setRGB(0, 0, width, height, colors, offset, stride);
+
+        draw(nativeCanvas, nativePaintOrZero, true /*compositeOnly*/, false /*forceSrcMode*/,
+                new GcSnapshot.Drawable() {
+                    public void draw(Graphics2D graphics, Paint_Delegate paint) {
+                        if (paint != null && paint.isFilterBitmap()) {
+                            graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
+                                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
+                        }
+
+                        graphics.drawImage(image, (int) x, (int) y, null);
+                    }
+        });
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeDrawBitmapMatrix(int nCanvas, int nBitmap,
+                                                      int nMatrix, int nPaint) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(nCanvas);
+        if (canvasDelegate == null) {
+            return;
+        }
+
+        // get the delegate from the native int, which can be null
+        Paint_Delegate paintDelegate = Paint_Delegate.getDelegate(nPaint);
+
+        // get the delegate from the native int.
+        Bitmap_Delegate bitmapDelegate = Bitmap_Delegate.getDelegate(nBitmap);
+        if (bitmapDelegate == null) {
+            return;
+        }
+
+        final BufferedImage image = getImageToDraw(bitmapDelegate, paintDelegate, sBoolOut);
+
+        Matrix_Delegate matrixDelegate = Matrix_Delegate.getDelegate(nMatrix);
+        if (matrixDelegate == null) {
+            return;
+        }
+
+        final AffineTransform mtx = matrixDelegate.getAffineTransform();
+
+        canvasDelegate.getSnapshot().draw(new GcSnapshot.Drawable() {
+                public void draw(Graphics2D graphics, Paint_Delegate paint) {
+                    if (paint != null && paint.isFilterBitmap()) {
+                        graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
+                                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
+                    }
+
+                    //FIXME add support for canvas, screen and bitmap densities.
+                    graphics.drawImage(image, mtx, null);
+                }
+        }, paintDelegate, true /*compositeOnly*/, false /*forceSrcMode*/);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeDrawBitmapMesh(int nCanvas, int nBitmap,
+            int meshWidth, int meshHeight, float[] verts, int vertOffset, int[] colors,
+            int colorOffset, int nPaint) {
+        // FIXME
+        Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
+                "Canvas.drawBitmapMesh is not supported.", null, null /*data*/);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeDrawVertices(int nCanvas, int mode, int n,
+            float[] verts, int vertOffset,
+            float[] texs, int texOffset,
+            int[] colors, int colorOffset,
+            short[] indices, int indexOffset,
+            int indexCount, int nPaint) {
+        // FIXME
+        Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
+                "Canvas.drawVertices is not supported.", null, null /*data*/);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawText(int nativeCanvas,
+            final char[] text, final int index, final int count,
+            final float startX, final float startY, int paint) {
+        draw(nativeCanvas, paint, false /*compositeOnly*/, false /*forceSrcMode*/,
+                new GcSnapshot.Drawable() {
+            public void draw(Graphics2D graphics, Paint_Delegate paintDelegate) {
+                // WARNING: the logic in this method is similar to Paint_Delegate.measureText.
+                // Any change to this method should be reflected in Paint.measureText
+                // Paint.TextAlign indicates how the text is positioned relative to X.
+                // LEFT is the default and there's nothing to do.
+                float x = startX;
+                float y = startY;
+                if (paintDelegate.getTextAlign() != Paint.Align.LEFT.nativeInt) {
+                    float m = paintDelegate.measureText(text, index, count);
+                    if (paintDelegate.getTextAlign() == Paint.Align.CENTER.nativeInt) {
+                        x -= m / 2;
+                    } else if (paintDelegate.getTextAlign() == Paint.Align.RIGHT.nativeInt) {
+                        x -= m;
+                    }
+                }
+
+                List<FontInfo> fonts = paintDelegate.getFonts();
+
+                if (fonts.size() > 0) {
+                    FontInfo mainFont = fonts.get(0);
+                    int i = index;
+                    int lastIndex = index + count;
+                    while (i < lastIndex) {
+                        // always start with the main font.
+                        int upTo = mainFont.mFont.canDisplayUpTo(text, i, lastIndex);
+                        if (upTo == -1) {
+                            // draw all the rest and exit.
+                            graphics.setFont(mainFont.mFont);
+                            graphics.drawChars(text, i, lastIndex - i, (int)x, (int)y);
+                            return;
+                        } else if (upTo > 0) {
+                            // draw what's possible
+                            graphics.setFont(mainFont.mFont);
+                            graphics.drawChars(text, i, upTo - i, (int)x, (int)y);
+
+                            // compute the width that was drawn to increase x
+                            x += mainFont.mMetrics.charsWidth(text, i, upTo - i);
+
+                            // move index to the first non displayed char.
+                            i = upTo;
+
+                            // don't call continue at this point. Since it is certain the main font
+                            // cannot display the font a index upTo (now ==i), we move on to the
+                            // fallback fonts directly.
+                        }
+
+                        // no char supported, attempt to read the next char(s) with the
+                        // fallback font. In this case we only test the first character
+                        // and then go back to test with the main font.
+                        // Special test for 2-char characters.
+                        boolean foundFont = false;
+                        for (int f = 1 ; f < fonts.size() ; f++) {
+                            FontInfo fontInfo = fonts.get(f);
+
+                            // need to check that the font can display the character. We test
+                            // differently if the char is a high surrogate.
+                            int charCount = Character.isHighSurrogate(text[i]) ? 2 : 1;
+                            upTo = fontInfo.mFont.canDisplayUpTo(text, i, i + charCount);
+                            if (upTo == -1) {
+                                // draw that char
+                                graphics.setFont(fontInfo.mFont);
+                                graphics.drawChars(text, i, charCount, (int)x, (int)y);
+
+                                // update x
+                                x += fontInfo.mMetrics.charsWidth(text, i, charCount);
+
+                                // update the index in the text, and move on
+                                i += charCount;
+                                foundFont = true;
+                                break;
+
+                            }
+                        }
+
+                        // in case no font can display the char, display it with the main font.
+                        // (it'll put a square probably)
+                        if (foundFont == false) {
+                            int charCount = Character.isHighSurrogate(text[i]) ? 2 : 1;
+
+                            graphics.setFont(mainFont.mFont);
+                            graphics.drawChars(text, i, charCount, (int)x, (int)y);
+
+                            // measure it to advance x
+                            x += mainFont.mMetrics.charsWidth(text, i, charCount);
+
+                            // and move to the next chars.
+                            i += charCount;
+                        }
+                    }
+                }
+            }
+        });
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawText(int nativeCanvas, String text,
+                                               int start, int end, float x,
+                                               float y, int paint) {
+        int count = end - start;
+        char[] buffer = TemporaryBuffer.obtain(count);
+        TextUtils.getChars(text, start, end, buffer, 0);
+
+        native_drawText(nativeCanvas, buffer, 0, count, x, y, paint);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawPosText(int nativeCanvas,
+                                                  char[] text, int index,
+                                                  int count, float[] pos,
+                                                  int paint) {
+        // FIXME
+        Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
+                "Canvas.drawPosText is not supported.", null, null /*data*/);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawPosText(int nativeCanvas,
+                                                  String text, float[] pos,
+                                                  int paint) {
+        // FIXME
+        Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
+                "Canvas.drawPosText is not supported.", null, null /*data*/);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawTextOnPath(int nativeCanvas,
+                                                     char[] text, int index,
+                                                     int count, int path,
+                                                     float hOffset,
+                                                     float vOffset,
+                                                     int paint) {
+        // FIXME
+        Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
+                "Canvas.drawTextOnPath is not supported.", null, null /*data*/);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawTextOnPath(int nativeCanvas,
+                                                     String text, int path,
+                                                     float hOffset,
+                                                     float vOffset,
+                                                     int paint) {
+        // FIXME
+        Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
+                "Canvas.drawTextOnPath is not supported.", null, null /*data*/);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_drawPicture(int nativeCanvas,
+                                                  int nativePicture) {
+        // FIXME
+        Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
+                "Canvas.drawPicture is not supported.", null, null /*data*/);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void finalizer(int nativeCanvas) {
+        // get the delegate from the native int so that it can be disposed.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(nativeCanvas);
+        if (canvasDelegate == null) {
+            return;
+        }
+
+        canvasDelegate.dispose();
+
+        // remove it from the manager.
+        sManager.removeJavaReferenceFor(nativeCanvas);
+    }
+
+    // ---- Private delegate/helper methods ----
+
+    /**
+     * Executes a {@link GcSnapshot.Drawable} with a given canvas and paint.
+     * <p>Note that the drawable may actually be executed several times if there are
+     * layers involved (see {@link #saveLayer(RectF, int, int)}.
+     */
+    private static void draw(int nCanvas, int nPaint, boolean compositeOnly, boolean forceSrcMode,
+            GcSnapshot.Drawable drawable) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(nCanvas);
+        if (canvasDelegate == null) {
+            return;
+        }
+
+        // get the paint which can be null if nPaint is 0;
+        Paint_Delegate paintDelegate = Paint_Delegate.getDelegate(nPaint);
+
+        canvasDelegate.getSnapshot().draw(drawable, paintDelegate, compositeOnly, forceSrcMode);
+    }
+
+    /**
+     * Executes a {@link GcSnapshot.Drawable} with a given canvas. No paint object will be provided
+     * to {@link GcSnapshot.Drawable#draw(Graphics2D, Paint_Delegate)}.
+     * <p>Note that the drawable may actually be executed several times if there are
+     * layers involved (see {@link #saveLayer(RectF, int, int)}.
+     */
+    private static void draw(int nCanvas, GcSnapshot.Drawable drawable) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(nCanvas);
+        if (canvasDelegate == null) {
+            return;
+        }
+
+        canvasDelegate.mSnapshot.draw(drawable);
+    }
+
+    private Canvas_Delegate(Bitmap_Delegate bitmap) {
+        mSnapshot = GcSnapshot.createDefaultSnapshot(mBitmap = bitmap);
+    }
+
+    private Canvas_Delegate() {
+        mSnapshot = GcSnapshot.createDefaultSnapshot(null /*image*/);
+    }
+
+    /**
+     * Disposes of the {@link Graphics2D} stack.
+     */
+    private void dispose() {
+        mSnapshot.dispose();
+    }
+
+    private int save(int saveFlags) {
+        // get the current save count
+        int count = mSnapshot.size();
+
+        mSnapshot = mSnapshot.save(saveFlags);
+
+        // return the old save count
+        return count;
+    }
+
+    private int saveLayerAlpha(RectF rect, int alpha, int saveFlags) {
+        Paint_Delegate paint = new Paint_Delegate();
+        paint.setAlpha(alpha);
+        return saveLayer(rect, paint, saveFlags);
+    }
+
+    private int saveLayer(RectF rect, Paint_Delegate paint, int saveFlags) {
+        // get the current save count
+        int count = mSnapshot.size();
+
+        mSnapshot = mSnapshot.saveLayer(rect, paint, saveFlags);
+
+        // return the old save count
+        return count;
+    }
+
+    /**
+     * Restores the {@link GcSnapshot} to <var>saveCount</var>
+     * @param saveCount the saveCount
+     */
+    private void restoreTo(int saveCount) {
+        mSnapshot = mSnapshot.restoreTo(saveCount);
+    }
+
+    /**
+     * Restores the {@link GcSnapshot} to <var>saveCount</var>
+     * @param saveCount the saveCount
+     */
+    private void restore() {
+        mSnapshot = mSnapshot.restore();
+    }
+
+    private boolean clipRect(float left, float top, float right, float bottom, int regionOp) {
+        return mSnapshot.clipRect(left, top, right, bottom, regionOp);
+    }
+
+    private void setBitmap(Bitmap_Delegate bitmap) {
+        mBitmap = bitmap;
+        assert mSnapshot.size() == 1;
+        mSnapshot.setBitmap(mBitmap);
+    }
+
+    private static void drawBitmap(
+            int nativeCanvas,
+            Bitmap_Delegate bitmap,
+            int nativePaintOrZero,
+            final int sleft, final int stop, final int sright, final int sbottom,
+            final int dleft, final int dtop, final int dright, final int dbottom) {
+        // get the delegate from the native int.
+        Canvas_Delegate canvasDelegate = sManager.getDelegate(nativeCanvas);
+        if (canvasDelegate == null) {
+            return;
+        }
+
+        // get the paint, which could be null if the int is 0
+        Paint_Delegate paintDelegate = Paint_Delegate.getDelegate(nativePaintOrZero);
+
+        final BufferedImage image = getImageToDraw(bitmap, paintDelegate, sBoolOut);
+
+        draw(nativeCanvas, nativePaintOrZero, true /*compositeOnly*/, sBoolOut[0],
+                new GcSnapshot.Drawable() {
+                    public void draw(Graphics2D graphics, Paint_Delegate paint) {
+                        if (paint != null && paint.isFilterBitmap()) {
+                            graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
+                                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
+                        }
+
+                        //FIXME add support for canvas, screen and bitmap densities.
+                        graphics.drawImage(image, dleft, dtop, dright, dbottom,
+                                sleft, stop, sright, sbottom, null);
+                    }
+        });
+    }
+
+
+    /**
+     * Returns a BufferedImage ready for drawing, based on the bitmap and paint delegate.
+     * The image returns, through a 1-size boolean array, whether the drawing code should
+     * use a SRC composite no matter what the paint says.
+     *
+     * @param bitmap the bitmap
+     * @param paint the paint that will be used to draw
+     * @param forceSrcMode whether the composite will have to be SRC
+     * @return the image to draw
+     */
+    private static BufferedImage getImageToDraw(Bitmap_Delegate bitmap, Paint_Delegate paint,
+            boolean[] forceSrcMode) {
+        BufferedImage image = bitmap.getImage();
+        forceSrcMode[0] = false;
+
+        // if the bitmap config is alpha_8, then we erase all color value from it
+        // before drawing it.
+        if (bitmap.getConfig() == Bitmap.Config.ALPHA_8) {
+            fixAlpha8Bitmap(image);
+        } else if (bitmap.hasAlpha() == false) {
+            // hasAlpha is merely a rendering hint. There can in fact be alpha values
+            // in the bitmap but it should be ignored at drawing time.
+            // There is two ways to do this:
+            // - override the composite to be SRC. This can only be used if the composite
+            //   was going to be SRC or SRC_OVER in the first place
+            // - Create a different bitmap to draw in which all the alpha channel values is set
+            //   to 0xFF.
+            if (paint != null) {
+                Xfermode_Delegate xfermodeDelegate = paint.getXfermode();
+                if (xfermodeDelegate instanceof PorterDuffXfermode_Delegate) {
+                    PorterDuff.Mode mode =
+                        ((PorterDuffXfermode_Delegate)xfermodeDelegate).getMode();
+
+                    forceSrcMode[0] = mode == PorterDuff.Mode.SRC_OVER ||
+                            mode == PorterDuff.Mode.SRC;
+                }
+            }
+
+            // if we can't force SRC mode, then create a temp bitmap of TYPE_RGB
+            if (forceSrcMode[0] == false) {
+                image = Bitmap_Delegate.createCopy(image, BufferedImage.TYPE_INT_RGB, 0xFF);
+            }
+        }
+
+        return image;
+    }
+
+    private static void fixAlpha8Bitmap(final BufferedImage image) {
+        int w = image.getWidth();
+        int h = image.getHeight();
+        int[] argb = new int[w * h];
+        image.getRGB(0, 0, image.getWidth(), image.getHeight(), argb, 0, image.getWidth());
+
+        final int length = argb.length;
+        for (int i = 0 ; i < length; i++) {
+            argb[i] &= 0xFF000000;
+        }
+        image.setRGB(0, 0, w, h, argb, 0, w);
+    }
+}
+
diff --git a/tools/layoutlib/bridge/src/android/graphics/ColorFilter_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/ColorFilter_Delegate.java
new file mode 100644
index 0000000..4c692c2
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/ColorFilter_Delegate.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+/**
+ * Delegate implementing the native methods of android.graphics.ColorFilter
+ *
+ * Through the layoutlib_create tool, the original native methods of ColorFilter have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original ColorFilter class.
+ *
+ * This also serve as a base class for all ColorFilter delegate classes.
+ *
+ * @see DelegateManager
+ *
+ */
+public abstract class ColorFilter_Delegate {
+
+    // ---- delegate manager ----
+    protected static final DelegateManager<ColorFilter_Delegate> sManager =
+            new DelegateManager<ColorFilter_Delegate>(ColorFilter_Delegate.class);
+
+    // ---- delegate helper data ----
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    public static ColorFilter_Delegate getDelegate(int nativeShader) {
+        return sManager.getDelegate(nativeShader);
+    }
+
+    public abstract boolean isSupported();
+    public abstract String getSupportMessage();
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static void finalizer(int native_instance) {
+        sManager.removeJavaReferenceFor(native_instance);
+    }
+
+    // ---- Private delegate/helper methods ----
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/ColorMatrixColorFilter_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/ColorMatrixColorFilter_Delegate.java
new file mode 100644
index 0000000..d4c5b8d
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/ColorMatrixColorFilter_Delegate.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+/**
+ * Delegate implementing the native methods of android.graphics.ColorMatrixColorFilter
+ *
+ * Through the layoutlib_create tool, the original native methods of ColorMatrixColorFilter have
+ * been replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original ColorMatrixColorFilter class.
+ *
+ * Because this extends {@link ColorFilter_Delegate}, there's no need to use a
+ * {@link DelegateManager}, as all the Shader classes will be added to the manager
+ * owned by {@link ColorFilter_Delegate}.
+ *
+ * @see ColorFilter_Delegate
+ *
+ */
+public class ColorMatrixColorFilter_Delegate extends ColorFilter_Delegate {
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public boolean isSupported() {
+        return false;
+    }
+
+    @Override
+    public String getSupportMessage() {
+        return "ColorMatrix Color Filters are not supported.";
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeColorMatrixFilter(float[] array) {
+        ColorMatrixColorFilter_Delegate newDelegate = new ColorMatrixColorFilter_Delegate();
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    // ---- Private delegate/helper methods ----
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/ComposePathEffect_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/ComposePathEffect_Delegate.java
new file mode 100644
index 0000000..7c04a87
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/ComposePathEffect_Delegate.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import java.awt.Stroke;
+
+/**
+ * Delegate implementing the native methods of android.graphics.ComposePathEffect
+ *
+ * Through the layoutlib_create tool, the original native methods of ComposePathEffect have been
+ * replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original ComposePathEffect class.
+ *
+ * Because this extends {@link PathEffect_Delegate}, there's no need to use a {@link DelegateManager},
+ * as all the Shader classes will be added to the manager owned by {@link PathEffect_Delegate}.
+ *
+ * @see PathEffect_Delegate
+ *
+ */
+public class ComposePathEffect_Delegate extends PathEffect_Delegate {
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public Stroke getStroke(Paint_Delegate paint) {
+        // FIXME
+        return null;
+    }
+
+    @Override
+    public boolean isSupported() {
+        return false;
+    }
+
+    @Override
+    public String getSupportMessage() {
+        return "Compose Path Effects are not supported in Layout Preview mode.";
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeCreate(int outerpe, int innerpe) {
+        ComposePathEffect_Delegate newDelegate = new ComposePathEffect_Delegate();
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    // ---- Private delegate/helper methods ----
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/ComposeShader.java b/tools/layoutlib/bridge/src/android/graphics/ComposeShader.java
deleted file mode 100644
index 863d64a..0000000
--- a/tools/layoutlib/bridge/src/android/graphics/ComposeShader.java
+++ /dev/null
@@ -1,53 +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.graphics;
-
-import java.awt.Paint;
-
-/** A subclass of shader that returns the composition of two other shaders, combined by
-    an {@link android.graphics.Xfermode} subclass.
-*/
-public class ComposeShader extends Shader {
-    /** Create a new compose shader, given shaders A, B, and a combining mode.
-        When the mode is applied, it will be given the result from shader A as its
-        "dst", and the result of from shader B as its "src".
-        @param shaderA  The colors from this shader are seen as the "dst" by the mode
-        @param shaderB  The colors from this shader are seen as the "src" by the mode
-        @param mode     The mode that combines the colors from the two shaders. If mode
-                        is null, then SRC_OVER is assumed.
-    */
-    public ComposeShader(Shader shaderA, Shader shaderB, Xfermode mode) {
-        // FIXME Implement shader
-    }
-
-    /** Create a new compose shader, given shaders A, B, and a combining PorterDuff mode.
-        When the mode is applied, it will be given the result from shader A as its
-        "dst", and the result of from shader B as its "src".
-        @param shaderA  The colors from this shader are seen as the "dst" by the mode
-        @param shaderB  The colors from this shader are seen as the "src" by the mode
-        @param mode     The PorterDuff mode that combines the colors from the two shaders.
-    */
-    public ComposeShader(Shader shaderA, Shader shaderB, PorterDuff.Mode mode) {
-        // FIXME Implement shader
-    }
-
-    @Override
-    Paint getJavaPaint() {
-        return null;
-    }
-}
-
diff --git a/tools/layoutlib/bridge/src/android/graphics/ComposeShader_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/ComposeShader_Delegate.java
new file mode 100644
index 0000000..fcc12d7
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/ComposeShader_Delegate.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import java.awt.Paint;
+
+/**
+ * Delegate implementing the native methods of android.graphics.ComposeShader
+ *
+ * Through the layoutlib_create tool, the original native methods of ComposeShader have been
+ * replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original ComposeShader class.
+ *
+ * Because this extends {@link Shader_Delegate}, there's no need to use a {@link DelegateManager},
+ * as all the Shader classes will be added to the manager owned by {@link Shader_Delegate}.
+ *
+ * @see Shader_Delegate
+ *
+ */
+public class ComposeShader_Delegate extends Shader_Delegate {
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public Paint getJavaPaint() {
+        // FIXME
+        return null;
+    }
+
+    @Override
+    public boolean isSupported() {
+        return false;
+    }
+
+    @Override
+    public String getSupportMessage() {
+        return "Compose Shaders are not supported in Layout Preview mode.";
+    }
+
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeCreate1(int native_shaderA, int native_shaderB,
+            int native_mode) {
+        // FIXME not supported yet.
+        ComposeShader_Delegate newDelegate = new ComposeShader_Delegate();
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeCreate2(int native_shaderA, int native_shaderB,
+            int porterDuffMode) {
+        // FIXME not supported yet.
+        ComposeShader_Delegate newDelegate = new ComposeShader_Delegate();
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    // ---- Private delegate/helper methods ----
+
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/CornerPathEffect_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/CornerPathEffect_Delegate.java
new file mode 100644
index 0000000..b0f8168
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/CornerPathEffect_Delegate.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import java.awt.Stroke;
+
+/**
+ * Delegate implementing the native methods of android.graphics.CornerPathEffect
+ *
+ * Through the layoutlib_create tool, the original native methods of CornerPathEffect have been
+ * replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original CornerPathEffect class.
+ *
+ * Because this extends {@link PathEffect_Delegate}, there's no need to use a {@link DelegateManager},
+ * as all the Shader classes will be added to the manager owned by {@link PathEffect_Delegate}.
+ *
+ * @see PathEffect_Delegate
+ *
+ */
+public class CornerPathEffect_Delegate extends PathEffect_Delegate {
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public Stroke getStroke(Paint_Delegate paint) {
+        // FIXME
+        return null;
+    }
+
+    @Override
+    public boolean isSupported() {
+        return false;
+    }
+
+    @Override
+    public String getSupportMessage() {
+        return "Corner Path Effects are not supported in Layout Preview mode.";
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeCreate(float radius) {
+        CornerPathEffect_Delegate newDelegate = new CornerPathEffect_Delegate();
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    // ---- Private delegate/helper methods ----
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/DashPathEffect.java b/tools/layoutlib/bridge/src/android/graphics/DashPathEffect.java
deleted file mode 100644
index 46d4c70..0000000
--- a/tools/layoutlib/bridge/src/android/graphics/DashPathEffect.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-public class DashPathEffect extends PathEffect {
-
-    private final float[] mIntervals;
-    private final float mPhase;
-
-    /**
-     * The intervals array must contain an even number of entries (>=2), with
-     * the even indices specifying the "on" intervals, and the odd indices
-     * specifying the "off" intervals. phase is an offset into the intervals
-     * array (mod the sum of all of the intervals). The intervals array
-     * controls the length of the dashes. The paint's strokeWidth controls the
-     * thickness of the dashes.
-     * Note: this patheffect only affects drawing with the paint's style is set
-     * to STROKE or STROKE_AND_FILL. It is ignored if the drawing is done with
-     * style == FILL.
-     * @param intervals array of ON and OFF distances
-     * @param phase offset into the intervals array
-     */
-    public DashPathEffect(float intervals[], float phase) {
-        if (intervals.length < 2) {
-            throw new ArrayIndexOutOfBoundsException();
-        }
-
-        mIntervals = intervals;
-        mPhase = phase;
-    }
-
-    public float[] getIntervals() {
-        return mIntervals;
-    }
-
-    public float getPhase() {
-        return mPhase;
-    }
-}
-
diff --git a/tools/layoutlib/bridge/src/android/graphics/DashPathEffect_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/DashPathEffect_Delegate.java
new file mode 100644
index 0000000..d97c2ec
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/DashPathEffect_Delegate.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import java.awt.BasicStroke;
+import java.awt.Stroke;
+
+/**
+ * Delegate implementing the native methods of android.graphics.DashPathEffect
+ *
+ * Through the layoutlib_create tool, the original native methods of DashPathEffect have been
+ * replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original DashPathEffect class.
+ *
+ * Because this extends {@link PathEffect_Delegate}, there's no need to use a
+ * {@link DelegateManager}, as all the PathEffect classes will be added to the manager owned by
+ * {@link PathEffect_Delegate}.
+ *
+ * @see PathEffect_Delegate
+ *
+ */
+public final class DashPathEffect_Delegate extends PathEffect_Delegate {
+
+    // ---- delegate data ----
+
+    private final float[] mIntervals;
+    private final float mPhase;
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public Stroke getStroke(Paint_Delegate paint) {
+        return new BasicStroke(
+                paint.getStrokeWidth(),
+                paint.getJavaCap(),
+                paint.getJavaJoin(),
+                paint.getJavaStrokeMiter(),
+                mIntervals,
+                mPhase);
+    }
+
+    @Override
+    public boolean isSupported() {
+        return true;
+    }
+
+    @Override
+    public String getSupportMessage() {
+        // no message since isSupported returns true;
+        return null;
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeCreate(float intervals[], float phase) {
+        DashPathEffect_Delegate newDelegate = new DashPathEffect_Delegate(intervals, phase);
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    // ---- Private delegate/helper methods ----
+
+    private DashPathEffect_Delegate(float intervals[], float phase) {
+        mIntervals = new float[intervals.length];
+        System.arraycopy(intervals, 0, mIntervals, 0, intervals.length);
+        mPhase = phase;
+    }
+}
+
diff --git a/tools/layoutlib/bridge/src/android/graphics/DiscretePathEffect_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/DiscretePathEffect_Delegate.java
new file mode 100644
index 0000000..ec4a810
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/DiscretePathEffect_Delegate.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import java.awt.Stroke;
+
+/**
+ * Delegate implementing the native methods of android.graphics.DiscretePathEffect
+ *
+ * Through the layoutlib_create tool, the original native methods of DiscretePathEffect have been
+ * replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original DiscretePathEffect class.
+ *
+ * Because this extends {@link PathEffect_Delegate}, there's no need to use a {@link DelegateManager},
+ * as all the Shader classes will be added to the manager owned by {@link PathEffect_Delegate}.
+ *
+ * @see PathEffect_Delegate
+ *
+ */
+public class DiscretePathEffect_Delegate extends PathEffect_Delegate {
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public Stroke getStroke(Paint_Delegate paint) {
+        // FIXME
+        return null;
+    }
+
+    @Override
+    public boolean isSupported() {
+        return false;
+    }
+
+    @Override
+    public String getSupportMessage() {
+        return "Discrete Path Effects are not supported in Layout Preview mode.";
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeCreate(float length, float deviation) {
+        DiscretePathEffect_Delegate newDelegate = new DiscretePathEffect_Delegate();
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    // ---- Private delegate/helper methods ----
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/DrawFilter_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/DrawFilter_Delegate.java
new file mode 100644
index 0000000..870c46b
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/DrawFilter_Delegate.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+/**
+ * Delegate implementing the native methods of android.graphics.DrawFilter
+ *
+ * Through the layoutlib_create tool, the original native methods of DrawFilter have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original DrawFilter class.
+ *
+ * This also serve as a base class for all DrawFilter delegate classes.
+ *
+ * @see DelegateManager
+ *
+ */
+public abstract class DrawFilter_Delegate {
+
+    // ---- delegate manager ----
+    protected static final DelegateManager<DrawFilter_Delegate> sManager =
+            new DelegateManager<DrawFilter_Delegate>(DrawFilter_Delegate.class);
+
+    // ---- delegate helper data ----
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    public static DrawFilter_Delegate getDelegate(int nativeDrawFilter) {
+        return sManager.getDelegate(nativeDrawFilter);
+    }
+
+    public abstract boolean isSupported();
+    public abstract String getSupportMessage();
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeDestructor(int nativeDrawFilter) {
+        sManager.removeJavaReferenceFor(nativeDrawFilter);
+    }
+
+    // ---- Private delegate/helper methods ----
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/EmbossMaskFilter_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/EmbossMaskFilter_Delegate.java
new file mode 100644
index 0000000..ebc1c1d
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/EmbossMaskFilter_Delegate.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+/**
+ * Delegate implementing the native methods of android.graphics.EmbossMaskFilter
+ *
+ * Through the layoutlib_create tool, the original native methods of EmbossMaskFilter have
+ * been replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original EmbossMaskFilter class.
+ *
+ * Because this extends {@link MaskFilter_Delegate}, there's no need to use a
+ * {@link DelegateManager}, as all the Shader classes will be added to the manager
+ * owned by {@link MaskFilter_Delegate}.
+ *
+ * @see MaskFilter_Delegate
+ *
+ */
+public class EmbossMaskFilter_Delegate extends MaskFilter_Delegate {
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public boolean isSupported() {
+        return false;
+    }
+
+    @Override
+    public String getSupportMessage() {
+        return "Emboss Mask Filters are not supported.";
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeConstructor(float[] direction, float ambient,
+            float specular, float blurRadius) {
+        EmbossMaskFilter_Delegate newDelegate = new EmbossMaskFilter_Delegate();
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    // ---- Private delegate/helper methods ----
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/GradientShader.java b/tools/layoutlib/bridge/src/android/graphics/Gradient_Delegate.java
similarity index 84%
rename from tools/layoutlib/bridge/src/android/graphics/GradientShader.java
rename to tools/layoutlib/bridge/src/android/graphics/Gradient_Delegate.java
index 8c5a2a4..38c092d 100644
--- a/tools/layoutlib/bridge/src/android/graphics/GradientShader.java
+++ b/tools/layoutlib/bridge/src/android/graphics/Gradient_Delegate.java
@@ -16,23 +16,28 @@
 
 package android.graphics;
 
+import android.graphics.Shader.TileMode;
 
 /**
- * Base class for Gradient shader. This is not a standard android class and is just used
- * as a base class for the re-implemented gradient classes.
- *
- * It also provides a base class to handle common code between the different shaders'
- * implementations of {@link java.awt.Paint}.
- *
- * @see LinearGradient
- * @see RadialGradient
- * @see SweepGradient
+ * Base class for true Gradient shader delegate.
  */
-public abstract class GradientShader extends Shader {
+public abstract class Gradient_Delegate extends Shader_Delegate {
 
     protected final int[] mColors;
     protected final float[] mPositions;
 
+    @Override
+    public boolean isSupported() {
+        // all gradient shaders are supported.
+        return true;
+    }
+
+    @Override
+    public String getSupportMessage() {
+        // all gradient shaders are supported, no need for a gradient support
+        return null;
+    }
+
     /**
      * Creates the base shader and do some basic test on the parameters.
      *
@@ -41,7 +46,7 @@
      *            corresponding color in the colors array. If this is null, the
      *            the colors are distributed evenly along the gradient line.
      */
-    protected GradientShader(int colors[], float positions[]) {
+    protected Gradient_Delegate(int colors[], float positions[]) {
         if (colors.length < 2) {
             throw new IllegalArgumentException("needs >= 2 number of colors");
         }
@@ -90,7 +95,7 @@
          * Pre-computes the colors for the gradient. This must be called once before any call
          * to {@link #getGradientColor(float)}
          */
-        protected synchronized void precomputeGradientColors() {
+        protected void precomputeGradientColors() {
             if (mGradient == null) {
                 // actually create an array with an extra size, so that we can really go
                 // from 0 to SIZE (100%), or currentPos in the loop below will never equal 1.0
@@ -126,20 +131,23 @@
                             pos = 0.f;
                             break;
                         case REPEAT:
-                            // remove the integer part to stay in the [0,1] range
-                            // careful: this is a negative value, so use ceil instead of floor
-                            pos = pos - (float)Math.ceil(pos);
+                            // remove the integer part to stay in the [0,1] range.
+                            // we also need to invert the value from [-1,0] to [0, 1]
+                            pos = pos - (float)Math.floor(pos);
                             break;
                         case MIRROR:
+                            // this is the same as the positive side, just make the value positive
+                            // first.
+                            pos = Math.abs(pos);
+
                             // get the integer and the decimal part
-                            // careful: this is a negative value, so use ceil instead of floor
-                            int intPart = (int)Math.ceil(pos);
+                            int intPart = (int)Math.floor(pos);
                             pos = pos - intPart;
-                            // 0  -> -1 : mirrored order
-                            // -1 -> -2: normal order
+                            // 0 -> 1 : normal order
+                            // 1 -> 2: mirrored
                             // etc..
-                            // this means if the intpart is even we invert
-                            if ((intPart % 2) == 0) {
+                            // this means if the intpart is odd we invert
+                            if ((intPart % 2) == 1) {
                                 pos = 1.f - pos;
                             }
                             break;
@@ -199,7 +207,5 @@
         private int computeChannel(int c1, int c2, float percent) {
             return c1 + (int)((percent * (c2-c1)) + .5);
         }
-
-
     }
 }
diff --git a/tools/layoutlib/bridge/src/android/graphics/LayerRasterizer_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/LayerRasterizer_Delegate.java
new file mode 100644
index 0000000..51e0576
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/LayerRasterizer_Delegate.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+/**
+ * Delegate implementing the native methods of android.graphics.LayerRasterizer
+ *
+ * Through the layoutlib_create tool, the original native methods of LayerRasterizer have
+ * been replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original LayerRasterizer class.
+ *
+ * Because this extends {@link Rasterizer_Delegate}, there's no need to use a
+ * {@link DelegateManager}, as all the Shader classes will be added to the manager
+ * owned by {@link Rasterizer_Delegate}.
+ *
+ * @see Rasterizer_Delegate
+ *
+ */
+public class LayerRasterizer_Delegate extends Rasterizer_Delegate {
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public boolean isSupported() {
+        return false;
+    }
+
+    @Override
+    public String getSupportMessage() {
+        return "Layer Rasterizers are not supported.";
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeConstructor() {
+        LayerRasterizer_Delegate newDelegate = new LayerRasterizer_Delegate();
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeAddLayer(int native_layer, int native_paint, float dx, float dy) {
+
+    }
+
+    // ---- Private delegate/helper methods ----
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/LightingColorFilter_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/LightingColorFilter_Delegate.java
new file mode 100644
index 0000000..3afe965
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/LightingColorFilter_Delegate.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+/**
+ * Delegate implementing the native methods of android.graphics.LightingColorFilter
+ *
+ * Through the layoutlib_create tool, the original native methods of LightingColorFilter have
+ * been replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original LightingColorFilter class.
+ *
+ * Because this extends {@link ColorFilter_Delegate}, there's no need to use a
+ * {@link DelegateManager}, as all the Shader classes will be added to the manager
+ * owned by {@link ColorFilter_Delegate}.
+ *
+ * @see ColorFilter_Delegate
+ *
+ */
+public class LightingColorFilter_Delegate extends ColorFilter_Delegate {
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public boolean isSupported() {
+        return false;
+    }
+
+    @Override
+    public String getSupportMessage() {
+        return "Lighting Color Filters are not supported.";
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int native_CreateLightingFilter(int mul, int add) {
+        LightingColorFilter_Delegate newDelegate = new LightingColorFilter_Delegate();
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    // ---- Private delegate/helper methods ----
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/LinearGradient.java b/tools/layoutlib/bridge/src/android/graphics/LinearGradient.java
deleted file mode 100644
index 10c4a5e..0000000
--- a/tools/layoutlib/bridge/src/android/graphics/LinearGradient.java
+++ /dev/null
@@ -1,173 +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.graphics;
-
-public class LinearGradient extends GradientShader {
-
-    private java.awt.Paint mJavaPaint;
-
-    /**
-     * Create a shader that draws a linear gradient along a line.
-     *
-     * @param x0 The x-coordinate for the start of the gradient line
-     * @param y0 The y-coordinate for the start of the gradient line
-     * @param x1 The x-coordinate for the end of the gradient line
-     * @param y1 The y-coordinate for the end of the gradient line
-     * @param colors The colors to be distributed along the gradient line
-     * @param positions May be null. The relative positions [0..1] of each
-     *            corresponding color in the colors array. If this is null, the
-     *            the colors are distributed evenly along the gradient line.
-     * @param tile The Shader tiling mode
-     */
-    public LinearGradient(float x0, float y0, float x1, float y1, int colors[], float positions[],
-            TileMode tile) {
-        super(colors, positions);
-        mJavaPaint = new LinearGradientPaint(x0, y0, x1, y1, mColors, mPositions, tile);
-    }
-
-    /**
-     * Create a shader that draws a linear gradient along a line.
-     *
-     * @param x0 The x-coordinate for the start of the gradient line
-     * @param y0 The y-coordinate for the start of the gradient line
-     * @param x1 The x-coordinate for the end of the gradient line
-     * @param y1 The y-coordinate for the end of the gradient line
-     * @param color0 The color at the start of the gradient line.
-     * @param color1 The color at the end of the gradient line.
-     * @param tile The Shader tiling mode
-     */
-    public LinearGradient(float x0, float y0, float x1, float y1, int color0, int color1,
-            TileMode tile) {
-        this(x0, y0, x1, y1, new int[] { color0, color1}, null /*positions*/, tile);
-    }
-
-    // ---------- Custom Methods
-
-    @Override
-    java.awt.Paint getJavaPaint() {
-        return mJavaPaint;
-    }
-
-    /**
-     * Linear Gradient (Java) Paint able to handle more than 2 points, as
-     * {@link java.awt.GradientPaint} only supports 2 points and does not support Android's tile
-     * modes.
-     */
-    private static class LinearGradientPaint extends GradientPaint {
-
-        private final float mX0;
-        private final float mY0;
-        private final float mDx;
-        private final float mDy;
-        private final float mDSize2;
-
-        public LinearGradientPaint(float x0, float y0, float x1, float y1, int colors[],
-                float positions[], TileMode tile) {
-            super(colors, positions, tile);
-                mX0 = x0;
-                mY0 = y0;
-                mDx = x1 - x0;
-                mDy = y1 - y0;
-                mDSize2 = mDx * mDx + mDy * mDy;
-        }
-
-        public java.awt.PaintContext createContext(
-                java.awt.image.ColorModel      colorModel,
-                java.awt.Rectangle             deviceBounds,
-                java.awt.geom.Rectangle2D      userBounds,
-                java.awt.geom.AffineTransform  xform,
-                java.awt.RenderingHints        hints) {
-            precomputeGradientColors();
-            return new LinearGradientPaintContext(colorModel);
-        }
-
-        private class LinearGradientPaintContext implements java.awt.PaintContext {
-
-            private final java.awt.image.ColorModel mColorModel;
-
-            public LinearGradientPaintContext(java.awt.image.ColorModel colorModel) {
-                mColorModel = colorModel;
-                // FIXME: so far all this is always the same rect gotten in getRaster with an indentity matrix?
-            }
-
-            public void dispose() {
-            }
-
-            public java.awt.image.ColorModel getColorModel() {
-                return mColorModel;
-            }
-
-            public java.awt.image.Raster getRaster(int x, int y, int w, int h) {
-                java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(w, h,
-                        java.awt.image.BufferedImage.TYPE_INT_ARGB);
-
-                int[] data = new int[w*h];
-
-                if (mDx == 0) { // vertical gradient
-                    // compute first column and copy to all other columns
-                    int index = 0;
-                    for (int iy = 0 ; iy < h ; iy++) {
-                        int color = getColor(iy + y, mY0, mDy);
-                        for (int ix = 0 ; ix < w ; ix++) {
-                            data[index++] = color;
-                        }
-                    }
-                } else if (mDy == 0) { // horizontal
-                    // compute first line in a tmp array and copy to all lines
-                    int[] line = new int[w];
-                    for (int ix = 0 ; ix < w ; ix++) {
-                        line[ix] = getColor(ix + x, mX0, mDx);
-                    }
-
-                    for (int iy = 0 ; iy < h ; iy++) {
-                        System.arraycopy(line, 0, data, iy*w, line.length);
-                    }
-                } else {
-                    int index = 0;
-                    for (int iy = 0 ; iy < h ; iy++) {
-                        for (int ix = 0 ; ix < w ; ix++) {
-                            data[index++] = getColor(ix + x, iy + y);
-                        }
-                    }
-                }
-
-                image.setRGB(0 /*startX*/, 0 /*startY*/, w, h, data, 0 /*offset*/, w /*scansize*/);
-
-                return image.getRaster();
-            }
-        }
-
-        /** Returns a color for the easy vertical/horizontal mode */
-        private int getColor(float absPos, float refPos, float refSize) {
-            float pos = (absPos - refPos) / refSize;
-
-            return getGradientColor(pos);
-        }
-
-        /**
-         * Returns a color for an arbitrary point.
-         */
-        private int getColor(float x, float y) {
-            // find the x position on the gradient vector.
-            float _x = (mDx*mDy*(y-mY0) + mDy*mDy*mX0 + mDx*mDx*x) / mDSize2;
-            // from it get the position relative to the vector
-            float pos = (float) ((_x - mX0) / mDx);
-
-            return getGradientColor(pos);
-        }
-    }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/LinearGradient_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/LinearGradient_Delegate.java
new file mode 100644
index 0000000..a735ea1
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/LinearGradient_Delegate.java
@@ -0,0 +1,219 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import android.graphics.Shader.TileMode;
+
+/**
+ * Delegate implementing the native methods of android.graphics.LinearGradient
+ *
+ * Through the layoutlib_create tool, the original native methods of LinearGradient have been
+ * replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original LinearGradient class.
+ *
+ * Because this extends {@link Shader_Delegate}, there's no need to use a {@link DelegateManager},
+ * as all the Shader classes will be added to the manager owned by {@link Shader_Delegate}.
+ *
+ * @see Shader_Delegate
+ *
+ */
+public final class LinearGradient_Delegate extends Gradient_Delegate {
+
+    // ---- delegate data ----
+    private java.awt.Paint mJavaPaint;
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public java.awt.Paint getJavaPaint() {
+        return mJavaPaint;
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeCreate1(
+            float x0, float y0, float x1, float y1,
+            int colors[], float positions[], int tileMode) {
+        LinearGradient_Delegate newDelegate = new LinearGradient_Delegate(x0, y0, x1, y1,
+                colors, positions, Shader_Delegate.getTileMode(tileMode));
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeCreate2(
+            float x0, float y0, float x1, float y1,
+            int color0, int color1, int tileMode) {
+        return nativeCreate1(x0, y0, x1, y1, new int[] { color0, color1}, null /*positions*/,
+                tileMode);
+    }
+
+    // ---- Private delegate/helper methods ----
+
+    /**
+     * Create a shader that draws a linear gradient along a line.
+     *
+     * @param x0 The x-coordinate for the start of the gradient line
+     * @param y0 The y-coordinate for the start of the gradient line
+     * @param x1 The x-coordinate for the end of the gradient line
+     * @param y1 The y-coordinate for the end of the gradient line
+     * @param colors The colors to be distributed along the gradient line
+     * @param positions May be null. The relative positions [0..1] of each
+     *            corresponding color in the colors array. If this is null, the
+     *            the colors are distributed evenly along the gradient line.
+     * @param tile The Shader tiling mode
+     */
+    private LinearGradient_Delegate(float x0, float y0, float x1, float y1,
+            int colors[], float positions[], TileMode tile) {
+        super(colors, positions);
+        mJavaPaint = new LinearGradientPaint(x0, y0, x1, y1, mColors, mPositions, tile);
+    }
+
+    // ---- Custom Java Paint ----
+    /**
+     * Linear Gradient (Java) Paint able to handle more than 2 points, as
+     * {@link java.awt.GradientPaint} only supports 2 points and does not support Android's tile
+     * modes.
+     */
+    private class LinearGradientPaint extends GradientPaint {
+
+        private final float mX0;
+        private final float mY0;
+        private final float mDx;
+        private final float mDy;
+        private final float mDSize2;
+
+        public LinearGradientPaint(float x0, float y0, float x1, float y1, int colors[],
+                float positions[], TileMode tile) {
+            super(colors, positions, tile);
+            mX0 = x0;
+            mY0 = y0;
+            mDx = x1 - x0;
+            mDy = y1 - y0;
+            mDSize2 = mDx * mDx + mDy * mDy;
+        }
+
+        public java.awt.PaintContext createContext(
+                java.awt.image.ColorModel      colorModel,
+                java.awt.Rectangle             deviceBounds,
+                java.awt.geom.Rectangle2D      userBounds,
+                java.awt.geom.AffineTransform  xform,
+                java.awt.RenderingHints        hints) {
+            precomputeGradientColors();
+
+            java.awt.geom.AffineTransform canvasMatrix;
+            try {
+                canvasMatrix = xform.createInverse();
+            } catch (java.awt.geom.NoninvertibleTransformException e) {
+                Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
+                        "Unable to inverse matrix in LinearGradient", e, null /*data*/);
+                canvasMatrix = new java.awt.geom.AffineTransform();
+            }
+
+            java.awt.geom.AffineTransform localMatrix = getLocalMatrix();
+            try {
+                localMatrix = localMatrix.createInverse();
+            } catch (java.awt.geom.NoninvertibleTransformException e) {
+                Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
+                        "Unable to inverse matrix in LinearGradient", e, null /*data*/);
+                localMatrix = new java.awt.geom.AffineTransform();
+            }
+
+            return new LinearGradientPaintContext(canvasMatrix, localMatrix, colorModel);
+        }
+
+        private class LinearGradientPaintContext implements java.awt.PaintContext {
+
+            private final java.awt.geom.AffineTransform mCanvasMatrix;
+            private final java.awt.geom.AffineTransform mLocalMatrix;
+            private final java.awt.image.ColorModel mColorModel;
+
+            private LinearGradientPaintContext(
+                    java.awt.geom.AffineTransform canvasMatrix,
+                    java.awt.geom.AffineTransform localMatrix,
+                    java.awt.image.ColorModel colorModel) {
+                mCanvasMatrix = canvasMatrix;
+                mLocalMatrix = localMatrix;
+                mColorModel = colorModel;
+            }
+
+            public void dispose() {
+            }
+
+            public java.awt.image.ColorModel getColorModel() {
+                return mColorModel;
+            }
+
+            public java.awt.image.Raster getRaster(int x, int y, int w, int h) {
+                java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(w, h,
+                        java.awt.image.BufferedImage.TYPE_INT_ARGB);
+
+                int[] data = new int[w*h];
+
+                int index = 0;
+                float[] pt1 = new float[2];
+                float[] pt2 = new float[2];
+                for (int iy = 0 ; iy < h ; iy++) {
+                    for (int ix = 0 ; ix < w ; ix++) {
+                        // handle the canvas transform
+                        pt1[0] = x + ix;
+                        pt1[1] = y + iy;
+                        mCanvasMatrix.transform(pt1, 0, pt2, 0, 1);
+
+                        // handle the local matrix.
+                        pt1[0] = pt2[0];
+                        pt1[1] = pt2[1];
+                        mLocalMatrix.transform(pt1, 0, pt2, 0, 1);
+
+                        data[index++] = getColor(pt2[0], pt2[1]);
+                    }
+                }
+
+                image.setRGB(0 /*startX*/, 0 /*startY*/, w, h, data, 0 /*offset*/, w /*scansize*/);
+
+                return image.getRaster();
+            }
+        }
+
+        /**
+         * Returns a color for an arbitrary point.
+         */
+        private int getColor(float x, float y) {
+            float pos;
+            if (mDx == 0) {
+                pos = (y - mY0) / mDy;
+            } else if (mDy == 0) {
+                pos = (x - mX0) / mDx;
+            } else {
+                // find the x position on the gradient vector.
+                float _x = (mDx*mDy*(y-mY0) + mDy*mDy*mX0 + mDx*mDx*x) / mDSize2;
+                // from it get the position relative to the vector
+                pos = (_x - mX0) / mDx;
+            }
+
+            return getGradientColor(pos);
+        }
+    }
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/MaskFilter_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/MaskFilter_Delegate.java
new file mode 100644
index 0000000..c2f27e4
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/MaskFilter_Delegate.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+/**
+ * Delegate implementing the native methods of android.graphics.MaskFilter
+ *
+ * Through the layoutlib_create tool, the original native methods of MaskFilter have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original MaskFilter class.
+ *
+ * This also serve as a base class for all MaskFilter delegate classes.
+ *
+ * @see DelegateManager
+ *
+ */
+public abstract class MaskFilter_Delegate {
+
+    // ---- delegate manager ----
+    protected static final DelegateManager<MaskFilter_Delegate> sManager =
+            new DelegateManager<MaskFilter_Delegate>(MaskFilter_Delegate.class);
+
+    // ---- delegate helper data ----
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    public static MaskFilter_Delegate getDelegate(int nativeShader) {
+        return sManager.getDelegate(nativeShader);
+    }
+
+    public abstract boolean isSupported();
+    public abstract String getSupportMessage();
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeDestructor(int native_filter) {
+        sManager.removeJavaReferenceFor(native_filter);
+    }
+
+    // ---- Private delegate/helper methods ----
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Matrix.java b/tools/layoutlib/bridge/src/android/graphics/Matrix.java
deleted file mode 100644
index 9e30671..0000000
--- a/tools/layoutlib/bridge/src/android/graphics/Matrix.java
+++ /dev/null
@@ -1,1032 +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.graphics;
-
-import java.awt.geom.AffineTransform;
-import java.awt.geom.NoninvertibleTransformException;
-
-
-/**
- * A matrix implementation overridden by the LayoutLib bridge.
- */
-public class Matrix extends _Original_Matrix {
-
-    float mValues[] = new float[9];
-
-    /**
-     * Create an identity matrix
-     */
-    public Matrix() {
-        reset();
-    }
-
-    /**
-     * Create a matrix that is a (deep) copy of src
-     * @param src The matrix to copy into this matrix
-     */
-    public Matrix(Matrix src) {
-        set(src);
-    }
-
-    /**
-     * Creates a Matrix object from the float array. The array becomes the internal storage
-     * of the object.
-     * @param data
-     */
-    private Matrix(float[] data) {
-        assert data.length != 9;
-        mValues = data;
-    }
-
-    //---------- Custom Methods
-
-    /**
-     * Adds the given transformation to the current Matrix
-     * <p/>This in effect does this = this*matrix
-     * @param matrix
-     */
-    private void addTransform(float[] matrix) {
-        float[] tmp = new float[9];
-
-        // first row
-        tmp[0] = matrix[0] * mValues[0] + matrix[1] * mValues[3] + matrix[2] * mValues[6];
-        tmp[1] = matrix[0] * mValues[1] + matrix[1] * mValues[4] + matrix[2] * mValues[7];
-        tmp[2] = matrix[0] * mValues[2] + matrix[1] * mValues[5] + matrix[2] * mValues[8];
-
-        // 2nd row
-        tmp[3] = matrix[3] * mValues[0] + matrix[4] * mValues[3] + matrix[5] * mValues[6];
-        tmp[4] = matrix[3] * mValues[1] + matrix[4] * mValues[4] + matrix[5] * mValues[7];
-        tmp[5] = matrix[3] * mValues[2] + matrix[4] * mValues[5] + matrix[5] * mValues[8];
-
-        // 3rd row
-        tmp[6] = matrix[6] * mValues[0] + matrix[7] * mValues[3] + matrix[8] * mValues[6];
-        tmp[7] = matrix[6] * mValues[1] + matrix[7] * mValues[4] + matrix[8] * mValues[7];
-        tmp[8] = matrix[6] * mValues[2] + matrix[7] * mValues[5] + matrix[8] * mValues[8];
-
-        // copy the result over to mValues
-        mValues = tmp;
-    }
-
-    public AffineTransform getTransform() {
-        // the AffineTransform constructor takes the value in a different order
-        // for a matrix [ 0 1 2 ]
-        //              [ 3 4 5 ]
-        // the order is 0, 3, 1, 4, 2, 5...
-        return new AffineTransform(mValues[0], mValues[3], mValues[1],
-                mValues[4], mValues[2], mValues[5]);
-    }
-
-    public boolean hasPerspective() {
-        return (mValues[6] != 0 || mValues[7] != 0 || mValues[8] != 1);
-    }
-
-    //----------
-
-    /**
-     * Returns true if the matrix is identity.
-     * This maybe faster than testing if (getType() == 0)
-     */
-    @Override
-    public boolean isIdentity() {
-        for (int i = 0, k = 0; i < 3; i++) {
-            for (int j = 0; j < 3; j++, k++) {
-                if (mValues[k] != ((i==j) ? 1 : 0)) {
-                    return false;
-                }
-            }
-        }
-
-        return true;
-    }
-
-    /**
-     * Returns true if will map a rectangle to another rectangle. This can be
-     * true if the matrix is identity, scale-only, or rotates a multiple of 90
-     * degrees.
-     */
-    @Override
-    public boolean rectStaysRect() {
-        return (computeTypeMask() & kRectStaysRect_Mask) != 0;
-    }
-
-    /**
-     * (deep) copy the src matrix into this matrix. If src is null, reset this
-     * matrix to the identity matrix.
-     */
-    public void set(Matrix src) {
-        if (src == null) {
-            reset();
-        } else {
-            System.arraycopy(src.mValues, 0, mValues, 0, mValues.length);
-        }
-    }
-
-    @Override
-    public void set(_Original_Matrix src) {
-        throw new UnsupportedOperationException("CALL TO PARENT FORBIDDEN");
-    }
-
-    /** Returns true if obj is a Matrix and its values equal our values.
-    */
-    @Override
-    public boolean equals(Object obj) {
-        if (obj != null && obj instanceof Matrix) {
-            Matrix matrix = (Matrix)obj;
-            for (int i = 0 ; i < 9 ; i++) {
-                if (mValues[i] != matrix.mValues[i]) {
-                    return false;
-                }
-            }
-
-            return true;
-        }
-
-        return false;
-    }
-
-    /** Set the matrix to identity */
-    @Override
-    public void reset() {
-        for (int i = 0, k = 0; i < 3; i++) {
-            for (int j = 0; j < 3; j++, k++) {
-                mValues[k] = ((i==j) ? 1 : 0);
-            }
-        }
-    }
-
-    /** Set the matrix to translate by (dx, dy). */
-    @Override
-    public void setTranslate(float dx, float dy) {
-        mValues[0] = 1;
-        mValues[1] = 0;
-        mValues[2] = dx;
-        mValues[3] = 0;
-        mValues[4] = 1;
-        mValues[5] = dy;
-        mValues[6] = 0;
-        mValues[7] = 0;
-        mValues[8] = 1;
-    }
-
-    /**
-     * Set the matrix to scale by sx and sy, with a pivot point at (px, py).
-     * The pivot point is the coordinate that should remain unchanged by the
-     * specified transformation.
-     */
-    @Override
-    public void setScale(float sx, float sy, float px, float py) {
-        // TODO: do it in one pass
-
-        // translate so that the pivot is in 0,0
-        mValues[0] = 1;
-        mValues[1] = 0;
-        mValues[2] = -px;
-        mValues[3] = 0;
-        mValues[4] = 1;
-        mValues[5] = -py;
-        mValues[6] = 0;
-        mValues[7] = 0;
-        mValues[8] = 1;
-
-        // scale
-        addTransform(new float[] { sx, 0, 0, 0, sy, 0, 0, 0, 1 });
-        // translate back the pivot
-        addTransform(new float[] { 1, 0, px, 0, 1, py, 0, 0, 1 });
-    }
-
-    /** Set the matrix to scale by sx and sy. */
-    @Override
-    public void setScale(float sx, float sy) {
-        mValues[0] = sx;
-        mValues[1] = 0;
-        mValues[2] = 0;
-        mValues[3] = 0;
-        mValues[4] = sy;
-        mValues[5] = 0;
-        mValues[6] = 0;
-        mValues[7] = 0;
-        mValues[8] = 1;
-    }
-
-    /**
-     * Set the matrix to rotate by the specified number of degrees, with a pivot
-     * point at (px, py). The pivot point is the coordinate that should remain
-     * unchanged by the specified transformation.
-     */
-    @Override
-    public void setRotate(float degrees, float px, float py) {
-        // TODO: do it in one pass
-
-        // translate so that the pivot is in 0,0
-        mValues[0] = 1;
-        mValues[1] = 0;
-        mValues[2] = -px;
-        mValues[3] = 0;
-        mValues[4] = 1;
-        mValues[5] = -py;
-        mValues[6] = 0;
-        mValues[7] = 0;
-        mValues[8] = 1;
-
-        // scale
-        double rad = Math.toRadians(degrees);
-        float cos = (float)Math.cos(rad);
-        float sin = (float)Math.sin(rad);
-        addTransform(new float[] { cos, -sin, 0, sin, cos, 0, 0, 0, 1 });
-        // translate back the pivot
-        addTransform(new float[] { 1, 0, px, 0, 1, py, 0, 0, 1 });
-    }
-
-    /**
-     * Set the matrix to rotate about (0,0) by the specified number of degrees.
-     */
-    @Override
-    public void setRotate(float degrees) {
-        double rad = Math.toRadians(degrees);
-        float cos = (float)Math.cos(rad);
-        float sin = (float)Math.sin(rad);
-
-        mValues[0] = cos;
-        mValues[1] = -sin;
-        mValues[2] = 0;
-        mValues[3] = sin;
-        mValues[4] = cos;
-        mValues[5] = 0;
-        mValues[6] = 0;
-        mValues[7] = 0;
-        mValues[8] = 1;
-    }
-
-    /**
-     * Set the matrix to rotate by the specified sine and cosine values, with a
-     * pivot point at (px, py). The pivot point is the coordinate that should
-     * remain unchanged by the specified transformation.
-     */
-    @Override
-    public void setSinCos(float sinValue, float cosValue, float px, float py) {
-        // TODO: do it in one pass
-
-        // translate so that the pivot is in 0,0
-        mValues[0] = 1;
-        mValues[1] = 0;
-        mValues[2] = -px;
-        mValues[3] = 0;
-        mValues[4] = 1;
-        mValues[5] = -py;
-        mValues[6] = 0;
-        mValues[7] = 0;
-        mValues[8] = 1;
-
-        // scale
-        addTransform(new float[] { cosValue, -sinValue, 0, sinValue, cosValue, 0, 0, 0, 1 });
-        // translate back the pivot
-        addTransform(new float[] { 1, 0, px, 0, 1, py, 0, 0, 1 });
-    }
-
-    /** Set the matrix to rotate by the specified sine and cosine values. */
-    @Override
-    public void setSinCos(float sinValue, float cosValue) {
-        mValues[0] = cosValue;
-        mValues[1] = -sinValue;
-        mValues[2] = 0;
-        mValues[3] = sinValue;
-        mValues[4] = cosValue;
-        mValues[5] = 0;
-        mValues[6] = 0;
-        mValues[7] = 0;
-        mValues[8] = 1;
-    }
-
-    /**
-     * Set the matrix to skew by sx and sy, with a pivot point at (px, py).
-     * The pivot point is the coordinate that should remain unchanged by the
-     * specified transformation.
-     */
-    @Override
-    public void setSkew(float kx, float ky, float px, float py) {
-        // TODO: do it in one pass
-
-        // translate so that the pivot is in 0,0
-        mValues[0] = 1;
-        mValues[1] = 0;
-        mValues[2] = -px;
-        mValues[3] = 0;
-        mValues[4] = 1;
-        mValues[5] = -py;
-        mValues[6] = 0;
-        mValues[7] = 0;
-        mValues[8] = 1;
-
-        // scale
-        addTransform(new float[] { 1, kx, 0, ky, 1, 0, 0, 0, 1 });
-        // translate back the pivot
-        addTransform(new float[] { 1, 0, px, 0, 1, py, 0, 0, 1 });
-    }
-
-    /** Set the matrix to skew by sx and sy. */
-    @Override
-    public void setSkew(float kx, float ky) {
-        mValues[0] = 1;
-        mValues[1] = kx;
-        mValues[2] = -0;
-        mValues[3] = ky;
-        mValues[4] = 1;
-        mValues[5] = 0;
-        mValues[6] = 0;
-        mValues[7] = 0;
-        mValues[8] = 1;
-    }
-
-    /**
-     * Set the matrix to the concatenation of the two specified matrices,
-     * returning true if the the result can be represented. Either of the two
-     * matrices may also be the target matrix. this = a * b
-     */
-    public boolean setConcat(Matrix a, Matrix b) {
-        if (a == this) {
-            preConcat(b);
-        } else if (b == this) {
-            postConcat(b);
-        } else {
-            Matrix tmp = new Matrix(b);
-            tmp.addTransform(a.mValues);
-            set(tmp);
-        }
-
-        return true;
-    }
-
-    @Override
-    public boolean setConcat(_Original_Matrix a, _Original_Matrix b) {
-        throw new UnsupportedOperationException("CALL TO PARENT FORBIDDEN");
-    }
-
-    /**
-     * Preconcats the matrix with the specified translation.
-     * M' = M * T(dx, dy)
-     */
-    @Override
-    public boolean preTranslate(float dx, float dy) {
-        // create a matrix that will be multiply by this
-        Matrix m = new Matrix(new float[] { 1, 0, dx, 0, 1, dy, 0, 0, 1 });
-        m.addTransform(this.mValues);
-
-        System.arraycopy(m.mValues, 0, mValues, 0, 9);
-        return true;
-    }
-
-    /**
-     * Preconcats the matrix with the specified scale.
-     * M' = M * S(sx, sy, px, py)
-     */
-    @Override
-    public boolean preScale(float sx, float sy, float px, float py) {
-        Matrix m = new Matrix();
-        m.setScale(sx, sy, px, py);
-        m.addTransform(mValues);
-        set(m);
-
-        return true;
-    }
-
-    /**
-     * Preconcats the matrix with the specified scale.
-     * M' = M * S(sx, sy)
-     */
-    @Override
-    public boolean preScale(float sx, float sy) {
-        Matrix m = new Matrix();
-        m.setScale(sx, sy);
-        m.addTransform(mValues);
-        set(m);
-
-        return true;
-    }
-
-    /**
-     * Preconcats the matrix with the specified rotation.
-     * M' = M * R(degrees, px, py)
-     */
-    @Override
-    public boolean preRotate(float degrees, float px, float py) {
-        Matrix m = new Matrix();
-        m.setRotate(degrees, px, py);
-        m.addTransform(mValues);
-        set(m);
-
-        return true;
-    }
-
-    /**
-     * Preconcats the matrix with the specified rotation.
-     * M' = M * R(degrees)
-     */
-    @Override
-    public boolean preRotate(float degrees) {
-        Matrix m = new Matrix();
-        m.setRotate(degrees);
-        m.addTransform(mValues);
-        set(m);
-
-        return true;
-    }
-
-    /**
-     * Preconcats the matrix with the specified skew.
-     * M' = M * K(kx, ky, px, py)
-     */
-    @Override
-    public boolean preSkew(float kx, float ky, float px, float py) {
-        Matrix m = new Matrix();
-        m.setSkew(kx, ky, px, py);
-        m.addTransform(mValues);
-        set(m);
-
-        return true;
-    }
-
-    /**
-     * Preconcats the matrix with the specified skew.
-     * M' = M * K(kx, ky)
-     */
-    @Override
-    public boolean preSkew(float kx, float ky) {
-        Matrix m = new Matrix();
-        m.setSkew(kx, ky);
-        m.addTransform(mValues);
-        set(m);
-
-        return true;
-    }
-
-    /**
-     * Preconcats the matrix with the specified matrix.
-     * M' = M * other
-     */
-    public boolean preConcat(Matrix other) {
-        Matrix m = new Matrix(other);
-        other.addTransform(mValues);
-        set(m);
-
-        return true;
-    }
-
-    @Override
-    public boolean preConcat(_Original_Matrix other) {
-        throw new UnsupportedOperationException("CALL TO PARENT FORBIDDEN");
-    }
-
-    /**
-     * Postconcats the matrix with the specified translation.
-     * M' = T(dx, dy) * M
-     */
-    @Override
-    public boolean postTranslate(float dx, float dy) {
-        addTransform(new float[] { 1, 0, dx, 0, 1, dy, 0, 0, 1 });
-        return true;
-    }
-
-    /**
-     * Postconcats the matrix with the specified scale.
-     * M' = S(sx, sy, px, py) * M
-     */
-    @Override
-    public boolean postScale(float sx, float sy, float px, float py) {
-        // TODO: do it in one pass
-        // translate so that the pivot is in 0,0
-        addTransform(new float[] { 1, 0, -px, 0, 1, py, 0, 0, 1 });
-        // scale
-        addTransform(new float[] { sx, 0, 0, 0, sy, 0, 0, 0, 1 });
-        // translate back the pivot
-        addTransform(new float[] { 1, 0, px, 0, 1, py, 0, 0, 1 });
-
-        return true;
-    }
-
-    /**
-     * Postconcats the matrix with the specified scale.
-     * M' = S(sx, sy) * M
-     */
-    @Override
-    public boolean postScale(float sx, float sy) {
-        addTransform(new float[] { sx, 0, 0, 0, sy, 0, 0, 0, 1 });
-        return true;
-    }
-
-    /**
-     * Postconcats the matrix with the specified rotation.
-     * M' = R(degrees, px, py) * M
-     */
-    @Override
-    public boolean postRotate(float degrees, float px, float py) {
-        // TODO: do it in one pass
-        // translate so that the pivot is in 0,0
-        addTransform(new float[] { 1, 0, -px, 0, 1, py, 0, 0, 1 });
-        // scale
-        double rad = Math.toRadians(degrees);
-        float cos = (float)Math.cos(rad);
-        float sin = (float)Math.sin(rad);
-        addTransform(new float[] { cos, -sin, 0, sin, cos, 0, 0, 0, 1 });
-        // translate back the pivot
-        addTransform(new float[] { 1, 0, px, 0, 1, py, 0, 0, 1 });
-
-        return true;
-    }
-
-    /**
-     * Postconcats the matrix with the specified rotation.
-     * M' = R(degrees) * M
-     */
-    @Override
-    public boolean postRotate(float degrees) {
-        double rad = Math.toRadians(degrees);
-        float cos = (float)Math.cos(rad);
-        float sin = (float)Math.sin(rad);
-        addTransform(new float[] { cos, -sin, 0, sin, cos, 0, 0, 0, 1 });
-
-        return true;
-    }
-
-    /**
-     * Postconcats the matrix with the specified skew.
-     * M' = K(kx, ky, px, py) * M
-     */
-    @Override
-    public boolean postSkew(float kx, float ky, float px, float py) {
-        // TODO: do it in one pass
-        // translate so that the pivot is in 0,0
-        addTransform(new float[] { 1, 0, -px, 0, 1, py, 0, 0, 1 });
-        // scale
-        addTransform(new float[] { 1, kx, 0, ky, 1, 0, 0, 0, 1 });
-        // translate back the pivot
-        addTransform(new float[] { 1, 0, px, 0, 1, py, 0, 0, 1 });
-
-        return true;
-    }
-
-    /**
-     * Postconcats the matrix with the specified skew.
-     * M' = K(kx, ky) * M
-     */
-    @Override
-    public boolean postSkew(float kx, float ky) {
-        addTransform(new float[] { 1, kx, 0, ky, 1, 0, 0, 0, 1 });
-
-        return true;
-    }
-
-    /**
-     * Postconcats the matrix with the specified matrix.
-     * M' = other * M
-     */
-    public boolean postConcat(Matrix other) {
-        addTransform(other.mValues);
-
-        return true;
-    }
-
-    @Override
-    public boolean postConcat(_Original_Matrix other) {
-        throw new UnsupportedOperationException("CALL TO PARENT FORBIDDEN");
-    }
-
-    /** Controlls how the src rect should align into the dst rect for
-        setRectToRect().
-    */
-    public enum ScaleToFit {
-        /**
-         * Scale in X and Y independently, so that src matches dst exactly.
-         * This may change the aspect ratio of the src.
-         */
-        FILL    (0),
-        /**
-         * Compute a scale that will maintain the original src aspect ratio,
-         * but will also ensure that src fits entirely inside dst. At least one
-         * axis (X or Y) will fit exactly. START aligns the result to the
-         * left and top edges of dst.
-         */
-        START   (1),
-        /**
-         * Compute a scale that will maintain the original src aspect ratio,
-         * but will also ensure that src fits entirely inside dst. At least one
-         * axis (X or Y) will fit exactly. The result is centered inside dst.
-         */
-        CENTER  (2),
-        /**
-         * Compute a scale that will maintain the original src aspect ratio,
-         * but will also ensure that src fits entirely inside dst. At least one
-         * axis (X or Y) will fit exactly. END aligns the result to the
-         * right and bottom edges of dst.
-         */
-        END     (3);
-
-        // the native values must match those in SkMatrix.h
-        ScaleToFit(int nativeInt) {
-            this.nativeInt = nativeInt;
-        }
-        final int nativeInt;
-    }
-
-    /**
-     * Set the matrix to the scale and translate values that map the source
-     * rectangle to the destination rectangle, returning true if the result
-     * can be represented.
-     *
-     * @param src the source rectangle to map from.
-     * @param dst the destination rectangle to map to.
-     * @param stf the ScaleToFit option
-     * @return true if the matrix can be represented by the rectangle mapping.
-     */
-    public boolean setRectToRect(RectF src, RectF dst, ScaleToFit stf) {
-        if (dst == null || src == null) {
-            throw new NullPointerException();
-        }
-
-        if (src.isEmpty()) {
-            reset();
-            return false;
-        }
-
-        if (dst.isEmpty()) {
-            mValues[0] = mValues[1] = mValues[2] = mValues[3] = mValues[4] = mValues[5]
-               = mValues[6] = mValues[7] = 0;
-            mValues[8] = 1;
-        } else {
-            float    tx, sx = dst.width() / src.width();
-            float    ty, sy = dst.height() / src.height();
-            boolean  xLarger = false;
-
-            if (stf != ScaleToFit.FILL) {
-                if (sx > sy) {
-                    xLarger = true;
-                    sx = sy;
-                } else {
-                    sy = sx;
-                }
-            }
-
-            tx = dst.left - src.left * sx;
-            ty = dst.top - src.top * sy;
-            if (stf == ScaleToFit.CENTER || stf == ScaleToFit.END) {
-                float diff;
-
-                if (xLarger) {
-                    diff = dst.width() - src.width() * sy;
-                } else {
-                    diff = dst.height() - src.height() * sy;
-                }
-
-                if (stf == ScaleToFit.CENTER) {
-                    diff = diff / 2;
-                }
-
-                if (xLarger) {
-                    tx += diff;
-                } else {
-                    ty += diff;
-                }
-            }
-
-            mValues[0] = sx;
-            mValues[4] = sy;
-            mValues[2] = tx;
-            mValues[5] = ty;
-            mValues[1]  = mValues[3] = mValues[6] = mValues[7] = 0;
-
-        }
-        // shared cleanup
-        mValues[8] = 1;
-        return true;
-    }
-
-    @Override
-    public boolean setRectToRect(RectF src, RectF dst, _Original_Matrix.ScaleToFit stf) {
-        throw new UnsupportedOperationException("CALL TO PARENT FORBIDDEN");
-    }
-
-    /**
-     * Set the matrix such that the specified src points would map to the
-     * specified dst points. The "points" are represented as an array of floats,
-     * order [x0, y0, x1, y1, ...], where each "point" is 2 float values.
-     *
-     * @param src   The array of src [x,y] pairs (points)
-     * @param srcIndex Index of the first pair of src values
-     * @param dst   The array of dst [x,y] pairs (points)
-     * @param dstIndex Index of the first pair of dst values
-     * @param pointCount The number of pairs/points to be used. Must be [0..4]
-     * @return true if the matrix was set to the specified transformation
-     */
-    @Override
-    public boolean setPolyToPoly(float[] src, int srcIndex,
-                                 float[] dst, int dstIndex,
-                                 int pointCount) {
-        if (pointCount > 4) {
-            throw new IllegalArgumentException();
-        }
-        checkPointArrays(src, srcIndex, dst, dstIndex, pointCount);
-        throw new UnsupportedOperationException("STUB NEEDED");
-    }
-
-    /**
-     * If this matrix can be inverted, return true and if inverse is not null,
-     * set inverse to be the inverse of this matrix. If this matrix cannot be
-     * inverted, ignore inverse and return false.
-     */
-    public boolean invert(Matrix inverse) {
-        if (inverse == null) {
-            return false;
-        }
-
-        try {
-            AffineTransform affineTransform = getTransform();
-            AffineTransform inverseTransform = affineTransform.createInverse();
-            inverse.mValues[0] = (float)inverseTransform.getScaleX();
-            inverse.mValues[1] = (float)inverseTransform.getShearX();
-            inverse.mValues[2] = (float)inverseTransform.getTranslateX();
-            inverse.mValues[3] = (float)inverseTransform.getScaleX();
-            inverse.mValues[4] = (float)inverseTransform.getShearY();
-            inverse.mValues[5] = (float)inverseTransform.getTranslateY();
-
-            return true;
-        } catch (NoninvertibleTransformException e) {
-            return false;
-        }
-    }
-
-    @Override
-    public boolean invert(_Original_Matrix inverse) {
-        throw new UnsupportedOperationException("CALL TO PARENT FORBIDDEN");
-    }
-
-    /**
-    * Apply this matrix to the array of 2D points specified by src, and write
-     * the transformed points into the array of points specified by dst. The
-     * two arrays represent their "points" as pairs of floats [x, y].
-     *
-     * @param dst   The array of dst points (x,y pairs)
-     * @param dstIndex The index of the first [x,y] pair of dst floats
-     * @param src   The array of src points (x,y pairs)
-     * @param srcIndex The index of the first [x,y] pair of src floats
-     * @param pointCount The number of points (x,y pairs) to transform
-     */
-    @Override
-    public void mapPoints(float[] dst, int dstIndex, float[] src, int srcIndex,
-                          int pointCount) {
-        checkPointArrays(src, srcIndex, dst, dstIndex, pointCount);
-
-        for (int i = 0 ; i < pointCount ; i++) {
-            // just in case we are doing in place, we better put this in temp vars
-            float x = mValues[0] * src[i + srcIndex] +
-                      mValues[1] * src[i + srcIndex + 1] +
-                      mValues[2];
-            float y = mValues[3] * src[i + srcIndex] +
-                      mValues[4] * src[i + srcIndex + 1] +
-                      mValues[5];
-
-            dst[i + dstIndex]     = x;
-            dst[i + dstIndex + 1] = y;
-        }
-    }
-
-    /**
-    * Apply this matrix to the array of 2D vectors specified by src, and write
-     * the transformed vectors into the array of vectors specified by dst. The
-     * two arrays represent their "vectors" as pairs of floats [x, y].
-     *
-     * @param dst   The array of dst vectors (x,y pairs)
-     * @param dstIndex The index of the first [x,y] pair of dst floats
-     * @param src   The array of src vectors (x,y pairs)
-     * @param srcIndex The index of the first [x,y] pair of src floats
-     * @param vectorCount The number of vectors (x,y pairs) to transform
-     */
-    @Override
-    public void mapVectors(float[] dst, int dstIndex, float[] src, int srcIndex,
-                          int vectorCount) {
-        checkPointArrays(src, srcIndex, dst, dstIndex, vectorCount);
-        throw new UnsupportedOperationException("STUB NEEDED");
-    }
-
-    /**
-     * Apply this matrix to the array of 2D points specified by src, and write
-     * the transformed points into the array of points specified by dst. The
-     * two arrays represent their "points" as pairs of floats [x, y].
-     *
-     * @param dst   The array of dst points (x,y pairs)
-     * @param src   The array of src points (x,y pairs)
-     */
-    @Override
-    public void mapPoints(float[] dst, float[] src) {
-        if (dst.length != src.length) {
-            throw new ArrayIndexOutOfBoundsException();
-        }
-        mapPoints(dst, 0, src, 0, dst.length >> 1);
-    }
-
-    /**
-     * Apply this matrix to the array of 2D vectors specified by src, and write
-     * the transformed vectors into the array of vectors specified by dst. The
-     * two arrays represent their "vectors" as pairs of floats [x, y].
-     *
-     * @param dst   The array of dst vectors (x,y pairs)
-     * @param src   The array of src vectors (x,y pairs)
-     */
-    @Override
-    public void mapVectors(float[] dst, float[] src) {
-        if (dst.length != src.length) {
-            throw new ArrayIndexOutOfBoundsException();
-        }
-        mapVectors(dst, 0, src, 0, dst.length >> 1);
-    }
-
-    /**
-     * Apply this matrix to the array of 2D points, and write the transformed
-     * points back into the array
-     *
-     * @param pts The array [x0, y0, x1, y1, ...] of points to transform.
-     */
-    @Override
-    public void mapPoints(float[] pts) {
-        mapPoints(pts, 0, pts, 0, pts.length >> 1);
-    }
-
-    /**
-     * Apply this matrix to the array of 2D vectors, and write the transformed
-     * vectors back into the array.
-     * @param vecs The array [x0, y0, x1, y1, ...] of vectors to transform.
-     */
-    @Override
-    public void mapVectors(float[] vecs) {
-        mapVectors(vecs, 0, vecs, 0, vecs.length >> 1);
-    }
-
-    /**
-     * Apply this matrix to the src rectangle, and write the transformed
-     * rectangle into dst. This is accomplished by transforming the 4 corners of
-     * src, and then setting dst to the bounds of those points.
-     *
-     * @param dst Where the transformed rectangle is written.
-     * @param src The original rectangle to be transformed.
-     * @return the result of calling rectStaysRect()
-     */
-    @Override
-    public boolean mapRect(RectF dst, RectF src) {
-        if (dst == null || src == null) {
-            throw new NullPointerException();
-        }
-
-        // array with 4 corners
-        float[] corners = new float[] {
-                src.left, src.top,
-                src.right, src.top,
-                src.right, src.bottom,
-                src.left, src.bottom,
-        };
-
-        // apply the transform to them.
-        mapPoints(corners);
-
-        // now put the result in the rect. We take the min/max of Xs and min/max of Ys
-        dst.left = Math.min(Math.min(corners[0], corners[2]), Math.min(corners[4], corners[6]));
-        dst.right = Math.max(Math.max(corners[0], corners[2]), Math.max(corners[4], corners[6]));
-
-        dst.top = Math.min(Math.min(corners[1], corners[3]), Math.min(corners[5], corners[7]));
-        dst.bottom = Math.max(Math.max(corners[1], corners[3]), Math.max(corners[5], corners[7]));
-
-        return rectStaysRect();
-    }
-
-    /**
-     * Apply this matrix to the rectangle, and write the transformed rectangle
-     * back into it. This is accomplished by transforming the 4 corners of rect,
-     * and then setting it to the bounds of those points
-     *
-     * @param rect The rectangle to transform.
-     * @return the result of calling rectStaysRect()
-     */
-    @Override
-    public boolean mapRect(RectF rect) {
-        return mapRect(rect, rect);
-    }
-
-    /**
-     * Return the mean radius of a circle after it has been mapped by
-     * this matrix. NOTE: in perspective this value assumes the circle
-     * has its center at the origin.
-     */
-    @Override
-    public float mapRadius(float radius) {
-        throw new UnsupportedOperationException("STUB NEEDED");
-    }
-
-    /** Copy 9 values from the matrix into the array.
-    */
-    @Override
-    public void getValues(float[] values) {
-        if (values.length < 9) {
-            throw new ArrayIndexOutOfBoundsException();
-        }
-        System.arraycopy(mValues, 0, values, 0, mValues.length);
-    }
-
-    /** Copy 9 values from the array into the matrix.
-        Depending on the implementation of Matrix, these may be
-        transformed into 16.16 integers in the Matrix, such that
-        a subsequent call to getValues() will not yield exactly
-        the same values.
-    */
-    @Override
-    public void setValues(float[] values) {
-        if (values.length < 9) {
-            throw new ArrayIndexOutOfBoundsException();
-        }
-        System.arraycopy(values, 0, mValues, 0, mValues.length);
-    }
-
-    @SuppressWarnings("unused")
-    private final static int kIdentity_Mask      = 0;
-    private final static int kTranslate_Mask     = 0x01;  //!< set if the matrix has translation
-    private final static int kScale_Mask         = 0x02;  //!< set if the matrix has X or Y scale
-    private final static int kAffine_Mask        = 0x04;  //!< set if the matrix skews or rotates
-    private final static int kPerspective_Mask   = 0x08;  //!< set if the matrix is in perspective
-    private final static int kRectStaysRect_Mask = 0x10;
-    @SuppressWarnings("unused")
-    private final static int kUnknown_Mask       = 0x80;
-
-    @SuppressWarnings("unused")
-    private final static int kAllMasks           = kTranslate_Mask |
-                                                     kScale_Mask |
-                                                     kAffine_Mask |
-                                                     kPerspective_Mask |
-                                                     kRectStaysRect_Mask;
-
-    // these guys align with the masks, so we can compute a mask from a variable 0/1
-    @SuppressWarnings("unused")
-    private final static int kTranslate_Shift = 0;
-    @SuppressWarnings("unused")
-    private final static int kScale_Shift = 1;
-    @SuppressWarnings("unused")
-    private final static int kAffine_Shift = 2;
-    @SuppressWarnings("unused")
-    private final static int kPerspective_Shift = 3;
-    private final static int kRectStaysRect_Shift = 4;
-
-    private int computeTypeMask() {
-        int mask = 0;
-
-        if (mValues[6] != 0. || mValues[7] != 0. || mValues[8] != 1.) {
-            mask |= kPerspective_Mask;
-        }
-
-        if (mValues[2] != 0. || mValues[5] != 0.) {
-            mask |= kTranslate_Mask;
-        }
-
-        float m00 = mValues[0];
-        float m01 = mValues[1];
-        float m10 = mValues[3];
-        float m11 = mValues[4];
-
-        if (m01 != 0. || m10 != 0.) {
-            mask |= kAffine_Mask;
-        }
-
-        if (m00 != 1. || m11 != 1.) {
-            mask |= kScale_Mask;
-        }
-
-        if ((mask & kPerspective_Mask) == 0) {
-            // map non-zero to 1
-            int im00 = m00 != 0 ? 1 : 0;
-            int im01 = m01 != 0 ? 1 : 0;
-            int im10 = m10 != 0 ? 1 : 0;
-            int im11 = m11 != 0 ? 1 : 0;
-
-            // record if the (p)rimary and (s)econdary diagonals are all 0 or
-            // all non-zero (answer is 0 or 1)
-            int dp0 = (im00 | im11) ^ 1;  // true if both are 0
-            int dp1 = im00 & im11;        // true if both are 1
-            int ds0 = (im01 | im10) ^ 1;  // true if both are 0
-            int ds1 = im01 & im10;        // true if both are 1
-
-            // return 1 if primary is 1 and secondary is 0 or
-            // primary is 0 and secondary is 1
-            mask |= ((dp0 & ds1) | (dp1 & ds0)) << kRectStaysRect_Shift;
-        }
-
-        return mask;
-    }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Matrix_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Matrix_Delegate.java
new file mode 100644
index 0000000..451edd2
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/Matrix_Delegate.java
@@ -0,0 +1,1129 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import android.graphics.Matrix.ScaleToFit;
+
+import java.awt.geom.AffineTransform;
+import java.awt.geom.NoninvertibleTransformException;
+
+/**
+ * Delegate implementing the native methods of android.graphics.Matrix
+ *
+ * Through the layoutlib_create tool, the original native methods of Matrix have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original Matrix class.
+ *
+ * @see DelegateManager
+ *
+ */
+public final class Matrix_Delegate {
+
+    private final static int MATRIX_SIZE = 9;
+
+    // ---- delegate manager ----
+    private static final DelegateManager<Matrix_Delegate> sManager =
+            new DelegateManager<Matrix_Delegate>(Matrix_Delegate.class);
+
+    // ---- delegate data ----
+    private float mValues[] = new float[MATRIX_SIZE];
+
+    // ---- Public Helper methods ----
+
+    public static Matrix_Delegate getDelegate(int native_instance) {
+        return sManager.getDelegate(native_instance);
+    }
+
+    /**
+     * Returns an {@link AffineTransform} matching the given Matrix.
+     */
+    public static AffineTransform getAffineTransform(Matrix m) {
+        Matrix_Delegate delegate = sManager.getDelegate(m.native_instance);
+        if (delegate == null) {
+            return null;
+        }
+
+        return delegate.getAffineTransform();
+    }
+
+    public static boolean hasPerspective(Matrix m) {
+        Matrix_Delegate delegate = sManager.getDelegate(m.native_instance);
+        if (delegate == null) {
+            return false;
+        }
+
+        return delegate.hasPerspective();
+    }
+
+    /**
+     * Sets the content of the matrix with the content of another matrix.
+     */
+    public void set(Matrix_Delegate matrix) {
+        System.arraycopy(matrix.mValues, 0, mValues, 0, MATRIX_SIZE);
+    }
+
+    /**
+     * Sets the content of the matrix with the content of another matrix represented as an array
+     * of values.
+     */
+    public void set(float[] values) {
+        System.arraycopy(values, 0, mValues, 0, MATRIX_SIZE);
+    }
+
+    /**
+     * Resets the matrix to be the identity matrix.
+     */
+    public void reset() {
+        reset(mValues);
+    }
+
+    /**
+     * Returns whether or not the matrix is identity.
+     */
+    public boolean isIdentity() {
+        for (int i = 0, k = 0; i < 3; i++) {
+            for (int j = 0; j < 3; j++, k++) {
+                if (mValues[k] != ((i==j) ? 1 : 0)) {
+                    return false;
+                }
+            }
+        }
+
+        return true;
+    }
+
+    public static float[] makeValues(AffineTransform matrix) {
+        float[] values = new float[MATRIX_SIZE];
+        values[0] = (float) matrix.getScaleX();
+        values[1] = (float) matrix.getShearX();
+        values[2] = (float) matrix.getTranslateX();
+        values[3] = (float) matrix.getShearY();
+        values[4] = (float) matrix.getScaleY();
+        values[5] = (float) matrix.getTranslateY();
+        values[6] = 0.f;
+        values[7] = 0.f;
+        values[8] = 1.f;
+
+        return values;
+    }
+
+    public static Matrix_Delegate make(AffineTransform matrix) {
+        return new Matrix_Delegate(makeValues(matrix));
+    }
+
+    public boolean mapRect(RectF dst, RectF src) {
+        // array with 4 corners
+        float[] corners = new float[] {
+                src.left, src.top,
+                src.right, src.top,
+                src.right, src.bottom,
+                src.left, src.bottom,
+        };
+
+        // apply the transform to them.
+        mapPoints(corners);
+
+        // now put the result in the rect. We take the min/max of Xs and min/max of Ys
+        dst.left = Math.min(Math.min(corners[0], corners[2]), Math.min(corners[4], corners[6]));
+        dst.right = Math.max(Math.max(corners[0], corners[2]), Math.max(corners[4], corners[6]));
+
+        dst.top = Math.min(Math.min(corners[1], corners[3]), Math.min(corners[5], corners[7]));
+        dst.bottom = Math.max(Math.max(corners[1], corners[3]), Math.max(corners[5], corners[7]));
+
+
+        return (computeTypeMask() & kRectStaysRect_Mask) != 0;
+    }
+
+
+    /**
+     * Returns an {@link AffineTransform} matching the matrix.
+     */
+    public AffineTransform getAffineTransform() {
+        return getAffineTransform(mValues);
+    }
+
+    public boolean hasPerspective() {
+        return (mValues[6] != 0 || mValues[7] != 0 || mValues[8] != 1);
+    }
+
+
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int native_create(int native_src_or_zero) {
+        // create the delegate
+        Matrix_Delegate newDelegate = new Matrix_Delegate();
+
+        // copy from values if needed.
+        if (native_src_or_zero > 0) {
+            Matrix_Delegate oldDelegate = sManager.getDelegate(native_src_or_zero);
+            if (oldDelegate != null) {
+                System.arraycopy(
+                        oldDelegate.mValues, 0,
+                        newDelegate.mValues, 0,
+                        MATRIX_SIZE);
+            }
+        }
+
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_isIdentity(int native_object) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        return d.isIdentity();
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_rectStaysRect(int native_object) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return true;
+        }
+
+        return (d.computeTypeMask() & kRectStaysRect_Mask) != 0;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_reset(int native_object) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return;
+        }
+
+        reset(d.mValues);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_set(int native_object, int other) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return;
+        }
+
+        Matrix_Delegate src = sManager.getDelegate(other);
+        if (src == null) {
+            return;
+        }
+
+        System.arraycopy(src.mValues, 0, d.mValues, 0, MATRIX_SIZE);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_setTranslate(int native_object, float dx, float dy) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return;
+        }
+
+        setTranslate(d.mValues, dx, dy);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_setScale(int native_object, float sx, float sy,
+            float px, float py) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return;
+        }
+
+        d.mValues = getScale(sx, sy, px, py);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_setScale(int native_object, float sx, float sy) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return;
+        }
+
+        d.mValues[0] = sx;
+        d.mValues[1] = 0;
+        d.mValues[2] = 0;
+        d.mValues[3] = 0;
+        d.mValues[4] = sy;
+        d.mValues[5] = 0;
+        d.mValues[6] = 0;
+        d.mValues[7] = 0;
+        d.mValues[8] = 1;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_setRotate(int native_object, float degrees, float px, float py) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return;
+        }
+
+        d.mValues = getRotate(degrees, px, py);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_setRotate(int native_object, float degrees) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return;
+        }
+
+        setRotate(d.mValues, degrees);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_setSinCos(int native_object, float sinValue, float cosValue,
+            float px, float py) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return;
+        }
+
+        // TODO: do it in one pass
+
+        // translate so that the pivot is in 0,0
+        setTranslate(d.mValues, -px, -py);
+
+        // scale
+        d.postTransform(getRotate(sinValue, cosValue));
+        // translate back the pivot
+        d.postTransform(getTranslate(px, py));
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_setSinCos(int native_object, float sinValue, float cosValue) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return;
+        }
+
+        setRotate(d.mValues, sinValue, cosValue);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_setSkew(int native_object, float kx, float ky,
+            float px, float py) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return;
+        }
+
+        d.mValues = getSkew(kx, ky, px, py);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_setSkew(int native_object, float kx, float ky) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return;
+        }
+
+        d.mValues[0] = 1;
+        d.mValues[1] = kx;
+        d.mValues[2] = -0;
+        d.mValues[3] = ky;
+        d.mValues[4] = 1;
+        d.mValues[5] = 0;
+        d.mValues[6] = 0;
+        d.mValues[7] = 0;
+        d.mValues[8] = 1;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_setConcat(int native_object, int a, int b) {
+        if (a == native_object) {
+            return native_preConcat(native_object, b);
+        } else if (b == native_object) {
+            return native_postConcat(native_object, a);
+        }
+
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        Matrix_Delegate a_mtx = sManager.getDelegate(a);
+        if (a_mtx == null) {
+            return false;
+        }
+
+        Matrix_Delegate b_mtx = sManager.getDelegate(b);
+        if (b_mtx == null) {
+            return false;
+        }
+
+        multiply(d.mValues, a_mtx.mValues, b_mtx.mValues);
+
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_preTranslate(int native_object, float dx, float dy) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        d.preTransform(getTranslate(dx, dy));
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_preScale(int native_object, float sx, float sy,
+            float px, float py) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        d.preTransform(getScale(sx, sy, px, py));
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_preScale(int native_object, float sx, float sy) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        d.preTransform(getScale(sx, sy));
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_preRotate(int native_object, float degrees,
+            float px, float py) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        d.preTransform(getRotate(degrees, px, py));
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_preRotate(int native_object, float degrees) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        double rad = Math.toRadians(degrees);
+        float sin = (float)Math.sin(rad);
+        float cos = (float)Math.cos(rad);
+
+        d.preTransform(getRotate(sin, cos));
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_preSkew(int native_object, float kx, float ky,
+            float px, float py) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        d.preTransform(getSkew(kx, ky, px, py));
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_preSkew(int native_object, float kx, float ky) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        d.preTransform(getSkew(kx, ky));
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_preConcat(int native_object, int other_matrix) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        Matrix_Delegate other = sManager.getDelegate(other_matrix);
+        if (d == null) {
+            return false;
+        }
+
+        d.preTransform(other.mValues);
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_postTranslate(int native_object, float dx, float dy) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        d.postTransform(getTranslate(dx, dy));
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_postScale(int native_object, float sx, float sy,
+            float px, float py) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        d.postTransform(getScale(sx, sy, px, py));
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_postScale(int native_object, float sx, float sy) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        d.postTransform(getScale(sx, sy));
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_postRotate(int native_object, float degrees,
+            float px, float py) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        d.postTransform(getRotate(degrees, px, py));
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_postRotate(int native_object, float degrees) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        d.postTransform(getRotate(degrees));
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_postSkew(int native_object, float kx, float ky,
+            float px, float py) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        d.postTransform(getSkew(kx, ky, px, py));
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_postSkew(int native_object, float kx, float ky) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        d.postTransform(getSkew(kx, ky));
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_postConcat(int native_object, int other_matrix) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        Matrix_Delegate other = sManager.getDelegate(other_matrix);
+        if (d == null) {
+            return false;
+        }
+
+        d.postTransform(other.mValues);
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_setRectToRect(int native_object, RectF src,
+            RectF dst, int stf) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        if (src.isEmpty()) {
+            reset(d.mValues);
+            return false;
+        }
+
+        if (dst.isEmpty()) {
+            d.mValues[0] = d.mValues[1] = d.mValues[2] = d.mValues[3] = d.mValues[4] = d.mValues[5]
+               = d.mValues[6] = d.mValues[7] = 0;
+            d.mValues[8] = 1;
+        } else {
+            float    tx, sx = dst.width() / src.width();
+            float    ty, sy = dst.height() / src.height();
+            boolean  xLarger = false;
+
+            if (stf != ScaleToFit.FILL.nativeInt) {
+                if (sx > sy) {
+                    xLarger = true;
+                    sx = sy;
+                } else {
+                    sy = sx;
+                }
+            }
+
+            tx = dst.left - src.left * sx;
+            ty = dst.top - src.top * sy;
+            if (stf == ScaleToFit.CENTER.nativeInt || stf == ScaleToFit.END.nativeInt) {
+                float diff;
+
+                if (xLarger) {
+                    diff = dst.width() - src.width() * sy;
+                } else {
+                    diff = dst.height() - src.height() * sy;
+                }
+
+                if (stf == ScaleToFit.CENTER.nativeInt) {
+                    diff = diff / 2;
+                }
+
+                if (xLarger) {
+                    tx += diff;
+                } else {
+                    ty += diff;
+                }
+            }
+
+            d.mValues[0] = sx;
+            d.mValues[4] = sy;
+            d.mValues[2] = tx;
+            d.mValues[5] = ty;
+            d.mValues[1]  = d.mValues[3] = d.mValues[6] = d.mValues[7] = 0;
+
+        }
+        // shared cleanup
+        d.mValues[8] = 1;
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_setPolyToPoly(int native_object, float[] src, int srcIndex,
+            float[] dst, int dstIndex, int pointCount) {
+        // FIXME
+        Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
+                "Matrix.setPolyToPoly is not supported.",
+                null, null /*data*/);
+        return false;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_invert(int native_object, int inverse) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        Matrix_Delegate inv_mtx = sManager.getDelegate(inverse);
+        if (inv_mtx == null) {
+            return false;
+        }
+
+        try {
+            AffineTransform affineTransform = d.getAffineTransform();
+            AffineTransform inverseTransform = affineTransform.createInverse();
+            inv_mtx.mValues[0] = (float)inverseTransform.getScaleX();
+            inv_mtx.mValues[1] = (float)inverseTransform.getShearX();
+            inv_mtx.mValues[2] = (float)inverseTransform.getTranslateX();
+            inv_mtx.mValues[3] = (float)inverseTransform.getScaleX();
+            inv_mtx.mValues[4] = (float)inverseTransform.getShearY();
+            inv_mtx.mValues[5] = (float)inverseTransform.getTranslateY();
+
+            return true;
+        } catch (NoninvertibleTransformException e) {
+            return false;
+        }
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_mapPoints(int native_object, float[] dst, int dstIndex,
+            float[] src, int srcIndex, int ptCount, boolean isPts) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return;
+        }
+
+        if (isPts) {
+            d.mapPoints(dst, dstIndex, src, srcIndex, ptCount);
+        } else {
+            d.mapVectors(dst, dstIndex, src, srcIndex, ptCount);
+        }
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_mapRect(int native_object, RectF dst, RectF src) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return false;
+        }
+
+        return d.mapRect(dst, src);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static float native_mapRadius(int native_object, float radius) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return 0.f;
+        }
+
+        float[] src = new float[] { radius, 0.f, 0.f, radius };
+        d.mapVectors(src, 0, src, 0, 2);
+
+        float l1 = getPointLength(src, 0);
+        float l2 = getPointLength(src, 2);
+
+        return (float) Math.sqrt(l1 * l2);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_getValues(int native_object, float[] values) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return;
+        }
+
+        System.arraycopy(d.mValues, 0, d.mValues, 0, MATRIX_SIZE);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_setValues(int native_object, float[] values) {
+        Matrix_Delegate d = sManager.getDelegate(native_object);
+        if (d == null) {
+            return;
+        }
+
+        System.arraycopy(values, 0, d.mValues, 0, MATRIX_SIZE);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_equals(int native_a, int native_b) {
+        Matrix_Delegate a = sManager.getDelegate(native_a);
+        if (a == null) {
+            return false;
+        }
+
+        Matrix_Delegate b = sManager.getDelegate(native_b);
+        if (b == null) {
+            return false;
+        }
+
+        for (int i = 0 ; i < MATRIX_SIZE ; i++) {
+            if (a.mValues[i] != b.mValues[i]) {
+                return false;
+            }
+        }
+
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void finalizer(int native_instance) {
+        sManager.removeJavaReferenceFor(native_instance);
+    }
+
+    // ---- Private helper methods ----
+
+    /*package*/ static AffineTransform getAffineTransform(float[] matrix) {
+        // the AffineTransform constructor takes the value in a different order
+        // for a matrix [ 0 1 2 ]
+        //              [ 3 4 5 ]
+        // the order is 0, 3, 1, 4, 2, 5...
+        return new AffineTransform(
+                matrix[0], matrix[3], matrix[1],
+                matrix[4], matrix[2], matrix[5]);
+    }
+
+    /**
+     * Reset a matrix to the identity
+     */
+    private static void reset(float[] mtx) {
+        for (int i = 0, k = 0; i < 3; i++) {
+            for (int j = 0; j < 3; j++, k++) {
+                mtx[k] = ((i==j) ? 1 : 0);
+            }
+        }
+    }
+
+    @SuppressWarnings("unused")
+    private final static int kIdentity_Mask      = 0;
+    private final static int kTranslate_Mask     = 0x01;  //!< set if the matrix has translation
+    private final static int kScale_Mask         = 0x02;  //!< set if the matrix has X or Y scale
+    private final static int kAffine_Mask        = 0x04;  //!< set if the matrix skews or rotates
+    private final static int kPerspective_Mask   = 0x08;  //!< set if the matrix is in perspective
+    private final static int kRectStaysRect_Mask = 0x10;
+    @SuppressWarnings("unused")
+    private final static int kUnknown_Mask       = 0x80;
+
+    @SuppressWarnings("unused")
+    private final static int kAllMasks           = kTranslate_Mask |
+                                                   kScale_Mask |
+                                                   kAffine_Mask |
+                                                   kPerspective_Mask |
+                                                   kRectStaysRect_Mask;
+
+    // these guys align with the masks, so we can compute a mask from a variable 0/1
+    @SuppressWarnings("unused")
+    private final static int kTranslate_Shift = 0;
+    @SuppressWarnings("unused")
+    private final static int kScale_Shift = 1;
+    @SuppressWarnings("unused")
+    private final static int kAffine_Shift = 2;
+    @SuppressWarnings("unused")
+    private final static int kPerspective_Shift = 3;
+    private final static int kRectStaysRect_Shift = 4;
+
+    private int computeTypeMask() {
+        int mask = 0;
+
+        if (mValues[6] != 0. || mValues[7] != 0. || mValues[8] != 1.) {
+            mask |= kPerspective_Mask;
+        }
+
+        if (mValues[2] != 0. || mValues[5] != 0.) {
+            mask |= kTranslate_Mask;
+        }
+
+        float m00 = mValues[0];
+        float m01 = mValues[1];
+        float m10 = mValues[3];
+        float m11 = mValues[4];
+
+        if (m01 != 0. || m10 != 0.) {
+            mask |= kAffine_Mask;
+        }
+
+        if (m00 != 1. || m11 != 1.) {
+            mask |= kScale_Mask;
+        }
+
+        if ((mask & kPerspective_Mask) == 0) {
+            // map non-zero to 1
+            int im00 = m00 != 0 ? 1 : 0;
+            int im01 = m01 != 0 ? 1 : 0;
+            int im10 = m10 != 0 ? 1 : 0;
+            int im11 = m11 != 0 ? 1 : 0;
+
+            // record if the (p)rimary and (s)econdary diagonals are all 0 or
+            // all non-zero (answer is 0 or 1)
+            int dp0 = (im00 | im11) ^ 1;  // true if both are 0
+            int dp1 = im00 & im11;        // true if both are 1
+            int ds0 = (im01 | im10) ^ 1;  // true if both are 0
+            int ds1 = im01 & im10;        // true if both are 1
+
+            // return 1 if primary is 1 and secondary is 0 or
+            // primary is 0 and secondary is 1
+            mask |= ((dp0 & ds1) | (dp1 & ds0)) << kRectStaysRect_Shift;
+        }
+
+        return mask;
+    }
+
+    private Matrix_Delegate() {
+        reset();
+    }
+
+    private Matrix_Delegate(float[] values) {
+        System.arraycopy(values, 0, mValues, 0, MATRIX_SIZE);
+    }
+
+    /**
+     * Adds the given transformation to the current Matrix
+     * <p/>This in effect does this = this*matrix
+     * @param matrix
+     */
+    private void postTransform(float[] matrix) {
+        float[] tmp = new float[9];
+        multiply(tmp, mValues, matrix);
+        mValues = tmp;
+    }
+
+    /**
+     * Adds the given transformation to the current Matrix
+     * <p/>This in effect does this = matrix*this
+     * @param matrix
+     */
+    private void preTransform(float[] matrix) {
+        float[] tmp = new float[9];
+        multiply(tmp, matrix, mValues);
+        mValues = tmp;
+    }
+
+    /**
+     * Apply this matrix to the array of 2D points specified by src, and write
+      * the transformed points into the array of points specified by dst. The
+      * two arrays represent their "points" as pairs of floats [x, y].
+      *
+      * @param dst   The array of dst points (x,y pairs)
+      * @param dstIndex The index of the first [x,y] pair of dst floats
+      * @param src   The array of src points (x,y pairs)
+      * @param srcIndex The index of the first [x,y] pair of src floats
+      * @param pointCount The number of points (x,y pairs) to transform
+      */
+
+     private void mapPoints(float[] dst, int dstIndex, float[] src, int srcIndex,
+                           int pointCount) {
+         final int count = pointCount * 2;
+
+         float[] tmpDest = dst;
+         boolean inPlace = dst == src;
+         if (inPlace) {
+             tmpDest = new float[dstIndex + count];
+         }
+
+         for (int i = 0 ; i < count ; i += 2) {
+             // just in case we are doing in place, we better put this in temp vars
+             float x = mValues[0] * src[i + srcIndex] +
+                       mValues[1] * src[i + srcIndex + 1] +
+                       mValues[2];
+             float y = mValues[3] * src[i + srcIndex] +
+                       mValues[4] * src[i + srcIndex + 1] +
+                       mValues[5];
+
+             tmpDest[i + dstIndex]     = x;
+             tmpDest[i + dstIndex + 1] = y;
+         }
+
+         if (inPlace) {
+             System.arraycopy(tmpDest, dstIndex, dst, dstIndex, count);
+         }
+     }
+
+     /**
+      * Apply this matrix to the array of 2D points, and write the transformed
+      * points back into the array
+      *
+      * @param pts The array [x0, y0, x1, y1, ...] of points to transform.
+      */
+
+     private void mapPoints(float[] pts) {
+         mapPoints(pts, 0, pts, 0, pts.length >> 1);
+     }
+
+     private void mapVectors(float[] dst, int dstIndex, float[] src, int srcIndex, int ptCount) {
+         if (hasPerspective()) {
+             // transform the (0,0) point
+             float[] origin = new float[] { 0.f, 0.f};
+             mapPoints(origin);
+
+             // translate the vector data as points
+             mapPoints(dst, dstIndex, src, srcIndex, ptCount);
+
+             // then substract the transformed origin.
+             final int count = ptCount * 2;
+             for (int i = 0 ; i < count ; i += 2) {
+                 dst[dstIndex + i] = dst[dstIndex + i] - origin[0];
+                 dst[dstIndex + i + 1] = dst[dstIndex + i + 1] - origin[1];
+             }
+         } else {
+             // make a copy of the matrix
+             Matrix_Delegate copy = new Matrix_Delegate(mValues);
+
+             // remove the translation
+             setTranslate(copy.mValues, 0, 0);
+
+             // map the content as points.
+             copy.mapPoints(dst, dstIndex, src, srcIndex, ptCount);
+         }
+     }
+
+     private static float getPointLength(float[] src, int index) {
+         return (float) Math.sqrt(src[index] * src[index] + src[index + 1] * src[index + 1]);
+     }
+
+    /**
+     * multiply two matrices and store them in a 3rd.
+     * <p/>This in effect does dest = a*b
+     * dest cannot be the same as a or b.
+     */
+     /*package*/ static void multiply(float dest[], float[] a, float[] b) {
+        // first row
+        dest[0] = b[0] * a[0] + b[1] * a[3] + b[2] * a[6];
+        dest[1] = b[0] * a[1] + b[1] * a[4] + b[2] * a[7];
+        dest[2] = b[0] * a[2] + b[1] * a[5] + b[2] * a[8];
+
+        // 2nd row
+        dest[3] = b[3] * a[0] + b[4] * a[3] + b[5] * a[6];
+        dest[4] = b[3] * a[1] + b[4] * a[4] + b[5] * a[7];
+        dest[5] = b[3] * a[2] + b[4] * a[5] + b[5] * a[8];
+
+        // 3rd row
+        dest[6] = b[6] * a[0] + b[7] * a[3] + b[8] * a[6];
+        dest[7] = b[6] * a[1] + b[7] * a[4] + b[8] * a[7];
+        dest[8] = b[6] * a[2] + b[7] * a[5] + b[8] * a[8];
+    }
+
+    /**
+     * Returns a matrix that represents a given translate
+     * @param dx
+     * @param dy
+     * @return
+     */
+    /*package*/ static float[] getTranslate(float dx, float dy) {
+        return setTranslate(new float[9], dx, dy);
+    }
+
+    /*package*/ static float[] setTranslate(float[] dest, float dx, float dy) {
+        dest[0] = 1;
+        dest[1] = 0;
+        dest[2] = dx;
+        dest[3] = 0;
+        dest[4] = 1;
+        dest[5] = dy;
+        dest[6] = 0;
+        dest[7] = 0;
+        dest[8] = 1;
+        return dest;
+    }
+
+    /*package*/ static float[] getScale(float sx, float sy) {
+        return new float[] { sx, 0, 0, 0, sy, 0, 0, 0, 1 };
+    }
+
+    /**
+     * Returns a matrix that represents the given scale info.
+     * @param sx
+     * @param sy
+     * @param px
+     * @param py
+     */
+    /*package*/ static float[] getScale(float sx, float sy, float px, float py) {
+        float[] tmp = new float[9];
+        float[] tmp2 = new float[9];
+
+        // TODO: do it in one pass
+
+        // translate tmp so that the pivot is in 0,0
+        setTranslate(tmp, -px, -py);
+
+        // scale into tmp2
+        multiply(tmp2, tmp, getScale(sx, sy));
+
+        // translate back the pivot back into tmp
+        multiply(tmp, tmp2, getTranslate(px, py));
+
+        return tmp;
+    }
+
+
+    /*package*/ static float[] getRotate(float degrees) {
+        double rad = Math.toRadians(degrees);
+        float sin = (float)Math.sin(rad);
+        float cos = (float)Math.cos(rad);
+
+        return getRotate(sin, cos);
+    }
+
+    /*package*/ static float[] getRotate(float sin, float cos) {
+        return setRotate(new float[9], sin, cos);
+    }
+
+    /*package*/ static float[] setRotate(float[] dest, float degrees) {
+        double rad = Math.toRadians(degrees);
+        float sin = (float)Math.sin(rad);
+        float cos = (float)Math.cos(rad);
+
+        return setRotate(dest, sin, cos);
+    }
+
+    /*package*/ static float[] setRotate(float[] dest, float sin, float cos) {
+        dest[0] = cos;
+        dest[1] = -sin;
+        dest[2] = 0;
+        dest[3] = sin;
+        dest[4] = cos;
+        dest[5] = 0;
+        dest[6] = 0;
+        dest[7] = 0;
+        dest[8] = 1;
+        return dest;
+    }
+
+    /*package*/ static float[] getRotate(float degrees, float px, float py) {
+        float[] tmp = new float[9];
+        float[] tmp2 = new float[9];
+
+        // TODO: do it in one pass
+
+        // translate so that the pivot is in 0,0
+        setTranslate(tmp, -px, -py);
+
+        // rotate into tmp2
+        double rad = Math.toRadians(degrees);
+        float cos = (float)Math.cos(rad);
+        float sin = (float)Math.sin(rad);
+        multiply(tmp2, tmp, getRotate(sin, cos));
+
+        // translate back the pivot back into tmp
+        multiply(tmp, tmp2, getTranslate(px, py));
+
+        return tmp;
+    }
+
+    /*package*/ static float[] getSkew(float kx, float ky) {
+        return new float[] { 1, kx, 0, ky, 1, 0, 0, 0, 1 };
+    }
+
+    /*package*/ static float[] getSkew(float kx, float ky, float px, float py) {
+        float[] tmp = new float[9];
+        float[] tmp2 = new float[9];
+
+        // TODO: do it in one pass
+
+        // translate so that the pivot is in 0,0
+        setTranslate(tmp, -px, -py);
+
+        // skew into tmp2
+        multiply(tmp2, tmp, new float[] { 1, kx, 0, ky, 1, 0, 0, 0, 1 });
+        // translate back the pivot back into tmp
+        multiply(tmp, tmp2, getTranslate(px, py));
+
+        return tmp;
+    }
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/NinePatch_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/NinePatch_Delegate.java
new file mode 100644
index 0000000..5e882ce
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/NinePatch_Delegate.java
@@ -0,0 +1,225 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.layoutlib.bridge.impl.GcSnapshot;
+import com.android.ninepatch.NinePatchChunk;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import android.graphics.drawable.NinePatchDrawable;
+
+import java.awt.Graphics2D;
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.lang.ref.SoftReference;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Delegate implementing the native methods of android.graphics.NinePatch
+ *
+ * Through the layoutlib_create tool, the original native methods of NinePatch have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ * Because it's a stateless class to start with, there's no need to keep a {@link DelegateManager}
+ * around to map int to instance of the delegate.
+ *
+ */
+public final class NinePatch_Delegate {
+
+    /**
+     * Cache map for {@link NinePatchChunk}.
+     * When the chunks are created they are serialized into a byte[], and both are put
+     * in the cache, using a {@link SoftReference} for the chunk. The default Java classes
+     * for {@link NinePatch} and {@link NinePatchDrawable} only reference to the byte[] data, and
+     * provide this for drawing.
+     * Using the cache map allows us to not have to deserialize the byte[] back into a
+     * {@link NinePatchChunk} every time a rendering is done.
+     */
+    private final static Map<byte[], SoftReference<NinePatchChunk>> sChunkCache =
+        new HashMap<byte[], SoftReference<NinePatchChunk>>();
+
+    // ---- Public Helper methods ----
+
+    /**
+     * Serializes the given chunk.
+     *
+     * @return the serialized data for the chunk.
+     */
+    public static byte[] serialize(NinePatchChunk chunk) {
+        // serialize the chunk to get a byte[]
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        ObjectOutputStream oos = null;
+        try {
+            oos = new ObjectOutputStream(baos);
+            oos.writeObject(chunk);
+        } catch (IOException e) {
+            Bridge.getLog().error(null, "Failed to serialize NinePatchChunk.", e, null /*data*/);
+            return null;
+        } finally {
+            if (oos != null) {
+                try {
+                    oos.close();
+                } catch (IOException e) {
+                }
+            }
+        }
+
+        // get the array and add it to the cache
+        byte[] array = baos.toByteArray();
+        sChunkCache.put(array, new SoftReference<NinePatchChunk>(chunk));
+        return array;
+    }
+
+    /**
+     * Returns a {@link NinePatchChunk} object for the given serialized representation.
+     *
+     * If the chunk is present in the cache then the object from the cache is returned, otherwise
+     * the array is deserialized into a {@link NinePatchChunk} object.
+     *
+     * @param array the serialized representation of the chunk.
+     * @return the NinePatchChunk or null if deserialization failed.
+     */
+    public static NinePatchChunk getChunk(byte[] array) {
+        SoftReference<NinePatchChunk> chunkRef = sChunkCache.get(array);
+        NinePatchChunk chunk = chunkRef.get();
+        if (chunk == null) {
+            ByteArrayInputStream bais = new ByteArrayInputStream(array);
+            ObjectInputStream ois = null;
+            try {
+                ois = new ObjectInputStream(bais);
+                chunk = (NinePatchChunk) ois.readObject();
+
+                // put back the chunk in the cache
+                if (chunk != null) {
+                    sChunkCache.put(array, new SoftReference<NinePatchChunk>(chunk));
+                }
+            } catch (IOException e) {
+                Bridge.getLog().error(LayoutLog.TAG_BROKEN,
+                        "Failed to deserialize NinePatchChunk content.", e, null /*data*/);
+                return null;
+            } catch (ClassNotFoundException e) {
+                Bridge.getLog().error(LayoutLog.TAG_BROKEN,
+                        "Failed to deserialize NinePatchChunk class.", e, null /*data*/);
+                return null;
+            } finally {
+                if (ois != null) {
+                    try {
+                        ois.close();
+                    } catch (IOException e) {
+                    }
+                }
+            }
+        }
+
+        return chunk;
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static boolean isNinePatchChunk(byte[] chunk) {
+        NinePatchChunk chunkObject = getChunk(chunk);
+        if (chunkObject != null) {
+            return true;
+        }
+
+        return false;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void validateNinePatchChunk(int bitmap, byte[] chunk) {
+        // the default JNI implementation only checks that the byte[] has the same
+        // size as the C struct it represent. Since we cannot do the same check (serialization
+        // will return different size depending on content), we do nothing.
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeDraw(int canvas_instance, RectF loc, int bitmap_instance,
+            byte[] c, int paint_instance_or_null, int destDensity, int srcDensity) {
+        draw(canvas_instance,
+                (int) loc.left, (int) loc.top, (int) loc.width(), (int) loc.height(),
+                bitmap_instance, c, paint_instance_or_null,
+                destDensity, srcDensity);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeDraw(int canvas_instance, Rect loc, int bitmap_instance,
+            byte[] c, int paint_instance_or_null, int destDensity, int srcDensity) {
+        draw(canvas_instance,
+                loc.left, loc.top, loc.width(), loc.height(),
+                bitmap_instance, c, paint_instance_or_null,
+                destDensity, srcDensity);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeGetTransparentRegion(int bitmap, byte[] chunk, Rect location) {
+        return 0;
+    }
+
+    // ---- Private Helper methods ----
+
+    private static void draw(int canvas_instance,
+            final int left, final int top, final int right, final int bottom,
+            int bitmap_instance, byte[] c, int paint_instance_or_null,
+            final int destDensity, final int srcDensity) {
+        // get the delegate from the native int.
+        final Bitmap_Delegate bitmap_delegate = Bitmap_Delegate.getDelegate(bitmap_instance);
+        if (bitmap_delegate == null) {
+            return;
+        }
+
+        if (c == null) {
+            // not a 9-patch?
+            BufferedImage image = bitmap_delegate.getImage();
+            Canvas_Delegate.native_drawBitmap(canvas_instance, bitmap_instance,
+                    new Rect(0, 0, image.getWidth(), image.getHeight()),
+                    new Rect(left, top, right, bottom),
+                    paint_instance_or_null, destDensity, srcDensity);
+            return;
+        }
+
+        final NinePatchChunk chunkObject = getChunk(c);
+        assert chunkObject != null;
+        if (chunkObject == null) {
+            return;
+        }
+
+        Canvas_Delegate canvas_delegate = Canvas_Delegate.getDelegate(canvas_instance);
+        if (canvas_delegate == null) {
+            return;
+        }
+
+        // this one can be null
+        Paint_Delegate paint_delegate = Paint_Delegate.getDelegate(paint_instance_or_null);
+
+        canvas_delegate.getSnapshot().draw(new GcSnapshot.Drawable() {
+                public void draw(Graphics2D graphics, Paint_Delegate paint) {
+                    chunkObject.draw(bitmap_delegate.getImage(), graphics,
+                            left, top, right - left, bottom - top, destDensity, srcDensity);
+                }
+            }, paint_delegate, true /*compositeOnly*/, false /*forceSrcMode*/);
+
+     }
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Paint.java b/tools/layoutlib/bridge/src/android/graphics/Paint.java
deleted file mode 100644
index d13b5fe..0000000
--- a/tools/layoutlib/bridge/src/android/graphics/Paint.java
+++ /dev/null
@@ -1,1211 +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.graphics;
-
-import android.text.SpannableString;
-import android.text.SpannableStringBuilder;
-import android.text.SpannedString;
-import android.text.TextUtils;
-
-import java.awt.BasicStroke;
-import java.awt.Font;
-import java.awt.Toolkit;
-import java.awt.font.FontRenderContext;
-import java.awt.geom.AffineTransform;
-import java.awt.geom.Rectangle2D;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * A paint implementation overridden by the LayoutLib bridge.
- */
-public class Paint extends _Original_Paint {
-
-    private int mColor = 0xFFFFFFFF;
-    private float mStrokeWidth = 1.f;
-    private float mTextSize = 20;
-    private float mScaleX = 1;
-    private float mSkewX = 0;
-    private Align mAlign = Align.LEFT;
-    private Style mStyle = Style.FILL;
-    private float mStrokeMiter = 4.0f;
-    private Cap mCap = Cap.BUTT;
-    private Join mJoin = Join.MITER;
-    private int mFlags = 0;
-
-    /**
-     * Class associating a {@link Font} and it's {@link java.awt.FontMetrics}.
-     */
-    public static final class FontInfo {
-        Font mFont;
-        java.awt.FontMetrics mMetrics;
-    }
-
-    private List<FontInfo> mFonts;
-    private final FontRenderContext mFontContext = new FontRenderContext(
-            new AffineTransform(), true, true);
-
-    public static final int ANTI_ALIAS_FLAG       = _Original_Paint.ANTI_ALIAS_FLAG;
-    public static final int FILTER_BITMAP_FLAG    = _Original_Paint.FILTER_BITMAP_FLAG;
-    public static final int DITHER_FLAG           = _Original_Paint.DITHER_FLAG;
-    public static final int UNDERLINE_TEXT_FLAG   = _Original_Paint.UNDERLINE_TEXT_FLAG;
-    public static final int STRIKE_THRU_TEXT_FLAG = _Original_Paint.STRIKE_THRU_TEXT_FLAG;
-    public static final int FAKE_BOLD_TEXT_FLAG   = _Original_Paint.FAKE_BOLD_TEXT_FLAG;
-    public static final int LINEAR_TEXT_FLAG      = _Original_Paint.LINEAR_TEXT_FLAG;
-    public static final int SUBPIXEL_TEXT_FLAG    = _Original_Paint.SUBPIXEL_TEXT_FLAG;
-    public static final int DEV_KERN_TEXT_FLAG    = _Original_Paint.DEV_KERN_TEXT_FLAG;
-
-    public static class FontMetrics extends _Original_Paint.FontMetrics {
-    }
-
-    public static class FontMetricsInt extends _Original_Paint.FontMetricsInt {
-    }
-
-    /**
-     * The Style specifies if the primitive being drawn is filled,
-     * stroked, or both (in the same color). The default is FILL.
-     */
-    public enum Style {
-        /**
-         * Geometry and text drawn with this style will be filled, ignoring all
-         * stroke-related settings in the paint.
-         */
-        FILL            (0),
-        /**
-         * Geometry and text drawn with this style will be stroked, respecting
-         * the stroke-related fields on the paint.
-         */
-        STROKE          (1),
-        /**
-         * Geometry and text drawn with this style will be both filled and
-         * stroked at the same time, respecting the stroke-related fields on
-         * the paint.
-         */
-        FILL_AND_STROKE (2);
-
-        Style(int nativeInt) {
-            this.nativeInt = nativeInt;
-        }
-        final int nativeInt;
-    }
-
-    /**
-     * The Cap specifies the treatment for the beginning and ending of
-     * stroked lines and paths. The default is BUTT.
-     */
-    public enum Cap {
-        /**
-         * The stroke ends with the path, and does not project beyond it.
-         */
-        BUTT    (0),
-        /**
-         * The stroke projects out as a square, with the center at the end
-         * of the path.
-         */
-        ROUND   (1),
-        /**
-         * The stroke projects out as a semicircle, with the center at the
-         * end of the path.
-         */
-        SQUARE  (2);
-
-        private Cap(int nativeInt) {
-            this.nativeInt = nativeInt;
-        }
-        final int nativeInt;
-
-        /** custom for layoutlib */
-        public int getJavaCap() {
-            switch (this) {
-                case BUTT:
-                    return BasicStroke.CAP_BUTT;
-                case ROUND:
-                    return BasicStroke.CAP_ROUND;
-                default:
-                case SQUARE:
-                    return BasicStroke.CAP_SQUARE;
-            }
-        }
-    }
-
-    /**
-     * The Join specifies the treatment where lines and curve segments
-     * join on a stroked path. The default is MITER.
-     */
-    public enum Join {
-        /**
-         * The outer edges of a join meet at a sharp angle
-         */
-        MITER   (0),
-        /**
-         * The outer edges of a join meet in a circular arc.
-         */
-        ROUND   (1),
-        /**
-         * The outer edges of a join meet with a straight line
-         */
-        BEVEL   (2);
-
-        private Join(int nativeInt) {
-            this.nativeInt = nativeInt;
-        }
-        final int nativeInt;
-
-        /** custom for layoutlib */
-        public int getJavaJoin() {
-            switch (this) {
-                default:
-                case MITER:
-                    return BasicStroke.JOIN_MITER;
-                case ROUND:
-                    return BasicStroke.JOIN_ROUND;
-                case BEVEL:
-                    return BasicStroke.JOIN_BEVEL;
-            }
-        }
-    }
-
-    /**
-     * Align specifies how drawText aligns its text relative to the
-     * [x,y] coordinates. The default is LEFT.
-     */
-    public enum Align {
-        /**
-         * The text is drawn to the right of the x,y origin
-         */
-        LEFT    (0),
-        /**
-         * The text is drawn centered horizontally on the x,y origin
-         */
-        CENTER  (1),
-        /**
-         * The text is drawn to the left of the x,y origin
-         */
-        RIGHT   (2);
-
-        private Align(int nativeInt) {
-            this.nativeInt = nativeInt;
-        }
-        final int nativeInt;
-    }
-
-    public Paint() {
-        this(0);
-    }
-
-    /*
-     * Do not remove or com.android.layoutlib.bridge.TestClassReplacement fails.
-     */
-    @Override
-    public void finalize() { }
-
-    public Paint(int flags) {
-        setFlags(flags | DEFAULT_PAINT_FLAGS);
-        initFont();
-    }
-
-    public Paint(Paint paint) {
-        set(paint);
-        initFont();
-    }
-
-    @Override
-    public void reset() {
-        super.reset();
-    }
-
-    /**
-     * Returns the list of {@link Font} objects. The first item is the main font, the rest
-     * are fall backs for characters not present in the main font.
-     */
-    public List<FontInfo> getFonts() {
-        return mFonts;
-    }
-
-    private void initFont() {
-        mTypeface = Typeface.DEFAULT;
-        updateFontObject();
-    }
-
-    /**
-     * Update the {@link Font} object from the typeface, text size and scaling
-     */
-    @SuppressWarnings("deprecation")
-    private void updateFontObject() {
-        if (mTypeface != null) {
-            // Get the fonts from the TypeFace object.
-            List<Font> fonts = mTypeface.getFonts();
-
-            // create new font objects as well as FontMetrics, based on the current text size
-            // and skew info.
-            ArrayList<FontInfo> infoList = new ArrayList<FontInfo>(fonts.size());
-            for (Font font : fonts) {
-                FontInfo info = new FontInfo();
-                info.mFont = font.deriveFont(mTextSize);
-                if (mScaleX != 1.0 || mSkewX != 0) {
-                    // TODO: support skew
-                    info.mFont = info.mFont.deriveFont(new AffineTransform(
-                            mScaleX, mSkewX, 0, 0, 1, 0));
-                }
-                info.mMetrics = Toolkit.getDefaultToolkit().getFontMetrics(info.mFont);
-
-                infoList.add(info);
-            }
-
-            mFonts = Collections.unmodifiableList(infoList);
-        }
-    }
-
-    //----------------------------------------
-
-    public void set(Paint src) {
-        if (this != src) {
-            mColor = src.mColor;
-            mTextSize = src.mTextSize;
-            mScaleX = src.mScaleX;
-            mSkewX = src.mSkewX;
-            mAlign = src.mAlign;
-            mStyle = src.mStyle;
-            mFlags = src.mFlags;
-
-            updateFontObject();
-
-            super.set(src);
-        }
-    }
-
-    @Override
-    public void setCompatibilityScaling(float factor) {
-        super.setCompatibilityScaling(factor);
-    }
-
-    @Override
-    public int getFlags() {
-        return mFlags;
-    }
-
-    @Override
-    public void setFlags(int flags) {
-        mFlags = flags;
-    }
-
-    @Override
-    public boolean isAntiAlias() {
-        return super.isAntiAlias();
-    }
-
-    @Override
-    public boolean isDither() {
-        return super.isDither();
-    }
-
-    @Override
-    public boolean isLinearText() {
-        return super.isLinearText();
-    }
-
-    @Override
-    public boolean isStrikeThruText() {
-        return super.isStrikeThruText();
-    }
-
-    @Override
-    public boolean isUnderlineText() {
-        return super.isUnderlineText();
-    }
-
-    @Override
-    public boolean isFakeBoldText() {
-        return super.isFakeBoldText();
-    }
-
-    @Override
-    public boolean isSubpixelText() {
-        return super.isSubpixelText();
-    }
-
-    @Override
-    public boolean isFilterBitmap() {
-        return super.isFilterBitmap();
-    }
-
-    /**
-     * Return the font's recommended interline spacing, given the Paint's
-     * settings for typeface, textSize, etc. If metrics is not null, return the
-     * fontmetric values in it.
-     *
-     * @param metrics If this object is not null, its fields are filled with
-     *                the appropriate values given the paint's text attributes.
-     * @return the font's recommended interline spacing.
-     */
-    public float getFontMetrics(FontMetrics metrics) {
-        if (mFonts.size() > 0) {
-            java.awt.FontMetrics javaMetrics = mFonts.get(0).mMetrics;
-            if (metrics != null) {
-                // Android expects negative ascent so we invert the value from Java.
-                metrics.top = - javaMetrics.getMaxAscent();
-                metrics.ascent = - javaMetrics.getAscent();
-                metrics.descent = javaMetrics.getDescent();
-                metrics.bottom = javaMetrics.getMaxDescent();
-                metrics.leading = javaMetrics.getLeading();
-            }
-
-            return javaMetrics.getHeight();
-        }
-
-        return 0;
-    }
-
-    public int getFontMetricsInt(FontMetricsInt metrics) {
-        if (mFonts.size() > 0) {
-            java.awt.FontMetrics javaMetrics = mFonts.get(0).mMetrics;
-            if (metrics != null) {
-                // Android expects negative ascent so we invert the value from Java.
-                metrics.top = - javaMetrics.getMaxAscent();
-                metrics.ascent = - javaMetrics.getAscent();
-                metrics.descent = javaMetrics.getDescent();
-                metrics.bottom = javaMetrics.getMaxDescent();
-                metrics.leading = javaMetrics.getLeading();
-            }
-
-            return javaMetrics.getHeight();
-        }
-
-        return 0;
-    }
-
-    /**
-     * Reimplemented to return Paint.FontMetrics instead of _Original_Paint.FontMetrics
-     */
-    public FontMetrics getFontMetrics() {
-        FontMetrics fm = new FontMetrics();
-        getFontMetrics(fm);
-        return fm;
-    }
-
-    /**
-     * Reimplemented to return Paint.FontMetricsInt instead of _Original_Paint.FontMetricsInt
-     */
-    public FontMetricsInt getFontMetricsInt() {
-        FontMetricsInt fm = new FontMetricsInt();
-        getFontMetricsInt(fm);
-        return fm;
-    }
-
-
-
-    @Override
-    public float getFontMetrics(_Original_Paint.FontMetrics metrics) {
-        throw new UnsupportedOperationException("CALL TO PARENT FORBIDDEN");
-    }
-
-    @Override
-    public int getFontMetricsInt(_Original_Paint.FontMetricsInt metrics) {
-        throw new UnsupportedOperationException("CALL TO PARENT FORBIDDEN");
-    }
-
-    @Override
-    public Typeface setTypeface(Typeface typeface) {
-        if (typeface != null) {
-            mTypeface = typeface;
-        } else {
-            mTypeface = Typeface.DEFAULT;
-        }
-
-        updateFontObject();
-
-        return typeface;
-    }
-
-    @Override
-    public Typeface getTypeface() {
-        return super.getTypeface();
-    }
-
-    @Override
-    public int getColor() {
-        return mColor;
-    }
-
-    @Override
-    public void setColor(int color) {
-        mColor = color;
-    }
-
-    @Override
-    public void setARGB(int a, int r, int g, int b) {
-        super.setARGB(a, r, g, b);
-    }
-
-    @Override
-    public void setAlpha(int alpha) {
-        mColor = (alpha << 24) | (mColor & 0x00FFFFFF);
-    }
-
-    @Override
-    public int getAlpha() {
-        return mColor >>> 24;
-    }
-
-    /**
-     * Set or clear the shader object.
-     * <p />
-     * Pass null to clear any previous shader.
-     * As a convenience, the parameter passed is also returned.
-     *
-     * @param shader May be null. the new shader to be installed in the paint
-     * @return       shader
-     */
-    @Override
-    public Shader setShader(Shader shader) {
-        return mShader = shader;
-    }
-
-    @Override
-    public Shader getShader() {
-        return super.getShader();
-    }
-
-    /**
-     * Set or clear the paint's colorfilter, returning the parameter.
-     *
-     * @param filter May be null. The new filter to be installed in the paint
-     * @return       filter
-     */
-    @Override
-    public ColorFilter setColorFilter(ColorFilter filter) {
-        mColorFilter = filter;
-        return filter;
-    }
-
-    @Override
-    public ColorFilter getColorFilter() {
-        return super.getColorFilter();
-    }
-
-    /**
-     * Set or clear the xfermode object.
-     * <p />
-     * Pass null to clear any previous xfermode.
-     * As a convenience, the parameter passed is also returned.
-     *
-     * @param xfermode May be null. The xfermode to be installed in the paint
-     * @return         xfermode
-     */
-    @Override
-    public Xfermode setXfermode(Xfermode xfermode) {
-        return mXfermode = xfermode;
-    }
-
-    @Override
-    public Xfermode getXfermode() {
-        return super.getXfermode();
-    }
-
-    @Override
-    public Rasterizer setRasterizer(Rasterizer rasterizer) {
-        mRasterizer = rasterizer;
-        return rasterizer;
-    }
-
-    @Override
-    public Rasterizer getRasterizer() {
-        return super.getRasterizer();
-    }
-
-    @Override
-    public void setShadowLayer(float radius, float dx, float dy, int color) {
-        // TODO Auto-generated method stub
-    }
-
-    @Override
-    public void clearShadowLayer() {
-        super.clearShadowLayer();
-    }
-
-    public void setTextAlign(Align align) {
-        mAlign = align;
-    }
-
-    @Override
-    public void setTextAlign(android.graphics._Original_Paint.Align align) {
-        throw new UnsupportedOperationException("CALL TO PARENT FORBIDDEN");
-    }
-
-    public Align getTextAlign() {
-        return mAlign;
-    }
-
-    public void setStyle(Style style) {
-        mStyle = style;
-    }
-
-    @Override
-    public void setStyle(android.graphics._Original_Paint.Style style) {
-        throw new UnsupportedOperationException("CALL TO PARENT FORBIDDEN");
-    }
-
-    public Style getStyle() {
-        return mStyle;
-    }
-
-    @Override
-    public void setDither(boolean dither) {
-        mFlags |= dither ? DITHER_FLAG : ~DITHER_FLAG;
-    }
-
-    @Override
-    public void setAntiAlias(boolean aa) {
-        mFlags |= aa ? ANTI_ALIAS_FLAG : ~ANTI_ALIAS_FLAG;
-    }
-
-    @Override
-    public void setFakeBoldText(boolean flag) {
-        mFlags |= flag ? FAKE_BOLD_TEXT_FLAG : ~FAKE_BOLD_TEXT_FLAG;
-    }
-
-    @Override
-    public void setLinearText(boolean flag) {
-        mFlags |= flag ? LINEAR_TEXT_FLAG : ~LINEAR_TEXT_FLAG;
-    }
-
-    @Override
-    public void setSubpixelText(boolean flag) {
-        mFlags |= flag ? SUBPIXEL_TEXT_FLAG : ~SUBPIXEL_TEXT_FLAG;
-    }
-
-    @Override
-    public void setUnderlineText(boolean flag) {
-        mFlags |= flag ? UNDERLINE_TEXT_FLAG : ~UNDERLINE_TEXT_FLAG;
-    }
-
-    @Override
-    public void setStrikeThruText(boolean flag) {
-        mFlags |= flag ? STRIKE_THRU_TEXT_FLAG : ~STRIKE_THRU_TEXT_FLAG;
-    }
-
-    @Override
-    public void setFilterBitmap(boolean flag) {
-        mFlags |= flag ? FILTER_BITMAP_FLAG : ~FILTER_BITMAP_FLAG;
-    }
-
-    @Override
-    public float getStrokeWidth() {
-        return mStrokeWidth;
-    }
-
-    @Override
-    public void setStrokeWidth(float width) {
-        mStrokeWidth = width;
-    }
-
-    @Override
-    public float getStrokeMiter() {
-        return mStrokeMiter;
-    }
-
-    @Override
-    public void setStrokeMiter(float miter) {
-        mStrokeMiter = miter;
-    }
-
-    @Override
-    public void setStrokeCap(android.graphics._Original_Paint.Cap cap) {
-        throw new UnsupportedOperationException("CALL TO PARENT FORBIDDEN");
-    }
-
-    public void setStrokeCap(Cap cap) {
-        mCap = cap;
-    }
-
-    public Cap getStrokeCap() {
-        return mCap;
-    }
-
-    @Override
-    public void setStrokeJoin(android.graphics._Original_Paint.Join join) {
-        throw new UnsupportedOperationException("CALL TO PARENT FORBIDDEN");
-    }
-
-    public void setStrokeJoin(Join join) {
-        mJoin = join;
-    }
-
-    public Join getStrokeJoin() {
-        return mJoin;
-    }
-
-    @Override
-    public boolean getFillPath(Path src, Path dst) {
-        return super.getFillPath(src, dst);
-    }
-
-    @Override
-    public PathEffect setPathEffect(PathEffect effect) {
-        mPathEffect = effect;
-        return effect;
-    }
-
-    @Override
-    public PathEffect getPathEffect() {
-        return super.getPathEffect();
-    }
-
-    @Override
-    public MaskFilter setMaskFilter(MaskFilter maskfilter) {
-        mMaskFilter = maskfilter;
-        return maskfilter;
-    }
-
-    @Override
-    public MaskFilter getMaskFilter() {
-        return super.getMaskFilter();
-    }
-
-    /**
-     * Return the paint's text size.
-     *
-     * @return the paint's text size.
-     */
-    @Override
-    public float getTextSize() {
-        return mTextSize;
-    }
-
-    /**
-     * Set the paint's text size. This value must be > 0
-     *
-     * @param textSize set the paint's text size.
-     */
-    @Override
-    public void setTextSize(float textSize) {
-        mTextSize = textSize;
-
-        updateFontObject();
-    }
-
-    /**
-     * Return the paint's horizontal scale factor for text. The default value
-     * is 1.0.
-     *
-     * @return the paint's scale factor in X for drawing/measuring text
-     */
-    @Override
-    public float getTextScaleX() {
-        return mScaleX;
-    }
-
-    /**
-     * Set the paint's horizontal scale factor for text. The default value
-     * is 1.0. Values > 1.0 will stretch the text wider. Values < 1.0 will
-     * stretch the text narrower.
-     *
-     * @param scaleX set the paint's scale in X for drawing/measuring text.
-     */
-    @Override
-    public void setTextScaleX(float scaleX) {
-        mScaleX = scaleX;
-
-        updateFontObject();
-    }
-
-    /**
-     * Return the paint's horizontal skew factor for text. The default value
-     * is 0.
-     *
-     * @return         the paint's skew factor in X for drawing text.
-     */
-    @Override
-    public float getTextSkewX() {
-        return mSkewX;
-    }
-
-    /**
-     * Set the paint's horizontal skew factor for text. The default value
-     * is 0. For approximating oblique text, use values around -0.25.
-     *
-     * @param skewX set the paint's skew factor in X for drawing text.
-     */
-    @Override
-    public void setTextSkewX(float skewX) {
-        mSkewX = skewX;
-
-        updateFontObject();
-    }
-
-    @Override
-    public float getFontSpacing() {
-        return super.getFontSpacing();
-    }
-
-    /**
-     * Return the distance above (negative) the baseline (ascent) based on the
-     * current typeface and text size.
-     *
-     * @return the distance above (negative) the baseline (ascent) based on the
-     *         current typeface and text size.
-     */
-    @Override
-    public float ascent() {
-        if (mFonts.size() > 0) {
-            java.awt.FontMetrics javaMetrics = mFonts.get(0).mMetrics;
-            // Android expects negative ascent so we invert the value from Java.
-            return - javaMetrics.getAscent();
-        }
-
-        return 0;
-    }
-
-    /**
-     * Return the distance below (positive) the baseline (descent) based on the
-     * current typeface and text size.
-     *
-     * @return the distance below (positive) the baseline (descent) based on
-     *         the current typeface and text size.
-     */
-    @Override
-    public float descent() {
-        if (mFonts.size() > 0) {
-            java.awt.FontMetrics javaMetrics = mFonts.get(0).mMetrics;
-            return javaMetrics.getDescent();
-        }
-
-        return 0;
-    }
-
-    /**
-     * Return the width of the text.
-     *
-     * @param text  The text to measure
-     * @param index The index of the first character to start measuring
-     * @param count THe number of characters to measure, beginning with start
-     * @return      The width of the text
-     */
-    @Override
-    public float measureText(char[] text, int index, int count) {
-        // WARNING: the logic in this method is similar to Canvas.drawText.
-        // Any change to this method should be reflected in Canvas.drawText
-        if (mFonts.size() > 0) {
-            FontInfo mainFont = mFonts.get(0);
-            int i = index;
-            int lastIndex = index + count;
-            float total = 0f;
-            while (i < lastIndex) {
-                // always start with the main font.
-                int upTo = mainFont.mFont.canDisplayUpTo(text, i, lastIndex);
-                if (upTo == -1) {
-                    // shortcut to exit
-                    return total + mainFont.mMetrics.charsWidth(text, i, lastIndex - i);
-                } else if (upTo > 0) {
-                    total += mainFont.mMetrics.charsWidth(text, i, upTo - i);
-                    i = upTo;
-                    // don't call continue at this point. Since it is certain the main font
-                    // cannot display the font a index upTo (now ==i), we move on to the
-                    // fallback fonts directly.
-                }
-
-                // no char supported, attempt to read the next char(s) with the
-                // fallback font. In this case we only test the first character
-                // and then go back to test with the main font.
-                // Special test for 2-char characters.
-                boolean foundFont = false;
-                for (int f = 1 ; f < mFonts.size() ; f++) {
-                    FontInfo fontInfo = mFonts.get(f);
-
-                    // need to check that the font can display the character. We test
-                    // differently if the char is a high surrogate.
-                    int charCount = Character.isHighSurrogate(text[i]) ? 2 : 1;
-                    upTo = fontInfo.mFont.canDisplayUpTo(text, i, i + charCount);
-                    if (upTo == -1) {
-                        total += fontInfo.mMetrics.charsWidth(text, i, charCount);
-                        i += charCount;
-                        foundFont = true;
-                        break;
-
-                    }
-                }
-
-                // in case no font can display the char, measure it with the main font.
-                if (foundFont == false) {
-                    int size = Character.isHighSurrogate(text[i]) ? 2 : 1;
-                    total += mainFont.mMetrics.charsWidth(text, i, size);
-                    i += size;
-                }
-            }
-        }
-
-        return 0;
-    }
-
-    /**
-     * Return the width of the text.
-     *
-     * @param text  The text to measure
-     * @param start The index of the first character to start measuring
-     * @param end   1 beyond the index of the last character to measure
-     * @return      The width of the text
-     */
-    @Override
-    public float measureText(String text, int start, int end) {
-        return measureText(text.toCharArray(), start, end - start);
-    }
-
-    /**
-     * Return the width of the text.
-     *
-     * @param text  The text to measure
-     * @return      The width of the text
-     */
-    @Override
-    public float measureText(String text) {
-        return measureText(text.toCharArray(), 0, text.length());
-    }
-
-    /*
-     * re-implement to call SpannableStringBuilder.measureText with a Paint object
-     * instead of an _Original_Paint
-     */
-    @Override
-    public float measureText(CharSequence text, int start, int end) {
-        if (text instanceof String) {
-            return measureText((String)text, start, end);
-        }
-        if (text instanceof SpannedString ||
-            text instanceof SpannableString) {
-            return measureText(text.toString(), start, end);
-        }
-        if (text instanceof SpannableStringBuilder) {
-            return ((SpannableStringBuilder)text).measureText(start, end, this);
-        }
-
-        char[] buf = TemporaryBuffer.obtain(end - start);
-        TextUtils.getChars(text, start, end, buf, 0);
-        float result = measureText(buf, 0, end - start);
-        TemporaryBuffer.recycle(buf);
-        return result;
-    }
-
-    /**
-     * Measure the text, stopping early if the measured width exceeds maxWidth.
-     * Return the number of chars that were measured, and if measuredWidth is
-     * not null, return in it the actual width measured.
-     *
-     * @param text  The text to measure
-     * @param index The offset into text to begin measuring at
-     * @param count The number of maximum number of entries to measure. If count
-     *              is negative, then the characters before index are measured
-     *              in reverse order. This allows for measuring the end of
-     *              string.
-     * @param maxWidth The maximum width to accumulate.
-     * @param measuredWidth Optional. If not null, returns the actual width
-     *                     measured.
-     * @return The number of chars that were measured. Will always be <=
-     *         abs(count).
-     */
-    @Override
-    public int breakText(char[] text, int index, int count,
-                                float maxWidth, float[] measuredWidth) {
-        int inc = count > 0 ? 1 : -1;
-
-        int measureIndex = 0;
-        float measureAcc = 0;
-        for (int i = index ; i != index + count ; i += inc, measureIndex++) {
-            int start, end;
-            if (i < index) {
-                start = i;
-                end = index;
-            } else {
-                start = index;
-                end = i;
-            }
-
-            // measure from start to end
-            float res = measureText(text, start, end - start + 1);
-
-            if (measuredWidth != null) {
-                measuredWidth[measureIndex] = res;
-            }
-
-            measureAcc += res;
-            if (res > maxWidth) {
-                // we should not return this char index, but since it's 0-based and we need
-                // to return a count, we simply return measureIndex;
-                return measureIndex;
-            }
-
-        }
-
-        return measureIndex;
-    }
-
-    /**
-     * Measure the text, stopping early if the measured width exceeds maxWidth.
-     * Return the number of chars that were measured, and if measuredWidth is
-     * not null, return in it the actual width measured.
-     *
-     * @param text  The text to measure
-     * @param measureForwards If true, measure forwards, starting at index.
-     *                        Otherwise, measure backwards, starting with the
-     *                        last character in the string.
-     * @param maxWidth The maximum width to accumulate.
-     * @param measuredWidth Optional. If not null, returns the actual width
-     *                     measured.
-     * @return The number of chars that were measured. Will always be <=
-     *         abs(count).
-     */
-    @Override
-    public int breakText(String text, boolean measureForwards,
-                                float maxWidth, float[] measuredWidth) {
-        return breakText(text,
-                0 /* start */, text.length() /* end */,
-                measureForwards, maxWidth, measuredWidth);
-    }
-
-    /**
-     * Measure the text, stopping early if the measured width exceeds maxWidth.
-     * Return the number of chars that were measured, and if measuredWidth is
-     * not null, return in it the actual width measured.
-     *
-     * @param text  The text to measure
-     * @param start The offset into text to begin measuring at
-     * @param end   The end of the text slice to measure.
-     * @param measureForwards If true, measure forwards, starting at start.
-     *                        Otherwise, measure backwards, starting with end.
-     * @param maxWidth The maximum width to accumulate.
-     * @param measuredWidth Optional. If not null, returns the actual width
-     *                     measured.
-     * @return The number of chars that were measured. Will always be <=
-     *         abs(end - start).
-     */
-    @Override
-    public int breakText(CharSequence text, int start, int end, boolean measureForwards,
-            float maxWidth, float[] measuredWidth) {
-        char[] buf = new char[end - start];
-        int result;
-
-        TextUtils.getChars(text, start, end, buf, 0);
-
-        if (measureForwards) {
-            result = breakText(buf, 0, end - start, maxWidth, measuredWidth);
-        } else {
-            result = breakText(buf, 0, -(end - start), maxWidth, measuredWidth);
-        }
-
-        return result;
-    }
-
-    /**
-     * Return the advance widths for the characters in the string.
-     *
-     * @param text     The text to measure
-     * @param index    The index of the first char to to measure
-     * @param count    The number of chars starting with index to measure
-     * @param widths   array to receive the advance widths of the characters.
-     *                 Must be at least a large as count.
-     * @return         the actual number of widths returned.
-     */
-    @Override
-    public int getTextWidths(char[] text, int index, int count,
-                             float[] widths) {
-        if (mFonts.size() > 0) {
-            if ((index | count) < 0 || index + count > text.length
-                    || count > widths.length) {
-                throw new ArrayIndexOutOfBoundsException();
-            }
-
-            // FIXME: handle multi-char characters.
-            // Need to figure out if the lengths of the width array takes into account
-            // multi-char characters.
-            for (int i = 0; i < count; i++) {
-                char c = text[i + index];
-                boolean found = false;
-                for (FontInfo info : mFonts) {
-                    if (info.mFont.canDisplay(c)) {
-                        widths[i] = info.mMetrics.charWidth(c);
-                        found = true;
-                        break;
-                    }
-                }
-
-                if (found == false) {
-                    // we stop there.
-                    return i;
-                }
-            }
-
-            return count;
-        }
-
-        return 0;
-    }
-
-    /**
-     * Return the advance widths for the characters in the string.
-     *
-     * @param text   The text to measure
-     * @param start  The index of the first char to to measure
-     * @param end    The end of the text slice to measure
-     * @param widths array to receive the advance widths of the characters.
-     *               Must be at least a large as the text.
-     * @return       the number of unichars in the specified text.
-     */
-    @Override
-    public int getTextWidths(String text, int start, int end, float[] widths) {
-        if ((start | end | (end - start) | (text.length() - end)) < 0) {
-            throw new IndexOutOfBoundsException();
-        }
-        if (end - start > widths.length) {
-            throw new ArrayIndexOutOfBoundsException();
-        }
-
-        return getTextWidths(text.toCharArray(), start, end - start, widths);
-    }
-
-    /*
-     * re-implement to call SpannableStringBuilder.getTextWidths with a Paint object
-     * instead of an _Original_Paint
-     */
-    @Override
-    public int getTextWidths(CharSequence text, int start, int end, float[] widths) {
-        if (text instanceof String) {
-            return getTextWidths((String)text, start, end, widths);
-        }
-        if (text instanceof SpannedString || text instanceof SpannableString) {
-            return getTextWidths(text.toString(), start, end, widths);
-        }
-        if (text instanceof SpannableStringBuilder) {
-            return ((SpannableStringBuilder)text).getTextWidths(start, end, widths, this);
-        }
-
-        char[] buf = TemporaryBuffer.obtain(end - start);
-        TextUtils.getChars(text, start, end, buf, 0);
-        int result = getTextWidths(buf, 0, end - start, widths);
-        TemporaryBuffer.recycle(buf);
-        return result;
-    }
-
-    @Override
-    public int getTextWidths(String text, float[] widths) {
-        return super.getTextWidths(text, widths);
-    }
-
-    /**
-     * Return the path (outline) for the specified text.
-     * Note: just like Canvas.drawText, this will respect the Align setting in
-     * the paint.
-     *
-     * @param text     The text to retrieve the path from
-     * @param index    The index of the first character in text
-     * @param count    The number of characterss starting with index
-     * @param x        The x coordinate of the text's origin
-     * @param y        The y coordinate of the text's origin
-     * @param path     The path to receive the data describing the text. Must
-     *                 be allocated by the caller.
-     */
-    @Override
-    public void getTextPath(char[] text, int index, int count,
-                            float x, float y, Path path) {
-
-        // TODO this is the ORIGINAL implementation. REPLACE AS NEEDED OR REMOVE
-
-        if ((index | count) < 0 || index + count > text.length) {
-            throw new ArrayIndexOutOfBoundsException();
-        }
-
-        // TODO native_getTextPath(mNativePaint, text, index, count, x, y, path.ni());
-
-        throw new UnsupportedOperationException("IMPLEMENT AS NEEDED");
-    }
-
-    /**
-     * Return the path (outline) for the specified text.
-     * Note: just like Canvas.drawText, this will respect the Align setting
-     * in the paint.
-     *
-     * @param text  The text to retrieve the path from
-     * @param start The first character in the text
-     * @param end   1 past the last charcter in the text
-     * @param x     The x coordinate of the text's origin
-     * @param y     The y coordinate of the text's origin
-     * @param path  The path to receive the data describing the text. Must
-     *              be allocated by the caller.
-     */
-    @Override
-    public void getTextPath(String text, int start, int end,
-                            float x, float y, Path path) {
-        if ((start | end | (end - start) | (text.length() - end)) < 0) {
-            throw new IndexOutOfBoundsException();
-        }
-
-        getTextPath(text.toCharArray(), start, end - start, x, y, path);
-    }
-
-    /**
-     * Return in bounds (allocated by the caller) the smallest rectangle that
-     * encloses all of the characters, with an implied origin at (0,0).
-     *
-     * @param text  String to measure and return its bounds
-     * @param start Index of the first char in the string to measure
-     * @param end   1 past the last char in the string measure
-     * @param bounds Returns the unioned bounds of all the text. Must be
-     *               allocated by the caller.
-     */
-    @Override
-    public void getTextBounds(String text, int start, int end, Rect bounds) {
-        if ((start | end | (end - start) | (text.length() - end)) < 0) {
-            throw new IndexOutOfBoundsException();
-        }
-        if (bounds == null) {
-            throw new NullPointerException("need bounds Rect");
-        }
-
-        getTextBounds(text.toCharArray(), start, end - start, bounds);
-    }
-
-    /**
-     * Return in bounds (allocated by the caller) the smallest rectangle that
-     * encloses all of the characters, with an implied origin at (0,0).
-     *
-     * @param text  Array of chars to measure and return their unioned bounds
-     * @param index Index of the first char in the array to measure
-     * @param count The number of chars, beginning at index, to measure
-     * @param bounds Returns the unioned bounds of all the text. Must be
-     *               allocated by the caller.
-     */
-    @Override
-    public void getTextBounds(char[] text, int index, int count, Rect bounds) {
-        // FIXME
-        if (mFonts.size() > 0) {
-            if ((index | count) < 0 || index + count > text.length) {
-                throw new ArrayIndexOutOfBoundsException();
-            }
-            if (bounds == null) {
-                throw new NullPointerException("need bounds Rect");
-            }
-
-            FontInfo mainInfo = mFonts.get(0);
-
-            Rectangle2D rect = mainInfo.mFont.getStringBounds(text, index, index + count, mFontContext);
-            bounds.set(0, 0, (int)rect.getWidth(), (int)rect.getHeight());
-        }
-    }
-
-    public static void finalizer(int foo) {
-        // pass
-    }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/PaintFlagsDrawFilter_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/PaintFlagsDrawFilter_Delegate.java
new file mode 100644
index 0000000..71d346a
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/PaintFlagsDrawFilter_Delegate.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+/**
+ * Delegate implementing the native methods of android.graphics.PaintFlagsDrawFilter
+ *
+ * Through the layoutlib_create tool, the original native methods of PaintFlagsDrawFilter have been
+ * replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original PaintFlagsDrawFilter class.
+ *
+ * Because this extends {@link DrawFilter_Delegate}, there's no need to use a
+ * {@link DelegateManager}, as all the DrawFilter classes will be added to the manager owned by
+ * {@link DrawFilter_Delegate}.
+ *
+ * @see DrawFilter_Delegate
+ *
+ */
+public class PaintFlagsDrawFilter_Delegate extends DrawFilter_Delegate {
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public boolean isSupported() {
+        return false;
+    }
+
+    @Override
+    public String getSupportMessage() {
+        return "Paint Flags Draw Filters are not supported.";
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeConstructor(int clearBits, int setBits) {
+        PaintFlagsDrawFilter_Delegate newDelegate = new PaintFlagsDrawFilter_Delegate();
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    // ---- Private delegate/helper methods ----
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Paint_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Paint_Delegate.java
new file mode 100644
index 0000000..d4cf1f6
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/Paint_Delegate.java
@@ -0,0 +1,1163 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import android.graphics.Paint.FontMetrics;
+import android.graphics.Paint.FontMetricsInt;
+
+import java.awt.BasicStroke;
+import java.awt.Font;
+import java.awt.Shape;
+import java.awt.Stroke;
+import java.awt.Toolkit;
+import java.awt.font.FontRenderContext;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Rectangle2D;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Delegate implementing the native methods of android.graphics.Paint
+ *
+ * Through the layoutlib_create tool, the original native methods of Paint have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original Paint class.
+ *
+ * @see DelegateManager
+ *
+ */
+public class Paint_Delegate {
+
+    /**
+     * Class associating a {@link Font} and it's {@link java.awt.FontMetrics}.
+     */
+    /*package*/ static final class FontInfo {
+        Font mFont;
+        java.awt.FontMetrics mMetrics;
+    }
+
+    // ---- delegate manager ----
+    private static final DelegateManager<Paint_Delegate> sManager =
+            new DelegateManager<Paint_Delegate>(Paint_Delegate.class);
+
+    // ---- delegate helper data ----
+    private List<FontInfo> mFonts;
+    private final FontRenderContext mFontContext = new FontRenderContext(
+            new AffineTransform(), true, true);
+
+    // ---- delegate data ----
+    private int mFlags;
+    private int mColor;
+    private int mStyle;
+    private int mCap;
+    private int mJoin;
+    private int mTextAlign;
+    private Typeface_Delegate mTypeface;
+    private float mStrokeWidth;
+    private float mStrokeMiter;
+    private float mTextSize;
+    private float mTextScaleX;
+    private float mTextSkewX;
+
+    private Xfermode_Delegate mXfermode;
+    private ColorFilter_Delegate mColorFilter;
+    private Shader_Delegate mShader;
+    private PathEffect_Delegate mPathEffect;
+    private MaskFilter_Delegate mMaskFilter;
+    private Rasterizer_Delegate mRasterizer;
+
+    // ---- Public Helper methods ----
+
+    public static Paint_Delegate getDelegate(int native_paint) {
+        return sManager.getDelegate(native_paint);
+    }
+
+    /**
+     * Returns the list of {@link Font} objects. The first item is the main font, the rest
+     * are fall backs for characters not present in the main font.
+     */
+    public List<FontInfo> getFonts() {
+        return mFonts;
+    }
+
+    public boolean isAntiAliased() {
+        return (mFlags & Paint.ANTI_ALIAS_FLAG) != 0;
+    }
+
+    public boolean isFilterBitmap() {
+        return (mFlags & Paint.FILTER_BITMAP_FLAG) != 0;
+    }
+
+    public int getStyle() {
+        return mStyle;
+    }
+
+    public int getColor() {
+        return mColor;
+    }
+
+    public int getAlpha() {
+        return mColor >>> 24;
+    }
+
+    public void setAlpha(int alpha) {
+        mColor = (alpha << 24) | (mColor & 0x00FFFFFF);
+    }
+
+    public int getTextAlign() {
+        return mTextAlign;
+    }
+
+    public float getStrokeWidth() {
+        return mStrokeWidth;
+    }
+
+    /**
+     * returns the value of stroke miter needed by the java api.
+     */
+    public float getJavaStrokeMiter() {
+        float miter = mStrokeMiter * mStrokeWidth;
+        if (miter < 1.f) {
+            miter = 1.f;
+        }
+        return miter;
+    }
+
+    public int getJavaCap() {
+        switch (Paint.sCapArray[mCap]) {
+            case BUTT:
+                return BasicStroke.CAP_BUTT;
+            case ROUND:
+                return BasicStroke.CAP_ROUND;
+            default:
+            case SQUARE:
+                return BasicStroke.CAP_SQUARE;
+        }
+    }
+
+    public int getJavaJoin() {
+        switch (Paint.sJoinArray[mJoin]) {
+            default:
+            case MITER:
+                return BasicStroke.JOIN_MITER;
+            case ROUND:
+                return BasicStroke.JOIN_ROUND;
+            case BEVEL:
+                return BasicStroke.JOIN_BEVEL;
+        }
+    }
+
+    public Stroke getJavaStroke() {
+        if (mPathEffect != null) {
+            if (mPathEffect.isSupported()) {
+                Stroke stroke = mPathEffect.getStroke(this);
+                assert stroke != null;
+                if (stroke != null) {
+                    return stroke;
+                }
+            } else {
+                Bridge.getLog().fidelityWarning(LayoutLog.TAG_PATHEFFECT,
+                        mPathEffect.getSupportMessage(),
+                        null, null /*data*/);
+            }
+        }
+
+        // if no custom stroke as been set, set the default one.
+        return new BasicStroke(
+                    getStrokeWidth(),
+                    getJavaCap(),
+                    getJavaJoin(),
+                    getJavaStrokeMiter());
+    }
+
+    /**
+     * Returns the {@link Xfermode} delegate or null if none have been set
+     *
+     * @return the delegate or null.
+     */
+    public Xfermode_Delegate getXfermode() {
+        return mXfermode;
+    }
+
+    /**
+     * Returns the {@link ColorFilter} delegate or null if none have been set
+     *
+     * @return the delegate or null.
+     */
+    public ColorFilter_Delegate getColorFilter() {
+        return mColorFilter;
+    }
+
+    /**
+     * Returns the {@link Shader} delegate or null if none have been set
+     *
+     * @return the delegate or null.
+     */
+    public Shader_Delegate getShader() {
+        return mShader;
+    }
+
+    /**
+     * Returns the {@link MaskFilter} delegate or null if none have been set
+     *
+     * @return the delegate or null.
+     */
+    public MaskFilter_Delegate getMaskFilter() {
+        return mMaskFilter;
+    }
+
+    /**
+     * Returns the {@link Rasterizer} delegate or null if none have been set
+     *
+     * @return the delegate or null.
+     */
+    public Rasterizer_Delegate getRasterizer() {
+        return mRasterizer;
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int getFlags(Paint thisPaint) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return 0;
+        }
+
+        return delegate.mFlags;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void setFlags(Paint thisPaint, int flags) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return;
+        }
+
+        delegate.mFlags = flags;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void setFilterBitmap(Paint thisPaint, boolean filter) {
+        setFlag(thisPaint, Paint.FILTER_BITMAP_FLAG, filter);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void setAntiAlias(Paint thisPaint, boolean aa) {
+        setFlag(thisPaint, Paint.ANTI_ALIAS_FLAG, aa);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void setSubpixelText(Paint thisPaint, boolean subpixelText) {
+        setFlag(thisPaint, Paint.SUBPIXEL_TEXT_FLAG, subpixelText);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void setUnderlineText(Paint thisPaint, boolean underlineText) {
+        setFlag(thisPaint, Paint.UNDERLINE_TEXT_FLAG, underlineText);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void setStrikeThruText(Paint thisPaint, boolean strikeThruText) {
+        setFlag(thisPaint, Paint.STRIKE_THRU_TEXT_FLAG, strikeThruText);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void setFakeBoldText(Paint thisPaint, boolean fakeBoldText) {
+        setFlag(thisPaint, Paint.FAKE_BOLD_TEXT_FLAG, fakeBoldText);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void setDither(Paint thisPaint, boolean dither) {
+        setFlag(thisPaint, Paint.DITHER_FLAG, dither);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void setLinearText(Paint thisPaint, boolean linearText) {
+        setFlag(thisPaint, Paint.LINEAR_TEXT_FLAG, linearText);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int getColor(Paint thisPaint) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return 0;
+        }
+
+        return delegate.mColor;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void setColor(Paint thisPaint, int color) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return;
+        }
+
+        delegate.mColor = color;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int getAlpha(Paint thisPaint) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return 0;
+        }
+
+        return delegate.getAlpha();
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void setAlpha(Paint thisPaint, int a) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return;
+        }
+
+        delegate.setAlpha(a);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static float getStrokeWidth(Paint thisPaint) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return 1.f;
+        }
+
+        return delegate.mStrokeWidth;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void setStrokeWidth(Paint thisPaint, float width) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return;
+        }
+
+        delegate.mStrokeWidth = width;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static float getStrokeMiter(Paint thisPaint) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return 1.f;
+        }
+
+        return delegate.mStrokeMiter;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void setStrokeMiter(Paint thisPaint, float miter) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return;
+        }
+
+        delegate.mStrokeMiter = miter;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void setShadowLayer(Paint thisPaint, float radius, float dx, float dy,
+            int color) {
+        // FIXME
+        Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
+                "Paint.setShadowLayer is not supported.", null, null /*data*/);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static float getTextSize(Paint thisPaint) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return 1.f;
+        }
+
+        return delegate.mTextSize;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void setTextSize(Paint thisPaint, float textSize) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return;
+        }
+
+        delegate.mTextSize = textSize;
+        delegate.updateFontObject();
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static float getTextScaleX(Paint thisPaint) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return 1.f;
+        }
+
+        return delegate.mTextScaleX;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void setTextScaleX(Paint thisPaint, float scaleX) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return;
+        }
+
+        delegate.mTextScaleX = scaleX;
+        delegate.updateFontObject();
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static float getTextSkewX(Paint thisPaint) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return 1.f;
+        }
+
+        return delegate.mTextSkewX;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void setTextSkewX(Paint thisPaint, float skewX) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return;
+        }
+
+        delegate.mTextSkewX = skewX;
+        delegate.updateFontObject();
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static float ascent(Paint thisPaint) {
+        // get the delegate
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return 0;
+        }
+
+        if (delegate.mFonts.size() > 0) {
+            java.awt.FontMetrics javaMetrics = delegate.mFonts.get(0).mMetrics;
+            // Android expects negative ascent so we invert the value from Java.
+            return - javaMetrics.getAscent();
+        }
+
+        return 0;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static float descent(Paint thisPaint) {
+        // get the delegate
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return 0;
+        }
+
+        if (delegate.mFonts.size() > 0) {
+            java.awt.FontMetrics javaMetrics = delegate.mFonts.get(0).mMetrics;
+            return javaMetrics.getDescent();
+        }
+
+        return 0;
+
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static float getFontMetrics(Paint thisPaint, FontMetrics metrics) {
+        // get the delegate
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return 0;
+        }
+
+        return delegate.getFontMetrics(metrics);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int getFontMetricsInt(Paint thisPaint, FontMetricsInt fmi) {
+        // get the delegate
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return 0;
+        }
+
+        if (delegate.mFonts.size() > 0) {
+            java.awt.FontMetrics javaMetrics = delegate.mFonts.get(0).mMetrics;
+            if (fmi != null) {
+                // Android expects negative ascent so we invert the value from Java.
+                fmi.top = - javaMetrics.getMaxAscent();
+                fmi.ascent = - javaMetrics.getAscent();
+                fmi.descent = javaMetrics.getDescent();
+                fmi.bottom = javaMetrics.getMaxDescent();
+                fmi.leading = javaMetrics.getLeading();
+            }
+
+            return javaMetrics.getHeight();
+        }
+
+        return 0;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static float native_measureText(Paint thisPaint, char[] text, int index,
+            int count) {
+        // get the delegate
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return 0;
+        }
+
+        return delegate.measureText(text, index, count);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static float native_measureText(Paint thisPaint, String text, int start, int end) {
+        return native_measureText(thisPaint, text.toCharArray(), start, end - start);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static float native_measureText(Paint thisPaint, String text) {
+        return native_measureText(thisPaint, text.toCharArray(), 0, text.length());
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_breakText(Paint thisPaint, char[] text, int index, int count,
+            float maxWidth, float[] measuredWidth) {
+
+        // get the delegate
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return 0;
+        }
+
+        int inc = count > 0 ? 1 : -1;
+
+        int measureIndex = 0;
+        float measureAcc = 0;
+        for (int i = index; i != index + count; i += inc, measureIndex++) {
+            int start, end;
+            if (i < index) {
+                start = i;
+                end = index;
+            } else {
+                start = index;
+                end = i;
+            }
+
+            // measure from start to end
+            float res = delegate.measureText(text, start, end - start + 1);
+
+            if (measuredWidth != null) {
+                measuredWidth[measureIndex] = res;
+            }
+
+            measureAcc += res;
+            if (res > maxWidth) {
+                // we should not return this char index, but since it's 0-based
+                // and we need to return a count, we simply return measureIndex;
+                return measureIndex;
+            }
+
+        }
+
+        return measureIndex;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_breakText(Paint thisPaint, String text, boolean measureForwards,
+            float maxWidth, float[] measuredWidth) {
+        return native_breakText(thisPaint, text.toCharArray(), 0, text.length(), maxWidth,
+                measuredWidth);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_init() {
+        Paint_Delegate newDelegate = new Paint_Delegate();
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_initWithPaint(int paint) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(paint);
+        if (delegate == null) {
+            return 0;
+        }
+
+        Paint_Delegate newDelegate = new Paint_Delegate(delegate);
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_reset(int native_object) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(native_object);
+        if (delegate == null) {
+            return;
+        }
+
+        delegate.reset();
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_set(int native_dst, int native_src) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate_dst = sManager.getDelegate(native_dst);
+        if (delegate_dst == null) {
+            return;
+        }
+
+        // get the delegate from the native int.
+        Paint_Delegate delegate_src = sManager.getDelegate(native_src);
+        if (delegate_src == null) {
+            return;
+        }
+
+        delegate_dst.set(delegate_src);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_getStyle(int native_object) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(native_object);
+        if (delegate == null) {
+            return 0;
+        }
+
+        return delegate.mStyle;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_setStyle(int native_object, int style) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(native_object);
+        if (delegate == null) {
+            return;
+        }
+
+        delegate.mStyle = style;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_getStrokeCap(int native_object) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(native_object);
+        if (delegate == null) {
+            return 0;
+        }
+
+        return delegate.mCap;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_setStrokeCap(int native_object, int cap) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(native_object);
+        if (delegate == null) {
+            return;
+        }
+
+        delegate.mCap = cap;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_getStrokeJoin(int native_object) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(native_object);
+        if (delegate == null) {
+            return 0;
+        }
+
+        return delegate.mJoin;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_setStrokeJoin(int native_object, int join) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(native_object);
+        if (delegate == null) {
+            return;
+        }
+
+        delegate.mJoin = join;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_getFillPath(int native_object, int src, int dst) {
+        Paint_Delegate paint = sManager.getDelegate(native_object);
+        if (paint == null) {
+            return false;
+        }
+
+        Path_Delegate srcPath = Path_Delegate.getDelegate(src);
+        if (srcPath == null) {
+            return true;
+        }
+
+        Path_Delegate dstPath = Path_Delegate.getDelegate(dst);
+        if (dstPath == null) {
+            return true;
+        }
+
+        Stroke stroke = paint.getJavaStroke();
+        Shape strokeShape = stroke.createStrokedShape(srcPath.getJavaShape());
+
+        dstPath.setJavaShape(strokeShape);
+
+        // FIXME figure out the return value?
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_setShader(int native_object, int shader) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(native_object);
+        if (delegate == null) {
+            return shader;
+        }
+
+        delegate.mShader = Shader_Delegate.getDelegate(shader);
+
+        return shader;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_setColorFilter(int native_object, int filter) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(native_object);
+        if (delegate == null) {
+            return filter;
+        }
+
+        delegate.mColorFilter = ColorFilter_Delegate.getDelegate(filter);;
+
+        // since none of those are supported, display a fidelity warning right away
+        if (delegate.mColorFilter != null && delegate.mColorFilter.isSupported() == false) {
+            Bridge.getLog().fidelityWarning(LayoutLog.TAG_COLORFILTER,
+                    delegate.mColorFilter.getSupportMessage(), null, null /*data*/);
+        }
+
+        return filter;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_setXfermode(int native_object, int xfermode) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(native_object);
+        if (delegate == null) {
+            return xfermode;
+        }
+
+        delegate.mXfermode = Xfermode_Delegate.getDelegate(xfermode);
+
+        return xfermode;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_setPathEffect(int native_object, int effect) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(native_object);
+        if (delegate == null) {
+            return effect;
+        }
+
+        delegate.mPathEffect = PathEffect_Delegate.getDelegate(effect);
+
+        return effect;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_setMaskFilter(int native_object, int maskfilter) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(native_object);
+        if (delegate == null) {
+            return maskfilter;
+        }
+
+        delegate.mMaskFilter = MaskFilter_Delegate.getDelegate(maskfilter);
+
+        // since none of those are supported, display a fidelity warning right away
+        if (delegate.mMaskFilter != null && delegate.mMaskFilter.isSupported() == false) {
+            Bridge.getLog().fidelityWarning(LayoutLog.TAG_MASKFILTER,
+                    delegate.mMaskFilter.getSupportMessage(), null, null /*data*/);
+        }
+
+        return maskfilter;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_setTypeface(int native_object, int typeface) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(native_object);
+        if (delegate == null) {
+            return 0;
+        }
+
+        delegate.mTypeface = Typeface_Delegate.getDelegate(typeface);
+        delegate.updateFontObject();
+        return typeface;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_setRasterizer(int native_object, int rasterizer) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(native_object);
+        if (delegate == null) {
+            return rasterizer;
+        }
+
+        delegate.mRasterizer = Rasterizer_Delegate.getDelegate(rasterizer);
+
+        // since none of those are supported, display a fidelity warning right away
+        if (delegate.mRasterizer != null && delegate.mRasterizer.isSupported() == false) {
+            Bridge.getLog().fidelityWarning(LayoutLog.TAG_RASTERIZER,
+                    delegate.mRasterizer.getSupportMessage(), null, null /*data*/);
+        }
+
+        return rasterizer;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_getTextAlign(int native_object) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(native_object);
+        if (delegate == null) {
+            return 0;
+        }
+
+        return delegate.mTextAlign;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_setTextAlign(int native_object, int align) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(native_object);
+        if (delegate == null) {
+            return;
+        }
+
+        delegate.mTextAlign = align;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static float native_getFontMetrics(int native_paint, FontMetrics metrics) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(native_paint);
+        if (delegate == null) {
+            return 0.f;
+        }
+
+        return delegate.getFontMetrics(metrics);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_getTextWidths(int native_object, char[] text, int index,
+            int count, float[] widths) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(native_object);
+        if (delegate == null) {
+            return 0;
+        }
+
+        if (delegate.mFonts.size() > 0) {
+            // FIXME: handle multi-char characters (see measureText)
+            float totalAdvance = 0;
+            for (int i = 0; i < count; i++) {
+                char c = text[i + index];
+                boolean found = false;
+                for (FontInfo info : delegate.mFonts) {
+                    if (info.mFont.canDisplay(c)) {
+                        float adv = info.mMetrics.charWidth(c);
+                        totalAdvance += adv;
+                        if (widths != null) {
+                            widths[i] = adv;
+                        }
+
+                        found = true;
+                        break;
+                    }
+                }
+
+                if (found == false) {
+                    // no advance for this char.
+                    if (widths != null) {
+                        widths[i] = 0.f;
+                    }
+                }
+            }
+
+            return (int) totalAdvance;
+        }
+
+        return 0;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_getTextWidths(int native_object, String text, int start,
+            int end, float[] widths) {
+        return native_getTextWidths(native_object, text.toCharArray(), start, end - start, widths);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_getTextPath(int native_object,
+                char[] text, int index, int count, float x, float y, int path) {
+        // FIXME
+        Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
+                "Paint.getTextPath is not supported.", null, null /*data*/);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_getTextPath(int native_object,
+            String text, int start, int end, float x, float y, int path) {
+        // FIXME
+        Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
+                "Paint.getTextPath is not supported.", null, null /*data*/);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeGetStringBounds(int nativePaint, String text, int start,
+            int end, Rect bounds) {
+        nativeGetCharArrayBounds(nativePaint, text.toCharArray(), start, end - start, bounds);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeGetCharArrayBounds(int nativePaint, char[] text, int index,
+            int count, Rect bounds) {
+
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(nativePaint);
+        if (delegate == null) {
+            return;
+        }
+
+        // FIXME should test if the main font can display all those characters.
+        // See MeasureText
+        if (delegate.mFonts.size() > 0) {
+            FontInfo mainInfo = delegate.mFonts.get(0);
+
+            Rectangle2D rect = mainInfo.mFont.getStringBounds(text, index, index + count,
+                    delegate.mFontContext);
+            bounds.set(0, 0, (int) rect.getWidth(), (int) rect.getHeight());
+        }
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void finalizer(int nativePaint) {
+        sManager.removeJavaReferenceFor(nativePaint);
+    }
+
+    // ---- Private delegate/helper methods ----
+
+    /*package*/ Paint_Delegate() {
+        reset();
+    }
+
+    private Paint_Delegate(Paint_Delegate paint) {
+        set(paint);
+    }
+
+    private void set(Paint_Delegate paint) {
+        mFlags = paint.mFlags;
+        mColor = paint.mColor;
+        mStyle = paint.mStyle;
+        mCap = paint.mCap;
+        mJoin = paint.mJoin;
+        mTextAlign = paint.mTextAlign;
+        mTypeface = paint.mTypeface;
+        mStrokeWidth = paint.mStrokeWidth;
+        mStrokeMiter = paint.mStrokeMiter;
+        mTextSize = paint.mTextSize;
+        mTextScaleX = paint.mTextScaleX;
+        mTextSkewX = paint.mTextSkewX;
+        mXfermode = paint.mXfermode;
+        mColorFilter = paint.mColorFilter;
+        mShader = paint.mShader;
+        mPathEffect = paint.mPathEffect;
+        mMaskFilter = paint.mMaskFilter;
+        mRasterizer = paint.mRasterizer;
+        updateFontObject();
+    }
+
+    private void reset() {
+        mFlags = Paint.DEFAULT_PAINT_FLAGS;
+        mColor = 0xFF000000;
+        mStyle = Paint.Style.FILL.nativeInt;
+        mCap = Paint.Cap.BUTT.nativeInt;
+        mJoin = Paint.Join.MITER.nativeInt;
+        mTextAlign = 0;
+        mTypeface = Typeface_Delegate.getDelegate(Typeface.sDefaults[0].native_instance);
+        mStrokeWidth = 1.f;
+        mStrokeMiter = 4.f;
+        mTextSize = 20.f;
+        mTextScaleX = 1.f;
+        mTextSkewX = 0.f;
+        mXfermode = null;
+        mColorFilter = null;
+        mShader = null;
+        mPathEffect = null;
+        mMaskFilter = null;
+        mRasterizer = null;
+        updateFontObject();
+    }
+
+    /**
+     * Update the {@link Font} object from the typeface, text size and scaling
+     */
+    @SuppressWarnings("deprecation")
+    private void updateFontObject() {
+        if (mTypeface != null) {
+            // Get the fonts from the TypeFace object.
+            List<Font> fonts = mTypeface.getFonts();
+
+            // create new font objects as well as FontMetrics, based on the current text size
+            // and skew info.
+            ArrayList<FontInfo> infoList = new ArrayList<FontInfo>(fonts.size());
+            for (Font font : fonts) {
+                FontInfo info = new FontInfo();
+                info.mFont = font.deriveFont(mTextSize);
+                if (mTextScaleX != 1.0 || mTextSkewX != 0) {
+                    // TODO: support skew
+                    info.mFont = info.mFont.deriveFont(new AffineTransform(
+                            mTextScaleX, mTextSkewX, 0, 0, 1, 0));
+                }
+                info.mMetrics = Toolkit.getDefaultToolkit().getFontMetrics(info.mFont);
+
+                infoList.add(info);
+            }
+
+            mFonts = Collections.unmodifiableList(infoList);
+        }
+    }
+
+    /*package*/ float measureText(char[] text, int index, int count) {
+
+        // WARNING: the logic in this method is similar to Canvas_Delegate.native_drawText
+        // Any change to this method should be reflected there as well
+
+        if (mFonts.size() > 0) {
+            FontInfo mainFont = mFonts.get(0);
+            int i = index;
+            int lastIndex = index + count;
+            float total = 0f;
+            while (i < lastIndex) {
+                // always start with the main font.
+                int upTo = mainFont.mFont.canDisplayUpTo(text, i, lastIndex);
+                if (upTo == -1) {
+                    // shortcut to exit
+                    return total + mainFont.mMetrics.charsWidth(text, i, lastIndex - i);
+                } else if (upTo > 0) {
+                    total += mainFont.mMetrics.charsWidth(text, i, upTo - i);
+                    i = upTo;
+                    // don't call continue at this point. Since it is certain the main font
+                    // cannot display the font a index upTo (now ==i), we move on to the
+                    // fallback fonts directly.
+                }
+
+                // no char supported, attempt to read the next char(s) with the
+                // fallback font. In this case we only test the first character
+                // and then go back to test with the main font.
+                // Special test for 2-char characters.
+                boolean foundFont = false;
+                for (int f = 1 ; f < mFonts.size() ; f++) {
+                    FontInfo fontInfo = mFonts.get(f);
+
+                    // need to check that the font can display the character. We test
+                    // differently if the char is a high surrogate.
+                    int charCount = Character.isHighSurrogate(text[i]) ? 2 : 1;
+                    upTo = fontInfo.mFont.canDisplayUpTo(text, i, i + charCount);
+                    if (upTo == -1) {
+                        total += fontInfo.mMetrics.charsWidth(text, i, charCount);
+                        i += charCount;
+                        foundFont = true;
+                        break;
+
+                    }
+                }
+
+                // in case no font can display the char, measure it with the main font.
+                if (foundFont == false) {
+                    int size = Character.isHighSurrogate(text[i]) ? 2 : 1;
+                    total += mainFont.mMetrics.charsWidth(text, i, size);
+                    i += size;
+                }
+            }
+
+            return total;
+        }
+
+        return 0;
+    }
+
+    private float getFontMetrics(FontMetrics metrics) {
+        if (mFonts.size() > 0) {
+            java.awt.FontMetrics javaMetrics = mFonts.get(0).mMetrics;
+            if (metrics != null) {
+                // Android expects negative ascent so we invert the value from Java.
+                metrics.top = - javaMetrics.getMaxAscent();
+                metrics.ascent = - javaMetrics.getAscent();
+                metrics.descent = javaMetrics.getDescent();
+                metrics.bottom = javaMetrics.getMaxDescent();
+                metrics.leading = javaMetrics.getLeading();
+            }
+
+            return javaMetrics.getHeight();
+        }
+
+        return 0;
+    }
+
+
+
+    private static void setFlag(Paint thisPaint, int flagMask, boolean flagValue) {
+        // get the delegate from the native int.
+        Paint_Delegate delegate = sManager.getDelegate(thisPaint.mNativePaint);
+        if (delegate == null) {
+            return;
+        }
+
+        if (flagValue) {
+            delegate.mFlags |= flagMask;
+        } else {
+            delegate.mFlags &= ~flagMask;
+        }
+    }
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Path.java b/tools/layoutlib/bridge/src/android/graphics/Path.java
deleted file mode 100644
index 12d2cde..0000000
--- a/tools/layoutlib/bridge/src/android/graphics/Path.java
+++ /dev/null
@@ -1,611 +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.
- */
-
-package android.graphics;
-
-import java.awt.Shape;
-import java.awt.geom.AffineTransform;
-import java.awt.geom.Ellipse2D;
-import java.awt.geom.GeneralPath;
-import java.awt.geom.PathIterator;
-import java.awt.geom.Rectangle2D;
-
-/**
- * The Path class encapsulates compound (multiple contour) geometric paths
- * consisting of straight line segments, quadratic curves, and cubic curves.
- * It can be drawn with canvas.drawPath(path, paint), either filled or stroked
- * (based on the paint's Style), or it can be used for clipping or to draw
- * text on a path.
- */
-public class Path {
-    
-    private FillType mFillType = FillType.WINDING;
-    private GeneralPath mPath = new GeneralPath();
-    
-    private float mLastX = 0;
-    private float mLastY = 0;
-    
-    //---------- Custom methods ----------
-
-    public Shape getAwtShape() {
-        return mPath;
-    }
-
-    //----------
-
-    /**
-     * Create an empty path
-     */
-    public Path() {
-    }
-
-    /**
-     * Create a new path, copying the contents from the src path.
-     *
-     * @param src The path to copy from when initializing the new path
-     */
-    public Path(Path src) {
-        mPath.append(src.mPath, false /* connect */);
-    }
-    
-    /**
-     * Clear any lines and curves from the path, making it empty.
-     * This does NOT change the fill-type setting.
-     */
-    public void reset() {
-        mPath = new GeneralPath();
-    }
-
-    /**
-     * Rewinds the path: clears any lines and curves from the path but
-     * keeps the internal data structure for faster reuse.
-     */
-    public void rewind() {
-        // FIXME
-        throw new UnsupportedOperationException();
-    }
-
-    /** Replace the contents of this with the contents of src.
-    */
-    public void set(Path src) {
-        mPath.append(src.mPath, false /* connect */);
-    }
-
-    /** Enum for the ways a path may be filled
-    */
-    public enum FillType {
-        // these must match the values in SkPath.h
-        WINDING         (GeneralPath.WIND_NON_ZERO, false),
-        EVEN_ODD        (GeneralPath.WIND_EVEN_ODD, false),
-        INVERSE_WINDING (GeneralPath.WIND_NON_ZERO, true),
-        INVERSE_EVEN_ODD(GeneralPath.WIND_EVEN_ODD, true);
-        
-        FillType(int rule, boolean inverse) {
-            this.rule = rule;
-            this.inverse = inverse;
-        }
-
-        final int rule;
-        final boolean inverse;
-    }
-    
-    /**
-     * Return the path's fill type. This defines how "inside" is
-     * computed. The default value is WINDING.
-     *
-     * @return the path's fill type
-     */
-    public FillType getFillType() {
-        return mFillType;
-    }
-
-    /**
-     * Set the path's fill type. This defines how "inside" is computed.
-     *
-     * @param ft The new fill type for this path
-     */
-    public void setFillType(FillType ft) {
-        mFillType = ft;
-        mPath.setWindingRule(ft.rule);
-    }
-    
-    /**
-     * Returns true if the filltype is one of the INVERSE variants
-     *
-     * @return true if the filltype is one of the INVERSE variants
-     */
-    public boolean isInverseFillType() {
-        return mFillType.inverse;
-    }
-    
-    /**
-     * Toggles the INVERSE state of the filltype
-     */
-    public void toggleInverseFillType() {
-        switch (mFillType) {
-            case WINDING:
-                mFillType = FillType.INVERSE_WINDING;
-                break;
-            case EVEN_ODD:
-                mFillType = FillType.INVERSE_EVEN_ODD;
-                break;
-            case INVERSE_WINDING:
-                mFillType = FillType.WINDING;
-                break;
-            case INVERSE_EVEN_ODD:
-                mFillType = FillType.EVEN_ODD;
-                break;
-        }
-    }
-    
-    /**
-     * Returns true if the path is empty (contains no lines or curves)
-     *
-     * @return true if the path is empty (contains no lines or curves)
-     */
-    public boolean isEmpty() {
-        return mPath.getCurrentPoint() == null;
-    }
-
-    /**
-     * Returns true if the path specifies a rectangle. If so, and if rect is
-     * not null, set rect to the bounds of the path. If the path does not
-     * specify a rectangle, return false and ignore rect.
-     *
-     * @param rect If not null, returns the bounds of the path if it specifies
-     *             a rectangle
-     * @return     true if the path specifies a rectangle
-     */
-    public boolean isRect(RectF rect) {
-        // FIXME
-        throw new UnsupportedOperationException();
-    }
-
-    /**
-     * Compute the bounds of the path, and write the answer into bounds. If the
-     * path contains 0 or 1 points, the bounds is set to (0,0,0,0)
-     *
-     * @param bounds Returns the computed bounds of the path
-     * @param exact If true, return the exact (but slower) bounds, else return
-     *              just the bounds of all control points
-     */
-    public void computeBounds(RectF bounds, boolean exact) {
-        Rectangle2D rect = mPath.getBounds2D();
-        bounds.left = (float)rect.getMinX();
-        bounds.right = (float)rect.getMaxX();
-        bounds.top = (float)rect.getMinY();
-        bounds.bottom = (float)rect.getMaxY();
-    }
-
-    /**
-     * Hint to the path to prepare for adding more points. This can allow the
-     * path to more efficiently allocate its storage.
-     *
-     * @param extraPtCount The number of extra points that may be added to this
-     *                     path
-     */
-    public void incReserve(int extraPtCount) {
-        // pass
-    }
-
-    /**
-     * Set the beginning of the next contour to the point (x,y).
-     *
-     * @param x The x-coordinate of the start of a new contour
-     * @param y The y-coordinate of the start of a new contour
-     */
-    public void moveTo(float x, float y) {
-        mPath.moveTo(mLastX = x, mLastY = y);
-    }
-
-    /**
-     * Set the beginning of the next contour relative to the last point on the
-     * previous contour. If there is no previous contour, this is treated the
-     * same as moveTo().
-     *
-     * @param dx The amount to add to the x-coordinate of the end of the
-     *           previous contour, to specify the start of a new contour
-     * @param dy The amount to add to the y-coordinate of the end of the
-     *           previous contour, to specify the start of a new contour
-     */
-    public void rMoveTo(float dx, float dy) {
-        dx += mLastX;
-        dy += mLastY;
-        mPath.moveTo(mLastX = dx, mLastY = dy);
-    }
-
-    /**
-     * Add a line from the last point to the specified point (x,y).
-     * If no moveTo() call has been made for this contour, the first point is
-     * automatically set to (0,0).
-     *
-     * @param x The x-coordinate of the end of a line
-     * @param y The y-coordinate of the end of a line
-     */
-    public void lineTo(float x, float y) {
-        mPath.lineTo(mLastX = x, mLastY = y);
-    }
-
-    /**
-     * Same as lineTo, but the coordinates are considered relative to the last
-     * point on this contour. If there is no previous point, then a moveTo(0,0)
-     * is inserted automatically.
-     *
-     * @param dx The amount to add to the x-coordinate of the previous point on
-     *           this contour, to specify a line
-     * @param dy The amount to add to the y-coordinate of the previous point on
-     *           this contour, to specify a line
-     */
-    public void rLineTo(float dx, float dy) {
-        if (isEmpty()) {
-            mPath.moveTo(mLastX = 0, mLastY = 0);
-        }
-        dx += mLastX;
-        dy += mLastY;
-        mPath.lineTo(mLastX = dx, mLastY = dy);
-    }
-
-    /**
-     * Add a quadratic bezier from the last point, approaching control point
-     * (x1,y1), and ending at (x2,y2). If no moveTo() call has been made for
-     * this contour, the first point is automatically set to (0,0).
-     *
-     * @param x1 The x-coordinate of the control point on a quadratic curve
-     * @param y1 The y-coordinate of the control point on a quadratic curve
-     * @param x2 The x-coordinate of the end point on a quadratic curve
-     * @param y2 The y-coordinate of the end point on a quadratic curve
-     */
-    public void quadTo(float x1, float y1, float x2, float y2) {
-        mPath.quadTo(x1, y1, mLastX = x2, mLastY = y2);
-    }
-
-    /**
-     * Same as quadTo, but the coordinates are considered relative to the last
-     * point on this contour. If there is no previous point, then a moveTo(0,0)
-     * is inserted automatically.
-     *
-     * @param dx1 The amount to add to the x-coordinate of the last point on
-     *            this contour, for the control point of a quadratic curve
-     * @param dy1 The amount to add to the y-coordinate of the last point on
-     *            this contour, for the control point of a quadratic curve
-     * @param dx2 The amount to add to the x-coordinate of the last point on
-     *            this contour, for the end point of a quadratic curve
-     * @param dy2 The amount to add to the y-coordinate of the last point on
-     *            this contour, for the end point of a quadratic curve
-     */
-    public void rQuadTo(float dx1, float dy1, float dx2, float dy2) {
-        if (isEmpty()) {
-            mPath.moveTo(mLastX = 0, mLastY = 0);
-        }
-        dx1 += mLastX;
-        dy1 += mLastY;
-        dx2 += mLastX;
-        dy2 += mLastY;
-        mPath.quadTo(dx1, dy1, mLastX = dx2, mLastY = dy2);
-    }
-
-    /**
-     * Add a cubic bezier from the last point, approaching control points
-     * (x1,y1) and (x2,y2), and ending at (x3,y3). If no moveTo() call has been
-     * made for this contour, the first point is automatically set to (0,0).
-     *
-     * @param x1 The x-coordinate of the 1st control point on a cubic curve
-     * @param y1 The y-coordinate of the 1st control point on a cubic curve
-     * @param x2 The x-coordinate of the 2nd control point on a cubic curve
-     * @param y2 The y-coordinate of the 2nd control point on a cubic curve
-     * @param x3 The x-coordinate of the end point on a cubic curve
-     * @param y3 The y-coordinate of the end point on a cubic curve
-     */
-    public void cubicTo(float x1, float y1, float x2, float y2,
-                        float x3, float y3) {
-        mPath.curveTo(x1, y1, x2, y2, mLastX = x3, mLastY = y3);
-    }
-
-    /**
-     * Same as cubicTo, but the coordinates are considered relative to the
-     * current point on this contour. If there is no previous point, then a
-     * moveTo(0,0) is inserted automatically.
-     */
-    public void rCubicTo(float dx1, float dy1, float dx2, float dy2,
-                         float dx3, float dy3) {
-        if (isEmpty()) {
-            mPath.moveTo(mLastX = 0, mLastY = 0);
-        }
-        dx1 += mLastX;
-        dy1 += mLastY;
-        dx2 += mLastX;
-        dy2 += mLastY;
-        dx3 += mLastX;
-        dy3 += mLastY;
-        mPath.curveTo(dx1, dy1, dx2, dy2, mLastX = dx3, mLastY = dy3);
-    }
-
-    /**
-     * Append the specified arc to the path as a new contour. If the start of
-     * the path is different from the path's current last point, then an
-     * automatic lineTo() is added to connect the current contour to the
-     * start of the arc. However, if the path is empty, then we call moveTo()
-     * with the first point of the arc. The sweep angle is tread mod 360.
-     *
-     * @param oval        The bounds of oval defining shape and size of the arc
-     * @param startAngle  Starting angle (in degrees) where the arc begins
-     * @param sweepAngle  Sweep angle (in degrees) measured clockwise, treated
-     *                    mod 360.
-     * @param forceMoveTo If true, always begin a new contour with the arc
-     */
-    public void arcTo(RectF oval, float startAngle, float sweepAngle,
-                      boolean forceMoveTo) {
-        throw new UnsupportedOperationException();
-    }
-    
-    /**
-     * Append the specified arc to the path as a new contour. If the start of
-     * the path is different from the path's current last point, then an
-     * automatic lineTo() is added to connect the current contour to the
-     * start of the arc. However, if the path is empty, then we call moveTo()
-     * with the first point of the arc.
-     *
-     * @param oval        The bounds of oval defining shape and size of the arc
-     * @param startAngle  Starting angle (in degrees) where the arc begins
-     * @param sweepAngle  Sweep angle (in degrees) measured clockwise
-     */
-    public void arcTo(RectF oval, float startAngle, float sweepAngle) {
-        throw new UnsupportedOperationException();
-    }
-    
-    /**
-     * Close the current contour. If the current point is not equal to the
-     * first point of the contour, a line segment is automatically added.
-     */
-    public void close() {
-        mPath.closePath();
-    }
-
-    /**
-     * Specifies how closed shapes (e.g. rects, ovals) are oriented when they
-     * are added to a path.
-     */
-    public enum Direction {
-        /** clockwise */
-        CW  (0),    // must match enum in SkPath.h
-        /** counter-clockwise */
-        CCW (1);    // must match enum in SkPath.h
-        
-        Direction(int ni) {
-            nativeInt = ni;
-        }
-        final int nativeInt;
-    }
-    
-    /**
-     * Add a closed rectangle contour to the path
-     *
-     * @param rect The rectangle to add as a closed contour to the path
-     * @param dir  The direction to wind the rectangle's contour
-     */
-    public void addRect(RectF rect, Direction dir) {
-        if (rect == null) {
-            throw new NullPointerException("need rect parameter");
-        }
-        
-        addRect(rect.left, rect.top, rect.right, rect.bottom, dir);
-    }
-
-    /**
-     * Add a closed rectangle contour to the path
-     *
-     * @param left   The left side of a rectangle to add to the path
-     * @param top    The top of a rectangle to add to the path
-     * @param right  The right side of a rectangle to add to the path
-     * @param bottom The bottom of a rectangle to add to the path
-     * @param dir    The direction to wind the rectangle's contour
-     */
-    public void addRect(float left, float top, float right, float bottom,
-                        Direction dir) {
-        moveTo(left, top);
-
-        switch (dir) {
-            case CW:
-                lineTo(right, top);
-                lineTo(right, bottom);
-                lineTo(left, bottom);
-                break;
-            case CCW:
-                lineTo(left, bottom);
-                lineTo(right, bottom);
-                lineTo(right, top);
-                break;
-        }
-
-        close();
-    }
-
-    /**
-     * Add a closed oval contour to the path
-     *
-     * @param oval The bounds of the oval to add as a closed contour to the path
-     * @param dir  The direction to wind the oval's contour
-     */
-    public void addOval(RectF oval, Direction dir) {
-        if (oval == null) {
-            throw new NullPointerException("need oval parameter");
-        }
-
-        // FIXME Need to support direction
-        Ellipse2D ovalShape = new Ellipse2D.Float(oval.left, oval.top, oval.width(), oval.height());
-        
-        mPath.append(ovalShape, false /* connect */);
-    }
-
-    /**
-     * Add a closed circle contour to the path
-     *
-     * @param x   The x-coordinate of the center of a circle to add to the path
-     * @param y   The y-coordinate of the center of a circle to add to the path
-     * @param radius The radius of a circle to add to the path
-     * @param dir    The direction to wind the circle's contour
-     */
-    public void addCircle(float x, float y, float radius, Direction dir) {
-        // FIXME
-        throw new UnsupportedOperationException();
-    }
-
-    /**
-     * Add the specified arc to the path as a new contour.
-     *
-     * @param oval The bounds of oval defining the shape and size of the arc
-     * @param startAngle Starting angle (in degrees) where the arc begins
-     * @param sweepAngle Sweep angle (in degrees) measured clockwise
-     */
-    public void addArc(RectF oval, float startAngle, float sweepAngle) {
-        if (oval == null) {
-            throw new NullPointerException("need oval parameter");
-        }
-        // FIXME
-        throw new UnsupportedOperationException();
-    }
-
-    /**
-        * Add a closed round-rectangle contour to the path
-     *
-     * @param rect The bounds of a round-rectangle to add to the path
-     * @param rx   The x-radius of the rounded corners on the round-rectangle
-     * @param ry   The y-radius of the rounded corners on the round-rectangle
-     * @param dir  The direction to wind the round-rectangle's contour
-     */
-    public void addRoundRect(RectF rect, float rx, float ry, Direction dir) {
-        if (rect == null) {
-            throw new NullPointerException("need rect parameter");
-        }
-        // FIXME
-        throw new UnsupportedOperationException();
-    }
-    
-    /**
-     * Add a closed round-rectangle contour to the path. Each corner receives
-     * two radius values [X, Y]. The corners are ordered top-left, top-right,
-     * bottom-right, bottom-left
-     *
-     * @param rect The bounds of a round-rectangle to add to the path
-     * @param radii Array of 8 values, 4 pairs of [X,Y] radii
-     * @param dir  The direction to wind the round-rectangle's contour
-     */
-    public void addRoundRect(RectF rect, float[] radii, Direction dir) {
-        if (rect == null) {
-            throw new NullPointerException("need rect parameter");
-        }
-        if (radii.length < 8) {
-            throw new ArrayIndexOutOfBoundsException("radii[] needs 8 values");
-        }
-        // FIXME
-        throw new UnsupportedOperationException();
-    }
-    
-    /**
-     * Add a copy of src to the path, offset by (dx,dy)
-     *
-     * @param src The path to add as a new contour
-     * @param dx  The amount to translate the path in X as it is added
-     */
-    public void addPath(Path src, float dx, float dy) {
-        PathIterator iterator = src.mPath.getPathIterator(new AffineTransform(0, 0, dx, 0, 0, dy));
-        mPath.append(iterator, false /* connect */);
-    }
-
-    /**
-     * Add a copy of src to the path
-     *
-     * @param src The path that is appended to the current path
-     */
-    public void addPath(Path src) {
-        addPath(src, 0, 0);
-    }
-
-    /**
-     * Add a copy of src to the path, transformed by matrix
-     *
-     * @param src The path to add as a new contour
-     */
-    public void addPath(Path src, Matrix matrix) {
-        // FIXME
-        throw new UnsupportedOperationException();
-    }
-
-    /**
-     * Offset the path by (dx,dy), returning true on success
-     *
-     * @param dx  The amount in the X direction to offset the entire path
-     * @param dy  The amount in the Y direction to offset the entire path
-     * @param dst The translated path is written here. If this is null, then
-     *            the original path is modified.
-     */
-    public void offset(float dx, float dy, Path dst) {
-        GeneralPath newPath = new GeneralPath();
-        
-        PathIterator iterator = mPath.getPathIterator(new AffineTransform(0, 0, dx, 0, 0, dy));
-        
-        newPath.append(iterator, false /* connect */);
-        
-        if (dst != null) {
-            dst.mPath = newPath;
-        } else {
-            mPath = newPath;
-        }
-    }
-
-    /**
-     * Offset the path by (dx,dy), returning true on success
-     *
-     * @param dx The amount in the X direction to offset the entire path
-     * @param dy The amount in the Y direction to offset the entire path
-     */
-    public void offset(float dx, float dy) {
-        offset(dx, dy, null /* dst */);
-    }
-
-    /**
-     * Sets the last point of the path.
-     *
-     * @param dx The new X coordinate for the last point
-     * @param dy The new Y coordinate for the last point
-     */
-    public void setLastPoint(float dx, float dy) {
-        mLastX = dx;
-        mLastY = dy;
-    }
-
-    /**
-     * Transform the points in this path by matrix, and write the answer
-     * into dst. If dst is null, then the the original path is modified.
-     *
-     * @param matrix The matrix to apply to the path
-     * @param dst    The transformed path is written here. If dst is null,
-     *               then the the original path is modified
-     */
-    public void transform(Matrix matrix, Path dst) {
-        // FIXME
-        throw new UnsupportedOperationException();
-    }
-
-    /**
-     * Transform the points in this path by matrix.
-     *
-     * @param matrix The matrix to apply to the path
-     */
-    public void transform(Matrix matrix) {
-        transform(matrix, null /* dst */);
-    }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/PathDashPathEffect_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/PathDashPathEffect_Delegate.java
new file mode 100644
index 0000000..c448f0e
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/PathDashPathEffect_Delegate.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import java.awt.Stroke;
+
+/**
+ * Delegate implementing the native methods of android.graphics.PathDashPathEffect
+ *
+ * Through the layoutlib_create tool, the original native methods of PathDashPathEffect have been
+ * replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original PathDashPathEffect class.
+ *
+ * Because this extends {@link PathEffect_Delegate}, there's no need to use a {@link DelegateManager},
+ * as all the Shader classes will be added to the manager owned by {@link PathEffect_Delegate}.
+ *
+ * @see PathEffect_Delegate
+ *
+ */
+public class PathDashPathEffect_Delegate extends PathEffect_Delegate {
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public Stroke getStroke(Paint_Delegate paint) {
+        // FIXME
+        return null;
+    }
+
+    @Override
+    public boolean isSupported() {
+        return false;
+    }
+
+    @Override
+    public String getSupportMessage() {
+        return "Path Dash Path Effects are not supported in Layout Preview mode.";
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeCreate(int native_path, float advance, float phase,
+            int native_style) {
+        PathDashPathEffect_Delegate newDelegate = new PathDashPathEffect_Delegate();
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    // ---- Private delegate/helper methods ----
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/PathEffect_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/PathEffect_Delegate.java
new file mode 100644
index 0000000..bd2b6de
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/PathEffect_Delegate.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import java.awt.Stroke;
+
+/**
+ * Delegate implementing the native methods of android.graphics.PathEffect
+ *
+ * Through the layoutlib_create tool, the original native methods of PathEffect have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original PathEffect class.
+ *
+ * This also serve as a base class for all PathEffect delegate classes.
+ *
+ * @see DelegateManager
+ *
+ */
+public abstract class PathEffect_Delegate {
+
+    // ---- delegate manager ----
+    protected static final DelegateManager<PathEffect_Delegate> sManager =
+            new DelegateManager<PathEffect_Delegate>(PathEffect_Delegate.class);
+
+    // ---- delegate helper data ----
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    public static PathEffect_Delegate getDelegate(int nativeShader) {
+        return sManager.getDelegate(nativeShader);
+    }
+
+    public abstract Stroke getStroke(Paint_Delegate paint);
+    public abstract boolean isSupported();
+    public abstract String getSupportMessage();
+
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeDestructor(int native_patheffect) {
+        sManager.removeJavaReferenceFor(native_patheffect);
+    }
+
+    // ---- Private delegate/helper methods ----
+
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Path_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Path_Delegate.java
new file mode 100644
index 0000000..64f19d3
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/Path_Delegate.java
@@ -0,0 +1,815 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import android.graphics.Path.Direction;
+import android.graphics.Path.FillType;
+
+import java.awt.Shape;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Arc2D;
+import java.awt.geom.Area;
+import java.awt.geom.Ellipse2D;
+import java.awt.geom.GeneralPath;
+import java.awt.geom.PathIterator;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.awt.geom.RoundRectangle2D;
+
+/**
+ * Delegate implementing the native methods of android.graphics.Path
+ *
+ * Through the layoutlib_create tool, the original native methods of Path have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original Path class.
+ *
+ * @see DelegateManager
+ *
+ */
+public final class Path_Delegate {
+
+    // ---- delegate manager ----
+    private static final DelegateManager<Path_Delegate> sManager =
+            new DelegateManager<Path_Delegate>(Path_Delegate.class);
+
+    // ---- delegate data ----
+    private FillType mFillType = FillType.WINDING;
+    private GeneralPath mPath = new GeneralPath();
+
+    private float mLastX = 0;
+    private float mLastY = 0;
+
+    // ---- Public Helper methods ----
+
+    public static Path_Delegate getDelegate(int nPath) {
+        return sManager.getDelegate(nPath);
+    }
+
+    public Shape getJavaShape() {
+        return mPath;
+    }
+
+    public void setJavaShape(Shape shape) {
+        mPath.reset();
+        mPath.append(shape, false /*connect*/);
+    }
+
+    public void reset() {
+        mPath.reset();
+    }
+
+    public void setPathIterator(PathIterator iterator) {
+        mPath.reset();
+        mPath.append(iterator, false /*connect*/);
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int init1() {
+        // create the delegate
+        Path_Delegate newDelegate = new Path_Delegate();
+
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int init2(int nPath) {
+        // create the delegate
+        Path_Delegate newDelegate = new Path_Delegate();
+
+        // get the delegate to copy, which could be null if nPath is 0
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate != null) {
+            newDelegate.set(pathDelegate);
+        }
+
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_reset(int nPath) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        pathDelegate.mPath.reset();
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_rewind(int nPath) {
+        // call out to reset since there's nothing to optimize in
+        // terms of data structs.
+        native_reset(nPath);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_set(int native_dst, int native_src) {
+        Path_Delegate pathDstDelegate = sManager.getDelegate(native_dst);
+        if (pathDstDelegate == null) {
+            return;
+        }
+
+        Path_Delegate pathSrcDelegate = sManager.getDelegate(native_src);
+        if (pathSrcDelegate == null) {
+            return;
+        }
+
+        pathDstDelegate.set(pathSrcDelegate);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int native_getFillType(int nPath) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return 0;
+        }
+
+        return pathDelegate.mFillType.nativeInt;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_setFillType(int nPath, int ft) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        pathDelegate.mFillType = Path.sFillTypeArray[ft];
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_isEmpty(int nPath) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return true;
+        }
+
+        return pathDelegate.isEmpty();
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean native_isRect(int nPath, RectF rect) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return false;
+        }
+
+        // create an Area that can test if the path is a rect
+        Area area = new Area(pathDelegate.mPath);
+        if (area.isRectangular()) {
+            if (rect != null) {
+                pathDelegate.fillBounds(rect);
+            }
+
+            return true;
+        }
+
+        return false;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_computeBounds(int nPath, RectF bounds) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        pathDelegate.fillBounds(bounds);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_incReserve(int nPath, int extraPtCount) {
+        // since we use a java2D path, there's no way to pre-allocate new points,
+        // so we do nothing.
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_moveTo(int nPath, float x, float y) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        pathDelegate.moveTo(x, y);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_rMoveTo(int nPath, float dx, float dy) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        pathDelegate.rMoveTo(dx, dy);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_lineTo(int nPath, float x, float y) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        pathDelegate.lineTo(x, y);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_rLineTo(int nPath, float dx, float dy) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        pathDelegate.rLineTo(dx, dy);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_quadTo(int nPath, float x1, float y1, float x2, float y2) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        pathDelegate.quadTo(x1, y1, x2, y2);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_rQuadTo(int nPath, float dx1, float dy1, float dx2, float dy2) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        pathDelegate.rQuadTo(dx1, dy1, dx2, dy2);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_cubicTo(int nPath, float x1, float y1,
+            float x2, float y2, float x3, float y3) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        pathDelegate.cubicTo(x1, y1, x2, y2, x3, y3);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_rCubicTo(int nPath, float x1, float y1,
+            float x2, float y2, float x3, float y3) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        pathDelegate.rCubicTo(x1, y1, x2, y2, x3, y3);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_arcTo(int nPath, RectF oval,
+                    float startAngle, float sweepAngle, boolean forceMoveTo) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        pathDelegate.arcTo(oval, startAngle, sweepAngle, forceMoveTo);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_close(int nPath) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        pathDelegate.close();
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_addRect(int nPath, RectF rect, int dir) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        pathDelegate.addRect(rect.left, rect.top, rect.right, rect.bottom, dir);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_addRect(int nPath,
+            float left, float top, float right, float bottom, int dir) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        pathDelegate.addRect(left, top, right, bottom, dir);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_addOval(int nPath, RectF oval, int dir) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        pathDelegate.mPath.append(new Ellipse2D.Float(
+                oval.left, oval.top, oval.width(), oval.height()), false);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_addCircle(int nPath, float x, float y, float radius, int dir) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        // because x/y is the center of the circle, need to offset this by the radius
+        pathDelegate.mPath.append(new Ellipse2D.Float(
+                x - radius, y - radius, radius * 2, radius * 2), false);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_addArc(int nPath, RectF oval,
+            float startAngle, float sweepAngle) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        // because x/y is the center of the circle, need to offset this by the radius
+        pathDelegate.mPath.append(new Arc2D.Float(
+                oval.left, oval.top, oval.width(), oval.height(),
+                -startAngle, -sweepAngle, Arc2D.OPEN), false);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_addRoundRect(
+            int nPath, RectF rect, float rx, float ry, int dir) {
+
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        pathDelegate.mPath.append(new RoundRectangle2D.Float(
+                rect.left, rect.top, rect.width(), rect.height(), rx * 2, ry * 2), false);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_addRoundRect(int nPath, RectF rect, float[] radii, int dir) {
+        // Java2D doesn't support different rounded corners in each corner, so just use the
+        // first value.
+        native_addRoundRect(nPath, rect, radii[0], radii[1], dir);
+
+        // there can be a case where this API is used but with similar values for all corners, so
+        // in that case we don't warn.
+        // we only care if 2 corners are different so just compare to the next one.
+        for (int i = 0 ; i < 3 ; i++) {
+            if (radii[i * 2] != radii[(i + 1) * 2] || radii[i * 2 + 1] != radii[(i + 1) * 2 + 1]) {
+                Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
+                        "Different corner sizes are not supported in Path.addRoundRect.",
+                        null, null /*data*/);
+                break;
+            }
+        }
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_addPath(int nPath, int src, float dx, float dy) {
+        addPath(nPath, src, AffineTransform.getTranslateInstance(dx, dy));
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_addPath(int nPath, int src) {
+        addPath(nPath, src, null /*transform*/);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_addPath(int nPath, int src, int matrix) {
+        Matrix_Delegate matrixDelegate = Matrix_Delegate.getDelegate(matrix);
+        if (matrixDelegate == null) {
+            return;
+        }
+
+        addPath(nPath, src, matrixDelegate.getAffineTransform());
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_offset(int nPath, float dx, float dy, int dst_path) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        // could be null if the int is 0;
+        Path_Delegate dstDelegate = sManager.getDelegate(dst_path);
+
+        pathDelegate.offset(dx, dy, dstDelegate);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_offset(int nPath, float dx, float dy) {
+        native_offset(nPath, dx, dy, 0);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_setLastPoint(int nPath, float dx, float dy) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        pathDelegate.mLastX = dx;
+        pathDelegate.mLastY = dy;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_transform(int nPath, int matrix,
+                                                int dst_path) {
+        Path_Delegate pathDelegate = sManager.getDelegate(nPath);
+        if (pathDelegate == null) {
+            return;
+        }
+
+        Matrix_Delegate matrixDelegate = Matrix_Delegate.getDelegate(matrix);
+        if (matrixDelegate == null) {
+            return;
+        }
+
+        // this can be null if dst_path is 0
+        Path_Delegate dstDelegate = sManager.getDelegate(dst_path);
+
+        pathDelegate.transform(matrixDelegate, dstDelegate);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void native_transform(int nPath, int matrix) {
+        native_transform(nPath, matrix, 0);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void finalizer(int nPath) {
+        sManager.removeJavaReferenceFor(nPath);
+    }
+
+
+    // ---- Private helper methods ----
+
+    private void set(Path_Delegate delegate) {
+        mPath.reset();
+        setFillType(delegate.mFillType);
+        mPath.append(delegate.mPath, false /*connect*/);
+    }
+
+    private void setFillType(FillType fillType) {
+        mFillType = fillType;
+        mPath.setWindingRule(getWindingRule(fillType));
+    }
+
+    /**
+     * Returns the Java2D winding rules matching a given Android {@link FillType}.
+     * @param type the android fill type
+     * @return the matching java2d winding rule.
+     */
+    private static int getWindingRule(FillType type) {
+        switch (type) {
+            case WINDING:
+            case INVERSE_WINDING:
+                return GeneralPath.WIND_NON_ZERO;
+            case EVEN_ODD:
+            case INVERSE_EVEN_ODD:
+                return GeneralPath.WIND_EVEN_ODD;
+        }
+
+        assert false;
+        throw new IllegalArgumentException();
+    }
+
+    private static Direction getDirection(int direction) {
+        for (Direction d : Direction.values()) {
+            if (direction == d.nativeInt) {
+                return d;
+            }
+        }
+
+        assert false;
+        return null;
+    }
+
+    private static void addPath(int destPath, int srcPath, AffineTransform transform) {
+        Path_Delegate destPathDelegate = sManager.getDelegate(destPath);
+        if (destPathDelegate == null) {
+            return;
+        }
+
+        Path_Delegate srcPathDelegate = sManager.getDelegate(srcPath);
+        if (srcPathDelegate == null) {
+            return;
+        }
+
+        if (transform != null) {
+            destPathDelegate.mPath.append(
+                    srcPathDelegate.mPath.getPathIterator(transform), false);
+        } else {
+            destPathDelegate.mPath.append(srcPathDelegate.mPath, false);
+        }
+    }
+
+
+    /**
+     * Returns whether the path is empty.
+     * @return true if the path is empty.
+     */
+    private boolean isEmpty() {
+        return mPath.getCurrentPoint() == null;
+    }
+
+    /**
+     * Fills the given {@link RectF} with the path bounds.
+     * @param bounds the RectF to be filled.
+     */
+    private void fillBounds(RectF bounds) {
+        Rectangle2D rect = mPath.getBounds2D();
+        bounds.left = (float)rect.getMinX();
+        bounds.right = (float)rect.getMaxX();
+        bounds.top = (float)rect.getMinY();
+        bounds.bottom = (float)rect.getMaxY();
+    }
+
+    /**
+     * Set the beginning of the next contour to the point (x,y).
+     *
+     * @param x The x-coordinate of the start of a new contour
+     * @param y The y-coordinate of the start of a new contour
+     */
+    private void moveTo(float x, float y) {
+        mPath.moveTo(mLastX = x, mLastY = y);
+    }
+
+    /**
+     * Set the beginning of the next contour relative to the last point on the
+     * previous contour. If there is no previous contour, this is treated the
+     * same as moveTo().
+     *
+     * @param dx The amount to add to the x-coordinate of the end of the
+     *           previous contour, to specify the start of a new contour
+     * @param dy The amount to add to the y-coordinate of the end of the
+     *           previous contour, to specify the start of a new contour
+     */
+    private void rMoveTo(float dx, float dy) {
+        dx += mLastX;
+        dy += mLastY;
+        mPath.moveTo(mLastX = dx, mLastY = dy);
+    }
+
+    /**
+     * Add a line from the last point to the specified point (x,y).
+     * If no moveTo() call has been made for this contour, the first point is
+     * automatically set to (0,0).
+     *
+     * @param x The x-coordinate of the end of a line
+     * @param y The y-coordinate of the end of a line
+     */
+    private void lineTo(float x, float y) {
+        mPath.lineTo(mLastX = x, mLastY = y);
+    }
+
+    /**
+     * Same as lineTo, but the coordinates are considered relative to the last
+     * point on this contour. If there is no previous point, then a moveTo(0,0)
+     * is inserted automatically.
+     *
+     * @param dx The amount to add to the x-coordinate of the previous point on
+     *           this contour, to specify a line
+     * @param dy The amount to add to the y-coordinate of the previous point on
+     *           this contour, to specify a line
+     */
+    private void rLineTo(float dx, float dy) {
+        if (isEmpty()) {
+            mPath.moveTo(mLastX = 0, mLastY = 0);
+        }
+        dx += mLastX;
+        dy += mLastY;
+        mPath.lineTo(mLastX = dx, mLastY = dy);
+    }
+
+    /**
+     * Add a quadratic bezier from the last point, approaching control point
+     * (x1,y1), and ending at (x2,y2). If no moveTo() call has been made for
+     * this contour, the first point is automatically set to (0,0).
+     *
+     * @param x1 The x-coordinate of the control point on a quadratic curve
+     * @param y1 The y-coordinate of the control point on a quadratic curve
+     * @param x2 The x-coordinate of the end point on a quadratic curve
+     * @param y2 The y-coordinate of the end point on a quadratic curve
+     */
+    private void quadTo(float x1, float y1, float x2, float y2) {
+        mPath.quadTo(x1, y1, mLastX = x2, mLastY = y2);
+    }
+
+    /**
+     * Same as quadTo, but the coordinates are considered relative to the last
+     * point on this contour. If there is no previous point, then a moveTo(0,0)
+     * is inserted automatically.
+     *
+     * @param dx1 The amount to add to the x-coordinate of the last point on
+     *            this contour, for the control point of a quadratic curve
+     * @param dy1 The amount to add to the y-coordinate of the last point on
+     *            this contour, for the control point of a quadratic curve
+     * @param dx2 The amount to add to the x-coordinate of the last point on
+     *            this contour, for the end point of a quadratic curve
+     * @param dy2 The amount to add to the y-coordinate of the last point on
+     *            this contour, for the end point of a quadratic curve
+     */
+    private void rQuadTo(float dx1, float dy1, float dx2, float dy2) {
+        if (isEmpty()) {
+            mPath.moveTo(mLastX = 0, mLastY = 0);
+        }
+        dx1 += mLastX;
+        dy1 += mLastY;
+        dx2 += mLastX;
+        dy2 += mLastY;
+        mPath.quadTo(dx1, dy1, mLastX = dx2, mLastY = dy2);
+    }
+
+    /**
+     * Add a cubic bezier from the last point, approaching control points
+     * (x1,y1) and (x2,y2), and ending at (x3,y3). If no moveTo() call has been
+     * made for this contour, the first point is automatically set to (0,0).
+     *
+     * @param x1 The x-coordinate of the 1st control point on a cubic curve
+     * @param y1 The y-coordinate of the 1st control point on a cubic curve
+     * @param x2 The x-coordinate of the 2nd control point on a cubic curve
+     * @param y2 The y-coordinate of the 2nd control point on a cubic curve
+     * @param x3 The x-coordinate of the end point on a cubic curve
+     * @param y3 The y-coordinate of the end point on a cubic curve
+     */
+    private void cubicTo(float x1, float y1, float x2, float y2,
+                        float x3, float y3) {
+        mPath.curveTo(x1, y1, x2, y2, mLastX = x3, mLastY = y3);
+    }
+
+    /**
+     * Same as cubicTo, but the coordinates are considered relative to the
+     * current point on this contour. If there is no previous point, then a
+     * moveTo(0,0) is inserted automatically.
+     */
+    private void rCubicTo(float dx1, float dy1, float dx2, float dy2,
+                         float dx3, float dy3) {
+        if (isEmpty()) {
+            mPath.moveTo(mLastX = 0, mLastY = 0);
+        }
+        dx1 += mLastX;
+        dy1 += mLastY;
+        dx2 += mLastX;
+        dy2 += mLastY;
+        dx3 += mLastX;
+        dy3 += mLastY;
+        mPath.curveTo(dx1, dy1, dx2, dy2, mLastX = dx3, mLastY = dy3);
+    }
+
+    /**
+     * Append the specified arc to the path as a new contour. If the start of
+     * the path is different from the path's current last point, then an
+     * automatic lineTo() is added to connect the current contour to the
+     * start of the arc. However, if the path is empty, then we call moveTo()
+     * with the first point of the arc. The sweep angle is tread mod 360.
+     *
+     * @param oval        The bounds of oval defining shape and size of the arc
+     * @param startAngle  Starting angle (in degrees) where the arc begins
+     * @param sweepAngle  Sweep angle (in degrees) measured clockwise, treated
+     *                    mod 360.
+     * @param forceMoveTo If true, always begin a new contour with the arc
+     */
+    private void arcTo(RectF oval, float startAngle, float sweepAngle, boolean forceMoveTo) {
+        Arc2D arc = new Arc2D.Float(oval.left, oval.top, oval.width(), oval.height(), -startAngle,
+                -sweepAngle, Arc2D.OPEN);
+        mPath.append(arc, true /*connect*/);
+
+        resetLastPointFromPath();
+    }
+
+    /**
+     * Close the current contour. If the current point is not equal to the
+     * first point of the contour, a line segment is automatically added.
+     */
+    private void close() {
+        mPath.closePath();
+    }
+
+    private void resetLastPointFromPath() {
+        Point2D last = mPath.getCurrentPoint();
+        mLastX = (float) last.getX();
+        mLastY = (float) last.getY();
+    }
+
+    /**
+     * Add a closed rectangle contour to the path
+     *
+     * @param left   The left side of a rectangle to add to the path
+     * @param top    The top of a rectangle to add to the path
+     * @param right  The right side of a rectangle to add to the path
+     * @param bottom The bottom of a rectangle to add to the path
+     * @param dir    The direction to wind the rectangle's contour
+     */
+    private void addRect(float left, float top, float right, float bottom,
+                        int dir) {
+        moveTo(left, top);
+
+        Direction direction = getDirection(dir);
+
+        switch (direction) {
+            case CW:
+                lineTo(right, top);
+                lineTo(right, bottom);
+                lineTo(left, bottom);
+                break;
+            case CCW:
+                lineTo(left, bottom);
+                lineTo(right, bottom);
+                lineTo(right, top);
+                break;
+        }
+
+        close();
+
+        resetLastPointFromPath();
+    }
+
+    /**
+     * Offset the path by (dx,dy), returning true on success
+     *
+     * @param dx  The amount in the X direction to offset the entire path
+     * @param dy  The amount in the Y direction to offset the entire path
+     * @param dst The translated path is written here. If this is null, then
+     *            the original path is modified.
+     */
+    public void offset(float dx, float dy, Path_Delegate dst) {
+        GeneralPath newPath = new GeneralPath();
+
+        PathIterator iterator = mPath.getPathIterator(new AffineTransform(0, 0, dx, 0, 0, dy));
+
+        newPath.append(iterator, false /*connect*/);
+
+        if (dst != null) {
+            dst.mPath = newPath;
+        } else {
+            mPath = newPath;
+        }
+    }
+
+    /**
+     * Transform the points in this path by matrix, and write the answer
+     * into dst. If dst is null, then the the original path is modified.
+     *
+     * @param matrix The matrix to apply to the path
+     * @param dst    The transformed path is written here. If dst is null,
+     *               then the the original path is modified
+     */
+    public void transform(Matrix_Delegate matrix, Path_Delegate dst) {
+        if (matrix.hasPerspective()) {
+            assert false;
+            Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_AFFINE,
+                    "android.graphics.Path#transform() only " +
+                    "supports affine transformations.", null, null /*data*/);
+        }
+
+        GeneralPath newPath = new GeneralPath();
+
+        PathIterator iterator = mPath.getPathIterator(matrix.getAffineTransform());
+
+        newPath.append(iterator, false /*connect*/);
+
+        if (dst != null) {
+            dst.mPath = newPath;
+        } else {
+            mPath = newPath;
+        }
+    }
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/PixelXorXfermode_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/PixelXorXfermode_Delegate.java
new file mode 100644
index 0000000..4ab044b
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/PixelXorXfermode_Delegate.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import java.awt.Composite;
+
+/**
+ * Delegate implementing the native methods of android.graphics.PixelXorXfermode
+ *
+ * Through the layoutlib_create tool, the original native methods of PixelXorXfermode have been
+ * replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original PixelXorXfermode class.
+ *
+ * Because this extends {@link Xfermode_Delegate}, there's no need to use a
+ * {@link DelegateManager}, as all the PathEffect classes will be added to the manager owned by
+ * {@link Xfermode_Delegate}.
+ *
+ * @see Xfermode_Delegate
+ */
+public class PixelXorXfermode_Delegate extends Xfermode_Delegate {
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public Composite getComposite(int alpha) {
+        // FIXME
+        return null;
+    }
+
+    @Override
+    public boolean isSupported() {
+        return false;
+    }
+
+    @Override
+    public String getSupportMessage() {
+        return "Pixel XOR Xfermodes are not supported in Layout Preview mode.";
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeCreate(int opColor) {
+        PixelXorXfermode_Delegate newDelegate = new PixelXorXfermode_Delegate();
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    // ---- Private delegate/helper methods ----
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/PorterDuffColorFilter_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/PorterDuffColorFilter_Delegate.java
new file mode 100644
index 0000000..65c65a1
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/PorterDuffColorFilter_Delegate.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+/**
+ * Delegate implementing the native methods of android.graphics.PorterDuffColorFilter
+ *
+ * Through the layoutlib_create tool, the original native methods of PorterDuffColorFilter have
+ * been replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original PorterDuffColorFilter class.
+ *
+ * Because this extends {@link ColorFilter_Delegate}, there's no need to use a
+ * {@link DelegateManager}, as all the Shader classes will be added to the manager
+ * owned by {@link ColorFilter_Delegate}.
+ *
+ * @see ColorFilter_Delegate
+ *
+ */
+public class PorterDuffColorFilter_Delegate extends ColorFilter_Delegate {
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public boolean isSupported() {
+        return false;
+    }
+
+    @Override
+    public String getSupportMessage() {
+        return "PorterDuff Color Filters are not supported.";
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int native_CreatePorterDuffFilter(int srcColor, int porterDuffMode) {
+        PorterDuffColorFilter_Delegate newDelegate = new PorterDuffColorFilter_Delegate();
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    // ---- Private delegate/helper methods ----
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/PorterDuffXfermode.java b/tools/layoutlib/bridge/src/android/graphics/PorterDuffXfermode.java
deleted file mode 100644
index 974ae49..0000000
--- a/tools/layoutlib/bridge/src/android/graphics/PorterDuffXfermode.java
+++ /dev/null
@@ -1,40 +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.graphics;
-
-import android.graphics.PorterDuff.Mode;
-
-public class PorterDuffXfermode extends Xfermode {
-    private final Mode mMode;
-
-    /**
-     * Create an xfermode that uses the specified porter-duff mode.
-     *
-     * @param mode           The porter-duff mode that is applied
-     */
-    public PorterDuffXfermode(PorterDuff.Mode mode) {
-        mMode = mode;
-    }
-    
-    //---------- Custom Methods
-    
-    public PorterDuff.Mode getMode() {
-        return mMode;
-    }
-    
-    //----------
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/PorterDuffXfermode_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/PorterDuffXfermode_Delegate.java
new file mode 100644
index 0000000..4301c1a
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/PorterDuffXfermode_Delegate.java
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import java.awt.AlphaComposite;
+import java.awt.Composite;
+
+/**
+ * Delegate implementing the native methods of android.graphics.PorterDuffXfermode
+ *
+ * Through the layoutlib_create tool, the original native methods of PorterDuffXfermode have been
+ * replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original PorterDuffXfermode class.
+ *
+ * Because this extends {@link Xfermode_Delegate}, there's no need to use a
+ * {@link DelegateManager}, as all the PathEffect classes will be added to the manager owned by
+ * {@link Xfermode_Delegate}.
+ *
+ */
+public class PorterDuffXfermode_Delegate extends Xfermode_Delegate {
+
+    // ---- delegate data ----
+
+    private final int mMode;
+
+    // ---- Public Helper methods ----
+
+    public PorterDuff.Mode getMode() {
+        return getPorterDuffMode(mMode);
+    }
+
+    @Override
+    public Composite getComposite(int alpha) {
+        return getComposite(getPorterDuffMode(mMode), alpha);
+    }
+
+    @Override
+    public boolean isSupported() {
+        return true;
+    }
+
+    @Override
+    public String getSupportMessage() {
+        // no message since isSupported returns true;
+        return null;
+    }
+
+    public static PorterDuff.Mode getPorterDuffMode(int mode) {
+        for (PorterDuff.Mode m : PorterDuff.Mode.values()) {
+            if (m.nativeInt == mode) {
+                return m;
+            }
+        }
+
+        Bridge.getLog().error(LayoutLog.TAG_BROKEN,
+                String.format("Unknown PorterDuff.Mode: %d", mode), null /*data*/);
+        assert false;
+        return PorterDuff.Mode.SRC_OVER;
+    }
+
+    public static Composite getComposite(PorterDuff.Mode mode, int alpha) {
+        float falpha = alpha != 0xFF ? (float)alpha / 255.f : 1.f;
+        switch (mode) {
+            case CLEAR:
+                return AlphaComposite.getInstance(AlphaComposite.CLEAR, falpha);
+            case DARKEN:
+                break;
+            case DST:
+                return AlphaComposite.getInstance(AlphaComposite.DST, falpha);
+            case DST_ATOP:
+                return AlphaComposite.getInstance(AlphaComposite.DST_ATOP, falpha);
+            case DST_IN:
+                return AlphaComposite.getInstance(AlphaComposite.DST_IN, falpha);
+            case DST_OUT:
+                return AlphaComposite.getInstance(AlphaComposite.DST_OUT, falpha);
+            case DST_OVER:
+                return AlphaComposite.getInstance(AlphaComposite.DST_OVER, falpha);
+            case LIGHTEN:
+                break;
+            case MULTIPLY:
+                break;
+            case SCREEN:
+                break;
+            case SRC:
+                return AlphaComposite.getInstance(AlphaComposite.SRC, falpha);
+            case SRC_ATOP:
+                return AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, falpha);
+            case SRC_IN:
+                return AlphaComposite.getInstance(AlphaComposite.SRC_IN, falpha);
+            case SRC_OUT:
+                return AlphaComposite.getInstance(AlphaComposite.SRC_OUT, falpha);
+            case SRC_OVER:
+                return AlphaComposite.getInstance(AlphaComposite.SRC_OVER, falpha);
+            case XOR:
+                return AlphaComposite.getInstance(AlphaComposite.XOR, falpha);
+        }
+
+        Bridge.getLog().fidelityWarning(LayoutLog.TAG_BROKEN,
+                String.format("Unsupported PorterDuff Mode: %s", mode.name()),
+                null, null /*data*/);
+
+        return AlphaComposite.getInstance(AlphaComposite.SRC_OVER, falpha);
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeCreateXfermode(int mode) {
+        PorterDuffXfermode_Delegate newDelegate = new PorterDuffXfermode_Delegate(mode);
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    // ---- Private delegate/helper methods ----
+
+    private PorterDuffXfermode_Delegate(int mode) {
+        mMode = mode;
+    }
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/RadialGradient.java b/tools/layoutlib/bridge/src/android/graphics/RadialGradient.java
deleted file mode 100644
index 4409a80..0000000
--- a/tools/layoutlib/bridge/src/android/graphics/RadialGradient.java
+++ /dev/null
@@ -1,132 +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.graphics;
-
-public class RadialGradient extends GradientShader {
-
-    private RadialGradientPaint mPaint;
-
-    /**
-     * Create a shader that draws a radial gradient given the center and radius.
-     *
-     * @param x The x-coordinate of the center of the radius
-     * @param y The y-coordinate of the center of the radius
-     * @param radius Must be positive. The radius of the circle for this
-     *            gradient
-     * @param colors The colors to be distributed between the center and edge of
-     *            the circle
-     * @param positions May be NULL. The relative position of each corresponding
-     *            color in the colors array. If this is NULL, the the colors are
-     *            distributed evenly between the center and edge of the circle.
-     * @param tile The Shader tiling mode
-     */
-    public RadialGradient(float x, float y, float radius, int colors[], float positions[],
-            TileMode tile) {
-        super(colors, positions);
-        if (radius <= 0) {
-            throw new IllegalArgumentException("radius must be > 0");
-        }
-
-        mPaint = new RadialGradientPaint(x, y, radius, mColors, mPositions, tile);
-    }
-
-    /**
-     * Create a shader that draws a radial gradient given the center and radius.
-     *
-     * @param x The x-coordinate of the center of the radius
-     * @param y The y-coordinate of the center of the radius
-     * @param radius Must be positive. The radius of the circle for this
-     *            gradient
-     * @param color0 The color at the center of the circle.
-     * @param color1 The color at the edge of the circle.
-     * @param tile The Shader tiling mode
-     */
-    public RadialGradient(float x, float y, float radius, int color0, int color1, TileMode tile) {
-        this(x, y, radius, new int[] { color0, color1 }, null /* positions */, tile);
-    }
-
-    @Override
-    java.awt.Paint getJavaPaint() {
-        return mPaint;
-    }
-
-    private static class RadialGradientPaint extends GradientPaint {
-
-        private final float mX;
-        private final float mY;
-        private final float mRadius;
-
-        public RadialGradientPaint(float x, float y, float radius, int[] colors, float[] positions, TileMode mode) {
-            super(colors, positions, mode);
-            mX = x;
-            mY = y;
-            mRadius = radius;
-        }
-
-        public java.awt.PaintContext createContext(
-                java.awt.image.ColorModel     colorModel,
-                java.awt.Rectangle            deviceBounds,
-                java.awt.geom.Rectangle2D     userBounds,
-                java.awt.geom.AffineTransform xform,
-                java.awt.RenderingHints       hints) {
-            precomputeGradientColors();
-            return new RadialGradientPaintContext(colorModel);
-        }
-
-        private class RadialGradientPaintContext implements java.awt.PaintContext {
-
-            private final java.awt.image.ColorModel mColorModel;
-
-            public RadialGradientPaintContext(java.awt.image.ColorModel colorModel) {
-                mColorModel = colorModel;
-            }
-
-            public void dispose() {
-            }
-
-            public java.awt.image.ColorModel getColorModel() {
-                return mColorModel;
-            }
-
-            public java.awt.image.Raster getRaster(int x, int y, int w, int h) {
-                java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(w, h,
-                        java.awt.image.BufferedImage.TYPE_INT_ARGB);
-
-                int[] data = new int[w*h];
-
-                // compute distance from each point to the center, and figure out the distance from
-                // it.
-                int index = 0;
-                for (int iy = 0 ; iy < h ; iy++) {
-                    for (int ix = 0 ; ix < w ; ix++) {
-                        float _x = x + ix - mX;
-                        float _y = y + iy - mY;
-                        float distance = (float) Math.sqrt(_x * _x + _y * _y);
-
-                        data[index++] = getGradientColor(distance / mRadius);
-                    }
-                }
-
-                image.setRGB(0 /*startX*/, 0 /*startY*/, w, h, data, 0 /*offset*/, w /*scansize*/);
-
-                return image.getRaster();
-            }
-
-        }
-    }
-
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/RadialGradient_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/RadialGradient_Delegate.java
new file mode 100644
index 0000000..bdc0ab1
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/RadialGradient_Delegate.java
@@ -0,0 +1,197 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import android.graphics.Shader.TileMode;
+
+/**
+ * Delegate implementing the native methods of android.graphics.RadialGradient
+ *
+ * Through the layoutlib_create tool, the original native methods of RadialGradient have been
+ * replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original RadialGradient class.
+ *
+ * Because this extends {@link Shader_Delegate}, there's no need to use a {@link DelegateManager},
+ * as all the Shader classes will be added to the manager owned by {@link Shader_Delegate}.
+ *
+ * @see Shader_Delegate
+ *
+ */
+public class RadialGradient_Delegate extends Gradient_Delegate {
+
+    // ---- delegate data ----
+    private java.awt.Paint mJavaPaint;
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public java.awt.Paint getJavaPaint() {
+        return mJavaPaint;
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeCreate1(float x, float y, float radius,
+            int colors[], float positions[], int tileMode) {
+        RadialGradient_Delegate newDelegate = new RadialGradient_Delegate(x, y, radius,
+                colors, positions, Shader_Delegate.getTileMode(tileMode));
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeCreate2(float x, float y, float radius,
+            int color0, int color1, int tileMode) {
+        return nativeCreate1(x, y, radius, new int[] { color0, color1 }, null /*positions*/,
+                tileMode);
+    }
+
+    // ---- Private delegate/helper methods ----
+
+    /**
+     * Create a shader that draws a radial gradient given the center and radius.
+     *
+     * @param x The x-coordinate of the center of the radius
+     * @param y The y-coordinate of the center of the radius
+     * @param radius Must be positive. The radius of the circle for this
+     *            gradient
+     * @param colors The colors to be distributed between the center and edge of
+     *            the circle
+     * @param positions May be NULL. The relative position of each corresponding
+     *            color in the colors array. If this is NULL, the the colors are
+     *            distributed evenly between the center and edge of the circle.
+     * @param tile The Shader tiling mode
+     */
+    private RadialGradient_Delegate(float x, float y, float radius, int colors[], float positions[],
+            TileMode tile) {
+        super(colors, positions);
+        mJavaPaint = new RadialGradientPaint(x, y, radius, mColors, mPositions, tile);
+    }
+
+    private class RadialGradientPaint extends GradientPaint {
+
+        private final float mX;
+        private final float mY;
+        private final float mRadius;
+
+        public RadialGradientPaint(float x, float y, float radius,
+                int[] colors, float[] positions, TileMode mode) {
+            super(colors, positions, mode);
+            mX = x;
+            mY = y;
+            mRadius = radius;
+        }
+
+        public java.awt.PaintContext createContext(
+                java.awt.image.ColorModel     colorModel,
+                java.awt.Rectangle            deviceBounds,
+                java.awt.geom.Rectangle2D     userBounds,
+                java.awt.geom.AffineTransform xform,
+                java.awt.RenderingHints       hints) {
+            precomputeGradientColors();
+
+            java.awt.geom.AffineTransform canvasMatrix;
+            try {
+                canvasMatrix = xform.createInverse();
+            } catch (java.awt.geom.NoninvertibleTransformException e) {
+                Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
+                        "Unable to inverse matrix in RadialGradient", e, null /*data*/);
+                canvasMatrix = new java.awt.geom.AffineTransform();
+            }
+
+            java.awt.geom.AffineTransform localMatrix = getLocalMatrix();
+            try {
+                localMatrix = localMatrix.createInverse();
+            } catch (java.awt.geom.NoninvertibleTransformException e) {
+                Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
+                        "Unable to inverse matrix in RadialGradient", e, null /*data*/);
+                localMatrix = new java.awt.geom.AffineTransform();
+            }
+
+            return new RadialGradientPaintContext(canvasMatrix, localMatrix, colorModel);
+        }
+
+        private class RadialGradientPaintContext implements java.awt.PaintContext {
+
+            private final java.awt.geom.AffineTransform mCanvasMatrix;
+            private final java.awt.geom.AffineTransform mLocalMatrix;
+            private final java.awt.image.ColorModel mColorModel;
+
+            public RadialGradientPaintContext(
+                    java.awt.geom.AffineTransform canvasMatrix,
+                    java.awt.geom.AffineTransform localMatrix,
+                    java.awt.image.ColorModel colorModel) {
+                mCanvasMatrix = canvasMatrix;
+                mLocalMatrix = localMatrix;
+                mColorModel = colorModel;
+            }
+
+            public void dispose() {
+            }
+
+            public java.awt.image.ColorModel getColorModel() {
+                return mColorModel;
+            }
+
+            public java.awt.image.Raster getRaster(int x, int y, int w, int h) {
+                java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(w, h,
+                        java.awt.image.BufferedImage.TYPE_INT_ARGB);
+
+                int[] data = new int[w*h];
+
+                // compute distance from each point to the center, and figure out the distance from
+                // it.
+                int index = 0;
+                float[] pt1 = new float[2];
+                float[] pt2 = new float[2];
+                for (int iy = 0 ; iy < h ; iy++) {
+                    for (int ix = 0 ; ix < w ; ix++) {
+                        // handle the canvas transform
+                        pt1[0] = x + ix;
+                        pt1[1] = y + iy;
+                        mCanvasMatrix.transform(pt1, 0, pt2, 0, 1);
+
+                        // handle the local matrix
+                        pt1[0] = pt2[0] - mX;
+                        pt1[1] = pt2[1] - mY;
+                        mLocalMatrix.transform(pt1, 0, pt2, 0, 1);
+
+                        float _x = pt2[0];
+                        float _y = pt2[1];
+                        float distance = (float) Math.sqrt(_x * _x + _y * _y);
+
+                        data[index++] = getGradientColor(distance / mRadius);
+                    }
+                }
+
+                image.setRGB(0 /*startX*/, 0 /*startY*/, w, h, data, 0 /*offset*/, w /*scansize*/);
+
+                return image.getRaster();
+            }
+
+        }
+    }
+
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Rasterizer_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Rasterizer_Delegate.java
new file mode 100644
index 0000000..2812b6b
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/Rasterizer_Delegate.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+/**
+ * Delegate implementing the native methods of android.graphics.Rasterizer
+ *
+ * Through the layoutlib_create tool, the original native methods of Rasterizer have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original Rasterizer class.
+ *
+ * This also serve as a base class for all Rasterizer delegate classes.
+ *
+ * @see DelegateManager
+ *
+ */
+public abstract class Rasterizer_Delegate {
+
+    // ---- delegate manager ----
+    protected static final DelegateManager<Rasterizer_Delegate> sManager =
+            new DelegateManager<Rasterizer_Delegate>(Rasterizer_Delegate.class);
+
+    // ---- delegate helper data ----
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    public static Rasterizer_Delegate getDelegate(int nativeShader) {
+        return sManager.getDelegate(nativeShader);
+    }
+
+    public abstract boolean isSupported();
+    public abstract String getSupportMessage();
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static void finalizer(int native_instance) {
+        sManager.removeJavaReferenceFor(native_instance);
+    }
+
+    // ---- Private delegate/helper methods ----
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Region_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Region_Delegate.java
new file mode 100644
index 0000000..b0ee5c2
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/Region_Delegate.java
@@ -0,0 +1,474 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import android.os.Parcel;
+
+import java.awt.Rectangle;
+import java.awt.Shape;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Area;
+import java.awt.geom.Rectangle2D;
+
+/**
+ * Delegate implementing the native methods of android.graphics.Region
+ *
+ * Through the layoutlib_create tool, the original native methods of Region have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original Region class.
+ *
+ * This also serve as a base class for all Region delegate classes.
+ *
+ * @see DelegateManager
+ *
+ */
+public class Region_Delegate {
+
+    // ---- delegate manager ----
+    protected static final DelegateManager<Region_Delegate> sManager =
+            new DelegateManager<Region_Delegate>(Region_Delegate.class);
+
+    // ---- delegate helper data ----
+
+    // ---- delegate data ----
+    private Area mArea = new Area();
+
+    // ---- Public Helper methods ----
+
+    public static Region_Delegate getDelegate(int nativeShader) {
+        return sManager.getDelegate(nativeShader);
+    }
+
+    public Area getJavaArea() {
+        return mArea;
+    }
+
+    /**
+     * Combines two {@link Shape} into another one (actually an {@link Area}), according
+     * to the given {@link Region.Op}.
+     *
+     * If the Op is not one that combines two shapes, then this return null
+     *
+     * @param shape1 the firt shape to combine which can be null if there's no original clip.
+     * @param shape2 the 2nd shape to combine
+     * @param regionOp the operande for the combine
+     * @return a new area or null.
+     */
+    public static Area combineShapes(Shape shape1, Shape shape2, int regionOp) {
+        if (regionOp == Region.Op.DIFFERENCE.nativeInt) {
+            // if shape1 is null (empty), then the result is null.
+            if (shape1 == null) {
+                return null;
+            }
+
+            // result is always a new area.
+            Area result = new Area(shape1);
+            result.subtract(shape2 instanceof Area ? (Area) shape2 : new Area(shape2));
+            return result;
+
+        } else if (regionOp == Region.Op.INTERSECT.nativeInt) {
+            // if shape1 is null, then the result is simply shape2.
+            if (shape1 == null) {
+                return new Area(shape2);
+            }
+
+            // result is always a new area.
+            Area result = new Area(shape1);
+            result.intersect(shape2 instanceof Area ? (Area) shape2 : new Area(shape2));
+            return result;
+
+        } else if (regionOp == Region.Op.UNION.nativeInt) {
+            // if shape1 is null, then the result is simply shape2.
+            if (shape1 == null) {
+                return new Area(shape2);
+            }
+
+            // result is always a new area.
+            Area result = new Area(shape1);
+            result.add(shape2 instanceof Area ? (Area) shape2 : new Area(shape2));
+            return result;
+
+        } else if (regionOp == Region.Op.XOR.nativeInt) {
+            // if shape1 is null, then the result is simply shape2
+            if (shape1 == null) {
+                return new Area(shape2);
+            }
+
+            // result is always a new area.
+            Area result = new Area(shape1);
+            result.exclusiveOr(shape2 instanceof Area ? (Area) shape2 : new Area(shape2));
+            return result;
+
+        } else if (regionOp == Region.Op.REVERSE_DIFFERENCE.nativeInt) {
+            // result is always a new area.
+            Area result = new Area(shape2);
+
+            if (shape1 != null) {
+                result.subtract(shape1 instanceof Area ? (Area) shape1 : new Area(shape1));
+            }
+
+            return result;
+        }
+
+        return null;
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static boolean isEmpty(Region thisRegion) {
+        Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
+        if (regionDelegate == null) {
+            return true;
+        }
+
+        return regionDelegate.mArea.isEmpty();
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean isRect(Region thisRegion) {
+        Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
+        if (regionDelegate == null) {
+            return true;
+        }
+
+        return regionDelegate.mArea.isRectangular();
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean isComplex(Region thisRegion) {
+        Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
+        if (regionDelegate == null) {
+            return true;
+        }
+
+        return regionDelegate.mArea.isSingular() == false;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean contains(Region thisRegion, int x, int y) {
+        Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
+        if (regionDelegate == null) {
+            return false;
+        }
+
+        return regionDelegate.mArea.contains(x, y);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean quickContains(Region thisRegion,
+            int left, int top, int right, int bottom) {
+        Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
+        if (regionDelegate == null) {
+            return false;
+        }
+
+        return regionDelegate.mArea.isRectangular() &&
+                regionDelegate.mArea.contains(left, top, right - left, bottom - top);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean quickReject(Region thisRegion,
+            int left, int top, int right, int bottom) {
+        Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
+        if (regionDelegate == null) {
+            return false;
+        }
+
+        return regionDelegate.mArea.isEmpty() ||
+                regionDelegate.mArea.intersects(left, top, right - left, bottom - top) == false;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean quickReject(Region thisRegion, Region rgn) {
+        Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
+        if (regionDelegate == null) {
+            return false;
+        }
+
+        Region_Delegate targetRegionDelegate = sManager.getDelegate(rgn.mNativeRegion);
+        if (targetRegionDelegate == null) {
+            return false;
+        }
+
+        return regionDelegate.mArea.isEmpty() ||
+                regionDelegate.mArea.getBounds().intersects(
+                        targetRegionDelegate.mArea.getBounds()) == false;
+
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void translate(Region thisRegion, int dx, int dy, Region dst) {
+        Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
+        if (regionDelegate == null) {
+            return;
+        }
+
+        Region_Delegate targetRegionDelegate = sManager.getDelegate(dst.mNativeRegion);
+        if (targetRegionDelegate == null) {
+            return;
+        }
+
+        if (regionDelegate.mArea.isEmpty()) {
+            targetRegionDelegate.mArea = new Area();
+        } else {
+            targetRegionDelegate.mArea = new Area(regionDelegate.mArea);
+            AffineTransform mtx = new AffineTransform();
+            mtx.translate(dx, dy);
+            targetRegionDelegate.mArea.transform(mtx);
+        }
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void scale(Region thisRegion, float scale, Region dst) {
+        Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
+        if (regionDelegate == null) {
+            return;
+        }
+
+        Region_Delegate targetRegionDelegate = sManager.getDelegate(dst.mNativeRegion);
+        if (targetRegionDelegate == null) {
+            return;
+        }
+
+        if (regionDelegate.mArea.isEmpty()) {
+            targetRegionDelegate.mArea = new Area();
+        } else {
+            targetRegionDelegate.mArea = new Area(regionDelegate.mArea);
+            AffineTransform mtx = new AffineTransform();
+            mtx.scale(scale, scale);
+            targetRegionDelegate.mArea.transform(mtx);
+        }
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeConstructor() {
+        Region_Delegate newDelegate = new Region_Delegate();
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeDestructor(int native_region) {
+        sManager.removeJavaReferenceFor(native_region);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean nativeSetRegion(int native_dst, int native_src) {
+        Region_Delegate dstRegion = sManager.getDelegate(native_dst);
+        if (dstRegion == null) {
+            return true;
+        }
+
+        Region_Delegate srcRegion = sManager.getDelegate(native_src);
+        if (srcRegion == null) {
+            return true;
+        }
+
+        dstRegion.mArea.reset();
+        dstRegion.mArea.add(srcRegion.mArea);
+
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean nativeSetRect(int native_dst,
+            int left, int top, int right, int bottom) {
+        Region_Delegate dstRegion = sManager.getDelegate(native_dst);
+        if (dstRegion == null) {
+            return true;
+        }
+
+        dstRegion.mArea = new Area(new Rectangle2D.Float(left, top, right - left, bottom - top));
+        return dstRegion.mArea.getBounds().isEmpty() == false;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean nativeSetPath(int native_dst, int native_path, int native_clip) {
+        Region_Delegate dstRegion = sManager.getDelegate(native_dst);
+        if (dstRegion == null) {
+            return true;
+        }
+
+        Path_Delegate path = Path_Delegate.getDelegate(native_path);
+        if (path == null) {
+            return true;
+        }
+
+        dstRegion.mArea = new Area(path.getJavaShape());
+
+        Region_Delegate clip = sManager.getDelegate(native_clip);
+        if (clip != null) {
+            dstRegion.mArea.subtract(clip.getJavaArea());
+        }
+
+        return dstRegion.mArea.getBounds().isEmpty() == false;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean nativeGetBounds(int native_region, Rect rect) {
+        Region_Delegate region = sManager.getDelegate(native_region);
+        if (region == null) {
+            return true;
+        }
+
+        Rectangle bounds = region.mArea.getBounds();
+        if (bounds.isEmpty()) {
+            rect.left = rect.top = rect.right = rect.bottom = 0;
+            return false;
+        }
+
+        rect.left = bounds.x;
+        rect.top = bounds.y;
+        rect.right = bounds.x + bounds.width;
+        rect.bottom = bounds.y + bounds.height;
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean nativeGetBoundaryPath(int native_region, int native_path) {
+        Region_Delegate region = sManager.getDelegate(native_region);
+        if (region == null) {
+            return false;
+        }
+
+        Path_Delegate path = Path_Delegate.getDelegate(native_path);
+        if (path == null) {
+            return false;
+        }
+
+        if (region.mArea.isEmpty()) {
+            path.reset();
+            return false;
+        }
+
+        path.setPathIterator(region.mArea.getPathIterator(new AffineTransform()));
+        return true;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean nativeOp(int native_dst,
+            int left, int top, int right, int bottom, int op) {
+        Region_Delegate region = sManager.getDelegate(native_dst);
+        if (region == null) {
+            return false;
+        }
+
+        region.mArea = combineShapes(region.mArea,
+                new Rectangle2D.Float(left, top, right - left, bottom - top), op);
+
+        assert region.mArea != null;
+        if (region.mArea != null) {
+            region.mArea = new Area();
+        }
+
+        return region.mArea.getBounds().isEmpty() == false;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean nativeOp(int native_dst, Rect rect, int native_region, int op) {
+        Region_Delegate region = sManager.getDelegate(native_dst);
+        if (region == null) {
+            return false;
+        }
+
+        region.mArea = combineShapes(region.mArea,
+                new Rectangle2D.Float(rect.left, rect.top, rect.width(), rect.height()), op);
+
+        assert region.mArea != null;
+        if (region.mArea != null) {
+            region.mArea = new Area();
+        }
+
+        return region.mArea.getBounds().isEmpty() == false;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean nativeOp(int native_dst,
+            int native_region1, int native_region2, int op) {
+        Region_Delegate dstRegion = sManager.getDelegate(native_dst);
+        if (dstRegion == null) {
+            return true;
+        }
+
+        Region_Delegate region1 = sManager.getDelegate(native_region1);
+        if (region1 == null) {
+            return false;
+        }
+
+        Region_Delegate region2 = sManager.getDelegate(native_region2);
+        if (region2 == null) {
+            return false;
+        }
+
+        dstRegion.mArea = combineShapes(region1.mArea, region2.mArea, op);
+
+        assert dstRegion.mArea != null;
+        if (dstRegion.mArea != null) {
+            dstRegion.mArea = new Area();
+        }
+
+        return dstRegion.mArea.getBounds().isEmpty() == false;
+
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeCreateFromParcel(Parcel p) {
+        // This is only called by Region.CREATOR (Parcelable.Creator<Region>), which is only
+        // used during aidl call so really this should not be called.
+        Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
+                "AIDL is not suppored, and therefore Regions cannot be created from parcels.",
+                null /*data*/);
+        return 0;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean nativeWriteToParcel(int native_region,
+                                                      Parcel p) {
+        // This is only called when sending a region through aidl, so really this should not
+        // be called.
+        Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
+                "AIDL is not suppored, and therefore Regions cannot be written to parcels.",
+                null /*data*/);
+        return false;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean nativeEquals(int native_r1, int native_r2) {
+        Region_Delegate region1 = sManager.getDelegate(native_r1);
+        if (region1 == null) {
+            return false;
+        }
+
+        Region_Delegate region2 = sManager.getDelegate(native_r2);
+        if (region2 == null) {
+            return false;
+        }
+
+        return region1.mArea.equals(region2.mArea);
+    }
+
+    // ---- Private delegate/helper methods ----
+
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Shader.java b/tools/layoutlib/bridge/src/android/graphics/Shader.java
deleted file mode 100644
index 0cc5940..0000000
--- a/tools/layoutlib/bridge/src/android/graphics/Shader.java
+++ /dev/null
@@ -1,83 +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.graphics;
-
-
-
-/**
- * Shader is the based class for objects that return horizontal spans of colors
- * during drawing. A subclass of Shader is installed in a Paint calling
- * paint.setShader(shader). After that any object (other than a bitmap) that is
- * drawn with that paint will get its color(s) from the shader.
- */
-public abstract class Shader {
-
-    private final Matrix mMatrix = new Matrix();
-
-    public enum TileMode {
-        /**
-         * replicate the edge color if the shader draws outside of its
-         * original bounds
-         */
-        CLAMP   (0),
-        /**
-         * repeat the shader's image horizontally and vertically
-         */
-        REPEAT  (1),
-        /**
-         * repeat the shader's image horizontally and vertically, alternating
-         * mirror images so that adjacent images always seam
-         */
-        MIRROR  (2);
-
-        TileMode(int nativeInt) {
-            this.nativeInt = nativeInt;
-        }
-        final int nativeInt;
-    }
-
-    /**
-     * Return true if the shader has a non-identity local matrix.
-     * @param localM If not null, it is set to the shader's local matrix.
-     * @return true if the shader has a non-identity local matrix
-     */
-    public boolean getLocalMatrix(Matrix localM) {
-        if (localM != null) {
-            localM.set(mMatrix);
-        }
-
-        return !mMatrix.isIdentity();
-    }
-
-    /**
-     * Set the shader's local matrix. Passing null will reset the shader's
-     * matrix to identity
-     * @param localM The shader's new local matrix, or null to specify identity
-     */
-    public void setLocalMatrix(Matrix localM) {
-        if (localM != null) {
-            mMatrix.set(localM);
-        } else {
-            mMatrix.reset();
-        }
-    }
-
-    /**
-     * Returns a java.awt.Paint object matching this shader.
-     */
-    abstract java.awt.Paint getJavaPaint();
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Shader_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Shader_Delegate.java
new file mode 100644
index 0000000..472fc80
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/Shader_Delegate.java
@@ -0,0 +1,137 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import android.graphics.Shader.TileMode;
+
+/**
+ * Delegate implementing the native methods of android.graphics.Shader
+ *
+ * Through the layoutlib_create tool, the original native methods of Shader have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original Shader class.
+ *
+ * This also serve as a base class for all Shader delegate classes.
+ *
+ * @see DelegateManager
+ *
+ */
+public abstract class Shader_Delegate {
+
+    // ---- delegate manager ----
+    protected static final DelegateManager<Shader_Delegate> sManager =
+            new DelegateManager<Shader_Delegate>(Shader_Delegate.class);
+
+    // ---- delegate helper data ----
+
+    // ---- delegate data ----
+    private Matrix_Delegate mLocalMatrix = null;
+
+    // ---- Public Helper methods ----
+
+    public static Shader_Delegate getDelegate(int nativeShader) {
+        return sManager.getDelegate(nativeShader);
+    }
+
+    /**
+     * Returns the {@link TileMode} matching the given int.
+     * @param tileMode the tile mode int value
+     * @return the TileMode enum.
+     */
+    public static TileMode getTileMode(int tileMode) {
+        for (TileMode tm : TileMode.values()) {
+            if (tm.nativeInt == tileMode) {
+                return tm;
+            }
+        }
+
+        assert false;
+        return TileMode.CLAMP;
+    }
+
+    public abstract java.awt.Paint getJavaPaint();
+    public abstract boolean isSupported();
+    public abstract String getSupportMessage();
+
+    public boolean isValid() {
+        if (mLocalMatrix != null && mLocalMatrix.getAffineTransform().getDeterminant() == 0) {
+            return false;
+        }
+
+        return true;
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeDestructor(int native_shader) {
+        sManager.removeJavaReferenceFor(native_shader);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean nativeGetLocalMatrix(int native_shader, int matrix_instance) {
+        // get the delegate from the native int.
+        Shader_Delegate shaderDelegate = sManager.getDelegate(native_shader);
+        if (shaderDelegate == null) {
+            return false;
+        }
+
+        // get the (optional) out matrix.
+        Matrix_Delegate outMatrixDelegate = Matrix_Delegate.getDelegate(matrix_instance);
+
+        if (shaderDelegate.mLocalMatrix == null || shaderDelegate.mLocalMatrix.isIdentity()) {
+            if (outMatrixDelegate != null) {
+                outMatrixDelegate.reset();
+            }
+            return false;
+        }
+
+        if (outMatrixDelegate != null) {
+            outMatrixDelegate.set(shaderDelegate.mLocalMatrix);
+        }
+
+        return true;
+    }
+
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeSetLocalMatrix(int native_shader, int matrix_instance) {
+        // get the delegate from the native int.
+        Shader_Delegate shaderDelegate = sManager.getDelegate(native_shader);
+        if (shaderDelegate == null) {
+            return;
+        }
+
+        shaderDelegate.mLocalMatrix = Matrix_Delegate.getDelegate(matrix_instance);
+    }
+
+    // ---- Private delegate/helper methods ----
+
+    protected java.awt.geom.AffineTransform getLocalMatrix() {
+        if (mLocalMatrix != null) {
+            return mLocalMatrix.getAffineTransform();
+        }
+
+        return new java.awt.geom.AffineTransform();
+    }
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/SumPathEffect_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/SumPathEffect_Delegate.java
new file mode 100644
index 0000000..410df0c
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/SumPathEffect_Delegate.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import java.awt.Stroke;
+
+/**
+ * Delegate implementing the native methods of android.graphics.SumPathEffect
+ *
+ * Through the layoutlib_create tool, the original native methods of SumPathEffect have been
+ * replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original SumPathEffect class.
+ *
+ * Because this extends {@link PathEffect_Delegate}, there's no need to use a {@link DelegateManager},
+ * as all the Shader classes will be added to the manager owned by {@link PathEffect_Delegate}.
+ *
+ * @see PathEffect_Delegate
+ *
+ */
+public class SumPathEffect_Delegate extends PathEffect_Delegate {
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public Stroke getStroke(Paint_Delegate paint) {
+        // FIXME
+        return null;
+    }
+
+    @Override
+    public boolean isSupported() {
+        return false;
+    }
+
+    @Override
+    public String getSupportMessage() {
+        return "Sum Path Effects are not supported in Layout Preview mode.";
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeCreate(int first, int second) {
+        SumPathEffect_Delegate newDelegate = new SumPathEffect_Delegate();
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    // ---- Private delegate/helper methods ----
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/SweepGradient.java b/tools/layoutlib/bridge/src/android/graphics/SweepGradient.java
deleted file mode 100644
index 87036ed..0000000
--- a/tools/layoutlib/bridge/src/android/graphics/SweepGradient.java
+++ /dev/null
@@ -1,140 +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.graphics;
-
-public class SweepGradient extends GradientShader {
-
-    private SweepGradientPaint mPaint;
-
-    /**
-     * A subclass of Shader that draws a sweep gradient around a center point.
-     *
-     * @param cx       The x-coordinate of the center
-     * @param cy       The y-coordinate of the center
-     * @param colors   The colors to be distributed between around the center.
-     *                 There must be at least 2 colors in the array.
-     * @param positions May be NULL. The relative position of
-     *                 each corresponding color in the colors array, beginning
-     *                 with 0 and ending with 1.0. If the values are not
-     *                 monotonic, the drawing may produce unexpected results.
-     *                 If positions is NULL, then the colors are automatically
-     *                 spaced evenly.
-     */
-    public SweepGradient(float cx, float cy,
-                         int colors[], float positions[]) {
-        super(colors, positions);
-
-        mPaint = new SweepGradientPaint(cx, cy, mColors, mPositions);
-    }
-
-    /**
-     * A subclass of Shader that draws a sweep gradient around a center point.
-     *
-     * @param cx       The x-coordinate of the center
-     * @param cy       The y-coordinate of the center
-     * @param color0   The color to use at the start of the sweep
-     * @param color1   The color to use at the end of the sweep
-     */
-    public SweepGradient(float cx, float cy, int color0, int color1) {
-        this(cx, cy, new int[] { color0, color1}, null /*positions*/);
-    }
-
-    @Override
-    java.awt.Paint getJavaPaint() {
-        return mPaint;
-    }
-
-    private static class SweepGradientPaint extends GradientPaint {
-
-        private final float mCx;
-        private final float mCy;
-
-        public SweepGradientPaint(float cx, float cy, int[] colors, float[] positions) {
-            super(colors, positions, null /*tileMode*/);
-            mCx = cx;
-            mCy = cy;
-        }
-
-        public java.awt.PaintContext createContext(
-                java.awt.image.ColorModel     colorModel,
-                java.awt.Rectangle            deviceBounds,
-                java.awt.geom.Rectangle2D     userBounds,
-                java.awt.geom.AffineTransform xform,
-                java.awt.RenderingHints       hints) {
-            precomputeGradientColors();
-            return new SweepGradientPaintContext(colorModel);
-        }
-
-        private class SweepGradientPaintContext implements java.awt.PaintContext {
-
-            private final java.awt.image.ColorModel mColorModel;
-
-            public SweepGradientPaintContext(java.awt.image.ColorModel colorModel) {
-                mColorModel = colorModel;
-            }
-
-            public void dispose() {
-            }
-
-            public java.awt.image.ColorModel getColorModel() {
-                return mColorModel;
-            }
-
-            public java.awt.image.Raster getRaster(int x, int y, int w, int h) {
-                java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(w, h,
-                        java.awt.image.BufferedImage.TYPE_INT_ARGB);
-
-                int[] data = new int[w*h];
-
-                // compute angle from each point to the center, and figure out the distance from
-                // it.
-                int index = 0;
-                for (int iy = 0 ; iy < h ; iy++) {
-                    for (int ix = 0 ; ix < w ; ix++) {
-                        float dx = x + ix - mCx;
-                        float dy = y + iy - mCy;
-                        float angle;
-                        if (dx == 0) {
-                            angle = (float) (dy < 0 ? 3 * Math.PI / 2 : Math.PI / 2);
-                        } else if (dy == 0) {
-                            angle = (float) (dx < 0 ? Math.PI : 0);
-                        } else {
-                            angle = (float) Math.atan(dy / dx);
-                            if (dx > 0) {
-                                if (dy < 0) {
-                                    angle += Math.PI * 2;
-                                }
-                            } else {
-                                angle += Math.PI;
-                            }
-                        }
-
-                        // convert to 0-1. value and get color
-                        data[index++] = getGradientColor((float) (angle / (2 * Math.PI)));
-                    }
-                }
-
-                image.setRGB(0 /*startX*/, 0 /*startY*/, w, h, data, 0 /*offset*/, w /*scansize*/);
-
-                return image.getRaster();
-            }
-
-        }
-    }
-
-}
-
diff --git a/tools/layoutlib/bridge/src/android/graphics/SweepGradient_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/SweepGradient_Delegate.java
new file mode 100644
index 0000000..f70f9cf
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/SweepGradient_Delegate.java
@@ -0,0 +1,204 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+/**
+ * Delegate implementing the native methods of android.graphics.SweepGradient
+ *
+ * Through the layoutlib_create tool, the original native methods of SweepGradient have been
+ * replaced by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original SweepGradient class.
+ *
+ * Because this extends {@link Shader_Delegate}, there's no need to use a {@link DelegateManager},
+ * as all the Shader classes will be added to the manager owned by {@link Shader_Delegate}.
+ *
+ * @see Shader_Delegate
+ *
+ */
+public class SweepGradient_Delegate extends Gradient_Delegate {
+
+    // ---- delegate data ----
+    private java.awt.Paint mJavaPaint;
+
+    // ---- Public Helper methods ----
+
+    @Override
+    public java.awt.Paint getJavaPaint() {
+        return mJavaPaint;
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeCreate1(float x, float y, int colors[], float positions[]) {
+        SweepGradient_Delegate newDelegate = new SweepGradient_Delegate(x, y, colors, positions);
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeCreate2(float x, float y, int color0, int color1) {
+        return nativeCreate1(x, y, new int[] { color0, color1 }, null /*positions*/);
+    }
+
+    // ---- Private delegate/helper methods ----
+
+    /**
+     * A subclass of Shader that draws a sweep gradient around a center point.
+     *
+     * @param cx       The x-coordinate of the center
+     * @param cy       The y-coordinate of the center
+     * @param colors   The colors to be distributed between around the center.
+     *                 There must be at least 2 colors in the array.
+     * @param positions May be NULL. The relative position of
+     *                 each corresponding color in the colors array, beginning
+     *                 with 0 and ending with 1.0. If the values are not
+     *                 monotonic, the drawing may produce unexpected results.
+     *                 If positions is NULL, then the colors are automatically
+     *                 spaced evenly.
+     */
+    private SweepGradient_Delegate(float cx, float cy,
+                         int colors[], float positions[]) {
+        super(colors, positions);
+        mJavaPaint = new SweepGradientPaint(cx, cy, mColors, mPositions);
+    }
+
+    private class SweepGradientPaint extends GradientPaint {
+
+        private final float mCx;
+        private final float mCy;
+
+        public SweepGradientPaint(float cx, float cy, int[] colors,
+                float[] positions) {
+            super(colors, positions, null /*tileMode*/);
+            mCx = cx;
+            mCy = cy;
+        }
+
+        public java.awt.PaintContext createContext(
+                java.awt.image.ColorModel     colorModel,
+                java.awt.Rectangle            deviceBounds,
+                java.awt.geom.Rectangle2D     userBounds,
+                java.awt.geom.AffineTransform xform,
+                java.awt.RenderingHints       hints) {
+            precomputeGradientColors();
+
+            java.awt.geom.AffineTransform canvasMatrix;
+            try {
+                canvasMatrix = xform.createInverse();
+            } catch (java.awt.geom.NoninvertibleTransformException e) {
+                Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
+                        "Unable to inverse matrix in SweepGradient", e, null /*data*/);
+                canvasMatrix = new java.awt.geom.AffineTransform();
+            }
+
+            java.awt.geom.AffineTransform localMatrix = getLocalMatrix();
+            try {
+                localMatrix = localMatrix.createInverse();
+            } catch (java.awt.geom.NoninvertibleTransformException e) {
+                Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
+                        "Unable to inverse matrix in SweepGradient", e, null /*data*/);
+                localMatrix = new java.awt.geom.AffineTransform();
+            }
+
+            return new SweepGradientPaintContext(canvasMatrix, localMatrix, colorModel);
+        }
+
+        private class SweepGradientPaintContext implements java.awt.PaintContext {
+
+            private final java.awt.geom.AffineTransform mCanvasMatrix;
+            private final java.awt.geom.AffineTransform mLocalMatrix;
+            private final java.awt.image.ColorModel mColorModel;
+
+            public SweepGradientPaintContext(
+                    java.awt.geom.AffineTransform canvasMatrix,
+                    java.awt.geom.AffineTransform localMatrix,
+                    java.awt.image.ColorModel colorModel) {
+                mCanvasMatrix = canvasMatrix;
+                mLocalMatrix = localMatrix;
+                mColorModel = colorModel;
+            }
+
+            public void dispose() {
+            }
+
+            public java.awt.image.ColorModel getColorModel() {
+                return mColorModel;
+            }
+
+            public java.awt.image.Raster getRaster(int x, int y, int w, int h) {
+                java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(w, h,
+                        java.awt.image.BufferedImage.TYPE_INT_ARGB);
+
+                int[] data = new int[w*h];
+
+                // compute angle from each point to the center, and figure out the distance from
+                // it.
+                int index = 0;
+                float[] pt1 = new float[2];
+                float[] pt2 = new float[2];
+                for (int iy = 0 ; iy < h ; iy++) {
+                    for (int ix = 0 ; ix < w ; ix++) {
+                        // handle the canvas transform
+                        pt1[0] = x + ix;
+                        pt1[1] = y + iy;
+                        mCanvasMatrix.transform(pt1, 0, pt2, 0, 1);
+
+                        // handle the local matrix
+                        pt1[0] = pt2[0] - mCx;
+                        pt1[1] = pt2[1] - mCy;
+                        mLocalMatrix.transform(pt1, 0, pt2, 0, 1);
+
+                        float dx = pt2[0];
+                        float dy = pt2[1];
+
+                        float angle;
+                        if (dx == 0) {
+                            angle = (float) (dy < 0 ? 3 * Math.PI / 2 : Math.PI / 2);
+                        } else if (dy == 0) {
+                            angle = (float) (dx < 0 ? Math.PI : 0);
+                        } else {
+                            angle = (float) Math.atan(dy / dx);
+                            if (dx > 0) {
+                                if (dy < 0) {
+                                    angle += Math.PI * 2;
+                                }
+                            } else {
+                                angle += Math.PI;
+                            }
+                        }
+
+                        // convert to 0-1. value and get color
+                        data[index++] = getGradientColor((float) (angle / (2 * Math.PI)));
+                    }
+                }
+
+                image.setRGB(0 /*startX*/, 0 /*startY*/, w, h, data, 0 /*offset*/, w /*scansize*/);
+
+                return image.getRaster();
+            }
+
+        }
+    }
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Typeface.java b/tools/layoutlib/bridge/src/android/graphics/Typeface.java
deleted file mode 100644
index af3adb5..0000000
--- a/tools/layoutlib/bridge/src/android/graphics/Typeface.java
+++ /dev/null
@@ -1,190 +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.graphics;
-
-import com.android.layoutlib.bridge.FontLoader;
-
-import android.content.res.AssetManager;
-
-import java.awt.Font;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * Re-implementation of Typeface over java.awt
- */
-public class Typeface {
-    private static final String DEFAULT_FAMILY = "sans-serif";
-    private static final int[] styleBuffer = new int[1];
-
-    /** The default NORMAL typeface object */
-    public static Typeface DEFAULT;
-    /**
-     * The default BOLD typeface object. Note: this may be not actually be
-     * bold, depending on what fonts are installed. Call getStyle() to know
-     * for sure.
-     */
-    public static Typeface DEFAULT_BOLD;
-    /** The NORMAL style of the default sans serif typeface. */
-    public static Typeface SANS_SERIF;
-    /** The NORMAL style of the default serif typeface. */
-    public static Typeface SERIF;
-    /** The NORMAL style of the default monospace typeface. */
-    public static Typeface MONOSPACE;
-
-    private static Typeface[] sDefaults;
-    private static FontLoader mFontLoader;
-
-    private final int mStyle;
-    private final List<Font> mFonts;
-    private final String mFamily;
-
-    // Style
-    public static final int NORMAL = _Original_Typeface.NORMAL;
-    public static final int BOLD = _Original_Typeface.BOLD;
-    public static final int ITALIC = _Original_Typeface.ITALIC;
-    public static final int BOLD_ITALIC = _Original_Typeface.BOLD_ITALIC;
-
-    /**
-     * Returns the underlying {@link Font} objects. The first item in the list is the real
-     * font. Any other items are fallback fonts for characters not found in the first one.
-     */
-    public List<Font> getFonts() {
-        return mFonts;
-    }
-
-    /** Returns the typeface's intrinsic style attributes */
-    public int getStyle() {
-        return mStyle;
-    }
-
-    /** Returns true if getStyle() has the BOLD bit set. */
-    public final boolean isBold() {
-        return (getStyle() & BOLD) != 0;
-    }
-
-    /** Returns true if getStyle() has the ITALIC bit set. */
-    public final boolean isItalic() {
-        return (getStyle() & ITALIC) != 0;
-    }
-
-    /**
-     * Create a typeface object given a family name, and option style information.
-     * If null is passed for the name, then the "default" font will be chosen.
-     * The resulting typeface object can be queried (getStyle()) to discover what
-     * its "real" style characteristics are.
-     *
-     * @param familyName May be null. The name of the font family.
-     * @param style  The style (normal, bold, italic) of the typeface.
-     *               e.g. NORMAL, BOLD, ITALIC, BOLD_ITALIC
-     * @return The best matching typeface.
-     */
-    public static Typeface create(String familyName, int style) {
-        styleBuffer[0] = style;
-        Font font = mFontLoader.getFont(familyName, styleBuffer);
-        if (font != null) {
-            ArrayList<Font> list = new ArrayList<Font>();
-            list.add(font);
-            list.addAll(mFontLoader.getFallBackFonts());
-            return new Typeface(familyName, styleBuffer[0], list);
-        }
-
-        return null;
-    }
-
-    /**
-     * Create a typeface object that best matches the specified existing
-     * typeface and the specified Style. Use this call if you want to pick a new
-     * style from the same family of an existing typeface object. If family is
-     * null, this selects from the default font's family.
-     *
-     * @param family May be null. The name of the existing type face.
-     * @param style  The style (normal, bold, italic) of the typeface.
-     *               e.g. NORMAL, BOLD, ITALIC, BOLD_ITALIC
-     * @return The best matching typeface.
-     */
-    public static Typeface create(Typeface family, int style) {
-        styleBuffer[0] = style;
-        Font font = mFontLoader.getFont(family.mFamily, styleBuffer);
-        if (font != null) {
-            ArrayList<Font> list = new ArrayList<Font>();
-            list.add(font);
-            list.addAll(mFontLoader.getFallBackFonts());
-            return new Typeface(family.mFamily, styleBuffer[0], list);
-        }
-
-        return null;
-    }
-
-    /**
-     * Returns one of the default typeface objects, based on the specified style
-     *
-     * @return the default typeface that corresponds to the style
-     */
-    public static Typeface defaultFromStyle(int style) {
-        return sDefaults[style];
-    }
-
-    /**
-     * Create a new typeface from the specified font data.
-     * @param mgr The application's asset manager
-     * @param path  The file name of the font data in the assets directory
-     * @return The new typeface.
-     */
-    public static Typeface createFromAsset(AssetManager mgr, String path) {
-        return null;
-        //return new Typeface(nativeCreateFromAsset(mgr, path));
-    }
-
-    // don't allow clients to call this directly
-    private Typeface(String family, int style, List<Font> fonts) {
-        mFamily = family;
-        mFonts = Collections.unmodifiableList(fonts);
-        mStyle = style;
-    }
-
-    public static void init(FontLoader fontLoader) {
-        mFontLoader = fontLoader;
-
-        DEFAULT = create(DEFAULT_FAMILY, NORMAL);
-        DEFAULT_BOLD = create(DEFAULT_FAMILY, BOLD);
-        SANS_SERIF = create("sans-serif", NORMAL);
-        SERIF = create("serif", NORMAL);
-        MONOSPACE = create("monospace", NORMAL);
-        sDefaults = new Typeface[] {
-                DEFAULT,
-                DEFAULT_BOLD,
-                create(DEFAULT_FAMILY, ITALIC),
-                create(DEFAULT_FAMILY, BOLD_ITALIC),
-        };
-
-        /*
-        DEFAULT         = create((String)null, 0);
-        DEFAULT_BOLD    = create((String)null, Typeface.BOLD);
-        SANS_SERIF      = create("sans-serif", 0);
-        SERIF           = create("serif", 0);
-        MONOSPACE       = create("monospace", 0);
-
-        sDefaults = new Typeface[] {
-            DEFAULT,
-            DEFAULT_BOLD,
-            create((String)null, Typeface.ITALIC),
-            create((String)null, Typeface.BOLD_ITALIC),
-        };*/
-    }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Typeface_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Typeface_Delegate.java
new file mode 100644
index 0000000..0f084f7
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/Typeface_Delegate.java
@@ -0,0 +1,191 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.layoutlib.bridge.impl.FontLoader;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import android.content.res.AssetManager;
+
+import java.awt.Font;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Delegate implementing the native methods of android.graphics.Typeface
+ *
+ * Through the layoutlib_create tool, the original native methods of Typeface have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original Typeface class.
+ *
+ * @see DelegateManager
+ *
+ */
+public final class Typeface_Delegate {
+
+    // ---- delegate manager ----
+    private static final DelegateManager<Typeface_Delegate> sManager =
+            new DelegateManager<Typeface_Delegate>(Typeface_Delegate.class);
+
+    // ---- delegate helper data ----
+    private static final String DEFAULT_FAMILY = "sans-serif";
+    private static final int[] STYLE_BUFFER = new int[1];
+
+    private static FontLoader sFontLoader;
+    private static final List<Typeface_Delegate> sPostInitDelegate =
+            new ArrayList<Typeface_Delegate>();
+
+    // ---- delegate data ----
+
+    private final String mFamily;
+    private int mStyle;
+    private List<Font> mFonts;
+
+
+    // ---- Public Helper methods ----
+
+    public static synchronized void init(FontLoader fontLoader) {
+        sFontLoader = fontLoader;
+
+        for (Typeface_Delegate delegate : sPostInitDelegate) {
+            delegate.init();
+        }
+        sPostInitDelegate.clear();
+    }
+
+    public static Typeface_Delegate getDelegate(int nativeTypeface) {
+        return sManager.getDelegate(nativeTypeface);
+    }
+
+    public static List<Font> getFonts(Typeface typeface) {
+        return getFonts(typeface.native_instance);
+    }
+
+    public static List<Font> getFonts(int native_int) {
+        Typeface_Delegate delegate = sManager.getDelegate(native_int);
+        if (delegate == null) {
+            return null;
+        }
+
+        return delegate.getFonts();
+    }
+
+    public List<Font> getFonts() {
+        return mFonts;
+    }
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static synchronized int nativeCreate(String familyName, int style) {
+        if (familyName == null) {
+            familyName = DEFAULT_FAMILY;
+        }
+
+        Typeface_Delegate newDelegate = new Typeface_Delegate(familyName, style);
+        if (sFontLoader != null) {
+            newDelegate.init();
+        } else {
+            // font loader has not been initialized yet, add the delegate to a list of delegates
+            // to init when the font loader is initialized.
+            // There won't be any rendering before this happens anyway.
+            sPostInitDelegate.add(newDelegate);
+        }
+
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static synchronized int nativeCreateFromTypeface(int native_instance, int style) {
+        Typeface_Delegate delegate = sManager.getDelegate(native_instance);
+        if (delegate == null) {
+            return 0;
+        }
+
+        Typeface_Delegate newDelegate = new Typeface_Delegate(delegate.mFamily, style);
+        if (sFontLoader != null) {
+            newDelegate.init();
+        } else {
+            // font loader has not been initialized yet, add the delegate to a list of delegates
+            // to init when the font loader is initialized.
+            // There won't be any rendering before this happens anyway.
+            sPostInitDelegate.add(newDelegate);
+        }
+
+        return sManager.addNewDelegate(newDelegate);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static synchronized int nativeCreateFromAsset(AssetManager mgr, String path) {
+        Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
+                "Typeface.createFromAsset() is not supported.", null /*throwable*/, null /*data*/);
+        return 0;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static synchronized int nativeCreateFromFile(String path) {
+        Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
+                "Typeface.createFromFile() is not supported.", null /*throwable*/, null /*data*/);
+        return 0;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void nativeUnref(int native_instance) {
+        sManager.removeJavaReferenceFor(native_instance);
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static int nativeGetStyle(int native_instance) {
+        Typeface_Delegate delegate = sManager.getDelegate(native_instance);
+        if (delegate == null) {
+            return 0;
+        }
+
+        return delegate.mStyle;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static void setGammaForText(float blackGamma, float whiteGamma) {
+        // This is for device testing only: pass
+    }
+
+    // ---- Private delegate/helper methods ----
+
+    private Typeface_Delegate(String family, int style) {
+        mFamily = family;
+        mStyle = style;
+    }
+
+    private void init() {
+        STYLE_BUFFER[0] = mStyle;
+        Font font = sFontLoader.getFont(mFamily, STYLE_BUFFER);
+        if (font != null) {
+            List<Font> list = new ArrayList<Font>();
+            list.add(font);
+            list.addAll(sFontLoader.getFallBackFonts());
+            mFonts = Collections.unmodifiableList(list);
+            mStyle = STYLE_BUFFER[0];
+        }
+    }
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Xfermode_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Xfermode_Delegate.java
new file mode 100644
index 0000000..962d69c
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/Xfermode_Delegate.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.graphics;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import java.awt.Composite;
+
+/**
+ * Delegate implementing the native methods of android.graphics.Xfermode
+ *
+ * Through the layoutlib_create tool, the original native methods of Xfermode have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ * This class behaves like the original native implementation, but in Java, keeping previously
+ * native data into its own objects and mapping them to int that are sent back and forth between
+ * it and the original Xfermode class.
+ *
+ * This also serve as a base class for all Xfermode delegate classes.
+ *
+ * @see DelegateManager
+ *
+ */
+public abstract class Xfermode_Delegate {
+
+    // ---- delegate manager ----
+    protected static final DelegateManager<Xfermode_Delegate> sManager =
+            new DelegateManager<Xfermode_Delegate>(Xfermode_Delegate.class);
+
+    // ---- delegate helper data ----
+
+    // ---- delegate data ----
+
+    // ---- Public Helper methods ----
+
+    public static Xfermode_Delegate getDelegate(int native_instance) {
+        return sManager.getDelegate(native_instance);
+    }
+
+    public abstract Composite getComposite(int alpha);
+    public abstract boolean isSupported();
+    public abstract String getSupportMessage();
+
+
+    // ---- native methods ----
+
+    @LayoutlibDelegate
+    /*package*/ static void finalizer(int native_instance) {
+        sManager.removeJavaReferenceFor(native_instance);
+    }
+
+    // ---- Private delegate/helper methods ----
+
+}
diff --git a/tools/layoutlib/bridge/src/android/os/Build_Delegate.java b/tools/layoutlib/bridge/src/android/os/Build_Delegate.java
new file mode 100644
index 0000000..ff82a5e
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/os/Build_Delegate.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import java.util.Map;
+
+/**
+ * Delegate implementing the native methods of android.os.Build
+ *
+ * Through the layoutlib_create tool, the original native methods of Build have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ * Because it's a stateless class to start with, there's no need to keep a {@link DelegateManager}
+ * around to map int to instance of the delegate.
+ *
+ */
+public class Build_Delegate {
+
+    @LayoutlibDelegate
+    /*package*/ static String getString(String property) {
+        Map<String, String> properties = Bridge.getPlatformProperties();
+        String value = properties.get(property);
+        if (value != null) {
+            return value;
+        }
+
+        return Build.UNKNOWN;
+    }
+
+}
diff --git a/tools/layoutlib/bridge/src/android/os/HandlerThread_Delegate.java b/tools/layoutlib/bridge/src/android/os/HandlerThread_Delegate.java
new file mode 100644
index 0000000..afbe97c0
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/os/HandlerThread_Delegate.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 com.android.layoutlib.bridge.android.BridgeContext;
+import com.android.layoutlib.bridge.impl.RenderAction;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Delegate overriding selected methods of android.os.HandlerThread
+ *
+ * Through the layoutlib_create tool, selected methods of Handler have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ *
+ */
+public class HandlerThread_Delegate {
+
+    private static Map<BridgeContext, List<HandlerThread>> sThreads =
+            new HashMap<BridgeContext, List<HandlerThread>>();
+
+    public static void cleanUp(BridgeContext context) {
+        List<HandlerThread> list = sThreads.get(context);
+        if (list != null) {
+            for (HandlerThread thread : list) {
+                thread.quit();
+            }
+
+            list.clear();
+            sThreads.remove(context);
+        }
+    }
+
+    // -------- Delegate methods
+
+    @LayoutlibDelegate
+    /*package*/ static void run(HandlerThread theThread) {
+        // record the thread so that it can be quit() on clean up.
+        BridgeContext context = RenderAction.getCurrentContext();
+        List<HandlerThread> list = sThreads.get(context);
+        if (list == null) {
+            list = new ArrayList<HandlerThread>();
+            sThreads.put(context, list);
+        }
+
+        list.add(theThread);
+
+        // ---- START DEFAULT IMPLEMENTATION.
+
+        theThread.mTid = Process.myTid();
+        Looper.prepare();
+        synchronized (theThread) {
+            theThread.mLooper = Looper.myLooper();
+            theThread.notifyAll();
+        }
+        Process.setThreadPriority(theThread.mPriority);
+        theThread.onLooperPrepared();
+        Looper.loop();
+        theThread.mTid = -1;
+    }
+}
diff --git a/tools/layoutlib/bridge/src/android/os/Handler_Delegate.java b/tools/layoutlib/bridge/src/android/os/Handler_Delegate.java
new file mode 100644
index 0000000..2152c8a
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/os/Handler_Delegate.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.os;
+
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+
+/**
+ * Delegate overriding selected methods of android.os.Handler
+ *
+ * Through the layoutlib_create tool, selected methods of Handler have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ *
+ */
+public class Handler_Delegate {
+
+    // -------- Delegate methods
+
+    @LayoutlibDelegate
+    /*package*/ static boolean sendMessageAtTime(Handler handler, Message msg, long uptimeMillis) {
+        // get the callback
+        IHandlerCallback callback = sCallbacks.get();
+        if (callback != null) {
+            callback.sendMessageAtTime(handler, msg, uptimeMillis);
+        }
+        return true;
+    }
+
+    // -------- Delegate implementation
+
+    public interface IHandlerCallback {
+        void sendMessageAtTime(Handler handler, Message msg, long uptimeMillis);
+    }
+
+    private final static ThreadLocal<IHandlerCallback> sCallbacks =
+        new ThreadLocal<IHandlerCallback>();
+
+    public static void setCallback(IHandlerCallback callback) {
+        sCallbacks.set(callback);
+    }
+
+}
diff --git a/tools/layoutlib/bridge/src/android/os/SystemClock_Delegate.java b/tools/layoutlib/bridge/src/android/os/SystemClock_Delegate.java
new file mode 100644
index 0000000..63711a7
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/os/SystemClock_Delegate.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.os;
+
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+/**
+ * Delegate implementing the native methods of android.os.SystemClock
+ *
+ * Through the layoutlib_create tool, the original native methods of SystemClock have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ * Because it's a stateless class to start with, there's no need to keep a {@link DelegateManager}
+ * around to map int to instance of the delegate.
+ *
+ */
+public class SystemClock_Delegate {
+    private static long sBootTime = System.currentTimeMillis();
+
+    @LayoutlibDelegate
+    /*package*/ static boolean setCurrentTimeMillis(long millis) {
+        return true;
+    }
+
+    /**
+     * Returns milliseconds since boot, not counting time spent in deep sleep.
+     * <b>Note:</b> This value may get reset occasionally (before it would
+     * otherwise wrap around).
+     *
+     * @return milliseconds of non-sleep uptime since boot.
+     */
+    @LayoutlibDelegate
+    /*package*/ static long uptimeMillis() {
+        return System.currentTimeMillis() - sBootTime;
+    }
+
+    /**
+     * Returns milliseconds since boot, including time spent in sleep.
+     *
+     * @return elapsed milliseconds since boot.
+     */
+    @LayoutlibDelegate
+    /*package*/ static long elapsedRealtime() {
+        return System.currentTimeMillis() - sBootTime;
+    }
+
+    /**
+     * Returns milliseconds running in the current thread.
+     *
+     * @return elapsed milliseconds in the thread
+     */
+    @LayoutlibDelegate
+    /*package*/ static long currentThreadTimeMillis() {
+        return System.currentTimeMillis();
+    }
+}
diff --git a/tools/layoutlib/bridge/src/android/util/FloatMath.java b/tools/layoutlib/bridge/src/android/util/FloatMath_Delegate.java
similarity index 67%
rename from tools/layoutlib/bridge/src/android/util/FloatMath.java
rename to tools/layoutlib/bridge/src/android/util/FloatMath_Delegate.java
index aae44f2..1df78c2 100644
--- a/tools/layoutlib/bridge/src/android/util/FloatMath.java
+++ b/tools/layoutlib/bridge/src/android/util/FloatMath_Delegate.java
@@ -16,20 +16,23 @@
 
 package android.util;
 
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
 /**
- * Reimplements _Original_FloatMath with the standard libraries.
- * 
- * Math routines similar to those found in {@link java.lang.Math}. Performs
- * computations on {@code float} values directly without incurring the overhead
- * of conversions to and from {@code double}.
+ * Delegate implementing the native methods of android.util.FloatMath
  *
- * <p>On one platform, {@code FloatMath.sqrt(100)} executes in one third of the
- * time required by {@code java.lang.Math.sqrt(100)}.</p>
+ * Through the layoutlib_create tool, the original native methods of FloatMath have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ * Because it's a stateless class to start with, there's no need to keep a {@link DelegateManager}
+ * around to map int to instance of the delegate.
+ *
  */
-public class FloatMath {
+/*package*/ final class FloatMath_Delegate {
 
     /** Prevents instantiation. */
-    private FloatMath() {}
+    private FloatMath_Delegate() {}
 
     /**
      * Returns the float conversion of the most positive (i.e. closest to
@@ -38,7 +41,8 @@
      * @param value to be converted
      * @return the floor of value
      */
-    public static float floor(float value) {
+    @LayoutlibDelegate
+    /*package*/ static float floor(float value) {
         return (float)Math.floor(value);
     }
 
@@ -49,7 +53,8 @@
      * @param value to be converted
      * @return the ceiling of value
      */
-    public static float ceil(float value) {
+    @LayoutlibDelegate
+    /*package*/ static float ceil(float value) {
         return (float)Math.ceil(value);
     }
 
@@ -59,7 +64,8 @@
      * @param angle to compute the cosine of, in radians
      * @return the sine of angle
      */
-    public static  float sin(float angle) {
+    @LayoutlibDelegate
+    /*package*/ static  float sin(float angle) {
         return (float)Math.sin(angle);
     }
 
@@ -69,7 +75,8 @@
      * @param angle to compute the cosine of, in radians
      * @return the cosine of angle
      */
-    public static float cos(float angle) {
+    @LayoutlibDelegate
+    /*package*/ static float cos(float angle) {
         return (float)Math.cos(angle);
     }
 
@@ -80,7 +87,8 @@
      * @param value to compute sqrt of
      * @return the square root of value
      */
-    public static float sqrt(float value) {
+    @LayoutlibDelegate
+    /*package*/ static float sqrt(float value) {
         return (float)Math.sqrt(value);
     }
 }
diff --git a/tools/layoutlib/bridge/src/android/view/LayoutInflater_Delegate.java b/tools/layoutlib/bridge/src/android/view/LayoutInflater_Delegate.java
new file mode 100644
index 0000000..ea7242c
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/view/LayoutInflater_Delegate.java
@@ -0,0 +1,179 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.view;
+
+import com.android.layoutlib.bridge.android.BridgeInflater;
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+
+import android.content.res.TypedArray;
+import android.content.res.XmlResourceParser;
+import android.util.AttributeSet;
+import android.util.Xml;
+
+import java.io.IOException;
+
+/**
+ * Delegate used to provide new implementation of a select few methods of {@link LayoutInflater}
+ *
+ * Through the layoutlib_create tool, the original  methods of LayoutInflater have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ * Generally we don't want to copy-paste a huge method like that just for one small features,
+ * but because this is done after this platform is final and the next version (Honeycomb) has a
+ * better mechanism (or slightly less copy-paste), maintenance of this duplicated code is not
+ * a problem.
+ *
+ */
+public class LayoutInflater_Delegate {
+
+    public static boolean sIsInInclude = false;
+
+    @LayoutlibDelegate
+    /*package*/ static void parseInclude(LayoutInflater thisInflater,
+            XmlPullParser parser, View parent, AttributeSet attrs)
+            throws XmlPullParserException, IOException {
+
+        int type;
+
+        if (parent instanceof ViewGroup) {
+            final int layout = attrs.getAttributeResourceValue(null, "layout", 0);
+            if (layout == 0) {
+                final String value = attrs.getAttributeValue(null, "layout");
+                if (value == null) {
+                    throw new InflateException("You must specifiy a layout in the"
+                            + " include tag: <include layout=\"@layout/layoutID\" />");
+                } else {
+                    throw new InflateException("You must specifiy a valid layout "
+                            + "reference. The layout ID " + value + " is not valid.");
+                }
+            } else {
+                final XmlResourceParser childParser =
+                    thisInflater.getContext().getResources().getLayout(layout);
+
+                try {
+                    final AttributeSet childAttrs = Xml.asAttributeSet(childParser);
+
+                    while ((type = childParser.next()) != XmlPullParser.START_TAG &&
+                            type != XmlPullParser.END_DOCUMENT) {
+                        // Empty.
+                    }
+
+                    if (type != XmlPullParser.START_TAG) {
+                        throw new InflateException(childParser.getPositionDescription() +
+                                ": No start tag found!");
+                    }
+
+                    final String childName = childParser.getName();
+
+                    if (LayoutInflater.TAG_MERGE.equals(childName)) {
+                        // ---- START MODIFICATIONS ----
+                        if (thisInflater instanceof BridgeInflater) {
+                            ((BridgeInflater) thisInflater).setIsInMerge(true);
+                        }
+                        // ---- END MODIFICATIONS ----
+
+                        // Inflate all children.
+                        thisInflater.rInflate(childParser, parent, childAttrs);
+
+                        // ---- START MODIFICATIONS ----
+                        if (thisInflater instanceof BridgeInflater) {
+                            ((BridgeInflater) thisInflater).setIsInMerge(false);
+                        }
+                        // ---- END MODIFICATIONS ----
+                    } else {
+                        final View view = thisInflater.createViewFromTag(childName, childAttrs);
+                        final ViewGroup group = (ViewGroup) parent;
+
+                        // We try to load the layout params set in the <include /> tag. If
+                        // they don't exist, we will rely on the layout params set in the
+                        // included XML file.
+                        // During a layoutparams generation, a runtime exception is thrown
+                        // if either layout_width or layout_height is missing. We catch
+                        // this exception and set localParams accordingly: true means we
+                        // successfully loaded layout params from the <include /> tag,
+                        // false means we need to rely on the included layout params.
+                        ViewGroup.LayoutParams params = null;
+                        try {
+                            // ---- START CHANGES
+                            sIsInInclude = true;
+                            // ---- END CHANGES
+
+                            params = group.generateLayoutParams(attrs);
+                        } catch (RuntimeException e) {
+                            // ---- START CHANGES
+                            sIsInInclude = false;
+                            // ---- END CHANGES
+
+                            params = group.generateLayoutParams(childAttrs);
+                        } finally {
+                            // ---- START CHANGES
+                            sIsInInclude = false;
+                            // ---- END CHANGES
+
+                            if (params != null) {
+                                view.setLayoutParams(params);
+                            }
+                        }
+
+                        // Inflate all children.
+                        thisInflater.rInflate(childParser, view, childAttrs);
+
+                        // Attempt to override the included layout's android:id with the
+                        // one set on the <include /> tag itself.
+                        TypedArray a = thisInflater.mContext.obtainStyledAttributes(attrs,
+                            com.android.internal.R.styleable.View, 0, 0);
+                        int id = a.getResourceId(com.android.internal.R.styleable.View_id, View.NO_ID);
+                        // While we're at it, let's try to override android:visibility.
+                        int visibility = a.getInt(com.android.internal.R.styleable.View_visibility, -1);
+                        a.recycle();
+
+                        if (id != View.NO_ID) {
+                            view.setId(id);
+                        }
+
+                        switch (visibility) {
+                            case 0:
+                                view.setVisibility(View.VISIBLE);
+                                break;
+                            case 1:
+                                view.setVisibility(View.INVISIBLE);
+                                break;
+                            case 2:
+                                view.setVisibility(View.GONE);
+                                break;
+                        }
+
+                        group.addView(view);
+                    }
+                } finally {
+                    childParser.close();
+                }
+            }
+        } else {
+            throw new InflateException("<include /> can only be used inside of a ViewGroup");
+        }
+
+        final int currentDepth = parser.getDepth();
+        while (((type = parser.next()) != XmlPullParser.END_TAG ||
+                parser.getDepth() > currentDepth) && type != XmlPullParser.END_DOCUMENT) {
+            // Empty
+        }
+    }
+}
diff --git a/tools/layoutlib/bridge/src/android/view/View_Delegate.java b/tools/layoutlib/bridge/src/android/view/View_Delegate.java
new file mode 100644
index 0000000..8215f7c
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/view/View_Delegate.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.view;
+
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+/**
+ * Delegate used to provide new implementation of a select few methods of {@link View}
+ *
+ * Through the layoutlib_create tool, the original  methods of View have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ */
+public class View_Delegate {
+
+    @LayoutlibDelegate
+    /*package*/ static boolean isInEditMode(View thisView) {
+        return true;
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/internal/util/XmlUtils_Delegate.java b/tools/layoutlib/bridge/src/com/android/internal/util/XmlUtils_Delegate.java
new file mode 100644
index 0000000..bf998b8
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/internal/util/XmlUtils_Delegate.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.util;
+
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+
+/**
+ * Delegate used to provide new implementation of a select few methods of {@link XmlUtils}
+ *
+ * Through the layoutlib_create tool, the original  methods of XmlUtils have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ */
+public class XmlUtils_Delegate {
+
+    @LayoutlibDelegate
+    /*package*/ static final int convertValueToInt(CharSequence charSeq, int defaultValue) {
+        if (null == charSeq)
+            return defaultValue;
+
+        String nm = charSeq.toString();
+
+        // This code is copied from the original implementation. The issue is that
+        // The Dalvik libraries are able to handle Integer.parse("XXXXXXXX", 16) where XXXXXXX
+        // is > 80000000 but the Java VM cannot.
+
+        int sign = 1;
+        int index = 0;
+        int len = nm.length();
+        int base = 10;
+
+        if ('-' == nm.charAt(0)) {
+            sign = -1;
+            index++;
+        }
+
+        if ('0' == nm.charAt(index)) {
+            //  Quick check for a zero by itself
+            if (index == (len - 1))
+                return 0;
+
+            char c = nm.charAt(index + 1);
+
+            if ('x' == c || 'X' == c) {
+                index += 2;
+                base = 16;
+            } else {
+                index++;
+                base = 8;
+            }
+        }
+        else if ('#' == nm.charAt(index)) {
+            index++;
+            base = 16;
+        }
+
+        return ((int)Long.parseLong(nm.substring(index), base)) * sign;
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/Bridge.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/Bridge.java
index f91f601..c74eb33 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/Bridge.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/Bridge.java
@@ -16,68 +16,51 @@
 
 package com.android.layoutlib.bridge;
 
-import com.android.internal.util.XmlUtils;
-import com.android.layoutlib.api.ILayoutBridge;
-import com.android.layoutlib.api.ILayoutLog;
-import com.android.layoutlib.api.ILayoutResult;
-import com.android.layoutlib.api.IProjectCallback;
-import com.android.layoutlib.api.IResourceValue;
-import com.android.layoutlib.api.IStyleResourceValue;
-import com.android.layoutlib.api.IXmlPullParser;
-import com.android.layoutlib.api.ILayoutResult.ILayoutViewInfo;
-import com.android.layoutlib.bridge.LayoutResult.LayoutViewInfo;
-import com.android.ninepatch.NinePatch;
+import static com.android.ide.common.rendering.api.Result.Status.ERROR_UNKNOWN;
+import static com.android.ide.common.rendering.api.Result.Status.SUCCESS;
+
+import com.android.ide.common.rendering.api.Capability;
+import com.android.ide.common.rendering.api.DrawableParams;
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.ide.common.rendering.api.RenderSession;
+import com.android.ide.common.rendering.api.Result;
+import com.android.ide.common.rendering.api.SessionParams;
+import com.android.ide.common.rendering.api.Result.Status;
+import com.android.layoutlib.bridge.android.BridgeAssetManager;
+import com.android.layoutlib.bridge.impl.FontLoader;
+import com.android.layoutlib.bridge.impl.RenderDrawable;
+import com.android.layoutlib.bridge.impl.RenderSessionImpl;
+import com.android.ninepatch.NinePatchChunk;
+import com.android.resources.ResourceType;
 import com.android.tools.layoutlib.create.MethodAdapter;
 import com.android.tools.layoutlib.create.OverrideMethod;
+import com.android.util.Pair;
 
-import android.content.res.Configuration;
 import android.graphics.Bitmap;
-import android.graphics.Canvas;
-import android.graphics.Rect;
-import android.graphics.Region;
 import android.graphics.Typeface;
-import android.graphics.drawable.Drawable;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.IBinder;
+import android.graphics.Typeface_Delegate;
 import android.os.Looper;
-import android.os.ParcelFileDescriptor;
-import android.os.RemoteException;
-import android.util.DisplayMetrics;
-import android.util.TypedValue;
-import android.view.BridgeInflater;
-import android.view.InputChannel;
-import android.view.IWindow;
-import android.view.IWindowSession;
-import android.view.KeyEvent;
-import android.view.MotionEvent;
-import android.view.Surface;
-import android.view.SurfaceView;
 import android.view.View;
 import android.view.ViewGroup;
-import android.view.View.AttachInfo;
-import android.view.View.MeasureSpec;
-import android.view.WindowManager.LayoutParams;
-import android.widget.FrameLayout;
-import android.widget.TabHost;
-import android.widget.TabWidget;
+import android.view.ViewParent;
 
+import java.io.File;
 import java.lang.ref.SoftReference;
 import java.lang.reflect.Field;
 import java.lang.reflect.Modifier;
-import java.util.Collection;
+import java.util.Arrays;
+import java.util.EnumMap;
+import java.util.EnumSet;
 import java.util.HashMap;
 import java.util.Map;
+import java.util.concurrent.locks.ReentrantLock;
 
 /**
  * Main entry point of the LayoutLib Bridge.
  * <p/>To use this bridge, simply instantiate an object of type {@link Bridge} and call
- * {@link #computeLayout(IXmlPullParser, Object, int, int, String, boolean, Map, Map, IProjectCallback, ILayoutLog)}.
+ * {@link #createScene(SceneParams)}
  */
-public final class Bridge implements ILayoutBridge {
-
-    private static final int DEFAULT_TITLE_BAR_HEIGHT = 25;
-    private static final int DEFAULT_STATUS_BAR_HEIGHT = 25;
+public final class Bridge extends com.android.ide.common.rendering.api.Bridge {
 
     public static class StaticMethodNotImplementedException extends RuntimeException {
         private static final long serialVersionUID = 1L;
@@ -88,84 +71,138 @@
     }
 
     /**
-     * Maps from id to resource name/type. This is for android.R only.
+     * Lock to ensure only one rendering/inflating happens at a time.
+     * This is due to some singleton in the Android framework.
      */
-    private final static Map<Integer, String[]> sRMap = new HashMap<Integer, String[]>();
+    private final static ReentrantLock sLock = new ReentrantLock();
+
+    /**
+     * Maps from id to resource type/name. This is for android.R only.
+     */
+    private final static Map<Integer, Pair<ResourceType, String>> sRMap =
+        new HashMap<Integer, Pair<ResourceType, String>>();
+
     /**
      * Same as sRMap except for int[] instead of int resources. This is for android.R only.
      */
-    private final static Map<int[], String> sRArrayMap = new HashMap<int[], String>();
+    private final static Map<IntArray, String> sRArrayMap = new HashMap<IntArray, String>();
     /**
      * Reverse map compared to sRMap, resource type -> (resource name -> id).
      * This is for android.R only.
      */
-    private final static Map<String, Map<String, Integer>> sRFullMap =
-        new HashMap<String, Map<String,Integer>>();
+    private final static Map<ResourceType, Map<String, Integer>> sRFullMap =
+        new EnumMap<ResourceType, Map<String,Integer>>(ResourceType.class);
 
     private final static Map<Object, Map<String, SoftReference<Bitmap>>> sProjectBitmapCache =
         new HashMap<Object, Map<String, SoftReference<Bitmap>>>();
-    private final static Map<Object, Map<String, SoftReference<NinePatch>>> sProject9PatchCache =
-        new HashMap<Object, Map<String, SoftReference<NinePatch>>>();
+    private final static Map<Object, Map<String, SoftReference<NinePatchChunk>>> sProject9PatchCache =
+        new HashMap<Object, Map<String, SoftReference<NinePatchChunk>>>();
 
     private final static Map<String, SoftReference<Bitmap>> sFrameworkBitmapCache =
         new HashMap<String, SoftReference<Bitmap>>();
-    private final static Map<String, SoftReference<NinePatch>> sFramework9PatchCache =
-        new HashMap<String, SoftReference<NinePatch>>();
+    private final static Map<String, SoftReference<NinePatchChunk>> sFramework9PatchCache =
+        new HashMap<String, SoftReference<NinePatchChunk>>();
 
     private static Map<String, Map<String, Integer>> sEnumValueMap;
+    private static Map<String, String> sPlatformProperties;
 
     /**
-     * A default logger than prints to stdout/stderr.
+     * int[] wrapper to use as keys in maps.
      */
-    private final static ILayoutLog sDefaultLogger = new ILayoutLog() {
-        public void error(String message) {
+    private final static class IntArray {
+        private int[] mArray;
+
+        private IntArray() {
+            // do nothing
+        }
+
+        private IntArray(int[] a) {
+            mArray = a;
+        }
+
+        private void set(int[] a) {
+            mArray = a;
+        }
+
+        @Override
+        public int hashCode() {
+            return Arrays.hashCode(mArray);
+        }
+
+        @Override
+        public boolean equals(Object obj) {
+            if (this == obj) return true;
+            if (obj == null) return false;
+            if (getClass() != obj.getClass()) return false;
+
+            IntArray other = (IntArray) obj;
+            if (!Arrays.equals(mArray, other.mArray)) return false;
+            return true;
+        }
+    }
+
+    /** Instance of IntArrayWrapper to be reused in {@link #resolveResourceId(int[])}. */
+    private final static IntArray sIntArrayWrapper = new IntArray();
+
+    /**
+     * A default log than prints to stdout/stderr.
+     */
+    private final static LayoutLog sDefaultLog = new LayoutLog() {
+        @Override
+        public void error(String tag, String message, Object data) {
             System.err.println(message);
         }
 
-        public void error(Throwable t) {
-            String message = t.getMessage();
-            if (message == null) {
-                message = t.getClass().getName();
-            }
-
+        @Override
+        public void error(String tag, String message, Throwable throwable, Object data) {
             System.err.println(message);
         }
 
-        public void warning(String message) {
+        @Override
+        public void warning(String tag, String message, Object data) {
             System.out.println(message);
         }
     };
 
     /**
-     * Logger defined during a compute layout operation.
-     * <p/>
-     * This logger is generally set to {@link #sDefaultLogger} except during rendering
-     * operations when it might be set to a specific provided logger.
-     * <p/>
-     * To change this value, use a block synchronized on {@link #sDefaultLogger}.
+     * Current log.
      */
-    private static ILayoutLog sLogger = sDefaultLogger;
+    private static LayoutLog sCurrentLog = sDefaultLog;
 
-    /*
-     * (non-Javadoc)
-     * @see com.android.layoutlib.api.ILayoutBridge#getApiLevel()
-     */
+    private EnumSet<Capability> mCapabilities;
+
+    @Override
     public int getApiLevel() {
-        return API_CURRENT;
+        return com.android.ide.common.rendering.api.Bridge.API_CURRENT;
     }
 
-    /*
-     * (non-Javadoc)
-     * @see com.android.layoutlib.api.ILayoutLibBridge#init(java.lang.String, java.util.Map)
-     */
-    public boolean init(
-            String fontOsLocation, Map<String, Map<String, Integer>> enumValueMap) {
-
-        return sinit(fontOsLocation, enumValueMap);
+    @Override
+    public EnumSet<Capability> getCapabilities() {
+        return mCapabilities;
     }
 
-    private static synchronized boolean sinit(String fontOsLocation,
-            Map<String, Map<String, Integer>> enumValueMap) {
+    @Override
+    public boolean init(Map<String,String> platformProperties,
+            File fontLocation,
+            Map<String, Map<String, Integer>> enumValueMap,
+            LayoutLog log) {
+        sPlatformProperties = platformProperties;
+        sEnumValueMap = enumValueMap;
+
+        // don't use EnumSet.allOf(), because the bridge doesn't come with its specific version
+        // of layoutlib_api. It is provided by the client which could have a more recent version
+        // with newer, unsupported capabilities.
+        mCapabilities = EnumSet.of(
+                Capability.UNBOUND_RENDERING,
+                Capability.CUSTOM_BACKGROUND_COLOR,
+                Capability.RENDER,
+                Capability.LAYOUT_ONLY,
+                Capability.EMBEDDED_LAYOUT,
+                Capability.VIEW_MANIPULATION,
+                Capability.ADAPTER_BINDING,
+                Capability.EXTENDED_VIEWINFO);
+
+        BridgeAssetManager.initSystem();
 
         // When DEBUG_LAYOUT is set and is not 0 or false, setup a default listener
         // on static (native) methods which prints the signature on the console and
@@ -182,12 +219,8 @@
             OverrideMethod.setDefaultListener(new MethodAdapter() {
                 @Override
                 public void onInvokeV(String signature, boolean isNative, Object caller) {
-                    if (sLogger != null) {
-                        synchronized (sDefaultLogger) {
-                            sLogger.error("Missing Stub: " + signature +
-                                    (isNative ? " (native)" : ""));
-                        }
-                    }
+                    sDefaultLog.error(null, "Missing Stub: " + signature +
+                            (isNative ? " (native)" : ""), null /*data*/);
 
                     if (debug.equalsIgnoreCase("throw")) {
                         // Throwing this exception doesn't seem that useful. It breaks
@@ -200,293 +233,138 @@
             });
         }
 
-        // Override View.isInEditMode to return true.
-        //
-        // This allows custom views that are drawn in the Graphical Layout Editor to adapt their
-        // rendering for preview. Most important this let custom views know that they can't expect
-        // the rest of their activities to be alive.
-        OverrideMethod.setMethodListener("android.view.View#isInEditMode()Z",
-            new MethodAdapter() {
-                @Override
-                public int onInvokeI(String signature, boolean isNative, Object caller) {
-                    return 1;
-                }
-            }
-        );
-
         // load the fonts.
-        FontLoader fontLoader = FontLoader.create(fontOsLocation);
+        FontLoader fontLoader = FontLoader.create(fontLocation.getAbsolutePath());
         if (fontLoader != null) {
-            Typeface.init(fontLoader);
+            Typeface_Delegate.init(fontLoader);
         } else {
             return false;
         }
 
-        sEnumValueMap = enumValueMap;
-
         // now parse com.android.internal.R (and only this one as android.R is a subset of
         // the internal version), and put the content in the maps.
         try {
-            // WARNING: this only works because the class is already loaded, and therefore
-            // the objects returned by Field.get() are the same as the ones used by
-            // the code accessing the R class.
-            // int[] does not implement equals/hashCode, and if the parsing used a different class
-            // loader for the R class, this would NOT work.
             Class<?> r = com.android.internal.R.class;
 
             for (Class<?> inner : r.getDeclaredClasses()) {
-                String resType = inner.getSimpleName();
+                String resTypeName = inner.getSimpleName();
+                ResourceType resType = ResourceType.getEnum(resTypeName);
+                if (resType != null) {
+                    Map<String, Integer> fullMap = new HashMap<String, Integer>();
+                    sRFullMap.put(resType, fullMap);
 
-                Map<String, Integer> fullMap = new HashMap<String, Integer>();
-                sRFullMap.put(resType, fullMap);
-
-                for (Field f : inner.getDeclaredFields()) {
-                    // only process static final fields. Since the final attribute may have
-                    // been altered by layoutlib_create, we only check static
-                    int modifiers = f.getModifiers();
-                    if (Modifier.isStatic(modifiers)) {
-                        Class<?> type = f.getType();
-                        if (type.isArray() && type.getComponentType() == int.class) {
-                            // if the object is an int[] we put it in sRArrayMap
-                            sRArrayMap.put((int[]) f.get(null), f.getName());
-                        } else if (type == int.class) {
-                            Integer value = (Integer) f.get(null);
-                            sRMap.put(value, new String[] { f.getName(), resType });
-                            fullMap.put(f.getName(), value);
-                        } else {
-                            assert false;
+                    for (Field f : inner.getDeclaredFields()) {
+                        // only process static final fields. Since the final attribute may have
+                        // been altered by layoutlib_create, we only check static
+                        int modifiers = f.getModifiers();
+                        if (Modifier.isStatic(modifiers)) {
+                            Class<?> type = f.getType();
+                            if (type.isArray() && type.getComponentType() == int.class) {
+                                // if the object is an int[] we put it in sRArrayMap using an IntArray
+                                // wrapper that properly implements equals and hashcode for the array
+                                // objects, as required by the map contract.
+                                sRArrayMap.put(new IntArray((int[]) f.get(null)), f.getName());
+                            } else if (type == int.class) {
+                                Integer value = (Integer) f.get(null);
+                                sRMap.put(value, Pair.of(resType, f.getName()));
+                                fullMap.put(f.getName(), value);
+                            } else {
+                                assert false;
+                            }
                         }
                     }
                 }
             }
-        } catch (IllegalArgumentException e) {
-            // FIXME: log/return the error (there's no logger object at this point!)
-            e.printStackTrace();
-            return false;
-        } catch (IllegalAccessException e) {
-            e.printStackTrace();
+        } catch (Throwable throwable) {
+            if (log != null) {
+                log.error(LayoutLog.TAG_BROKEN,
+                        "Failed to load com.android.internal.R from the layout library jar",
+                        throwable);
+            }
             return false;
         }
 
         return true;
     }
 
-    /*
-     * For compatilibty purposes, we implement the old deprecated version of computeLayout.
-     * (non-Javadoc)
-     * @see com.android.layoutlib.api.ILayoutBridge#computeLayout(com.android.layoutlib.api.IXmlPullParser, java.lang.Object, int, int, java.lang.String, java.util.Map, java.util.Map, com.android.layoutlib.api.IProjectCallback, com.android.layoutlib.api.ILayoutLog)
-     */
-    @Deprecated
-    public ILayoutResult computeLayout(IXmlPullParser layoutDescription,
-            Object projectKey,
-            int screenWidth, int screenHeight, String themeName,
-            Map<String, Map<String, IResourceValue>> projectResources,
-            Map<String, Map<String, IResourceValue>> frameworkResources,
-            IProjectCallback customViewLoader, ILayoutLog logger) {
-        boolean isProjectTheme = false;
-        if (themeName.charAt(0) == '*') {
-            themeName = themeName.substring(1);
-            isProjectTheme = true;
-        }
+    @Override
+    public boolean dispose() {
+        BridgeAssetManager.clearSystem();
 
-        return computeLayout(layoutDescription, projectKey,
-                screenWidth, screenHeight, DisplayMetrics.DENSITY_DEFAULT,
-                DisplayMetrics.DENSITY_DEFAULT, DisplayMetrics.DENSITY_DEFAULT,
-                themeName, isProjectTheme,
-                projectResources, frameworkResources, customViewLoader, logger);
+        // dispose of the default typeface.
+        Typeface.sDefaults = null;
+
+        return true;
     }
 
-    /*
-     * For compatilibty purposes, we implement the old deprecated version of computeLayout.
-     * (non-Javadoc)
-     * @see com.android.layoutlib.api.ILayoutBridge#computeLayout(com.android.layoutlib.api.IXmlPullParser, java.lang.Object, int, int, java.lang.String, boolean, java.util.Map, java.util.Map, com.android.layoutlib.api.IProjectCallback, com.android.layoutlib.api.ILayoutLog)
+    /**
+     * Starts a layout session by inflating and rendering it. The method returns a
+     * {@link RenderSession} on which further actions can be taken.
+     *
+     * @param params the {@link SessionParams} object with all the information necessary to create
+     *           the scene.
+     * @return a new {@link RenderSession} object that contains the result of the layout.
+     * @since 5
      */
-    @Deprecated
-    public ILayoutResult computeLayout(IXmlPullParser layoutDescription, Object projectKey,
-            int screenWidth, int screenHeight, String themeName, boolean isProjectTheme,
-            Map<String, Map<String, IResourceValue>> projectResources,
-            Map<String, Map<String, IResourceValue>> frameworkResources,
-            IProjectCallback customViewLoader, ILayoutLog logger) {
-        return computeLayout(layoutDescription, projectKey,
-                screenWidth, screenHeight, DisplayMetrics.DENSITY_DEFAULT,
-                DisplayMetrics.DENSITY_DEFAULT, DisplayMetrics.DENSITY_DEFAULT,
-                themeName, isProjectTheme,
-                projectResources, frameworkResources, customViewLoader, logger);
-    }
-
-    /*
-     * For compatilibty purposes, we implement the old deprecated version of computeLayout.
-     * (non-Javadoc)
-     * @see com.android.layoutlib.api.ILayoutBridge#computeLayout(com.android.layoutlib.api.IXmlPullParser, java.lang.Object, int, int, int, float, float, java.lang.String, boolean, java.util.Map, java.util.Map, com.android.layoutlib.api.IProjectCallback, com.android.layoutlib.api.ILayoutLog)
-     */
-    public ILayoutResult computeLayout(IXmlPullParser layoutDescription, Object projectKey,
-            int screenWidth, int screenHeight, int density, float xdpi, float ydpi,
-            String themeName, boolean isProjectTheme,
-            Map<String, Map<String, IResourceValue>> projectResources,
-            Map<String, Map<String, IResourceValue>> frameworkResources,
-            IProjectCallback customViewLoader, ILayoutLog logger) {
-        return computeLayout(layoutDescription, projectKey,
-                screenWidth, screenHeight, false /* renderFullSize */,
-                density, xdpi, ydpi, themeName, isProjectTheme,
-                projectResources, frameworkResources, customViewLoader, logger);
-    }
-
-    /*
-     * (non-Javadoc)
-     * @see com.android.layoutlib.api.ILayoutBridge#computeLayout(com.android.layoutlib.api.IXmlPullParser, java.lang.Object, int, int, boolean, int, float, float, java.lang.String, boolean, java.util.Map, java.util.Map, com.android.layoutlib.api.IProjectCallback, com.android.layoutlib.api.ILayoutLog)
-     */
-    public ILayoutResult computeLayout(IXmlPullParser layoutDescription, Object projectKey,
-            int screenWidth, int screenHeight, boolean renderFullSize,
-            int density, float xdpi, float ydpi,
-            String themeName, boolean isProjectTheme,
-            Map<String, Map<String, IResourceValue>> projectResources,
-            Map<String, Map<String, IResourceValue>> frameworkResources,
-            IProjectCallback customViewLoader, ILayoutLog logger) {
-        if (logger == null) {
-            logger = sDefaultLogger;
-        }
-
-        synchronized (sDefaultLogger) {
-            sLogger = logger;
-        }
-
-        // find the current theme and compute the style inheritance map
-        Map<IStyleResourceValue, IStyleResourceValue> styleParentMap =
-            new HashMap<IStyleResourceValue, IStyleResourceValue>();
-
-        IStyleResourceValue currentTheme = computeStyleMaps(themeName, isProjectTheme,
-                projectResources.get(BridgeConstants.RES_STYLE),
-                frameworkResources.get(BridgeConstants.RES_STYLE), styleParentMap);
-
-        BridgeContext context = null;
+    @Override
+    public RenderSession createSession(SessionParams params) {
         try {
-            // setup the display Metrics.
-            DisplayMetrics metrics = new DisplayMetrics();
-            metrics.densityDpi = density;
-            metrics.density = density / (float) DisplayMetrics.DENSITY_DEFAULT;
-            metrics.scaledDensity = metrics.density;
-            metrics.widthPixels = screenWidth;
-            metrics.heightPixels = screenHeight;
-            metrics.xdpi = xdpi;
-            metrics.ydpi = ydpi;
-
-            context = new BridgeContext(projectKey, metrics, currentTheme, projectResources,
-                    frameworkResources, styleParentMap, customViewLoader, logger);
-            BridgeInflater inflater = new BridgeInflater(context, customViewLoader);
-            context.setBridgeInflater(inflater);
-
-            IResourceValue windowBackground = null;
-            int screenOffset = 0;
-            if (currentTheme != null) {
-                windowBackground = context.findItemInStyle(currentTheme, "windowBackground");
-                windowBackground = context.resolveResValue(windowBackground);
-
-                screenOffset = getScreenOffset(frameworkResources, currentTheme, context);
-            }
-
-            // we need to make sure the Looper has been initialized for this thread.
-            // this is required for View that creates Handler objects.
-            if (Looper.myLooper() == null) {
-                Looper.prepare();
-            }
-
-            BridgeXmlBlockParser parser = new BridgeXmlBlockParser(layoutDescription,
-                    context, false /* platformResourceFlag */);
-
-            ViewGroup root = new FrameLayout(context);
-
-            View view = inflater.inflate(parser, root);
-
-            // post-inflate process. For now this supports TabHost/TabWidget
-            postInflateProcess(view, customViewLoader);
-
-            // set the AttachInfo on the root view.
-            AttachInfo info = new AttachInfo(new WindowSession(), new Window(),
-                    new Handler(), null);
-            info.mHasWindowFocus = true;
-            info.mWindowVisibility = View.VISIBLE;
-            info.mInTouchMode = false; // this is so that we can display selections.
-            root.dispatchAttachedToWindow(info, 0);
-
-            // get the background drawable
-            if (windowBackground != null) {
-                Drawable d = ResourceHelper.getDrawable(windowBackground,
-                        context, true /* isFramework */);
-                root.setBackgroundDrawable(d);
-            }
-
-            // measure the views
-            int w_spec, h_spec;
-
-            if (renderFullSize) {
-                // measure the full size needed by the layout.
-                w_spec = MeasureSpec.makeMeasureSpec(screenWidth,
-                        MeasureSpec.UNSPECIFIED); // this lets us know the actual needed size
-                h_spec = MeasureSpec.makeMeasureSpec(screenHeight - screenOffset,
-                        MeasureSpec.UNSPECIFIED); // this lets us know the actual needed size
-                view.measure(w_spec, h_spec);
-
-                int neededWidth = root.getChildAt(0).getMeasuredWidth();
-                if (neededWidth > screenWidth) {
-                    screenWidth = neededWidth;
+            Result lastResult = SUCCESS.createResult();
+            RenderSessionImpl scene = new RenderSessionImpl(params);
+            try {
+                prepareThread();
+                lastResult = scene.init(params.getTimeout());
+                if (lastResult.isSuccess()) {
+                    lastResult = scene.inflate();
+                    if (lastResult.isSuccess()) {
+                        lastResult = scene.render(true /*freshRender*/);
+                    }
                 }
-
-                int neededHeight = root.getChildAt(0).getMeasuredHeight();
-                if (neededHeight > screenHeight - screenOffset) {
-                    screenHeight = neededHeight + screenOffset;
-                }
+            } finally {
+                scene.release();
+                cleanupThread();
             }
 
-            // remeasure with only the size we need
-            // This must always be done before the call to layout
-            w_spec = MeasureSpec.makeMeasureSpec(screenWidth, MeasureSpec.EXACTLY);
-            h_spec = MeasureSpec.makeMeasureSpec(screenHeight - screenOffset,
-                    MeasureSpec.EXACTLY);
-            view.measure(w_spec, h_spec);
-
-            // now do the layout.
-            view.layout(0, screenOffset, screenWidth, screenHeight);
-
-            // draw the views
-            Canvas canvas = new Canvas(screenWidth, screenHeight - screenOffset, logger);
-
-            root.draw(canvas);
-            canvas.dispose();
-
-            return new LayoutResult(visit(((ViewGroup)view).getChildAt(0), context),
-                    canvas.getImage());
-        } catch (PostInflateException e) {
-            return new LayoutResult(ILayoutResult.ERROR, "Error during post inflation process:\n"
-                    + e.getMessage());
-        } catch (Throwable e) {
+            return new BridgeRenderSession(scene, lastResult);
+        } catch (Throwable t) {
             // get the real cause of the exception.
-            Throwable t = e;
-            while (t.getCause() != null) {
-                t = t.getCause();
+            Throwable t2 = t;
+            while (t2.getCause() != null) {
+                t2 = t.getCause();
             }
-
-            // log it
-            logger.error(t);
-
-            // then return with an ERROR status and the message from the real exception
-            return new LayoutResult(ILayoutResult.ERROR,
-                    t.getClass().getSimpleName() + ": " + t.getMessage());
-        } finally {
-            // Make sure to remove static references, otherwise we could not unload the lib
-            BridgeResources.clearSystem();
-            BridgeAssetManager.clearSystem();
-
-            // Remove the global logger
-            synchronized (sDefaultLogger) {
-                sLogger = sDefaultLogger;
-            }
+            return new BridgeRenderSession(null,
+                    ERROR_UNKNOWN.createResult(t2.getMessage(), t));
         }
     }
 
-    /*
-     * (non-Javadoc)
-     * @see com.android.layoutlib.api.ILayoutLibBridge#clearCaches(java.lang.Object)
-     */
+    @Override
+    public Result renderDrawable(DrawableParams params) {
+        try {
+            Result lastResult = SUCCESS.createResult();
+            RenderDrawable action = new RenderDrawable(params);
+            try {
+                prepareThread();
+                lastResult = action.init(params.getTimeout());
+                if (lastResult.isSuccess()) {
+                    lastResult = action.render();
+                }
+            } finally {
+                action.release();
+                cleanupThread();
+            }
+
+            return lastResult;
+        } catch (Throwable t) {
+            // get the real cause of the exception.
+            Throwable t2 = t;
+            while (t2.getCause() != null) {
+                t2 = t.getCause();
+            }
+            return ERROR_UNKNOWN.createResult(t2.getMessage(), t);
+        }
+    }
+
+    @Override
     public void clearCaches(Object projectKey) {
         if (projectKey != null) {
             sProjectBitmapCache.remove(projectKey);
@@ -494,23 +372,97 @@
         }
     }
 
+    @Override
+    public Result getViewParent(Object viewObject) {
+        if (viewObject instanceof View) {
+            return Status.SUCCESS.createResult(((View)viewObject).getParent());
+        }
+
+        throw new IllegalArgumentException("viewObject is not a View");
+    }
+
+    @Override
+    public Result getViewIndex(Object viewObject) {
+        if (viewObject instanceof View) {
+            View view = (View) viewObject;
+            ViewParent parentView = view.getParent();
+
+            if (parentView instanceof ViewGroup) {
+                Status.SUCCESS.createResult(((ViewGroup) parentView).indexOfChild(view));
+            }
+
+            return Status.SUCCESS.createResult();
+        }
+
+        throw new IllegalArgumentException("viewObject is not a View");
+    }
+
+    /**
+     * Returns the lock for the bridge
+     */
+    public static ReentrantLock getLock() {
+        return sLock;
+    }
+
+    /**
+     * Prepares the current thread for rendering.
+     *
+     * Note that while this can be called several time, the first call to {@link #cleanupThread()}
+     * will do the clean-up, and make the thread unable to do further scene actions.
+     */
+    public static void prepareThread() {
+        // we need to make sure the Looper has been initialized for this thread.
+        // this is required for View that creates Handler objects.
+        if (Looper.myLooper() == null) {
+            Looper.prepare();
+        }
+    }
+
+    /**
+     * Cleans up thread-specific data. After this, the thread cannot be used for scene actions.
+     * <p>
+     * Note that it doesn't matter how many times {@link #prepareThread()} was called, a single
+     * call to this will prevent the thread from doing further scene actions
+     */
+    public static void cleanupThread() {
+        // clean up the looper
+        Looper.sThreadLocal.remove();
+    }
+
+    public static LayoutLog getLog() {
+        return sCurrentLog;
+    }
+
+    public static void setLog(LayoutLog log) {
+        // check only the thread currently owning the lock can do this.
+        if (sLock.isHeldByCurrentThread() == false) {
+            throw new IllegalStateException("scene must be acquired first. see #acquire(long)");
+        }
+
+        if (log != null) {
+            sCurrentLog = log;
+        } else {
+            sCurrentLog = sDefaultLog;
+        }
+    }
+
     /**
      * Returns details of a framework resource from its integer value.
      * @param value the integer value
-     * @return an array of 2 strings containing the resource name and type, or null if the id
-     * does not match any resource.
+     * @return a Pair containing the resource type and name, or null if the id
+     *     does not match any resource.
      */
-    public static String[] resolveResourceValue(int value) {
+    public static Pair<ResourceType, String> resolveResourceId(int value) {
         return sRMap.get(value);
-
     }
 
     /**
      * Returns the name of a framework resource whose value is an int array.
      * @param array
      */
-    public static String resolveResourceValue(int[] array) {
-        return sRArrayMap.get(array);
+    public static String resolveResourceId(int[] array) {
+        sIntArrayWrapper.set(array);
+        return sRArrayMap.get(sIntArrayWrapper);
     }
 
     /**
@@ -519,7 +471,7 @@
      * @param name the name of the resource.
      * @return an {@link Integer} containing the resource id, or null if no resource were found.
      */
-    public static Integer getResourceValue(String type, String name) {
+    public static Integer getResourceId(ResourceType type, String name) {
         Map<String, Integer> map = sRFullMap.get(type);
         if (map != null) {
             return map.get(name);
@@ -528,7 +480,10 @@
         return null;
     }
 
-    static Map<String, Integer> getEnumValues(String attributeName) {
+    /**
+     * Returns the list of possible enums for a given attribute name.
+     */
+    public static Map<String, Integer> getEnumValues(String attributeName) {
         if (sEnumValueMap != null) {
             return sEnumValueMap.get(attributeName);
         }
@@ -537,348 +492,10 @@
     }
 
     /**
-     * Visits a View and its children and generate a {@link ILayoutViewInfo} containing the
-     * bounds of all the views.
-     * @param view the root View
-     * @param context the context.
+     * Returns the platform build properties.
      */
-    private ILayoutViewInfo visit(View view, BridgeContext context) {
-        if (view == null) {
-            return null;
-        }
-
-        LayoutViewInfo result = new LayoutViewInfo(view.getClass().getName(),
-                context.getViewKey(view),
-                view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
-
-        if (view instanceof ViewGroup) {
-            ViewGroup group = ((ViewGroup) view);
-            int n = group.getChildCount();
-            ILayoutViewInfo[] children = new ILayoutViewInfo[n];
-            for (int i = 0; i < group.getChildCount(); i++) {
-                children[i] = visit(group.getChildAt(i), context);
-            }
-            result.setChildren(children);
-        }
-
-        return result;
-    }
-
-    /**
-     * Compute style information from the given list of style for the project and framework.
-     * @param themeName the name of the current theme.  In order to differentiate project and
-     * platform themes sharing the same name, all project themes must be prepended with
-     * a '*' character.
-     * @param isProjectTheme Is this a project theme
-     * @param inProjectStyleMap the project style map
-     * @param inFrameworkStyleMap the framework style map
-     * @param outInheritanceMap the map of style inheritance. This is filled by the method
-     * @return the {@link IStyleResourceValue} matching <var>themeName</var>
-     */
-    private IStyleResourceValue computeStyleMaps(
-            String themeName, boolean isProjectTheme, Map<String,
-            IResourceValue> inProjectStyleMap, Map<String, IResourceValue> inFrameworkStyleMap,
-            Map<IStyleResourceValue, IStyleResourceValue> outInheritanceMap) {
-
-        if (inProjectStyleMap != null && inFrameworkStyleMap != null) {
-            // first, get the theme
-            IResourceValue theme = null;
-
-            // project theme names have been prepended with a *
-            if (isProjectTheme) {
-                theme = inProjectStyleMap.get(themeName);
-            } else {
-                theme = inFrameworkStyleMap.get(themeName);
-            }
-
-            if (theme instanceof IStyleResourceValue) {
-                // compute the inheritance map for both the project and framework styles
-                computeStyleInheritance(inProjectStyleMap.values(), inProjectStyleMap,
-                        inFrameworkStyleMap, outInheritanceMap);
-
-                // Compute the style inheritance for the framework styles/themes.
-                // Since, for those, the style parent values do not contain 'android:'
-                // we want to force looking in the framework style only to avoid using
-                // similarly named styles from the project.
-                // To do this, we pass null in lieu of the project style map.
-                computeStyleInheritance(inFrameworkStyleMap.values(), null /*inProjectStyleMap */,
-                        inFrameworkStyleMap, outInheritanceMap);
-
-                return (IStyleResourceValue)theme;
-            }
-        }
-
-        return null;
-    }
-
-    /**
-     * Compute the parent style for all the styles in a given list.
-     * @param styles the styles for which we compute the parent.
-     * @param inProjectStyleMap the map of project styles.
-     * @param inFrameworkStyleMap the map of framework styles.
-     * @param outInheritanceMap the map of style inheritance. This is filled by the method.
-     */
-    private void computeStyleInheritance(Collection<IResourceValue> styles,
-            Map<String, IResourceValue> inProjectStyleMap,
-            Map<String, IResourceValue> inFrameworkStyleMap,
-            Map<IStyleResourceValue, IStyleResourceValue> outInheritanceMap) {
-        for (IResourceValue value : styles) {
-            if (value instanceof IStyleResourceValue) {
-                IStyleResourceValue style = (IStyleResourceValue)value;
-                IStyleResourceValue parentStyle = null;
-
-                // first look for a specified parent.
-                String parentName = style.getParentStyle();
-
-                // no specified parent? try to infer it from the name of the style.
-                if (parentName == null) {
-                    parentName = getParentName(value.getName());
-                }
-
-                if (parentName != null) {
-                    parentStyle = getStyle(parentName, inProjectStyleMap, inFrameworkStyleMap);
-
-                    if (parentStyle != null) {
-                        outInheritanceMap.put(style, parentStyle);
-                    }
-                }
-            }
-        }
-    }
-
-    /**
-     * Searches for and returns the {@link IStyleResourceValue} from a given name.
-     * <p/>The format of the name can be:
-     * <ul>
-     * <li>[android:]&lt;name&gt;</li>
-     * <li>[android:]style/&lt;name&gt;</li>
-     * <li>@[android:]style/&lt;name&gt;</li>
-     * </ul>
-     * @param parentName the name of the style.
-     * @param inProjectStyleMap the project style map. Can be <code>null</code>
-     * @param inFrameworkStyleMap the framework style map.
-     * @return The matching {@link IStyleResourceValue} object or <code>null</code> if not found.
-     */
-    private IStyleResourceValue getStyle(String parentName,
-            Map<String, IResourceValue> inProjectStyleMap,
-            Map<String, IResourceValue> inFrameworkStyleMap) {
-        boolean frameworkOnly = false;
-
-        String name = parentName;
-
-        // remove the useless @ if it's there
-        if (name.startsWith(BridgeConstants.PREFIX_RESOURCE_REF)) {
-            name = name.substring(BridgeConstants.PREFIX_RESOURCE_REF.length());
-        }
-
-        // check for framework identifier.
-        if (name.startsWith(BridgeConstants.PREFIX_ANDROID)) {
-            frameworkOnly = true;
-            name = name.substring(BridgeConstants.PREFIX_ANDROID.length());
-        }
-
-        // at this point we could have the format <type>/<name>. we want only the name as long as
-        // the type is style.
-        if (name.startsWith(BridgeConstants.REFERENCE_STYLE)) {
-            name = name.substring(BridgeConstants.REFERENCE_STYLE.length());
-        } else if (name.indexOf('/') != -1) {
-            return null;
-        }
-
-        IResourceValue parent = null;
-
-        // if allowed, search in the project resources.
-        if (frameworkOnly == false && inProjectStyleMap != null) {
-            parent = inProjectStyleMap.get(name);
-        }
-
-        // if not found, then look in the framework resources.
-        if (parent == null) {
-            parent = inFrameworkStyleMap.get(name);
-        }
-
-        // make sure the result is the proper class type and return it.
-        if (parent instanceof IStyleResourceValue) {
-            return (IStyleResourceValue)parent;
-        }
-
-        sLogger.error(String.format("Unable to resolve parent style name: %s", parentName));
-
-        return null;
-    }
-
-    /**
-     * Computes the name of the parent style, or <code>null</code> if the style is a root style.
-     */
-    private String getParentName(String styleName) {
-        int index = styleName.lastIndexOf('.');
-        if (index != -1) {
-            return styleName.substring(0, index);
-        }
-
-        return null;
-    }
-
-    /**
-     * Returns the top screen offset. This depends on whether the current theme defines the user
-     * of the title and status bars.
-     * @param frameworkResources The framework resources
-     * @param currentTheme The current theme
-     * @param context The context
-     * @return the pixel height offset
-     */
-    private int getScreenOffset(Map<String, Map<String, IResourceValue>> frameworkResources,
-            IStyleResourceValue currentTheme, BridgeContext context) {
-        int offset = 0;
-
-        // get the title bar flag from the current theme.
-        IResourceValue value = context.findItemInStyle(currentTheme, "windowNoTitle");
-
-        // because it may reference something else, we resolve it.
-        value = context.resolveResValue(value);
-
-        // if there's a value and it's true (default is false)
-        if (value == null || value.getValue() == null ||
-                XmlUtils.convertValueToBoolean(value.getValue(), false /* defValue */) == false) {
-            // default size of the window title bar
-            int defaultOffset = DEFAULT_TITLE_BAR_HEIGHT;
-
-            // get value from the theme.
-            value = context.findItemInStyle(currentTheme, "windowTitleSize");
-
-            // resolve it
-            value = context.resolveResValue(value);
-
-            if (value != null) {
-                // get the numerical value, if available
-                TypedValue typedValue = ResourceHelper.getValue(value.getValue());
-                if (typedValue != null) {
-                    // compute the pixel value based on the display metrics
-                    defaultOffset = (int)typedValue.getDimension(context.getResources().mMetrics);
-                }
-            }
-
-            offset += defaultOffset;
-        }
-
-        // get the fullscreen flag from the current theme.
-        value = context.findItemInStyle(currentTheme, "windowFullscreen");
-
-        // because it may reference something else, we resolve it.
-        value = context.resolveResValue(value);
-
-        if (value == null || value.getValue() == null ||
-                XmlUtils.convertValueToBoolean(value.getValue(), false /* defValue */) == false) {
-
-            // default value
-            int defaultOffset = DEFAULT_STATUS_BAR_HEIGHT;
-
-            // get the real value, first the list of Dimensions from the framework map
-            Map<String, IResourceValue> dimens = frameworkResources.get(BridgeConstants.RES_DIMEN);
-
-            // now get the value
-            value = dimens.get("status_bar_height");
-            if (value != null) {
-                TypedValue typedValue = ResourceHelper.getValue(value.getValue());
-                if (typedValue != null) {
-                    // compute the pixel value based on the display metrics
-                    defaultOffset = (int)typedValue.getDimension(context.getResources().mMetrics);
-                }
-            }
-
-            // add the computed offset.
-            offset += defaultOffset;
-        }
-
-        return offset;
-    }
-
-    /**
-     * Post process on a view hierachy that was just inflated.
-     * <p/>At the moment this only support TabHost: If {@link TabHost} is detected, look for the
-     * {@link TabWidget}, and the corresponding {@link FrameLayout} and make new tabs automatically
-     * based on the content of the {@link FrameLayout}.
-     * @param view the root view to process.
-     * @param projectCallback callback to the project.
-     */
-    private void postInflateProcess(View view, IProjectCallback projectCallback)
-            throws PostInflateException {
-        if (view instanceof TabHost) {
-            setupTabHost((TabHost)view, projectCallback);
-        } else if (view instanceof ViewGroup) {
-            ViewGroup group = (ViewGroup)view;
-            final int count = group.getChildCount();
-            for (int c = 0 ; c < count ; c++) {
-                View child = group.getChildAt(c);
-                postInflateProcess(child, projectCallback);
-            }
-        }
-    }
-
-    /**
-     * Sets up a {@link TabHost} object.
-     * @param tabHost the TabHost to setup.
-     * @param projectCallback The project callback object to access the project R class.
-     * @throws PostInflateException
-     */
-    private void setupTabHost(TabHost tabHost, IProjectCallback projectCallback)
-            throws PostInflateException {
-        // look for the TabWidget, and the FrameLayout. They have their own specific names
-        View v = tabHost.findViewById(android.R.id.tabs);
-
-        if (v == null) {
-            throw new PostInflateException(
-                    "TabHost requires a TabWidget with id \"android:id/tabs\".\n");
-        }
-
-        if ((v instanceof TabWidget) == false) {
-            throw new PostInflateException(String.format(
-                    "TabHost requires a TabWidget with id \"android:id/tabs\".\n" +
-                    "View found with id 'tabs' is '%s'", v.getClass().getCanonicalName()));
-        }
-
-        v = tabHost.findViewById(android.R.id.tabcontent);
-
-        if (v == null) {
-            // TODO: see if we can fake tabs even without the FrameLayout (same below when the framelayout is empty)
-            throw new PostInflateException(
-                    "TabHost requires a FrameLayout with id \"android:id/tabcontent\".");
-        }
-
-        if ((v instanceof FrameLayout) == false) {
-            throw new PostInflateException(String.format(
-                    "TabHost requires a FrameLayout with id \"android:id/tabcontent\".\n" +
-                    "View found with id 'tabcontent' is '%s'", v.getClass().getCanonicalName()));
-        }
-
-        FrameLayout content = (FrameLayout)v;
-
-        // now process the content of the framelayout and dynamically create tabs for it.
-        final int count = content.getChildCount();
-
-        if (count == 0) {
-            throw new PostInflateException(
-                    "The FrameLayout for the TabHost has no content. Rendering failed.\n");
-        }
-
-        // this must be called before addTab() so that the TabHost searches its TabWidget
-        // and FrameLayout.
-        tabHost.setup();
-
-        // for each child of the framelayout, add a new TabSpec
-        for (int i = 0 ; i < count ; i++) {
-            View child = content.getChildAt(i);
-            String tabSpec = String.format("tab_spec%d", i+1);
-            int id = child.getId();
-            String[] resource = projectCallback.resolveResourceValue(id);
-            String name;
-            if (resource != null) {
-                name = resource[0]; // 0 is resource name, 1 is resource type.
-            } else {
-                name = String.format("Tab %d", i+1); // default name if id is unresolved.
-            }
-            tabHost.addTab(tabHost.newTabSpec(tabSpec).setIndicator(name).setContent(id));
-        }
+    public static Map<String, String> getPlatformProperties() {
+        return sPlatformProperties;
     }
 
     /**
@@ -888,7 +505,7 @@
      * @param projectKey the key of the project, or null to query the framework cache.
      * @return the cached Bitmap or null if not found.
      */
-    static Bitmap getCachedBitmap(String value, Object projectKey) {
+    public static Bitmap getCachedBitmap(String value, Object projectKey) {
         if (projectKey != null) {
             Map<String, SoftReference<Bitmap>> map = sProjectBitmapCache.get(projectKey);
             if (map != null) {
@@ -913,7 +530,7 @@
      * @param bmp the Bitmap object
      * @param projectKey the key of the project, or null to put the bitmap in the framework cache.
      */
-    static void setCachedBitmap(String value, Bitmap bmp, Object projectKey) {
+    public static void setCachedBitmap(String value, Bitmap bmp, Object projectKey) {
         if (projectKey != null) {
             Map<String, SoftReference<Bitmap>> map = sProjectBitmapCache.get(projectKey);
 
@@ -929,24 +546,24 @@
     }
 
     /**
-     * Returns the 9 patch for a specific path, from a specific project cache, or from the
+     * Returns the 9 patch chunk for a specific path, from a specific project cache, or from the
      * framework cache.
      * @param value the path of the 9 patch
      * @param projectKey the key of the project, or null to query the framework cache.
      * @return the cached 9 patch or null if not found.
      */
-    static NinePatch getCached9Patch(String value, Object projectKey) {
+    public static NinePatchChunk getCached9Patch(String value, Object projectKey) {
         if (projectKey != null) {
-            Map<String, SoftReference<NinePatch>> map = sProject9PatchCache.get(projectKey);
+            Map<String, SoftReference<NinePatchChunk>> map = sProject9PatchCache.get(projectKey);
 
             if (map != null) {
-                SoftReference<NinePatch> ref = map.get(value);
+                SoftReference<NinePatchChunk> ref = map.get(value);
                 if (ref != null) {
                     return ref.get();
                 }
             }
         } else {
-            SoftReference<NinePatch> ref = sFramework9PatchCache.get(value);
+            SoftReference<NinePatchChunk> ref = sFramework9PatchCache.get(value);
             if (ref != null) {
                 return ref.get();
             }
@@ -956,224 +573,25 @@
     }
 
     /**
-     * Sets a 9 patch in a project cache or in the framework cache.
+     * Sets a 9 patch chunk in a project cache or in the framework cache.
      * @param value the path of the 9 patch
      * @param ninePatch the 9 patch object
      * @param projectKey the key of the project, or null to put the bitmap in the framework cache.
      */
-    static void setCached9Patch(String value, NinePatch ninePatch, Object projectKey) {
+    public static void setCached9Patch(String value, NinePatchChunk ninePatch, Object projectKey) {
         if (projectKey != null) {
-            Map<String, SoftReference<NinePatch>> map = sProject9PatchCache.get(projectKey);
+            Map<String, SoftReference<NinePatchChunk>> map = sProject9PatchCache.get(projectKey);
 
             if (map == null) {
-                map = new HashMap<String, SoftReference<NinePatch>>();
+                map = new HashMap<String, SoftReference<NinePatchChunk>>();
                 sProject9PatchCache.put(projectKey, map);
             }
 
-            map.put(value, new SoftReference<NinePatch>(ninePatch));
+            map.put(value, new SoftReference<NinePatchChunk>(ninePatch));
         } else {
-            sFramework9PatchCache.put(value, new SoftReference<NinePatch>(ninePatch));
+            sFramework9PatchCache.put(value, new SoftReference<NinePatchChunk>(ninePatch));
         }
     }
 
-    private static final class PostInflateException extends Exception {
-        private static final long serialVersionUID = 1L;
-
-        public PostInflateException(String message) {
-            super(message);
-        }
-    }
-
-    /**
-     * Implementation of {@link IWindowSession} so that mSession is not null in
-     * the {@link SurfaceView}.
-     */
-    private static final class WindowSession implements IWindowSession {
-
-        @SuppressWarnings("unused")
-        public int add(IWindow arg0, LayoutParams arg1, int arg2, Rect arg3,
-                InputChannel outInputchannel)
-                throws RemoteException {
-            // pass for now.
-            return 0;
-        }
-
-        @SuppressWarnings("unused")
-        public int addWithoutInputChannel(IWindow arg0, LayoutParams arg1, int arg2, Rect arg3)
-                throws RemoteException {
-            // pass for now.
-            return 0;
-        }
-        
-        @SuppressWarnings("unused")
-        public void finishDrawing(IWindow arg0) throws RemoteException {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public void finishKey(IWindow arg0) throws RemoteException {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public boolean getInTouchMode() throws RemoteException {
-            // pass for now.
-            return false;
-        }
-
-        @SuppressWarnings("unused")
-        public boolean performHapticFeedback(IWindow window, int effectId, boolean always) {
-            // pass for now.
-            return false;
-        }
-
-        @SuppressWarnings("unused")
-        public MotionEvent getPendingPointerMove(IWindow arg0) throws RemoteException {
-            // pass for now.
-            return null;
-        }
-
-        @SuppressWarnings("unused")
-        public MotionEvent getPendingTrackballMove(IWindow arg0) throws RemoteException {
-            // pass for now.
-            return null;
-        }
-
-        @SuppressWarnings("unused")
-        public int relayout(IWindow arg0, LayoutParams arg1, int arg2, int arg3, int arg4,
-                boolean arg4_5, Rect arg5, Rect arg6, Rect arg7, Configuration arg7b, Surface arg8)
-                throws RemoteException {
-            // pass for now.
-            return 0;
-        }
-
-        public void getDisplayFrame(IWindow window, Rect outDisplayFrame) {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public void remove(IWindow arg0) throws RemoteException {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public void setInTouchMode(boolean arg0) throws RemoteException {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public void setTransparentRegion(IWindow arg0, Region arg1) throws RemoteException {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public void setInsets(IWindow window, int touchable, Rect contentInsets,
-                Rect visibleInsets) {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public void setWallpaperPosition(IBinder window, float x, float y,
-            float xStep, float yStep) {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public void wallpaperOffsetsComplete(IBinder window) {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public Bundle sendWallpaperCommand(IBinder window, String action, int x, int y,
-                int z, Bundle extras, boolean sync) {
-            // pass for now.
-            return null;
-        }
-
-        @SuppressWarnings("unused")
-        public void wallpaperCommandComplete(IBinder window, Bundle result) {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public void closeSystemDialogs(String reason) {
-            // pass for now.
-        }
-
-        public IBinder asBinder() {
-            // pass for now.
-            return null;
-        }
-    }
-
-    /**
-     * Implementation of {@link IWindow} to pass to the {@link AttachInfo}.
-     */
-    private static final class Window implements IWindow {
-
-        @SuppressWarnings("unused")
-        public void dispatchAppVisibility(boolean arg0) throws RemoteException {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public void dispatchGetNewSurface() throws RemoteException {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public void dispatchKey(KeyEvent arg0) throws RemoteException {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public void dispatchPointer(MotionEvent arg0, long arg1, boolean arg2) throws RemoteException {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public void dispatchTrackball(MotionEvent arg0, long arg1, boolean arg2) throws RemoteException {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public void executeCommand(String arg0, String arg1, ParcelFileDescriptor arg2)
-                throws RemoteException {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public void resized(int arg0, int arg1, Rect arg2, Rect arg3, boolean arg4, Configuration arg5)
-                throws RemoteException {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public void windowFocusChanged(boolean arg0, boolean arg1) throws RemoteException {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
-                boolean sync) {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public void dispatchWallpaperCommand(String action, int x, int y,
-                int z, Bundle extras, boolean sync) {
-            // pass for now.
-        }
-
-        @SuppressWarnings("unused")
-        public void closeSystemDialogs(String reason) {
-            // pass for now.
-        }
-
-        public IBinder asBinder() {
-            // pass for now.
-            return null;
-        }
-    }
 
 }
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeConstants.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeConstants.java
index 791e53b..112af1e 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeConstants.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeConstants.java
@@ -41,24 +41,6 @@
 
     public final static String R = "com.android.internal.R";
 
-    public final static String PREFIX_ANDROID_RESOURCE_REF = "@android:";
-    public final static String PREFIX_RESOURCE_REF = "@";
-    public final static String PREFIX_ANDROID_THEME_REF = "?android:";
-    public final static String PREFIX_THEME_REF = "?";
-
-    public final static String PREFIX_ANDROID = "android:";
-
-    public final static String RES_STYLE = "style";
-    public final static String RES_ATTR = "attr";
-    public final static String RES_DIMEN = "dimen";
-    public final static String RES_DRAWABLE = "drawable";
-    public final static String RES_COLOR = "color";
-    public final static String RES_LAYOUT = "layout";
-    public final static String RES_STRING = "string";
-    public final static String RES_ID = "id";
-
-    public final static String REFERENCE_STYLE = RES_STYLE + "/";
-    public final static String REFERENCE_NULL = "@null";
 
     public final static String MATCH_PARENT = "match_parent";
     public final static String FILL_PARENT = "fill_parent";
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeContentResolver.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeContentResolver.java
deleted file mode 100644
index 20ccc0b..0000000
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeContentResolver.java
+++ /dev/null
@@ -1,190 +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 com.android.layoutlib.bridge;
-
-import android.content.ContentProviderOperation;
-import android.content.ContentProviderResult;
-import android.content.ContentResolver;
-import android.content.ContentValues;
-import android.content.Context;
-import android.content.IContentProvider;
-import android.content.OperationApplicationException;
-import android.content.res.AssetFileDescriptor;
-import android.database.ContentObserver;
-import android.database.Cursor;
-import android.database.CursorWindow;
-import android.database.IBulkCursor;
-import android.database.IContentObserver;
-import android.net.Uri;
-import android.os.Bundle;
-import android.os.IBinder;
-import android.os.ParcelFileDescriptor;
-import android.os.RemoteException;
-
-import java.io.FileNotFoundException;
-import java.util.ArrayList;
-
-/**
- * A mock content resolver for the LayoutLib Bridge.
- * <p/>
- * It won't serve any actual data but it's good enough for all
- * the widgets which expect to have a content resolver available via
- * {@link BridgeContext#getContentResolver()}.
- */
-public class BridgeContentResolver extends ContentResolver {
-
-    private BridgeContentProvider mProvider = null;
-
-    public static final class BridgeContentProvider implements IContentProvider {
-
-        public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> arg0)
-                throws RemoteException, OperationApplicationException {
-            // TODO Auto-generated method stub
-            return null;
-        }
-
-        public int bulkInsert(Uri arg0, ContentValues[] arg1) throws RemoteException {
-            // TODO Auto-generated method stub
-            return 0;
-        }
-
-        public IBulkCursor bulkQuery(Uri arg0, String[] arg1, String arg2, String[] arg3,
-                String arg4, IContentObserver arg5, CursorWindow arg6) throws RemoteException {
-            // TODO Auto-generated method stub
-            return null;
-        }
-
-        public Bundle call(String arg0, String arg1, Bundle arg2) throws RemoteException {
-            // TODO Auto-generated method stub
-            return null;
-        }
-
-        public int delete(Uri arg0, String arg1, String[] arg2) throws RemoteException {
-            // TODO Auto-generated method stub
-            return 0;
-        }
-
-        public String getType(Uri arg0) throws RemoteException {
-            // TODO Auto-generated method stub
-            return null;
-        }
-
-        public Uri insert(Uri arg0, ContentValues arg1) throws RemoteException {
-            // TODO Auto-generated method stub
-            return null;
-        }
-
-        public AssetFileDescriptor openAssetFile(Uri arg0, String arg1) throws RemoteException,
-                FileNotFoundException {
-            // TODO Auto-generated method stub
-            return null;
-        }
-
-        public ParcelFileDescriptor openFile(Uri arg0, String arg1) throws RemoteException,
-                FileNotFoundException {
-            // TODO Auto-generated method stub
-            return null;
-        }
-
-        public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3, String arg4)
-                throws RemoteException {
-            // TODO Auto-generated method stub
-            return null;
-        }
-
-        public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3)
-                throws RemoteException {
-            // TODO Auto-generated method stub
-            return 0;
-        }
-
-        public IBinder asBinder() {
-            // TODO Auto-generated method stub
-            return null;
-        }
-
-    }
-
-    public BridgeContentResolver(Context context) {
-        super(context);
-    }
-
-    @Override
-    public IContentProvider acquireProvider(Context c, String name) {
-        if (mProvider == null) {
-            mProvider = new BridgeContentProvider();
-        }
-
-        return mProvider;
-    }
-
-    @Override
-    public IContentProvider acquireExistingProvider(Context c, String name) {
-        if (mProvider == null) {
-            mProvider = new BridgeContentProvider();
-        }
-
-        return mProvider;
-    }
-
-    @Override
-    public boolean releaseProvider(IContentProvider icp) {
-        // ignore
-        return false;
-    }
-
-    /**
-     * Stub for the layoutlib bridge content resolver.
-     */
-    @Override
-    public void registerContentObserver(Uri uri, boolean notifyForDescendents,
-            ContentObserver observer) {
-        // pass
-    }
-
-    /**
-     * Stub for the layoutlib bridge content resolver.
-     */
-    @Override
-    public void unregisterContentObserver(ContentObserver observer) {
-        // pass
-    }
-
-    /**
-     * Stub for the layoutlib bridge content resolver.
-     */
-    @Override
-    public void notifyChange(Uri uri, ContentObserver observer, boolean syncToNetwork) {
-        // pass
-    }
-
-    /**
-     * Stub for the layoutlib bridge content resolver.
-     */
-    @Override
-    public void startSync(Uri uri, Bundle extras) {
-        // pass
-    }
-
-    /**
-     * Stub for the layoutlib bridge content resolver.
-     */
-    @Override
-    public void cancelSync(Uri uri) {
-        // pass
-    }
-}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeContext.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeContext.java
deleted file mode 100644
index ecd22e2..0000000
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeContext.java
+++ /dev/null
@@ -1,1207 +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 com.android.layoutlib.bridge;
-
-import com.android.layoutlib.api.ILayoutLog;
-import com.android.layoutlib.api.IProjectCallback;
-import com.android.layoutlib.api.IResourceValue;
-import com.android.layoutlib.api.IStyleResourceValue;
-
-import android.content.BroadcastReceiver;
-import android.content.ComponentName;
-import android.content.ContentResolver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.IntentSender;
-import android.content.ServiceConnection;
-import android.content.SharedPreferences;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageManager;
-import android.content.res.AssetManager;
-import android.content.res.Configuration;
-import android.content.res.Resources;
-import android.content.res.TypedArray;
-import android.content.res.Resources.Theme;
-import android.database.sqlite.SQLiteDatabase;
-import android.database.sqlite.SQLiteDatabase.CursorFactory;
-import android.graphics.Bitmap;
-import android.graphics.drawable.Drawable;
-import android.net.Uri;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Looper;
-import android.util.AttributeSet;
-import android.util.DisplayMetrics;
-import android.view.BridgeInflater;
-import android.view.View;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.TreeMap;
-import java.util.Map.Entry;
-
-/**
- * Custom implementation of Context to handle non compiled resources.
- */
-public final class BridgeContext extends Context {
-
-    private final Resources mResources;
-    private final Theme mTheme;
-    private final HashMap<View, Object> mViewKeyMap = new HashMap<View, Object>();
-    private final IStyleResourceValue mThemeValues;
-    private final Object mProjectKey;
-    private final Map<String, Map<String, IResourceValue>> mProjectResources;
-    private final Map<String, Map<String, IResourceValue>> mFrameworkResources;
-    private final Map<IStyleResourceValue, IStyleResourceValue> mStyleInheritanceMap;
-
-    // maps for dynamically generated id representing style objects (IStyleResourceValue)
-    private Map<Integer, IStyleResourceValue> mDynamicIdToStyleMap;
-    private Map<IStyleResourceValue, Integer> mStyleToDynamicIdMap;
-    private int mDynamicIdGenerator = 0x01030000; // Base id for framework R.style
-
-    // cache for TypedArray generated from IStyleResourceValue object
-    private Map<int[], Map<Integer, TypedArray>> mTypedArrayCache;
-    private BridgeInflater mInflater;
-
-    private final IProjectCallback mProjectCallback;
-    private final ILayoutLog mLogger;
-    private BridgeContentResolver mContentResolver;
-
-    /**
-     * @param projectKey An Object identifying the project. This is used for the cache mechanism.
-     * @param metrics the {@link DisplayMetrics}.
-     * @param themeName The name of the theme to use.
-     * @param projectResources the resources of the project. The map contains (String, map) pairs
-     * where the string is the type of the resource reference used in the layout file, and the
-     * map contains (String, {@link IResourceValue}) pairs where the key is the resource name,
-     * and the value is the resource value.
-     * @param frameworkResources the framework resources. The map contains (String, map) pairs
-     * where the string is the type of the resource reference used in the layout file, and the map
-     * contains (String, {@link IResourceValue}) pairs where the key is the resource name, and the
-     * value is the resource value.
-     * @param styleInheritanceMap
-     * @param customViewLoader
-     */
-    public BridgeContext(Object projectKey, DisplayMetrics metrics,
-            IStyleResourceValue currentTheme,
-            Map<String, Map<String, IResourceValue>> projectResources,
-            Map<String, Map<String, IResourceValue>> frameworkResources,
-            Map<IStyleResourceValue, IStyleResourceValue> styleInheritanceMap,
-            IProjectCallback customViewLoader, ILayoutLog logger) {
-        mProjectKey = projectKey;
-        mProjectCallback = customViewLoader;
-        mLogger = logger;
-        Configuration config = new Configuration();
-
-        AssetManager assetManager = BridgeAssetManager.initSystem();
-        mResources = BridgeResources.initSystem(
-                this,
-                assetManager,
-                metrics,
-                config,
-                customViewLoader);
-
-        mTheme = mResources.newTheme();
-
-        mThemeValues = currentTheme;
-        mProjectResources = projectResources;
-        mFrameworkResources = frameworkResources;
-        mStyleInheritanceMap = styleInheritanceMap;
-    }
-
-    public void setBridgeInflater(BridgeInflater inflater) {
-        mInflater = inflater;
-    }
-
-    public void addViewKey(View view, Object viewKey) {
-        mViewKeyMap.put(view, viewKey);
-    }
-
-    public Object getViewKey(View view) {
-        return mViewKeyMap.get(view);
-    }
-
-    public Object getProjectKey() {
-        return mProjectKey;
-    }
-
-    public IProjectCallback getProjectCallback() {
-        return mProjectCallback;
-    }
-
-    public ILayoutLog getLogger() {
-        return mLogger;
-    }
-
-    // ------------ Context methods
-
-    @Override
-    public Resources getResources() {
-        return mResources;
-    }
-
-    @Override
-    public Theme getTheme() {
-        return mTheme;
-    }
-
-    @Override
-    public ClassLoader getClassLoader() {
-        return this.getClass().getClassLoader();
-    }
-
-    @Override
-    public Object getSystemService(String service) {
-        if (LAYOUT_INFLATER_SERVICE.equals(service)) {
-            return mInflater;
-        }
-
-        // AutoCompleteTextView and MultiAutoCompleteTextView want a window
-        // service. We don't have any but it's not worth an exception.
-        if (WINDOW_SERVICE.equals(service)) {
-            return null;
-        }
-
-        throw new UnsupportedOperationException("Unsupported Service: " + service);
-    }
-
-
-    @Override
-    public final TypedArray obtainStyledAttributes(int[] attrs) {
-        return createStyleBasedTypedArray(mThemeValues, attrs);
-    }
-
-    @Override
-    public final TypedArray obtainStyledAttributes(int resid, int[] attrs)
-            throws Resources.NotFoundException {
-        // get the IStyleResourceValue based on the resId;
-        IStyleResourceValue style = getStyleByDynamicId(resid);
-
-        if (style == null) {
-            throw new Resources.NotFoundException();
-        }
-
-        if (mTypedArrayCache == null) {
-            mTypedArrayCache = new HashMap<int[], Map<Integer,TypedArray>>();
-
-            Map<Integer, TypedArray> map = new HashMap<Integer, TypedArray>();
-            mTypedArrayCache.put(attrs, map);
-
-            BridgeTypedArray ta = createStyleBasedTypedArray(style, attrs);
-            map.put(resid, ta);
-
-            return ta;
-        }
-
-        // get the 2nd map
-        Map<Integer, TypedArray> map = mTypedArrayCache.get(attrs);
-        if (map == null) {
-            map = new HashMap<Integer, TypedArray>();
-            mTypedArrayCache.put(attrs, map);
-        }
-
-        // get the array from the 2nd map
-        TypedArray ta = map.get(resid);
-
-        if (ta == null) {
-            ta = createStyleBasedTypedArray(style, attrs);
-            map.put(resid, ta);
-        }
-
-        return ta;
-    }
-
-    @Override
-    public final TypedArray obtainStyledAttributes(AttributeSet set, int[] attrs) {
-        return obtainStyledAttributes(set, attrs, 0, 0);
-    }
-
-    @Override
-    public TypedArray obtainStyledAttributes(AttributeSet set, int[] attrs,
-            int defStyleAttr, int defStyleRes) {
-
-        // Hint: for XmlPullParser, attach source //DEVICE_SRC/dalvik/libcore/xml/src/java
-        BridgeXmlBlockParser parser = null;
-        if (set instanceof BridgeXmlBlockParser) {
-            parser = (BridgeXmlBlockParser)set;
-        } else if (set != null) { // null parser is ok
-            // really this should not be happening since its instantiated in Bridge
-            mLogger.error("Parser is not a BridgeXmlBlockParser!");
-            return null;
-        }
-
-        boolean[] frameworkAttributes = new boolean[1];
-        TreeMap<Integer, String> styleNameMap = searchAttrs(attrs, frameworkAttributes);
-
-        BridgeTypedArray ta = ((BridgeResources) mResources).newTypeArray(attrs.length,
-                parser != null ? parser.isPlatformFile() : true);
-
-        // resolve the defStyleAttr value into a IStyleResourceValue
-        IStyleResourceValue defStyleValues = null;
-
-        // look for a custom style.
-        String customStyle = null;
-        if (parser != null) {
-            customStyle = parser.getAttributeValue(null /* namespace*/, "style");
-        }
-        if (customStyle != null) {
-            IResourceValue item = findResValue(customStyle, false /*forceFrameworkOnly*/);
-
-            if (item instanceof IStyleResourceValue) {
-                defStyleValues = (IStyleResourceValue)item;
-            }
-        }
-
-        if (defStyleValues == null && defStyleAttr != 0) {
-            // get the name from the int.
-            String defStyleName = searchAttr(defStyleAttr);
-
-            // look for the style in the current theme, and its parent:
-            if (mThemeValues != null) {
-                IResourceValue item = findItemInStyle(mThemeValues, defStyleName);
-
-                if (item != null) {
-                    // item is a reference to a style entry. Search for it.
-                    item = findResValue(item.getValue(), false /*forceFrameworkOnly*/);
-
-                    if (item instanceof IStyleResourceValue) {
-                        defStyleValues = (IStyleResourceValue)item;
-                    }
-                } else {
-                    // TODO: log the error properly
-                    System.out.println("Failed to find defStyle: " + defStyleName);
-                }
-            }
-        }
-
-        if (defStyleRes != 0) {
-            // FIXME: See what we need to do with this.
-            throw new UnsupportedOperationException();
-        }
-
-        String namespace = BridgeConstants.NS_RESOURCES;
-        if (frameworkAttributes[0] == false) {
-            // need to use the application namespace
-            namespace = mProjectCallback.getNamespace();
-        }
-
-        if (styleNameMap != null) {
-            for (Entry<Integer, String> styleAttribute : styleNameMap.entrySet()) {
-                int index = styleAttribute.getKey().intValue();
-
-                String name = styleAttribute.getValue();
-                String value = null;
-                if (parser != null) {
-                    value = parser.getAttributeValue(namespace, name);
-                }
-
-                // if there's no direct value for this attribute in the XML, we look for default
-                // values in the widget defStyle, and then in the theme.
-                if (value == null) {
-                    IResourceValue resValue = null;
-
-                    // look for the value in the defStyle first (and its parent if needed)
-                    if (defStyleValues != null) {
-                        resValue = findItemInStyle(defStyleValues, name);
-                    }
-
-                    // if the item is not present in the defStyle, we look in the main theme (and
-                    // its parent themes)
-                    if (resValue == null && mThemeValues != null) {
-                        resValue = findItemInStyle(mThemeValues, name);
-                    }
-
-                    // if we found a value, we make sure this doesn't reference another value.
-                    // So we resolve it.
-                    if (resValue != null) {
-                        resValue = resolveResValue(resValue);
-                    }
-
-                    ta.bridgeSetValue(index, name, resValue);
-                } else {
-                    // there is a value in the XML, but we need to resolve it in case it's
-                    // referencing another resource or a theme value.
-                    ta.bridgeSetValue(index, name, resolveValue(null, name, value));
-                }
-            }
-        }
-
-        ta.sealArray();
-
-        return ta;
-    }
-
-    @Override
-    public Looper getMainLooper() {
-        return Looper.myLooper();
-    }
-
-
-    // ------------- private new methods
-
-    /**
-     * Creates a {@link BridgeTypedArray} by filling the values defined by the int[] with the
-     * values found in the given style.
-     * @see #obtainStyledAttributes(int, int[])
-     */
-    private BridgeTypedArray createStyleBasedTypedArray(IStyleResourceValue style, int[] attrs)
-            throws Resources.NotFoundException {
-        TreeMap<Integer, String> styleNameMap = searchAttrs(attrs, null);
-
-        BridgeTypedArray ta = ((BridgeResources) mResources).newTypeArray(attrs.length,
-                false /* platformResourceFlag */);
-
-        // loop through all the values in the style map, and init the TypedArray with
-        // the style we got from the dynamic id
-        for (Entry<Integer, String> styleAttribute : styleNameMap.entrySet()) {
-            int index = styleAttribute.getKey().intValue();
-
-            String name = styleAttribute.getValue();
-
-            // get the value from the style, or its parent styles.
-            IResourceValue resValue = findItemInStyle(style, name);
-
-            // resolve it to make sure there are no references left.
-            ta.bridgeSetValue(index, name, resolveResValue(resValue));
-        }
-
-        ta.sealArray();
-
-        return ta;
-    }
-
-
-    /**
-     * Resolves the value of a resource, if the value references a theme or resource value.
-     * <p/>
-     * This method ensures that it returns a {@link IResourceValue} object that does not
-     * reference another resource.
-     * If the resource cannot be resolved, it returns <code>null</code>.
-     * <p/>
-     * If a value that does not need to be resolved is given, the method will return a new
-     * instance of IResourceValue that contains the input value.
-     *
-     * @param type the type of the resource
-     * @param name the name of the attribute containing this value.
-     * @param value the resource value, or reference to resolve
-     * @return the resolved resource value or <code>null</code> if it failed to resolve it.
-     */
-    private IResourceValue resolveValue(String type, String name, String value) {
-        if (value == null) {
-            return null;
-        }
-
-        // get the IResourceValue referenced by this value
-        IResourceValue resValue = findResValue(value, false /*forceFrameworkOnly*/);
-
-        // if resValue is null, but value is not null, this means it was not a reference.
-        // we return the name/value wrapper in a IResourceValue
-        if (resValue == null) {
-            return new ResourceValue(type, name, value);
-        }
-
-        // we resolved a first reference, but we need to make sure this isn't a reference also.
-        return resolveResValue(resValue);
-    }
-
-    /**
-     * Returns the {@link IResourceValue} referenced by the value of <var>value</var>.
-     * <p/>
-     * This method ensures that it returns a {@link IResourceValue} object that does not
-     * reference another resource.
-     * If the resource cannot be resolved, it returns <code>null</code>.
-     * <p/>
-     * If a value that does not need to be resolved is given, the method will return the input
-     * value.
-     *
-     * @param value the value containing the reference to resolve.
-     * @return a {@link IResourceValue} object or <code>null</code>
-     */
-    IResourceValue resolveResValue(IResourceValue value) {
-        if (value == null) {
-            return null;
-        }
-
-        // if the resource value is a style, we simply return it.
-        if (value instanceof IStyleResourceValue) {
-            return value;
-        }
-
-        // else attempt to find another IResourceValue referenced by this one.
-        IResourceValue resolvedValue = findResValue(value.getValue(), value.isFramework());
-
-        // if the value did not reference anything, then we simply return the input value
-        if (resolvedValue == null) {
-            return value;
-        }
-
-        // otherwise, we attempt to resolve this new value as well
-        return resolveResValue(resolvedValue);
-    }
-
-    /**
-     * Searches for, and returns a {@link IResourceValue} by its reference.
-     * <p/>
-     * The reference format can be:
-     * <pre>@resType/resName</pre>
-     * <pre>@android:resType/resName</pre>
-     * <pre>@resType/android:resName</pre>
-     * <pre>?resType/resName</pre>
-     * <pre>?android:resType/resName</pre>
-     * <pre>?resType/android:resName</pre>
-     * Any other string format will return <code>null</code>.
-     * <p/>
-     * The actual format of a reference is <pre>@[namespace:]resType/resName</pre> but this method
-     * only support the android namespace.
-     *
-     * @param reference the resource reference to search for.
-     * @param forceFrameworkOnly if true all references are considered to be toward framework
-     *      resource even if the reference does not include the android: prefix.
-     * @return a {@link IResourceValue} or <code>null</code>.
-     */
-    IResourceValue findResValue(String reference, boolean forceFrameworkOnly) {
-        if (reference == null) {
-            return null;
-        }
-        if (reference.startsWith(BridgeConstants.PREFIX_THEME_REF)) {
-            // no theme? no need to go further!
-            if (mThemeValues == null) {
-                return null;
-            }
-
-            boolean frameworkOnly = false;
-
-            // eleminate the prefix from the string
-            if (reference.startsWith(BridgeConstants.PREFIX_ANDROID_THEME_REF)) {
-                frameworkOnly = true;
-                reference = reference.substring(BridgeConstants.PREFIX_ANDROID_THEME_REF.length());
-            } else {
-                reference = reference.substring(BridgeConstants.PREFIX_THEME_REF.length());
-            }
-
-            // at this point, value can contain type/name (drawable/foo for instance).
-            // split it to make sure.
-            String[] segments = reference.split("\\/");
-
-            // we look for the referenced item name.
-            String referenceName = null;
-
-            if (segments.length == 2) {
-                // there was a resType in the reference. If it's attr, we ignore it
-                // else, we assert for now.
-                if (BridgeConstants.RES_ATTR.equals(segments[0])) {
-                    referenceName = segments[1];
-                } else {
-                    // At this time, no support for ?type/name where type is not "attr"
-                    return null;
-                }
-            } else {
-                // it's just an item name.
-                referenceName = segments[0];
-            }
-
-            // now we look for android: in the referenceName in order to support format
-            // such as: ?attr/android:name
-            if (referenceName.startsWith(BridgeConstants.PREFIX_ANDROID)) {
-                frameworkOnly = true;
-                referenceName = referenceName.substring(BridgeConstants.PREFIX_ANDROID.length());
-            }
-
-            // Now look for the item in the theme, starting with the current one.
-            if (frameworkOnly) {
-                // FIXME for now we do the same as if it didn't specify android:
-                return findItemInStyle(mThemeValues, referenceName);
-            }
-
-            return findItemInStyle(mThemeValues, referenceName);
-        } else if (reference.startsWith(BridgeConstants.PREFIX_RESOURCE_REF)) {
-            boolean frameworkOnly = false;
-
-            // check for the specific null reference value.
-            if (BridgeConstants.REFERENCE_NULL.equals(reference)) {
-                return null;
-            }
-
-            // Eliminate the prefix from the string.
-            if (reference.startsWith(BridgeConstants.PREFIX_ANDROID_RESOURCE_REF)) {
-                frameworkOnly = true;
-                reference = reference.substring(
-                        BridgeConstants.PREFIX_ANDROID_RESOURCE_REF.length());
-            } else {
-                reference = reference.substring(BridgeConstants.PREFIX_RESOURCE_REF.length());
-            }
-
-            // at this point, value contains type/[android:]name (drawable/foo for instance)
-            String[] segments = reference.split("\\/");
-
-            // now we look for android: in the resource name in order to support format
-            // such as: @drawable/android:name
-            if (segments[1].startsWith(BridgeConstants.PREFIX_ANDROID)) {
-                frameworkOnly = true;
-                segments[1] = segments[1].substring(BridgeConstants.PREFIX_ANDROID.length());
-            }
-
-            return findResValue(segments[0], segments[1],
-                    forceFrameworkOnly ? true :frameworkOnly);
-        }
-
-        // Looks like the value didn't reference anything. Return null.
-        return null;
-    }
-
-    /**
-     * Searches for, and returns a {@link IResourceValue} by its name, and type.
-     * @param resType the type of the resource
-     * @param resName  the name of the resource
-     * @param frameworkOnly if <code>true</code>, the method does not search in the
-     * project resources
-     */
-    private IResourceValue findResValue(String resType, String resName, boolean frameworkOnly) {
-        // map of IResouceValue for the given type
-        Map<String, IResourceValue> typeMap;
-
-        // if allowed, search in the project resources first.
-        if (frameworkOnly == false) {
-            typeMap = mProjectResources.get(resType);
-            if (typeMap != null) {
-                IResourceValue item = typeMap.get(resName);
-                if (item != null) {
-                    return item;
-                }
-            }
-        }
-
-        // now search in the framework resources.
-        typeMap = mFrameworkResources.get(resType);
-        if (typeMap != null) {
-            IResourceValue item = typeMap.get(resName);
-            if (item != null) {
-                return item;
-            }
-        }
-
-        // didn't find the resource anywhere.
-        return null;
-    }
-
-    /**
-     * Returns a framework resource by type and name. The returned resource is resolved.
-     * @param resourceType the type of the resource
-     * @param resourceName the name of the resource
-     */
-    public IResourceValue getFrameworkResource(String resourceType, String resourceName) {
-        return getResource(resourceType, resourceName, mFrameworkResources);
-    }
-
-    /**
-     * Returns a project resource by type and name. The returned resource is resolved.
-     * @param resourceType the type of the resource
-     * @param resourceName the name of the resource
-     */
-    public IResourceValue getProjectResource(String resourceType, String resourceName) {
-        return getResource(resourceType, resourceName, mProjectResources);
-    }
-
-    IResourceValue getResource(String resourceType, String resourceName,
-            Map<String, Map<String, IResourceValue>> resourceRepository) {
-        Map<String, IResourceValue> typeMap = resourceRepository.get(resourceType);
-        if (typeMap != null) {
-            IResourceValue item = typeMap.get(resourceName);
-            if (item != null) {
-                item = resolveResValue(item);
-                return item;
-            }
-        }
-
-        // didn't find the resource anywhere.
-        return null;
-
-    }
-
-    /**
-     * Returns the {@link IResourceValue} matching a given name in a given style. If the
-     * item is not directly available in the style, the method looks in its parent style.
-     * @param style the style to search in
-     * @param itemName the name of the item to search for.
-     * @return the {@link IResourceValue} object or <code>null</code>
-     */
-    IResourceValue findItemInStyle(IStyleResourceValue style, String itemName) {
-        IResourceValue item = style.findItem(itemName);
-
-        // if we didn't find it, we look in the parent style (if applicable)
-        if (item == null && mStyleInheritanceMap != null) {
-            IStyleResourceValue parentStyle = mStyleInheritanceMap.get(style);
-            if (parentStyle != null) {
-                return findItemInStyle(parentStyle, itemName);
-            }
-        }
-
-        return item;
-    }
-
-    /**
-     * The input int[] attrs is one of com.android.internal.R.styleable fields where the name
-     * of the field is the style being referenced and the array contains one index per attribute.
-     * <p/>
-     * searchAttrs() finds all the names of the attributes referenced so for example if
-     * attrs == com.android.internal.R.styleable.View, this returns the list of the "xyz" where
-     * there's a field com.android.internal.R.styleable.View_xyz and the field value is the index
-     * that is used to reference the attribute later in the TypedArray.
-     *
-     * @param attrs An attribute array reference given to obtainStyledAttributes.
-     * @return A sorted map Attribute-Value to Attribute-Name for all attributes declared by the
-     *         attribute array. Returns null if nothing is found.
-     */
-    private TreeMap<Integer,String> searchAttrs(int[] attrs, boolean[] outFrameworkFlag) {
-        // get the name of the array from the framework resources
-        String arrayName = Bridge.resolveResourceValue(attrs);
-        if (arrayName != null) {
-            // if we found it, get the name of each of the int in the array.
-            TreeMap<Integer,String> attributes = new TreeMap<Integer, String>();
-            for (int i = 0 ; i < attrs.length ; i++) {
-                String[] info = Bridge.resolveResourceValue(attrs[i]);
-                if (info != null) {
-                    attributes.put(i, info[0]);
-                } else {
-                    // FIXME Not sure what we should be doing here...
-                    attributes.put(i, null);
-                }
-            }
-
-            if (outFrameworkFlag != null) {
-                outFrameworkFlag[0] = true;
-            }
-
-            return attributes;
-        }
-
-        // if the name was not found in the framework resources, look in the project
-        // resources
-        arrayName = mProjectCallback.resolveResourceValue(attrs);
-        if (arrayName != null) {
-            TreeMap<Integer,String> attributes = new TreeMap<Integer, String>();
-            for (int i = 0 ; i < attrs.length ; i++) {
-                String[] info = mProjectCallback.resolveResourceValue(attrs[i]);
-                if (info != null) {
-                    attributes.put(i, info[0]);
-                } else {
-                    // FIXME Not sure what we should be doing here...
-                    attributes.put(i, null);
-                }
-            }
-
-            if (outFrameworkFlag != null) {
-                outFrameworkFlag[0] = false;
-            }
-
-            return attributes;
-        }
-
-        return null;
-    }
-
-    /**
-     * Searches for the attribute referenced by its internal id.
-     *
-     * @param attr An attribute reference given to obtainStyledAttributes such as defStyle.
-     * @return The unique name of the attribute, if found, e.g. "buttonStyle". Returns null
-     *         if nothing is found.
-     */
-    public String searchAttr(int attr) {
-        String[] info = Bridge.resolveResourceValue(attr);
-        if (info != null) {
-            return info[0];
-        }
-
-        info = mProjectCallback.resolveResourceValue(attr);
-        if (info != null) {
-            return info[0];
-        }
-
-        return null;
-    }
-
-    int getDynamicIdByStyle(IStyleResourceValue resValue) {
-        if (mDynamicIdToStyleMap == null) {
-            // create the maps.
-            mDynamicIdToStyleMap = new HashMap<Integer, IStyleResourceValue>();
-            mStyleToDynamicIdMap = new HashMap<IStyleResourceValue, Integer>();
-        }
-
-        // look for an existing id
-        Integer id = mStyleToDynamicIdMap.get(resValue);
-
-        if (id == null) {
-            // generate a new id
-            id = Integer.valueOf(++mDynamicIdGenerator);
-
-            // and add it to the maps.
-            mDynamicIdToStyleMap.put(id, resValue);
-            mStyleToDynamicIdMap.put(resValue, id);
-        }
-
-        return id;
-    }
-
-    private IStyleResourceValue getStyleByDynamicId(int i) {
-        if (mDynamicIdToStyleMap != null) {
-            return mDynamicIdToStyleMap.get(i);
-        }
-
-        return null;
-    }
-
-    int getFrameworkIdValue(String idName, int defValue) {
-        Integer value = Bridge.getResourceValue(BridgeConstants.RES_ID, idName);
-        if (value != null) {
-            return value.intValue();
-        }
-
-        return defValue;
-    }
-
-    int getProjectIdValue(String idName, int defValue) {
-        if (mProjectCallback != null) {
-            Integer value = mProjectCallback.getResourceValue(BridgeConstants.RES_ID, idName);
-            if (value != null) {
-                return value.intValue();
-            }
-        }
-
-        return defValue;
-    }
-
-    //------------ NOT OVERRIDEN --------------------
-
-    @Override
-    public boolean bindService(Intent arg0, ServiceConnection arg1, int arg2) {
-        // TODO Auto-generated method stub
-        return false;
-    }
-
-    @Override
-    public int checkCallingOrSelfPermission(String arg0) {
-        // TODO Auto-generated method stub
-        return 0;
-    }
-
-    @Override
-    public int checkCallingOrSelfUriPermission(Uri arg0, int arg1) {
-        // TODO Auto-generated method stub
-        return 0;
-    }
-
-    @Override
-    public int checkCallingPermission(String arg0) {
-        // TODO Auto-generated method stub
-        return 0;
-    }
-
-    @Override
-    public int checkCallingUriPermission(Uri arg0, int arg1) {
-        // TODO Auto-generated method stub
-        return 0;
-    }
-
-    @Override
-    public int checkPermission(String arg0, int arg1, int arg2) {
-        // TODO Auto-generated method stub
-        return 0;
-    }
-
-    @Override
-    public int checkUriPermission(Uri arg0, int arg1, int arg2, int arg3) {
-        // TODO Auto-generated method stub
-        return 0;
-    }
-
-    @Override
-    public int checkUriPermission(Uri arg0, String arg1, String arg2, int arg3,
-            int arg4, int arg5) {
-        // TODO Auto-generated method stub
-        return 0;
-    }
-
-    @Override
-    public void clearWallpaper() {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public Context createPackageContext(String arg0, int arg1) {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public String[] databaseList() {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public boolean deleteDatabase(String arg0) {
-        // TODO Auto-generated method stub
-        return false;
-    }
-
-    @Override
-    public boolean deleteFile(String arg0) {
-        // TODO Auto-generated method stub
-        return false;
-    }
-
-    @Override
-    public void enforceCallingOrSelfPermission(String arg0, String arg1) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public void enforceCallingOrSelfUriPermission(Uri arg0, int arg1,
-            String arg2) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public void enforceCallingPermission(String arg0, String arg1) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public void enforceCallingUriPermission(Uri arg0, int arg1, String arg2) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public void enforcePermission(String arg0, int arg1, int arg2, String arg3) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public void enforceUriPermission(Uri arg0, int arg1, int arg2, int arg3,
-            String arg4) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public void enforceUriPermission(Uri arg0, String arg1, String arg2,
-            int arg3, int arg4, int arg5, String arg6) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public String[] fileList() {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public AssetManager getAssets() {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public File getCacheDir() {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public File getExternalCacheDir() {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public ContentResolver getContentResolver() {
-        if (mContentResolver == null) {
-            mContentResolver = new BridgeContentResolver(this);
-        }
-        return mContentResolver;
-    }
-
-    @Override
-    public File getDatabasePath(String arg0) {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public File getDir(String arg0, int arg1) {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public File getFileStreamPath(String arg0) {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public File getFilesDir() {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public File getExternalFilesDir(String type) {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public String getPackageCodePath() {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public PackageManager getPackageManager() {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public String getPackageName() {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public ApplicationInfo getApplicationInfo() {
-        return new ApplicationInfo();
-    }
-
-    @Override
-    public String getPackageResourcePath() {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public File getSharedPrefsFile(String name) {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public SharedPreferences getSharedPreferences(String arg0, int arg1) {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public Drawable getWallpaper() {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public int getWallpaperDesiredMinimumWidth() {
-        return -1;
-    }
-
-    @Override
-    public int getWallpaperDesiredMinimumHeight() {
-        return -1;
-    }
-
-    @Override
-    public void grantUriPermission(String arg0, Uri arg1, int arg2) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @SuppressWarnings("unused")
-    @Override
-    public FileInputStream openFileInput(String arg0)
-            throws FileNotFoundException {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @SuppressWarnings("unused")
-    @Override
-    public FileOutputStream openFileOutput(String arg0, int arg1)
-            throws FileNotFoundException {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public SQLiteDatabase openOrCreateDatabase(String arg0, int arg1,
-            CursorFactory arg2) {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public Drawable peekWallpaper() {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public Intent registerReceiver(BroadcastReceiver arg0, IntentFilter arg1) {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public Intent registerReceiver(BroadcastReceiver arg0, IntentFilter arg1,
-            String arg2, Handler arg3) {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public void removeStickyBroadcast(Intent arg0) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public void revokeUriPermission(Uri arg0, int arg1) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public void sendBroadcast(Intent arg0) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public void sendBroadcast(Intent arg0, String arg1) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public void sendOrderedBroadcast(Intent arg0, String arg1) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public void sendOrderedBroadcast(Intent arg0, String arg1,
-            BroadcastReceiver arg2, Handler arg3, int arg4, String arg5,
-            Bundle arg6) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public void sendStickyBroadcast(Intent arg0) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public void sendStickyOrderedBroadcast(Intent intent,
-            BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData,
-           Bundle initialExtras) {
-        // TODO Auto-generated method stub
-    }
-
-    @Override
-    public void setTheme(int arg0) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @SuppressWarnings("unused")
-    @Override
-    public void setWallpaper(Bitmap arg0) throws IOException {
-        // TODO Auto-generated method stub
-
-    }
-
-    @SuppressWarnings("unused")
-    @Override
-    public void setWallpaper(InputStream arg0) throws IOException {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public void startActivity(Intent arg0) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public void startIntentSender(IntentSender intent,
-            Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
-            throws IntentSender.SendIntentException {
-        // TODO Auto-generated method stub
-    }
-
-    @Override
-    public boolean startInstrumentation(ComponentName arg0, String arg1,
-            Bundle arg2) {
-        // TODO Auto-generated method stub
-        return false;
-    }
-
-    @Override
-    public ComponentName startService(Intent arg0) {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public boolean stopService(Intent arg0) {
-        // TODO Auto-generated method stub
-        return false;
-    }
-
-    @Override
-    public void unbindService(ServiceConnection arg0) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public void unregisterReceiver(BroadcastReceiver arg0) {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public Context getApplicationContext() {
-        throw new UnsupportedOperationException();
-    }
-}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeRenderSession.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeRenderSession.java
new file mode 100644
index 0000000..e38b910
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeRenderSession.java
@@ -0,0 +1,185 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.layoutlib.bridge;
+
+import com.android.ide.common.rendering.api.IAnimationListener;
+import com.android.ide.common.rendering.api.ILayoutPullParser;
+import com.android.ide.common.rendering.api.RenderParams;
+import com.android.ide.common.rendering.api.RenderSession;
+import com.android.ide.common.rendering.api.Result;
+import com.android.ide.common.rendering.api.ViewInfo;
+import com.android.layoutlib.bridge.impl.RenderSessionImpl;
+
+import android.view.View;
+import android.view.ViewGroup;
+
+import java.awt.image.BufferedImage;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * An implementation of {@link RenderSession}.
+ *
+ * This is a pretty basic class that does almost nothing. All of the work is done in
+ * {@link RenderSessionImpl}.
+ *
+ */
+public class BridgeRenderSession extends RenderSession {
+
+    private final RenderSessionImpl mSession;
+    private Result mLastResult;
+
+    @Override
+    public Result getResult() {
+        return mLastResult;
+    }
+
+    @Override
+    public BufferedImage getImage() {
+        return mSession.getImage();
+    }
+
+    @Override
+    public boolean isAlphaChannelImage() {
+        return mSession.isAlphaChannelImage();
+    }
+
+    @Override
+    public List<ViewInfo> getRootViews() {
+        return mSession.getViewInfos();
+    }
+
+    @Override
+    public Map<String, String> getDefaultProperties(Object viewObject) {
+        return mSession.getDefaultProperties(viewObject);
+    }
+
+    @Override
+    public Result getProperty(Object objectView, String propertyName) {
+        // TODO Auto-generated method stub
+        return super.getProperty(objectView, propertyName);
+    }
+
+    @Override
+    public Result setProperty(Object objectView, String propertyName, String propertyValue) {
+        // TODO Auto-generated method stub
+        return super.setProperty(objectView, propertyName, propertyValue);
+    }
+
+    @Override
+    public Result render(long timeout) {
+        try {
+            Bridge.prepareThread();
+            mLastResult = mSession.acquire(timeout);
+            if (mLastResult.isSuccess()) {
+                mLastResult = mSession.render(false /*freshRender*/);
+            }
+        } finally {
+            mSession.release();
+            Bridge.cleanupThread();
+        }
+
+        return mLastResult;
+    }
+
+    @Override
+    public Result animate(Object targetObject, String animationName,
+            boolean isFrameworkAnimation, IAnimationListener listener) {
+        // Animation is only supported in API 11+
+        return super.animate(targetObject, animationName, isFrameworkAnimation, listener);
+    }
+
+    @Override
+    public Result insertChild(Object parentView, ILayoutPullParser childXml, int index,
+            IAnimationListener listener) {
+        if (parentView instanceof ViewGroup == false) {
+            throw new IllegalArgumentException("parentView is not a ViewGroup");
+        }
+
+        try {
+            Bridge.prepareThread();
+            mLastResult = mSession.acquire(RenderParams.DEFAULT_TIMEOUT);
+            if (mLastResult.isSuccess()) {
+                mLastResult = mSession.insertChild((ViewGroup) parentView, childXml, index,
+                        listener);
+            }
+        } finally {
+            mSession.release();
+            Bridge.cleanupThread();
+        }
+
+        return mLastResult;
+    }
+
+
+    @Override
+    public Result moveChild(Object parentView, Object childView, int index,
+            Map<String, String> layoutParams, IAnimationListener listener) {
+        if (parentView instanceof ViewGroup == false) {
+            throw new IllegalArgumentException("parentView is not a ViewGroup");
+        }
+        if (childView instanceof View == false) {
+            throw new IllegalArgumentException("childView is not a View");
+        }
+
+        try {
+            Bridge.prepareThread();
+            mLastResult = mSession.acquire(RenderParams.DEFAULT_TIMEOUT);
+            if (mLastResult.isSuccess()) {
+                mLastResult = mSession.moveChild((ViewGroup) parentView, (View) childView, index,
+                        layoutParams, listener);
+            }
+        } finally {
+            mSession.release();
+            Bridge.cleanupThread();
+        }
+
+        return mLastResult;
+    }
+
+    @Override
+    public Result removeChild(Object childView, IAnimationListener listener) {
+        if (childView instanceof View == false) {
+            throw new IllegalArgumentException("childView is not a View");
+        }
+
+        try {
+            Bridge.prepareThread();
+            mLastResult = mSession.acquire(RenderParams.DEFAULT_TIMEOUT);
+            if (mLastResult.isSuccess()) {
+                mLastResult = mSession.removeChild((View) childView, listener);
+            }
+        } finally {
+            mSession.release();
+            Bridge.cleanupThread();
+        }
+
+        return mLastResult;
+    }
+
+    @Override
+    public void dispose() {
+    }
+
+    /*package*/ BridgeRenderSession(RenderSessionImpl scene, Result lastResult) {
+        mSession = scene;
+        if (scene != null) {
+            mSession.setScene(this);
+        }
+        mLastResult = lastResult;
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/LayoutResult.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/LayoutResult.java
deleted file mode 100644
index c4c5225..0000000
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/LayoutResult.java
+++ /dev/null
@@ -1,126 +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 com.android.layoutlib.bridge;
-
-import com.android.layoutlib.api.ILayoutResult;
-
-import java.awt.image.BufferedImage;
-
-/**
- * Implementation of {@link ILayoutResult}
- */
-public final class LayoutResult implements ILayoutResult {
-
-    private final ILayoutViewInfo mRootView;
-    private final BufferedImage mImage;
-    private final int mSuccess;
-    private final String mErrorMessage;
-
-    /**
-     * Creates a {@link #SUCCESS} {@link ILayoutResult} with the specified params
-     * @param rootView
-     * @param image
-     */
-    public LayoutResult(ILayoutViewInfo rootView, BufferedImage image) {
-        mSuccess = SUCCESS;
-        mErrorMessage = null;
-        mRootView = rootView;
-        mImage = image;
-    }
-    
-    /**
-     * Creates a LayoutResult with a specific success code and associated message
-     * @param code
-     * @param message
-     */
-    public LayoutResult(int code, String message) {
-        mSuccess = code;
-        mErrorMessage = message;
-        mRootView = null;
-        mImage = null;
-    }
-
-    public int getSuccess() {
-        return mSuccess;
-    }
-
-    public String getErrorMessage() {
-        return mErrorMessage;
-    }
-
-    public BufferedImage getImage() {
-        return mImage;
-    }
-
-    public ILayoutViewInfo getRootView() {
-        return mRootView;
-    }
-    
-    /**
-     * Implementation of {@link ILayoutResult.ILayoutViewInfo}
-     */
-    public static final class LayoutViewInfo implements ILayoutViewInfo {
-        private final Object mKey;
-        private final String mName;
-        private final int mLeft;
-        private final int mRight;
-        private final int mTop;
-        private final int mBottom;
-        private ILayoutViewInfo[] mChildren;
-
-        public LayoutViewInfo(String name, Object key, int left, int top, int right, int bottom) {
-            mName = name;
-            mKey = key;
-            mLeft = left;
-            mRight = right;
-            mTop = top;
-            mBottom = bottom;
-        }
-        
-        public void setChildren(ILayoutViewInfo[] children) {
-            mChildren = children;
-        }
-
-        public ILayoutViewInfo[] getChildren() {
-            return mChildren;
-        }
-
-        public Object getViewKey() {
-            return mKey;
-        }
-
-        public String getName() {
-            return mName;
-        }
-
-        public int getLeft() {
-            return mLeft;
-        }
-
-        public int getTop() {
-            return mTop;
-        }
-
-        public int getRight() {
-            return mRight;
-        }
-
-        public int getBottom() {
-            return mBottom;
-        }
-    }
-}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/MockView.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/MockView.java
index 1ca3182..3d50b2a 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/MockView.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/MockView.java
@@ -19,21 +19,23 @@
 import android.content.Context;
 import android.graphics.Canvas;
 import android.util.AttributeSet;
+import android.view.Gravity;
 import android.widget.TextView;
 
 /**
  * Base class for mocked views.
- * 
+ *
  * TODO: implement onDraw and draw a rectangle in a random color with the name of the class
  * (or better the id of the view).
  */
 public class MockView extends TextView {
-    
+
     public MockView(Context context, AttributeSet attrs, int defStyle) {
         super(context, attrs, defStyle);
-        
+
         setText(this.getClass().getSimpleName());
         setTextColor(0xFF000000);
+        setGravity(Gravity.CENTER);
     }
 
     @Override
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/NinePatchDrawable.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/NinePatchDrawable.java
deleted file mode 100644
index abbf2f0..0000000
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/NinePatchDrawable.java
+++ /dev/null
@@ -1,107 +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 com.android.layoutlib.bridge;
-
-import com.android.ninepatch.NinePatch;
-
-import android.graphics.Canvas;
-import android.graphics.ColorFilter;
-import android.graphics.Rect;
-import android.graphics.drawable.Drawable;
-
-public class NinePatchDrawable extends Drawable {
-
-    private NinePatch m9Patch;
-
-    NinePatchDrawable(NinePatch ninePatch) {
-        m9Patch = ninePatch;
-    }
-
-    @Override
-    public int getMinimumWidth() {
-        return m9Patch.getWidth();
-    }
-
-    @Override
-    public int getMinimumHeight() {
-        return m9Patch.getHeight();
-    }
-
-    /**
-     * Return the intrinsic width of the underlying drawable object.  Returns
-     * -1 if it has no intrinsic width, such as with a solid color.
-     */
-    @Override
-    public int getIntrinsicWidth() {
-        return m9Patch.getWidth();
-    }
-
-    /**
-     * Return the intrinsic height of the underlying drawable object. Returns
-     * -1 if it has no intrinsic height, such as with a solid color.
-     */
-    @Override
-    public int getIntrinsicHeight() {
-        return m9Patch.getHeight();
-    }
-
-    /**
-     * Return in padding the insets suggested by this Drawable for placing
-     * content inside the drawable's bounds. Positive values move toward the
-     * center of the Drawable (set Rect.inset). Returns true if this drawable
-     * actually has a padding, else false. When false is returned, the padding
-     * is always set to 0.
-     */
-    @Override
-    public boolean getPadding(Rect padding) {
-        int[] padd = new int[4];
-        m9Patch.getPadding(padd);
-        padding.left = padd[0];
-        padding.top = padd[1];
-        padding.right = padd[2];
-        padding.bottom = padd[3];
-        return true;
-    }
-
-    @Override
-    public void draw(Canvas canvas) {
-        Rect r = getBounds();
-        m9Patch.draw(canvas.getGraphics2d(), r.left, r.top, r.width(), r.height());
-
-        return;
-    }
-
-
-    // ----------- Not implemented methods ---------------
-
-
-    @Override
-    public int getOpacity() {
-        // FIXME
-        return 0xFF;
-    }
-
-    @Override
-    public void setAlpha(int arg0) {
-        // FIXME !
-    }
-
-    @Override
-    public void setColorFilter(ColorFilter arg0) {
-        // FIXME
-    }
-}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/ResourceHelper.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/ResourceHelper.java
deleted file mode 100644
index f624753..0000000
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/ResourceHelper.java
+++ /dev/null
@@ -1,381 +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 com.android.layoutlib.bridge;
-
-import com.android.layoutlib.api.IDensityBasedResourceValue;
-import com.android.layoutlib.api.IResourceValue;
-import com.android.layoutlib.api.IDensityBasedResourceValue.Density;
-import com.android.ninepatch.NinePatch;
-
-import org.kxml2.io.KXmlParser;
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
-import android.graphics.Bitmap;
-import android.graphics.drawable.BitmapDrawable;
-import android.graphics.drawable.ColorDrawable;
-import android.graphics.drawable.Drawable;
-import android.util.TypedValue;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Helper class to provide various convertion method used in handling android resources.
- */
-public final class ResourceHelper {
-
-    private final static Pattern sFloatPattern = Pattern.compile("(-?[0-9]+(?:\\.[0-9]+)?)(.*)");
-    private final static float[] sFloatOut = new float[1];
-
-    private final static TypedValue mValue = new TypedValue();
-
-    /**
-     * Returns the color value represented by the given string value
-     * @param value the color value
-     * @return the color as an int
-     * @throw NumberFormatException if the conversion failed.
-     */
-    static int getColor(String value) {
-        if (value != null) {
-            if (value.startsWith("#") == false) {
-                throw new NumberFormatException();
-            }
-
-            value = value.substring(1);
-
-            // make sure it's not longer than 32bit
-            if (value.length() > 8) {
-                throw new NumberFormatException();
-            }
-
-            if (value.length() == 3) { // RGB format
-                char[] color = new char[8];
-                color[0] = color[1] = 'F';
-                color[2] = color[3] = value.charAt(0);
-                color[4] = color[5] = value.charAt(1);
-                color[6] = color[7] = value.charAt(2);
-                value = new String(color);
-            } else if (value.length() == 4) { // ARGB format
-                char[] color = new char[8];
-                color[0] = color[1] = value.charAt(0);
-                color[2] = color[3] = value.charAt(1);
-                color[4] = color[5] = value.charAt(2);
-                color[6] = color[7] = value.charAt(3);
-                value = new String(color);
-            } else if (value.length() == 6) {
-                value = "FF" + value;
-            }
-
-            // this is a RRGGBB or AARRGGBB value
-
-            // Integer.parseInt will fail to parse strings like "ff191919", so we use
-            // a Long, but cast the result back into an int, since we know that we're only
-            // dealing with 32 bit values.
-            return (int)Long.parseLong(value, 16);
-        }
-
-        throw new NumberFormatException();
-    }
-
-    /**
-     * Returns a drawable from the given value.
-     * @param value The value that contains a path to a 9 patch, a bitmap or a xml based drawable,
-     * or an hexadecimal color
-     * @param context
-     * @param isFramework indicates whether the resource is a framework resources.
-     * Framework resources are cached, and loaded only once.
-     */
-    public static Drawable getDrawable(IResourceValue value, BridgeContext context, boolean isFramework) {
-        Drawable d = null;
-
-        String stringValue = value.getValue();
-
-        String lowerCaseValue = stringValue.toLowerCase();
-
-        if (lowerCaseValue.endsWith(NinePatch.EXTENSION_9PATCH)) {
-            File file = new File(stringValue);
-            if (file.isFile()) {
-                NinePatch ninePatch = Bridge.getCached9Patch(stringValue,
-                        isFramework ? null : context.getProjectKey());
-
-                if (ninePatch == null) {
-                    try {
-                        ninePatch = NinePatch.load(file.toURL(), false /* convert */);
-
-                        Bridge.setCached9Patch(stringValue, ninePatch,
-                                isFramework ? null : context.getProjectKey());
-                    } catch (MalformedURLException e) {
-                        // URL is wrong, we'll return null below
-                    } catch (IOException e) {
-                        // failed to read the file, we'll return null below.
-                    }
-                }
-
-                if (ninePatch != null) {
-                    return new NinePatchDrawable(ninePatch);
-                }
-            }
-
-            return null;
-        } else if (lowerCaseValue.endsWith(".xml")) {
-            // create a blockparser for the file
-            File f = new File(stringValue);
-            if (f.isFile()) {
-                try {
-                    // let the framework inflate the Drawable from the XML file.
-                    KXmlParser parser = new KXmlParser();
-                    parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
-                    parser.setInput(new FileReader(f));
-
-                    d = Drawable.createFromXml(context.getResources(),
-                            new BridgeXmlBlockParser(parser, context, isFramework));
-                    return d;
-                } catch (XmlPullParserException e) {
-                    context.getLogger().error(e);
-                } catch (FileNotFoundException e) {
-                    // will not happen, since we pre-check
-                } catch (IOException e) {
-                    context.getLogger().error(e);
-                }
-            }
-
-            return null;
-        } else {
-            File bmpFile = new File(stringValue);
-            if (bmpFile.isFile()) {
-                try {
-                    Bitmap bitmap = Bridge.getCachedBitmap(stringValue,
-                            isFramework ? null : context.getProjectKey());
-
-                    if (bitmap == null) {
-                        bitmap = new Bitmap(bmpFile);
-                        try {
-                            bitmap.setDensity(Density.MEDIUM.getValue());
-                        } catch (NoClassDefFoundError error) {
-                            // look like we're running in an older version of ADT that doesn't
-                            // include the new layoutlib_api. Let's just ignore this, the drawing
-                            // will just be wrong.
-                        }
-                        Bridge.setCachedBitmap(stringValue, bitmap,
-                                isFramework ? null : context.getProjectKey());
-                    }
-
-                    try {
-                        if (value instanceof IDensityBasedResourceValue) {
-                            Density density = ((IDensityBasedResourceValue)value).getDensity();
-                            if (density != Density.MEDIUM) {
-                                // create a copy of the bitmap
-                                bitmap = Bitmap.createBitmap(bitmap);
-
-                                // apply the density
-                                bitmap.setDensity(density.getValue());
-                            }
-                        }
-                    } catch (NoClassDefFoundError error) {
-                        // look like we're running in an older version of ADT that doesn't include
-                        // the new layoutlib_api. Let's just ignore this, the drawing will just be
-                        // wrong.
-                    }
-
-                    return new BitmapDrawable(context.getResources(), bitmap);
-                } catch (IOException e) {
-                    // we'll return null below
-                    // TODO: log the error.
-                }
-            } else {
-                // attempt to get a color from the value
-                try {
-                    int color = getColor(stringValue);
-                    return new ColorDrawable(color);
-                } catch (NumberFormatException e) {
-                    // we'll return null below.
-                    // TODO: log the error
-                }
-            }
-        }
-
-        return null;
-    }
-
-
-    // ------- TypedValue stuff
-    // This is taken from //device/libs/utils/ResourceTypes.cpp
-
-    private static final class UnitEntry {
-        String name;
-        int type;
-        int unit;
-        float scale;
-
-        UnitEntry(String name, int type, int unit, float scale) {
-            this.name = name;
-            this.type = type;
-            this.unit = unit;
-            this.scale = scale;
-        }
-    }
-
-    private final static UnitEntry[] sUnitNames = new UnitEntry[] {
-        new UnitEntry("px", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_PX, 1.0f),
-        new UnitEntry("dip", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_DIP, 1.0f),
-        new UnitEntry("dp", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_DIP, 1.0f),
-        new UnitEntry("sp", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_SP, 1.0f),
-        new UnitEntry("pt", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_PT, 1.0f),
-        new UnitEntry("in", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_IN, 1.0f),
-        new UnitEntry("mm", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_MM, 1.0f),
-        new UnitEntry("%", TypedValue.TYPE_FRACTION, TypedValue.COMPLEX_UNIT_FRACTION, 1.0f/100),
-        new UnitEntry("%p", TypedValue.TYPE_FRACTION, TypedValue.COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100),
-    };
-
-    /**
-     * Returns the raw value from the given string.
-     * This object is only valid until the next call on to {@link ResourceHelper}.
-     */
-    public static TypedValue getValue(String s) {
-        if (stringToFloat(s, mValue)) {
-            return mValue;
-        }
-
-        return null;
-    }
-
-    /**
-     * Convert the string into a {@link TypedValue}.
-     * @param s
-     * @param outValue
-     * @return true if success.
-     */
-    public static boolean stringToFloat(String s, TypedValue outValue) {
-        // remove the space before and after
-        s.trim();
-        int len = s.length();
-
-        if (len <= 0) {
-            return false;
-        }
-
-        // check that there's no non ascii characters.
-        char[] buf = s.toCharArray();
-        for (int i = 0 ; i < len ; i++) {
-            if (buf[i] > 255) {
-                return false;
-            }
-        }
-
-        // check the first character
-        if (buf[0] < '0' && buf[0] > '9' && buf[0] != '.') {
-            return false;
-        }
-
-        // now look for the string that is after the float...
-        Matcher m = sFloatPattern.matcher(s);
-        if (m.matches()) {
-            String f_str = m.group(1);
-            String end = m.group(2);
-
-            float f;
-            try {
-                f = Float.parseFloat(f_str);
-            } catch (NumberFormatException e) {
-                // this shouldn't happen with the regexp above.
-                return false;
-            }
-
-            if (end.length() > 0 && end.charAt(0) != ' ') {
-                // Might be a unit...
-                if (parseUnit(end, outValue, sFloatOut)) {
-
-                    f *= sFloatOut[0];
-                    boolean neg = f < 0;
-                    if (neg) {
-                        f = -f;
-                    }
-                    long bits = (long)(f*(1<<23)+.5f);
-                    int radix;
-                    int shift;
-                    if ((bits&0x7fffff) == 0) {
-                        // Always use 23p0 if there is no fraction, just to make
-                        // things easier to read.
-                        radix = TypedValue.COMPLEX_RADIX_23p0;
-                        shift = 23;
-                    } else if ((bits&0xffffffffff800000L) == 0) {
-                        // Magnitude is zero -- can fit in 0 bits of precision.
-                        radix = TypedValue.COMPLEX_RADIX_0p23;
-                        shift = 0;
-                    } else if ((bits&0xffffffff80000000L) == 0) {
-                        // Magnitude can fit in 8 bits of precision.
-                        radix = TypedValue.COMPLEX_RADIX_8p15;
-                        shift = 8;
-                    } else if ((bits&0xffffff8000000000L) == 0) {
-                        // Magnitude can fit in 16 bits of precision.
-                        radix = TypedValue.COMPLEX_RADIX_16p7;
-                        shift = 16;
-                    } else {
-                        // Magnitude needs entire range, so no fractional part.
-                        radix = TypedValue.COMPLEX_RADIX_23p0;
-                        shift = 23;
-                    }
-                    int mantissa = (int)(
-                        (bits>>shift) & TypedValue.COMPLEX_MANTISSA_MASK);
-                    if (neg) {
-                        mantissa = (-mantissa) & TypedValue.COMPLEX_MANTISSA_MASK;
-                    }
-                    outValue.data |=
-                        (radix<<TypedValue.COMPLEX_RADIX_SHIFT)
-                        | (mantissa<<TypedValue.COMPLEX_MANTISSA_SHIFT);
-                    return true;
-                }
-                return false;
-            }
-
-            // make sure it's only spaces at the end.
-            end = end.trim();
-
-            if (end.length() == 0) {
-                if (outValue != null) {
-                    outValue.type = TypedValue.TYPE_FLOAT;
-                    outValue.data = Float.floatToIntBits(f);
-                    return true;
-                }
-            }
-        }
-
-        return false;
-    }
-
-    private static boolean parseUnit(String str, TypedValue outValue, float[] outScale) {
-        str = str.trim();
-
-        for (UnitEntry unit : sUnitNames) {
-            if (unit.name.equals(str)) {
-                outValue.type = unit.type;
-                outValue.data = unit.unit << TypedValue.COMPLEX_UNIT_SHIFT;
-                outScale[0] = unit.scale;
-
-                return true;
-            }
-        }
-
-        return false;
-    }
-}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/ResourceValue.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/ResourceValue.java
deleted file mode 100644
index 01a4871..0000000
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/ResourceValue.java
+++ /dev/null
@@ -1,67 +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 com.android.layoutlib.bridge;
-
-import com.android.layoutlib.api.IResourceValue;
-
-/**
- * Basic implementation of IResourceValue.
- */
-class ResourceValue implements IResourceValue {
-    private final String mType;
-    private final String mName;
-    private String mValue = null;
-    
-    ResourceValue(String name) {
-        mType = null;
-        mName = name;
-    }
-
-    public ResourceValue(String type, String name, String value) {
-        mType = type;
-        mName = name;
-        mValue = value;
-    }
-
-    public String getType() {
-        return mType;
-    }
-
-    public final String getName() {
-        return mName;
-    }
-    
-    public final String getValue() {
-        return mValue;
-    }
-    
-    public final void setValue(String value) {
-        mValue = value;
-    }
-    
-    public void replaceWith(ResourceValue value) {
-        mValue = value.mValue;
-    }
-
-    public boolean isFramework() {
-        // ResourceValue object created directly in the framework are used to describe
-        // non resolvable coming from the XML. Since they will never be cached (as they can't
-        // be a value pointing to a bitmap, or they'd be resolvable.), the return value deoes
-        // not matter.
-        return false;
-    }
-}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeAssetManager.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeAssetManager.java
similarity index 89%
rename from tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeAssetManager.java
rename to tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeAssetManager.java
index 71803fc..a825060 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeAssetManager.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeAssetManager.java
@@ -14,7 +14,9 @@
  * limitations under the License.
  */
 
-package com.android.layoutlib.bridge;
+package com.android.layoutlib.bridge.android;
+
+import com.android.layoutlib.bridge.Bridge;
 
 import android.content.res.AssetManager;
 
@@ -28,7 +30,7 @@
      * <p/>
      * {@link Bridge} calls this method after setting up a new bridge.
      */
-    /*package*/ static AssetManager initSystem() {
+    /*package*/ public static AssetManager initSystem() {
         if (!(AssetManager.sSystem instanceof BridgeAssetManager)) {
             // Note that AssetManager() creates a system AssetManager and we override it
             // with our BridgeAssetManager.
@@ -42,7 +44,7 @@
      * Clears the static {@link AssetManager#sSystem} to make sure we don't leave objects
      * around that would prevent us from unloading the library.
      */
-    /*package*/ static void clearSystem() {
+    public static void clearSystem() {
         AssetManager.sSystem = null;
     }
 
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContentProvider.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContentProvider.java
new file mode 100644
index 0000000..3835378
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContentProvider.java
@@ -0,0 +1,122 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.layoutlib.bridge.android;
+
+import android.content.ContentProviderOperation;
+import android.content.ContentProviderResult;
+import android.content.ContentValues;
+import android.content.IContentProvider;
+import android.content.OperationApplicationException;
+import android.content.res.AssetFileDescriptor;
+import android.database.Cursor;
+import android.database.CursorWindow;
+import android.database.IBulkCursor;
+import android.database.IContentObserver;
+import android.net.Uri;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.ParcelFileDescriptor;
+import android.os.RemoteException;
+
+import java.io.FileNotFoundException;
+import java.util.ArrayList;
+
+/**
+ * Mock implementation of {@link IContentProvider}.
+ *
+ * TODO: never return null when the method is not supposed to. Return fake data instead.
+ */
+public final class BridgeContentProvider implements IContentProvider {
+
+    public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> arg0)
+            throws RemoteException, OperationApplicationException {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    public int bulkInsert(Uri arg0, ContentValues[] arg1) throws RemoteException {
+        // TODO Auto-generated method stub
+        return 0;
+    }
+
+    public IBulkCursor bulkQuery(Uri arg0, String[] arg1, String arg2, String[] arg3,
+            String arg4, IContentObserver arg5, CursorWindow arg6) throws RemoteException {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    public Bundle call(String arg0, String arg1, Bundle arg2) throws RemoteException {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    public int delete(Uri arg0, String arg1, String[] arg2) throws RemoteException {
+        // TODO Auto-generated method stub
+        return 0;
+    }
+
+    public String getType(Uri arg0) throws RemoteException {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    public Uri insert(Uri arg0, ContentValues arg1) throws RemoteException {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    public AssetFileDescriptor openAssetFile(Uri arg0, String arg1) throws RemoteException,
+            FileNotFoundException {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    public ParcelFileDescriptor openFile(Uri arg0, String arg1) throws RemoteException,
+            FileNotFoundException {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3, String arg4)
+            throws RemoteException {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3)
+            throws RemoteException {
+        // TODO Auto-generated method stub
+        return 0;
+    }
+
+    public IBinder asBinder() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    public String[] getStreamTypes(Uri arg0, String arg1) throws RemoteException {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    public AssetFileDescriptor openTypedAssetFile(Uri arg0, String arg1, Bundle arg2)
+            throws RemoteException, FileNotFoundException {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContentResolver.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContentResolver.java
new file mode 100644
index 0000000..0257686
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContentResolver.java
@@ -0,0 +1,105 @@
+/*
+ * 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.layoutlib.bridge.android;
+
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.IContentProvider;
+import android.database.ContentObserver;
+import android.net.Uri;
+import android.os.Bundle;
+
+/**
+ * A mock content resolver for the LayoutLib Bridge.
+ * <p/>
+ * It won't serve any actual data but it's good enough for all
+ * the widgets which expect to have a content resolver available via
+ * {@link BridgeContext#getContentResolver()}.
+ */
+public class BridgeContentResolver extends ContentResolver {
+
+    private BridgeContentProvider mProvider = null;
+
+    public BridgeContentResolver(Context context) {
+        super(context);
+    }
+
+    @Override
+    public IContentProvider acquireProvider(Context c, String name) {
+        if (mProvider == null) {
+            mProvider = new BridgeContentProvider();
+        }
+
+        return mProvider;
+    }
+
+    @Override
+    public IContentProvider acquireExistingProvider(Context c, String name) {
+        if (mProvider == null) {
+            mProvider = new BridgeContentProvider();
+        }
+
+        return mProvider;
+    }
+
+    @Override
+    public boolean releaseProvider(IContentProvider icp) {
+        // ignore
+        return false;
+    }
+
+    /**
+     * Stub for the layoutlib bridge content resolver.
+     */
+    @Override
+    public void registerContentObserver(Uri uri, boolean notifyForDescendents,
+            ContentObserver observer) {
+        // pass
+    }
+
+    /**
+     * Stub for the layoutlib bridge content resolver.
+     */
+    @Override
+    public void unregisterContentObserver(ContentObserver observer) {
+        // pass
+    }
+
+    /**
+     * Stub for the layoutlib bridge content resolver.
+     */
+    @Override
+    public void notifyChange(Uri uri, ContentObserver observer, boolean syncToNetwork) {
+        // pass
+    }
+
+    /**
+     * Stub for the layoutlib bridge content resolver.
+     */
+    @Override
+    public void startSync(Uri uri, Bundle extras) {
+        // pass
+    }
+
+    /**
+     * Stub for the layoutlib bridge content resolver.
+     */
+    @Override
+    public void cancelSync(Uri uri) {
+        // pass
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java
new file mode 100644
index 0000000..ea3d5d2
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java
@@ -0,0 +1,1244 @@
+/*
+ * 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.layoutlib.bridge.android;
+
+import com.android.ide.common.rendering.api.ILayoutPullParser;
+import com.android.ide.common.rendering.api.IProjectCallback;
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.ide.common.rendering.api.RenderResources;
+import com.android.ide.common.rendering.api.ResourceReference;
+import com.android.ide.common.rendering.api.ResourceValue;
+import com.android.ide.common.rendering.api.StyleResourceValue;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.BridgeConstants;
+import com.android.layoutlib.bridge.impl.Stack;
+import com.android.resources.ResourceType;
+import com.android.util.Pair;
+
+import org.kxml2.io.KXmlParser;
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.IntentSender;
+import android.content.ServiceConnection;
+import android.content.SharedPreferences;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.content.res.AssetManager;
+import android.content.res.Configuration;
+import android.content.res.Resources;
+import android.content.res.TypedArray;
+import android.content.res.Resources.Theme;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteDatabase.CursorFactory;
+import android.graphics.Bitmap;
+import android.graphics.drawable.Drawable;
+import android.net.Uri;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.util.AttributeSet;
+import android.util.DisplayMetrics;
+import android.util.TypedValue;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.Map.Entry;
+
+/**
+ * Custom implementation of Context/Activity to handle non compiled resources.
+ */
+public final class BridgeContext extends Activity {
+
+    private Resources mSystemResources;
+    private final HashMap<View, Object> mViewKeyMap = new HashMap<View, Object>();
+    private final Object mProjectKey;
+    private final DisplayMetrics mMetrics;
+    private final RenderResources mRenderResources;
+    private final ApplicationInfo mApplicationInfo;
+
+    private final Map<Object, Map<String, String>> mDefaultPropMaps =
+        new IdentityHashMap<Object, Map<String,String>>();
+
+    // maps for dynamically generated id representing style objects (StyleResourceValue)
+    private Map<Integer, StyleResourceValue> mDynamicIdToStyleMap;
+    private Map<StyleResourceValue, Integer> mStyleToDynamicIdMap;
+    private int mDynamicIdGenerator = 0x01030000; // Base id for framework R.style
+
+    // cache for TypedArray generated from IStyleResourceValue object
+    private Map<int[], Map<Integer, TypedArray>> mTypedArrayCache;
+    private BridgeInflater mBridgeInflater;
+
+    private final IProjectCallback mProjectCallback;
+    private BridgeContentResolver mContentResolver;
+
+    private final Stack<BridgeXmlBlockParser> mParserStack = new Stack<BridgeXmlBlockParser>();
+
+    /**
+     * @param projectKey An Object identifying the project. This is used for the cache mechanism.
+     * @param metrics the {@link DisplayMetrics}.
+     * @param themeName The name of the theme to use.
+     * @param projectResources the resources of the project. The map contains (String, map) pairs
+     * where the string is the type of the resource reference used in the layout file, and the
+     * map contains (String, {@link }) pairs where the key is the resource name,
+     * and the value is the resource value.
+     * @param frameworkResources the framework resources. The map contains (String, map) pairs
+     * where the string is the type of the resource reference used in the layout file, and the map
+     * contains (String, {@link ResourceValue}) pairs where the key is the resource name, and the
+     * value is the resource value.
+     * @param styleInheritanceMap
+     * @param projectCallback
+     * @param targetSdkVersion the targetSdkVersion of the application.
+     */
+    public BridgeContext(Object projectKey, DisplayMetrics metrics,
+            RenderResources renderResources,
+            IProjectCallback projectCallback,
+            int targetSdkVersion) {
+        mProjectKey = projectKey;
+        mMetrics = metrics;
+        mProjectCallback = projectCallback;
+
+        mRenderResources = renderResources;
+
+        mApplicationInfo = new ApplicationInfo();
+        mApplicationInfo.targetSdkVersion = targetSdkVersion;
+    }
+
+    /**
+     * Initializes the {@link Resources} singleton to be linked to this {@link Context}, its
+     * {@link DisplayMetrics}, {@link Configuration}, and {@link IProjectCallback}.
+     *
+     * @see #disposeResources()
+     */
+    public void initResources() {
+        AssetManager assetManager = AssetManager.getSystem();
+        Configuration config = new Configuration();
+
+        mSystemResources = BridgeResources.initSystem(
+                this,
+                assetManager,
+                mMetrics,
+                config,
+                mProjectCallback);
+        mTheme = mSystemResources.newTheme();
+    }
+
+    /**
+     * Disposes the {@link Resources} singleton.
+     */
+    public void disposeResources() {
+        BridgeResources.disposeSystem();
+    }
+
+    public void setBridgeInflater(BridgeInflater inflater) {
+        mBridgeInflater = inflater;
+    }
+
+    public void addViewKey(View view, Object viewKey) {
+        mViewKeyMap.put(view, viewKey);
+    }
+
+    public Object getViewKey(View view) {
+        return mViewKeyMap.get(view);
+    }
+
+    public Object getProjectKey() {
+        return mProjectKey;
+    }
+
+    public DisplayMetrics getMetrics() {
+        return mMetrics;
+    }
+
+    public IProjectCallback getProjectCallback() {
+        return mProjectCallback;
+    }
+
+    public RenderResources getRenderResources() {
+        return mRenderResources;
+    }
+
+    public Map<String, String> getDefaultPropMap(Object key) {
+        return mDefaultPropMaps.get(key);
+    }
+
+    /**
+     * Adds a parser to the stack.
+     * @param parser the parser to add.
+     */
+    public void pushParser(BridgeXmlBlockParser parser) {
+        mParserStack.push(parser);
+    }
+
+    /**
+     * Removes the parser at the top of the stack
+     */
+    public void popParser() {
+        mParserStack.pop();
+    }
+
+    /**
+     * Returns the current parser at the top the of the stack.
+     * @return a parser or null.
+     */
+    public BridgeXmlBlockParser getCurrentParser() {
+        return mParserStack.peek();
+    }
+
+    /**
+     * Returns the previous parser.
+     * @return a parser or null if there isn't any previous parser
+     */
+    public BridgeXmlBlockParser getPreviousParser() {
+        if (mParserStack.size() < 2) {
+            return null;
+        }
+        return mParserStack.get(mParserStack.size() - 2);
+    }
+
+    public boolean resolveThemeAttribute(int resid, TypedValue outValue, boolean resolveRefs) {
+        Pair<ResourceType, String> resourceInfo = Bridge.resolveResourceId(resid);
+        if (resourceInfo == null) {
+            resourceInfo = mProjectCallback.resolveResourceId(resid);
+        }
+
+        if (resourceInfo == null) {
+            return false;
+        }
+
+        ResourceValue value = mRenderResources.findItemInTheme(resourceInfo.getSecond());
+        if (resolveRefs) {
+            value = mRenderResources.resolveResValue(value);
+        }
+
+        // check if this is a style resource
+        if (value instanceof StyleResourceValue) {
+            // get the id that will represent this style.
+            outValue.resourceId = getDynamicIdByStyle((StyleResourceValue)value);
+            return true;
+        }
+
+
+        int a;
+        // if this is a framework value.
+        if (value.isFramework()) {
+            // look for idName in the android R classes.
+            // use 0 a default res value as it's not a valid id value.
+            a = getFrameworkResourceValue(value.getResourceType(), value.getName(), 0 /*defValue*/);
+        } else {
+            // look for idName in the project R class.
+            // use 0 a default res value as it's not a valid id value.
+            a = getProjectResourceValue(value.getResourceType(), value.getName(), 0 /*defValue*/);
+        }
+
+        if (a != 0) {
+            outValue.resourceId = a;
+            return true;
+        }
+
+        return false;
+    }
+
+
+    public ResourceReference resolveId(int id) {
+        // first get the String related to this id in the framework
+        Pair<ResourceType, String> resourceInfo = Bridge.resolveResourceId(id);
+
+        if (resourceInfo != null) {
+            return new ResourceReference(resourceInfo.getSecond(), true);
+        }
+
+        // didn't find a match in the framework? look in the project.
+        if (mProjectCallback != null) {
+            resourceInfo = mProjectCallback.resolveResourceId(id);
+
+            if (resourceInfo != null) {
+                return new ResourceReference(resourceInfo.getSecond(), false);
+            }
+        }
+
+        return null;
+    }
+
+    public Pair<View, Boolean> inflateView(ResourceReference resource, ViewGroup parent,
+            boolean attachToRoot, boolean skipCallbackParser) {
+        String layoutName = resource.getName();
+        boolean isPlatformLayout = resource.isFramework();
+
+        if (isPlatformLayout == false && skipCallbackParser == false) {
+            // check if the project callback can provide us with a custom parser.
+            ILayoutPullParser parser = mProjectCallback.getParser(layoutName);
+            if (parser != null) {
+                BridgeXmlBlockParser blockParser = new BridgeXmlBlockParser(parser,
+                        this, resource.isFramework());
+                try {
+                    pushParser(blockParser);
+                    return Pair.of(
+                            mBridgeInflater.inflate(blockParser, parent, attachToRoot),
+                            true);
+                } finally {
+                    popParser();
+                }
+            }
+        }
+
+        ResourceValue resValue;
+        if (resource instanceof ResourceValue) {
+            resValue = (ResourceValue) resource;
+        } else {
+            if (isPlatformLayout) {
+                resValue = mRenderResources.getFrameworkResource(ResourceType.LAYOUT,
+                        resource.getName());
+            } else {
+                resValue = mRenderResources.getProjectResource(ResourceType.LAYOUT,
+                        resource.getName());
+            }
+        }
+
+        if (resValue != null) {
+
+            File xml = new File(resValue.getValue());
+            if (xml.isFile()) {
+                // we need to create a pull parser around the layout XML file, and then
+                // give that to our XmlBlockParser
+                try {
+                    KXmlParser parser = new KXmlParser();
+                    parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
+                    parser.setInput(new FileInputStream(xml), "UTF-8"); //$NON-NLS-1$);
+
+                    // set the resource ref to have correct view cookies
+                    mBridgeInflater.setResourceReference(resource);
+
+                    BridgeXmlBlockParser blockParser = new BridgeXmlBlockParser(parser,
+                            this, resource.isFramework());
+                    try {
+                        pushParser(blockParser);
+                        return Pair.of(
+                                mBridgeInflater.inflate(blockParser, parent, attachToRoot),
+                                false);
+                    } finally {
+                        popParser();
+                    }
+                } catch (XmlPullParserException e) {
+                    Bridge.getLog().error(LayoutLog.TAG_BROKEN,
+                            "Failed to configure parser for " + xml, e, null /*data*/);
+                    // we'll return null below.
+                } catch (FileNotFoundException e) {
+                    // this shouldn't happen since we check above.
+                } finally {
+                    mBridgeInflater.setResourceReference(null);
+                }
+            } else {
+                Bridge.getLog().error(LayoutLog.TAG_BROKEN,
+                        String.format("File %s is missing!", xml), null);
+            }
+        } else {
+            Bridge.getLog().error(LayoutLog.TAG_BROKEN,
+                    String.format("Layout %s%s does not exist.", isPlatformLayout ? "android:" : "",
+                            layoutName), null);
+        }
+
+        return Pair.of(null, false);
+    }
+
+    // ------------- Activity Methods
+
+    @Override
+    public LayoutInflater getLayoutInflater() {
+        return mBridgeInflater;
+    }
+
+    // ------------ Context methods
+
+    @Override
+    public Resources getResources() {
+        return mSystemResources;
+    }
+
+    @Override
+    public Theme getTheme() {
+        return mTheme;
+    }
+
+    @Override
+    public ClassLoader getClassLoader() {
+        return this.getClass().getClassLoader();
+    }
+
+    @Override
+    public Object getSystemService(String service) {
+        if (LAYOUT_INFLATER_SERVICE.equals(service)) {
+            return mBridgeInflater;
+        }
+
+        // AutoCompleteTextView and MultiAutoCompleteTextView want a window
+        // service. We don't have any but it's not worth an exception.
+        if (WINDOW_SERVICE.equals(service)) {
+            return null;
+        }
+
+        // needed by SearchView
+        if (INPUT_METHOD_SERVICE.equals(service)) {
+            return null;
+        }
+
+        throw new UnsupportedOperationException("Unsupported Service: " + service);
+    }
+
+
+    @Override
+    public final TypedArray obtainStyledAttributes(int[] attrs) {
+        return createStyleBasedTypedArray(mRenderResources.getCurrentTheme(), attrs);
+    }
+
+    @Override
+    public final TypedArray obtainStyledAttributes(int resid, int[] attrs)
+            throws Resources.NotFoundException {
+        // get the StyleResourceValue based on the resId;
+        StyleResourceValue style = getStyleByDynamicId(resid);
+
+        if (style == null) {
+            throw new Resources.NotFoundException();
+        }
+
+        if (mTypedArrayCache == null) {
+            mTypedArrayCache = new HashMap<int[], Map<Integer,TypedArray>>();
+
+            Map<Integer, TypedArray> map = new HashMap<Integer, TypedArray>();
+            mTypedArrayCache.put(attrs, map);
+
+            BridgeTypedArray ta = createStyleBasedTypedArray(style, attrs);
+            map.put(resid, ta);
+
+            return ta;
+        }
+
+        // get the 2nd map
+        Map<Integer, TypedArray> map = mTypedArrayCache.get(attrs);
+        if (map == null) {
+            map = new HashMap<Integer, TypedArray>();
+            mTypedArrayCache.put(attrs, map);
+        }
+
+        // get the array from the 2nd map
+        TypedArray ta = map.get(resid);
+
+        if (ta == null) {
+            ta = createStyleBasedTypedArray(style, attrs);
+            map.put(resid, ta);
+        }
+
+        return ta;
+    }
+
+    @Override
+    public final TypedArray obtainStyledAttributes(AttributeSet set, int[] attrs) {
+        return obtainStyledAttributes(set, attrs, 0, 0);
+    }
+
+    @Override
+    public TypedArray obtainStyledAttributes(AttributeSet set, int[] attrs,
+            int defStyleAttr, int defStyleRes) {
+
+        Map<String, String> defaultPropMap = null;
+        boolean isPlatformFile = true;
+
+        // Hint: for XmlPullParser, attach source //DEVICE_SRC/dalvik/libcore/xml/src/java
+        if (set instanceof BridgeXmlBlockParser) {
+            BridgeXmlBlockParser parser = null;
+            parser = (BridgeXmlBlockParser)set;
+
+            isPlatformFile = parser.isPlatformFile();
+
+            Object key = parser.getViewCookie();
+            if (key != null) {
+                defaultPropMap = mDefaultPropMaps.get(key);
+                if (defaultPropMap == null) {
+                    defaultPropMap = new HashMap<String, String>();
+                    mDefaultPropMaps.put(key, defaultPropMap);
+                }
+            }
+
+        } else if (set instanceof BridgeLayoutParamsMapAttributes) {
+            // this is only for temp layout params generated dynamically, so this is never
+            // platform content.
+            isPlatformFile = false;
+        } else if (set != null) { // null parser is ok
+            // really this should not be happening since its instantiated in Bridge
+            Bridge.getLog().error(LayoutLog.TAG_BROKEN,
+                    "Parser is not a BridgeXmlBlockParser!", null /*data*/);
+            return null;
+        }
+
+        boolean[] frameworkAttributes = new boolean[1];
+        TreeMap<Integer, String> styleNameMap = searchAttrs(attrs, frameworkAttributes);
+
+        BridgeTypedArray ta = ((BridgeResources) mSystemResources).newTypeArray(attrs.length,
+                isPlatformFile);
+
+        // look for a custom style.
+        String customStyle = null;
+        if (set != null) {
+            customStyle = set.getAttributeValue(null /* namespace*/, "style");
+        }
+
+        StyleResourceValue customStyleValues = null;
+        if (customStyle != null) {
+            ResourceValue item = mRenderResources.findResValue(customStyle,
+                    false /*forceFrameworkOnly*/);
+
+            // resolve it in case it links to something else
+            item = mRenderResources.resolveResValue(item);
+
+            if (item instanceof StyleResourceValue) {
+                customStyleValues = (StyleResourceValue)item;
+            }
+        }
+
+        // resolve the defStyleAttr value into a IStyleResourceValue
+        StyleResourceValue defStyleValues = null;
+
+        if (defStyleAttr != 0) {
+            // get the name from the int.
+            String defStyleName = searchAttr(defStyleAttr);
+
+            if (defaultPropMap != null) {
+                defaultPropMap.put("style", defStyleName);
+            }
+
+            // look for the style in the current theme, and its parent:
+            ResourceValue item = mRenderResources.findItemInTheme(defStyleName);
+
+            if (item != null) {
+                // item is a reference to a style entry. Search for it.
+                item = mRenderResources.findResValue(item.getValue(),
+                        false /*forceFrameworkOnly*/);
+
+                if (item instanceof StyleResourceValue) {
+                    defStyleValues = (StyleResourceValue)item;
+                }
+            } else {
+                Bridge.getLog().error(null,
+                        String.format(
+                                "Failed to find style '%s' in current theme", defStyleName),
+                        null /*data*/);
+            }
+        } else if (defStyleRes != 0) {
+            Pair<ResourceType, String> value = Bridge.resolveResourceId(defStyleRes);
+            if (value == null) {
+                value = mProjectCallback.resolveResourceId(defStyleRes);
+            }
+
+            if (value != null) {
+                if (value.getFirst() == ResourceType.STYLE) {
+                    // look for the style in the current theme, and its parent:
+                    ResourceValue item = mRenderResources.findItemInTheme(value.getSecond());
+                    if (item != null) {
+                        if (item instanceof StyleResourceValue) {
+                            if (defaultPropMap != null) {
+                                defaultPropMap.put("style", item.getName());
+                            }
+
+                            defStyleValues = (StyleResourceValue)item;
+                        }
+                    } else {
+                        Bridge.getLog().error(null,
+                                String.format(
+                                        "Style with id 0x%x (resolved to '%s') does not exist.",
+                                        defStyleRes, value.getSecond()),
+                                null /*data*/);
+                    }
+                } else {
+                    Bridge.getLog().error(null,
+                            String.format(
+                                    "Resouce id 0x%x is not of type STYLE (instead %s)",
+                                    defStyleRes, value.getFirst().toString()),
+                            null /*data*/);
+                }
+            } else {
+                Bridge.getLog().error(null,
+                        String.format(
+                                "Failed to find style with id 0x%x in current theme",
+                                defStyleRes),
+                        null /*data*/);
+            }
+        }
+
+        String namespace = BridgeConstants.NS_RESOURCES;
+        if (frameworkAttributes[0] == false) {
+            // need to use the application namespace
+            namespace = mProjectCallback.getNamespace();
+        }
+
+        if (styleNameMap != null) {
+            for (Entry<Integer, String> styleAttribute : styleNameMap.entrySet()) {
+                int index = styleAttribute.getKey().intValue();
+
+                String name = styleAttribute.getValue();
+                String value = null;
+                if (set != null) {
+                    value = set.getAttributeValue(namespace, name);
+                }
+
+                // if there's no direct value for this attribute in the XML, we look for default
+                // values in the widget defStyle, and then in the theme.
+                if (value == null) {
+                    ResourceValue resValue = null;
+
+                    // look for the value in the custom style first (and its parent if needed)
+                    if (customStyleValues != null) {
+                        resValue = mRenderResources.findItemInStyle(customStyleValues, name);
+                    }
+
+                    // then look for the value in the default Style (and its parent if needed)
+                    if (resValue == null && defStyleValues != null) {
+                        resValue = mRenderResources.findItemInStyle(defStyleValues, name);
+                    }
+
+                    // if the item is not present in the defStyle, we look in the main theme (and
+                    // its parent themes)
+                    if (resValue == null) {
+                        resValue = mRenderResources.findItemInTheme(name);
+                    }
+
+                    // if we found a value, we make sure this doesn't reference another value.
+                    // So we resolve it.
+                    if (resValue != null) {
+                        // put the first default value, before the resolution.
+                        if (defaultPropMap != null) {
+                            defaultPropMap.put(name, resValue.getValue());
+                        }
+
+                        resValue = mRenderResources.resolveResValue(resValue);
+                    }
+
+                    ta.bridgeSetValue(index, name, resValue);
+                } else {
+                    // there is a value in the XML, but we need to resolve it in case it's
+                    // referencing another resource or a theme value.
+                    ta.bridgeSetValue(index, name,
+                            mRenderResources.resolveValue(null, name, value, isPlatformFile));
+                }
+            }
+        }
+
+        ta.sealArray();
+
+        return ta;
+    }
+
+    @Override
+    public Looper getMainLooper() {
+        return Looper.myLooper();
+    }
+
+
+    // ------------- private new methods
+
+    /**
+     * Creates a {@link BridgeTypedArray} by filling the values defined by the int[] with the
+     * values found in the given style.
+     * @see #obtainStyledAttributes(int, int[])
+     */
+    private BridgeTypedArray createStyleBasedTypedArray(StyleResourceValue style, int[] attrs)
+            throws Resources.NotFoundException {
+        TreeMap<Integer, String> styleNameMap = searchAttrs(attrs, null);
+
+        BridgeTypedArray ta = ((BridgeResources) mSystemResources).newTypeArray(attrs.length,
+                false /* platformResourceFlag */);
+
+        // loop through all the values in the style map, and init the TypedArray with
+        // the style we got from the dynamic id
+        for (Entry<Integer, String> styleAttribute : styleNameMap.entrySet()) {
+            int index = styleAttribute.getKey().intValue();
+
+            String name = styleAttribute.getValue();
+
+            // get the value from the style, or its parent styles.
+            ResourceValue resValue = mRenderResources.findItemInStyle(style, name);
+
+            // resolve it to make sure there are no references left.
+            ta.bridgeSetValue(index, name, mRenderResources.resolveResValue(resValue));
+        }
+
+        ta.sealArray();
+
+        return ta;
+    }
+
+
+    /**
+     * The input int[] attrs is one of com.android.internal.R.styleable fields where the name
+     * of the field is the style being referenced and the array contains one index per attribute.
+     * <p/>
+     * searchAttrs() finds all the names of the attributes referenced so for example if
+     * attrs == com.android.internal.R.styleable.View, this returns the list of the "xyz" where
+     * there's a field com.android.internal.R.styleable.View_xyz and the field value is the index
+     * that is used to reference the attribute later in the TypedArray.
+     *
+     * @param attrs An attribute array reference given to obtainStyledAttributes.
+     * @return A sorted map Attribute-Value to Attribute-Name for all attributes declared by the
+     *         attribute array. Returns null if nothing is found.
+     */
+    private TreeMap<Integer,String> searchAttrs(int[] attrs, boolean[] outFrameworkFlag) {
+        // get the name of the array from the framework resources
+        String arrayName = Bridge.resolveResourceId(attrs);
+        if (arrayName != null) {
+            // if we found it, get the name of each of the int in the array.
+            TreeMap<Integer,String> attributes = new TreeMap<Integer, String>();
+            for (int i = 0 ; i < attrs.length ; i++) {
+                Pair<ResourceType, String> info = Bridge.resolveResourceId(attrs[i]);
+                if (info != null) {
+                    attributes.put(i, info.getSecond());
+                } else {
+                    // FIXME Not sure what we should be doing here...
+                    attributes.put(i, null);
+                }
+            }
+
+            if (outFrameworkFlag != null) {
+                outFrameworkFlag[0] = true;
+            }
+
+            return attributes;
+        }
+
+        // if the name was not found in the framework resources, look in the project
+        // resources
+        arrayName = mProjectCallback.resolveResourceId(attrs);
+        if (arrayName != null) {
+            TreeMap<Integer,String> attributes = new TreeMap<Integer, String>();
+            for (int i = 0 ; i < attrs.length ; i++) {
+                Pair<ResourceType, String> info = mProjectCallback.resolveResourceId(attrs[i]);
+                if (info != null) {
+                    attributes.put(i, info.getSecond());
+                } else {
+                    // FIXME Not sure what we should be doing here...
+                    attributes.put(i, null);
+                }
+            }
+
+            if (outFrameworkFlag != null) {
+                outFrameworkFlag[0] = false;
+            }
+
+            return attributes;
+        }
+
+        return null;
+    }
+
+    /**
+     * Searches for the attribute referenced by its internal id.
+     *
+     * @param attr An attribute reference given to obtainStyledAttributes such as defStyle.
+     * @return The unique name of the attribute, if found, e.g. "buttonStyle". Returns null
+     *         if nothing is found.
+     */
+    public String searchAttr(int attr) {
+        Pair<ResourceType, String> info = Bridge.resolveResourceId(attr);
+        if (info != null) {
+            return info.getSecond();
+        }
+
+        info = mProjectCallback.resolveResourceId(attr);
+        if (info != null) {
+            return info.getSecond();
+        }
+
+        return null;
+    }
+
+    int getDynamicIdByStyle(StyleResourceValue resValue) {
+        if (mDynamicIdToStyleMap == null) {
+            // create the maps.
+            mDynamicIdToStyleMap = new HashMap<Integer, StyleResourceValue>();
+            mStyleToDynamicIdMap = new HashMap<StyleResourceValue, Integer>();
+        }
+
+        // look for an existing id
+        Integer id = mStyleToDynamicIdMap.get(resValue);
+
+        if (id == null) {
+            // generate a new id
+            id = Integer.valueOf(++mDynamicIdGenerator);
+
+            // and add it to the maps.
+            mDynamicIdToStyleMap.put(id, resValue);
+            mStyleToDynamicIdMap.put(resValue, id);
+        }
+
+        return id;
+    }
+
+    private StyleResourceValue getStyleByDynamicId(int i) {
+        if (mDynamicIdToStyleMap != null) {
+            return mDynamicIdToStyleMap.get(i);
+        }
+
+        return null;
+    }
+
+    int getFrameworkResourceValue(ResourceType resType, String resName, int defValue) {
+        Integer value = Bridge.getResourceId(resType, resName);
+        if (value != null) {
+            return value.intValue();
+        }
+
+        return defValue;
+    }
+
+    int getProjectResourceValue(ResourceType resType, String resName, int defValue) {
+        if (mProjectCallback != null) {
+            Integer value = mProjectCallback.getResourceId(resType, resName);
+            if (value != null) {
+                return value.intValue();
+            }
+        }
+
+        return defValue;
+    }
+
+    //------------ NOT OVERRIDEN --------------------
+
+    @Override
+    public boolean bindService(Intent arg0, ServiceConnection arg1, int arg2) {
+        // TODO Auto-generated method stub
+        return false;
+    }
+
+    @Override
+    public int checkCallingOrSelfPermission(String arg0) {
+        // TODO Auto-generated method stub
+        return 0;
+    }
+
+    @Override
+    public int checkCallingOrSelfUriPermission(Uri arg0, int arg1) {
+        // TODO Auto-generated method stub
+        return 0;
+    }
+
+    @Override
+    public int checkCallingPermission(String arg0) {
+        // TODO Auto-generated method stub
+        return 0;
+    }
+
+    @Override
+    public int checkCallingUriPermission(Uri arg0, int arg1) {
+        // TODO Auto-generated method stub
+        return 0;
+    }
+
+    @Override
+    public int checkPermission(String arg0, int arg1, int arg2) {
+        // TODO Auto-generated method stub
+        return 0;
+    }
+
+    @Override
+    public int checkUriPermission(Uri arg0, int arg1, int arg2, int arg3) {
+        // TODO Auto-generated method stub
+        return 0;
+    }
+
+    @Override
+    public int checkUriPermission(Uri arg0, String arg1, String arg2, int arg3,
+            int arg4, int arg5) {
+        // TODO Auto-generated method stub
+        return 0;
+    }
+
+    @Override
+    public void clearWallpaper() {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public Context createPackageContext(String arg0, int arg1) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public String[] databaseList() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public boolean deleteDatabase(String arg0) {
+        // TODO Auto-generated method stub
+        return false;
+    }
+
+    @Override
+    public boolean deleteFile(String arg0) {
+        // TODO Auto-generated method stub
+        return false;
+    }
+
+    @Override
+    public void enforceCallingOrSelfPermission(String arg0, String arg1) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void enforceCallingOrSelfUriPermission(Uri arg0, int arg1,
+            String arg2) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void enforceCallingPermission(String arg0, String arg1) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void enforceCallingUriPermission(Uri arg0, int arg1, String arg2) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void enforcePermission(String arg0, int arg1, int arg2, String arg3) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void enforceUriPermission(Uri arg0, int arg1, int arg2, int arg3,
+            String arg4) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void enforceUriPermission(Uri arg0, String arg1, String arg2,
+            int arg3, int arg4, int arg5, String arg6) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public String[] fileList() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public AssetManager getAssets() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public File getCacheDir() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public File getExternalCacheDir() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public ContentResolver getContentResolver() {
+        if (mContentResolver == null) {
+            mContentResolver = new BridgeContentResolver(this);
+        }
+        return mContentResolver;
+    }
+
+    @Override
+    public File getDatabasePath(String arg0) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public File getDir(String arg0, int arg1) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public File getFileStreamPath(String arg0) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public File getFilesDir() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public File getExternalFilesDir(String type) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public String getPackageCodePath() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public PackageManager getPackageManager() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public String getPackageName() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public ApplicationInfo getApplicationInfo() {
+        return mApplicationInfo;
+    }
+
+    @Override
+    public String getPackageResourcePath() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public File getSharedPrefsFile(String name) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public SharedPreferences getSharedPreferences(String arg0, int arg1) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public Drawable getWallpaper() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public int getWallpaperDesiredMinimumWidth() {
+        return -1;
+    }
+
+    @Override
+    public int getWallpaperDesiredMinimumHeight() {
+        return -1;
+    }
+
+    @Override
+    public void grantUriPermission(String arg0, Uri arg1, int arg2) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public FileInputStream openFileInput(String arg0) throws FileNotFoundException {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public FileOutputStream openFileOutput(String arg0, int arg1) throws FileNotFoundException {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public SQLiteDatabase openOrCreateDatabase(String arg0, int arg1, CursorFactory arg2) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public Drawable peekWallpaper() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public Intent registerReceiver(BroadcastReceiver arg0, IntentFilter arg1) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public Intent registerReceiver(BroadcastReceiver arg0, IntentFilter arg1,
+            String arg2, Handler arg3) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public void removeStickyBroadcast(Intent arg0) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void revokeUriPermission(Uri arg0, int arg1) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void sendBroadcast(Intent arg0) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void sendBroadcast(Intent arg0, String arg1) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void sendOrderedBroadcast(Intent arg0, String arg1) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void sendOrderedBroadcast(Intent arg0, String arg1,
+            BroadcastReceiver arg2, Handler arg3, int arg4, String arg5,
+            Bundle arg6) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void sendStickyBroadcast(Intent arg0) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void sendStickyOrderedBroadcast(Intent intent,
+            BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData,
+           Bundle initialExtras) {
+        // TODO Auto-generated method stub
+    }
+
+    @Override
+    public void setTheme(int arg0) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void setWallpaper(Bitmap arg0) throws IOException {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void setWallpaper(InputStream arg0) throws IOException {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void startActivity(Intent arg0) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void startIntentSender(IntentSender intent,
+            Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
+            throws IntentSender.SendIntentException {
+        // TODO Auto-generated method stub
+    }
+
+    @Override
+    public boolean startInstrumentation(ComponentName arg0, String arg1,
+            Bundle arg2) {
+        // TODO Auto-generated method stub
+        return false;
+    }
+
+    @Override
+    public ComponentName startService(Intent arg0) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public boolean stopService(Intent arg0) {
+        // TODO Auto-generated method stub
+        return false;
+    }
+
+    @Override
+    public void unbindService(ServiceConnection arg0) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void unregisterReceiver(BroadcastReceiver arg0) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public Context getApplicationContext() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public boolean isRestricted() {
+        return false;
+    }
+}
diff --git a/tools/layoutlib/bridge/src/android/view/BridgeInflater.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeInflater.java
similarity index 66%
rename from tools/layoutlib/bridge/src/android/view/BridgeInflater.java
rename to tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeInflater.java
index 0910d79..edfe83e 100644
--- a/tools/layoutlib/bridge/src/android/view/BridgeInflater.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeInflater.java
@@ -14,36 +14,44 @@
  * limitations under the License.
  */
 
-package android.view;
+package com.android.layoutlib.bridge.android;
 
-import com.android.layoutlib.api.IProjectCallback;
-import com.android.layoutlib.api.IResourceValue;
+import com.android.ide.common.rendering.api.IProjectCallback;
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.ide.common.rendering.api.MergeCookie;
+import com.android.ide.common.rendering.api.ResourceReference;
+import com.android.ide.common.rendering.api.ResourceValue;
 import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.BridgeConstants;
-import com.android.layoutlib.bridge.BridgeContext;
-import com.android.layoutlib.bridge.BridgeXmlBlockParser;
+import com.android.resources.ResourceType;
+import com.android.util.Pair;
 
 import org.kxml2.io.KXmlParser;
 import org.xmlpull.v1.XmlPullParser;
 
 import android.content.Context;
 import android.util.AttributeSet;
+import android.view.InflateException;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
 
 import java.io.File;
-import java.io.FileReader;
+import java.io.FileInputStream;
 
 /**
- * Custom implementation of {@link LayoutInflater} to handle custom views. 
+ * Custom implementation of {@link LayoutInflater} to handle custom views.
  */
 public final class BridgeInflater extends LayoutInflater {
-    
+
     private final IProjectCallback mProjectCallback;
+    private boolean mIsInMerge = false;
+    private ResourceReference mResourceReference;
 
     /**
      * List of class prefixes which are tried first by default.
      * <p/>
      * This should match the list in com.android.internal.policy.impl.PhoneLayoutInflater.
-     */ 
+     */
     private static final String[] sClassPrefixList = {
         "android.widget.",
         "android.webkit."
@@ -53,10 +61,10 @@
         super(original, newContext);
         mProjectCallback = null;
     }
-    
+
     /**
      * Instantiate a new BridgeInflater with an {@link IProjectCallback} object.
-     * 
+     *
      * @param context The Android application context.
      * @param projectCallback the {@link IProjectCallback} object.
      */
@@ -82,7 +90,7 @@
                     // Ignore. We'll try again using the base class below.
                 }
             }
-    
+
             // Next try using the parent loader. This will most likely only work for
             // fully-qualified class names.
             try {
@@ -92,7 +100,7 @@
             } catch (ClassNotFoundException e) {
                 // Ignore. We'll try again using the custom view loader below.
             }
-    
+
             // Finally try again using the custom view loader
             try {
                 if (view == null) {
@@ -109,12 +117,12 @@
             ClassNotFoundException exception = new ClassNotFoundException("onCreateView", e);
             throw exception;
         }
-        
+
         setupViewInContext(view, attrs);
-        
+
         return view;
     }
-    
+
     @Override
     public View createViewFromTag(String name, AttributeSet attrs) {
         View view = null;
@@ -128,7 +136,7 @@
                 // Wrap the real exception in an InflateException so that the calling
                 // method can deal with it.
                 InflateException exception = new InflateException();
-                if (e2.getClass().equals(ClassNotFoundException.class) == false) { 
+                if (e2.getClass().equals(ClassNotFoundException.class) == false) {
                     exception.initCause(e2);
                 } else {
                     exception.initCause(e);
@@ -136,30 +144,30 @@
                 throw exception;
             }
         }
-        
+
         setupViewInContext(view, attrs);
-        
+
         return view;
     }
-    
+
     @Override
     public View inflate(int resource, ViewGroup root) {
         Context context = getContext();
         if (context instanceof BridgeContext) {
             BridgeContext bridgeContext = (BridgeContext)context;
-            
-            IResourceValue value = null;
 
-            String[] layoutInfo = Bridge.resolveResourceValue(resource);
+            ResourceValue value = null;
+
+            Pair<ResourceType, String> layoutInfo = Bridge.resolveResourceId(resource);
             if (layoutInfo != null) {
-                value = bridgeContext.getFrameworkResource(BridgeConstants.RES_LAYOUT,
-                        layoutInfo[0]);
+                value = bridgeContext.getRenderResources().getFrameworkResource(
+                        ResourceType.LAYOUT, layoutInfo.getSecond());
             } else {
-                layoutInfo = mProjectCallback.resolveResourceValue(resource);
-                
+                layoutInfo = mProjectCallback.resolveResourceId(resource);
+
                 if (layoutInfo != null) {
-                    value = bridgeContext.getProjectResource(BridgeConstants.RES_LAYOUT,
-                            layoutInfo[0]);
+                    value = bridgeContext.getRenderResources().getProjectResource(
+                            ResourceType.LAYOUT, layoutInfo.getSecond());
                 }
             }
 
@@ -169,22 +177,24 @@
                     try {
                         KXmlParser parser = new KXmlParser();
                         parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
-                        parser.setInput(new FileReader(f));
-                        
+                        parser.setInput(new FileInputStream(f), "UTF-8"); //$NON-NLS-1$
+
                         BridgeXmlBlockParser bridgeParser = new BridgeXmlBlockParser(
                                 parser, bridgeContext, false);
-                        
+
                         return inflate(bridgeParser, root);
                     } catch (Exception e) {
-                        bridgeContext.getLogger().error(e);
-                        // return null below.
+                        Bridge.getLog().error(LayoutLog.TAG_RESOURCES_READ,
+                                "Failed to parse file " + f.getAbsolutePath(), e, null /*data*/);
+
+                        return null;
                     }
                 }
             }
         }
         return null;
     }
-    
+
     private View loadCustomView(String name, AttributeSet attrs) throws ClassNotFoundException,
             Exception{
         if (mProjectCallback != null) {
@@ -192,12 +202,12 @@
             if (name.equals("view")) {
                 name = attrs.getAttributeValue(null, "class");
             }
-            
+
             mConstructorArgs[1] = attrs;
 
             Object customView = mProjectCallback.loadView(name, mConstructorSignature,
                     mConstructorArgs);
-            
+
             if (customView instanceof View) {
                 return (View)customView;
             }
@@ -205,14 +215,42 @@
 
         return null;
     }
-    
-    
-    
+
     private void setupViewInContext(View view, AttributeSet attrs) {
         if (getContext() instanceof BridgeContext) {
             BridgeContext bc = (BridgeContext) getContext();
             if (attrs instanceof BridgeXmlBlockParser) {
-                Object viewKey = ((BridgeXmlBlockParser) attrs).getViewKey();
+                BridgeXmlBlockParser parser = (BridgeXmlBlockParser) attrs;
+
+                // get the view key
+                Object viewKey = parser.getViewCookie();
+
+                if (viewKey == null) {
+                    int currentDepth = parser.getDepth();
+
+                    // test whether we are in an included file or in a adapter binding view.
+                    BridgeXmlBlockParser previousParser = bc.getPreviousParser();
+                    if (previousParser != null) {
+                        // looks like we inside an embedded layout.
+                        // only apply the cookie of the calling node (<include>) if we are at the
+                        // top level of the embedded layout. If there is a merge tag, then
+                        // skip it and look for the 2nd level
+                        int testDepth = mIsInMerge ? 2 : 1;
+                        if (currentDepth == testDepth) {
+                            viewKey = previousParser.getViewCookie();
+                            // if we are in a merge, wrap the cookie in a MergeCookie.
+                            if (viewKey != null && mIsInMerge) {
+                                viewKey = new MergeCookie(viewKey);
+                            }
+                        }
+                    } else if (mResourceReference != null && currentDepth == 1) {
+                        // else if there's a resource reference, this means we are in an adapter
+                        // binding case. Set the resource ref as the view cookie only for the top
+                        // level view.
+                        viewKey = mResourceReference;
+                    }
+                }
+
                 if (viewKey != null) {
                     bc.addViewKey(view, viewKey);
                 }
@@ -220,6 +258,14 @@
         }
     }
 
+    public void setIsInMerge(boolean isInMerge) {
+        mIsInMerge = isInMerge;
+    }
+
+    public void setResourceReference(ResourceReference reference) {
+        mResourceReference = reference;
+    }
+
     @Override
     public LayoutInflater cloneInContext(Context newContext) {
         return new BridgeInflater(this, newContext);
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeLayoutParamsMapAttributes.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeLayoutParamsMapAttributes.java
new file mode 100644
index 0000000..d208408
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeLayoutParamsMapAttributes.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.layoutlib.bridge.android;
+
+import com.android.layoutlib.bridge.BridgeConstants;
+
+import android.util.AttributeSet;
+
+import java.util.Map;
+
+/**
+ * An implementation of the {@link AttributeSet} interface on top of a map of attribute in the form
+ * of (name, value).
+ *
+ * This is meant to be called only from {@link BridgeContext#obtainStyledAttributes(AttributeSet, int[], int, int)}
+ * in the case of LayoutParams and therefore isn't a full implementation.
+ */
+public class BridgeLayoutParamsMapAttributes implements AttributeSet {
+
+    private final Map<String, String> mAttributes;
+
+    public BridgeLayoutParamsMapAttributes(Map<String, String> attributes) {
+        mAttributes = attributes;
+    }
+
+    public String getAttributeValue(String namespace, String name) {
+        if (BridgeConstants.NS_RESOURCES.equals(namespace)) {
+            return mAttributes.get(name);
+        }
+
+        return null;
+    }
+
+    // ---- the following methods are not called from
+    // BridgeContext#obtainStyledAttributes(AttributeSet, int[], int, int)
+    // Should they ever be called, we'll just implement them on a need basis.
+
+    public int getAttributeCount() {
+        throw new UnsupportedOperationException();
+    }
+
+    public String getAttributeName(int index) {
+        throw new UnsupportedOperationException();
+    }
+
+    public String getAttributeValue(int index) {
+        throw new UnsupportedOperationException();
+    }
+
+    public String getPositionDescription() {
+        throw new UnsupportedOperationException();
+    }
+
+    public int getAttributeNameResource(int index) {
+        throw new UnsupportedOperationException();
+    }
+
+    public int getAttributeListValue(String namespace, String attribute,
+            String[] options, int defaultValue) {
+        throw new UnsupportedOperationException();
+    }
+
+    public boolean getAttributeBooleanValue(String namespace, String attribute,
+            boolean defaultValue) {
+        throw new UnsupportedOperationException();
+    }
+
+    public int getAttributeResourceValue(String namespace, String attribute,
+            int defaultValue) {
+        throw new UnsupportedOperationException();
+    }
+
+    public int getAttributeIntValue(String namespace, String attribute,
+            int defaultValue) {
+        throw new UnsupportedOperationException();
+    }
+
+    public int getAttributeUnsignedIntValue(String namespace, String attribute,
+            int defaultValue) {
+        throw new UnsupportedOperationException();
+    }
+
+    public float getAttributeFloatValue(String namespace, String attribute,
+            float defaultValue) {
+        throw new UnsupportedOperationException();
+    }
+
+    public int getAttributeListValue(int index,
+            String[] options, int defaultValue) {
+        throw new UnsupportedOperationException();
+    }
+
+    public boolean getAttributeBooleanValue(int index, boolean defaultValue) {
+        throw new UnsupportedOperationException();
+    }
+
+    public int getAttributeResourceValue(int index, int defaultValue) {
+        throw new UnsupportedOperationException();
+    }
+
+    public int getAttributeIntValue(int index, int defaultValue) {
+        throw new UnsupportedOperationException();
+    }
+
+    public int getAttributeUnsignedIntValue(int index, int defaultValue) {
+        throw new UnsupportedOperationException();
+    }
+
+    public float getAttributeFloatValue(int index, float defaultValue) {
+        throw new UnsupportedOperationException();
+    }
+
+    public String getIdAttribute() {
+        throw new UnsupportedOperationException();
+    }
+
+    public String getClassAttribute() {
+        throw new UnsupportedOperationException();
+    }
+
+    public int getIdAttributeResourceValue(int defaultValue) {
+        throw new UnsupportedOperationException();
+    }
+
+    public int getStyleAttribute() {
+        throw new UnsupportedOperationException();
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeResources.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeResources.java
similarity index 66%
rename from tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeResources.java
rename to tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeResources.java
index 6358abb..345f053 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeResources.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeResources.java
@@ -14,10 +14,17 @@
  * limitations under the License.
  */
 
-package com.android.layoutlib.bridge;
+package com.android.layoutlib.bridge.android;
 
-import com.android.layoutlib.api.IProjectCallback;
-import com.android.layoutlib.api.IResourceValue;
+import com.android.ide.common.rendering.api.IProjectCallback;
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.ide.common.rendering.api.ResourceValue;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.BridgeConstants;
+import com.android.layoutlib.bridge.impl.ResourceHelper;
+import com.android.ninepatch.NinePatch;
+import com.android.resources.ResourceType;
+import com.android.util.Pair;
 
 import org.kxml2.io.KXmlParser;
 import org.xmlpull.v1.XmlPullParser;
@@ -39,7 +46,6 @@
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
-import java.io.FileReader;
 import java.io.InputStream;
 
 /**
@@ -52,6 +58,35 @@
     private boolean[] mPlatformResourceFlag = new boolean[1];
 
     /**
+     * Simpler wrapper around FileInputStream. This is used when the input stream represent
+     * not a normal bitmap but a nine patch.
+     * This is useful when the InputStream is created in a method but used in another that needs
+     * to know whether this is 9-patch or not, such as BitmapFactory.
+     */
+    public class NinePatchInputStream extends FileInputStream {
+        private boolean mFakeMarkSupport = true;
+        public NinePatchInputStream(File file) throws FileNotFoundException {
+            super(file);
+        }
+
+        @Override
+        public boolean markSupported() {
+            if (mFakeMarkSupport) {
+                // this is needed so that BitmapFactory doesn't wrap this in a BufferedInputStream.
+                return true;
+            }
+
+            return super.markSupported();
+        }
+
+        public void disableFakeMarkSupport() {
+            // disable fake mark support so that in case codec actually try to use them
+            // we don't lie to them.
+            mFakeMarkSupport = false;
+        }
+    }
+
+    /**
      * This initializes the static field {@link Resources#mSystem} which is used
      * by methods who get global resources using {@link Resources#getSystem()}.
      * <p/>
@@ -64,21 +99,18 @@
             DisplayMetrics metrics,
             Configuration config,
             IProjectCallback projectCallback) {
-        if (!(Resources.mSystem instanceof BridgeResources)) {
-            Resources.mSystem = new BridgeResources(context,
-                    assets,
-                    metrics,
-                    config,
-                    projectCallback);
-        }
-        return Resources.mSystem;
+        return Resources.mSystem = new BridgeResources(context,
+                assets,
+                metrics,
+                config,
+                projectCallback);
     }
 
     /**
-     * Clears the static {@link Resources#mSystem} to make sure we don't leave objects
+     * Disposes the static {@link Resources#mSystem} to make sure we don't leave objects
      * around that would prevent us from unloading the library.
      */
-    /*package*/ static void clearSystem() {
+    /*package*/ static void disposeSystem() {
         if (Resources.mSystem instanceof BridgeResources) {
             ((BridgeResources)(Resources.mSystem)).mContext = null;
             ((BridgeResources)(Resources.mSystem)).mProjectCallback = null;
@@ -97,22 +129,24 @@
         return new BridgeTypedArray(this, mContext, numEntries, platformFile);
     }
 
-    private IResourceValue getResourceValue(int id, boolean[] platformResFlag_out) {
+    private ResourceValue getResourceValue(int id, boolean[] platformResFlag_out) {
         // first get the String related to this id in the framework
-        String[] resourceInfo = Bridge.resolveResourceValue(id);
+        Pair<ResourceType, String> resourceInfo = Bridge.resolveResourceId(id);
 
         if (resourceInfo != null) {
             platformResFlag_out[0] = true;
-            return mContext.getFrameworkResource(resourceInfo[1], resourceInfo[0]);
+            return mContext.getRenderResources().getFrameworkResource(
+                    resourceInfo.getFirst(), resourceInfo.getSecond());
         }
 
         // didn't find a match in the framework? look in the project.
         if (mProjectCallback != null) {
-            resourceInfo = mProjectCallback.resolveResourceValue(id);
+            resourceInfo = mProjectCallback.resolveResourceId(id);
 
             if (resourceInfo != null) {
                 platformResFlag_out[0] = false;
-                return mContext.getProjectResource(resourceInfo[1], resourceInfo[0]);
+                return mContext.getRenderResources().getProjectResource(
+                        resourceInfo.getFirst(), resourceInfo.getSecond());
             }
         }
 
@@ -121,10 +155,10 @@
 
     @Override
     public Drawable getDrawable(int id) throws NotFoundException {
-        IResourceValue value = getResourceValue(id, mPlatformResourceFlag);
+        ResourceValue value = getResourceValue(id, mPlatformResourceFlag);
 
         if (value != null) {
-            return ResourceHelper.getDrawable(value, mContext, value.isFramework());
+            return ResourceHelper.getDrawable(value, mContext);
         }
 
         // id was not found or not resolved. Throw a NotFoundException.
@@ -136,12 +170,14 @@
 
     @Override
     public int getColor(int id) throws NotFoundException {
-        IResourceValue value = getResourceValue(id, mPlatformResourceFlag);
+        ResourceValue value = getResourceValue(id, mPlatformResourceFlag);
 
         if (value != null) {
             try {
                 return ResourceHelper.getColor(value.getValue());
             } catch (NumberFormatException e) {
+                Bridge.getLog().error(LayoutLog.TAG_RESOURCES_FORMAT, e.getMessage(), e,
+                        null /*data*/);
                 return 0;
             }
         }
@@ -155,14 +191,12 @@
 
     @Override
     public ColorStateList getColorStateList(int id) throws NotFoundException {
-        IResourceValue value = getResourceValue(id, mPlatformResourceFlag);
+        ResourceValue resValue = getResourceValue(id, mPlatformResourceFlag);
 
-        if (value != null) {
-            try {
-                int color = ResourceHelper.getColor(value.getValue());
-                return ColorStateList.valueOf(color);
-            } catch (NumberFormatException e) {
-                return null;
+        if (resValue != null) {
+            ColorStateList stateList = ResourceHelper.getColorStateList(resValue, mContext);
+            if (stateList != null) {
+                return stateList;
             }
         }
 
@@ -175,7 +209,7 @@
 
     @Override
     public CharSequence getText(int id) throws NotFoundException {
-        IResourceValue value = getResourceValue(id, mPlatformResourceFlag);
+        ResourceValue value = getResourceValue(id, mPlatformResourceFlag);
 
         if (value != null) {
             return value.getValue();
@@ -190,27 +224,75 @@
 
     @Override
     public XmlResourceParser getLayout(int id) throws NotFoundException {
-        IResourceValue value = getResourceValue(id, mPlatformResourceFlag);
+        ResourceValue value = getResourceValue(id, mPlatformResourceFlag);
 
         if (value != null) {
-            File xml = new File(value.getValue());
-            if (xml.isFile()) {
-                // we need to create a pull parser around the layout XML file, and then
-                // give that to our XmlBlockParser
-                try {
-                    KXmlParser parser = new KXmlParser();
+            XmlPullParser parser = null;
+
+            try {
+                // check if the current parser can provide us with a custom parser.
+                if (mPlatformResourceFlag[0] == false) {
+                    parser = mProjectCallback.getParser(value.getName());
+                }
+
+                // create a new one manually if needed.
+                if (parser == null) {
+                    File xml = new File(value.getValue());
+                    if (xml.isFile()) {
+                        // we need to create a pull parser around the layout XML file, and then
+                        // give that to our XmlBlockParser
+                        parser = new KXmlParser();
+                        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
+                        parser.setInput(new FileInputStream(xml), "UTF-8"); //$NON-NLS-1$);
+                    }
+                }
+
+                if (parser != null) {
+                    return new BridgeXmlBlockParser(parser, mContext, mPlatformResourceFlag[0]);
+                }
+            } catch (XmlPullParserException e) {
+                Bridge.getLog().error(LayoutLog.TAG_BROKEN,
+                        "Failed to configure parser for " + value.getValue(), e, null /*data*/);
+                // we'll return null below.
+            } catch (FileNotFoundException e) {
+                // this shouldn't happen since we check above.
+            }
+
+        }
+
+        // id was not found or not resolved. Throw a NotFoundException.
+        throwException(id);
+
+        // this is not used since the method above always throws
+        return null;
+    }
+
+    @Override
+    public XmlResourceParser getAnimation(int id) throws NotFoundException {
+        ResourceValue value = getResourceValue(id, mPlatformResourceFlag);
+
+        if (value != null) {
+            XmlPullParser parser = null;
+
+            try {
+                File xml = new File(value.getValue());
+                if (xml.isFile()) {
+                    // we need to create a pull parser around the layout XML file, and then
+                    // give that to our XmlBlockParser
+                    parser = new KXmlParser();
                     parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
-                    parser.setInput(new FileReader(xml));
+                    parser.setInput(new FileInputStream(xml), "UTF-8"); //$NON-NLS-1$);
 
                     return new BridgeXmlBlockParser(parser, mContext, mPlatformResourceFlag[0]);
-                } catch (XmlPullParserException e) {
-                    mContext.getLogger().error(e);
-
-                    // we'll return null below.
-                } catch (FileNotFoundException e) {
-                    // this shouldn't happen since we check above.
                 }
+            } catch (XmlPullParserException e) {
+                Bridge.getLog().error(LayoutLog.TAG_BROKEN,
+                        "Failed to configure parser for " + value.getValue(), e, null /*data*/);
+                // we'll return null below.
+            } catch (FileNotFoundException e) {
+                // this shouldn't happen since we check above.
             }
+
         }
 
         // id was not found or not resolved. Throw a NotFoundException.
@@ -233,7 +315,7 @@
 
     @Override
     public float getDimension(int id) throws NotFoundException {
-        IResourceValue value = getResourceValue(id, mPlatformResourceFlag);
+        ResourceValue value = getResourceValue(id, mPlatformResourceFlag);
 
         if (value != null) {
             String v = value.getValue();
@@ -262,7 +344,7 @@
 
     @Override
     public int getDimensionPixelOffset(int id) throws NotFoundException {
-        IResourceValue value = getResourceValue(id, mPlatformResourceFlag);
+        ResourceValue value = getResourceValue(id, mPlatformResourceFlag);
 
         if (value != null) {
             String v = value.getValue();
@@ -284,7 +366,7 @@
 
     @Override
     public int getDimensionPixelSize(int id) throws NotFoundException {
-        IResourceValue value = getResourceValue(id, mPlatformResourceFlag);
+        ResourceValue value = getResourceValue(id, mPlatformResourceFlag);
 
         if (value != null) {
             String v = value.getValue();
@@ -306,7 +388,7 @@
 
     @Override
     public int getInteger(int id) throws NotFoundException {
-        IResourceValue value = getResourceValue(id, mPlatformResourceFlag);
+        ResourceValue value = getResourceValue(id, mPlatformResourceFlag);
 
         if (value != null && value.getValue() != null) {
             String v = value.getValue();
@@ -361,7 +443,7 @@
 
     @Override
     public String getString(int id) throws NotFoundException {
-        IResourceValue value = getResourceValue(id, mPlatformResourceFlag);
+        ResourceValue value = getResourceValue(id, mPlatformResourceFlag);
 
         if (value != null && value.getValue() != null) {
             return value.getValue();
@@ -377,7 +459,7 @@
     @Override
     public void getValue(int id, TypedValue outValue, boolean resolveRefs)
             throws NotFoundException {
-        IResourceValue value = getResourceValue(id, mPlatformResourceFlag);
+        ResourceValue value = getResourceValue(id, mPlatformResourceFlag);
 
         if (value != null) {
             String v = value.getValue();
@@ -406,7 +488,7 @@
 
     @Override
     public XmlResourceParser getXml(int id) throws NotFoundException {
-        IResourceValue value = getResourceValue(id, mPlatformResourceFlag);
+        ResourceValue value = getResourceValue(id, mPlatformResourceFlag);
 
         if (value != null) {
             String v = value.getValue();
@@ -418,7 +500,7 @@
                     try {
                         KXmlParser parser = new KXmlParser();
                         parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
-                        parser.setInput(new FileReader(f));
+                        parser.setInput(new FileInputStream(f), "UTF-8"); //$NON-NLS-1$);
 
                         return new BridgeXmlBlockParser(parser, mContext, mPlatformResourceFlag[0]);
                     } catch (XmlPullParserException e) {
@@ -453,7 +535,7 @@
         try {
             KXmlParser parser = new KXmlParser();
             parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
-            parser.setInput(new FileReader(f));
+            parser.setInput(new FileInputStream(f), "UTF-8"); //$NON-NLS-1$);
 
             return new BridgeXmlBlockParser(parser, mContext, mPlatformResourceFlag[0]);
         } catch (XmlPullParserException e) {
@@ -470,16 +552,22 @@
 
     @Override
     public InputStream openRawResource(int id) throws NotFoundException {
-        IResourceValue value = getResourceValue(id, mPlatformResourceFlag);
+        ResourceValue value = getResourceValue(id, mPlatformResourceFlag);
 
         if (value != null) {
-            String v = value.getValue();
+            String path = value.getValue();
 
-            if (v != null) {
+            if (path != null) {
                 // check this is a file
-                File f = new File(value.getValue());
+                File f = new File(path);
                 if (f.isFile()) {
                     try {
+                        // if it's a nine-patch return a custom input stream so that
+                        // other methods (mainly bitmap factory) can detect it's a 9-patch
+                        // and actually load it as a 9-patch instead of a normal bitmap
+                        if (path.toLowerCase().endsWith(NinePatch.EXTENSION_9PATCH)) {
+                            return new NinePatchInputStream(f);
+                        }
                         return new FileInputStream(f);
                     } catch (FileNotFoundException e) {
                         NotFoundException newE = new NotFoundException();
@@ -501,9 +589,17 @@
     public InputStream openRawResource(int id, TypedValue value) throws NotFoundException {
         getValue(id, value, true);
 
-        File f = new File(value.string.toString());
+        String path = value.string.toString();
+
+        File f = new File(path);
         if (f.isFile()) {
             try {
+                // if it's a nine-patch return a custom input stream so that
+                // other methods (mainly bitmap factory) can detect it's a 9-patch
+                // and actually load it as a 9-patch instead of a normal bitmap
+                if (path.toLowerCase().endsWith(NinePatch.EXTENSION_9PATCH)) {
+                    return new NinePatchInputStream(f);
+                }
                 return new FileInputStream(f);
             } catch (FileNotFoundException e) {
                 NotFoundException exception = new NotFoundException();
@@ -527,18 +623,18 @@
      */
     private void throwException(int id) throws NotFoundException {
         // first get the String related to this id in the framework
-        String[] resourceInfo = Bridge.resolveResourceValue(id);
+        Pair<ResourceType, String> resourceInfo = Bridge.resolveResourceId(id);
 
         // if the name is unknown in the framework, get it from the custom view loader.
         if (resourceInfo == null && mProjectCallback != null) {
-            resourceInfo = mProjectCallback.resolveResourceValue(id);
+            resourceInfo = mProjectCallback.resolveResourceId(id);
         }
 
         String message = null;
         if (resourceInfo != null) {
             message = String.format(
                     "Could not find %1$s resource matching value 0x%2$X (resolved name: %3$s) in current configuration.",
-                    resourceInfo[1], id, resourceInfo[0]);
+                    resourceInfo.getFirst(), id, resourceInfo.getSecond());
         } else {
             message = String.format(
                     "Could not resolve resource value: 0x%1$X.", id);
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeTypedArray.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeTypedArray.java
similarity index 68%
rename from tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeTypedArray.java
rename to tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeTypedArray.java
index 70c5bd7..d4600a1 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeTypedArray.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeTypedArray.java
@@ -14,14 +14,21 @@
  * limitations under the License.
  */
 
-package com.android.layoutlib.bridge;
+package com.android.layoutlib.bridge.android;
 
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.ide.common.rendering.api.RenderResources;
+import com.android.ide.common.rendering.api.ResourceValue;
+import com.android.ide.common.rendering.api.StyleResourceValue;
 import com.android.internal.util.XmlUtils;
-import com.android.layoutlib.api.IResourceValue;
-import com.android.layoutlib.api.IStyleResourceValue;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.BridgeConstants;
+import com.android.layoutlib.bridge.impl.ResourceHelper;
+import com.android.resources.ResourceType;
 
 import org.kxml2.io.KXmlParser;
 import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
 
 import android.content.res.ColorStateList;
 import android.content.res.Resources;
@@ -29,43 +36,43 @@
 import android.graphics.drawable.Drawable;
 import android.util.DisplayMetrics;
 import android.util.TypedValue;
+import android.view.LayoutInflater_Delegate;
 import android.view.ViewGroup.LayoutParams;
 
 import java.io.File;
-import java.io.FileReader;
+import java.io.FileInputStream;
+import java.util.Arrays;
 import java.util.Map;
 
 /**
- * TODO: describe.
+ * Custom implementation of TypedArray to handle non compiled resources.
  */
 public final class BridgeTypedArray extends TypedArray {
 
-    @SuppressWarnings("hiding")
-    private BridgeResources mResources;
+    private BridgeResources mBridgeResources;
     private BridgeContext mContext;
-    @SuppressWarnings("hiding")
-    private IResourceValue[] mData;
+    private ResourceValue[] mResourceData;
     private String[] mNames;
     private final boolean mPlatformFile;
 
     public BridgeTypedArray(BridgeResources resources, BridgeContext context, int len,
             boolean platformFile) {
         super(null, null, null, 0);
-        mResources = resources;
+        mBridgeResources = resources;
         mContext = context;
         mPlatformFile = platformFile;
-        mData = new IResourceValue[len];
+        mResourceData = new ResourceValue[len];
         mNames = new String[len];
     }
 
     /** A bridge-specific method that sets a value in the type array */
-    public void bridgeSetValue(int index, String name, IResourceValue value) {
-        mData[index] = value;
+    public void bridgeSetValue(int index, String name, ResourceValue value) {
+        mResourceData[index] = value;
         mNames[index] = name;
     }
 
     /**
-     * Seals the array after all calls to {@link #bridgeSetValue(int, String, IResourceValue)} have
+     * Seals the array after all calls to {@link #bridgeSetValue(int, String, ResourceValue)} have
      * been done.
      * <p/>This allows to compute the list of non default values, permitting
      * {@link #getIndexCount()} to return the proper value.
@@ -74,7 +81,7 @@
         // fills TypedArray.mIndices which is used to implement getIndexCount/getIndexAt
         // first count the array size
         int count = 0;
-        for (IResourceValue data : mData) {
+        for (ResourceValue data : mResourceData) {
             if (data != null) {
                 count++;
             }
@@ -86,8 +93,8 @@
 
         // fill the array with the indices.
         int index = 1;
-        for (int i = 0 ; i < mData.length ; i++) {
-            if (mData[i] != null) {
+        for (int i = 0 ; i < mResourceData.length ; i++) {
+            if (mResourceData[i] != null) {
                 mIndices[index++] = i;
             }
         }
@@ -98,7 +105,7 @@
      */
     @Override
     public int length() {
-        return mData.length;
+        return mResourceData.length;
     }
 
     /**
@@ -106,7 +113,7 @@
      */
     @Override
     public Resources getResources() {
-        return mResources;
+        return mBridgeResources;
     }
 
     /**
@@ -119,9 +126,9 @@
      */
     @Override
     public CharSequence getText(int index) {
-        if (mData[index] != null) {
+        if (mResourceData[index] != null) {
             // FIXME: handle styled strings!
-            return mData[index].getValue();
+            return mResourceData[index].getValue();
         }
 
         return null;
@@ -137,8 +144,8 @@
      */
     @Override
     public String getString(int index) {
-        if (mData[index] != null) {
-            return mData[index].getValue();
+        if (mResourceData[index] != null) {
+            return mResourceData[index].getValue();
         }
 
         return null;
@@ -154,11 +161,11 @@
      */
     @Override
     public boolean getBoolean(int index, boolean defValue) {
-        if (mData[index] == null) {
+        if (mResourceData[index] == null) {
             return defValue;
         }
 
-        String s = mData[index].getValue();
+        String s = mResourceData[index].getValue();
         if (s != null) {
             return XmlUtils.convertValueToBoolean(s, defValue);
         }
@@ -176,11 +183,15 @@
      */
     @Override
     public int getInt(int index, int defValue) {
-        if (mData[index] == null) {
+        if (mResourceData[index] == null) {
             return defValue;
         }
 
-        String s = mData[index].getValue();
+        String s = mResourceData[index].getValue();
+
+        if (RenderResources.REFERENCE_NULL.equals(s)) {
+            return defValue;
+        }
 
         try {
             return (s == null) ? defValue : XmlUtils.convertValueToInt(s, defValue);
@@ -204,9 +215,10 @@
                 if (i != null) {
                     result |= i.intValue();
                 } else {
-                    mContext.getLogger().warning(String.format(
-                            "Unknown constant \"%s\" in attribute \"%2$s\"",
-                            keyword, mNames[index]));
+                    Bridge.getLog().warning(LayoutLog.TAG_RESOURCES_FORMAT,
+                            String.format(
+                                "\"%s\" in attribute \"%2$s\" is not a valid value",
+                                keyword, mNames[index]), null /*data*/);
                 }
             }
             return result;
@@ -224,19 +236,20 @@
      */
     @Override
     public float getFloat(int index, float defValue) {
-        if (mData[index] == null) {
+        if (mResourceData[index] == null) {
             return defValue;
         }
 
-        String s = mData[index].getValue();
+        String s = mResourceData[index].getValue();
 
         if (s != null) {
             try {
                 return Float.parseFloat(s);
             } catch (NumberFormatException e) {
-                mContext.getLogger().warning(String.format(
-                        "Unable to convert \"%s\" into a float in attribute \"%2$s\"",
-                        s, mNames[index]));
+                Bridge.getLog().warning(LayoutLog.TAG_RESOURCES_FORMAT,
+                        String.format(
+                            "\"%s\" in attribute \"%2$s\" cannot be converted to float.",
+                            s, mNames[index]), null /*data*/);
 
                 // we'll return the default value below.
             }
@@ -258,19 +271,14 @@
      */
     @Override
     public int getColor(int index, int defValue) {
-        if (mData[index] == null) {
+        if (mResourceData[index] == null) {
             return defValue;
         }
 
-        String s = mData[index].getValue();
-        try {
-            return ResourceHelper.getColor(s);
-        } catch (NumberFormatException e) {
-            mContext.getLogger().warning(String.format(
-                    "Unable to convert \"%s\" into a color in attribute \"%2$s\"",
-                    s, mNames[index]));
-
-            // we'll return the default value below.
+        ColorStateList colorStateList = ResourceHelper.getColorStateList(
+                mResourceData[index], mContext);
+        if (colorStateList != null) {
+            return colorStateList.getDefaultColor();
         }
 
         return defValue;
@@ -287,50 +295,57 @@
      */
     @Override
     public ColorStateList getColorStateList(int index) {
-        if (mData[index] == null) {
+        if (mResourceData[index] == null) {
             return null;
         }
 
-        String value = mData[index].getValue();
+        ResourceValue resValue = mResourceData[index];
+        String value = resValue.getValue();
 
         if (value == null) {
             return null;
         }
 
+        if (RenderResources.REFERENCE_NULL.equals(value)) {
+            return null;
+        }
+
+        // let the framework inflate the ColorStateList from the XML file.
+        File f = new File(value);
+        if (f.isFile()) {
+            try {
+                KXmlParser parser = new KXmlParser();
+                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
+                parser.setInput(new FileInputStream(f), "UTF-8"); //$NON-NLS-1$);
+
+                BridgeXmlBlockParser blockParser = new BridgeXmlBlockParser(
+                        parser, mContext, resValue.isFramework());
+                try {
+                    return ColorStateList.createFromXml(mContext.getResources(), blockParser);
+                } finally {
+                    blockParser.ensurePopped();
+                }
+            } catch (XmlPullParserException e) {
+                Bridge.getLog().error(LayoutLog.TAG_BROKEN,
+                        "Failed to configure parser for " + value, e, null /*data*/);
+                return null;
+            } catch (Exception e) {
+                // this is an error and not warning since the file existence is checked before
+                // attempting to parse it.
+                Bridge.getLog().error(LayoutLog.TAG_RESOURCES_READ,
+                        "Failed to parse file " + value, e, null /*data*/);
+
+                return null;
+            }
+        }
+
         try {
             int color = ResourceHelper.getColor(value);
             return ColorStateList.valueOf(color);
         } catch (NumberFormatException e) {
-            // if it's not a color value, we'll attempt to read the xml based color below.
+            Bridge.getLog().error(LayoutLog.TAG_RESOURCES_FORMAT, e.getMessage(), e, null /*data*/);
         }
 
-        // let the framework inflate the ColorStateList from the XML file.
-        try {
-            File f = new File(value);
-            if (f.isFile()) {
-                KXmlParser parser = new KXmlParser();
-                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
-                parser.setInput(new FileReader(f));
-
-                ColorStateList colorStateList = ColorStateList.createFromXml(
-                        mContext.getResources(),
-                        // FIXME: we need to know if this resource is platform or not
-                        new BridgeXmlBlockParser(parser, mContext, false));
-                return colorStateList;
-            }
-        } catch (Exception e) {
-            // this is an error and not warning since the file existence is checked before
-            // attempting to parse it.
-            mContext.getLogger().error(e);
-
-            // return null below.
-        }
-
-        // looks like were unable to resolve the color value.
-        mContext.getLogger().warning(String.format(
-                "Unable to resolve color value \"%1$s\" in attribute \"%2$s\"",
-                value, mNames[index]));
-
         return null;
     }
 
@@ -345,19 +360,20 @@
      */
     @Override
     public int getInteger(int index, int defValue) {
-        if (mData[index] == null) {
+        if (mResourceData[index] == null) {
             return defValue;
         }
 
-        String s = mData[index].getValue();
+        String s = mResourceData[index].getValue();
 
         if (s != null) {
             try {
                 return Integer.parseInt(s);
             } catch (NumberFormatException e) {
-                mContext.getLogger().warning(String.format(
-                        "Unable to convert \"%s\" into a integer in attribute \"%2$s\"",
-                        s, mNames[index]));
+                Bridge.getLog().warning(LayoutLog.TAG_RESOURCES_FORMAT,
+                        String.format(
+                            "\"%s\" in attribute \"%2$s\" cannont be converted to an integer.",
+                            s, mNames[index]), null /*data*/);
 
                 // The default value is returned below.
             }
@@ -384,11 +400,11 @@
      */
     @Override
     public float getDimension(int index, float defValue) {
-        if (mData[index] == null) {
+        if (mResourceData[index] == null) {
             return defValue;
         }
 
-        String s = mData[index].getValue();
+        String s = mResourceData[index].getValue();
 
         if (s == null) {
             return defValue;
@@ -397,16 +413,19 @@
             return LayoutParams.MATCH_PARENT;
         } else if (s.equals(BridgeConstants.WRAP_CONTENT)) {
             return LayoutParams.WRAP_CONTENT;
+        } else if (RenderResources.REFERENCE_NULL.equals(s)) {
+            return defValue;
         }
 
         if (ResourceHelper.stringToFloat(s, mValue)) {
-            return mValue.getDimension(mResources.mMetrics);
+            return mValue.getDimension(mBridgeResources.mMetrics);
         }
 
         // looks like we were unable to resolve the dimension value
-        mContext.getLogger().warning(String.format(
-                "Unable to resolve dimension value \"%1$s\" in attribute \"%2$s\"",
-                s, mNames[index]));
+        Bridge.getLog().warning(LayoutLog.TAG_RESOURCES_FORMAT,
+                String.format(
+                    "\"%1$s\" in attribute \"%2$s\" is not a valid format.",
+                    s, mNames[index]), null /*data*/);
 
         return defValue;
     }
@@ -453,31 +472,23 @@
      */
     @Override
     public int getDimensionPixelSize(int index, int defValue) {
-        if (mData[index] == null) {
+        try {
+            return getDimension(index);
+        } catch (RuntimeException e) {
+            if (mResourceData[index] != null) {
+                String s = mResourceData[index].getValue();
+
+                if (s != null) {
+                    // looks like we were unable to resolve the dimension value
+                    Bridge.getLog().warning(LayoutLog.TAG_RESOURCES_FORMAT,
+                            String.format(
+                                "\"%1$s\" in attribute \"%2$s\" is not a valid format.",
+                                s, mNames[index]), null /*data*/);
+                }
+            }
+
             return defValue;
         }
-
-        String s = mData[index].getValue();
-
-        if (s == null) {
-            return defValue;
-        } else if (s.equals(BridgeConstants.MATCH_PARENT) ||
-                s.equals(BridgeConstants.FILL_PARENT)) {
-            return LayoutParams.MATCH_PARENT;
-        } else if (s.equals(BridgeConstants.WRAP_CONTENT)) {
-            return LayoutParams.WRAP_CONTENT;
-        }
-
-        // FIXME huh?
-
-        float f = getDimension(index, defValue);
-        final int res = (int)(f+0.5f);
-        if (res != 0) return res;
-        if (f == 0) return 0;
-        if (f > 0) return 1;
-
-        throw new UnsupportedOperationException("Can't convert to dimension: " +
-                Integer.toString(index));
     }
 
     /**
@@ -494,7 +505,20 @@
      */
     @Override
     public int getLayoutDimension(int index, String name) {
-        return getDimensionPixelSize(index, 0);
+        try {
+            // this will throw an exception
+            return getDimension(index);
+        } catch (RuntimeException e) {
+
+            if (LayoutInflater_Delegate.sIsInInclude) {
+                throw new RuntimeException();
+            }
+
+            Bridge.getLog().warning(LayoutLog.TAG_RESOURCES_FORMAT,
+                    "You must supply a " + name + " attribute.", null);
+
+            return 0;
+        }
     }
 
     @Override
@@ -502,6 +526,36 @@
         return getDimensionPixelSize(index, defValue);
     }
 
+    private int getDimension(int index) {
+        if (mResourceData[index] == null) {
+            throw new RuntimeException();
+        }
+
+        String s = mResourceData[index].getValue();
+
+        if (s == null) {
+            throw new RuntimeException();
+        } else if (s.equals(BridgeConstants.MATCH_PARENT) ||
+                s.equals(BridgeConstants.FILL_PARENT)) {
+            return LayoutParams.MATCH_PARENT;
+        } else if (s.equals(BridgeConstants.WRAP_CONTENT)) {
+            return LayoutParams.WRAP_CONTENT;
+        } else if (RenderResources.REFERENCE_NULL.equals(s)) {
+            throw new RuntimeException();
+        }
+
+        if (ResourceHelper.stringToFloat(s, mValue)) {
+            float f = mValue.getDimension(mBridgeResources.mMetrics);
+
+            final int res = (int)(f+0.5f);
+            if (res != 0) return res;
+            if (f == 0) return 0;
+            if (f > 0) return 1;
+        }
+
+        throw new RuntimeException();
+    }
+
     /**
      * Retrieve a fractional unit attribute at <var>index</var>.
      *
@@ -519,11 +573,11 @@
      */
     @Override
     public float getFraction(int index, int base, int pbase, float defValue) {
-        if (mData[index] == null) {
+        if (mResourceData[index] == null) {
             return defValue;
         }
 
-        String value = mData[index].getValue();
+        String value = mResourceData[index].getValue();
         if (value == null) {
             return defValue;
         }
@@ -533,9 +587,10 @@
         }
 
         // looks like we were unable to resolve the fraction value
-        mContext.getLogger().warning(String.format(
-                "Unable to resolve fraction value \"%1$s\" in attribute \"%2$s\"",
-                value, mNames[index]));
+        Bridge.getLog().warning(LayoutLog.TAG_RESOURCES_FORMAT,
+                String.format(
+                    "\"%1$s\" in attribute \"%2$s\" cannont be converted to a fraction.",
+                    value, mNames[index]), null /*data*/);
 
         return defValue;
     }
@@ -556,8 +611,8 @@
      */
     @Override
     public int getResourceId(int index, int defValue) {
-        // get the IResource for this index
-        IResourceValue resValue = mData[index];
+        // get the Resource for this index
+        ResourceValue resValue = mResourceData[index];
 
         // no data, return the default value.
         if (resValue == null) {
@@ -565,24 +620,30 @@
         }
 
         // check if this is a style resource
-        if (resValue instanceof IStyleResourceValue) {
+        if (resValue instanceof StyleResourceValue) {
             // get the id that will represent this style.
-            return mContext.getDynamicIdByStyle((IStyleResourceValue)resValue);
+            return mContext.getDynamicIdByStyle((StyleResourceValue)resValue);
         }
 
-        // if the attribute was a reference to an id, and not a declaration of an id (@+id), then
-        // the xml attribute value was "resolved" which leads us to a IResourceValue with
-        // getType() returning "id" and getName() returning the id name
+        if (RenderResources.REFERENCE_NULL.equals(resValue.getValue())) {
+            return defValue;
+        }
+
+        // if the attribute was a reference to a resource, and not a declaration of an id (@+id),
+        // then the xml attribute value was "resolved" which leads us to a ResourceValue with a
+        // valid getType() and getName() returning a resource name.
         // (and getValue() returning null!). We need to handle this!
-        if (resValue.getType() != null && resValue.getType().equals(BridgeConstants.RES_ID)) {
+        if (resValue.getResourceType() != null) {
             // if this is a framework id
             if (mPlatformFile || resValue.isFramework()) {
                 // look for idName in the android R classes
-                return mContext.getFrameworkIdValue(resValue.getName(), defValue);
+                return mContext.getFrameworkResourceValue(
+                        resValue.getResourceType(), resValue.getName(), defValue);
             }
 
             // look for idName in the project R class.
-            return mContext.getProjectIdValue(resValue.getName(), defValue);
+            return mContext.getProjectResourceValue(
+                    resValue.getResourceType(), resValue.getName(), defValue);
         }
 
         // else, try to get the value, and resolve it somehow.
@@ -619,29 +680,33 @@
             // if this is a framework id
             if (mPlatformFile || value.startsWith("@android") || value.startsWith("@+android")) {
                 // look for idName in the android R classes
-                return mContext.getFrameworkIdValue(idName, defValue);
+                return mContext.getFrameworkResourceValue(ResourceType.ID, idName, defValue);
             }
 
             // look for idName in the project R class.
-            return mContext.getProjectIdValue(idName, defValue);
+            return mContext.getProjectResourceValue(ResourceType.ID, idName, defValue);
         }
 
         // not a direct id valid reference? resolve it
         Integer idValue = null;
 
         if (resValue.isFramework()) {
-            idValue = Bridge.getResourceValue(resValue.getType(), resValue.getName());
+            idValue = Bridge.getResourceId(resValue.getResourceType(),
+                    resValue.getName());
         } else {
-            idValue = mContext.getProjectCallback().getResourceValue(
-                    resValue.getType(), resValue.getName());
+            idValue = mContext.getProjectCallback().getResourceId(
+                    resValue.getResourceType(), resValue.getName());
         }
 
         if (idValue != null) {
             return idValue.intValue();
         }
 
-        mContext.getLogger().warning(String.format(
-                "Unable to resolve id \"%1$s\" for attribute \"%2$s\"", value, mNames[index]));
+        Bridge.getLog().warning(LayoutLog.TAG_RESOURCES_RESOLVE,
+                String.format(
+                    "Unable to resolve id \"%1$s\" for attribute \"%2$s\"", value, mNames[index]),
+                    resValue);
+
         return defValue;
     }
 
@@ -657,28 +722,17 @@
      */
     @Override
     public Drawable getDrawable(int index) {
-        if (mData[index] == null) {
+        if (mResourceData[index] == null) {
             return null;
         }
 
-        IResourceValue value = mData[index];
+        ResourceValue value = mResourceData[index];
         String stringValue = value.getValue();
-        if (stringValue == null || BridgeConstants.REFERENCE_NULL.equals(stringValue)) {
+        if (stringValue == null || RenderResources.REFERENCE_NULL.equals(stringValue)) {
             return null;
         }
 
-        Drawable d = ResourceHelper.getDrawable(value, mContext, mData[index].isFramework());
-
-        if (d != null) {
-            return d;
-        }
-
-        // looks like we were unable to resolve the drawable
-        mContext.getLogger().warning(String.format(
-                "Unable to resolve drawable \"%1$s\" in attribute \"%2$s\"", stringValue,
-                mNames[index]));
-
-        return null;
+        return ResourceHelper.getDrawable(value, mContext);
     }
 
 
@@ -694,18 +748,23 @@
      */
     @Override
     public CharSequence[] getTextArray(int index) {
-        if (mData[index] == null) {
+        if (mResourceData[index] == null) {
             return null;
         }
 
-        String value = mData[index].getValue();
+        String value = mResourceData[index].getValue();
         if (value != null) {
+            if (RenderResources.REFERENCE_NULL.equals(value)) {
+                return null;
+            }
+
             return new CharSequence[] { value };
         }
 
-        mContext.getLogger().warning(String.format(
-                String.format("Unknown value for getTextArray(%d) => %s", //DEBUG
-                index, mData[index].getName())));
+        Bridge.getLog().warning(LayoutLog.TAG_RESOURCES_FORMAT,
+                String.format(
+                    String.format("Unknown value for getTextArray(%d) => %s", //DEBUG
+                    index, mResourceData[index].getName())), null /*data*/);
 
         return null;
     }
@@ -721,11 +780,11 @@
      */
     @Override
     public boolean getValue(int index, TypedValue outValue) {
-        if (mData[index] == null) {
+        if (mResourceData[index] == null) {
             return false;
         }
 
-        String s = mData[index].getValue();
+        String s = mResourceData[index].getValue();
 
         return ResourceHelper.stringToFloat(s, outValue);
     }
@@ -739,7 +798,7 @@
      */
     @Override
     public boolean hasValue(int index) {
-        return mData[index] != null;
+        return mResourceData[index] != null;
     }
 
     /**
@@ -786,6 +845,6 @@
 
     @Override
     public String toString() {
-        return mData.toString();
+        return Arrays.toString(mResourceData);
     }
  }
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindow.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindow.java
new file mode 100644
index 0000000..0efa102
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindow.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.layoutlib.bridge.android;
+
+import android.content.res.Configuration;
+import android.graphics.Rect;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.ParcelFileDescriptor;
+import android.os.RemoteException;
+import android.view.IWindow;
+import android.view.KeyEvent;
+import android.view.MotionEvent;
+import android.view.View.AttachInfo;
+
+/**
+ * Implementation of {@link IWindow} to pass to the {@link AttachInfo}.
+ */
+public final class BridgeWindow implements IWindow {
+
+    public void dispatchAppVisibility(boolean arg0) throws RemoteException {
+        // pass for now.
+    }
+
+    public void dispatchGetNewSurface() throws RemoteException {
+        // pass for now.
+    }
+
+    public void dispatchKey(KeyEvent arg0) throws RemoteException {
+        // pass for now.
+    }
+
+    public void dispatchPointer(MotionEvent arg0, long arg1, boolean arg2) throws RemoteException {
+        // pass for now.
+    }
+
+    public void dispatchTrackball(MotionEvent arg0, long arg1, boolean arg2)
+    throws RemoteException {
+        // pass for now.
+    }
+
+    public void executeCommand(String arg0, String arg1, ParcelFileDescriptor arg2)
+            throws RemoteException {
+        // pass for now.
+    }
+
+    public void resized(int arg0, int arg1, Rect arg2, Rect arg3, boolean arg4, Configuration arg5)
+            throws RemoteException {
+        // pass for now.
+    }
+
+    public void windowFocusChanged(boolean arg0, boolean arg1) throws RemoteException {
+        // pass for now.
+    }
+
+    public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
+            boolean sync) {
+        // pass for now.
+    }
+
+    public void dispatchWallpaperCommand(String action, int x, int y,
+            int z, Bundle extras, boolean sync) {
+        // pass for now.
+    }
+
+    public void closeSystemDialogs(String reason) {
+        // pass for now.
+    }
+
+    public void dispatchSystemUiVisibilityChanged(int visibility) {
+        // pass for now.
+    }
+
+    public IBinder asBinder() {
+        // pass for now.
+        return null;
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowSession.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowSession.java
new file mode 100644
index 0000000..7866bfa
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowSession.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.layoutlib.bridge.android;
+
+import android.content.res.Configuration;
+import android.graphics.Rect;
+import android.graphics.Region;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.view.IWindow;
+import android.view.IWindowSession;
+import android.view.InputChannel;
+import android.view.Surface;
+import android.view.SurfaceView;
+import android.view.WindowManager.LayoutParams;
+
+/**
+ * Implementation of {@link IWindowSession} so that mSession is not null in
+ * the {@link SurfaceView}.
+ */
+public final class BridgeWindowSession implements IWindowSession {
+
+    public int add(IWindow arg0, LayoutParams arg1, int arg2, Rect arg3,
+            InputChannel outInputchannel)
+            throws RemoteException {
+        // pass for now.
+        return 0;
+    }
+
+    public int addWithoutInputChannel(IWindow arg0, LayoutParams arg1, int arg2, Rect arg3)
+            throws RemoteException {
+        // pass for now.
+        return 0;
+    }
+
+    public void finishDrawing(IWindow arg0) throws RemoteException {
+        // pass for now.
+    }
+
+    public boolean getInTouchMode() throws RemoteException {
+        // pass for now.
+        return false;
+    }
+
+    public boolean performHapticFeedback(IWindow window, int effectId, boolean always) {
+        // pass for now.
+        return false;
+    }
+
+    public int relayout(IWindow arg0, LayoutParams arg1, int arg2, int arg3, int arg4,
+            boolean arg4_5, Rect arg5, Rect arg6, Rect arg7, Configuration arg7b, Surface arg8)
+            throws RemoteException {
+        // pass for now.
+        return 0;
+    }
+
+    public void getDisplayFrame(IWindow window, Rect outDisplayFrame) {
+        // pass for now.
+    }
+
+    public void remove(IWindow arg0) throws RemoteException {
+        // pass for now.
+    }
+
+    public void setInTouchMode(boolean arg0) throws RemoteException {
+        // pass for now.
+    }
+
+    public void setTransparentRegion(IWindow arg0, Region arg1) throws RemoteException {
+        // pass for now.
+    }
+
+    public void setWallpaperPosition(IBinder window, float x, float y,
+        float xStep, float yStep) {
+        // pass for now.
+    }
+
+    public void wallpaperOffsetsComplete(IBinder window) {
+        // pass for now.
+    }
+
+    public Bundle sendWallpaperCommand(IBinder window, String action, int x, int y,
+            int z, Bundle extras, boolean sync) {
+        // pass for now.
+        return null;
+    }
+
+    public void wallpaperCommandComplete(IBinder window, Bundle result) {
+        // pass for now.
+    }
+
+    public IBinder asBinder() {
+        // pass for now.
+        return null;
+    }
+
+    public void setInsets(IWindow arg0, int arg1, Rect arg2, Rect arg3) throws RemoteException {
+        // TODO Auto-generated method stub
+
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeXmlBlockParser.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeXmlBlockParser.java
similarity index 91%
rename from tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeXmlBlockParser.java
rename to tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeXmlBlockParser.java
index d842a66..70dbaa4 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeXmlBlockParser.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeXmlBlockParser.java
@@ -14,9 +14,10 @@
  * limitations under the License.
  */
 
-package com.android.layoutlib.bridge;
+package com.android.layoutlib.bridge.android;
 
-import com.android.layoutlib.api.IXmlPullParser;
+
+import com.android.ide.common.rendering.api.ILayoutPullParser;
 
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
@@ -36,14 +37,15 @@
  */
 public class BridgeXmlBlockParser implements XmlResourceParser {
 
-    private XmlPullParser mParser;
-    private XmlPullAttributes mAttrib;
+    private final XmlPullParser mParser;
+    private final XmlPullAttributes mAttrib;
+    private final BridgeContext mContext;
+    private final boolean mPlatformFile;
 
     private boolean mStarted = false;
-    private boolean mDecNextDepth = false;
-    private int mDepth = 0;
     private int mEventType = START_DOCUMENT;
-    private final boolean mPlatformFile;
+
+    private boolean mPopped = true; // default to true in case it's not pushed.
 
     /**
      * Builds a {@link BridgeXmlBlockParser}.
@@ -53,25 +55,37 @@
      */
     public BridgeXmlBlockParser(XmlPullParser parser, BridgeContext context, boolean platformFile) {
         mParser = parser;
+        mContext = context;
         mPlatformFile = platformFile;
         mAttrib = new BridgeXmlPullAttributes(parser, context, mPlatformFile);
+
+        if (mContext != null) {
+            mContext.pushParser(this);
+            mPopped = false;
+        }
     }
-    
+
     public boolean isPlatformFile() {
         return mPlatformFile;
     }
 
-    public Object getViewKey() {
-        if (mParser instanceof IXmlPullParser) {
-            return ((IXmlPullParser)mParser).getViewKey();
+    public Object getViewCookie() {
+        if (mParser instanceof ILayoutPullParser) {
+            return ((ILayoutPullParser)mParser).getViewCookie();
         }
 
         return null;
     }
-    
-    
+
+    public void ensurePopped() {
+        if (mContext != null && mPopped == false) {
+            mContext.popParser();
+            mPopped = true;
+        }
+    }
+
     // ------- XmlResourceParser implementation
-    
+
     public void setFeature(String name, boolean state)
             throws XmlPullParserException {
         if (FEATURE_PROCESS_NAMESPACES.equals(name) && state) {
@@ -145,7 +159,7 @@
     }
 
     public int getDepth() {
-        return mDepth;
+        return mParser.getDepth();
     }
 
     public String getText() {
@@ -236,17 +250,10 @@
             return START_DOCUMENT;
         }
         int ev = mParser.next();
-        if (mDecNextDepth) {
-            mDepth--;
-            mDecNextDepth = false;
-        }
-        switch (ev) {
-        case START_TAG:
-            mDepth++;
-            break;
-        case END_TAG:
-            mDecNextDepth = true;
-            break;
+
+        if (ev == END_TAG && mParser.getDepth() == 1) {
+            // done with parser remove it from the context stack.
+            ensurePopped();
         }
         mEventType = ev;
         return ev;
@@ -301,7 +308,7 @@
 
     // AttributeSet implementation
 
-    
+
     public void close() {
         // pass
     }
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeXmlPullAttributes.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeXmlPullAttributes.java
similarity index 80%
rename from tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeXmlPullAttributes.java
rename to tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeXmlPullAttributes.java
index d145ff6..ba856e0 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeXmlPullAttributes.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeXmlPullAttributes.java
@@ -14,9 +14,13 @@
  * limitations under the License.
  */
 
-package com.android.layoutlib.bridge;
+package com.android.layoutlib.bridge.android;
 
-import com.android.layoutlib.api.IResourceValue;
+import com.android.ide.common.rendering.api.RenderResources;
+import com.android.ide.common.rendering.api.ResourceValue;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.BridgeConstants;
+import com.android.resources.ResourceType;
 
 import org.xmlpull.v1.XmlPullParser;
 
@@ -55,7 +59,7 @@
         String ns = mParser.getAttributeNamespace(index);
 
         if (BridgeConstants.NS_RESOURCES.equals(ns)) {
-            Integer v = Bridge.getResourceValue(BridgeConstants.RES_ATTR, name);
+            Integer v = Bridge.getResourceId(ResourceType.ATTR, name);
             if (v != null) {
                 return v.intValue();
             }
@@ -66,8 +70,7 @@
         // this is not an attribute in the android namespace, we query the customviewloader, if
         // the namespaces match.
         if (mContext.getProjectCallback().getNamespace().equals(ns)) {
-            Integer v = mContext.getProjectCallback().getResourceValue(BridgeConstants.RES_ATTR,
-                    name);
+            Integer v = mContext.getProjectCallback().getResourceId(ResourceType.ATTR, name);
             if (v != null) {
                 return v.intValue();
             }
@@ -100,16 +103,17 @@
 
     private int resolveResourceValue(String value, int defaultValue) {
         // now look for this particular value
-        IResourceValue resource = mContext.resolveResValue(
-                mContext.findResValue(value, mPlatformFile));
+        RenderResources resources = mContext.getRenderResources();
+        ResourceValue resource = resources.resolveResValue(
+                resources.findResValue(value, mPlatformFile));
 
         if (resource != null) {
             Integer id = null;
             if (mPlatformFile || resource.isFramework()) {
-                id = Bridge.getResourceValue(resource.getType(), resource.getName());
+                id = Bridge.getResourceId(resource.getResourceType(), resource.getName());
             } else {
-                id = mContext.getProjectCallback().getResourceValue(
-                        resource.getType(), resource.getName());
+                id = mContext.getProjectCallback().getResourceId(
+                        resource.getResourceType(), resource.getName());
             }
 
             if (id != null) {
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/CustomBar.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/CustomBar.java
new file mode 100644
index 0000000..060e6ee
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/CustomBar.java
@@ -0,0 +1,263 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.layoutlib.bridge.bars;
+
+import com.android.ide.common.rendering.api.RenderResources;
+import com.android.ide.common.rendering.api.ResourceValue;
+import com.android.ide.common.rendering.api.StyleResourceValue;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.android.BridgeContext;
+import com.android.layoutlib.bridge.android.BridgeXmlBlockParser;
+import com.android.layoutlib.bridge.impl.ResourceHelper;
+import com.android.resources.Density;
+import com.android.resources.ResourceType;
+
+import org.kxml2.io.KXmlParser;
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+
+import android.content.Context;
+import android.content.res.ColorStateList;
+import android.graphics.Bitmap;
+import android.graphics.Bitmap_Delegate;
+import android.graphics.drawable.BitmapDrawable;
+import android.graphics.drawable.Drawable;
+import android.util.TypedValue;
+import android.view.Gravity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.widget.ImageView;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Base "bar" class for the window decor around the the edited layout.
+ * This is basically an horizontal layout that loads a given layout on creation (it is read
+ * through {@link Class#getResourceAsStream(String)}).
+ *
+ * The given layout should be a merge layout so that all the children belong to this class directly.
+ *
+ * It also provides a few utility methods to configure the content of the layout.
+ */
+abstract class CustomBar extends LinearLayout {
+
+    protected abstract TextView getStyleableTextView();
+
+    protected CustomBar(Context context, Density density, String layoutPath)
+            throws XmlPullParserException {
+        super(context);
+        setOrientation(LinearLayout.HORIZONTAL);
+        setGravity(Gravity.CENTER_VERTICAL);
+
+        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(
+                Context.LAYOUT_INFLATER_SERVICE);
+
+        KXmlParser parser = new KXmlParser();
+        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
+        parser.setInput(
+                getClass().getResourceAsStream(layoutPath),
+                "UTF8"); //$NON-NLS-1$
+
+        BridgeXmlBlockParser bridgeParser = new BridgeXmlBlockParser(
+                parser, (BridgeContext) context, false /*platformFile*/);
+
+        try {
+            inflater.inflate(bridgeParser, this, true);
+        } finally {
+            bridgeParser.ensurePopped();
+        }
+    }
+
+    private InputStream getIcon(String iconName, Density[] densityInOut, String[] pathOut,
+            boolean tryOtherDensities) {
+        // current density
+        Density density = densityInOut[0];
+
+        // bitmap url relative to this class
+        pathOut[0] = "/bars/" + density.getResourceValue() + "/" + iconName;
+
+        InputStream stream = getClass().getResourceAsStream(pathOut[0]);
+        if (stream == null && tryOtherDensities) {
+            for (Density d : Density.values()) {
+                if (d != density) {
+                    densityInOut[0] = d;
+                    stream = getIcon(iconName, densityInOut, pathOut, false /*tryOtherDensities*/);
+                    if (stream != null) {
+                        return stream;
+                    }
+                }
+            }
+        }
+
+        return stream;
+    }
+
+    protected void loadIcon(int index, String iconName, Density density) {
+        View child = getChildAt(index);
+        if (child instanceof ImageView) {
+            ImageView imageView = (ImageView) child;
+
+            String[] pathOut = new String[1];
+            Density[] densityInOut = new Density[] { density };
+            InputStream stream = getIcon(iconName, densityInOut, pathOut,
+                    true /*tryOtherDensities*/);
+            density = densityInOut[0];
+
+            if (stream != null) {
+                // look for a cached bitmap
+                Bitmap bitmap = Bridge.getCachedBitmap(pathOut[0], true /*isFramework*/);
+                if (bitmap == null) {
+                    try {
+                        bitmap = Bitmap_Delegate.createBitmap(stream, false /*isMutable*/, density);
+                        Bridge.setCachedBitmap(pathOut[0], bitmap, true /*isFramework*/);
+                    } catch (IOException e) {
+                        return;
+                    }
+                }
+
+                if (bitmap != null) {
+                    BitmapDrawable drawable = new BitmapDrawable(getContext().getResources(),
+                            bitmap);
+                    imageView.setBackgroundDrawable(drawable);
+                }
+            }
+        }
+    }
+
+    protected void loadIcon(int index, String iconReference) {
+        ResourceValue value = getResourceValue(iconReference);
+        if (value != null) {
+            loadIcon(index, value);
+        }
+    }
+
+    protected Drawable loadIcon(int index, ResourceType type, String name) {
+        BridgeContext bridgeContext = (BridgeContext) mContext;
+        RenderResources res = bridgeContext.getRenderResources();
+
+        // find the resource
+        ResourceValue value = res.getFrameworkResource(type, name);
+
+        // resolve it if needed
+        value = res.resolveResValue(value);
+        return loadIcon(index, value);
+    }
+
+    private Drawable loadIcon(int index, ResourceValue value) {
+        View child = getChildAt(index);
+        if (child instanceof ImageView) {
+            ImageView imageView = (ImageView) child;
+
+            Drawable drawable = ResourceHelper.getDrawable(
+                    value, (BridgeContext) mContext);
+            if (drawable != null) {
+                imageView.setBackgroundDrawable(drawable);
+            }
+
+            return drawable;
+        }
+
+        return null;
+    }
+
+    protected TextView setText(int index, String stringReference) {
+        View child = getChildAt(index);
+        if (child instanceof TextView) {
+            TextView textView = (TextView) child;
+            ResourceValue value = getResourceValue(stringReference);
+            if (value != null) {
+                textView.setText(value.getValue());
+            } else {
+                textView.setText(stringReference);
+            }
+            return textView;
+        }
+
+        return null;
+    }
+
+    protected void setStyle(String themeEntryName) {
+
+        BridgeContext bridgeContext = (BridgeContext) mContext;
+        RenderResources res = bridgeContext.getRenderResources();
+
+        ResourceValue value = res.findItemInTheme(themeEntryName);
+        value = res.resolveResValue(value);
+
+        if (value instanceof StyleResourceValue == false) {
+            return;
+        }
+
+        StyleResourceValue style = (StyleResourceValue) value;
+
+        // get the background
+        ResourceValue backgroundValue = res.findItemInStyle(style, "background");
+        backgroundValue = res.resolveResValue(backgroundValue);
+        if (backgroundValue != null) {
+            Drawable d = ResourceHelper.getDrawable(backgroundValue, bridgeContext);
+            if (d != null) {
+                setBackgroundDrawable(d);
+            }
+        }
+
+        TextView textView = getStyleableTextView();
+        if (textView != null) {
+            // get the text style
+            ResourceValue textStyleValue = res.findItemInStyle(style, "titleTextStyle");
+            textStyleValue = res.resolveResValue(textStyleValue);
+            if (textStyleValue instanceof StyleResourceValue) {
+                StyleResourceValue textStyle = (StyleResourceValue) textStyleValue;
+
+                ResourceValue textSize = res.findItemInStyle(textStyle, "textSize");
+                textSize = res.resolveResValue(textSize);
+
+                if (textSize != null) {
+                    TypedValue out = new TypedValue();
+                    if (ResourceHelper.stringToFloat(textSize.getValue(), out)) {
+                        textView.setTextSize(
+                                out.getDimension(bridgeContext.getResources().mMetrics));
+                    }
+                }
+
+
+                ResourceValue textColor = res.findItemInStyle(textStyle, "textColor");
+                textColor = res.resolveResValue(textColor);
+                if (textColor != null) {
+                    ColorStateList stateList = ResourceHelper.getColorStateList(
+                            textColor, bridgeContext);
+                    if (stateList != null) {
+                        textView.setTextColor(stateList);
+                    }
+                }
+            }
+        }
+    }
+
+    private ResourceValue getResourceValue(String reference) {
+        BridgeContext bridgeContext = (BridgeContext) mContext;
+        RenderResources res = bridgeContext.getRenderResources();
+
+        // find the resource
+        ResourceValue value = res.findResValue(reference, false /*isFramework*/);
+
+        // resolve it if needed
+        return res.resolveResValue(value);
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/PhoneSystemBar.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/PhoneSystemBar.java
new file mode 100644
index 0000000..5507ef9
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/PhoneSystemBar.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.layoutlib.bridge.bars;
+
+import com.android.resources.Density;
+import com.android.resources.ResourceType;
+
+import org.xmlpull.v1.XmlPullParserException;
+
+import android.content.Context;
+import android.graphics.drawable.Drawable;
+import android.graphics.drawable.LevelListDrawable;
+import android.view.Gravity;
+import android.widget.TextView;
+
+public class PhoneSystemBar extends CustomBar {
+
+    public PhoneSystemBar(Context context, Density density) throws XmlPullParserException {
+        super(context, density, "/bars/phone_system_bar.xml");
+
+        setGravity(mGravity | Gravity.RIGHT);
+        setBackgroundColor(0xFF000000);
+
+        // Cannot access the inside items through id because no R.id values have been
+        // created for them.
+        // We do know the order though.
+        // 0 is the spacer.
+        loadIcon(1, "stat_sys_wifi_signal_4_fully.png", density);
+        Drawable drawable = loadIcon(2, ResourceType.DRAWABLE, "stat_sys_battery_charge");
+        if (drawable instanceof LevelListDrawable) {
+            ((LevelListDrawable) drawable).setLevel(100);
+        }
+    }
+
+    @Override
+    protected TextView getStyleableTextView() {
+        return null;
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/TitleBar.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/TitleBar.java
new file mode 100644
index 0000000..d7401d9
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/TitleBar.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.layoutlib.bridge.bars;
+
+import com.android.resources.Density;
+
+import org.xmlpull.v1.XmlPullParserException;
+
+import android.content.Context;
+import android.widget.TextView;
+
+public class TitleBar extends CustomBar {
+
+    private TextView mTextView;
+
+    public TitleBar(Context context, Density density, String label)
+            throws XmlPullParserException {
+        super(context, density, "/bars/title_bar.xml");
+
+        // Cannot access the inside items through id because no R.id values have been
+        // created for them.
+        // We do know the order though.
+        mTextView = setText(0, label);
+
+        setStyle("windowTitleBackgroundStyle");
+    }
+
+    @Override
+    protected TextView getStyleableTextView() {
+        return mTextView;
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/DelegateManager.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/DelegateManager.java
new file mode 100644
index 0000000..ae1217d
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/DelegateManager.java
@@ -0,0 +1,146 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.layoutlib.bridge.impl;
+
+import com.android.layoutlib.bridge.util.Debug;
+import com.android.layoutlib.bridge.util.SparseWeakArray;
+
+import android.util.SparseArray;
+
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Manages native delegates.
+ *
+ * This is used in conjunction with layoublib_create: certain Android java classes are mere
+ * wrappers around a heavily native based implementation, and we need a way to run these classes
+ * in our Eclipse rendering framework without bringing all the native code from the Android
+ * platform.
+ *
+ * Thus we instruct layoutlib_create to modify the bytecode of these classes to replace their
+ * native methods by "delegate calls".
+ *
+ * For example, a native method android.graphics.Matrix.init(...) will actually become
+ * a call to android.graphics.Matrix_Delegate.init(...).
+ *
+ * The Android java classes that use native code uses an int (Java side) to reference native
+ * objects. This int is generally directly the pointer to the C structure counterpart.
+ * Typically a creation method will return such an int, and then this int will be passed later
+ * to a Java method to identify the C object to manipulate.
+ *
+ * Since we cannot use the Java object reference as the int directly, DelegateManager manages the
+ * int -> Delegate class link.
+ *
+ * Native methods usually always have the int as parameters. The first thing the delegate method
+ * will do is call {@link #getDelegate(int)} to get the Java object matching the int.
+ *
+ * Typical native init methods are returning a new int back to the Java class, so
+ * {@link #addNewDelegate(Object)} does the same.
+ *
+ * The JNI references are counted, so we do the same through a {@link WeakReference}. Because
+ * the Java object needs to count as a reference (even though it only holds an int), we use the
+ * following mechanism:
+ *
+ * - {@link #addNewDelegate(Object)} and {@link #removeJavaReferenceFor(int)} adds and removes
+ *   the delegate to/from a list. This list hold the reference and prevents the GC from reclaiming
+ *   the delegate.
+ *
+ * - {@link #addNewDelegate(Object)} also adds the delegate to a {@link SparseArray} that holds a
+ *   {@link WeakReference} to the delegate. This allows the delegate to be deleted automatically
+ *   when nothing references it. This means that any class that holds a delegate (except for the
+ *   Java main class) must not use the int but the Delegate class instead. The integers must
+ *   only be used in the API between the main Java class and the Delegate.
+ *
+ * @param <T> the delegate class to manage
+ */
+public final class DelegateManager<T> {
+    private final Class<T> mClass;
+    private final SparseWeakArray<T> mDelegates = new SparseWeakArray<T>();
+    /** list used to store delegates when their main object holds a reference to them.
+     * This is to ensure that the WeakReference in the SparseWeakArray doesn't get GC'ed
+     * @see #addNewDelegate(Object)
+     * @see #removeJavaReferenceFor(int)
+     */
+    private final List<T> mJavaReferences = new ArrayList<T>();
+    private int mDelegateCounter = 0;
+
+    public DelegateManager(Class<T> theClass) {
+        mClass = theClass;
+    }
+
+    /**
+     * Returns the delegate from the given native int.
+     * <p>
+     * If the int is zero, then this will always return null.
+     * <p>
+     * If the int is non zero and the delegate is not found, this will throw an assert.
+     *
+     * @param native_object the native int.
+     * @return the delegate or null if not found.
+     */
+    public T getDelegate(int native_object) {
+        if (native_object > 0) {
+            T delegate =  mDelegates.get(native_object);
+
+            if (Debug.DEBUG) {
+                if (delegate == null) {
+                    System.out.println("Unknown " + mClass.getSimpleName() + " with int " +
+                            native_object);
+                }
+            }
+
+            assert delegate != null;
+            return delegate;
+        }
+        return null;
+    }
+
+    /**
+     * Adds a delegate to the manager and returns the native int used to identify it.
+     * @param newDelegate the delegate to add
+     * @return a unique native int to identify the delegate
+     */
+    public int addNewDelegate(T newDelegate) {
+        int native_object = ++mDelegateCounter;
+        mDelegates.put(native_object, newDelegate);
+        assert !mJavaReferences.contains(newDelegate);
+        mJavaReferences.add(newDelegate);
+
+        if (Debug.DEBUG) {
+            System.out.println("New " + mClass.getSimpleName() + " with int " + native_object);
+        }
+
+        return native_object;
+    }
+
+    /**
+     * Removes the main reference on the given delegate.
+     * @param native_object the native integer representing the delegate.
+     */
+    public void removeJavaReferenceFor(int native_object) {
+        T delegate = getDelegate(native_object);
+
+        if (Debug.DEBUG) {
+            System.out.println("Removing main Java ref on " + mClass.getSimpleName() +
+                    " with int " + native_object);
+        }
+
+        mJavaReferences.remove(delegate);
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/FontLoader.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/FontLoader.java
similarity index 95%
rename from tools/layoutlib/bridge/src/com/android/layoutlib/bridge/FontLoader.java
rename to tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/FontLoader.java
index 801503b..f62fad2 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/FontLoader.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/FontLoader.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.layoutlib.bridge;
+package com.android.layoutlib.bridge.impl;
 
 import org.xml.sax.Attributes;
 import org.xml.sax.SAXException;
@@ -134,6 +134,15 @@
         return mFallBackFonts;
     }
 
+    /**
+     * Returns a {@link Font} object given a family name and a style value (constant in
+     * {@link Typeface}).
+     * @param family the family name
+     * @param style a 1-item array containing the requested style. Based on the font being read
+     *              the actual style may be different. The array contains the actual style after
+     *              the method returns.
+     * @return the font object or null if no match could be found.
+     */
     public synchronized Font getFont(String family, int[] style) {
         if (family == null) {
             return null;
@@ -154,7 +163,7 @@
             mTtfToFontMap.put(ttf, styleMap);
         }
 
-        Font f = styleMap.get(style);
+        Font f = styleMap.get(style[0]);
 
         if (f != null) {
             return f;
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/GcSnapshot.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/GcSnapshot.java
new file mode 100644
index 0000000..2abe56c
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/GcSnapshot.java
@@ -0,0 +1,806 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.layoutlib.bridge.impl;
+
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.layoutlib.bridge.Bridge;
+
+import android.graphics.Bitmap_Delegate;
+import android.graphics.Canvas;
+import android.graphics.Paint;
+import android.graphics.Paint_Delegate;
+import android.graphics.Rect;
+import android.graphics.RectF;
+import android.graphics.Region;
+import android.graphics.Region_Delegate;
+import android.graphics.Shader_Delegate;
+import android.graphics.Xfermode_Delegate;
+
+import java.awt.AlphaComposite;
+import java.awt.Color;
+import java.awt.Composite;
+import java.awt.Graphics2D;
+import java.awt.RenderingHints;
+import java.awt.Shape;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Area;
+import java.awt.geom.Rectangle2D;
+import java.awt.image.BufferedImage;
+import java.util.ArrayList;
+
+/**
+ * Class representing a graphics context snapshot, as well as a context stack as a linked list.
+ * <p>
+ * This is based on top of {@link Graphics2D} but can operate independently if none are available
+ * yet when setting transforms and clip information.
+ * <p>
+ * This allows for drawing through {@link #draw(Drawable, Paint_Delegate)} and
+ * {@link #draw(Drawable, Paint_Delegate)}
+ *
+ * Handling of layers (created with {@link Canvas#saveLayer(RectF, Paint, int)}) is handled through
+ * a list of Graphics2D for each layers. The class actually maintains a list of {@link Layer}
+ * for each layer. Doing a save() will duplicate this list so that each graphics2D object
+ * ({@link Layer#getGraphics()}) is configured only for the new snapshot.
+ */
+public class GcSnapshot {
+
+    private final GcSnapshot mPrevious;
+    private final int mFlags;
+
+    /** list of layers. The first item in the list is always the  */
+    private final ArrayList<Layer> mLayers = new ArrayList<Layer>();
+
+    /** temp transform in case transformation are set before a Graphics2D exists */
+    private AffineTransform mTransform = null;
+    /** temp clip in case clipping is set before a Graphics2D exists */
+    private Area mClip = null;
+
+    // local layer data
+    /** a local layer created with {@link Canvas#saveLayer(RectF, Paint, int)}.
+     * If this is null, this does not mean there's no layer, just that the snapshot is not the
+     * one that created the layer.
+     * @see #getLayerSnapshot()
+     */
+    private final Layer mLocalLayer;
+    private final Paint_Delegate mLocalLayerPaint;
+    private final Rect mLayerBounds;
+
+    public interface Drawable {
+        void draw(Graphics2D graphics, Paint_Delegate paint);
+    }
+
+    /**
+     * Class containing information about a layer.
+     *
+     * This contains graphics, bitmap and layer information.
+     */
+    private static class Layer {
+        private final Graphics2D mGraphics;
+        private final Bitmap_Delegate mBitmap;
+        private final BufferedImage mImage;
+        /** the flags that were used to configure the layer. This is never changed, and passed
+         * as is when {@link #makeCopy()} is called */
+        private final int mFlags;
+        /** the original content of the layer when the next object was created. This is not
+         * passed in {@link #makeCopy()} and instead is recreated when a new layer is added
+         * (depending on its flags) */
+        private BufferedImage mOriginalCopy;
+
+        /**
+         * Creates a layer with a graphics and a bitmap. This is only used to create
+         * the base layer.
+         *
+         * @param graphics the graphics
+         * @param bitmap the bitmap
+         */
+        Layer(Graphics2D graphics, Bitmap_Delegate bitmap) {
+            mGraphics = graphics;
+            mBitmap = bitmap;
+            mImage = mBitmap.getImage();
+            mFlags = 0;
+        }
+
+        /**
+         * Creates a layer with a graphics and an image. If the image belongs to a
+         * {@link Bitmap_Delegate} (case of the base layer), then
+         * {@link Layer#Layer(Graphics2D, Bitmap_Delegate)} should be used.
+         *
+         * @param graphics the graphics the new graphics for this layer
+         * @param image the image the image from which the graphics came
+         * @param flags the flags that were used to save this layer
+         */
+        Layer(Graphics2D graphics, BufferedImage image, int flags) {
+            mGraphics = graphics;
+            mBitmap = null;
+            mImage = image;
+            mFlags = flags;
+        }
+
+        /** The Graphics2D, guaranteed to be non null */
+        Graphics2D getGraphics() {
+            return mGraphics;
+        }
+
+        /** The BufferedImage, guaranteed to be non null */
+        BufferedImage getImage() {
+            return mImage;
+        }
+
+        /** Returns the layer save flags. This is only valid for additional layers.
+         * For the base layer this will always return 0;
+         * For a given layer, all further copies of this {@link Layer} object in new snapshots
+         * will always return the same value.
+         */
+        int getFlags() {
+            return mFlags;
+        }
+
+        Layer makeCopy() {
+            if (mBitmap != null) {
+                return new Layer((Graphics2D) mGraphics.create(), mBitmap);
+            }
+
+            return new Layer((Graphics2D) mGraphics.create(), mImage, mFlags);
+        }
+
+        /** sets an optional copy of the original content to be used during restore */
+        void setOriginalCopy(BufferedImage image) {
+            mOriginalCopy = image;
+        }
+
+        BufferedImage getOriginalCopy() {
+            return mOriginalCopy;
+        }
+
+        /**
+         * Sets the clip for the graphics2D object associated with the layer.
+         * This should be used over the normal Graphics2D setClip method.
+         *
+         * @param clipShape the shape to use a the clip shape.
+         */
+        void setClip(Shape clipShape) {
+            // because setClip is only guaranteed to work with rectangle shape,
+            // first reset the clip to max and then intersect the current (empty)
+            // clip with the shap.
+            mGraphics.setClip(null);
+            mGraphics.clip(clipShape);
+        }
+
+        /**
+         * Clips the layer with the given shape. This performs an intersect between the current
+         * clip shape and the given shape.
+         * @param shape the new clip shape.
+         */
+        public void clip(Shape shape) {
+            mGraphics.clip(shape);
+        }
+    }
+
+    /**
+     * Creates the root snapshot associating it with a given bitmap.
+     * <p>
+     * If <var>bitmap</var> is null, then {@link GcSnapshot#setBitmap(Bitmap_Delegate)} must be
+     * called before the snapshot can be used to draw. Transform and clip operations are permitted
+     * before.
+     *
+     * @param image the image to associate to the snapshot or null.
+     * @return the root snapshot
+     */
+    public static GcSnapshot createDefaultSnapshot(Bitmap_Delegate bitmap) {
+        GcSnapshot snapshot = new GcSnapshot();
+        if (bitmap != null) {
+            snapshot.setBitmap(bitmap);
+        }
+
+        return snapshot;
+    }
+
+    /**
+     * Saves the current state according to the given flags and returns the new current snapshot.
+     * <p/>
+     * This is the equivalent of {@link Canvas#save(int)}
+     *
+     * @param flags the save flags.
+     * @return the new snapshot
+     *
+     * @see Canvas#save(int)
+     */
+    public GcSnapshot save(int flags) {
+        return new GcSnapshot(this, null /*layerbounds*/, null /*paint*/, flags);
+    }
+
+    /**
+     * Saves the current state and creates a new layer, and returns the new current snapshot.
+     * <p/>
+     * This is the equivalent of {@link Canvas#saveLayer(RectF, Paint, int)}
+     *
+     * @param layerBounds the layer bounds
+     * @param paint the Paint information used to blit the layer back into the layers underneath
+     *          upon restore
+     * @param flags the save flags.
+     * @return the new snapshot
+     *
+     * @see Canvas#saveLayer(RectF, Paint, int)
+     */
+    public GcSnapshot saveLayer(RectF layerBounds, Paint_Delegate paint, int flags) {
+        return new GcSnapshot(this, layerBounds, paint, flags);
+    }
+
+    /**
+     * Creates the root snapshot.
+     * {@link #setGraphics2D(Graphics2D)} will have to be called on it when possible.
+     */
+    private GcSnapshot() {
+        mPrevious = null;
+        mFlags = 0;
+        mLocalLayer = null;
+        mLocalLayerPaint = null;
+        mLayerBounds = null;
+    }
+
+    /**
+     * Creates a new {@link GcSnapshot} on top of another one, with a layer data to be restored
+     * into the main graphics when {@link #restore()} is called.
+     *
+     * @param previous the previous snapshot head.
+     * @param layerBounds the region of the layer. Optional, if null, this is a normal save()
+     * @param paint the Paint information used to blit the layer back into the layers underneath
+     *          upon restore
+     * @param flags the flags regarding what should be saved.
+     */
+    private GcSnapshot(GcSnapshot previous, RectF layerBounds, Paint_Delegate paint, int flags) {
+        assert previous != null;
+        mPrevious = previous;
+        mFlags = flags;
+
+        // make a copy of the current layers before adding the new one.
+        // This keeps the same BufferedImage reference but creates new Graphics2D for this
+        // snapshot.
+        // It does not copy whatever original copy the layers have, as they will be done
+        // only if the new layer doesn't clip drawing to itself.
+        for (Layer layer : mPrevious.mLayers) {
+            mLayers.add(layer.makeCopy());
+        }
+
+        if (layerBounds != null) {
+            // get the current transform
+            AffineTransform matrix = mLayers.get(0).getGraphics().getTransform();
+
+            // transform the layerBounds with the current transform and stores it into a int rect
+            RectF rect2 = new RectF();
+            mapRect(matrix, rect2, layerBounds);
+            mLayerBounds = new Rect();
+            rect2.round(mLayerBounds);
+
+            // get the base layer (always at index 0)
+            Layer baseLayer = mLayers.get(0);
+
+            // create the image for the layer
+            BufferedImage layerImage = new BufferedImage(
+                    baseLayer.getImage().getWidth(),
+                    baseLayer.getImage().getHeight(),
+                    (mFlags & Canvas.HAS_ALPHA_LAYER_SAVE_FLAG) != 0 ?
+                            BufferedImage.TYPE_INT_ARGB :
+                                BufferedImage.TYPE_INT_RGB);
+
+            // create a graphics for it so that drawing can be done.
+            Graphics2D layerGraphics = layerImage.createGraphics();
+
+            // because this layer inherits the current context for transform and clip,
+            // set them to one from the base layer.
+            AffineTransform currentMtx = baseLayer.getGraphics().getTransform();
+            layerGraphics.setTransform(currentMtx);
+
+            // create a new layer for this new layer and add it to the list at the end.
+            mLayers.add(mLocalLayer = new Layer(layerGraphics, layerImage, flags));
+
+            // set the clip on it.
+            Shape currentClip = baseLayer.getGraphics().getClip();
+            mLocalLayer.setClip(currentClip);
+
+            // if the drawing is not clipped to the local layer only, we save the current content
+            // of all other layers. We are only interested in the part that will actually
+            // be drawn, so we create as small bitmaps as we can.
+            // This is so that we can erase the drawing that goes in the layers below that will
+            // be coming from the layer itself.
+            if ((mFlags & Canvas.CLIP_TO_LAYER_SAVE_FLAG) == 0) {
+                int w = mLayerBounds.width();
+                int h = mLayerBounds.height();
+                for (int i = 0 ; i < mLayers.size() - 1 ; i++) {
+                    Layer layer = mLayers.get(i);
+                    BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
+                    Graphics2D graphics = image.createGraphics();
+                    graphics.drawImage(layer.getImage(),
+                            0, 0, w, h,
+                            mLayerBounds.left, mLayerBounds.top,
+                                    mLayerBounds.right, mLayerBounds.bottom,
+                            null);
+                    graphics.dispose();
+                    layer.setOriginalCopy(image);
+                }
+            }
+        } else {
+            mLocalLayer = null;
+            mLayerBounds = null;
+        }
+
+        mLocalLayerPaint  = paint;
+    }
+
+    public void dispose() {
+        for (Layer layer : mLayers) {
+            layer.getGraphics().dispose();
+        }
+
+        if (mPrevious != null) {
+            mPrevious.dispose();
+        }
+    }
+
+    /**
+     * Restores the top {@link GcSnapshot}, and returns the next one.
+     */
+    public GcSnapshot restore() {
+        return doRestore();
+    }
+
+    /**
+     * Restores the {@link GcSnapshot} to <var>saveCount</var>.
+     * @param saveCount the saveCount or -1 to only restore 1.
+     *
+     * @return the new head of the Gc snapshot stack.
+     */
+    public GcSnapshot restoreTo(int saveCount) {
+        return doRestoreTo(size(), saveCount);
+    }
+
+    public int size() {
+        if (mPrevious != null) {
+            return mPrevious.size() + 1;
+        }
+
+        return 1;
+    }
+
+    /**
+     * Link the snapshot to a Bitmap_Delegate.
+     * <p/>
+     * This is only for the case where the snapshot was created with a null image when calling
+     * {@link #createDefaultSnapshot(Bitmap_Delegate)}, and is therefore not yet linked to
+     * a previous snapshot.
+     * <p/>
+     * If any transform or clip information was set before, they are put into the Graphics object.
+     * @param bitmap the bitmap to link to.
+     */
+    public void setBitmap(Bitmap_Delegate bitmap) {
+        // create a new Layer for the bitmap. This will be the base layer.
+        Graphics2D graphics2D = bitmap.getImage().createGraphics();
+        Layer baseLayer = new Layer(graphics2D, bitmap);
+
+        // Set the current transform and clip which can either come from mTransform/mClip if they
+        // were set when there was no bitmap/layers or from the current base layers if there is
+        // one already.
+
+        graphics2D.setTransform(getTransform());
+        // reset mTransform in case there was one.
+        mTransform = null;
+
+        baseLayer.setClip(getClip());
+        // reset mClip in case there was one.
+        mClip = null;
+
+        // replace whatever current layers we have with this.
+        mLayers.clear();
+        mLayers.add(baseLayer);
+
+    }
+
+    public void translate(float dx, float dy) {
+        if (mLayers.size() > 0) {
+            for (Layer layer : mLayers) {
+                layer.getGraphics().translate(dx, dy);
+            }
+        } else {
+            if (mTransform == null) {
+                mTransform = new AffineTransform();
+            }
+            mTransform.translate(dx, dy);
+        }
+    }
+
+    public void rotate(double radians) {
+        if (mLayers.size() > 0) {
+            for (Layer layer : mLayers) {
+                layer.getGraphics().rotate(radians);
+            }
+        } else {
+            if (mTransform == null) {
+                mTransform = new AffineTransform();
+            }
+            mTransform.rotate(radians);
+        }
+    }
+
+    public void scale(float sx, float sy) {
+        if (mLayers.size() > 0) {
+            for (Layer layer : mLayers) {
+                layer.getGraphics().scale(sx, sy);
+            }
+        } else {
+            if (mTransform == null) {
+                mTransform = new AffineTransform();
+            }
+            mTransform.scale(sx, sy);
+        }
+    }
+
+    public AffineTransform getTransform() {
+        if (mLayers.size() > 0) {
+            // all graphics2D in the list have the same transform
+            return mLayers.get(0).getGraphics().getTransform();
+        } else {
+            if (mTransform == null) {
+                mTransform = new AffineTransform();
+            }
+            return mTransform;
+        }
+    }
+
+    public void setTransform(AffineTransform transform) {
+        if (mLayers.size() > 0) {
+            for (Layer layer : mLayers) {
+                layer.getGraphics().setTransform(transform);
+            }
+        } else {
+            if (mTransform == null) {
+                mTransform = new AffineTransform();
+            }
+            mTransform.setTransform(transform);
+        }
+    }
+
+    public boolean clip(Shape shape, int regionOp) {
+        // Simple case of intersect with existing layers.
+        // Because Graphics2D#setClip works a bit peculiarly, we optimize
+        // the case of clipping by intersection, as it's supported natively.
+        if (regionOp == Region.Op.INTERSECT.nativeInt && mLayers.size() > 0) {
+            for (Layer layer : mLayers) {
+                layer.clip(shape);
+            }
+
+            Shape currentClip = getClip();
+            return currentClip != null && currentClip.getBounds().isEmpty() == false;
+        }
+
+        Area area = null;
+
+        if (regionOp == Region.Op.REPLACE.nativeInt) {
+            area = new Area(shape);
+        } else {
+            area = Region_Delegate.combineShapes(getClip(), shape, regionOp);
+        }
+
+        assert area != null;
+
+        if (mLayers.size() > 0) {
+            if (area != null) {
+                for (Layer layer : mLayers) {
+                    layer.setClip(area);
+                }
+            }
+
+            Shape currentClip = getClip();
+            return currentClip != null && currentClip.getBounds().isEmpty() == false;
+        } else {
+            if (area != null) {
+                mClip = area;
+            } else {
+                mClip = new Area();
+            }
+
+            return mClip.getBounds().isEmpty() == false;
+        }
+    }
+
+    public boolean clipRect(float left, float top, float right, float bottom, int regionOp) {
+        return clip(new Rectangle2D.Float(left, top, right - left, bottom - top), regionOp);
+    }
+
+    /**
+     * Returns the current clip, or null if none have been setup.
+     */
+    public Shape getClip() {
+        if (mLayers.size() > 0) {
+            // they all have the same clip
+            return mLayers.get(0).getGraphics().getClip();
+        } else {
+            return mClip;
+        }
+    }
+
+    private GcSnapshot doRestoreTo(int size, int saveCount) {
+        if (size <= saveCount) {
+            return this;
+        }
+
+        // restore the current one first.
+        GcSnapshot previous = doRestore();
+
+        if (size == saveCount + 1) { // this was the only one that needed restore.
+            return previous;
+        } else {
+            return previous.doRestoreTo(size - 1, saveCount);
+        }
+    }
+
+    /**
+     * Executes the Drawable's draw method, with a null paint delegate.
+     * <p/>
+     * Note that the method can be called several times if there are more than one active layer.
+     * @param drawable
+     */
+    public void draw(Drawable drawable) {
+        draw(drawable, null, false /*compositeOnly*/, false /*forceSrcMode*/);
+    }
+
+    /**
+     * Executes the Drawable's draw method.
+     * <p/>
+     * Note that the method can be called several times if there are more than one active layer.
+     * @param drawable
+     * @param paint
+     * @param compositeOnly whether the paint is used for composite only. This is typically
+     *          the case for bitmaps.
+     * @param forceSrcMode if true, this overrides the composite to be SRC
+     */
+    public void draw(Drawable drawable, Paint_Delegate paint, boolean compositeOnly,
+            boolean forceSrcMode) {
+        // the current snapshot may not have a mLocalLayer (ie it was created on save() instead
+        // of saveLayer(), but that doesn't mean there's no layer.
+        // mLayers however saves all the information we need (flags).
+        if (mLayers.size() == 1) {
+            // no layer, only base layer. easy case.
+            drawInLayer(mLayers.get(0), drawable, paint, compositeOnly, forceSrcMode);
+        } else {
+            // draw in all the layers until the layer save flags tells us to stop (ie drawing
+            // in that layer is limited to the layer itself.
+            int flags;
+            int i = mLayers.size() - 1;
+
+            do {
+                Layer layer = mLayers.get(i);
+
+                drawInLayer(layer, drawable, paint, compositeOnly, forceSrcMode);
+
+                // then go to previous layer, only if there are any left, and its flags
+                // doesn't restrict drawing to the layer itself.
+                i--;
+                flags = layer.getFlags();
+            } while (i >= 0 && (flags & Canvas.CLIP_TO_LAYER_SAVE_FLAG) == 0);
+        }
+    }
+
+    private void drawInLayer(Layer layer, Drawable drawable, Paint_Delegate paint,
+            boolean compositeOnly, boolean forceSrcMode) {
+        Graphics2D originalGraphics = layer.getGraphics();
+        // get a Graphics2D object configured with the drawing parameters.
+        Graphics2D configuredGraphics2D =
+            paint != null ?
+                    createCustomGraphics(originalGraphics, paint, compositeOnly, forceSrcMode) :
+                        (Graphics2D) originalGraphics.create();
+
+        if (configuredGraphics2D != null) {
+            try {
+                drawable.draw(configuredGraphics2D, paint);
+            } finally {
+                // dispose Graphics2D object
+                configuredGraphics2D.dispose();
+            }
+        }
+    }
+
+    private GcSnapshot doRestore() {
+        if (mPrevious != null) {
+            if (mLocalLayer != null) {
+                // prepare to blit the layers in which we have draw, in the layer beneath
+                // them, starting with the top one (which is the current local layer).
+                int i = mLayers.size() - 1;
+                int flags;
+                do {
+                    Layer dstLayer = mLayers.get(i - 1);
+
+                    restoreLayer(dstLayer);
+
+                    flags = dstLayer.getFlags();
+                    i--;
+                } while (i > 0 && (flags & Canvas.CLIP_TO_LAYER_SAVE_FLAG) == 0);
+            }
+
+            // if this snapshot does not save everything, then set the previous snapshot
+            // to this snapshot content
+
+            // didn't save the matrix? set the current matrix on the previous snapshot
+            if ((mFlags & Canvas.MATRIX_SAVE_FLAG) == 0) {
+                AffineTransform mtx = getTransform();
+                for (Layer layer : mPrevious.mLayers) {
+                    layer.getGraphics().setTransform(mtx);
+                }
+            }
+
+            // didn't save the clip? set the current clip on the previous snapshot
+            if ((mFlags & Canvas.CLIP_SAVE_FLAG) == 0) {
+                Shape clip = getClip();
+                for (Layer layer : mPrevious.mLayers) {
+                    layer.setClip(clip);
+                }
+            }
+        }
+
+        for (Layer layer : mLayers) {
+            layer.getGraphics().dispose();
+        }
+
+        return mPrevious;
+    }
+
+    private void restoreLayer(Layer dstLayer) {
+
+        Graphics2D baseGfx = dstLayer.getImage().createGraphics();
+
+        // if the layer contains an original copy this means the flags
+        // didn't restrict drawing to the local layer and we need to make sure the
+        // layer bounds in the layer beneath didn't receive any drawing.
+        // so we use the originalCopy to erase the new drawings in there.
+        BufferedImage originalCopy = dstLayer.getOriginalCopy();
+        if (originalCopy != null) {
+            Graphics2D g = (Graphics2D) baseGfx.create();
+            g.setComposite(AlphaComposite.Src);
+
+            g.drawImage(originalCopy,
+                    mLayerBounds.left, mLayerBounds.top, mLayerBounds.right, mLayerBounds.bottom,
+                    0, 0, mLayerBounds.width(), mLayerBounds.height(),
+                    null);
+            g.dispose();
+        }
+
+        // now draw put the content of the local layer onto the layer,
+        // using the paint information
+        Graphics2D g = createCustomGraphics(baseGfx, mLocalLayerPaint,
+                true /*alphaOnly*/, false /*forceSrcMode*/);
+
+        if (g != null) {
+            g.drawImage(mLocalLayer.getImage(),
+                    mLayerBounds.left, mLayerBounds.top, mLayerBounds.right, mLayerBounds.bottom,
+                    mLayerBounds.left, mLayerBounds.top, mLayerBounds.right, mLayerBounds.bottom,
+                    null);
+            g.dispose();
+        }
+
+        baseGfx.dispose();
+    }
+
+    /**
+     * Creates a new {@link Graphics2D} based on the {@link Paint} parameters.
+     * <p/>The object must be disposed ({@link Graphics2D#dispose()}) after being used.
+     */
+    private Graphics2D createCustomGraphics(Graphics2D original, Paint_Delegate paint,
+            boolean compositeOnly, boolean forceSrcMode) {
+        // make new one graphics
+        Graphics2D g = (Graphics2D) original.create();
+
+        // configure it
+
+        if (paint.isAntiAliased()) {
+            g.setRenderingHint(
+                    RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+            g.setRenderingHint(
+                    RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
+        }
+
+        boolean customShader = false;
+
+        // get the shader first, as it'll replace the color if it can be used it.
+        if (compositeOnly == false) {
+            Shader_Delegate shaderDelegate = paint.getShader();
+            if (shaderDelegate != null) {
+                if (shaderDelegate.isSupported()) {
+                    // shader could have a local matrix that's not valid (for instance 0 scaling).
+                    if (shaderDelegate.isValid()) {
+                        java.awt.Paint shaderPaint = shaderDelegate.getJavaPaint();
+                        assert shaderPaint != null;
+                        if (shaderPaint != null) {
+                            g.setPaint(shaderPaint);
+                            customShader = true;
+                        }
+                    } else {
+                        g.dispose();
+                        return null;
+                    }
+                } else {
+                    Bridge.getLog().fidelityWarning(LayoutLog.TAG_SHADER,
+                            shaderDelegate.getSupportMessage(),
+                            null /*throwable*/, null /*data*/);
+                }
+            }
+
+            // if no shader, use the paint color
+            if (customShader == false) {
+                g.setColor(new Color(paint.getColor(), true /*hasAlpha*/));
+            }
+
+            // set the stroke
+            g.setStroke(paint.getJavaStroke());
+        }
+
+        // the alpha for the composite. Always opaque if the normal paint color is used since
+        // it contains the alpha
+        int alpha = (compositeOnly || customShader) ? paint.getAlpha() : 0xFF;
+
+        if (forceSrcMode) {
+            g.setComposite(AlphaComposite.getInstance(
+                    AlphaComposite.SRC, alpha / 255.f));
+        } else {
+            boolean customXfermode = false;
+            Xfermode_Delegate xfermodeDelegate = paint.getXfermode();
+            if (xfermodeDelegate != null) {
+                if (xfermodeDelegate.isSupported()) {
+                    Composite composite = xfermodeDelegate.getComposite(alpha);
+                    assert composite != null;
+                    if (composite != null) {
+                        g.setComposite(composite);
+                        customXfermode = true;
+                    }
+                } else {
+                    Bridge.getLog().fidelityWarning(LayoutLog.TAG_XFERMODE,
+                            xfermodeDelegate.getSupportMessage(),
+                            null /*throwable*/, null /*data*/);
+                }
+            }
+
+            // if there was no custom xfermode, but we have alpha (due to a shader and a non
+            // opaque alpha channel in the paint color), then we create an AlphaComposite anyway
+            // that will handle the alpha.
+            if (customXfermode == false && alpha != 0xFF) {
+                g.setComposite(AlphaComposite.getInstance(
+                        AlphaComposite.SRC_OVER, alpha / 255.f));
+            }
+        }
+
+        return g;
+    }
+
+    private void mapRect(AffineTransform matrix, RectF dst, RectF src) {
+        // array with 4 corners
+        float[] corners = new float[] {
+                src.left, src.top,
+                src.right, src.top,
+                src.right, src.bottom,
+                src.left, src.bottom,
+        };
+
+        // apply the transform to them.
+        matrix.transform(corners, 0, corners, 0, 4);
+
+        // now put the result in the rect. We take the min/max of Xs and min/max of Ys
+        dst.left = Math.min(Math.min(corners[0], corners[2]), Math.min(corners[4], corners[6]));
+        dst.right = Math.max(Math.max(corners[0], corners[2]), Math.max(corners[4], corners[6]));
+
+        dst.top = Math.min(Math.min(corners[1], corners[3]), Math.min(corners[5], corners[7]));
+        dst.bottom = Math.max(Math.max(corners[1], corners[3]), Math.max(corners[5], corners[7]));
+    }
+
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderAction.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderAction.java
new file mode 100644
index 0000000..6194f5d
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderAction.java
@@ -0,0 +1,290 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.layoutlib.bridge.impl;
+
+import static com.android.ide.common.rendering.api.Result.Status.ERROR_LOCK_INTERRUPTED;
+import static com.android.ide.common.rendering.api.Result.Status.ERROR_TIMEOUT;
+import static com.android.ide.common.rendering.api.Result.Status.SUCCESS;
+
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.ide.common.rendering.api.RenderParams;
+import com.android.ide.common.rendering.api.RenderResources;
+import com.android.ide.common.rendering.api.Result;
+import com.android.ide.common.rendering.api.RenderResources.FrameworkResourceIdProvider;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.android.BridgeContext;
+import com.android.resources.ResourceType;
+
+import android.os.HandlerThread_Delegate;
+import android.util.DisplayMetrics;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReentrantLock;
+
+/**
+ * Base class for rendering action.
+ *
+ * It provides life-cycle methods to init and stop the rendering.
+ * The most important methods are:
+ * {@link #init(long)} and {@link #acquire(long)} to start a rendering and {@link #release()}
+ * after the rendering.
+ *
+ *
+ * @param <T> the {@link RenderParams} implementation
+ *
+ */
+public abstract class RenderAction<T extends RenderParams> extends FrameworkResourceIdProvider {
+
+    /**
+     * The current context being rendered. This is set through {@link #acquire(long)} and
+     * {@link #init(long)}, and unset in {@link #release()}.
+     */
+    private static BridgeContext sCurrentContext = null;
+
+    private final T mParams;
+
+    private BridgeContext mContext;
+
+    /**
+     * Creates a renderAction.
+     * <p>
+     * This <b>must</b> be followed by a call to {@link RenderAction#init()}, which act as a
+     * call to {@link RenderAction#acquire(long)}
+     *
+     * @param params the RenderParams. This must be a copy that the action can keep
+     *
+     */
+    protected RenderAction(T params) {
+        mParams = params;
+    }
+
+    /**
+     * Initializes and acquires the scene, creating various Android objects such as context,
+     * inflater, and parser.
+     *
+     * @param timeout the time to wait if another rendering is happening.
+     *
+     * @return whether the scene was prepared
+     *
+     * @see #acquire(long)
+     * @see #release()
+     */
+    public Result init(long timeout) {
+        // acquire the lock. if the result is null, lock was just acquired, otherwise, return
+        // the result.
+        Result result = acquireLock(timeout);
+        if (result != null) {
+            return result;
+        }
+
+        // setup the display Metrics.
+        DisplayMetrics metrics = new DisplayMetrics();
+        metrics.densityDpi = mParams.getDensity().getDpiValue();
+        metrics.density = metrics.densityDpi / (float) DisplayMetrics.DENSITY_DEFAULT;
+        metrics.scaledDensity = metrics.density;
+        metrics.widthPixels = mParams.getScreenWidth();
+        metrics.heightPixels = mParams.getScreenHeight();
+        metrics.xdpi = mParams.getXdpi();
+        metrics.ydpi = mParams.getYdpi();
+
+        RenderResources resources = mParams.getResources();
+
+        // build the context
+        mContext = new BridgeContext(mParams.getProjectKey(), metrics, resources,
+                mParams.getProjectCallback(), mParams.getTargetSdkVersion());
+
+        setUp();
+
+        return SUCCESS.createResult();
+    }
+
+    /**
+     * Prepares the scene for action.
+     * <p>
+     * This call is blocking if another rendering/inflating is currently happening, and will return
+     * whether the preparation worked.
+     *
+     * The preparation can fail if another rendering took too long and the timeout was elapsed.
+     *
+     * More than one call to this from the same thread will have no effect and will return
+     * {@link Result#SUCCESS}.
+     *
+     * After scene actions have taken place, only one call to {@link #release()} must be
+     * done.
+     *
+     * @param timeout the time to wait if another rendering is happening.
+     *
+     * @return whether the scene was prepared
+     *
+     * @see #release()
+     *
+     * @throws IllegalStateException if {@link #init(long)} was never called.
+     */
+    public Result acquire(long timeout) {
+        if (mContext == null) {
+            throw new IllegalStateException("After scene creation, #init() must be called");
+        }
+
+        // acquire the lock. if the result is null, lock was just acquired, otherwise, return
+        // the result.
+        Result result = acquireLock(timeout);
+        if (result != null) {
+            return result;
+        }
+
+        setUp();
+
+        return SUCCESS.createResult();
+    }
+
+    /**
+     * Acquire the lock so that the scene can be acted upon.
+     * <p>
+     * This returns null if the lock was just acquired, otherwise it returns
+     * {@link Result#SUCCESS} if the lock already belonged to that thread, or another
+     * instance (see {@link Result#getStatus()}) if an error occurred.
+     *
+     * @param timeout the time to wait if another rendering is happening.
+     * @return null if the lock was just acquire or another result depending on the state.
+     *
+     * @throws IllegalStateException if the current context is different than the one owned by
+     *      the scene.
+     */
+    private Result acquireLock(long timeout) {
+        ReentrantLock lock = Bridge.getLock();
+        if (lock.isHeldByCurrentThread() == false) {
+            try {
+                boolean acquired = lock.tryLock(timeout, TimeUnit.MILLISECONDS);
+
+                if (acquired == false) {
+                    return ERROR_TIMEOUT.createResult();
+                }
+            } catch (InterruptedException e) {
+                return ERROR_LOCK_INTERRUPTED.createResult();
+            }
+        } else {
+            // This thread holds the lock already. Checks that this wasn't for a different context.
+            // If this is called by init, mContext will be null and so should sCurrentContext
+            // anyway
+            if (mContext != sCurrentContext) {
+                throw new IllegalStateException("Acquiring different scenes from same thread without releases");
+            }
+            return SUCCESS.createResult();
+        }
+
+        return null;
+    }
+
+    /**
+     * Cleans up the scene after an action.
+     */
+    public void release() {
+        ReentrantLock lock = Bridge.getLock();
+
+        // with the use of finally blocks, it is possible to find ourself calling this
+        // without a successful call to prepareScene. This test makes sure that unlock() will
+        // not throw IllegalMonitorStateException.
+        if (lock.isHeldByCurrentThread()) {
+            tearDown();
+            lock.unlock();
+        }
+    }
+
+    /**
+     * Sets up the session for rendering.
+     * <p/>
+     * The counterpart is {@link #tearDown()}.
+     */
+    private void setUp() {
+        // make sure the Resources object references the context (and other objects) for this
+        // scene
+        mContext.initResources();
+        sCurrentContext = mContext;
+
+        LayoutLog currentLog = mParams.getLog();
+        Bridge.setLog(currentLog);
+        mContext.getRenderResources().setFrameworkResourceIdProvider(this);
+        mContext.getRenderResources().setLogger(currentLog);
+    }
+
+    /**
+     * Tear down the session after rendering.
+     * <p/>
+     * The counterpart is {@link #setUp()}.
+     */
+    private void tearDown() {
+        // Make sure to remove static references, otherwise we could not unload the lib
+        mContext.disposeResources();
+
+        // quit HandlerThread created during this session.
+        HandlerThread_Delegate.cleanUp(sCurrentContext);
+
+        sCurrentContext = null;
+
+        Bridge.setLog(null);
+        mContext.getRenderResources().setFrameworkResourceIdProvider(null);
+        mContext.getRenderResources().setLogger(null);
+    }
+
+    public static BridgeContext getCurrentContext() {
+        return sCurrentContext;
+    }
+
+    protected T getParams() {
+        return mParams;
+    }
+
+    protected BridgeContext getContext() {
+        return mContext;
+    }
+
+    /**
+     * Returns the log associated with the session.
+     * @return the log or null if there are none.
+     */
+    public LayoutLog getLog() {
+        if (mParams != null) {
+            return mParams.getLog();
+        }
+
+        return null;
+    }
+
+    /**
+     * Checks that the lock is owned by the current thread and that the current context is the one
+     * from this scene.
+     *
+     * @throws IllegalStateException if the current context is different than the one owned by
+     *      the scene, or if {@link #acquire(long)} was not called.
+     */
+    protected void checkLock() {
+        ReentrantLock lock = Bridge.getLock();
+        if (lock.isHeldByCurrentThread() == false) {
+            throw new IllegalStateException("scene must be acquired first. see #acquire(long)");
+        }
+        if (sCurrentContext != mContext) {
+            throw new IllegalStateException("Thread acquired a scene but is rendering a different one");
+        }
+    }
+
+    // --- FrameworkResourceIdProvider methods
+
+    @Override
+    public Integer getId(ResourceType resType, String resName) {
+        return Bridge.getResourceId(resType, resName);
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderDrawable.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderDrawable.java
new file mode 100644
index 0000000..10a4368
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderDrawable.java
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.layoutlib.bridge.impl;
+
+import static com.android.ide.common.rendering.api.Result.Status.ERROR_UNKNOWN;
+
+import com.android.ide.common.rendering.api.DrawableParams;
+import com.android.ide.common.rendering.api.ResourceValue;
+import com.android.ide.common.rendering.api.Result;
+import com.android.ide.common.rendering.api.Result.Status;
+import com.android.layoutlib.bridge.android.BridgeContext;
+import com.android.layoutlib.bridge.android.BridgeWindow;
+import com.android.layoutlib.bridge.android.BridgeWindowSession;
+import com.android.resources.ResourceType;
+
+import android.graphics.Bitmap;
+import android.graphics.Bitmap_Delegate;
+import android.graphics.Canvas;
+import android.graphics.drawable.Drawable;
+import android.os.Handler;
+import android.view.View;
+import android.view.View.AttachInfo;
+import android.view.View.MeasureSpec;
+import android.widget.FrameLayout;
+
+import java.awt.AlphaComposite;
+import java.awt.Color;
+import java.awt.Graphics2D;
+import java.awt.image.BufferedImage;
+import java.io.IOException;
+
+/**
+ * Action to render a given Drawable provided through {@link DrawableParams#getDrawable()}.
+ *
+ * The class only provides a simple {@link #render()} method, but the full life-cycle of the
+ * action must be respected.
+ *
+ * @see RenderAction
+ *
+ */
+public class RenderDrawable extends RenderAction<DrawableParams> {
+
+    public RenderDrawable(DrawableParams params) {
+        super(new DrawableParams(params));
+    }
+
+    public Result render() {
+        checkLock();
+        try {
+            // get the drawable resource value
+            DrawableParams params = getParams();
+            ResourceValue drawableResource = params.getDrawable();
+
+            // resolve it
+            BridgeContext context = getContext();
+            drawableResource = context.getRenderResources().resolveResValue(drawableResource);
+
+            if (drawableResource == null ||
+                    drawableResource.getResourceType() != ResourceType.DRAWABLE) {
+                return Status.ERROR_NOT_A_DRAWABLE.createResult();
+            }
+
+            // create a simple FrameLayout
+            FrameLayout content = new FrameLayout(context);
+
+            // get the actual Drawable object to draw
+            Drawable d = ResourceHelper.getDrawable(drawableResource, context);
+            content.setBackgroundDrawable(d);
+
+            // set the AttachInfo on the root view.
+            AttachInfo info = new AttachInfo(new BridgeWindowSession(), new BridgeWindow(),
+                    new Handler(), null);
+            info.mHasWindowFocus = true;
+            info.mWindowVisibility = View.VISIBLE;
+            info.mInTouchMode = false; // this is so that we can display selections.
+            content.dispatchAttachedToWindow(info, 0);
+
+
+            // measure
+            int w = params.getScreenWidth();
+            int h = params.getScreenHeight();
+            int w_spec = MeasureSpec.makeMeasureSpec(w, MeasureSpec.EXACTLY);
+            int h_spec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
+            content.measure(w_spec, h_spec);
+
+            // now do the layout.
+            content.layout(0, 0, w, h);
+
+            // preDraw setup
+            content.mAttachInfo.mTreeObserver.dispatchOnPreDraw();
+
+            // draw into a new image
+            BufferedImage image = getImage(w, h);
+
+            // create an Android bitmap around the BufferedImage
+            Bitmap bitmap = Bitmap_Delegate.createBitmap(image,
+                    true /*isMutable*/, params.getDensity());
+
+            // create a Canvas around the Android bitmap
+            Canvas canvas = new Canvas(bitmap);
+            canvas.setDensity(params.getDensity().getDpiValue());
+
+            // and draw
+            content.draw(canvas);
+
+            return Status.SUCCESS.createResult(image);
+        } catch (IOException e) {
+            return ERROR_UNKNOWN.createResult(e.getMessage(), e);
+        }
+    }
+
+    protected BufferedImage getImage(int w, int h) {
+        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
+        Graphics2D gc = image.createGraphics();
+        gc.setComposite(AlphaComposite.Src);
+
+        gc.setColor(new Color(0x00000000, true));
+        gc.fillRect(0, 0, w, h);
+
+        // done
+        gc.dispose();
+
+        return image;
+    }
+
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderSessionImpl.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderSessionImpl.java
new file mode 100644
index 0000000..f29a9d0
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderSessionImpl.java
@@ -0,0 +1,1158 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.layoutlib.bridge.impl;
+
+import static com.android.ide.common.rendering.api.Result.Status.ERROR_INFLATION;
+import static com.android.ide.common.rendering.api.Result.Status.ERROR_NOT_INFLATED;
+import static com.android.ide.common.rendering.api.Result.Status.ERROR_UNKNOWN;
+import static com.android.ide.common.rendering.api.Result.Status.ERROR_VIEWGROUP_NO_CHILDREN;
+import static com.android.ide.common.rendering.api.Result.Status.SUCCESS;
+
+import com.android.ide.common.rendering.api.AdapterBinding;
+import com.android.ide.common.rendering.api.IAnimationListener;
+import com.android.ide.common.rendering.api.ILayoutPullParser;
+import com.android.ide.common.rendering.api.IProjectCallback;
+import com.android.ide.common.rendering.api.RenderParams;
+import com.android.ide.common.rendering.api.RenderResources;
+import com.android.ide.common.rendering.api.RenderSession;
+import com.android.ide.common.rendering.api.ResourceReference;
+import com.android.ide.common.rendering.api.ResourceValue;
+import com.android.ide.common.rendering.api.Result;
+import com.android.ide.common.rendering.api.SessionParams;
+import com.android.ide.common.rendering.api.ViewInfo;
+import com.android.ide.common.rendering.api.Result.Status;
+import com.android.ide.common.rendering.api.SessionParams.RenderingMode;
+import com.android.internal.util.XmlUtils;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.android.BridgeContext;
+import com.android.layoutlib.bridge.android.BridgeInflater;
+import com.android.layoutlib.bridge.android.BridgeLayoutParamsMapAttributes;
+import com.android.layoutlib.bridge.android.BridgeWindow;
+import com.android.layoutlib.bridge.android.BridgeWindowSession;
+import com.android.layoutlib.bridge.android.BridgeXmlBlockParser;
+import com.android.layoutlib.bridge.bars.PhoneSystemBar;
+import com.android.layoutlib.bridge.bars.TitleBar;
+import com.android.layoutlib.bridge.impl.binding.FakeAdapter;
+import com.android.layoutlib.bridge.impl.binding.FakeExpandableAdapter;
+import com.android.resources.ResourceType;
+import com.android.resources.ScreenSize;
+import com.android.util.Pair;
+
+import org.xmlpull.v1.XmlPullParserException;
+
+import android.graphics.Bitmap;
+import android.graphics.Bitmap_Delegate;
+import android.graphics.Canvas;
+import android.graphics.drawable.Drawable;
+import android.os.Handler;
+import android.util.DisplayMetrics;
+import android.util.TypedValue;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.View.AttachInfo;
+import android.view.View.MeasureSpec;
+import android.view.ViewGroup.LayoutParams;
+import android.view.ViewGroup.MarginLayoutParams;
+import android.widget.AbsListView;
+import android.widget.AbsSpinner;
+import android.widget.AdapterView;
+import android.widget.ExpandableListView;
+import android.widget.FrameLayout;
+import android.widget.LinearLayout;
+import android.widget.ListView;
+import android.widget.TabHost;
+import android.widget.TabWidget;
+import android.widget.TabHost.TabSpec;
+
+import java.awt.AlphaComposite;
+import java.awt.Color;
+import java.awt.Graphics2D;
+import java.awt.image.BufferedImage;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Class implementing the render session.
+ *
+ * A session is a stateful representation of a layout file. It is initialized with data coming
+ * through the {@link Bridge} API to inflate the layout. Further actions and rendering can then
+ * be done on the layout.
+ *
+ */
+public class RenderSessionImpl extends RenderAction<SessionParams> {
+
+    private static final int DEFAULT_TITLE_BAR_HEIGHT = 25;
+    private static final int DEFAULT_STATUS_BAR_HEIGHT = 25;
+
+    // scene state
+    private RenderSession mScene;
+    private BridgeXmlBlockParser mBlockParser;
+    private BridgeInflater mInflater;
+    private ResourceValue mWindowBackground;
+    private ViewGroup mViewRoot;
+    private FrameLayout mContentRoot;
+    private Canvas mCanvas;
+    private int mMeasuredScreenWidth = -1;
+    private int mMeasuredScreenHeight = -1;
+    private boolean mIsAlphaChannelImage;
+    private boolean mWindowIsFloating;
+
+    private int mStatusBarSize;
+    private int mTitleBarSize;
+
+
+    // information being returned through the API
+    private BufferedImage mImage;
+    private List<ViewInfo> mViewInfoList;
+
+    private static final class PostInflateException extends Exception {
+        private static final long serialVersionUID = 1L;
+
+        public PostInflateException(String message) {
+            super(message);
+        }
+    }
+
+    /**
+     * Creates a layout scene with all the information coming from the layout bridge API.
+     * <p>
+     * This <b>must</b> be followed by a call to {@link RenderSessionImpl#init()}, which act as a
+     * call to {@link RenderSessionImpl#acquire(long)}
+     *
+     * @see LayoutBridge#createScene(com.android.layoutlib.api.SceneParams)
+     */
+    public RenderSessionImpl(SessionParams params) {
+        super(new SessionParams(params));
+    }
+
+    /**
+     * Initializes and acquires the scene, creating various Android objects such as context,
+     * inflater, and parser.
+     *
+     * @param timeout the time to wait if another rendering is happening.
+     *
+     * @return whether the scene was prepared
+     *
+     * @see #acquire(long)
+     * @see #release()
+     */
+    @Override
+    public Result init(long timeout) {
+        Result result = super.init(timeout);
+        if (result.isSuccess() == false) {
+            return result;
+        }
+
+        SessionParams params = getParams();
+        BridgeContext context = getContext();
+
+        RenderResources resources = getParams().getResources();
+        DisplayMetrics metrics = getContext().getMetrics();
+
+        // use default of true in case it's not found to use alpha by default
+        mIsAlphaChannelImage  = getBooleanThemeValue(resources,
+                "windowIsFloating", true /*defaultValue*/);
+
+        mWindowIsFloating = getBooleanThemeValue(resources, "windowIsFloating",
+                true /*defaultValue*/);
+
+        findBackground(resources);
+        findStatusBar(resources, metrics);
+        findTitleBar(resources, metrics);
+
+        // build the inflater and parser.
+        mInflater = new BridgeInflater(context, params.getProjectCallback());
+        context.setBridgeInflater(mInflater);
+
+        mBlockParser = new BridgeXmlBlockParser(
+                params.getLayoutDescription(), context, false /* platformResourceFlag */);
+
+        return SUCCESS.createResult();
+    }
+
+    /**
+     * Inflates the layout.
+     * <p>
+     * {@link #acquire(long)} must have been called before this.
+     *
+     * @throws IllegalStateException if the current context is different than the one owned by
+     *      the scene, or if {@link #init(long)} was not called.
+     */
+    public Result inflate() {
+        checkLock();
+
+        try {
+
+            SessionParams params = getParams();
+            BridgeContext context = getContext();
+
+            // the view group that receives the window background.
+            ViewGroup backgroundView = null;
+
+            if (mWindowIsFloating || params.isForceNoDecor()) {
+                backgroundView = mViewRoot = mContentRoot = new FrameLayout(context);
+            } else {
+                /*
+                 * we're creating the following layout
+                 *
+                   +-------------------------------------------------+
+                   | System bar                                      |
+                   +-------------------------------------------------+
+                   | (Layout with background drawable)               |
+                   | +---------------------------------------------+ |
+                   | | Title (optional)                            | |
+                   | +---------------------------------------------+ |
+                   | | Content, vertical extending                 | |
+                   | |                                             | |
+                   | +---------------------------------------------+ |
+                   +-------------------------------------------------+
+
+                 */
+
+                LinearLayout topLayout = new LinearLayout(context);
+                mViewRoot = topLayout;
+                topLayout.setOrientation(LinearLayout.VERTICAL);
+
+                if (mStatusBarSize > 0) {
+                    // system bar
+                    try {
+                        PhoneSystemBar systemBar = new PhoneSystemBar(context,
+                                params.getDensity());
+                        systemBar.setLayoutParams(
+                                new LinearLayout.LayoutParams(
+                                        LayoutParams.MATCH_PARENT, mStatusBarSize));
+                        topLayout.addView(systemBar);
+                    } catch (XmlPullParserException e) {
+
+                    }
+                }
+
+                LinearLayout backgroundLayout = new LinearLayout(context);
+                backgroundView = backgroundLayout;
+                backgroundLayout.setOrientation(LinearLayout.VERTICAL);
+                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
+                        LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
+                layoutParams.weight = 1;
+                backgroundLayout.setLayoutParams(layoutParams);
+                topLayout.addView(backgroundLayout);
+
+
+                // if the theme says no title, then the size will be 0
+                if (mTitleBarSize > 0) {
+                    try {
+                        TitleBar titleBar = new TitleBar(context,
+                                params.getDensity(), params.getAppLabel());
+                        titleBar.setLayoutParams(
+                                new LinearLayout.LayoutParams(
+                                        LayoutParams.MATCH_PARENT, mTitleBarSize));
+                        backgroundLayout.addView(titleBar);
+                    } catch (XmlPullParserException e) {
+
+                    }
+                }
+
+                // content frame
+                mContentRoot = new FrameLayout(context);
+                layoutParams = new LinearLayout.LayoutParams(
+                        LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
+                layoutParams.weight = 1;
+                mContentRoot.setLayoutParams(layoutParams);
+                backgroundLayout.addView(mContentRoot);
+            }
+
+
+            View view = mInflater.inflate(mBlockParser, mContentRoot);
+
+            // done with the parser, pop it.
+            context.popParser();
+
+            // set the AttachInfo on the root view.
+            AttachInfo info = new AttachInfo(new BridgeWindowSession(), new BridgeWindow(),
+                    new Handler(), null);
+            info.mHasWindowFocus = true;
+            info.mWindowVisibility = View.VISIBLE;
+            info.mInTouchMode = false; // this is so that we can display selections.
+            mViewRoot.dispatchAttachedToWindow(info, 0);
+
+            // post-inflate process. For now this supports TabHost/TabWidget
+            postInflateProcess(view, params.getProjectCallback());
+
+            // get the background drawable
+            if (mWindowBackground != null && backgroundView != null) {
+                Drawable d = ResourceHelper.getDrawable(mWindowBackground, context);
+                backgroundView.setBackgroundDrawable(d);
+            }
+
+            return SUCCESS.createResult();
+        } catch (PostInflateException e) {
+            return ERROR_INFLATION.createResult(e.getMessage(), e);
+        } catch (Throwable e) {
+            // get the real cause of the exception.
+            Throwable t = e;
+            while (t.getCause() != null) {
+                t = t.getCause();
+            }
+
+            return ERROR_INFLATION.createResult(t.getMessage(), t);
+        }
+    }
+
+    /**
+     * Renders the scene.
+     * <p>
+     * {@link #acquire(long)} must have been called before this.
+     *
+     * @param freshRender whether the render is a new one and should erase the existing bitmap (in
+     *      the case where bitmaps are reused). This is typically needed when not playing
+     *      animations.)
+     *
+     * @throws IllegalStateException if the current context is different than the one owned by
+     *      the scene, or if {@link #acquire(long)} was not called.
+     *
+     * @see RenderParams#getRenderingMode()
+     * @see RenderSession#render(long)
+     */
+    public Result render(boolean freshRender) {
+        checkLock();
+
+        SessionParams params = getParams();
+
+        try {
+            if (mViewRoot == null) {
+                return ERROR_NOT_INFLATED.createResult();
+            }
+
+            RenderingMode renderingMode = params.getRenderingMode();
+
+            // only do the screen measure when needed.
+            boolean newRenderSize = false;
+            if (mMeasuredScreenWidth == -1) {
+                newRenderSize = true;
+                mMeasuredScreenWidth = params.getScreenWidth();
+                mMeasuredScreenHeight = params.getScreenHeight();
+
+                if (renderingMode != RenderingMode.NORMAL) {
+                    int widthMeasureSpecMode = renderingMode.isHorizExpand() ?
+                            MeasureSpec.UNSPECIFIED // this lets us know the actual needed size
+                            : MeasureSpec.EXACTLY;
+                    int heightMeasureSpecMode = renderingMode.isVertExpand() ?
+                            MeasureSpec.UNSPECIFIED // this lets us know the actual needed size
+                            : MeasureSpec.EXACTLY;
+
+                    // We used to compare the measured size of the content to the screen size but
+                    // this does not work anymore due to the 2 following issues:
+                    // - If the content is in a decor (system bar, title/action bar), the root view
+                    //   will not resize even with the UNSPECIFIED because of the embedded layout.
+                    // - If there is no decor, but a dialog frame, then the dialog padding prevents
+                    //   comparing the size of the content to the screen frame (as it would not
+                    //   take into account the dialog padding).
+
+                    // The solution is to first get the content size in a normal rendering, inside
+                    // the decor or the dialog padding.
+                    // Then measure only the content with UNSPECIFIED to see the size difference
+                    // and apply this to the screen size.
+
+                    // first measure the full layout, with EXACTLY to get the size of the
+                    // content as it is inside the decor/dialog
+                    Pair<Integer, Integer> exactMeasure = measureView(
+                            mViewRoot, mContentRoot.getChildAt(0),
+                            mMeasuredScreenWidth, MeasureSpec.EXACTLY,
+                            mMeasuredScreenHeight, MeasureSpec.EXACTLY);
+
+                    // now measure the content only using UNSPECIFIED (where applicable, based on
+                    // the rendering mode). This will give us the size the content needs.
+                    Pair<Integer, Integer> result = measureView(
+                            mContentRoot, mContentRoot.getChildAt(0),
+                            mMeasuredScreenWidth, widthMeasureSpecMode,
+                            mMeasuredScreenHeight, heightMeasureSpecMode);
+
+                    // now look at the difference and add what is needed.
+                    if (renderingMode.isHorizExpand()) {
+                        int measuredWidth = exactMeasure.getFirst();
+                        int neededWidth = result.getFirst();
+                        if (neededWidth > measuredWidth) {
+                            mMeasuredScreenWidth += neededWidth - measuredWidth;
+                        }
+                    }
+
+                    if (renderingMode.isVertExpand()) {
+                        int measuredHeight = exactMeasure.getSecond();
+                        int neededHeight = result.getSecond();
+                        if (neededHeight > measuredHeight) {
+                            mMeasuredScreenHeight += neededHeight - measuredHeight;
+                        }
+                    }
+                }
+            }
+
+            // measure again with the size we need
+            // This must always be done before the call to layout
+            measureView(mViewRoot, null /*measuredView*/,
+                    mMeasuredScreenWidth, MeasureSpec.EXACTLY,
+                    mMeasuredScreenHeight, MeasureSpec.EXACTLY);
+
+            // now do the layout.
+            mViewRoot.layout(0, 0, mMeasuredScreenWidth, mMeasuredScreenHeight);
+
+            if (params.isLayoutOnly()) {
+                // delete the canvas and image to reset them on the next full rendering
+                mImage = null;
+                mCanvas = null;
+            } else {
+                mViewRoot.mAttachInfo.mTreeObserver.dispatchOnPreDraw();
+
+                // draw the views
+                // create the BufferedImage into which the layout will be rendered.
+                boolean newImage = false;
+                if (newRenderSize || mCanvas == null) {
+                    if (params.getImageFactory() != null) {
+                        mImage = params.getImageFactory().getImage(
+                                mMeasuredScreenWidth,
+                                mMeasuredScreenHeight);
+                    } else {
+                        mImage = new BufferedImage(
+                                mMeasuredScreenWidth,
+                                mMeasuredScreenHeight,
+                                BufferedImage.TYPE_INT_ARGB);
+                        newImage = true;
+                    }
+
+                    if (params.isBgColorOverridden()) {
+                        // since we override the content, it's the same as if it was a new image.
+                        newImage = true;
+                        Graphics2D gc = mImage.createGraphics();
+                        gc.setColor(new Color(params.getOverrideBgColor(), true));
+                        gc.setComposite(AlphaComposite.Src);
+                        gc.fillRect(0, 0, mMeasuredScreenWidth, mMeasuredScreenHeight);
+                        gc.dispose();
+                    }
+
+                    // create an Android bitmap around the BufferedImage
+                    Bitmap bitmap = Bitmap_Delegate.createBitmap(mImage,
+                            true /*isMutable*/, params.getDensity());
+
+                    // create a Canvas around the Android bitmap
+                    mCanvas = new Canvas(bitmap);
+                    mCanvas.setDensity(params.getDensity().getDpiValue());
+                }
+
+                if (freshRender && newImage == false) {
+                    Graphics2D gc = mImage.createGraphics();
+                    gc.setComposite(AlphaComposite.Src);
+
+                    gc.setColor(new Color(0x00000000, true));
+                    gc.fillRect(0, 0,
+                            mMeasuredScreenWidth, mMeasuredScreenHeight);
+
+                    // done
+                    gc.dispose();
+                }
+
+                mViewRoot.draw(mCanvas);
+            }
+
+            mViewInfoList = startVisitingViews(mViewRoot, 0, params.getExtendedViewInfoMode());
+
+            // success!
+            return SUCCESS.createResult();
+        } catch (Throwable e) {
+            // get the real cause of the exception.
+            Throwable t = e;
+            while (t.getCause() != null) {
+                t = t.getCause();
+            }
+
+            return ERROR_UNKNOWN.createResult(t.getMessage(), t);
+        }
+    }
+
+    /**
+     * Executes {@link View#measure(int, int)} on a given view with the given parameters (used
+     * to create measure specs with {@link MeasureSpec#makeMeasureSpec(int, int)}.
+     *
+     * if <var>measuredView</var> is non null, the method returns a {@link Pair} of (width, height)
+     * for the view (using {@link View#getMeasuredWidth()} and {@link View#getMeasuredHeight()}).
+     *
+     * @param viewToMeasure the view on which to execute measure().
+     * @param measuredView if non null, the view to query for its measured width/height.
+     * @param width the width to use in the MeasureSpec.
+     * @param widthMode the MeasureSpec mode to use for the width.
+     * @param height the height to use in the MeasureSpec.
+     * @param heightMode the MeasureSpec mode to use for the height.
+     * @return the measured width/height if measuredView is non-null, null otherwise.
+     */
+    private Pair<Integer, Integer> measureView(ViewGroup viewToMeasure, View measuredView,
+            int width, int widthMode, int height, int heightMode) {
+        int w_spec = MeasureSpec.makeMeasureSpec(width, widthMode);
+        int h_spec = MeasureSpec.makeMeasureSpec(height, heightMode);
+        viewToMeasure.measure(w_spec, h_spec);
+
+        if (measuredView != null) {
+            return Pair.of(measuredView.getMeasuredWidth(), measuredView.getMeasuredHeight());
+        }
+
+        return null;
+    }
+
+    /**
+     * Insert a new child into an existing parent.
+     * <p>
+     * {@link #acquire(long)} must have been called before this.
+     *
+     * @throws IllegalStateException if the current context is different than the one owned by
+     *      the scene, or if {@link #acquire(long)} was not called.
+     *
+     * @see RenderSession#insertChild(Object, ILayoutPullParser, int, IAnimationListener)
+     */
+    public Result insertChild(final ViewGroup parentView, ILayoutPullParser childXml,
+            final int index, final IAnimationListener listener) {
+        checkLock();
+
+        BridgeContext context = getContext();
+
+        // create a block parser for the XML
+        BridgeXmlBlockParser blockParser = new BridgeXmlBlockParser(
+                childXml, context, false /* platformResourceFlag */);
+
+        // inflate the child without adding it to the root since we want to control where it'll
+        // get added. We do pass the parentView however to ensure that the layoutParams will
+        // be created correctly.
+        final View child = mInflater.inflate(blockParser, parentView, false /*attachToRoot*/);
+        blockParser.ensurePopped();
+
+        invalidateRenderingSize();
+
+        if (listener != null) {
+            // there is no support for animating views in this API level, so we fake the animation
+            // through a no animation thread.
+            new Thread("not animated insertChild") {
+                @Override
+                public void run() {
+                    Result result = addView(parentView, child, index);
+                    if (result.isSuccess() == false) {
+                        listener.done(result);
+                    }
+
+                    // ready to do the work, acquire the scene.
+                    result = acquire(250);
+                    if (result.isSuccess() == false) {
+                        listener.done(result);
+                        return;
+                    }
+
+                    try {
+                        result = render(false /*freshRender*/);
+                        if (result.isSuccess()) {
+                            listener.onNewFrame(RenderSessionImpl.this.getSession());
+                        }
+                    } finally {
+                        release();
+                    }
+
+                    listener.done(result);
+                }
+            }.start();
+
+            // always return success since the real status will come through the listener.
+            return SUCCESS.createResult(child);
+        }
+
+        // add it to the parentView in the correct location
+        Result result = addView(parentView, child, index);
+        if (result.isSuccess() == false) {
+            return result;
+        }
+
+        result = render(false /*freshRender*/);
+        if (result.isSuccess()) {
+            result = result.getCopyWithData(child);
+        }
+
+        return result;
+    }
+
+    /**
+     * Adds a given view to a given parent at a given index.
+     *
+     * @param parent the parent to receive the view
+     * @param view the view to add to the parent
+     * @param index the index where to do the add.
+     *
+     * @return a Result with {@link Status#SUCCESS} or
+     *     {@link Status#ERROR_VIEWGROUP_NO_CHILDREN} if the given parent doesn't support
+     *     adding views.
+     */
+    private Result addView(ViewGroup parent, View view, int index) {
+        try {
+            parent.addView(view, index);
+            return SUCCESS.createResult();
+        } catch (UnsupportedOperationException e) {
+            // looks like this is a view class that doesn't support children manipulation!
+            return ERROR_VIEWGROUP_NO_CHILDREN.createResult();
+        }
+    }
+
+    /**
+     * Moves a view to a new parent at a given location
+     * <p>
+     * {@link #acquire(long)} must have been called before this.
+     *
+     * @throws IllegalStateException if the current context is different than the one owned by
+     *      the scene, or if {@link #acquire(long)} was not called.
+     *
+     * @see RenderSession#moveChild(Object, Object, int, Map, IAnimationListener)
+     */
+    public Result moveChild(final ViewGroup newParentView, final View childView, final int index,
+            Map<String, String> layoutParamsMap, final IAnimationListener listener) {
+        checkLock();
+
+        invalidateRenderingSize();
+
+        LayoutParams layoutParams = null;
+        if (layoutParamsMap != null) {
+            // need to create a new LayoutParams object for the new parent.
+            layoutParams = newParentView.generateLayoutParams(
+                    new BridgeLayoutParamsMapAttributes(layoutParamsMap));
+        }
+
+        // get the current parent of the view that needs to be moved.
+        final ViewGroup previousParent = (ViewGroup) childView.getParent();
+
+        if (listener != null) {
+            final LayoutParams params = layoutParams;
+
+            // there is no support for animating views in this API level, so we fake the animation
+            // through a no animation thread.
+            new Thread("not animated moveChild") {
+                @Override
+                public void run() {
+                    Result result = moveView(previousParent, newParentView, childView, index,
+                            params);
+                    if (result.isSuccess() == false) {
+                        listener.done(result);
+                    }
+
+                    // ready to do the work, acquire the scene.
+                    result = acquire(250);
+                    if (result.isSuccess() == false) {
+                        listener.done(result);
+                        return;
+                    }
+
+                    try {
+                        result = render(false /*freshRender*/);
+                        if (result.isSuccess()) {
+                            listener.onNewFrame(RenderSessionImpl.this.getSession());
+                        }
+                    } finally {
+                        release();
+                    }
+
+                    listener.done(result);
+                }
+            }.start();
+
+            // always return success since the real status will come through the listener.
+            return SUCCESS.createResult(layoutParams);
+        }
+
+        Result result = moveView(previousParent, newParentView, childView, index, layoutParams);
+        if (result.isSuccess() == false) {
+            return result;
+        }
+
+        result = render(false /*freshRender*/);
+        if (layoutParams != null && result.isSuccess()) {
+            result = result.getCopyWithData(layoutParams);
+        }
+
+        return result;
+    }
+
+    /**
+     * Moves a View from its current parent to a new given parent at a new given location, with
+     * an optional new {@link LayoutParams} instance
+     *
+     * @param previousParent the previous parent, still owning the child at the time of the call.
+     * @param newParent the new parent
+     * @param movedView the view to move
+     * @param index the new location in the new parent
+     * @param params an option (can be null) {@link LayoutParams} instance.
+     *
+     * @return a Result with {@link Status#SUCCESS} or
+     *     {@link Status#ERROR_VIEWGROUP_NO_CHILDREN} if the given parent doesn't support
+     *     adding views.
+     */
+    private Result moveView(ViewGroup previousParent, final ViewGroup newParent,
+            final View movedView, final int index, final LayoutParams params) {
+        try {
+            // standard code with no animation. pretty simple.
+            previousParent.removeView(movedView);
+
+            // add it to the parentView in the correct location
+            if (params != null) {
+                newParent.addView(movedView, index, params);
+            } else {
+                newParent.addView(movedView, index);
+            }
+
+            return SUCCESS.createResult();
+        } catch (UnsupportedOperationException e) {
+            // looks like this is a view class that doesn't support children manipulation!
+            return ERROR_VIEWGROUP_NO_CHILDREN.createResult();
+        }
+    }
+
+    /**
+     * Removes a child from its current parent.
+     * <p>
+     * {@link #acquire(long)} must have been called before this.
+     *
+     * @throws IllegalStateException if the current context is different than the one owned by
+     *      the scene, or if {@link #acquire(long)} was not called.
+     *
+     * @see RenderSession#removeChild(Object, IAnimationListener)
+     */
+    public Result removeChild(final View childView, final IAnimationListener listener) {
+        checkLock();
+
+        invalidateRenderingSize();
+
+        final ViewGroup parent = (ViewGroup) childView.getParent();
+
+        if (listener != null) {
+            // there is no support for animating views in this API level, so we fake the animation
+            // through a no animation thread.
+            new Thread("not animated moveChild") {
+                @Override
+                public void run() {
+                    Result result = removeView(parent, childView);
+                    if (result.isSuccess() == false) {
+                        listener.done(result);
+                    }
+
+                    // ready to do the work, acquire the scene.
+                    result = acquire(250);
+                    if (result.isSuccess() == false) {
+                        listener.done(result);
+                        return;
+                    }
+
+                    try {
+                        result = render(false /*freshRender*/);
+                        if (result.isSuccess()) {
+                            listener.onNewFrame(RenderSessionImpl.this.getSession());
+                        }
+                    } finally {
+                        release();
+                    }
+
+                    listener.done(result);
+                }
+            }.start();
+
+            // always return success since the real status will come through the listener.
+            return SUCCESS.createResult();
+        }
+
+        Result result = removeView(parent, childView);
+        if (result.isSuccess() == false) {
+            return result;
+        }
+
+        return render(false /*freshRender*/);
+    }
+
+    /**
+     * Removes a given view from its current parent.
+     *
+     * @param view the view to remove from its parent
+     *
+     * @return a Result with {@link Status#SUCCESS} or
+     *     {@link Status#ERROR_VIEWGROUP_NO_CHILDREN} if the given parent doesn't support
+     *     adding views.
+     */
+    private Result removeView(ViewGroup parent, View view) {
+        try {
+            parent.removeView(view);
+            return SUCCESS.createResult();
+        } catch (UnsupportedOperationException e) {
+            // looks like this is a view class that doesn't support children manipulation!
+            return ERROR_VIEWGROUP_NO_CHILDREN.createResult();
+        }
+    }
+
+
+    private void findBackground(RenderResources resources) {
+        if (getParams().isBgColorOverridden() == false) {
+            mWindowBackground = resources.findItemInTheme("windowBackground");
+            if (mWindowBackground != null) {
+                mWindowBackground = resources.resolveResValue(mWindowBackground);
+            }
+        }
+    }
+
+    private void findStatusBar(RenderResources resources, DisplayMetrics metrics) {
+        boolean windowFullscreen = getBooleanThemeValue(resources,
+                "windowFullscreen", false /*defaultValue*/);
+
+        if (windowFullscreen == false && mWindowIsFloating == false) {
+            // default value
+            mStatusBarSize = DEFAULT_STATUS_BAR_HEIGHT;
+
+            // get the real value
+            ResourceValue value = resources.getFrameworkResource(ResourceType.DIMEN,
+                    "status_bar_height");
+
+            if (value != null) {
+                TypedValue typedValue = ResourceHelper.getValue(value.getValue());
+                if (typedValue != null) {
+                    // compute the pixel value based on the display metrics
+                    mStatusBarSize = (int)typedValue.getDimension(metrics);
+                }
+            }
+        }
+    }
+
+    private void findTitleBar(RenderResources resources, DisplayMetrics metrics) {
+        if (mWindowIsFloating) {
+            return;
+        }
+
+        boolean windowNoTitle = getBooleanThemeValue(resources,
+                "windowNoTitle", false /*defaultValue*/);
+
+        if (windowNoTitle == false) {
+
+            // default size of the window title bar
+            mTitleBarSize = DEFAULT_TITLE_BAR_HEIGHT;
+
+            // get value from the theme.
+            ResourceValue value = resources.findItemInTheme("windowTitleSize");
+
+            // resolve it
+            value = resources.resolveResValue(value);
+
+            if (value != null) {
+                // get the numerical value, if available
+                TypedValue typedValue = ResourceHelper.getValue(value.getValue());
+                if (typedValue != null) {
+                    // compute the pixel value based on the display metrics
+                    mTitleBarSize = (int)typedValue.getDimension(metrics);
+                }
+            }
+        }
+    }
+
+    private boolean getBooleanThemeValue(RenderResources resources,
+            String name, boolean defaultValue) {
+
+        // get the title bar flag from the current theme.
+        ResourceValue value = resources.findItemInTheme(name);
+
+        // because it may reference something else, we resolve it.
+        value = resources.resolveResValue(value);
+
+        // if there's no value, return the default.
+        if (value == null || value.getValue() == null) {
+            return defaultValue;
+        }
+
+        return XmlUtils.convertValueToBoolean(value.getValue(), defaultValue);
+    }
+
+    /**
+     * Post process on a view hierachy that was just inflated.
+     * <p/>At the moment this only support TabHost: If {@link TabHost} is detected, look for the
+     * {@link TabWidget}, and the corresponding {@link FrameLayout} and make new tabs automatically
+     * based on the content of the {@link FrameLayout}.
+     * @param view the root view to process.
+     * @param projectCallback callback to the project.
+     */
+    private void postInflateProcess(View view, IProjectCallback projectCallback)
+            throws PostInflateException {
+        if (view instanceof TabHost) {
+            setupTabHost((TabHost)view, projectCallback);
+        } else if (view instanceof AdapterView<?>) {
+            // get the view ID.
+            int id = view.getId();
+
+            BridgeContext context = getContext();
+
+            // get a ResourceReference from the integer ID.
+            ResourceReference listRef = context.resolveId(id);
+
+            if (listRef != null) {
+                SessionParams params = getParams();
+                AdapterBinding binding = params.getAdapterBindings().get(listRef);
+
+                // if there was no adapter binding, trying to get it from the call back.
+                if (binding == null) {
+                    binding = params.getProjectCallback().getAdapterBinding(listRef,
+                            context.getViewKey(view), view);
+                }
+
+                if (binding != null) {
+
+                    if (view instanceof AbsListView) {
+                        if ((binding.getFooterCount() > 0 || binding.getHeaderCount() > 0) &&
+                                view instanceof ListView) {
+                            ListView list = (ListView) view;
+
+                            boolean skipCallbackParser = false;
+
+                            int count = binding.getHeaderCount();
+                            for (int i = 0 ; i < count ; i++) {
+                                Pair<View, Boolean> pair = context.inflateView(
+                                        binding.getHeaderAt(i),
+                                        list, false /*attachToRoot*/, skipCallbackParser);
+                                if (pair.getFirst() != null) {
+                                    list.addHeaderView(pair.getFirst());
+                                }
+
+                                skipCallbackParser |= pair.getSecond();
+                            }
+
+                            count = binding.getFooterCount();
+                            for (int i = 0 ; i < count ; i++) {
+                                Pair<View, Boolean> pair = context.inflateView(
+                                        binding.getFooterAt(i),
+                                        list, false /*attachToRoot*/, skipCallbackParser);
+                                if (pair.getFirst() != null) {
+                                    list.addFooterView(pair.getFirst());
+                                }
+
+                                skipCallbackParser |= pair.getSecond();
+                            }
+                        }
+
+                        if (view instanceof ExpandableListView) {
+                            ((ExpandableListView) view).setAdapter(
+                                    new FakeExpandableAdapter(
+                                            listRef, binding, params.getProjectCallback()));
+                        } else {
+                            ((AbsListView) view).setAdapter(
+                                    new FakeAdapter(
+                                            listRef, binding, params.getProjectCallback()));
+                        }
+                    } else if (view instanceof AbsSpinner) {
+                        ((AbsSpinner) view).setAdapter(
+                                new FakeAdapter(
+                                        listRef, binding, params.getProjectCallback()));
+                    }
+                }
+            }
+        } else if (view instanceof ViewGroup) {
+            ViewGroup group = (ViewGroup)view;
+            final int count = group.getChildCount();
+            for (int c = 0 ; c < count ; c++) {
+                View child = group.getChildAt(c);
+                postInflateProcess(child, projectCallback);
+            }
+        }
+    }
+
+    /**
+     * Sets up a {@link TabHost} object.
+     * @param tabHost the TabHost to setup.
+     * @param projectCallback The project callback object to access the project R class.
+     * @throws PostInflateException
+     */
+    private void setupTabHost(TabHost tabHost, IProjectCallback projectCallback)
+            throws PostInflateException {
+        // look for the TabWidget, and the FrameLayout. They have their own specific names
+        View v = tabHost.findViewById(android.R.id.tabs);
+
+        if (v == null) {
+            throw new PostInflateException(
+                    "TabHost requires a TabWidget with id \"android:id/tabs\".\n");
+        }
+
+        if ((v instanceof TabWidget) == false) {
+            throw new PostInflateException(String.format(
+                    "TabHost requires a TabWidget with id \"android:id/tabs\".\n" +
+                    "View found with id 'tabs' is '%s'", v.getClass().getCanonicalName()));
+        }
+
+        v = tabHost.findViewById(android.R.id.tabcontent);
+
+        if (v == null) {
+            // TODO: see if we can fake tabs even without the FrameLayout (same below when the framelayout is empty)
+            throw new PostInflateException(
+                    "TabHost requires a FrameLayout with id \"android:id/tabcontent\".");
+        }
+
+        if ((v instanceof FrameLayout) == false) {
+            throw new PostInflateException(String.format(
+                    "TabHost requires a FrameLayout with id \"android:id/tabcontent\".\n" +
+                    "View found with id 'tabcontent' is '%s'", v.getClass().getCanonicalName()));
+        }
+
+        FrameLayout content = (FrameLayout)v;
+
+        // now process the content of the framelayout and dynamically create tabs for it.
+        final int count = content.getChildCount();
+
+        // this must be called before addTab() so that the TabHost searches its TabWidget
+        // and FrameLayout.
+        tabHost.setup();
+
+        if (count == 0) {
+            // Create a dummy child to get a single tab
+            TabSpec spec = tabHost.newTabSpec("tag").setIndicator("Tab Label",
+                    tabHost.getResources().getDrawable(android.R.drawable.ic_menu_info_details))
+                    .setContent(new TabHost.TabContentFactory() {
+                        public View createTabContent(String tag) {
+                            return new LinearLayout(getContext());
+                        }
+                    });
+            tabHost.addTab(spec);
+            return;
+        } else {
+            // for each child of the framelayout, add a new TabSpec
+            for (int i = 0 ; i < count ; i++) {
+                View child = content.getChildAt(i);
+                String tabSpec = String.format("tab_spec%d", i+1);
+                int id = child.getId();
+                Pair<ResourceType, String> resource = projectCallback.resolveResourceId(id);
+                String name;
+                if (resource != null) {
+                    name = resource.getSecond();
+                } else {
+                    name = String.format("Tab %d", i+1); // default name if id is unresolved.
+                }
+                tabHost.addTab(tabHost.newTabSpec(tabSpec).setIndicator(name).setContent(id));
+            }
+        }
+    }
+
+    private List<ViewInfo> startVisitingViews(View view, int offset, boolean setExtendedInfo) {
+        if (view == null) {
+            return null;
+        }
+
+        // adjust the offset to this view.
+        offset += view.getTop();
+
+        if (view == mContentRoot) {
+            return visitAllChildren(mContentRoot, offset, setExtendedInfo);
+        }
+
+        // otherwise, look for mContentRoot in the children
+        if (view instanceof ViewGroup) {
+            ViewGroup group = ((ViewGroup) view);
+
+            for (int i = 0; i < group.getChildCount(); i++) {
+                List<ViewInfo> list = startVisitingViews(group.getChildAt(i), offset,
+                        setExtendedInfo);
+                if (list != null) {
+                    return list;
+                }
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * Visits a View and its children and generate a {@link ViewInfo} containing the
+     * bounds of all the views.
+     * @param view the root View
+     * @param offset an offset for the view bounds.
+     * @param setExtendedInfo whether to set the extended view info in the {@link ViewInfo} object.
+     */
+    private ViewInfo visit(View view, int offset, boolean setExtendedInfo) {
+        if (view == null) {
+            return null;
+        }
+
+        ViewInfo result = new ViewInfo(view.getClass().getName(),
+                getContext().getViewKey(view),
+                view.getLeft(), view.getTop() + offset, view.getRight(), view.getBottom() + offset,
+                view, view.getLayoutParams());
+
+        if (setExtendedInfo) {
+            MarginLayoutParams marginParams = null;
+            LayoutParams params = view.getLayoutParams();
+            if (params instanceof MarginLayoutParams) {
+                marginParams = (MarginLayoutParams) params;
+            }
+            result.setExtendedInfo(view.getBaseline(),
+                    marginParams != null ? marginParams.leftMargin : 0,
+                    marginParams != null ? marginParams.topMargin : 0,
+                    marginParams != null ? marginParams.rightMargin : 0,
+                    marginParams != null ? marginParams.bottomMargin : 0);
+        }
+
+        if (view instanceof ViewGroup) {
+            ViewGroup group = ((ViewGroup) view);
+            result.setChildren(visitAllChildren(group, 0 /*offset*/, setExtendedInfo));
+        }
+
+        return result;
+    }
+
+    /**
+     * Visits all the children of a given ViewGroup generate a list of {@link ViewInfo}
+     * containing the bounds of all the views.
+     * @param view the root View
+     * @param offset an offset for the view bounds.
+     * @param setExtendedInfo whether to set the extended view info in the {@link ViewInfo} object.
+     */
+    private List<ViewInfo> visitAllChildren(ViewGroup viewGroup, int offset,
+            boolean setExtendedInfo) {
+        if (viewGroup == null) {
+            return null;
+        }
+
+        List<ViewInfo> children = new ArrayList<ViewInfo>();
+        for (int i = 0; i < viewGroup.getChildCount(); i++) {
+            children.add(visit(viewGroup.getChildAt(i), offset, setExtendedInfo));
+        }
+        return children;
+    }
+
+
+    private void invalidateRenderingSize() {
+        mMeasuredScreenWidth = mMeasuredScreenHeight = -1;
+    }
+
+    public BufferedImage getImage() {
+        return mImage;
+    }
+
+    public boolean isAlphaChannelImage() {
+        return mIsAlphaChannelImage;
+    }
+
+    public List<ViewInfo> getViewInfos() {
+        return mViewInfoList;
+    }
+
+    public Map<String, String> getDefaultProperties(Object viewObject) {
+        return getContext().getDefaultPropMap(viewObject);
+    }
+
+    public void setScene(RenderSession session) {
+        mScene = session;
+    }
+
+    public RenderSession getSession() {
+        return mScene;
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/ResourceHelper.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/ResourceHelper.java
new file mode 100644
index 0000000..e5efa4e
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/ResourceHelper.java
@@ -0,0 +1,475 @@
+/*
+ * 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.layoutlib.bridge.impl;
+
+import com.android.ide.common.rendering.api.DensityBasedResourceValue;
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.ide.common.rendering.api.RenderResources;
+import com.android.ide.common.rendering.api.ResourceValue;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.android.BridgeContext;
+import com.android.layoutlib.bridge.android.BridgeXmlBlockParser;
+import com.android.ninepatch.NinePatch;
+import com.android.ninepatch.NinePatchChunk;
+import com.android.resources.Density;
+
+import org.kxml2.io.KXmlParser;
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+
+import android.content.res.ColorStateList;
+import android.graphics.Bitmap;
+import android.graphics.Bitmap_Delegate;
+import android.graphics.NinePatch_Delegate;
+import android.graphics.Rect;
+import android.graphics.drawable.BitmapDrawable;
+import android.graphics.drawable.ColorDrawable;
+import android.graphics.drawable.Drawable;
+import android.graphics.drawable.NinePatchDrawable;
+import android.util.TypedValue;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Helper class to provide various conversion method used in handling android resources.
+ */
+public final class ResourceHelper {
+
+    private final static Pattern sFloatPattern = Pattern.compile("(-?[0-9]+(?:\\.[0-9]+)?)(.*)");
+    private final static float[] sFloatOut = new float[1];
+
+    private final static TypedValue mValue = new TypedValue();
+
+    /**
+     * Returns the color value represented by the given string value
+     * @param value the color value
+     * @return the color as an int
+     * @throw NumberFormatException if the conversion failed.
+     */
+    public static int getColor(String value) {
+        if (value != null) {
+            if (value.startsWith("#") == false) {
+                throw new NumberFormatException(
+                        String.format("Color value '%s' must start with #", value));
+            }
+
+            value = value.substring(1);
+
+            // make sure it's not longer than 32bit
+            if (value.length() > 8) {
+                throw new NumberFormatException(String.format(
+                        "Color value '%s' is too long. Format is either" +
+                        "#AARRGGBB, #RRGGBB, #RGB, or #ARGB",
+                        value));
+            }
+
+            if (value.length() == 3) { // RGB format
+                char[] color = new char[8];
+                color[0] = color[1] = 'F';
+                color[2] = color[3] = value.charAt(0);
+                color[4] = color[5] = value.charAt(1);
+                color[6] = color[7] = value.charAt(2);
+                value = new String(color);
+            } else if (value.length() == 4) { // ARGB format
+                char[] color = new char[8];
+                color[0] = color[1] = value.charAt(0);
+                color[2] = color[3] = value.charAt(1);
+                color[4] = color[5] = value.charAt(2);
+                color[6] = color[7] = value.charAt(3);
+                value = new String(color);
+            } else if (value.length() == 6) {
+                value = "FF" + value;
+            }
+
+            // this is a RRGGBB or AARRGGBB value
+
+            // Integer.parseInt will fail to parse strings like "ff191919", so we use
+            // a Long, but cast the result back into an int, since we know that we're only
+            // dealing with 32 bit values.
+            return (int)Long.parseLong(value, 16);
+        }
+
+        throw new NumberFormatException();
+    }
+
+    public static ColorStateList getColorStateList(ResourceValue resValue, BridgeContext context) {
+        String value = resValue.getValue();
+        if (value != null && RenderResources.REFERENCE_NULL.equals(value) == false) {
+            // first check if the value is a file (xml most likely)
+            File f = new File(value);
+            if (f.isFile()) {
+                try {
+                    // let the framework inflate the ColorStateList from the XML file, by
+                    // providing an XmlPullParser
+                    KXmlParser parser = new KXmlParser();
+                    parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
+                    parser.setInput(new FileInputStream(f), "UTF-8"); //$NON-NLS-1$);
+
+                    BridgeXmlBlockParser blockParser = new BridgeXmlBlockParser(
+                            parser, context, resValue.isFramework());
+                    try {
+                        return ColorStateList.createFromXml(context.getResources(), blockParser);
+                    } finally {
+                        blockParser.ensurePopped();
+                    }
+                } catch (XmlPullParserException e) {
+                    Bridge.getLog().error(LayoutLog.TAG_BROKEN,
+                            "Failed to configure parser for " + value, e, null /*data*/);
+                    // we'll return null below.
+                } catch (Exception e) {
+                    // this is an error and not warning since the file existence is
+                    // checked before attempting to parse it.
+                    Bridge.getLog().error(LayoutLog.TAG_RESOURCES_READ,
+                            "Failed to parse file " + value, e, null /*data*/);
+
+                    return null;
+                }
+            } else {
+                // try to load the color state list from an int
+                try {
+                    int color = ResourceHelper.getColor(value);
+                    return ColorStateList.valueOf(color);
+                } catch (NumberFormatException e) {
+                    Bridge.getLog().error(LayoutLog.TAG_RESOURCES_FORMAT,
+                            "Failed to convert " + value + " into a ColorStateList", e,
+                            null /*data*/);
+                    return null;
+                }
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * Returns a drawable from the given value.
+     * @param value The value that contains a path to a 9 patch, a bitmap or a xml based drawable,
+     * or an hexadecimal color
+     * @param context the current context
+     */
+    public static Drawable getDrawable(ResourceValue value, BridgeContext context) {
+        String stringValue = value.getValue();
+        if (RenderResources.REFERENCE_NULL.equals(stringValue)) {
+            return null;
+        }
+
+        String lowerCaseValue = stringValue.toLowerCase();
+
+        Density density = Density.MEDIUM;
+        if (value instanceof DensityBasedResourceValue) {
+            density =
+                ((DensityBasedResourceValue)value).getResourceDensity();
+        }
+
+
+        if (lowerCaseValue.endsWith(NinePatch.EXTENSION_9PATCH)) {
+            File file = new File(stringValue);
+            if (file.isFile()) {
+                try {
+                    return getNinePatchDrawable(
+                            new FileInputStream(file), density, value.isFramework(),
+                            stringValue, context);
+                } catch (IOException e) {
+                    // failed to read the file, we'll return null below.
+                    Bridge.getLog().error(LayoutLog.TAG_RESOURCES_READ,
+                            "Failed lot load " + file.getAbsolutePath(), e, null /*data*/);
+                }
+            }
+
+            return null;
+        } else if (lowerCaseValue.endsWith(".xml")) {
+            // create a block parser for the file
+            File f = new File(stringValue);
+            if (f.isFile()) {
+                try {
+                    // let the framework inflate the Drawable from the XML file.
+                    KXmlParser parser = new KXmlParser();
+                    parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
+                    parser.setInput(new FileInputStream(f), "UTF-8"); //$NON-NLS-1$);
+
+                    BridgeXmlBlockParser blockParser = new BridgeXmlBlockParser(
+                            parser, context, value.isFramework());
+                    try {
+                        return Drawable.createFromXml(context.getResources(), blockParser);
+                    } finally {
+                        blockParser.ensurePopped();
+                    }
+                } catch (Exception e) {
+                    // this is an error and not warning since the file existence is checked before
+                    // attempting to parse it.
+                    Bridge.getLog().error(null, "Failed to parse file " + stringValue,
+                            e, null /*data*/);
+                }
+            } else {
+                Bridge.getLog().error(LayoutLog.TAG_BROKEN,
+                        String.format("File %s does not exist (or is not a file)", stringValue),
+                        null /*data*/);
+            }
+
+            return null;
+        } else {
+            File bmpFile = new File(stringValue);
+            if (bmpFile.isFile()) {
+                try {
+                    Bitmap bitmap = Bridge.getCachedBitmap(stringValue,
+                            value.isFramework() ? null : context.getProjectKey());
+
+                    if (bitmap == null) {
+                        bitmap = Bitmap_Delegate.createBitmap(bmpFile, false /*isMutable*/,
+                                density);
+                        Bridge.setCachedBitmap(stringValue, bitmap,
+                                value.isFramework() ? null : context.getProjectKey());
+                    }
+
+                    return new BitmapDrawable(context.getResources(), bitmap);
+                } catch (IOException e) {
+                    // we'll return null below
+                    Bridge.getLog().error(LayoutLog.TAG_RESOURCES_READ,
+                            "Failed lot load " + bmpFile.getAbsolutePath(), e, null /*data*/);
+                }
+            } else {
+                // attempt to get a color from the value
+                try {
+                    int color = getColor(stringValue);
+                    return new ColorDrawable(color);
+                } catch (NumberFormatException e) {
+                    // we'll return null below.
+                    Bridge.getLog().error(LayoutLog.TAG_RESOURCES_FORMAT,
+                            "Failed to convert " + stringValue + " into a drawable", e,
+                            null /*data*/);
+                }
+            }
+        }
+
+        return null;
+    }
+
+    private static Drawable getNinePatchDrawable(InputStream inputStream, Density density,
+            boolean isFramework, String cacheKey, BridgeContext context) throws IOException {
+        // see if we still have both the chunk and the bitmap in the caches
+        NinePatchChunk chunk = Bridge.getCached9Patch(cacheKey,
+                isFramework ? null : context.getProjectKey());
+        Bitmap bitmap = Bridge.getCachedBitmap(cacheKey,
+                isFramework ? null : context.getProjectKey());
+
+        // if either chunk or bitmap is null, then we reload the 9-patch file.
+        if (chunk == null || bitmap == null) {
+            try {
+                NinePatch ninePatch = NinePatch.load(inputStream, true /*is9Patch*/,
+                        false /* convert */);
+                if (ninePatch != null) {
+                    if (chunk == null) {
+                        chunk = ninePatch.getChunk();
+
+                        Bridge.setCached9Patch(cacheKey, chunk,
+                                isFramework ? null : context.getProjectKey());
+                    }
+
+                    if (bitmap == null) {
+                        bitmap = Bitmap_Delegate.createBitmap(ninePatch.getImage(),
+                                false /*isMutable*/,
+                                density);
+
+                        Bridge.setCachedBitmap(cacheKey, bitmap,
+                                isFramework ? null : context.getProjectKey());
+                    }
+                }
+            } catch (MalformedURLException e) {
+                // URL is wrong, we'll return null below
+            }
+        }
+
+        if (chunk != null && bitmap != null) {
+            int[] padding = chunk.getPadding();
+            Rect paddingRect = new Rect(padding[0], padding[1], padding[2], padding[3]);
+
+            return new NinePatchDrawable(context.getResources(), bitmap,
+                    NinePatch_Delegate.serialize(chunk),
+                    paddingRect, null);
+        }
+
+        return null;
+    }
+
+    // ------- TypedValue stuff
+    // This is taken from //device/libs/utils/ResourceTypes.cpp
+
+    private static final class UnitEntry {
+        String name;
+        int type;
+        int unit;
+        float scale;
+
+        UnitEntry(String name, int type, int unit, float scale) {
+            this.name = name;
+            this.type = type;
+            this.unit = unit;
+            this.scale = scale;
+        }
+    }
+
+    private final static UnitEntry[] sUnitNames = new UnitEntry[] {
+        new UnitEntry("px", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_PX, 1.0f),
+        new UnitEntry("dip", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_DIP, 1.0f),
+        new UnitEntry("dp", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_DIP, 1.0f),
+        new UnitEntry("sp", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_SP, 1.0f),
+        new UnitEntry("pt", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_PT, 1.0f),
+        new UnitEntry("in", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_IN, 1.0f),
+        new UnitEntry("mm", TypedValue.TYPE_DIMENSION, TypedValue.COMPLEX_UNIT_MM, 1.0f),
+        new UnitEntry("%", TypedValue.TYPE_FRACTION, TypedValue.COMPLEX_UNIT_FRACTION, 1.0f/100),
+        new UnitEntry("%p", TypedValue.TYPE_FRACTION, TypedValue.COMPLEX_UNIT_FRACTION_PARENT, 1.0f/100),
+    };
+
+    /**
+     * Returns the raw value from the given string.
+     * This object is only valid until the next call on to {@link ResourceHelper}.
+     */
+    public static TypedValue getValue(String s) {
+        if (stringToFloat(s, mValue)) {
+            return mValue;
+        }
+
+        return null;
+    }
+
+    /**
+     * Convert the string into a {@link TypedValue}.
+     * @param s
+     * @param outValue
+     * @return true if success.
+     */
+    public static boolean stringToFloat(String s, TypedValue outValue) {
+        // remove the space before and after
+        s = s.trim();
+        int len = s.length();
+
+        if (len <= 0) {
+            return false;
+        }
+
+        // check that there's no non ascii characters.
+        char[] buf = s.toCharArray();
+        for (int i = 0 ; i < len ; i++) {
+            if (buf[i] > 255) {
+                return false;
+            }
+        }
+
+        // check the first character
+        if (buf[0] < '0' && buf[0] > '9' && buf[0] != '.' && buf[0] != '-') {
+            return false;
+        }
+
+        // now look for the string that is after the float...
+        Matcher m = sFloatPattern.matcher(s);
+        if (m.matches()) {
+            String f_str = m.group(1);
+            String end = m.group(2);
+
+            float f;
+            try {
+                f = Float.parseFloat(f_str);
+            } catch (NumberFormatException e) {
+                // this shouldn't happen with the regexp above.
+                return false;
+            }
+
+            if (end.length() > 0 && end.charAt(0) != ' ') {
+                // Might be a unit...
+                if (parseUnit(end, outValue, sFloatOut)) {
+
+                    f *= sFloatOut[0];
+                    boolean neg = f < 0;
+                    if (neg) {
+                        f = -f;
+                    }
+                    long bits = (long)(f*(1<<23)+.5f);
+                    int radix;
+                    int shift;
+                    if ((bits&0x7fffff) == 0) {
+                        // Always use 23p0 if there is no fraction, just to make
+                        // things easier to read.
+                        radix = TypedValue.COMPLEX_RADIX_23p0;
+                        shift = 23;
+                    } else if ((bits&0xffffffffff800000L) == 0) {
+                        // Magnitude is zero -- can fit in 0 bits of precision.
+                        radix = TypedValue.COMPLEX_RADIX_0p23;
+                        shift = 0;
+                    } else if ((bits&0xffffffff80000000L) == 0) {
+                        // Magnitude can fit in 8 bits of precision.
+                        radix = TypedValue.COMPLEX_RADIX_8p15;
+                        shift = 8;
+                    } else if ((bits&0xffffff8000000000L) == 0) {
+                        // Magnitude can fit in 16 bits of precision.
+                        radix = TypedValue.COMPLEX_RADIX_16p7;
+                        shift = 16;
+                    } else {
+                        // Magnitude needs entire range, so no fractional part.
+                        radix = TypedValue.COMPLEX_RADIX_23p0;
+                        shift = 23;
+                    }
+                    int mantissa = (int)(
+                        (bits>>shift) & TypedValue.COMPLEX_MANTISSA_MASK);
+                    if (neg) {
+                        mantissa = (-mantissa) & TypedValue.COMPLEX_MANTISSA_MASK;
+                    }
+                    outValue.data |=
+                        (radix<<TypedValue.COMPLEX_RADIX_SHIFT)
+                        | (mantissa<<TypedValue.COMPLEX_MANTISSA_SHIFT);
+                    return true;
+                }
+                return false;
+            }
+
+            // make sure it's only spaces at the end.
+            end = end.trim();
+
+            if (end.length() == 0) {
+                if (outValue != null) {
+                    outValue.type = TypedValue.TYPE_FLOAT;
+                    outValue.data = Float.floatToIntBits(f);
+                    return true;
+                }
+            }
+        }
+
+        return false;
+    }
+
+    private static boolean parseUnit(String str, TypedValue outValue, float[] outScale) {
+        str = str.trim();
+
+        for (UnitEntry unit : sUnitNames) {
+            if (unit.name.equals(str)) {
+                outValue.type = unit.type;
+                outValue.data = unit.unit << TypedValue.COMPLEX_UNIT_SHIFT;
+                outScale[0] = unit.scale;
+
+                return true;
+            }
+        }
+
+        return false;
+    }
+}
+
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/Stack.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/Stack.java
new file mode 100644
index 0000000..9bd0015
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/Stack.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.layoutlib.bridge.impl;
+
+import java.util.ArrayList;
+
+/**
+ * Custom Stack implementation on top of an {@link ArrayList} instead of
+ * using {@link java.util.Stack} which is on top of a vector.
+ *
+ * @param <T>
+ */
+public class Stack<T> extends ArrayList<T> {
+
+    private static final long serialVersionUID = 1L;
+
+    public Stack() {
+        super();
+    }
+
+    public Stack(int size) {
+        super(size);
+    }
+
+    /**
+     * Pushes the given object to the stack
+     * @param object the object to push
+     */
+    public void push(T object) {
+        add(object);
+    }
+
+    /**
+     * Remove the object at the top of the stack and returns it.
+     * @return the removed object or null if the stack was empty.
+     */
+    public T pop() {
+        if (size() > 0) {
+            return remove(size() - 1);
+        }
+
+        return null;
+    }
+
+    /**
+     * Returns the object at the top of the stack.
+     * @return the object at the top or null if the stack is empty.
+     */
+    public T peek() {
+        if (size() > 0) {
+            return get(size() - 1);
+        }
+
+        return null;
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/binding/BaseAdapter.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/binding/BaseAdapter.java
new file mode 100644
index 0000000..e0414fe
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/binding/BaseAdapter.java
@@ -0,0 +1,247 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.layoutlib.bridge.impl.binding;
+
+import com.android.ide.common.rendering.api.AdapterBinding;
+import com.android.ide.common.rendering.api.DataBindingItem;
+import com.android.ide.common.rendering.api.IProjectCallback;
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.ide.common.rendering.api.ResourceReference;
+import com.android.ide.common.rendering.api.IProjectCallback.ViewAttribute;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.android.BridgeContext;
+import com.android.layoutlib.bridge.impl.RenderAction;
+import com.android.util.Pair;
+
+import android.database.DataSetObserver;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.Checkable;
+import android.widget.ImageView;
+import android.widget.TextView;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Base adapter to do fake data binding in {@link AdapterView} objects.
+ */
+public class BaseAdapter {
+
+    /**
+     * This is the items provided by the adapter. They are dynamically generated.
+     */
+    protected final static class AdapterItem {
+        private final DataBindingItem mItem;
+        private final int mType;
+        private final int mFullPosition;
+        private final int mPositionPerType;
+        private List<AdapterItem> mChildren;
+
+        protected AdapterItem(DataBindingItem item, int type, int fullPosition,
+                int positionPerType) {
+            mItem = item;
+            mType = type;
+            mFullPosition = fullPosition;
+            mPositionPerType = positionPerType;
+        }
+
+        void addChild(AdapterItem child) {
+            if (mChildren == null) {
+                mChildren = new ArrayList<AdapterItem>();
+            }
+
+            mChildren.add(child);
+        }
+
+        List<AdapterItem> getChildren() {
+            if (mChildren != null) {
+                return mChildren;
+            }
+
+            return Collections.emptyList();
+        }
+
+        int getType() {
+            return mType;
+        }
+
+        int getFullPosition() {
+            return mFullPosition;
+        }
+
+        int getPositionPerType() {
+            return mPositionPerType;
+        }
+
+        DataBindingItem getDataBindingItem() {
+            return mItem;
+        }
+    }
+
+    private final AdapterBinding mBinding;
+    private final IProjectCallback mCallback;
+    private final ResourceReference mAdapterRef;
+    private boolean mSkipCallbackParser = false;
+
+    protected final List<AdapterItem> mItems = new ArrayList<AdapterItem>();
+
+    protected BaseAdapter(ResourceReference adapterRef, AdapterBinding binding,
+            IProjectCallback callback) {
+        mAdapterRef = adapterRef;
+        mBinding = binding;
+        mCallback = callback;
+    }
+
+    // ------- Some Adapter method used by all children classes.
+
+    public boolean areAllItemsEnabled() {
+        return true;
+    }
+
+    public boolean hasStableIds() {
+        return true;
+    }
+
+    public boolean isEmpty() {
+        return mItems.size() == 0;
+    }
+
+    public void registerDataSetObserver(DataSetObserver observer) {
+        // pass
+    }
+
+    public void unregisterDataSetObserver(DataSetObserver observer) {
+        // pass
+    }
+
+    // -------
+
+
+    protected AdapterBinding getBinding() {
+        return mBinding;
+    }
+
+    protected View getView(AdapterItem item, AdapterItem parentItem, View convertView,
+            ViewGroup parent) {
+        // we don't care about recycling here because we never scroll.
+        DataBindingItem dataBindingItem = item.getDataBindingItem();
+
+        BridgeContext context = RenderAction.getCurrentContext();
+
+        Pair<View, Boolean> pair = context.inflateView(dataBindingItem.getViewReference(),
+                parent, false /*attachToRoot*/, mSkipCallbackParser);
+
+        View view = pair.getFirst();
+        mSkipCallbackParser |= pair.getSecond();
+
+        if (view != null) {
+            fillView(context, view, item, parentItem);
+        } else {
+            // create a text view to display an error.
+            TextView tv = new TextView(context);
+            tv.setText("Unable to find layout: " + dataBindingItem.getViewReference().getName());
+            view = tv;
+        }
+
+        return view;
+    }
+
+    private void fillView(BridgeContext context, View view, AdapterItem item,
+            AdapterItem parentItem) {
+        if (view instanceof ViewGroup) {
+            ViewGroup group = (ViewGroup) view;
+            final int count = group.getChildCount();
+            for (int i = 0 ; i < count ; i++) {
+                fillView(context, group.getChildAt(i), item, parentItem);
+            }
+        } else {
+            int id = view.getId();
+            if (id != 0) {
+                ResourceReference resolvedRef = context.resolveId(id);
+                if (resolvedRef != null) {
+                    int fullPosition = item.getFullPosition();
+                    int positionPerType = item.getPositionPerType();
+                    int fullParentPosition = parentItem != null ? parentItem.getFullPosition() : 0;
+                    int parentPositionPerType = parentItem != null ?
+                            parentItem.getPositionPerType() : 0;
+
+                    if (view instanceof TextView) {
+                        TextView tv = (TextView) view;
+                        Object value = mCallback.getAdapterItemValue(
+                                mAdapterRef, context.getViewKey(view),
+                                item.getDataBindingItem().getViewReference(),
+                                fullPosition, positionPerType,
+                                fullParentPosition, parentPositionPerType,
+                                resolvedRef, ViewAttribute.TEXT, tv.getText().toString());
+                        if (value != null) {
+                            if (value.getClass() != ViewAttribute.TEXT.getAttributeClass()) {
+                                Bridge.getLog().error(LayoutLog.TAG_BROKEN, String.format(
+                                        "Wrong Adapter Item value class for TEXT. Expected String, got %s",
+                                        value.getClass().getName()), null);
+                            } else {
+                                tv.setText((String) value);
+                            }
+                        }
+                    }
+
+                    if (view instanceof Checkable) {
+                        Checkable cb = (Checkable) view;
+
+                        Object value = mCallback.getAdapterItemValue(
+                                mAdapterRef, context.getViewKey(view),
+                                item.getDataBindingItem().getViewReference(),
+                                fullPosition, positionPerType,
+                                fullParentPosition, parentPositionPerType,
+                                resolvedRef, ViewAttribute.IS_CHECKED, cb.isChecked());
+                        if (value != null) {
+                            if (value.getClass() != ViewAttribute.IS_CHECKED.getAttributeClass()) {
+                                Bridge.getLog().error(LayoutLog.TAG_BROKEN, String.format(
+                                        "Wrong Adapter Item value class for TEXT. Expected Boolean, got %s",
+                                        value.getClass().getName()), null);
+                            } else {
+                                cb.setChecked((Boolean) value);
+                            }
+                        }
+                    }
+
+                    if (view instanceof ImageView) {
+                        ImageView iv = (ImageView) view;
+
+                        Object value = mCallback.getAdapterItemValue(
+                                mAdapterRef, context.getViewKey(view),
+                                item.getDataBindingItem().getViewReference(),
+                                fullPosition, positionPerType,
+                                fullParentPosition, parentPositionPerType,
+                                resolvedRef, ViewAttribute.SRC, iv.getDrawable());
+                        if (value != null) {
+                            if (value.getClass() != ViewAttribute.SRC.getAttributeClass()) {
+                                Bridge.getLog().error(LayoutLog.TAG_BROKEN, String.format(
+                                        "Wrong Adapter Item value class for TEXT. Expected Boolean, got %s",
+                                        value.getClass().getName()), null);
+                            } else {
+                                // FIXME
+                            }
+                        }
+                    }
+                }
+            }
+        }
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/binding/FakeAdapter.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/binding/FakeAdapter.java
new file mode 100644
index 0000000..c9bb424
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/binding/FakeAdapter.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.layoutlib.bridge.impl.binding;
+
+import com.android.ide.common.rendering.api.AdapterBinding;
+import com.android.ide.common.rendering.api.DataBindingItem;
+import com.android.ide.common.rendering.api.IProjectCallback;
+import com.android.ide.common.rendering.api.ResourceReference;
+
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ListAdapter;
+import android.widget.SpinnerAdapter;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Fake adapter to do fake data binding in {@link AdapterView} objects for {@link ListAdapter}
+ * and {@link SpinnerAdapter}.
+ *
+ */
+public class FakeAdapter extends BaseAdapter implements ListAdapter, SpinnerAdapter {
+
+    // don't use a set because the order is important.
+    private final List<ResourceReference> mTypes = new ArrayList<ResourceReference>();
+
+    public FakeAdapter(ResourceReference adapterRef, AdapterBinding binding,
+            IProjectCallback callback) {
+        super(adapterRef, binding, callback);
+
+        final int repeatCount = getBinding().getRepeatCount();
+        final int itemCount = getBinding().getItemCount();
+
+        // Need an array to count for each type.
+        // This is likely too big, but is the max it can be.
+        int[] typeCount = new int[itemCount];
+
+        // We put several repeating sets.
+        for (int r = 0 ; r < repeatCount ; r++) {
+            // loop on the type of list items, and add however many for each type.
+            for (DataBindingItem dataBindingItem : getBinding()) {
+                ResourceReference viewRef = dataBindingItem.getViewReference();
+                int typeIndex = mTypes.indexOf(viewRef);
+                if (typeIndex == -1) {
+                    typeIndex = mTypes.size();
+                    mTypes.add(viewRef);
+                }
+
+                int count = dataBindingItem.getCount();
+
+                int index = typeCount[typeIndex];
+                typeCount[typeIndex] += count;
+
+                for (int k = 0 ; k < count ; k++) {
+                    mItems.add(new AdapterItem(dataBindingItem, typeIndex, mItems.size(), index++));
+                }
+            }
+        }
+    }
+
+    public boolean isEnabled(int position) {
+        return true;
+    }
+
+    public int getCount() {
+        return mItems.size();
+    }
+
+    public Object getItem(int position) {
+        return mItems.get(position);
+    }
+
+    public long getItemId(int position) {
+        return position;
+    }
+
+    public int getItemViewType(int position) {
+        return mItems.get(position).getType();
+    }
+
+    public View getView(int position, View convertView, ViewGroup parent) {
+        // we don't care about recycling here because we never scroll.
+        AdapterItem item = mItems.get(position);
+        return getView(item, null /*parentGroup*/, convertView, parent);
+    }
+
+    public int getViewTypeCount() {
+        return mTypes.size();
+    }
+
+    // ---- SpinnerAdapter
+
+    public View getDropDownView(int position, View convertView, ViewGroup parent) {
+        // pass
+        return null;
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/binding/FakeExpandableAdapter.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/binding/FakeExpandableAdapter.java
new file mode 100644
index 0000000..2c492e3
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/binding/FakeExpandableAdapter.java
@@ -0,0 +1,179 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.layoutlib.bridge.impl.binding;
+
+import com.android.ide.common.rendering.api.AdapterBinding;
+import com.android.ide.common.rendering.api.DataBindingItem;
+import com.android.ide.common.rendering.api.IProjectCallback;
+import com.android.ide.common.rendering.api.ResourceReference;
+
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ExpandableListAdapter;
+import android.widget.HeterogeneousExpandableList;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class FakeExpandableAdapter extends BaseAdapter implements ExpandableListAdapter,
+        HeterogeneousExpandableList {
+
+    // don't use a set because the order is important.
+    private final List<ResourceReference> mGroupTypes = new ArrayList<ResourceReference>();
+    private final List<ResourceReference> mChildrenTypes = new ArrayList<ResourceReference>();
+
+    public FakeExpandableAdapter(ResourceReference adapterRef, AdapterBinding binding,
+            IProjectCallback callback) {
+        super(adapterRef, binding, callback);
+
+        createItems(binding, binding.getItemCount(), binding.getRepeatCount(), mGroupTypes, 1);
+    }
+
+    private void createItems(Iterable<DataBindingItem> iterable, final int itemCount,
+            final int repeatCount, List<ResourceReference> types, int depth) {
+        // Need an array to count for each type.
+        // This is likely too big, but is the max it can be.
+        int[] typeCount = new int[itemCount];
+
+        // we put several repeating sets.
+        for (int r = 0 ; r < repeatCount ; r++) {
+            // loop on the type of list items, and add however many for each type.
+            for (DataBindingItem dataBindingItem : iterable) {
+                ResourceReference viewRef = dataBindingItem.getViewReference();
+                int typeIndex = types.indexOf(viewRef);
+                if (typeIndex == -1) {
+                    typeIndex = types.size();
+                    types.add(viewRef);
+                }
+
+                List<DataBindingItem> children = dataBindingItem.getChildren();
+                int count = dataBindingItem.getCount();
+
+                // if there are children, we use the count as a repeat count for the children.
+                if (children.size() > 0) {
+                    count = 1;
+                }
+
+                int index = typeCount[typeIndex];
+                typeCount[typeIndex] += count;
+
+                for (int k = 0 ; k < count ; k++) {
+                    AdapterItem item = new AdapterItem(dataBindingItem, typeIndex, mItems.size(),
+                            index++);
+                    mItems.add(item);
+
+                    if (children.size() > 0) {
+                        createItems(dataBindingItem, depth + 1);
+                    }
+                }
+            }
+        }
+    }
+
+    private void createItems(DataBindingItem item, int depth) {
+        if (depth == 2) {
+            createItems(item, item.getChildren().size(), item.getCount(), mChildrenTypes, depth);
+        }
+    }
+
+    private AdapterItem getChildItem(int groupPosition, int childPosition) {
+        AdapterItem item = mItems.get(groupPosition);
+
+        List<AdapterItem> children = item.getChildren();
+        return children.get(childPosition);
+    }
+
+    // ---- ExpandableListAdapter
+
+    public int getGroupCount() {
+        return mItems.size();
+    }
+
+    public int getChildrenCount(int groupPosition) {
+        AdapterItem item = mItems.get(groupPosition);
+        return item.getChildren().size();
+    }
+
+    public Object getGroup(int groupPosition) {
+        return mItems.get(groupPosition);
+    }
+
+    public Object getChild(int groupPosition, int childPosition) {
+        return getChildItem(groupPosition, childPosition);
+    }
+
+    public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
+            ViewGroup parent) {
+        // we don't care about recycling here because we never scroll.
+        AdapterItem item = mItems.get(groupPosition);
+        return getView(item, null /*parentItem*/, convertView, parent);
+    }
+
+    public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
+            View convertView, ViewGroup parent) {
+        // we don't care about recycling here because we never scroll.
+        AdapterItem parentItem = mItems.get(groupPosition);
+        AdapterItem item = getChildItem(groupPosition, childPosition);
+        return getView(item, parentItem, convertView, parent);
+    }
+
+    public long getGroupId(int groupPosition) {
+        return groupPosition;
+    }
+
+    public long getChildId(int groupPosition, int childPosition) {
+        return childPosition;
+    }
+
+    public long getCombinedGroupId(long groupId) {
+        return groupId << 16 | 0x0000FFFF;
+    }
+
+    public long getCombinedChildId(long groupId, long childId) {
+        return groupId << 16 | childId;
+    }
+
+    public boolean isChildSelectable(int groupPosition, int childPosition) {
+        return true;
+    }
+
+    public void onGroupCollapsed(int groupPosition) {
+        // pass
+    }
+
+    public void onGroupExpanded(int groupPosition) {
+        // pass
+    }
+
+    // ---- HeterogeneousExpandableList
+
+    public int getChildType(int groupPosition, int childPosition) {
+        return getChildItem(groupPosition, childPosition).getType();
+    }
+
+    public int getChildTypeCount() {
+        return mChildrenTypes.size();
+    }
+
+    public int getGroupType(int groupPosition) {
+        return mItems.get(groupPosition).getType();
+    }
+
+    public int getGroupTypeCount() {
+        return mGroupTypes.size();
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/util/Debug.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/util/Debug.java
new file mode 100644
index 0000000..82eab85
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/util/Debug.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.layoutlib.bridge.util;
+
+public class Debug {
+
+    public final static boolean DEBUG = false;
+
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/util/SparseWeakArray.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/util/SparseWeakArray.java
new file mode 100644
index 0000000..4d0c9ce
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/util/SparseWeakArray.java
@@ -0,0 +1,376 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.layoutlib.bridge.util;
+
+
+import com.android.internal.util.ArrayUtils;
+
+import android.util.SparseArray;
+
+import java.lang.ref.WeakReference;
+
+/**
+ * This is a custom {@link SparseArray} that uses {@link WeakReference} around the objects added
+ * to it. When the array is compacted, not only deleted indices but also empty references
+ * are removed, making the array efficient at removing references that were reclaimed.
+ *
+ * The code is taken from {@link SparseArray} directly and adapted to use weak references.
+ *
+ * Because our usage means that we never actually call {@link #remove(int)} or {@link #delete(int)},
+ * we must manually check if there are reclaimed references to trigger an internal compact step
+ * (which is normally only triggered when an item is manually removed).
+ *
+ * SparseArrays map integers to Objects.  Unlike a normal array of Objects,
+ * there can be gaps in the indices.  It is intended to be more efficient
+ * than using a HashMap to map Integers to Objects.
+ */
+@SuppressWarnings("unchecked")
+public class SparseWeakArray<E> {
+
+    private static final Object DELETED_REF = new Object();
+    private static final WeakReference<?> DELETED = new WeakReference(DELETED_REF);
+    private boolean mGarbage = false;
+
+    /**
+     * Creates a new SparseArray containing no mappings.
+     */
+    public SparseWeakArray() {
+        this(10);
+    }
+
+    /**
+     * Creates a new SparseArray containing no mappings that will not
+     * require any additional memory allocation to store the specified
+     * number of mappings.
+     */
+    public SparseWeakArray(int initialCapacity) {
+        initialCapacity = ArrayUtils.idealIntArraySize(initialCapacity);
+
+        mKeys = new int[initialCapacity];
+        mValues = new WeakReference[initialCapacity];
+        mSize = 0;
+    }
+
+    /**
+     * Gets the Object mapped from the specified key, or <code>null</code>
+     * if no such mapping has been made.
+     */
+    public E get(int key) {
+        return get(key, null);
+    }
+
+    /**
+     * Gets the Object mapped from the specified key, or the specified Object
+     * if no such mapping has been made.
+     */
+    public E get(int key, E valueIfKeyNotFound) {
+        int i = binarySearch(mKeys, 0, mSize, key);
+
+        if (i < 0 || mValues[i] == DELETED || mValues[i].get() == null) {
+            return valueIfKeyNotFound;
+        } else {
+            return (E) mValues[i].get();
+        }
+    }
+
+    /**
+     * Removes the mapping from the specified key, if there was any.
+     */
+    public void delete(int key) {
+        int i = binarySearch(mKeys, 0, mSize, key);
+
+        if (i >= 0) {
+            if (mValues[i] != DELETED) {
+                mValues[i] = DELETED;
+                mGarbage = true;
+            }
+        }
+    }
+
+    /**
+     * Alias for {@link #delete(int)}.
+     */
+    public void remove(int key) {
+        delete(key);
+    }
+
+    /**
+     * Removes the mapping at the specified index.
+     */
+    public void removeAt(int index) {
+        if (mValues[index] != DELETED) {
+            mValues[index] = DELETED;
+            mGarbage = true;
+        }
+    }
+
+    private void gc() {
+        int n = mSize;
+        int o = 0;
+        int[] keys = mKeys;
+        WeakReference<?>[] values = mValues;
+
+        for (int i = 0; i < n; i++) {
+            WeakReference<?> val = values[i];
+
+            // Don't keep any non DELETED values, but only the one that still have a valid
+            // reference.
+            if (val != DELETED && val.get() != null) {
+                if (i != o) {
+                    keys[o] = keys[i];
+                    values[o] = val;
+                }
+
+                o++;
+            }
+        }
+
+        mGarbage = false;
+        mSize = o;
+
+        int newSize = ArrayUtils.idealIntArraySize(mSize);
+        if (newSize < mKeys.length) {
+            int[] nkeys = new int[newSize];
+            WeakReference<?>[] nvalues = new WeakReference[newSize];
+
+            System.arraycopy(mKeys, 0, nkeys, 0, newSize);
+            System.arraycopy(mValues, 0, nvalues, 0, newSize);
+
+            mKeys = nkeys;
+            mValues = nvalues;
+        }
+    }
+
+    /**
+     * Adds a mapping from the specified key to the specified value,
+     * replacing the previous mapping from the specified key if there
+     * was one.
+     */
+    public void put(int key, E value) {
+        int i = binarySearch(mKeys, 0, mSize, key);
+
+        if (i >= 0) {
+            mValues[i] = new WeakReference(value);
+        } else {
+            i = ~i;
+
+            if (i < mSize && (mValues[i] == DELETED || mValues[i].get() == null)) {
+                mKeys[i] = key;
+                mValues[i] = new WeakReference(value);
+                return;
+            }
+
+            if (mSize >= mKeys.length && (mGarbage || hasReclaimedRefs())) {
+                gc();
+
+                // Search again because indices may have changed.
+                i = ~binarySearch(mKeys, 0, mSize, key);
+            }
+
+            if (mSize >= mKeys.length) {
+                int n = ArrayUtils.idealIntArraySize(mSize + 1);
+
+                int[] nkeys = new int[n];
+                WeakReference<?>[] nvalues = new WeakReference[n];
+
+                // Log.e("SparseArray", "grow " + mKeys.length + " to " + n);
+                System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
+                System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
+
+                mKeys = nkeys;
+                mValues = nvalues;
+            }
+
+            if (mSize - i != 0) {
+                // Log.e("SparseArray", "move " + (mSize - i));
+                System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i);
+                System.arraycopy(mValues, i, mValues, i + 1, mSize - i);
+            }
+
+            mKeys[i] = key;
+            mValues[i] = new WeakReference(value);
+            mSize++;
+        }
+    }
+
+    /**
+     * Returns the number of key-value mappings that this SparseArray
+     * currently stores.
+     */
+    public int size() {
+        if (mGarbage) {
+            gc();
+        }
+
+        return mSize;
+    }
+
+    /**
+     * Given an index in the range <code>0...size()-1</code>, returns
+     * the key from the <code>index</code>th key-value mapping that this
+     * SparseArray stores.
+     */
+    public int keyAt(int index) {
+        if (mGarbage) {
+            gc();
+        }
+
+        return mKeys[index];
+    }
+
+    /**
+     * Given an index in the range <code>0...size()-1</code>, returns
+     * the value from the <code>index</code>th key-value mapping that this
+     * SparseArray stores.
+     */
+    public E valueAt(int index) {
+        if (mGarbage) {
+            gc();
+        }
+
+        return (E) mValues[index].get();
+    }
+
+    /**
+     * Given an index in the range <code>0...size()-1</code>, sets a new
+     * value for the <code>index</code>th key-value mapping that this
+     * SparseArray stores.
+     */
+    public void setValueAt(int index, E value) {
+        if (mGarbage) {
+            gc();
+        }
+
+        mValues[index] = new WeakReference(value);
+    }
+
+    /**
+     * Returns the index for which {@link #keyAt} would return the
+     * specified key, or a negative number if the specified
+     * key is not mapped.
+     */
+    public int indexOfKey(int key) {
+        if (mGarbage) {
+            gc();
+        }
+
+        return binarySearch(mKeys, 0, mSize, key);
+    }
+
+    /**
+     * Returns an index for which {@link #valueAt} would return the
+     * specified key, or a negative number if no keys map to the
+     * specified value.
+     * Beware that this is a linear search, unlike lookups by key,
+     * and that multiple keys can map to the same value and this will
+     * find only one of them.
+     */
+    public int indexOfValue(E value) {
+        if (mGarbage) {
+            gc();
+        }
+
+        for (int i = 0; i < mSize; i++)
+            if (mValues[i].get() == value)
+                return i;
+
+        return -1;
+    }
+
+    /**
+     * Removes all key-value mappings from this SparseArray.
+     */
+    public void clear() {
+        int n = mSize;
+        WeakReference<?>[] values = mValues;
+
+        for (int i = 0; i < n; i++) {
+            values[i] = null;
+        }
+
+        mSize = 0;
+        mGarbage = false;
+    }
+
+    /**
+     * Puts a key/value pair into the array, optimizing for the case where
+     * the key is greater than all existing keys in the array.
+     */
+    public void append(int key, E value) {
+        if (mSize != 0 && key <= mKeys[mSize - 1]) {
+            put(key, value);
+            return;
+        }
+
+        if (mSize >= mKeys.length && (mGarbage || hasReclaimedRefs())) {
+            gc();
+        }
+
+        int pos = mSize;
+        if (pos >= mKeys.length) {
+            int n = ArrayUtils.idealIntArraySize(pos + 1);
+
+            int[] nkeys = new int[n];
+            WeakReference<?>[] nvalues = new WeakReference[n];
+
+            // Log.e("SparseArray", "grow " + mKeys.length + " to " + n);
+            System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
+            System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
+
+            mKeys = nkeys;
+            mValues = nvalues;
+        }
+
+        mKeys[pos] = key;
+        mValues[pos] = new WeakReference(value);
+        mSize = pos + 1;
+    }
+
+    private boolean hasReclaimedRefs() {
+        for (int i = 0 ; i < mSize ; i++) {
+            if (mValues[i].get() == null) { // DELETED.get() never returns null.
+                return true;
+            }
+        }
+
+        return false;
+    }
+
+    private static int binarySearch(int[] a, int start, int len, int key) {
+        int high = start + len, low = start - 1, guess;
+
+        while (high - low > 1) {
+            guess = (high + low) / 2;
+
+            if (a[guess] < key)
+                low = guess;
+            else
+                high = guess;
+        }
+
+        if (high == start + len)
+            return ~(start + len);
+        else if (a[high] == key)
+            return high;
+        else
+            return ~high;
+    }
+
+    private int[] mKeys;
+    private WeakReference<?>[] mValues;
+    private int mSize;
+}
diff --git a/tools/layoutlib/bridge/tests/.classpath b/tools/layoutlib/bridge/tests/.classpath
new file mode 100644
index 0000000..9cc2433d
--- /dev/null
+++ b/tools/layoutlib/bridge/tests/.classpath
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+	<classpathentry kind="src" path="src"/>
+	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+	<classpathentry combineaccessrules="false" kind="src" path="/layoutlib_bridge"/>
+	<classpathentry kind="var" path="ANDROID_PLAT_SRC/prebuilt/common/kxml2/kxml2-2.3.0.jar" sourcepath="/ANDROID_PLAT_SRC/dalvik/libcore/xml/src/main/java"/>
+	<classpathentry kind="var" path="ANDROID_PLAT_SRC/out/host/common/obj/JAVA_LIBRARIES/temp_layoutlib_intermediates/javalib.jar" sourcepath="/ANDROID_PLAT_SRC/frameworks/base"/>
+	<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/3"/>
+	<classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/tools/layoutlib/bridge/tests/.project b/tools/layoutlib/bridge/tests/.project
new file mode 100644
index 0000000..2325eed
--- /dev/null
+++ b/tools/layoutlib/bridge/tests/.project
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>layoutlib_bridge-tests</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>org.eclipse.jdt.core.javabuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>org.eclipse.jdt.core.javanature</nature>
+	</natures>
+</projectDescription>
diff --git a/tools/layoutlib/bridge/tests/Android.mk b/tools/layoutlib/bridge/tests/Android.mk
new file mode 100644
index 0000000..e303638
--- /dev/null
+++ b/tools/layoutlib/bridge/tests/Android.mk
@@ -0,0 +1,30 @@
+# Copyright (C) 2011 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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)
+
+# Only compile source java files in this lib.
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_MODULE := layoutlib-tests
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_JAVA_LIBRARIES := layoutlib kxml2-2.3.0 junit
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+# Build all sub-directories
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/NinePatchTest.java b/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/NinePatchTest.java
deleted file mode 100644
index 23351ab..0000000
--- a/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/NinePatchTest.java
+++ /dev/null
@@ -1,52 +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 com.android.layoutlib.bridge;
-
-import com.android.ninepatch.NinePatch;
-
-import java.net.URL;
-
-import junit.framework.TestCase;
-
-public class NinePatchTest extends TestCase {
-
-    private NinePatch mPatch;
-
-    @Override
-    protected void setUp() throws Exception {
-        URL url = this.getClass().getClassLoader().getResource(
-                "com/android/layoutlib/testdata/button.9.png");
-
-        mPatch = NinePatch.load(url, false /* convert */);
-    }
-
-    public void test9PatchLoad() throws Exception {
-        assertNotNull(mPatch);
-    }
-
-    public void test9PatchMinSize() {
-        int[] padding = new int[4];
-        mPatch.getPadding(padding);
-        assertEquals(13, padding[0]);
-        assertEquals(3, padding[1]);
-        assertEquals(13, padding[2]);
-        assertEquals(4, padding[3]);
-        assertEquals(36, mPatch.getWidth());
-        assertEquals(25, mPatch.getHeight());
-    }
-
-}
diff --git a/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/TestClassReplacement.java b/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/TestClassReplacement.java
deleted file mode 100644
index e0dc55f..0000000
--- a/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/TestClassReplacement.java
+++ /dev/null
@@ -1,139 +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 com.android.layoutlib.bridge;
-
-import java.lang.reflect.Method;
-
-import junit.framework.TestCase;
-
-public class TestClassReplacement extends TestCase {
-
-    public void testClassReplacements() {
-        // TODO: we want to test all the classes. For now only Paint passes the tests.
-//        final String[] classes = CreateInfo.RENAMED_CLASSES;
-        final String[] classes = new String[] {
-                "android.graphics.Paint",               "android.graphics._Original_Paint"
-        };
-        final int count = classes.length;
-        for (int i = 0 ; i < count ; i += 2) {
-            loadAndCompareClasses(classes[i], classes[i+1]);
-        }
-    }
-
-    private void loadAndCompareClasses(String newClassName, String oldClassName) {
-        // load the classes
-        try {
-            Class<?> newClass = TestClassReplacement.class.getClassLoader().loadClass(newClassName);
-            Class<?> oldClass = TestClassReplacement.class.getClassLoader().loadClass(oldClassName);
-
-            compare(newClass, oldClass);
-        } catch (ClassNotFoundException e) {
-            fail("Failed to load class: " + e.getMessage());
-        }
-    }
-
-    private void compare(Class<?> newClass, Class<?> oldClass) {
-        // first compare the methods.
-        Method[] newClassMethods = newClass.getDeclaredMethods();
-        Method[] oldClassMethods = oldClass.getDeclaredMethods();
-
-        for (Method oldMethod : oldClassMethods) {
-            // we ignore anything that starts with native
-            if (oldMethod.getName().startsWith("native")) {
-                continue;
-            }
-            boolean found = false;
-            for (Method newMethod : newClassMethods) {
-                if (compareMethods(newClass, newMethod, oldClass, oldMethod)) {
-                    found = true;
-                    break;
-                }
-            }
-
-            if (found == false) {
-                fail(String.format("Unable to find %1$s", oldMethod.toGenericString()));
-            }
-        }
-
-        // TODO: check (somehow?) that the methods that were removed from the original class
-        // have been put back in the new class!
-        // For this we need the original unmodified class (ie renamed, but w/o the methods removed)
-    }
-
-    private boolean compareMethods(Class<?> newClass, Method newMethod,
-            Class<?> oldClass, Method oldMethod) {
-        // first check the name of the method
-        if (newMethod.getName().equals(oldMethod.getName()) == false) {
-            return false;
-        }
-
-        // check the return value
-        Class<?> oldReturnType = oldMethod.getReturnType();
-        // if it's the old class, or if it's a inner class of the oldclass, we need to change this.
-        oldReturnType = adapt(oldReturnType, newClass, oldClass);
-
-        // compare the return types
-        Class<?> newReturnType = newMethod.getReturnType();
-        if (newReturnType.equals(oldReturnType) == false) {
-            return false;
-        }
-
-        // now check the parameters type.
-        Class<?>[] oldParameters = oldMethod.getParameterTypes();
-        Class<?>[] newParemeters = newMethod.getParameterTypes();
-        if (oldParameters.length != newParemeters.length) {
-            return false;
-        }
-
-        for (int i = 0 ; i < oldParameters.length ; i++) {
-            if (newParemeters[i].equals(adapt(oldParameters[i], newClass, oldClass)) == false) {
-                return false;
-            }
-        }
-
-        return true;
-    }
-
-    /**
-     * Adapts a class to deal with renamed classes.
-     * <p/>For instance if old class is <code>android.graphics._Original_Paint</code> and the
-     * new class is <code>android.graphics.Paint</code> and the class to adapt is
-     * <code>android.graphics._Original_Paint$Cap</code>, then the method will return a
-     * {@link Class} object representing <code>android.graphics.Paint$Cap</code>.
-     * <p/>
-     * This method will also ensure that all renamed classes contains all the proper inner classes
-     * that they should be declaring.
-     * @param theClass the class to adapt
-     * @param newClass the new class object
-     * @param oldClass the old class object
-     * @return the adapted class.
-     * @throws ClassNotFoundException
-     */
-    private Class<?> adapt(Class<?> theClass, Class<?> newClass, Class<?> oldClass) {
-        // only look for a new class if it's not primitive as Class.forName() would fail otherwise.
-        if (theClass.isPrimitive() == false) {
-            String n = theClass.getName().replace(oldClass.getName(), newClass.getName());
-            try {
-                return Class.forName(n);
-            } catch (ClassNotFoundException e) {
-                fail("Missing class: " + n);
-            }
-        }
-
-        return theClass;
-    }
-}
diff --git a/tools/layoutlib/bridge/tests/com/android/layoutlib/testdata/button.9.png b/tools/layoutlib/bridge/tests/com/android/layoutlib/testdata/button.9.png
deleted file mode 100644
index 9d52f40..0000000
--- a/tools/layoutlib/bridge/tests/com/android/layoutlib/testdata/button.9.png
+++ /dev/null
Binary files differ
diff --git a/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/AndroidGraphicsTests.java b/tools/layoutlib/bridge/tests/src/android/graphics/Matrix_DelegateTest.java
similarity index 70%
rename from tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/AndroidGraphicsTests.java
rename to tools/layoutlib/bridge/tests/src/android/graphics/Matrix_DelegateTest.java
index 6e14e82..ec4edac 100644
--- a/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/AndroidGraphicsTests.java
+++ b/tools/layoutlib/bridge/tests/src/android/graphics/Matrix_DelegateTest.java
@@ -14,19 +14,14 @@
  * limitations under the License.
  */
 
-package com.android.layoutlib.bridge;
-
-import android.graphics.Matrix;
-import android.graphics.Paint;
-import android.graphics._Original_Paint;
-import android.text.TextPaint;
+package android.graphics;
 
 import junit.framework.TestCase;
 
 /**
  *
  */
-public class AndroidGraphicsTests extends TestCase {
+public class Matrix_DelegateTest extends TestCase {
 
     @Override
     protected void setUp() throws Exception {
@@ -38,14 +33,17 @@
         super.tearDown();
     }
 
-    public void testMatrix() {
+    public void testIdentity() {
         Matrix m1 = new Matrix();
 
         assertTrue(m1.isIdentity());
 
         m1.setValues(new float[] { 1,0,0, 0,1,0, 0,0,1 });
         assertTrue(m1.isIdentity());
+    }
 
+    public void testCopyConstructor() {
+        Matrix m1 = new Matrix();
         Matrix m2 = new Matrix(m1);
 
         float[] v1 = new float[9];
@@ -57,17 +55,4 @@
             assertEquals(v1[i], v2[i]);
         }
     }
-
-    public void testPaint() {
-        _Original_Paint o = new _Original_Paint();
-        assertNotNull(o);
-
-        Paint p = new Paint();
-        assertNotNull(p);
-    }
-
-    public void textTextPaint() {
-        TextPaint p = new TextPaint();
-        assertNotNull(p);
-    }
 }
diff --git a/tools/layoutlib/bridge/tests/src/com/android/layoutlib/bridge/TestDelegates.java b/tools/layoutlib/bridge/tests/src/com/android/layoutlib/bridge/TestDelegates.java
new file mode 100644
index 0000000..d3218db
--- /dev/null
+++ b/tools/layoutlib/bridge/tests/src/com/android/layoutlib/bridge/TestDelegates.java
@@ -0,0 +1,197 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.layoutlib.bridge;
+
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+import com.android.tools.layoutlib.create.CreateInfo;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.List;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests that native delegate classes implement all the required methods.
+ *
+ * This looks at {@link CreateInfo#DELEGATE_CLASS_NATIVES} to get the list of classes that
+ * have their native methods reimplemented through a delegate.
+ *
+ * Since the reimplemented methods are not native anymore, we look for the annotation
+ * {@link LayoutlibDelegate}, and look for a matching method in the delegate (named the same
+ * as the modified class with _Delegate added as a suffix).
+ * If the original native method is not static, then we make sure the delegate method also
+ * include the original class as first parameter (to access "this").
+ *
+ */
+public class TestDelegates extends TestCase {
+
+    public void testNativeDelegates() {
+
+        final String[] classes = CreateInfo.DELEGATE_CLASS_NATIVES;
+        final int count = classes.length;
+        for (int i = 0 ; i < count ; i++) {
+            loadAndCompareClasses(classes[i], classes[i] + "_Delegate");
+        }
+    }
+
+    public void testMethodDelegates() {
+        final String[] methods = CreateInfo.DELEGATE_METHODS;
+        final int count = methods.length;
+        for (int i = 0 ; i < count ; i++) {
+            String methodName = methods[i];
+
+            // extract the class name
+            String className = methodName.substring(0, methodName.indexOf('#'));
+            String targetClassName = className.replace('$', '_') + "_Delegate";
+
+            loadAndCompareClasses(className, targetClassName);
+        }
+    }
+
+    private void loadAndCompareClasses(String originalClassName, String delegateClassName) {
+        // load the classes
+        try {
+            ClassLoader classLoader = TestDelegates.class.getClassLoader();
+            Class<?> originalClass = classLoader.loadClass(originalClassName);
+            Class<?> delegateClass = classLoader.loadClass(delegateClassName);
+
+            compare(originalClass, delegateClass);
+        } catch (ClassNotFoundException e) {
+           fail("Failed to load class: " + e.getMessage());
+        } catch (SecurityException e) {
+            fail("Failed to load class: " + e.getMessage());
+        }
+    }
+
+    private void compare(Class<?> originalClass, Class<?> delegateClass) throws SecurityException {
+        List<Method> checkedDelegateMethods = new ArrayList<Method>();
+
+        // loop on the methods of the original class, and for the ones that are annotated
+        // with @LayoutlibDelegate, look for a matching method in the delegate class.
+        // The annotation is automatically added by layoutlib_create when it replace a method
+        // by a call to a delegate
+        Method[] originalMethods = originalClass.getDeclaredMethods();
+        for (Method originalMethod : originalMethods) {
+            // look for methods that are delegated: they have the LayoutlibDelegate annotation
+            if (originalMethod.getAnnotation(LayoutlibDelegate.class) == null) {
+                continue;
+            }
+
+            // get the signature.
+            Class<?>[] parameters = originalMethod.getParameterTypes();
+
+            // if the method is not static, then the class is added as the first parameter
+            // (for "this")
+            if ((originalMethod.getModifiers() & Modifier.STATIC) == 0) {
+
+                Class<?>[] newParameters = new Class<?>[parameters.length + 1];
+                newParameters[0] = originalClass;
+                System.arraycopy(parameters, 0, newParameters, 1, parameters.length);
+                parameters = newParameters;
+            }
+
+            // if the original class is an inner class that's not static, then
+            // we add this on the enclosing class at the beginning
+            if (originalClass.getEnclosingClass() != null &&
+                    (originalClass.getModifiers() & Modifier.STATIC) == 0) {
+                Class<?>[] newParameters = new Class<?>[parameters.length + 1];
+                newParameters[0] = originalClass.getEnclosingClass();
+                System.arraycopy(parameters, 0, newParameters, 1, parameters.length);
+                parameters = newParameters;
+            }
+
+            try {
+                // try to load the method with the given parameter types.
+                Method delegateMethod = delegateClass.getDeclaredMethod(originalMethod.getName(),
+                        parameters);
+
+                // check that the method has the annotation
+                assertNotNull(
+                        String.format(
+                                "Delegate method %1$s for class %2$s does not have the @LayoutlibDelegate annotation",
+                                delegateMethod.getName(),
+                                originalClass.getName()),
+                        delegateMethod.getAnnotation(LayoutlibDelegate.class));
+
+                // check that the method is static
+                assertTrue(
+                        String.format(
+                                "Delegate method %1$s for class %2$s is not static",
+                                delegateMethod.getName(),
+                                originalClass.getName()),
+                        (delegateMethod.getModifiers() & Modifier.STATIC) == Modifier.STATIC);
+
+                // add the method as checked.
+                checkedDelegateMethods.add(delegateMethod);
+            } catch (NoSuchMethodException e) {
+                String name = getMethodName(originalMethod, parameters);
+                fail(String.format("Missing %1$s.%2$s", delegateClass.getName(), name));
+            }
+        }
+
+        // look for dead (delegate) code.
+        // This looks for all methods in the delegate class, and if they have the
+        // @LayoutlibDelegate annotation, make sure they have been previously found as a
+        // match for a method in the original class.
+        // If not, this means the method is a delegate for a method that either doesn't exist
+        // anymore or is not delegated anymore.
+        Method[] delegateMethods = delegateClass.getDeclaredMethods();
+        for (Method delegateMethod : delegateMethods) {
+            // look for methods that are delegates: they have the LayoutlibDelegate annotation
+            if (delegateMethod.getAnnotation(LayoutlibDelegate.class) == null) {
+                continue;
+            }
+
+            assertTrue(
+                    String.format(
+                            "Delegate method %1$s.%2$s is not used anymore and must be removed",
+                            delegateClass.getName(),
+                            getMethodName(delegateMethod)),
+                    checkedDelegateMethods.contains(delegateMethod));
+        }
+
+    }
+
+    private String getMethodName(Method method) {
+        return getMethodName(method, method.getParameterTypes());
+    }
+
+    private String getMethodName(Method method, Class<?>[] parameters) {
+        // compute a full class name that's long but not too long.
+        StringBuilder sb = new StringBuilder(method.getName() + "(");
+        for (int j = 0; j < parameters.length; j++) {
+            Class<?> theClass = parameters[j];
+            sb.append(theClass.getName());
+            int dimensions = 0;
+            while (theClass.isArray()) {
+                dimensions++;
+                theClass = theClass.getComponentType();
+            }
+            for (int i = 0; i < dimensions; i++) {
+                sb.append("[]");
+            }
+            if (j < (parameters.length - 1)) {
+                sb.append(",");
+            }
+        }
+        sb.append(")");
+
+        return sb.toString();
+    }
+}
diff --git a/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/BridgeXmlBlockParserTest.java b/tools/layoutlib/bridge/tests/src/com/android/layoutlib/bridge/android/BridgeXmlBlockParserTest.java
similarity index 95%
rename from tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/BridgeXmlBlockParserTest.java
rename to tools/layoutlib/bridge/tests/src/com/android/layoutlib/bridge/android/BridgeXmlBlockParserTest.java
index db1262f..70d5446 100644
--- a/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/BridgeXmlBlockParserTest.java
+++ b/tools/layoutlib/bridge/tests/src/com/android/layoutlib/bridge/android/BridgeXmlBlockParserTest.java
@@ -14,7 +14,9 @@
  * limitations under the License.
  */
 
-package com.android.layoutlib.bridge;
+package com.android.layoutlib.bridge.android;
+
+import com.android.layoutlib.bridge.android.BridgeXmlBlockParser;
 
 import org.kxml2.io.KXmlParser;
 import org.w3c.dom.Node;
@@ -42,7 +44,7 @@
 
         InputStream input = this.getClass().getClassLoader().getResourceAsStream(
             "com/android/layoutlib/testdata/layout1.xml");
-        parser.setInput(input, null /*encoding*/);
+        parser.setInput(input, "UTF-8"); //$NON-NLS-1$
 
         assertEquals(XmlPullParser.START_DOCUMENT, parser.next());
 
diff --git a/tools/layoutlib/bridge/tests/com/android/layoutlib/testdata/layout1.xml b/tools/layoutlib/bridge/tests/src/com/android/layoutlib/testdata/layout1.xml
similarity index 100%
rename from tools/layoutlib/bridge/tests/com/android/layoutlib/testdata/layout1.xml
rename to tools/layoutlib/bridge/tests/src/com/android/layoutlib/testdata/layout1.xml
diff --git a/tools/layoutlib/create/README.txt b/tools/layoutlib/create/README.txt
index c59e20d..894611b 100644
--- a/tools/layoutlib/create/README.txt
+++ b/tools/layoutlib/create/README.txt
@@ -30,9 +30,9 @@
 Consequently this tool:
 - parses the input JAR,
 - modifies some of the classes directly using some bytecode manipulation,
-- filters some packages and removes some that we don't want to end in the output JAR,
+- filters some packages and removes those we don't want in the output JAR,
 - injects some new classes,
-- and generates a modified JAR file that is suitable for the Android plugin
+- generates a modified JAR file that is suitable for the Android plugin
   for Eclipse to perform rendering.
 
 The ASM library is used to do the bytecode modification using its visitor pattern API.
@@ -63,7 +63,7 @@
 
 To do that, the analyzer is created with a list of base classes to keep -- everything
 that derives from these is kept. Currently the one such class is android.view.View:
-since we want to render layouts, anything that is sort of the view needs to be kept.
+since we want to render layouts, anything that is sort of a view needs to be kept.
 
 The analyzer is also given a list of class names to keep in the output.
 This is done using shell-like glob patterns that filter on the fully-qualified
@@ -90,6 +90,7 @@
 - the classes to inject in the output JAR -- these classes are directly implemented
   in layoutlib_create and will be used to interface with the renderer in Eclipse.
 - specific methods to override (see method stubs details below).
+- specific methods for which to delegate calls.
 - specific methods to remove based on their return type.
 - specific classes to rename.
 
@@ -114,6 +115,9 @@
 The code of the methods is then kept as-is, except for native methods which are
 replaced by a stub. Methods that are to be overridden are also replaced by a stub.
 
+The transformed class is then fed through the DelegateClassAdapter to implement
+method delegates. 
+
 Finally fields are also visited and changed from protected/private to public.
 
 
@@ -131,8 +135,7 @@
 method was native. We do not currently provide the parameters. The listener
 can however specify the return value of the overridden method.
 
-An extension being worked on is to actually replace these listeners by
-direct calls to a delegate class, complete with parameters.
+This strategy is now obsolete and replaced by the method delegates.
 
 
 - Strategies
@@ -160,6 +163,9 @@
 by a call to a specific OveriddeMethod.invokeX(). The bridge then registers
 a listener on the method signature and can provide an implementation.
 
+This strategy is now obsolete and replaced by the method delegates.
+See strategy 5 below.
+
 
 3- Renaming classes
 
@@ -195,5 +201,40 @@
 bridge will provide its own implementation.
 
 
+5- Method Delegates
+
+This strategy is used to override method implementations.
+Given a method SomeClass.MethodName(), 1 or 2 methods are generated:
+a- A copy of the original method named SomeClass.MethodName_Original().
+   The content is the original method as-is from the reader.
+   This step is omitted if the method is native, since it has no Java implementation.
+b- A brand new implementation of SomeClass.MethodName() which calls to a
+   non-existing static method named SomeClass_Delegate.MethodName().
+   The implementation of this 'delegate' method is done in layoutlib_brigde.
+
+The delegate method is a static method.
+If the original method is non-static, the delegate method receives the original 'this'
+as its first argument. If the original method is an inner non-static method, it also
+receives the inner 'this' as the second argument.
+
+
+
+- References -
+--------------
+
+
+The JVM Specification 2nd edition:
+  http://java.sun.com/docs/books/jvms/second_edition/html/VMSpecTOC.doc.html
+
+Understanding bytecode:
+  http://www.ibm.com/developerworks/ibm/library/it-haggar_bytecode/
+
+Bytecode opcode list:
+  http://en.wikipedia.org/wiki/Java_bytecode_instruction_listings
+
+ASM user guide:
+  http://download.forge.objectweb.org/asm/asm-guide.pdf
+
+
 --
 end
diff --git a/core/java/android/nfc/INfcSecureElement.aidl b/tools/layoutlib/create/src/com/android/tools/layoutlib/annotations/LayoutlibDelegate.java
old mode 100755
new mode 100644
similarity index 65%
rename from core/java/android/nfc/INfcSecureElement.aidl
rename to tools/layoutlib/create/src/com/android/tools/layoutlib/annotations/LayoutlibDelegate.java
index aa98dd2..9a48ea6
--- a/core/java/android/nfc/INfcSecureElement.aidl
+++ b/tools/layoutlib/create/src/com/android/tools/layoutlib/annotations/LayoutlibDelegate.java
@@ -14,15 +14,14 @@
  * limitations under the License.
  */
 
-package android.nfc;
+package com.android.tools.layoutlib.annotations;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
 
 /**
- * {@hide}
+ * Denotes a method that has been converted to a delegate by layoutlib_create.
  */
-interface INfcSecureElement {
-    int openSecureElementConnection();
-    int closeSecureElementConnection(int nativeHandle);
-    byte[] exchangeAPDU(int nativeHandle, in byte[] data);
-    int[] getSecureElementTechList(int nativeHandle);
-    byte[] getSecureElementUid(int nativeHandle);
-}
\ No newline at end of file
+@Retention(RetentionPolicy.RUNTIME)
+public @interface LayoutlibDelegate {
+}
diff --git a/tools/layoutlib/create/src/com/android/tools/layoutlib/create/AsmGenerator.java b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/AsmGenerator.java
index 7b55ed3e..a9ede26 100644
--- a/tools/layoutlib/create/src/com/android/tools/layoutlib/create/AsmGenerator.java
+++ b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/AsmGenerator.java
@@ -28,9 +28,9 @@
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Set;
 import java.util.TreeMap;
-import java.util.Map.Entry;
 import java.util.jar.JarEntry;
 import java.util.jar.JarOutputStream;
 
@@ -60,38 +60,56 @@
      *  old-FQCN to rename and they get erased as they get renamed. At the end, classes still
      *  left here are not in the code base anymore and thus were not renamed. */
     private HashSet<String> mClassesNotRenamed;
-    /** A map { FQCN => map { list of return types to delete from the FQCN } }. */
+    /** A map { FQCN => set { list of return types to delete from the FQCN } }. */
     private HashMap<String, Set<String>> mDeleteReturns;
+    /** A map { FQCN => set { method names } } of methods to rewrite as delegates.
+     *  The special name {@link DelegateClassAdapter#ALL_NATIVES} can be used as in internal set. */
+    private final HashMap<String, Set<String>> mDelegateMethods;
 
     /**
      * Creates a new generator that can generate the output JAR with the stubbed classes.
-     * 
+     *
      * @param log Output logger.
      * @param osDestJar The path of the destination JAR to create.
-     * @param injectClasses The list of class from layoutlib_create to inject in layoutlib.
-     * @param stubMethods The list of methods to stub out. Each entry must be in the form
-     *          "package.package.OuterClass$InnerClass#MethodName".
-     * @param renameClasses The list of classes to rename, must be an even list: the binary FQCN
-     *          of class to replace followed by the new FQCN.
-     * @param deleteReturns List of classes for which the methods returning them should be deleted.
-     * The array contains a list of null terminated section starting with the name of the class
-     * to rename in which the methods are deleted, followed by a list of return types identifying
-     * the methods to delete.
+     * @param createInfo Creation parameters. Must not be null.
      */
-    public AsmGenerator(Log log, String osDestJar,
-            Class<?>[] injectClasses,
-            String[] stubMethods,
-            String[] renameClasses, String[] deleteReturns) {
+    public AsmGenerator(Log log, String osDestJar, ICreateInfo createInfo) {
         mLog = log;
         mOsDestJar = osDestJar;
-        mInjectClasses = injectClasses != null ? injectClasses : new Class<?>[0];
-        mStubMethods = stubMethods != null ? new HashSet<String>(Arrays.asList(stubMethods)) :
-                                             new HashSet<String>();
+        mInjectClasses = createInfo.getInjectedClasses();
+        mStubMethods = new HashSet<String>(Arrays.asList(createInfo.getOverriddenMethods()));
+
+        // Create the map/set of methods to change to delegates
+        mDelegateMethods = new HashMap<String, Set<String>>();
+        for (String signature : createInfo.getDelegateMethods()) {
+            int pos = signature.indexOf('#');
+            if (pos <= 0 || pos >= signature.length() - 1) {
+                continue;
+            }
+            String className = binaryToInternalClassName(signature.substring(0, pos));
+            String methodName = signature.substring(pos + 1);
+            Set<String> methods = mDelegateMethods.get(className);
+            if (methods == null) {
+                methods = new HashSet<String>();
+                mDelegateMethods.put(className, methods);
+            }
+            methods.add(methodName);
+        }
+        for (String className : createInfo.getDelegateClassNatives()) {
+            className = binaryToInternalClassName(className);
+            Set<String> methods = mDelegateMethods.get(className);
+            if (methods == null) {
+                methods = new HashSet<String>();
+                mDelegateMethods.put(className, methods);
+            }
+            methods.add(DelegateClassAdapter.ALL_NATIVES);
+        }
 
         // Create the map of classes to rename.
         mRenameClasses = new HashMap<String, String>();
         mClassesNotRenamed = new HashSet<String>();
-        int n = renameClasses == null ? 0 : renameClasses.length;
+        String[] renameClasses = createInfo.getRenamedClasses();
+        int n = renameClasses.length;
         for (int i = 0; i < n; i += 2) {
             assert i + 1 < n;
             // The ASM class names uses "/" separators, whereas regular FQCN use "."
@@ -100,38 +118,37 @@
             mRenameClasses.put(oldFqcn, newFqcn);
             mClassesNotRenamed.add(oldFqcn);
         }
-        
+
         // create the map of renamed class -> return type of method to delete.
         mDeleteReturns = new HashMap<String, Set<String>>();
-        if (deleteReturns != null) {
-            Set<String> returnTypes = null;
-            String renamedClass = null;
-            for (String className : deleteReturns) {
-                // if we reach the end of a section, add it to the main map
-                if (className == null) {
-                    if (returnTypes != null) {
-                        mDeleteReturns.put(renamedClass, returnTypes);
-                    }
-                    
-                    renamedClass = null;
-                    continue;
+        String[] deleteReturns = createInfo.getDeleteReturns();
+        Set<String> returnTypes = null;
+        String renamedClass = null;
+        for (String className : deleteReturns) {
+            // if we reach the end of a section, add it to the main map
+            if (className == null) {
+                if (returnTypes != null) {
+                    mDeleteReturns.put(renamedClass, returnTypes);
                 }
-    
-                // if the renamed class is null, this is the beginning of a section
-                if (renamedClass == null) {
-                    renamedClass = binaryToInternalClassName(className);
-                    continue;
-                }
-    
-                // just a standard return type, we add it to the list.
-                if (returnTypes == null) {
-                    returnTypes = new HashSet<String>();
-                }
-                returnTypes.add(binaryToInternalClassName(className));
+
+                renamedClass = null;
+                continue;
             }
+
+            // if the renamed class is null, this is the beginning of a section
+            if (renamedClass == null) {
+                renamedClass = binaryToInternalClassName(className);
+                continue;
+            }
+
+            // just a standard return type, we add it to the list.
+            if (returnTypes == null) {
+                returnTypes = new HashSet<String>();
+            }
+            returnTypes.add(binaryToInternalClassName(className));
         }
     }
-    
+
     /**
      * Returns the list of classes that have not been renamed yet.
      * <p/>
@@ -163,12 +180,12 @@
     public void setDeps(Map<String, ClassReader> deps) {
         mDeps = deps;
     }
-    
+
     /** Gets the map of classes to output as-is, except if they have native methods */
     public Map<String, ClassReader> getKeep() {
         return mKeep;
     }
-    
+
     /** Gets the map of dependencies that must be completely stubbed */
     public Map<String, ClassReader> getDeps() {
         return mDeps;
@@ -177,7 +194,7 @@
     /** Generates the final JAR */
     public void generate() throws FileNotFoundException, IOException {
         TreeMap<String, byte[]> all = new TreeMap<String, byte[]>();
-        
+
         for (Class<?> clazz : mInjectClasses) {
             String name = classToEntryPath(clazz);
             InputStream is = ClassLoader.getSystemResourceAsStream(name);
@@ -186,7 +203,7 @@
             name = classNameToEntryPath(transformName(cr.getClassName()));
             all.put(name, b);
         }
-        
+
         for (Entry<String, ClassReader> entry : mDeps.entrySet()) {
             ClassReader cr = entry.getValue();
             byte[] b = transform(cr, true /* stubNativesOnly */);
@@ -211,8 +228,8 @@
 
     /**
      * Writes the JAR file.
-     * 
-     * @param outStream The file output stream were to write the JAR. 
+     *
+     * @param outStream The file output stream were to write the JAR.
      * @param all The map of all classes to output.
      * @throws IOException if an I/O error has occurred
      */
@@ -236,7 +253,7 @@
     String classNameToEntryPath(String className) {
         return className.replaceAll("\\.", "/").concat(".class");
     }
-    
+
     /**
      * Utility method to get the JAR entry path from a Class name.
      * e.g. it returns someting like "com/foo/OuterClass$InnerClass1$InnerClass2.class"
@@ -248,30 +265,32 @@
             name = "$" + clazz.getSimpleName() + name;
             clazz = parent;
         }
-        return classNameToEntryPath(clazz.getCanonicalName() + name);        
+        return classNameToEntryPath(clazz.getCanonicalName() + name);
     }
 
     /**
      * Transforms a class.
      * <p/>
      * There are 3 kind of transformations:
-     * 
+     *
      * 1- For "mock" dependencies classes, we want to remove all code from methods and replace
      * by a stub. Native methods must be implemented with this stub too. Abstract methods are
      * left intact. Modified classes must be overridable (non-private, non-final).
      * Native methods must be made non-final, non-private.
-     * 
+     *
      * 2- For "keep" classes, we want to rewrite all native methods as indicated above.
      * If a class has native methods, it must also be made non-private, non-final.
-     * 
+     *
      * Note that unfortunately static methods cannot be changed to non-static (since static and
      * non-static are invoked differently.)
      */
     byte[] transform(ClassReader cr, boolean stubNativesOnly) {
 
         boolean hasNativeMethods = hasNativeMethods(cr);
+
+        // Get the class name, as an internal name (e.g. com/android/SomeClass$InnerClass)
         String className = cr.getClassName();
-        
+
         String newName = transformName(className);
         // transformName returns its input argument if there's no need to rename the class
         if (newName != className) {
@@ -288,16 +307,28 @@
         // Rewrite the new class from scratch, without reusing the constant pool from the
         // original class reader.
         ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
-        
+
         ClassVisitor rv = cw;
         if (newName != className) {
             rv = new RenameClassAdapter(cw, className, newName);
         }
-        
-        TransformClassAdapter cv = new TransformClassAdapter(mLog, mStubMethods, 
+
+        ClassVisitor cv = new TransformClassAdapter(mLog, mStubMethods,
                 mDeleteReturns.get(className),
                 newName, rv,
                 stubNativesOnly, stubNativesOnly || hasNativeMethods);
+
+        Set<String> delegateMethods = mDelegateMethods.get(className);
+        if (delegateMethods != null && !delegateMethods.isEmpty()) {
+            // If delegateMethods only contains one entry ALL_NATIVES and the class is
+            // known to have no native methods, just skip this step.
+            if (hasNativeMethods ||
+                    !(delegateMethods.size() == 1 &&
+                            delegateMethods.contains(DelegateClassAdapter.ALL_NATIVES))) {
+                cv = new DelegateClassAdapter(mLog, cv, className, delegateMethods);
+            }
+        }
+
         cr.accept(cv, 0 /* flags */);
         return cw.toByteArray();
     }
@@ -323,7 +354,7 @@
                 return newName + className.substring(pos);
             }
         }
-        
+
         return className;
     }
 
diff --git a/tools/layoutlib/create/src/com/android/tools/layoutlib/create/CreateInfo.java b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/CreateInfo.java
index 2ed8641..95506c6 100644
--- a/tools/layoutlib/create/src/com/android/tools/layoutlib/create/CreateInfo.java
+++ b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/CreateInfo.java
@@ -16,51 +16,160 @@
 
 package com.android.tools.layoutlib.create;
 
-public class CreateInfo {
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+/**
+ * Describes the work to be done by {@link AsmGenerator}.
+ */
+public final class CreateInfo implements ICreateInfo {
+
+    /**
+     * Returns the list of class from layoutlib_create to inject in layoutlib.
+     * The list can be empty but must not be null.
+     */
+    public Class<?>[] getInjectedClasses() {
+        return INJECTED_CLASSES;
+    }
+
+    /**
+     * Returns the list of methods to rewrite as delegates.
+     * The list can be empty but must not be null.
+     */
+    public String[] getDelegateMethods() {
+        return DELEGATE_METHODS;
+    }
+
+    /**
+     * Returns the list of classes on which to delegate all native methods.
+     * The list can be empty but must not be null.
+     */
+    public String[] getDelegateClassNatives() {
+        return DELEGATE_CLASS_NATIVES;
+    }
+
+    /**
+     * Returns The list of methods to stub out. Each entry must be in the form
+     * "package.package.OuterClass$InnerClass#MethodName".
+     * The list can be empty but must not be null.
+     * <p/>
+     * This usage is deprecated. Please use method 'delegates' instead.
+     */
+    public String[] getOverriddenMethods() {
+        return OVERRIDDEN_METHODS;
+    }
+
+    /**
+     * Returns the list of classes to rename, must be an even list: the binary FQCN
+     * of class to replace followed by the new FQCN.
+     * The list can be empty but must not be null.
+     */
+    public String[] getRenamedClasses() {
+        return RENAMED_CLASSES;
+    }
+
+    /**
+     * Returns the list of classes for which the methods returning them should be deleted.
+     * The array contains a list of null terminated section starting with the name of the class
+     * to rename in which the methods are deleted, followed by a list of return types identifying
+     * the methods to delete.
+     * The list can be empty but must not be null.
+     */
+    public String[] getDeleteReturns() {
+        return DELETE_RETURNS;
+    }
+
+    //-----
+
     /**
      * The list of class from layoutlib_create to inject in layoutlib.
      */
-    public final static Class<?>[] INJECTED_CLASSES = new Class<?>[] {
+    private final static Class<?>[] INJECTED_CLASSES = new Class<?>[] {
             OverrideMethod.class,
             MethodListener.class,
             MethodAdapter.class,
-            CreateInfo.class
+            ICreateInfo.class,
+            CreateInfo.class,
+            LayoutlibDelegate.class
         };
 
     /**
+     * The list of methods to rewrite as delegates.
+     */
+    private final static String[] DELEGATE_METHODS = new String[] {
+        "android.content.res.Resources$Theme#obtainStyledAttributes",
+        "android.content.res.Resources$Theme#resolveAttribute",
+        "android.graphics.BitmapFactory#finishDecode",
+        "android.os.Handler#sendMessageAtTime",
+        "android.os.HandlerThread#run",
+        "android.os.Build#getString",
+        "android.view.LayoutInflater#parseInclude",
+        "android.view.View#isInEditMode",
+        "com.android.internal.util.XmlUtils#convertValueToInt",
+    };
+
+    /**
+     * The list of classes on which to delegate all native methods.
+     */
+    private final static String[] DELEGATE_CLASS_NATIVES = new String[] {
+        "android.graphics.AvoidXfermode",
+        "android.graphics.Bitmap",
+        "android.graphics.BitmapFactory",
+        "android.graphics.BitmapShader",
+        "android.graphics.BlurMaskFilter",
+        "android.graphics.Canvas",
+        "android.graphics.ColorFilter",
+        "android.graphics.ColorMatrixColorFilter",
+        "android.graphics.ComposePathEffect",
+        "android.graphics.ComposeShader",
+        "android.graphics.CornerPathEffect",
+        "android.graphics.DashPathEffect",
+        "android.graphics.DiscretePathEffect",
+        "android.graphics.DrawFilter",
+        "android.graphics.EmbossMaskFilter",
+        "android.graphics.LayerRasterizer",
+        "android.graphics.LightingColorFilter",
+        "android.graphics.LinearGradient",
+        "android.graphics.MaskFilter",
+        "android.graphics.Matrix",
+        "android.graphics.NinePatch",
+        "android.graphics.Paint",
+        "android.graphics.PaintFlagsDrawFilter",
+        "android.graphics.Path",
+        "android.graphics.PathDashPathEffect",
+        "android.graphics.PathEffect",
+        "android.graphics.PixelXorXfermode",
+        "android.graphics.PorterDuffColorFilter",
+        "android.graphics.PorterDuffXfermode",
+        "android.graphics.RadialGradient",
+        "android.graphics.Rasterizer",
+        "android.graphics.Region",
+        "android.graphics.Shader",
+        "android.graphics.SumPathEffect",
+        "android.graphics.SweepGradient",
+        "android.graphics.Typeface",
+        "android.graphics.Xfermode",
+        "android.os.SystemClock",
+        "android.util.FloatMath",
+    };
+
+    /**
      * The list of methods to stub out. Each entry must be in the form
      *  "package.package.OuterClass$InnerClass#MethodName".
+     *  This usage is deprecated. Please use method 'delegates' instead.
      */
-    public final static String[] OVERRIDDEN_METHODS = new String[] {
-            "android.view.View#isInEditMode",
-            "android.content.res.Resources$Theme#obtainStyledAttributes",
-        };
+    private final static String[] OVERRIDDEN_METHODS = new String[] {
+    };
 
     /**
      *  The list of classes to rename, must be an even list: the binary FQCN
      *  of class to replace followed by the new FQCN.
      */
-    public final static String[] RENAMED_CLASSES =
+    private final static String[] RENAMED_CLASSES =
         new String[] {
-            "android.graphics.Bitmap",              "android.graphics._Original_Bitmap",
-            "android.graphics.BitmapFactory",       "android.graphics._Original_BitmapFactory",
-            "android.graphics.BitmapShader",        "android.graphics._Original_BitmapShader",
-            "android.graphics.Canvas",              "android.graphics._Original_Canvas",
-            "android.graphics.ComposeShader",       "android.graphics._Original_ComposeShader",
-            "android.graphics.DashPathEffect",       "android.graphics._Original_DashPathEffect",
-            "android.graphics.LinearGradient",      "android.graphics._Original_LinearGradient",
-            "android.graphics.Matrix",              "android.graphics._Original_Matrix",
-            "android.graphics.Paint",               "android.graphics._Original_Paint",
-            "android.graphics.Path",                "android.graphics._Original_Path",
-            "android.graphics.PorterDuffXfermode",  "android.graphics._Original_PorterDuffXfermode",
-            "android.graphics.RadialGradient",      "android.graphics._Original_RadialGradient",
-            "android.graphics.Shader",              "android.graphics._Original_Shader",
-            "android.graphics.SweepGradient",       "android.graphics._Original_SweepGradient",
-            "android.graphics.Typeface",            "android.graphics._Original_Typeface",
             "android.os.ServiceManager",            "android.os._Original_ServiceManager",
-            "android.util.FloatMath",               "android.util._Original_FloatMath",
             "android.view.SurfaceView",             "android.view._Original_SurfaceView",
             "android.view.accessibility.AccessibilityManager", "android.view.accessibility._Original_AccessibilityManager",
+            "android.webkit.WebView",               "android.webkit._Original_WebView",
         };
 
     /**
@@ -69,15 +178,8 @@
      * to rename in which the methods are deleted, followed by a list of return types identifying
      * the methods to delete.
      */
-    public final static String[] REMOVED_METHODS =
+    private final static String[] DELETE_RETURNS =
         new String[] {
-            "android.graphics.Paint",       // class to delete methods from
-            "android.graphics.Paint$Align", // list of type identifying methods to delete
-            "android.graphics.Paint$Style",
-            "android.graphics.Paint$Join",
-            "android.graphics.Paint$Cap",
-            "android.graphics.Paint$FontMetrics",
-            "android.graphics.Paint$FontMetricsInt",
             null };                         // separator, for next class/methods list.
 }
 
diff --git a/tools/layoutlib/create/src/com/android/tools/layoutlib/create/DelegateClassAdapter.java b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/DelegateClassAdapter.java
new file mode 100644
index 0000000..0e24cc0
--- /dev/null
+++ b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/DelegateClassAdapter.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.tools.layoutlib.create;
+
+import org.objectweb.asm.ClassAdapter;
+import org.objectweb.asm.ClassVisitor;
+import org.objectweb.asm.MethodVisitor;
+import org.objectweb.asm.Opcodes;
+
+import java.util.Set;
+
+/**
+ * A {@link DelegateClassAdapter} can transform some methods from a class into
+ * delegates that defer the call to an associated delegate class.
+ * <p/>
+ * This is used to override specific methods and or all native methods in classes.
+ */
+public class DelegateClassAdapter extends ClassAdapter {
+
+    /** Suffix added to original methods. */
+    private static final String ORIGINAL_SUFFIX = "_Original";
+    private static String CONSTRUCTOR = "<init>";
+    private static String CLASS_INIT = "<clinit>";
+
+    public final static String ALL_NATIVES = "<<all_natives>>";
+
+    private final String mClassName;
+    private final Set<String> mDelegateMethods;
+    private final Log mLog;
+
+    /**
+     * Creates a new {@link DelegateClassAdapter} that can transform some methods
+     * from a class into delegates that defer the call to an associated delegate class.
+     * <p/>
+     * This is used to override specific methods and or all native methods in classes.
+     *
+     * @param log The logger object. Must not be null.
+     * @param cv the class visitor to which this adapter must delegate calls.
+     * @param className The internal class name of the class to visit,
+     *          e.g. <code>com/android/SomeClass$InnerClass</code>.
+     * @param delegateMethods The set of method names to modify and/or the
+     *          special constant {@link #ALL_NATIVES} to convert all native methods.
+     */
+    public DelegateClassAdapter(Log log,
+            ClassVisitor cv,
+            String className,
+            Set<String> delegateMethods) {
+        super(cv);
+        mLog = log;
+        mClassName = className;
+        mDelegateMethods = delegateMethods;
+    }
+
+    //----------------------------------
+    // Methods from the ClassAdapter
+
+    @Override
+    public MethodVisitor visitMethod(int access, String name, String desc,
+            String signature, String[] exceptions) {
+
+        boolean isStatic = (access & Opcodes.ACC_STATIC) != 0;
+        boolean isNative = (access & Opcodes.ACC_NATIVE) != 0;
+
+        boolean useDelegate = (isNative && mDelegateMethods.contains(ALL_NATIVES)) ||
+                              mDelegateMethods.contains(name);
+
+        if (!useDelegate) {
+            // Not creating a delegate for this method, pass it as-is from the reader
+            // to the writer.
+            return super.visitMethod(access, name, desc, signature, exceptions);
+        }
+
+        if (useDelegate) {
+            if (CONSTRUCTOR.equals(name) || CLASS_INIT.equals(name)) {
+                // We don't currently support generating delegates for constructors.
+                throw new UnsupportedOperationException(
+                    String.format(
+                        "Delegate doesn't support overriding constructor %1$s:%2$s(%3$s)",  //$NON-NLS-1$
+                        mClassName, name, desc));
+            }
+        }
+
+        if (isNative) {
+            // Remove native flag
+            access = access & ~Opcodes.ACC_NATIVE;
+            MethodVisitor mwDelegate = super.visitMethod(access, name, desc, signature, exceptions);
+
+            DelegateMethodAdapter2 a = new DelegateMethodAdapter2(
+                    mLog, null /*mwOriginal*/, mwDelegate, mClassName, name, desc, isStatic);
+
+            // A native has no code to visit, so we need to generate it directly.
+            a.generateDelegateCode();
+
+            return mwDelegate;
+        }
+
+        // Given a non-native SomeClass.MethodName(), we want to generate 2 methods:
+        // - A copy of the original method named SomeClass.MethodName_Original().
+        //   The content is the original method as-is from the reader.
+        // - A brand new implementation of SomeClass.MethodName() which calls to a
+        //   non-existing method named SomeClass_Delegate.MethodName().
+        //   The implementation of this 'delegate' method is done in layoutlib_brigde.
+
+        int accessDelegate = access;
+        // change access to public for the original one
+        if (Main.sOptions.generatePublicAccess) {
+            access &= ~(Opcodes.ACC_PROTECTED | Opcodes.ACC_PRIVATE);
+            access |= Opcodes.ACC_PUBLIC;
+        }
+
+        MethodVisitor mwOriginal = super.visitMethod(access, name + ORIGINAL_SUFFIX,
+                                                     desc, signature, exceptions);
+        MethodVisitor mwDelegate = super.visitMethod(accessDelegate, name,
+                                                     desc, signature, exceptions);
+
+        DelegateMethodAdapter2 a = new DelegateMethodAdapter2(
+                mLog, mwOriginal, mwDelegate, mClassName, name, desc, isStatic);
+        return a;
+    }
+}
diff --git a/tools/layoutlib/create/src/com/android/tools/layoutlib/create/DelegateMethodAdapter2.java b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/DelegateMethodAdapter2.java
new file mode 100644
index 0000000..ac4ae6d
--- /dev/null
+++ b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/DelegateMethodAdapter2.java
@@ -0,0 +1,431 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.tools.layoutlib.create;
+
+import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
+
+import org.objectweb.asm.AnnotationVisitor;
+import org.objectweb.asm.Attribute;
+import org.objectweb.asm.ClassReader;
+import org.objectweb.asm.ClassVisitor;
+import org.objectweb.asm.Label;
+import org.objectweb.asm.MethodVisitor;
+import org.objectweb.asm.Opcodes;
+import org.objectweb.asm.Type;
+
+import java.util.ArrayList;
+
+/**
+ * This method adapter generates delegate methods.
+ * <p/>
+ * Given a method {@code SomeClass.MethodName()}, this generates 1 or 2 methods:
+ * <ul>
+ * <li> A copy of the original method named {@code SomeClass.MethodName_Original()}.
+ *   The content is the original method as-is from the reader.
+ *   This step is omitted if the method is native, since it has no Java implementation.
+ * <li> A brand new implementation of {@code SomeClass.MethodName()} which calls to a
+ *   non-existing method named {@code SomeClass_Delegate.MethodName()}.
+ *   The implementation of this 'delegate' method is done in layoutlib_brigde.
+ * </ul>
+ * A method visitor is generally constructed to generate a single method; however
+ * here we might want to generate one or two depending on the context. To achieve
+ * that, the visitor here generates the 'original' method and acts as a no-op if
+ * no such method exists (e.g. when the original is a native method).
+ * The delegate method is generated after the {@code visitEnd} of the original method
+ * or by having the class adapter <em>directly</em> call {@link #generateDelegateCode()}
+ * for native methods.
+ * <p/>
+ * When generating the 'delegate', the implementation generates a call to a class
+ * class named <code>&lt;className&gt;_Delegate</code> with static methods matching
+ * the methods to be overridden here. The methods have the same return type.
+ * The argument type list is the same except the "this" reference is passed first
+ * for non-static methods.
+ * <p/>
+ * A new annotation is added to these 'delegate' methods so that we can easily find them
+ * for automated testing.
+ * <p/>
+ * This class isn't intended to be generic or reusable.
+ * It is called by {@link DelegateClassAdapter}, which takes care of properly initializing
+ * the two method writers for the original and the delegate class, as needed, with their
+ * expected names.
+ * <p/>
+ * The class adapter also takes care of calling {@link #generateDelegateCode()} directly for
+ * a native and use the visitor pattern for non-natives.
+ * Note that native methods have, by definition, no code so there's nothing a visitor
+ * can visit.
+ * <p/>
+ * Instances of this class are not re-usable.
+ * The class adapter creates a new instance for each method.
+ */
+class DelegateMethodAdapter2 implements MethodVisitor {
+
+    /** Suffix added to delegate classes. */
+    public static final String DELEGATE_SUFFIX = "_Delegate";
+
+    /** The parent method writer to copy of the original method.
+     *  Null when dealing with a native original method. */
+    private MethodVisitor mOrgWriter;
+    /** The parent method writer to generate the delegating method. Never null. */
+    private MethodVisitor mDelWriter;
+    /** The original method descriptor (return type + argument types.) */
+    private String mDesc;
+    /** True if the original method is static. */
+    private final boolean mIsStatic;
+    /** The internal class name (e.g. <code>com/android/SomeClass$InnerClass</code>.) */
+    private final String mClassName;
+    /** The method name. */
+    private final String mMethodName;
+    /** Logger object. */
+    private final Log mLog;
+
+    /** Array used to capture the first line number information from the original method
+     *  and duplicate it in the delegate. */
+    private Object[] mDelegateLineNumber;
+
+    /**
+     * Creates a new {@link DelegateMethodAdapter2} that will transform this method
+     * into a delegate call.
+     * <p/>
+     * See {@link DelegateMethodAdapter2} for more details.
+     *
+     * @param log The logger object. Must not be null.
+     * @param mvOriginal The parent method writer to copy of the original method.
+     *          Must be {@code null} when dealing with a native original method.
+     * @param mvDelegate The parent method writer to generate the delegating method.
+     *          Must never be null.
+     * @param className The internal class name of the class to visit,
+     *          e.g. <code>com/android/SomeClass$InnerClass</code>.
+     * @param methodName The simple name of the method.
+     * @param desc A method descriptor (c.f. {@link Type#getReturnType(String)} +
+     *          {@link Type#getArgumentTypes(String)})
+     * @param isStatic True if the method is declared static.
+     */
+    public DelegateMethodAdapter2(Log log,
+            MethodVisitor mvOriginal,
+            MethodVisitor mvDelegate,
+            String className,
+            String methodName,
+            String desc,
+            boolean isStatic) {
+        mLog = log;
+        mOrgWriter = mvOriginal;
+        mDelWriter = mvDelegate;
+        mClassName = className;
+        mMethodName = methodName;
+        mDesc = desc;
+        mIsStatic = isStatic;
+    }
+
+    /**
+     * Generates the new code for the method.
+     * <p/>
+     * For native methods, this must be invoked directly by {@link DelegateClassAdapter}
+     * (since they have no code to visit).
+     * <p/>
+     * Otherwise for non-native methods the {@link DelegateClassAdapter} simply needs to
+     * return this instance of {@link DelegateMethodAdapter2} and let the normal visitor pattern
+     * invoke it as part of the {@link ClassReader#accept(ClassVisitor, int)} workflow and then
+     * this method will be invoked from {@link MethodVisitor#visitEnd()}.
+     */
+    public void generateDelegateCode() {
+        /*
+         * The goal is to generate a call to a static delegate method.
+         * If this method is non-static, the first parameter will be 'this'.
+         * All the parameters must be passed and then the eventual return type returned.
+         *
+         * Example, let's say we have a method such as
+         *   public void myMethod(int a, Object b, ArrayList<String> c) { ... }
+         *
+         * We'll want to create a body that calls a delegate method like this:
+         *   TheClass_Delegate.myMethod(this, a, b, c);
+         *
+         * If the method is non-static and the class name is an inner class (e.g. has $ in its
+         * last segment), we want to push the 'this' of the outer class first:
+         *   OuterClass_InnerClass_Delegate.myMethod(
+         *     OuterClass.this,
+         *     OuterClass$InnerClass.this,
+         *     a, b, c);
+         *
+         * Only one level of inner class is supported right now, for simplicity and because
+         * we don't need more.
+         *
+         * The generated class name is the current class name with "_Delegate" appended to it.
+         * One thing to realize is that we don't care about generics -- since generic types
+         * are erased at build time, they have no influence on the method name being called.
+         */
+
+        // Add our annotation
+        AnnotationVisitor aw = mDelWriter.visitAnnotation(
+                Type.getObjectType(Type.getInternalName(LayoutlibDelegate.class)).toString(),
+                true); // visible at runtime
+        if (aw != null) {
+            aw.visitEnd();
+        }
+
+        mDelWriter.visitCode();
+
+        if (mDelegateLineNumber != null) {
+            Object[] p = mDelegateLineNumber;
+            mDelWriter.visitLineNumber((Integer) p[0], (Label) p[1]);
+        }
+
+        ArrayList<Type> paramTypes = new ArrayList<Type>();
+        String delegateClassName = mClassName + DELEGATE_SUFFIX;
+        boolean pushedArg0 = false;
+        int maxStack = 0;
+
+        // For an instance method (e.g. non-static), push the 'this' preceded
+        // by the 'this' of any outer class, if any.
+        if (!mIsStatic) {
+            // Check if the last segment of the class name has inner an class.
+            // Right now we only support one level of inner classes.
+            int slash = mClassName.lastIndexOf('/');
+            int dol = mClassName.lastIndexOf('$');
+            if (dol != -1 && dol > slash && dol == mClassName.indexOf('$')) {
+                String outerClass = mClassName.substring(0, dol);
+                Type outerType = Type.getObjectType(outerClass);
+
+                // Change a delegate class name to "com/foo/Outer_Inner_Delegate"
+                delegateClassName = delegateClassName.replace('$', '_');
+
+                // The first-level inner class has a package-protected member called 'this$0'
+                // that points to the outer class.
+
+                // Push this.getField("this$0") on the call stack.
+                mDelWriter.visitVarInsn(Opcodes.ALOAD, 0); // var 0 = this
+                mDelWriter.visitFieldInsn(Opcodes.GETFIELD,
+                        mClassName,                 // class where the field is defined
+                        "this$0",                   // field name
+                        outerType.getDescriptor()); // type of the field
+                maxStack++;
+                paramTypes.add(outerType);
+            }
+
+            // Push "this" for the instance method, which is always ALOAD 0
+            mDelWriter.visitVarInsn(Opcodes.ALOAD, 0);
+            maxStack++;
+            pushedArg0 = true;
+            paramTypes.add(Type.getObjectType(mClassName));
+        }
+
+        // Push all other arguments. Start at arg 1 if we already pushed 'this' above.
+        Type[] argTypes = Type.getArgumentTypes(mDesc);
+        int maxLocals = pushedArg0 ? 1 : 0;
+        for (Type t : argTypes) {
+            int size = t.getSize();
+            mDelWriter.visitVarInsn(t.getOpcode(Opcodes.ILOAD), maxLocals);
+            maxLocals += size;
+            maxStack += size;
+            paramTypes.add(t);
+        }
+
+        // Construct the descriptor of the delegate based on the parameters
+        // we pushed on the call stack. The return type remains unchanged.
+        String desc = Type.getMethodDescriptor(
+                Type.getReturnType(mDesc),
+                paramTypes.toArray(new Type[paramTypes.size()]));
+
+        // Invoke the static delegate
+        mDelWriter.visitMethodInsn(Opcodes.INVOKESTATIC,
+                delegateClassName,
+                mMethodName,
+                desc);
+
+        Type returnType = Type.getReturnType(mDesc);
+        mDelWriter.visitInsn(returnType.getOpcode(Opcodes.IRETURN));
+
+        mDelWriter.visitMaxs(maxStack, maxLocals);
+        mDelWriter.visitEnd();
+
+        // For debugging now. Maybe we should collect these and store them in
+        // a text file for helping create the delegates. We could also compare
+        // the text file to a golden and break the build on unsupported changes
+        // or regressions. Even better we could fancy-print something that looks
+        // like the expected Java method declaration.
+        mLog.debug("Delegate: %1$s # %2$s %3$s", delegateClassName, mMethodName, desc);
+    }
+
+    /* Pass down to visitor writer. In this implementation, either do nothing. */
+    public void visitCode() {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitCode();
+        }
+    }
+
+    /*
+     * visitMaxs is called just before visitEnd if there was any code to rewrite.
+     */
+    public void visitMaxs(int maxStack, int maxLocals) {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitMaxs(maxStack, maxLocals);
+        }
+    }
+
+    /** End of visiting. Generate the delegating code. */
+    public void visitEnd() {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitEnd();
+        }
+        generateDelegateCode();
+    }
+
+    /* Writes all annotation from the original method. */
+    public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
+        if (mOrgWriter != null) {
+            return mOrgWriter.visitAnnotation(desc, visible);
+        } else {
+            return null;
+        }
+    }
+
+    /* Writes all annotation default values from the original method. */
+    public AnnotationVisitor visitAnnotationDefault() {
+        if (mOrgWriter != null) {
+            return mOrgWriter.visitAnnotationDefault();
+        } else {
+            return null;
+        }
+    }
+
+    public AnnotationVisitor visitParameterAnnotation(int parameter, String desc,
+            boolean visible) {
+        if (mOrgWriter != null) {
+            return mOrgWriter.visitParameterAnnotation(parameter, desc, visible);
+        } else {
+            return null;
+        }
+    }
+
+    /* Writes all attributes from the original method. */
+    public void visitAttribute(Attribute attr) {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitAttribute(attr);
+        }
+    }
+
+    /*
+     * Only writes the first line number present in the original code so that source
+     * viewers can direct to the correct method, even if the content doesn't match.
+     */
+    public void visitLineNumber(int line, Label start) {
+        // Capture the first line values for the new delegate method
+        if (mDelegateLineNumber == null) {
+            mDelegateLineNumber = new Object[] { line, start };
+        }
+        if (mOrgWriter != null) {
+            mOrgWriter.visitLineNumber(line, start);
+        }
+    }
+
+    public void visitInsn(int opcode) {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitInsn(opcode);
+        }
+    }
+
+    public void visitLabel(Label label) {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitLabel(label);
+        }
+    }
+
+    public void visitTryCatchBlock(Label start, Label end, Label handler, String type) {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitTryCatchBlock(start, end, handler, type);
+        }
+    }
+
+    public void visitMethodInsn(int opcode, String owner, String name, String desc) {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitMethodInsn(opcode, owner, name, desc);
+        }
+    }
+
+    public void visitFieldInsn(int opcode, String owner, String name, String desc) {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitFieldInsn(opcode, owner, name, desc);
+        }
+    }
+
+    public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitFrame(type, nLocal, local, nStack, stack);
+        }
+    }
+
+    public void visitIincInsn(int var, int increment) {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitIincInsn(var, increment);
+        }
+    }
+
+    public void visitIntInsn(int opcode, int operand) {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitIntInsn(opcode, operand);
+        }
+    }
+
+    public void visitJumpInsn(int opcode, Label label) {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitJumpInsn(opcode, label);
+        }
+    }
+
+    public void visitLdcInsn(Object cst) {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitLdcInsn(cst);
+        }
+    }
+
+    public void visitLocalVariable(String name, String desc, String signature,
+            Label start, Label end, int index) {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitLocalVariable(name, desc, signature, start, end, index);
+        }
+    }
+
+    public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitLookupSwitchInsn(dflt, keys, labels);
+        }
+    }
+
+    public void visitMultiANewArrayInsn(String desc, int dims) {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitMultiANewArrayInsn(desc, dims);
+        }
+    }
+
+    public void visitTableSwitchInsn(int min, int max, Label dflt, Label[] labels) {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitTableSwitchInsn(min, max, dflt, labels);
+        }
+    }
+
+    public void visitTypeInsn(int opcode, String type) {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitTypeInsn(opcode, type);
+        }
+    }
+
+    public void visitVarInsn(int opcode, int var) {
+        if (mOrgWriter != null) {
+            mOrgWriter.visitVarInsn(opcode, var);
+        }
+    }
+
+}
diff --git a/tools/layoutlib/create/src/com/android/tools/layoutlib/create/ICreateInfo.java b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/ICreateInfo.java
new file mode 100644
index 0000000..40c1706
--- /dev/null
+++ b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/ICreateInfo.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.tools.layoutlib.create;
+
+/**
+ * Interface describing the work to be done by {@link AsmGenerator}.
+ */
+public interface ICreateInfo {
+
+    /**
+     * Returns the list of class from layoutlib_create to inject in layoutlib.
+     * The list can be empty but must not be null.
+     */
+    public abstract Class<?>[] getInjectedClasses();
+
+    /**
+     * Returns the list of methods to rewrite as delegates.
+     * The list can be empty but must not be null.
+     */
+    public abstract String[] getDelegateMethods();
+
+    /**
+     * Returns the list of classes on which to delegate all native methods.
+     * The list can be empty but must not be null.
+     */
+    public abstract String[] getDelegateClassNatives();
+
+    /**
+     * Returns The list of methods to stub out. Each entry must be in the form
+     * "package.package.OuterClass$InnerClass#MethodName".
+     * The list can be empty but must not be null.
+     */
+    public abstract String[] getOverriddenMethods();
+
+    /**
+     * Returns the list of classes to rename, must be an even list: the binary FQCN
+     * of class to replace followed by the new FQCN.
+     * The list can be empty but must not be null.
+     */
+    public abstract String[] getRenamedClasses();
+
+    /**
+     * Returns the list of classes for which the methods returning them should be deleted.
+     * The array contains a list of null terminated section starting with the name of the class
+     * to rename in which the methods are deleted, followed by a list of return types identifying
+     * the methods to delete.
+     * The list can be empty but must not be null.
+     */
+    public abstract String[] getDeleteReturns();
+
+}
diff --git a/tools/layoutlib/create/src/com/android/tools/layoutlib/create/Main.java b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/Main.java
index b30e9e5..c539578 100644
--- a/tools/layoutlib/create/src/com/android/tools/layoutlib/create/Main.java
+++ b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/Main.java
@@ -21,9 +21,36 @@
 import java.util.Set;
 
 
-
+/**
+ * Entry point for the layoutlib_create tool.
+ * <p/>
+ * The tool does not currently rely on any external configuration file.
+ * Instead the configuration is mostly done via the {@link CreateInfo} class.
+ * <p/>
+ * For a complete description of the tool and its implementation, please refer to
+ * the "README.txt" file at the root of this project.
+ * <p/>
+ * For a quick test, invoke this as follows:
+ * <pre>
+ * $ make layoutlib
+ * </pre>
+ * which does:
+ * <pre>
+ * $ make layoutlib_create &lt;bunch of framework jars&gt;
+ * $ java -jar out/host/linux-x86/framework/layoutlib_create.jar \
+ *        out/host/common/obj/JAVA_LIBRARIES/temp_layoutlib_intermediates/javalib.jar \
+ *        out/target/common/obj/JAVA_LIBRARIES/core_intermediates/classes.jar \
+ *        out/target/common/obj/JAVA_LIBRARIES/framework_intermediates/classes.jar
+ * </pre>
+ */
 public class Main {
 
+    public static class Options {
+        public boolean generatePublicAccess = true;
+    }
+
+    public static final Options sOptions = new Options();
+
     public static void main(String[] args) {
 
         Log log = new Log();
@@ -32,7 +59,7 @@
         String[] osDestJar = { null };
 
         if (!processArgs(log, args, osJarPath, osDestJar)) {
-            log.error("Usage: layoutlib_create [-v] output.jar input.jar ...");
+            log.error("Usage: layoutlib_create [-v] [-p] output.jar input.jar ...");
             System.exit(1);
         }
 
@@ -42,15 +69,12 @@
         }
 
         try {
-            AsmGenerator agen = new AsmGenerator(log, osDestJar[0],
-                    CreateInfo.INJECTED_CLASSES,
-                    CreateInfo.OVERRIDDEN_METHODS,
-                    CreateInfo.RENAMED_CLASSES,
-                    CreateInfo.REMOVED_METHODS
-            );
+            AsmGenerator agen = new AsmGenerator(log, osDestJar[0], new CreateInfo());
 
             AsmAnalyzer aa = new AsmAnalyzer(log, osJarPath, agen,
-                    new String[] { "android.view.View" },   // derived from
+                    new String[] {                          // derived from
+                        "android.view.View",
+                    },
                     new String[] {                          // include classes
                         "android.*", // for android.R
                         "android.util.*",
@@ -117,6 +141,8 @@
             String s = args[i];
             if (s.equals("-v")) {
                 log.setVerbose(true);
+            } else if (s.equals("-p")) {
+                sOptions.generatePublicAccess = false;
             } else if (!s.startsWith("-")) {
                 if (osDestJar[0] == null) {
                     osDestJar[0] = s;
diff --git a/tools/layoutlib/create/src/com/android/tools/layoutlib/create/StubMethodAdapter.java b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/StubMethodAdapter.java
index 9a57a4a..d70d028 100644
--- a/tools/layoutlib/create/src/com/android/tools/layoutlib/create/StubMethodAdapter.java
+++ b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/StubMethodAdapter.java
@@ -31,7 +31,7 @@
 
     private static String CONSTRUCTOR = "<init>";
     private static String CLASS_INIT = "<clinit>";
-    
+
     /** The parent method writer */
     private MethodVisitor mParentVisitor;
     /** The method return type. Can be null. */
@@ -40,7 +40,7 @@
     private String mInvokeSignature;
     /** Flag to output the first line number. */
     private boolean mOutputFirstLineNumber = true;
-    /** Flag that is true when implementing a constructor, to accept all original 
+    /** Flag that is true when implementing a constructor, to accept all original
      *  code calling the original super constructor. */
     private boolean mIsInitMethod = false;
 
@@ -55,12 +55,12 @@
         mInvokeSignature = invokeSignature;
         mIsStatic = isStatic;
         mIsNative = isNative;
-        
+
         if (CONSTRUCTOR.equals(methodName) || CLASS_INIT.equals(methodName)) {
             mIsInitMethod = true;
         }
     }
-    
+
     private void generateInvoke() {
         /* Generates the code:
          *  OverrideMethod.invoke("signature", mIsNative ? true : false, null or this);
@@ -188,7 +188,7 @@
         }
         mParentVisitor.visitMaxs(maxStack, maxLocals);
     }
-    
+
     /**
      * End of visiting.
      * For non-constructor, generate the messaging code and the return statement
@@ -250,6 +250,7 @@
                 generatePop();
                 generateInvoke();
                 mMessageGenerated = true;
+                //$FALL-THROUGH$
             default:
                 mParentVisitor.visitInsn(opcode);
             }
@@ -346,5 +347,5 @@
             mParentVisitor.visitVarInsn(opcode, var);
         }
     }
-    
+
 }
diff --git a/tools/layoutlib/create/src/com/android/tools/layoutlib/create/TransformClassAdapter.java b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/TransformClassAdapter.java
index e294d56..5a0a44a4 100644
--- a/tools/layoutlib/create/src/com/android/tools/layoutlib/create/TransformClassAdapter.java
+++ b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/TransformClassAdapter.java
@@ -26,7 +26,7 @@
 import java.util.Set;
 
 /**
- * Class adapter that can stub some or all of the methods of the class. 
+ * Class adapter that can stub some or all of the methods of the class.
  */
 class TransformClassAdapter extends ClassAdapter {
 
@@ -41,12 +41,12 @@
 
     /**
      * Creates a new class adapter that will stub some or all methods.
-     * @param logger 
-     * @param stubMethods 
+     * @param logger
+     * @param stubMethods  list of method signatures to always stub out
      * @param deleteReturns list of types that trigger the deletion of methods returning them.
      * @param className The name of the class being modified
      * @param cv The parent class writer visitor
-     * @param stubNativesOnly True if only native methods should be stubbed. False if all 
+     * @param stubNativesOnly True if only native methods should be stubbed. False if all
      *                        methods should be stubbed.
      * @param hasNative True if the method has natives, in which case its access should be
      *                  changed.
@@ -67,13 +67,15 @@
     @Override
     public void visit(int version, int access, String name,
             String signature, String superName, String[] interfaces) {
-        
+
         // This class might be being renamed.
         name = mClassName;
-        
+
         // remove protected or private and set as public
-        access = access & ~(Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED);
-        access |= Opcodes.ACC_PUBLIC;
+        if (Main.sOptions.generatePublicAccess) {
+            access = access & ~(Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED);
+            access |= Opcodes.ACC_PUBLIC;
+        }
         // remove final
         access = access & ~Opcodes.ACC_FINAL;
         // note: leave abstract classes as such
@@ -82,13 +84,15 @@
         mIsInterface = ((access & Opcodes.ACC_INTERFACE) != 0);
         super.visit(version, access, name, signature, superName, interfaces);
     }
-    
+
     /* Visits the header of an inner class. */
     @Override
     public void visitInnerClass(String name, String outerName, String innerName, int access) {
         // remove protected or private and set as public
-        access = access & ~(Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED);
-        access |= Opcodes.ACC_PUBLIC;
+        if (Main.sOptions.generatePublicAccess) {
+            access = access & ~(Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED);
+            access |= Opcodes.ACC_PUBLIC;
+        }
         // remove final
         access = access & ~Opcodes.ACC_FINAL;
         // note: leave abstract classes as such
@@ -101,7 +105,7 @@
     @Override
     public MethodVisitor visitMethod(int access, String name, String desc,
             String signature, String[] exceptions) {
-        
+
         if (mDeleteReturns != null) {
             Type t = Type.getReturnType(desc);
             if (t.getSort() == Type.OBJECT) {
@@ -117,8 +121,10 @@
         String methodSignature = mClassName.replace('/', '.') + "#" + name;
 
         // change access to public
-        access &= ~(Opcodes.ACC_PROTECTED | Opcodes.ACC_PRIVATE);
-        access |= Opcodes.ACC_PUBLIC;
+        if (Main.sOptions.generatePublicAccess) {
+            access &= ~(Opcodes.ACC_PROTECTED | Opcodes.ACC_PRIVATE);
+            access |= Opcodes.ACC_PUBLIC;
+        }
 
         // remove final
         access = access & ~Opcodes.ACC_FINAL;
@@ -130,16 +136,16 @@
             (mStubAll ||
              (access & Opcodes.ACC_NATIVE) != 0) ||
              mStubMethods.contains(methodSignature)) {
-            
+
             boolean isStatic = (access & Opcodes.ACC_STATIC) != 0;
             boolean isNative = (access & Opcodes.ACC_NATIVE) != 0;
 
             // remove abstract, final and native
             access = access & ~(Opcodes.ACC_ABSTRACT | Opcodes.ACC_FINAL | Opcodes.ACC_NATIVE);
-            
+
             String invokeSignature = methodSignature + desc;
             mLog.debug("  Stub: %s (%s)", invokeSignature, isNative ? "native" : "");
-            
+
             MethodVisitor mw = super.visitMethod(access, name, desc, signature, exceptions);
             return new StubMethodAdapter(mw, name, returnType(desc), invokeSignature,
                     isStatic, isNative);
@@ -149,15 +155,16 @@
             return super.visitMethod(access, name, desc, signature, exceptions);
         }
     }
-    
+
     /* Visits a field. Makes it public. */
     @Override
     public FieldVisitor visitField(int access, String name, String desc, String signature,
             Object value) {
         // change access to public
-        access &= ~(Opcodes.ACC_PROTECTED | Opcodes.ACC_PRIVATE);
-        access |= Opcodes.ACC_PUBLIC;
-        
+        if (Main.sOptions.generatePublicAccess) {
+            access &= ~(Opcodes.ACC_PROTECTED | Opcodes.ACC_PRIVATE);
+            access |= Opcodes.ACC_PUBLIC;
+        }
         return super.visitField(access, name, desc, signature, value);
     }
 
diff --git a/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/AsmAnalyzerTest.java b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/AsmAnalyzerTest.java
index 603284e..d6dba6a 100644
--- a/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/AsmAnalyzerTest.java
+++ b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/AsmAnalyzerTest.java
@@ -22,7 +22,6 @@
 import static org.junit.Assert.assertNotNull;
 
 import com.android.tools.layoutlib.create.AsmAnalyzer.DependencyVisitor;
-import com.android.tools.layoutlib.create.LogTest.MockLog;
 
 import org.junit.After;
 import org.junit.Before;
@@ -46,9 +45,9 @@
 
     @Before
     public void setUp() throws Exception {
-        mLog = new LogTest.MockLog();
+        mLog = new MockLog();
         URL url = this.getClass().getClassLoader().getResource("data/mock_android.jar");
-        
+
         mOsJarPath = new ArrayList<String>();
         mOsJarPath.add(url.getFile());
 
@@ -69,9 +68,9 @@
                 "mock_android.dummy.InnerTest$DerivingClass",
                 "mock_android.dummy.InnerTest$MyGenerics1",
                 "mock_android.dummy.InnerTest$MyIntEnum",
-                "mock_android.dummy.InnerTest$MyStaticInnerClass",   
-                "mock_android.dummy.InnerTest$NotStaticInner1", 
-                "mock_android.dummy.InnerTest$NotStaticInner2",  
+                "mock_android.dummy.InnerTest$MyStaticInnerClass",
+                "mock_android.dummy.InnerTest$NotStaticInner1",
+                "mock_android.dummy.InnerTest$NotStaticInner2",
                 "mock_android.view.View",
                 "mock_android.view.ViewGroup",
                 "mock_android.view.ViewGroup$LayoutParams",
@@ -83,7 +82,7 @@
             },
             map.keySet().toArray());
     }
-    
+
     @Test
     public void testFindClass() throws IOException, LogAbortException {
         Map<String, ClassReader> zipClasses = mAa.parseZip(mOsJarPath);
@@ -91,7 +90,7 @@
 
         ClassReader cr = mAa.findClass("mock_android.view.ViewGroup$LayoutParams",
                 zipClasses, found);
-        
+
         assertNotNull(cr);
         assertEquals("mock_android/view/ViewGroup$LayoutParams", cr.getClassName());
         assertArrayEquals(new String[] { "mock_android.view.ViewGroup$LayoutParams" },
@@ -172,14 +171,14 @@
                 "mock_android.widget.TableLayout",
             },
             found.keySet().toArray());
-        
+
         for (String key : found.keySet()) {
             ClassReader value = found.get(key);
             assertNotNull("No value for " + key, value);
             assertEquals(key, AsmAnalyzer.classReaderToClassName(value));
         }
     }
-    
+
     @Test
     public void testDependencyVisitor() throws IOException, LogAbortException {
         Map<String, ClassReader> zipClasses = mAa.parseZip(mOsJarPath);
@@ -190,7 +189,7 @@
 
         ClassReader cr = mAa.findClass("mock_android.widget.TableLayout", zipClasses, keep);
         DependencyVisitor visitor = mAa.getVisitor(zipClasses, keep, new_keep, in_deps, out_deps);
-        
+
         // get first level dependencies
         cr.accept(visitor, 0 /* flags */);
 
diff --git a/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/AsmGeneratorTest.java b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/AsmGeneratorTest.java
index 7cdf79a..f4ff389 100644
--- a/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/AsmGeneratorTest.java
+++ b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/AsmGeneratorTest.java
@@ -20,8 +20,6 @@
 
 import static org.junit.Assert.assertArrayEquals;
 
-import com.android.tools.layoutlib.create.LogTest.MockLog;
-
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -44,9 +42,9 @@
 
     @Before
     public void setUp() throws Exception {
-        mLog = new LogTest.MockLog();
+        mLog = new MockLog();
         URL url = this.getClass().getClassLoader().getResource("data/mock_android.jar");
-        
+
         mOsJarPath = new ArrayList<String>();
         mOsJarPath.add(url.getFile());
 
@@ -65,16 +63,41 @@
 
     @Test
     public void testClassRenaming() throws IOException, LogAbortException {
-        
-        AsmGenerator agen = new AsmGenerator(mLog, mOsDestJar,
-            null, // classes to inject in the final JAR
-            null,  // methods to force override
-            new String[] {  // classes to rename (so that we can replace them)
-                "mock_android.view.View", "mock_android.view._Original_View",
-                "not.an.actual.ClassName", "anoter.fake.NewClassName",
-            },
-            null // methods deleted from their return type.
-            );
+
+        ICreateInfo ci = new ICreateInfo() {
+            public Class<?>[] getInjectedClasses() {
+                // classes to inject in the final JAR
+                return new Class<?>[0];
+            }
+
+            public String[] getDelegateMethods() {
+                return new String[0];
+            }
+
+            public String[] getDelegateClassNatives() {
+                return new String[0];
+            }
+
+            public String[] getOverriddenMethods() {
+                // methods to force override
+                return new String[0];
+            }
+
+            public String[] getRenamedClasses() {
+                // classes to rename (so that we can replace them)
+                return new String[] {
+                        "mock_android.view.View", "mock_android.view._Original_View",
+                        "not.an.actual.ClassName", "anoter.fake.NewClassName",
+                };
+            }
+
+            public String[] getDeleteReturns() {
+                 // methods deleted from their return type.
+                return new String[0];
+            }
+        };
+
+        AsmGenerator agen = new AsmGenerator(mLog, mOsDestJar, ci);
 
         AsmAnalyzer aa = new AsmAnalyzer(mLog, mOsJarPath, agen,
                 null,                 // derived from
@@ -83,7 +106,7 @@
                 });
         aa.analyze();
         agen.generate();
-        
+
         Set<String> notRenamed = agen.getClassesNotRenamed();
         assertArrayEquals(new String[] { "not/an/actual/ClassName" }, notRenamed.toArray());
     }
diff --git a/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/ClassHasNativeVisitorTest.java b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/ClassHasNativeVisitorTest.java
index d6916ae..0135c40 100644
--- a/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/ClassHasNativeVisitorTest.java
+++ b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/ClassHasNativeVisitorTest.java
@@ -33,8 +33,9 @@
     @Test
     public void testHasNative() throws IOException {
         MockClassHasNativeVisitor cv = new MockClassHasNativeVisitor();
-        ClassReader cr = new ClassReader(
-                "com.android.tools.layoutlib.create.ClassHasNativeVisitorTest$ClassWithNative");
+        String className =
+                this.getClass().getCanonicalName() + "$" + ClassWithNative.class.getSimpleName();
+        ClassReader cr = new ClassReader(className);
 
         cr.accept(cv, 0 /* flags */);
         assertArrayEquals(new String[] { "native_method" }, cv.getMethodsFound());
@@ -44,14 +45,17 @@
     @Test
     public void testHasNoNative() throws IOException {
         MockClassHasNativeVisitor cv = new MockClassHasNativeVisitor();
-        ClassReader cr = new ClassReader(
-                "com.android.tools.layoutlib.create.ClassHasNativeVisitorTest$ClassWithoutNative");
+        String className =
+            this.getClass().getCanonicalName() + "$" + ClassWithoutNative.class.getSimpleName();
+        ClassReader cr = new ClassReader(className);
 
         cr.accept(cv, 0 /* flags */);
         assertArrayEquals(new String[0], cv.getMethodsFound());
         assertFalse(cv.hasNativeMethods());
     }
 
+    //-------
+
     /**
      * Overrides {@link ClassHasNativeVisitor} to collec the name of the native methods found.
      */
diff --git a/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/DelegateClassAdapterTest.java b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/DelegateClassAdapterTest.java
new file mode 100644
index 0000000..6e120ce
--- /dev/null
+++ b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/DelegateClassAdapterTest.java
@@ -0,0 +1,463 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.tools.layoutlib.create;
+
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import com.android.tools.layoutlib.create.dataclass.ClassWithNative;
+import com.android.tools.layoutlib.create.dataclass.OuterClass;
+import com.android.tools.layoutlib.create.dataclass.OuterClass.InnerClass;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.objectweb.asm.ClassReader;
+import org.objectweb.asm.ClassVisitor;
+import org.objectweb.asm.ClassWriter;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+public class DelegateClassAdapterTest {
+
+    private MockLog mLog;
+
+    private static final String NATIVE_CLASS_NAME = ClassWithNative.class.getCanonicalName();
+    private static final String OUTER_CLASS_NAME = OuterClass.class.getCanonicalName();
+    private static final String INNER_CLASS_NAME = OuterClass.class.getCanonicalName() + "$" +
+                                                   InnerClass.class.getSimpleName();
+
+    @Before
+    public void setUp() throws Exception {
+        mLog = new MockLog();
+        mLog.setVerbose(true); // capture debug error too
+    }
+
+    /**
+     * Tests that a class not being modified still works.
+     */
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testNoOp() throws Throwable {
+        // create an instance of the class that will be modified
+        // (load the class in a distinct class loader so that we can trash its definition later)
+        ClassLoader cl1 = new ClassLoader(this.getClass().getClassLoader()) { };
+        Class<ClassWithNative> clazz1 = (Class<ClassWithNative>) cl1.loadClass(NATIVE_CLASS_NAME);
+        ClassWithNative instance1 = clazz1.newInstance();
+        assertEquals(42, instance1.add(20, 22));
+        try {
+            instance1.callNativeInstance(10, 3.1415, new Object[0] );
+            fail("Test should have failed to invoke callTheNativeMethod [1]");
+        } catch (UnsatisfiedLinkError e) {
+            // This is expected to fail since the native method is not implemented.
+        }
+
+        // Now process it but tell the delegate to not modify any method
+        ClassWriter cw = new ClassWriter(0 /*flags*/);
+
+        HashSet<String> delegateMethods = new HashSet<String>();
+        String internalClassName = NATIVE_CLASS_NAME.replace('.', '/');
+        DelegateClassAdapter cv = new DelegateClassAdapter(
+                mLog, cw, internalClassName, delegateMethods);
+
+        ClassReader cr = new ClassReader(NATIVE_CLASS_NAME);
+        cr.accept(cv, 0 /* flags */);
+
+        // Load the generated class in a different class loader and try it again
+
+        ClassLoader2 cl2 = null;
+        try {
+            cl2 = new ClassLoader2() {
+                @Override
+                public void testModifiedInstance() throws Exception {
+                    Class<?> clazz2 = loadClass(NATIVE_CLASS_NAME);
+                    Object i2 = clazz2.newInstance();
+                    assertNotNull(i2);
+                    assertEquals(42, callAdd(i2, 20, 22));
+
+                    try {
+                        callCallNativeInstance(i2, 10, 3.1415, new Object[0]);
+                        fail("Test should have failed to invoke callTheNativeMethod [2]");
+                    } catch (InvocationTargetException e) {
+                        // This is expected to fail since the native method has NOT been
+                        // overridden here.
+                        assertEquals(UnsatisfiedLinkError.class, e.getCause().getClass());
+                    }
+
+                    // Check that the native method does NOT have the new annotation
+                    Method[] m = clazz2.getDeclaredMethods();
+                    assertEquals("native_instance", m[2].getName());
+                    assertTrue(Modifier.isNative(m[2].getModifiers()));
+                    Annotation[] a = m[2].getAnnotations();
+                    assertEquals(0, a.length);
+                }
+            };
+            cl2.add(NATIVE_CLASS_NAME, cw);
+            cl2.testModifiedInstance();
+        } catch (Throwable t) {
+            throw dumpGeneratedClass(t, cl2);
+        }
+    }
+
+    /**
+     * {@link DelegateMethodAdapter2} does not support overriding constructors yet,
+     * so this should fail with an {@link UnsupportedOperationException}.
+     *
+     * Although not tested here, the message of the exception should contain the
+     * constructor signature.
+     */
+    @Test(expected=UnsupportedOperationException.class)
+    public void testConstructorsNotSupported() throws IOException {
+        ClassWriter cw = new ClassWriter(0 /*flags*/);
+
+        String internalClassName = NATIVE_CLASS_NAME.replace('.', '/');
+
+        HashSet<String> delegateMethods = new HashSet<String>();
+        delegateMethods.add("<init>");
+        DelegateClassAdapter cv = new DelegateClassAdapter(
+                mLog, cw, internalClassName, delegateMethods);
+
+        ClassReader cr = new ClassReader(NATIVE_CLASS_NAME);
+        cr.accept(cv, 0 /* flags */);
+    }
+
+    @Test
+    public void testDelegateNative() throws Throwable {
+        ClassWriter cw = new ClassWriter(0 /*flags*/);
+        String internalClassName = NATIVE_CLASS_NAME.replace('.', '/');
+
+        HashSet<String> delegateMethods = new HashSet<String>();
+        delegateMethods.add(DelegateClassAdapter.ALL_NATIVES);
+        DelegateClassAdapter cv = new DelegateClassAdapter(
+                mLog, cw, internalClassName, delegateMethods);
+
+        ClassReader cr = new ClassReader(NATIVE_CLASS_NAME);
+        cr.accept(cv, 0 /* flags */);
+
+        // Load the generated class in a different class loader and try it
+        ClassLoader2 cl2 = null;
+        try {
+            cl2 = new ClassLoader2() {
+                @Override
+                public void testModifiedInstance() throws Exception {
+                    Class<?> clazz2 = loadClass(NATIVE_CLASS_NAME);
+                    Object i2 = clazz2.newInstance();
+                    assertNotNull(i2);
+
+                    // Use reflection to access inner methods
+                    assertEquals(42, callAdd(i2, 20, 22));
+
+                     Object[] objResult = new Object[] { null };
+                     int result = callCallNativeInstance(i2, 10, 3.1415, objResult);
+                     assertEquals((int)(10 + 3.1415), result);
+                     assertSame(i2, objResult[0]);
+
+                     // Check that the native method now has the new annotation and is not native
+                     Method[] m = clazz2.getDeclaredMethods();
+                     assertEquals("native_instance", m[2].getName());
+                     assertFalse(Modifier.isNative(m[2].getModifiers()));
+                     Annotation[] a = m[2].getAnnotations();
+                     assertEquals("LayoutlibDelegate", a[0].annotationType().getSimpleName());
+                }
+            };
+            cl2.add(NATIVE_CLASS_NAME, cw);
+            cl2.testModifiedInstance();
+        } catch (Throwable t) {
+            throw dumpGeneratedClass(t, cl2);
+        }
+    }
+
+    @Test
+    public void testDelegateInner() throws Throwable {
+        // We'll delegate the "get" method of both the inner and outer class.
+        HashSet<String> delegateMethods = new HashSet<String>();
+        delegateMethods.add("get");
+        delegateMethods.add("privateMethod");
+
+        // Generate the delegate for the outer class.
+        ClassWriter cwOuter = new ClassWriter(0 /*flags*/);
+        String outerClassName = OUTER_CLASS_NAME.replace('.', '/');
+        DelegateClassAdapter cvOuter = new DelegateClassAdapter(
+                mLog, cwOuter, outerClassName, delegateMethods);
+        ClassReader cr = new ClassReader(OUTER_CLASS_NAME);
+        cr.accept(cvOuter, 0 /* flags */);
+
+        // Generate the delegate for the inner class.
+        ClassWriter cwInner = new ClassWriter(0 /*flags*/);
+        String innerClassName = INNER_CLASS_NAME.replace('.', '/');
+        DelegateClassAdapter cvInner = new DelegateClassAdapter(
+                mLog, cwInner, innerClassName, delegateMethods);
+        cr = new ClassReader(INNER_CLASS_NAME);
+        cr.accept(cvInner, 0 /* flags */);
+
+        // Load the generated classes in a different class loader and try them
+        ClassLoader2 cl2 = null;
+        try {
+            cl2 = new ClassLoader2() {
+                @Override
+                public void testModifiedInstance() throws Exception {
+
+                    // Check the outer class
+                    Class<?> outerClazz2 = loadClass(OUTER_CLASS_NAME);
+                    Object o2 = outerClazz2.newInstance();
+                    assertNotNull(o2);
+
+                    // The original Outer.get returns 1+10+20,
+                    // but the delegate makes it return 4+10+20
+                    assertEquals(4+10+20, callGet(o2, 10, 20));
+                    assertEquals(1+10+20, callGet_Original(o2, 10, 20));
+
+                    // The original Outer has a private method that is
+                    // delegated. We should be able to call both the delegate
+                    // and the original (which is now public).
+                    assertEquals("outerPrivateMethod",
+                                 callMethod(o2, "privateMethod_Original", false /*makePublic*/));
+
+                    // The original method is private, so by default we can't access it
+                    boolean gotIllegalAccessException = false;
+                    try {
+                         callMethod(o2, "privateMethod", false /*makePublic*/);
+                    } catch(IllegalAccessException e) {
+                        gotIllegalAccessException = true;
+                    }
+                    assertTrue(gotIllegalAccessException);
+                    // Try again, but now making it accessible
+                    assertEquals("outerPrivate_Delegate",
+                            callMethod(o2, "privateMethod", true /*makePublic*/));
+
+                    // Check the inner class. Since it's not a static inner class, we need
+                    // to use the hidden constructor that takes the outer class as first parameter.
+                    Class<?> innerClazz2 = loadClass(INNER_CLASS_NAME);
+                    Constructor<?> innerCons = innerClazz2.getConstructor(
+                                                                new Class<?>[] { outerClazz2 });
+                    Object i2 = innerCons.newInstance(new Object[] { o2 });
+                    assertNotNull(i2);
+
+                    // The original Inner.get returns 3+10+20,
+                    // but the delegate makes it return 6+10+20
+                    assertEquals(6+10+20, callGet(i2, 10, 20));
+                    assertEquals(3+10+20, callGet_Original(i2, 10, 20));
+                }
+            };
+            cl2.add(OUTER_CLASS_NAME, cwOuter.toByteArray());
+            cl2.add(INNER_CLASS_NAME, cwInner.toByteArray());
+            cl2.testModifiedInstance();
+        } catch (Throwable t) {
+            throw dumpGeneratedClass(t, cl2);
+        }
+    }
+
+    //-------
+
+    /**
+     * A class loader than can define and instantiate our modified classes.
+     * <p/>
+     * The trick here is that this class loader will test our <em>modified</em> version
+     * of the classes, the one with the delegate calls.
+     * <p/>
+     * Trying to do so in the original class loader generates all sort of link issues because
+     * there are 2 different definitions of the same class name. This class loader will
+     * define and load the class when requested by name and provide helpers to access the
+     * instance methods via reflection.
+     */
+    private abstract class ClassLoader2 extends ClassLoader {
+
+        private final Map<String, byte[]> mClassDefs = new HashMap<String, byte[]>();
+
+        public ClassLoader2() {
+            super(null);
+        }
+
+        public ClassLoader2 add(String className, byte[] definition) {
+            mClassDefs.put(className, definition);
+            return this;
+        }
+
+        public ClassLoader2 add(String className, ClassWriter rewrittenClass) {
+            mClassDefs.put(className, rewrittenClass.toByteArray());
+            return this;
+        }
+
+        private Set<Entry<String, byte[]>> getByteCode() {
+            return mClassDefs.entrySet();
+        }
+
+        @SuppressWarnings("unused")
+        @Override
+        protected Class<?> findClass(String name) throws ClassNotFoundException {
+            try {
+                return super.findClass(name);
+            } catch (ClassNotFoundException e) {
+
+                byte[] def = mClassDefs.get(name);
+                if (def != null) {
+                    // Load the modified ClassWithNative from its bytes representation.
+                    return defineClass(name, def, 0, def.length);
+                }
+
+                try {
+                    // Load everything else from the original definition into the new class loader.
+                    ClassReader cr = new ClassReader(name);
+                    ClassWriter cw = new ClassWriter(0);
+                    cr.accept(cw, 0);
+                    byte[] bytes = cw.toByteArray();
+                    return defineClass(name, bytes, 0, bytes.length);
+
+                } catch (IOException ioe) {
+                    throw new RuntimeException(ioe);
+                }
+            }
+        }
+
+        /**
+         * Accesses {@link OuterClass#get} or {@link InnerClass#get}via reflection.
+         */
+        public int callGet(Object instance, int a, long b) throws Exception {
+            Method m = instance.getClass().getMethod("get",
+                    new Class<?>[] { int.class, long.class } );
+
+            Object result = m.invoke(instance, new Object[] { a, b });
+            return ((Integer) result).intValue();
+        }
+
+        /**
+         * Accesses the "_Original" methods for {@link OuterClass#get}
+         * or {@link InnerClass#get}via reflection.
+         */
+        public int callGet_Original(Object instance, int a, long b) throws Exception {
+            Method m = instance.getClass().getMethod("get_Original",
+                    new Class<?>[] { int.class, long.class } );
+
+            Object result = m.invoke(instance, new Object[] { a, b });
+            return ((Integer) result).intValue();
+        }
+
+        /**
+         * Accesses the any declared method that takes no parameter via reflection.
+         */
+        @SuppressWarnings("unchecked")
+        public <T> T callMethod(Object instance, String methodName, boolean makePublic) throws Exception {
+            Method m = instance.getClass().getDeclaredMethod(methodName, (Class<?>[])null);
+
+            boolean wasAccessible = m.isAccessible();
+            if (makePublic && !wasAccessible) {
+                m.setAccessible(true);
+            }
+
+            Object result = m.invoke(instance, (Object[])null);
+
+            if (makePublic && !wasAccessible) {
+                m.setAccessible(false);
+            }
+
+            return (T) result;
+        }
+
+        /**
+         * Accesses {@link ClassWithNative#add(int, int)} via reflection.
+         */
+        public int callAdd(Object instance, int a, int b) throws Exception {
+            Method m = instance.getClass().getMethod("add",
+                    new Class<?>[] { int.class, int.class });
+
+            Object result = m.invoke(instance, new Object[] { a, b });
+            return ((Integer) result).intValue();
+        }
+
+        /**
+         * Accesses {@link ClassWithNative#callNativeInstance(int, double, Object[])}
+         * via reflection.
+         */
+        public int callCallNativeInstance(Object instance, int a, double d, Object[] o)
+                throws Exception {
+            Method m = instance.getClass().getMethod("callNativeInstance",
+                    new Class<?>[] { int.class, double.class, Object[].class });
+
+            Object result = m.invoke(instance, new Object[] { a, d, o });
+            return ((Integer) result).intValue();
+        }
+
+        public abstract void testModifiedInstance() throws Exception;
+    }
+
+    /**
+     * For debugging, it's useful to dump the content of the generated classes
+     * along with the exception that was generated.
+     *
+     * However to make it work you need to pull in the org.objectweb.asm.util.TraceClassVisitor
+     * class and associated utilities which are found in the ASM source jar. Since we don't
+     * want that dependency in the source code, we only put it manually for development and
+     * access the TraceClassVisitor via reflection if present.
+     *
+     * @param t The exception thrown by {@link ClassLoader2#testModifiedInstance()}
+     * @param cl2 The {@link ClassLoader2} instance with the generated bytecode.
+     * @return Either original {@code t} or a new wrapper {@link Throwable}
+     */
+    private Throwable dumpGeneratedClass(Throwable t, ClassLoader2 cl2) {
+        try {
+            // For debugging, dump the bytecode of the class in case of unexpected error
+            // if we can find the TraceClassVisitor class.
+            Class<?> tcvClass = Class.forName("org.objectweb.asm.util.TraceClassVisitor");
+
+            StringBuilder sb = new StringBuilder();
+            sb.append('\n').append(t.getClass().getCanonicalName());
+            if (t.getMessage() != null) {
+                sb.append(": ").append(t.getMessage());
+              }
+
+            for (Entry<String, byte[]> entry : cl2.getByteCode()) {
+                String className = entry.getKey();
+                byte[] bytes = entry.getValue();
+
+                StringWriter sw = new StringWriter();
+                PrintWriter pw = new PrintWriter(sw);
+                // next 2 lines do: TraceClassVisitor tcv = new TraceClassVisitor(pw);
+                Constructor<?> cons = tcvClass.getConstructor(new Class<?>[] { pw.getClass() });
+                Object tcv = cons.newInstance(new Object[] { pw });
+                ClassReader cr2 = new ClassReader(bytes);
+                cr2.accept((ClassVisitor) tcv, 0 /* flags */);
+
+                sb.append("\nBytecode dump: <").append(className).append(">:\n")
+                  .append(sw.toString());
+            }
+
+            // Re-throw exception with new message
+            RuntimeException ex = new RuntimeException(sb.toString(), t);
+            return ex;
+        } catch (Throwable ignore) {
+            // In case of problem, just throw the original exception as-is.
+            return t;
+        }
+    }
+
+}
diff --git a/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/LogTest.java b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/LogTest.java
index 3f13158..1a5f653 100644
--- a/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/LogTest.java
+++ b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/LogTest.java
@@ -24,33 +24,8 @@
 
 public class LogTest {
 
-    public static class MockLog extends Log {
-        StringBuilder mOut = new StringBuilder();
-        StringBuilder mErr = new StringBuilder();
-        
-        public String getOut() {
-            return mOut.toString();
-        }
-        
-        public String getErr() {
-            return mErr.toString();
-        }
-        
-        @Override
-        protected void outPrintln(String msg) {
-            mOut.append(msg);
-            mOut.append('\n');
-        }
-        
-        @Override
-        protected void errPrintln(String msg) {
-            mErr.append(msg);
-            mErr.append('\n');
-        }
-    }
-
     private MockLog mLog;
-    
+
     @Before
     public void setUp() throws Exception {
         mLog = new MockLog();
diff --git a/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/MockLog.java b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/MockLog.java
new file mode 100644
index 0000000..de750a3
--- /dev/null
+++ b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/MockLog.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.tools.layoutlib.create;
+
+
+public class MockLog extends Log {
+    StringBuilder mOut = new StringBuilder();
+    StringBuilder mErr = new StringBuilder();
+
+    public String getOut() {
+        return mOut.toString();
+    }
+
+    public String getErr() {
+        return mErr.toString();
+    }
+
+    @Override
+    protected void outPrintln(String msg) {
+        mOut.append(msg);
+        mOut.append('\n');
+    }
+
+    @Override
+    protected void errPrintln(String msg) {
+        mErr.append(msg);
+        mErr.append('\n');
+    }
+}
diff --git a/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/dataclass/ClassWithNative.java b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/dataclass/ClassWithNative.java
new file mode 100644
index 0000000..c314853
--- /dev/null
+++ b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/dataclass/ClassWithNative.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.tools.layoutlib.create.dataclass;
+
+import com.android.tools.layoutlib.create.DelegateClassAdapterTest;
+
+/**
+ * Dummy test class with a native method.
+ * The native method is not defined and any attempt to invoke it will
+ * throw an {@link UnsatisfiedLinkError}.
+ *
+ * Used by {@link DelegateClassAdapterTest}.
+ */
+public class ClassWithNative {
+    public ClassWithNative() {
+    }
+
+    public int add(int a, int b) {
+        return a + b;
+    }
+
+    // Note: it's good to have a long or double for testing parameters since they take
+    // 2 slots in the stack/locals maps.
+
+    public int callNativeInstance(int a, double d, Object[] o) {
+        return native_instance(a, d, o);
+    }
+
+    private native int native_instance(int a, double d, Object[] o);
+}
+
diff --git a/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/dataclass/ClassWithNative_Delegate.java b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/dataclass/ClassWithNative_Delegate.java
new file mode 100644
index 0000000..a3d4dc6
--- /dev/null
+++ b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/dataclass/ClassWithNative_Delegate.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.tools.layoutlib.create.dataclass;
+
+import com.android.tools.layoutlib.create.DelegateClassAdapterTest;
+
+/**
+ * The delegate that receives the call to {@link ClassWithNative_Delegate}'s overridden methods.
+ *
+ * Used by {@link DelegateClassAdapterTest}.
+ */
+public class ClassWithNative_Delegate {
+    public static int native_instance(ClassWithNative instance, int a, double d, Object[] o) {
+        if (o != null && o.length > 0) {
+            o[0] = instance;
+        }
+        return (int)(a + d);
+    }
+}
+
diff --git a/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/dataclass/OuterClass.java b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/dataclass/OuterClass.java
new file mode 100644
index 0000000..f083e76
--- /dev/null
+++ b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/dataclass/OuterClass.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.tools.layoutlib.create.dataclass;
+
+import com.android.tools.layoutlib.create.DelegateClassAdapterTest;
+
+/**
+ * Test class with an inner class.
+ *
+ * Used by {@link DelegateClassAdapterTest}.
+ */
+public class OuterClass {
+    private int mOuterValue = 1;
+    public OuterClass() {
+    }
+
+    // Outer.get returns 1 + a + b
+    // Note: it's good to have a long or double for testing parameters since they take
+    // 2 slots in the stack/locals maps.
+    public int get(int a, long b) {
+        return mOuterValue + a + (int) b;
+    }
+
+    public class InnerClass {
+        public InnerClass() {
+        }
+
+        // Inner.get returns 2 + 1 + a + b
+        public int get(int a, long b) {
+            return 2 + mOuterValue + a + (int) b;
+        }
+    }
+
+    @SuppressWarnings("unused")
+    private String privateMethod() {
+        return "outerPrivateMethod";
+    }
+}
+
diff --git a/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/dataclass/OuterClass_Delegate.java b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/dataclass/OuterClass_Delegate.java
new file mode 100644
index 0000000..774be8e
--- /dev/null
+++ b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/dataclass/OuterClass_Delegate.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.tools.layoutlib.create.dataclass;
+
+import com.android.tools.layoutlib.create.DelegateClassAdapterTest;
+
+/**
+ * Used by {@link DelegateClassAdapterTest}.
+ */
+public class OuterClass_Delegate {
+    // The delegate override of Outer.get returns 4 + a + b
+    public static int get(OuterClass instance, int a, long b) {
+        return 4 + a + (int) b;
+    }
+
+    public static String privateMethod(OuterClass instance) {
+        return "outerPrivate_Delegate";
+    }
+}
+
diff --git a/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/dataclass/OuterClass_InnerClass_Delegate.java b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/dataclass/OuterClass_InnerClass_Delegate.java
new file mode 100644
index 0000000..b472220
--- /dev/null
+++ b/tools/layoutlib/create/tests/com/android/tools/layoutlib/create/dataclass/OuterClass_InnerClass_Delegate.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.tools.layoutlib.create.dataclass;
+
+import com.android.tools.layoutlib.create.DelegateClassAdapterTest;
+import com.android.tools.layoutlib.create.dataclass.OuterClass.InnerClass;
+
+/**
+ * Used by {@link DelegateClassAdapterTest}.
+ */
+public class OuterClass_InnerClass_Delegate {
+    // The delegate override of Inner.get return 6 + a + b
+    public static int get(OuterClass outer, InnerClass inner, int a, long b) {
+        return 6 + a + (int) b;
+    }
+}
diff --git a/voip/jni/rtp/AudioGroup.cpp b/voip/jni/rtp/AudioGroup.cpp
index 2cbd023..ae071ce 100644
--- a/voip/jni/rtp/AudioGroup.cpp
+++ b/voip/jni/rtp/AudioGroup.cpp
@@ -30,6 +30,7 @@
 
 #define LOG_TAG "AudioGroup"
 #include <cutils/atomic.h>
+#include <cutils/properties.h>
 #include <utils/Log.h>
 #include <utils/Errors.h>
 #include <utils/RefBase.h>
@@ -619,6 +620,14 @@
     if (mode < 0 || mode > LAST_MODE) {
         return false;
     }
+    //FIXME: temporary code to overcome echo and mic gain issues on herring board.
+    // Must be modified/removed when proper support for voice processing query and control
+    // is included in audio framework
+    char value[PROPERTY_VALUE_MAX];
+    property_get("ro.product.board", value, "");
+    if (mode == NORMAL && !strcmp(value, "herring")) {
+        mode = ECHO_SUPPRESSION;
+    }
     if (mode == ECHO_SUPPRESSION && AudioSystem::getParameters(
         0, String8("ec_supported")) == "ec_supported=yes") {
         mode = NORMAL;
diff --git a/wifi/java/android/net/wifi/WifiStateTracker.java b/wifi/java/android/net/wifi/WifiStateTracker.java
index bf2d033..fedf3bb 100644
--- a/wifi/java/android/net/wifi/WifiStateTracker.java
+++ b/wifi/java/android/net/wifi/WifiStateTracker.java
@@ -23,6 +23,18 @@
 import static android.net.wifi.WifiManager.WIFI_STATE_UNKNOWN;
 
 import android.app.ActivityManagerNative;
+import android.app.AlarmManager;
+import android.app.Notification;
+import android.app.PendingIntent;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.BluetoothHeadset;
+import android.bluetooth.BluetoothA2dp;
+import android.content.BroadcastReceiver;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.database.ContentObserver;
 import android.net.NetworkInfo;
 import android.net.NetworkStateTracker;
 import android.net.DhcpInfo;
@@ -32,8 +44,10 @@
 import android.net.NetworkInfo.State;
 import android.os.Message;
 import android.os.Parcelable;
+import android.os.PowerManager;
 import android.os.Handler;
 import android.os.HandlerThread;
+import android.os.SystemClock;
 import android.os.SystemProperties;
 import android.os.Looper;
 import android.os.RemoteException;
@@ -44,15 +58,6 @@
 import android.util.EventLog;
 import android.util.Log;
 import android.util.Config;
-import android.app.Notification;
-import android.app.PendingIntent;
-import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothHeadset;
-import android.bluetooth.BluetoothA2dp;
-import android.content.ContentResolver;
-import android.content.Intent;
-import android.content.Context;
-import android.database.ContentObserver;
 import com.android.internal.app.IBatteryStats;
 
 import java.net.UnknownHostException;
@@ -91,15 +96,16 @@
     private static final int EVENT_INTERFACE_CONFIGURATION_FAILED    = 7;
     private static final int EVENT_POLL_INTERVAL                     = 8;
     private static final int EVENT_DHCP_START                        = 9;
-    private static final int EVENT_DEFERRED_DISCONNECT               = 10;
-    private static final int EVENT_DEFERRED_RECONNECT                = 11;
+    private static final int EVENT_DHCP_RENEW                        = 10;
+    private static final int EVENT_DEFERRED_DISCONNECT               = 11;
+    private static final int EVENT_DEFERRED_RECONNECT                = 12;
     /**
      * The driver is started or stopped. The object will be the state: true for
      * started, false for stopped.
      */
-    private static final int EVENT_DRIVER_STATE_CHANGED              = 12;
-    private static final int EVENT_PASSWORD_KEY_MAY_BE_INCORRECT     = 13;
-    private static final int EVENT_MAYBE_START_SCAN_POST_DISCONNECT  = 14;
+    private static final int EVENT_DRIVER_STATE_CHANGED              = 13;
+    private static final int EVENT_PASSWORD_KEY_MAY_BE_INCORRECT     = 14;
+    private static final int EVENT_MAYBE_START_SCAN_POST_DISCONNECT  = 15;
 
     /**
      * The driver state indication.
@@ -160,6 +166,9 @@
      */
     private static final int DEFAULT_MAX_DHCP_RETRIES = 9;
 
+    //Minimum dhcp lease duration for renewal
+    private static final int MIN_RENEWAL_TIME_SECS = 5 * 60; //5 minutes
+
     private static final int DRIVER_POWER_MODE_AUTO = 0;
     private static final int DRIVER_POWER_MODE_ACTIVE = 1;
 
@@ -218,6 +227,15 @@
     private boolean mUseStaticIp = false;
     private int mReconnectCount;
 
+    private AlarmManager mAlarmManager;
+    private PendingIntent mDhcpRenewalIntent;
+    private PowerManager.WakeLock mDhcpRenewWakeLock;
+    private static final String WAKELOCK_TAG = "*wifi*";
+
+    private static final int DHCP_RENEW = 0;
+    private static final String ACTION_DHCP_RENEW = "android.net.wifi.DHCP_RENEW";
+
+
     /* Tracks if any network in the configuration is disabled */
     private AtomicBoolean mIsAnyNetworkDisabled = new AtomicBoolean(false);
 
@@ -386,6 +404,27 @@
         mDhcpInfo = new DhcpInfo();
         mRunState = RUN_STATE_STARTING;
 
+        mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
+        Intent dhcpRenewalIntent = new Intent(ACTION_DHCP_RENEW, null);
+        mDhcpRenewalIntent = PendingIntent.getBroadcast(mContext, DHCP_RENEW, dhcpRenewalIntent, 0);
+
+        mContext.registerReceiver(
+            new BroadcastReceiver() {
+                @Override
+                public void onReceive(Context context, Intent intent) {
+                    //DHCP renew
+                    if (mDhcpTarget != null) {
+                        Log.d(TAG, "Sending a DHCP renewal");
+                        //acquire a 40s wakelock to finish DHCP renewal
+                        mDhcpRenewWakeLock.acquire(40000);
+                        mDhcpTarget.sendEmptyMessage(EVENT_DHCP_RENEW);
+                    }
+                }
+            },new IntentFilter(ACTION_DHCP_RENEW));
+
+        PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
+        mDhcpRenewWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
+
         // Setting is in seconds
         NOTIFICATION_REPEAT_DELAY_MS = Settings.Secure.getInt(context.getContentResolver(), 
                 Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
@@ -2389,7 +2428,7 @@
 
     private class DhcpHandler extends Handler {
 
-        private Handler mTarget;
+        private Handler mWifiStateTrackerHandler;
         
         /**
          * Whether to skip the DHCP result callback to the target. For example,
@@ -2410,10 +2449,10 @@
          * in an error state and we will not disable coexistence.
          */
         private BluetoothHeadset mBluetoothHeadset;
-        
+
         public DhcpHandler(Looper looper, Handler target) {
             super(looper);
-            mTarget = target;
+            mWifiStateTrackerHandler = target;
             
             mBluetoothHeadset = new BluetoothHeadset(mContext, null);
         }
@@ -2423,7 +2462,7 @@
 
             switch (msg.what) {
                 case EVENT_DHCP_START:
-                    
+                case EVENT_DHCP_RENEW:
                     boolean modifiedBluetoothCoexistenceMode = false;
                     int powerMode = DRIVER_POWER_MODE_AUTO;
 
@@ -2465,14 +2504,61 @@
                         // A new request is being made, so assume we will callback
                         mCancelCallback = false;
                     }
-                    Log.d(TAG, "DhcpHandler: DHCP request started");
-                    if (NetworkUtils.runDhcp(mInterfaceName, mDhcpInfo)) {
-                        event = EVENT_INTERFACE_CONFIGURATION_SUCCEEDED;
-                        if (LOCAL_LOGD) Log.v(TAG, "DhcpHandler: DHCP request succeeded");
-                    } else {
-                        event = EVENT_INTERFACE_CONFIGURATION_FAILED;
-                        Log.i(TAG, "DhcpHandler: DHCP request failed: " +
-                            NetworkUtils.getDhcpError());
+
+                    if (msg.what == EVENT_DHCP_START) {
+                        Log.d(TAG, "DHCP request started");
+                        if (NetworkUtils.runDhcp(mInterfaceName, mDhcpInfo)) {
+                            event = EVENT_INTERFACE_CONFIGURATION_SUCCEEDED;
+                            Log.d(TAG, "DHCP succeeded with lease: " + mDhcpInfo.leaseDuration);
+                            setDhcpRenewalAlarm(mDhcpInfo.leaseDuration);
+                       } else {
+                            event = EVENT_INTERFACE_CONFIGURATION_FAILED;
+                            Log.e(TAG, "DHCP request failed: " + NetworkUtils.getDhcpError());
+                        }
+                        synchronized (this) {
+                            if (!mCancelCallback) {
+                                mWifiStateTrackerHandler.sendEmptyMessage(event);
+                            }
+                        }
+
+                    } else if (msg.what == EVENT_DHCP_RENEW) {
+                        Log.d(TAG, "DHCP renewal started");
+                        int oIp = mDhcpInfo.ipAddress;
+                        int oGw = mDhcpInfo.gateway;
+                        int oMsk = mDhcpInfo.netmask;
+                        int oDns1 = mDhcpInfo.dns1;
+                        int oDns2 = mDhcpInfo.dns2;
+
+                        if (NetworkUtils.runDhcpRenew(mInterfaceName, mDhcpInfo)) {
+                            Log.d(TAG, "DHCP renewal with lease: " + mDhcpInfo.leaseDuration);
+
+                            boolean changed =
+                                (oIp   != mDhcpInfo.ipAddress ||
+                                 oGw   != mDhcpInfo.gateway ||
+                                 oMsk  != mDhcpInfo.netmask ||
+                                 oDns1 != mDhcpInfo.dns1 ||
+                                 oDns2 != mDhcpInfo.dns2);
+
+                            if (changed) {
+                                Log.d(TAG, "IP config change on renewal");
+                                mWifiInfo.setIpAddress(mDhcpInfo.ipAddress);
+                                NetworkUtils.resetConnections(mInterfaceName);
+                                msg = mTarget.obtainMessage(EVENT_CONFIGURATION_CHANGED,
+                                        mNetworkInfo);
+                                msg.sendToTarget();
+                            }
+
+                            setDhcpRenewalAlarm(mDhcpInfo.leaseDuration);
+                        } else {
+                            event = EVENT_INTERFACE_CONFIGURATION_FAILED;
+                            Log.d(TAG, "DHCP renewal failed: " + NetworkUtils.getDhcpError());
+
+                            synchronized (this) {
+                                if (!mCancelCallback) {
+                                    mWifiStateTrackerHandler.sendEmptyMessage(event);
+                                }
+                            }
+                        }
                     }
 
                     if (powerMode != DRIVER_POWER_MODE_ACTIVE) {
@@ -2485,17 +2571,15 @@
                                 WifiNative.BLUETOOTH_COEXISTENCE_MODE_SENSE);
                     }
 
-                    synchronized (this) {
-                        if (!mCancelCallback) {
-                            mTarget.sendEmptyMessage(event);
-                        }
-                    }
                     break;
             }
         }
 
         public synchronized void setCancelCallback(boolean cancelCallback) {
             mCancelCallback = cancelCallback;
+            if (cancelCallback) {
+                mAlarmManager.cancel(mDhcpRenewalIntent);
+            }
         }
 
         /**
@@ -2511,6 +2595,20 @@
             int state = mBluetoothHeadset.getState(mBluetoothHeadset.getCurrentHeadset());
             return state == BluetoothHeadset.STATE_DISCONNECTED;
         }
+
+        private void setDhcpRenewalAlarm(long leaseDuration) {
+            //Do it a bit earlier than half the lease duration time
+            //to beat the native DHCP client and avoid extra packets
+            //48% for one hour lease time = 29 minutes
+            if (leaseDuration < MIN_RENEWAL_TIME_SECS) {
+                leaseDuration = MIN_RENEWAL_TIME_SECS;
+            }
+            mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
+                    SystemClock.elapsedRealtime() +
+                    leaseDuration * 480, //in milliseconds
+                    mDhcpRenewalIntent);
+        }
+
     }
     
     private void checkUseStaticIp() {