Split libmedia into libmedia and libaudioclient

This makes it so audioserver doesn't need to link against the entire libmedia,
which has dependencies on camera, ICU, OpenGL and other things that aren't
needed for audio.

Test: build/boot

Change-Id: I99ba1a3dc3b33ca9b3abd98e7519dbf228ee62af
diff --git a/media/libmedia/Android.mk b/media/libmedia/Android.mk
index c9dc351..41e4792 100644
--- a/media/libmedia/Android.mk
+++ b/media/libmedia/Android.mk
@@ -10,19 +10,11 @@
     aidl/android/IOMXBufferSource.aidl
 
 LOCAL_SRC_FILES += \
-    AudioTrack.cpp \
-    AudioTrackShared.cpp \
-    IAudioFlinger.cpp \
-    IAudioFlingerClient.cpp \
-    IAudioTrack.cpp \
-    IAudioRecord.cpp \
     ICrypto.cpp \
     IDataSource.cpp \
     IDrm.cpp \
     IDrmClient.cpp \
     IHDCP.cpp \
-    AudioRecord.cpp \
-    AudioSystem.cpp \
     mediaplayer.cpp \
     IMediaCodecList.cpp \
     IMediaCodecService.cpp \
@@ -52,11 +44,8 @@
     mediametadataretriever.cpp \
     MidiDeviceInfo.cpp \
     MidiIoWrapper.cpp \
-    ToneGenerator.cpp \
     JetPlayer.cpp \
     IOMX.cpp \
-    IAudioPolicyService.cpp \
-    IAudioPolicyServiceClient.cpp \
     MediaScanner.cpp \
     MediaScannerClient.cpp \
     CharacterEncodingDetector.cpp \
@@ -65,18 +54,13 @@
     MediaResource.cpp \
     MediaResourcePolicy.cpp \
     OMXBuffer.cpp \
-    IEffect.cpp \
-    IEffectClient.cpp \
-    AudioEffect.cpp \
     Visualizer.cpp \
-    MemoryLeakTrackUtil.cpp \
     StringArray.cpp \
-    AudioPolicy.cpp
 
 LOCAL_SHARED_LIBRARIES := \
 	libui liblog libcutils libutils libbinder libsonivox libicuuc libicui18n libexpat \
         libcamera_client libstagefright_foundation \
-        libgui libdl libaudioutils
+        libgui libdl libaudioutils libaudioclient
 
 LOCAL_EXPORT_SHARED_LIBRARY_HEADERS := libbinder
 
diff --git a/media/libmedia/AudioEffect.cpp b/media/libmedia/AudioEffect.cpp
deleted file mode 100644
index 590952f..0000000
--- a/media/libmedia/AudioEffect.cpp
+++ /dev/null
@@ -1,494 +0,0 @@
-/*
-**
-** Copyright 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 "AudioEffect"
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <limits.h>
-
-#include <private/media/AudioEffectShared.h>
-#include <media/AudioEffect.h>
-
-#include <utils/Log.h>
-#include <binder/IPCThreadState.h>
-
-
-
-namespace android {
-
-// ---------------------------------------------------------------------------
-
-AudioEffect::AudioEffect(const String16& opPackageName)
-    : mStatus(NO_INIT), mOpPackageName(opPackageName)
-{
-}
-
-
-AudioEffect::AudioEffect(const effect_uuid_t *type,
-                const String16& opPackageName,
-                const effect_uuid_t *uuid,
-                int32_t priority,
-                effect_callback_t cbf,
-                void* user,
-                audio_session_t sessionId,
-                audio_io_handle_t io
-                )
-    : mStatus(NO_INIT), mOpPackageName(opPackageName)
-{
-    mStatus = set(type, uuid, priority, cbf, user, sessionId, io);
-}
-
-AudioEffect::AudioEffect(const char *typeStr,
-                const String16& opPackageName,
-                const char *uuidStr,
-                int32_t priority,
-                effect_callback_t cbf,
-                void* user,
-                audio_session_t sessionId,
-                audio_io_handle_t io
-                )
-    : mStatus(NO_INIT), mOpPackageName(opPackageName)
-{
-    effect_uuid_t type;
-    effect_uuid_t *pType = NULL;
-    effect_uuid_t uuid;
-    effect_uuid_t *pUuid = NULL;
-
-    ALOGV("Constructor string\n - type: %s\n - uuid: %s", typeStr, uuidStr);
-
-    if (typeStr != NULL) {
-        if (stringToGuid(typeStr, &type) == NO_ERROR) {
-            pType = &type;
-        }
-    }
-
-    if (uuidStr != NULL) {
-        if (stringToGuid(uuidStr, &uuid) == NO_ERROR) {
-            pUuid = &uuid;
-        }
-    }
-
-    mStatus = set(pType, pUuid, priority, cbf, user, sessionId, io);
-}
-
-status_t AudioEffect::set(const effect_uuid_t *type,
-                const effect_uuid_t *uuid,
-                int32_t priority,
-                effect_callback_t cbf,
-                void* user,
-                audio_session_t sessionId,
-                audio_io_handle_t io)
-{
-    sp<IEffect> iEffect;
-    sp<IMemory> cblk;
-    int enabled;
-
-    ALOGV("set %p mUserData: %p uuid: %p timeLow %08x", this, user, type, type ? type->timeLow : 0);
-
-    if (mIEffect != 0) {
-        ALOGW("Effect already in use");
-        return INVALID_OPERATION;
-    }
-
-    const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
-    if (audioFlinger == 0) {
-        ALOGE("set(): Could not get audioflinger");
-        return NO_INIT;
-    }
-
-    if (type == NULL && uuid == NULL) {
-        ALOGW("Must specify at least type or uuid");
-        return BAD_VALUE;
-    }
-
-    mPriority = priority;
-    mCbf = cbf;
-    mUserData = user;
-    mSessionId = sessionId;
-
-    memset(&mDescriptor, 0, sizeof(effect_descriptor_t));
-    mDescriptor.type = *(type != NULL ? type : EFFECT_UUID_NULL);
-    mDescriptor.uuid = *(uuid != NULL ? uuid : EFFECT_UUID_NULL);
-
-    mIEffectClient = new EffectClient(this);
-
-    iEffect = audioFlinger->createEffect((effect_descriptor_t *)&mDescriptor,
-            mIEffectClient, priority, io, mSessionId, mOpPackageName, &mStatus, &mId, &enabled);
-
-    if (iEffect == 0 || (mStatus != NO_ERROR && mStatus != ALREADY_EXISTS)) {
-        ALOGE("set(): AudioFlinger could not create effect, status: %d", mStatus);
-        if (iEffect == 0) {
-            mStatus = NO_INIT;
-        }
-        return mStatus;
-    }
-
-    mEnabled = (volatile int32_t)enabled;
-
-    cblk = iEffect->getCblk();
-    if (cblk == 0) {
-        mStatus = NO_INIT;
-        ALOGE("Could not get control block");
-        return mStatus;
-    }
-
-    mIEffect = iEffect;
-    mCblkMemory = cblk;
-    mCblk = static_cast<effect_param_cblk_t*>(cblk->pointer());
-    int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
-    mCblk->buffer = (uint8_t *)mCblk + bufOffset;
-
-    IInterface::asBinder(iEffect)->linkToDeath(mIEffectClient);
-    mClientPid = IPCThreadState::self()->getCallingPid();
-    ALOGV("set() %p OK effect: %s id: %d status %d enabled %d pid %d", this, mDescriptor.name, mId,
-            mStatus, mEnabled, mClientPid);
-
-    if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
-        AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
-    }
-
-    return mStatus;
-}
-
-
-AudioEffect::~AudioEffect()
-{
-    ALOGV("Destructor %p", this);
-
-    if (mStatus == NO_ERROR || mStatus == ALREADY_EXISTS) {
-        if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
-            AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
-        }
-        if (mIEffect != NULL) {
-            mIEffect->disconnect();
-            IInterface::asBinder(mIEffect)->unlinkToDeath(mIEffectClient);
-        }
-        mIEffect.clear();
-        mCblkMemory.clear();
-        mIEffectClient.clear();
-        IPCThreadState::self()->flushCommands();
-    }
-}
-
-
-status_t AudioEffect::initCheck() const
-{
-    return mStatus;
-}
-
-// -------------------------------------------------------------------------
-
-effect_descriptor_t AudioEffect::descriptor() const
-{
-    return mDescriptor;
-}
-
-bool AudioEffect::getEnabled() const
-{
-    return (mEnabled != 0);
-}
-
-status_t AudioEffect::setEnabled(bool enabled)
-{
-    if (mStatus != NO_ERROR) {
-        return (mStatus == ALREADY_EXISTS) ? (status_t) INVALID_OPERATION : mStatus;
-    }
-
-    status_t status = NO_ERROR;
-
-    AutoMutex lock(mLock);
-    if (enabled != mEnabled) {
-        if (enabled) {
-            ALOGV("enable %p", this);
-            status = mIEffect->enable();
-        } else {
-            ALOGV("disable %p", this);
-            status = mIEffect->disable();
-        }
-        if (status == NO_ERROR) {
-            mEnabled = enabled;
-        }
-    }
-    return status;
-}
-
-status_t AudioEffect::command(uint32_t cmdCode,
-                              uint32_t cmdSize,
-                              void *cmdData,
-                              uint32_t *replySize,
-                              void *replyData)
-{
-    if (mStatus != NO_ERROR && mStatus != ALREADY_EXISTS) {
-        ALOGV("command() bad status %d", mStatus);
-        return mStatus;
-    }
-
-    if (cmdCode == EFFECT_CMD_ENABLE || cmdCode == EFFECT_CMD_DISABLE) {
-        if (mEnabled == (cmdCode == EFFECT_CMD_ENABLE)) {
-            return NO_ERROR;
-        }
-        if (replySize == NULL || *replySize != sizeof(status_t) || replyData == NULL) {
-            return BAD_VALUE;
-        }
-        mLock.lock();
-    }
-
-    status_t status = mIEffect->command(cmdCode, cmdSize, cmdData, replySize, replyData);
-
-    if (cmdCode == EFFECT_CMD_ENABLE || cmdCode == EFFECT_CMD_DISABLE) {
-        if (status == NO_ERROR) {
-            status = *(status_t *)replyData;
-        }
-        if (status == NO_ERROR) {
-            mEnabled = (cmdCode == EFFECT_CMD_ENABLE);
-        }
-        mLock.unlock();
-    }
-
-    return status;
-}
-
-
-status_t AudioEffect::setParameter(effect_param_t *param)
-{
-    if (mStatus != NO_ERROR) {
-        return (mStatus == ALREADY_EXISTS) ? (status_t) INVALID_OPERATION : mStatus;
-    }
-
-    if (param == NULL || param->psize == 0 || param->vsize == 0) {
-        return BAD_VALUE;
-    }
-
-    uint32_t size = sizeof(int);
-    uint32_t psize = ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) + param->vsize;
-
-    ALOGV("setParameter: param: %d, param2: %d", *(int *)param->data,
-            (param->psize == 8) ? *((int *)param->data + 1): -1);
-
-    return mIEffect->command(EFFECT_CMD_SET_PARAM, sizeof (effect_param_t) + psize, param, &size,
-            &param->status);
-}
-
-status_t AudioEffect::setParameterDeferred(effect_param_t *param)
-{
-    if (mStatus != NO_ERROR) {
-        return (mStatus == ALREADY_EXISTS) ? (status_t) INVALID_OPERATION : mStatus;
-    }
-
-    if (param == NULL || param->psize == 0 || param->vsize == 0) {
-        return BAD_VALUE;
-    }
-
-    Mutex::Autolock _l(mCblk->lock);
-
-    int psize = ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) + param->vsize;
-    int size = ((sizeof(effect_param_t) + psize - 1) / sizeof(int) + 1) * sizeof(int);
-
-    if (mCblk->clientIndex + size > EFFECT_PARAM_BUFFER_SIZE) {
-        return NO_MEMORY;
-    }
-    int *p = (int *)(mCblk->buffer + mCblk->clientIndex);
-    *p++ = size;
-    memcpy(p, param, sizeof(effect_param_t) + psize);
-    mCblk->clientIndex += size;
-
-    return NO_ERROR;
-}
-
-status_t AudioEffect::setParameterCommit()
-{
-    if (mStatus != NO_ERROR) {
-        return (mStatus == ALREADY_EXISTS) ? (status_t) INVALID_OPERATION : mStatus;
-    }
-
-    Mutex::Autolock _l(mCblk->lock);
-    if (mCblk->clientIndex == 0) {
-        return INVALID_OPERATION;
-    }
-    uint32_t size = 0;
-    return mIEffect->command(EFFECT_CMD_SET_PARAM_COMMIT, 0, NULL, &size, NULL);
-}
-
-status_t AudioEffect::getParameter(effect_param_t *param)
-{
-    if (mStatus != NO_ERROR && mStatus != ALREADY_EXISTS) {
-        return mStatus;
-    }
-
-    if (param == NULL || param->psize == 0 || param->vsize == 0) {
-        return BAD_VALUE;
-    }
-
-    ALOGV("getParameter: param: %d, param2: %d", *(int *)param->data,
-            (param->psize == 8) ? *((int *)param->data + 1): -1);
-
-    uint32_t psize = sizeof(effect_param_t) + ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
-            param->vsize;
-
-    return mIEffect->command(EFFECT_CMD_GET_PARAM, sizeof(effect_param_t) + param->psize, param,
-            &psize, param);
-}
-
-
-// -------------------------------------------------------------------------
-
-void AudioEffect::binderDied()
-{
-    ALOGW("IEffect died");
-    mStatus = DEAD_OBJECT;
-    if (mCbf != NULL) {
-        status_t status = DEAD_OBJECT;
-        mCbf(EVENT_ERROR, mUserData, &status);
-    }
-    mIEffect.clear();
-}
-
-// -------------------------------------------------------------------------
-
-void AudioEffect::controlStatusChanged(bool controlGranted)
-{
-    ALOGV("controlStatusChanged %p control %d callback %p mUserData %p", this, controlGranted, mCbf,
-            mUserData);
-    if (controlGranted) {
-        if (mStatus == ALREADY_EXISTS) {
-            mStatus = NO_ERROR;
-        }
-    } else {
-        if (mStatus == NO_ERROR) {
-            mStatus = ALREADY_EXISTS;
-        }
-    }
-    if (mCbf != NULL) {
-        mCbf(EVENT_CONTROL_STATUS_CHANGED, mUserData, &controlGranted);
-    }
-}
-
-void AudioEffect::enableStatusChanged(bool enabled)
-{
-    ALOGV("enableStatusChanged %p enabled %d mCbf %p", this, enabled, mCbf);
-    if (mStatus == ALREADY_EXISTS) {
-        mEnabled = enabled;
-        if (mCbf != NULL) {
-            mCbf(EVENT_ENABLE_STATUS_CHANGED, mUserData, &enabled);
-        }
-    }
-}
-
-void AudioEffect::commandExecuted(uint32_t cmdCode,
-                                  uint32_t cmdSize __unused,
-                                  void *cmdData,
-                                  uint32_t replySize __unused,
-                                  void *replyData)
-{
-    if (cmdData == NULL || replyData == NULL) {
-        return;
-    }
-
-    if (mCbf != NULL && cmdCode == EFFECT_CMD_SET_PARAM) {
-        effect_param_t *cmd = (effect_param_t *)cmdData;
-        cmd->status = *(int32_t *)replyData;
-        mCbf(EVENT_PARAMETER_CHANGED, mUserData, cmd);
-    }
-}
-
-// -------------------------------------------------------------------------
-
-status_t AudioEffect::queryNumberEffects(uint32_t *numEffects)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    return af->queryNumberEffects(numEffects);
-}
-
-status_t AudioEffect::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    return af->queryEffect(index, descriptor);
-}
-
-status_t AudioEffect::getEffectDescriptor(const effect_uuid_t *uuid,
-        effect_descriptor_t *descriptor) /*const*/
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    return af->getEffectDescriptor(uuid, descriptor);
-}
-
-
-status_t AudioEffect::queryDefaultPreProcessing(audio_session_t audioSession,
-                                          effect_descriptor_t *descriptors,
-                                          uint32_t *count)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->queryDefaultPreProcessing(audioSession, descriptors, count);
-}
-// -------------------------------------------------------------------------
-
-status_t AudioEffect::stringToGuid(const char *str, effect_uuid_t *guid)
-{
-    if (str == NULL || guid == NULL) {
-        return BAD_VALUE;
-    }
-
-    int tmp[10];
-
-    if (sscanf(str, "%08x-%04x-%04x-%04x-%02x%02x%02x%02x%02x%02x",
-            tmp, tmp+1, tmp+2, tmp+3, tmp+4, tmp+5, tmp+6, tmp+7, tmp+8, tmp+9) < 10) {
-        return BAD_VALUE;
-    }
-    guid->timeLow = (uint32_t)tmp[0];
-    guid->timeMid = (uint16_t)tmp[1];
-    guid->timeHiAndVersion = (uint16_t)tmp[2];
-    guid->clockSeq = (uint16_t)tmp[3];
-    guid->node[0] = (uint8_t)tmp[4];
-    guid->node[1] = (uint8_t)tmp[5];
-    guid->node[2] = (uint8_t)tmp[6];
-    guid->node[3] = (uint8_t)tmp[7];
-    guid->node[4] = (uint8_t)tmp[8];
-    guid->node[5] = (uint8_t)tmp[9];
-
-    return NO_ERROR;
-}
-
-status_t AudioEffect::guidToString(const effect_uuid_t *guid, char *str, size_t maxLen)
-{
-    if (guid == NULL || str == NULL) {
-        return BAD_VALUE;
-    }
-
-    snprintf(str, maxLen, "%08x-%04x-%04x-%04x-%02x%02x%02x%02x%02x%02x",
-            guid->timeLow,
-            guid->timeMid,
-            guid->timeHiAndVersion,
-            guid->clockSeq,
-            guid->node[0],
-            guid->node[1],
-            guid->node[2],
-            guid->node[3],
-            guid->node[4],
-            guid->node[5]);
-
-    return NO_ERROR;
-}
-
-
-} // namespace android
diff --git a/media/libmedia/AudioPolicy.cpp b/media/libmedia/AudioPolicy.cpp
deleted file mode 100644
index d1f7525..0000000
--- a/media/libmedia/AudioPolicy.cpp
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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 "AudioPolicy"
-//#define LOG_NDEBUG 0
-#include <utils/Log.h>
-#include <media/AudioPolicy.h>
-
-namespace android {
-
-//
-//  AudioMixMatchCriterion implementation
-//
-AudioMixMatchCriterion::AudioMixMatchCriterion(audio_usage_t usage,
-                                                 audio_source_t source,
-                                                 uint32_t rule)
-: mRule(rule)
-{
-    if (mRule == RULE_MATCH_ATTRIBUTE_USAGE ||
-            mRule == RULE_EXCLUDE_ATTRIBUTE_USAGE) {
-        mValue.mUsage = usage;
-    } else {
-        mValue.mSource = source;
-    }
-}
-
-status_t AudioMixMatchCriterion::readFromParcel(Parcel *parcel)
-{
-    mRule = parcel->readInt32();
-    if (mRule == RULE_MATCH_ATTRIBUTE_USAGE ||
-            mRule == RULE_EXCLUDE_ATTRIBUTE_USAGE) {
-        mValue.mUsage = (audio_usage_t)parcel->readInt32();
-    } else {
-        mValue.mSource = (audio_source_t)parcel->readInt32();
-    }
-    return NO_ERROR;
-}
-
-status_t AudioMixMatchCriterion::writeToParcel(Parcel *parcel) const
-{
-    parcel->writeInt32(mRule);
-    parcel->writeInt32(mValue.mUsage);
-    return NO_ERROR;
-}
-
-//
-//  AudioMix implementation
-//
-
-status_t AudioMix::readFromParcel(Parcel *parcel)
-{
-    mMixType = parcel->readInt32();
-    mFormat.sample_rate = (uint32_t)parcel->readInt32();
-    mFormat.channel_mask = (audio_channel_mask_t)parcel->readInt32();
-    mFormat.format = (audio_format_t)parcel->readInt32();
-    mRouteFlags = parcel->readInt32();
-    mDeviceType = (audio_devices_t) parcel->readInt32();
-    mDeviceAddress = parcel->readString8();
-    mCbFlags = (uint32_t)parcel->readInt32();
-    size_t size = (size_t)parcel->readInt32();
-    if (size > MAX_CRITERIA_PER_MIX) {
-        size = MAX_CRITERIA_PER_MIX;
-    }
-    for (size_t i = 0; i < size; i++) {
-        AudioMixMatchCriterion criterion;
-        if (criterion.readFromParcel(parcel) == NO_ERROR) {
-            mCriteria.add(criterion);
-        }
-    }
-    return NO_ERROR;
-}
-
-status_t AudioMix::writeToParcel(Parcel *parcel) const
-{
-    parcel->writeInt32(mMixType);
-    parcel->writeInt32(mFormat.sample_rate);
-    parcel->writeInt32(mFormat.channel_mask);
-    parcel->writeInt32(mFormat.format);
-    parcel->writeInt32(mRouteFlags);
-    parcel->writeInt32(mDeviceType);
-    parcel->writeString8(mDeviceAddress);
-    parcel->writeInt32(mCbFlags);
-    size_t size = mCriteria.size();
-    if (size > MAX_CRITERIA_PER_MIX) {
-        size = MAX_CRITERIA_PER_MIX;
-    }
-    size_t sizePosition = parcel->dataPosition();
-    parcel->writeInt32(size);
-    size_t finalSize = size;
-    for (size_t i = 0; i < size; i++) {
-        size_t position = parcel->dataPosition();
-        if (mCriteria[i].writeToParcel(parcel) != NO_ERROR) {
-            parcel->setDataPosition(position);
-            finalSize--;
-        }
-    }
-    if (size != finalSize) {
-        size_t position = parcel->dataPosition();
-        parcel->setDataPosition(sizePosition);
-        parcel->writeInt32(finalSize);
-        parcel->setDataPosition(position);
-    }
-    return NO_ERROR;
-}
-
-} // namespace android
diff --git a/media/libmedia/AudioRecord.cpp b/media/libmedia/AudioRecord.cpp
deleted file mode 100644
index ff5903d..0000000
--- a/media/libmedia/AudioRecord.cpp
+++ /dev/null
@@ -1,1345 +0,0 @@
-/*
-**
-** Copyright 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.
-*/
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "AudioRecord"
-
-#include <inttypes.h>
-#include <sys/resource.h>
-
-#include <binder/IPCThreadState.h>
-#include <media/AudioRecord.h>
-#include <utils/Log.h>
-#include <private/media/AudioTrackShared.h>
-#include <media/IAudioFlinger.h>
-
-#define WAIT_PERIOD_MS          10
-
-namespace android {
-// ---------------------------------------------------------------------------
-
-// static
-status_t AudioRecord::getMinFrameCount(
-        size_t* frameCount,
-        uint32_t sampleRate,
-        audio_format_t format,
-        audio_channel_mask_t channelMask)
-{
-    if (frameCount == NULL) {
-        return BAD_VALUE;
-    }
-
-    size_t size;
-    status_t status = AudioSystem::getInputBufferSize(sampleRate, format, channelMask, &size);
-    if (status != NO_ERROR) {
-        ALOGE("AudioSystem could not query the input buffer size for sampleRate %u, format %#x, "
-              "channelMask %#x; status %d", sampleRate, format, channelMask, status);
-        return status;
-    }
-
-    // We double the size of input buffer for ping pong use of record buffer.
-    // Assumes audio_is_linear_pcm(format)
-    if ((*frameCount = (size * 2) / (audio_channel_count_from_in_mask(channelMask) *
-            audio_bytes_per_sample(format))) == 0) {
-        ALOGE("Unsupported configuration: sampleRate %u, format %#x, channelMask %#x",
-            sampleRate, format, channelMask);
-        return BAD_VALUE;
-    }
-
-    return NO_ERROR;
-}
-
-// ---------------------------------------------------------------------------
-
-AudioRecord::AudioRecord(const String16 &opPackageName)
-    : mActive(false), mStatus(NO_INIT), mOpPackageName(opPackageName), mSessionId(AUDIO_SESSION_ALLOCATE),
-      mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(SP_DEFAULT),
-      mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
-{
-}
-
-AudioRecord::AudioRecord(
-        audio_source_t inputSource,
-        uint32_t sampleRate,
-        audio_format_t format,
-        audio_channel_mask_t channelMask,
-        const String16& opPackageName,
-        size_t frameCount,
-        callback_t cbf,
-        void* user,
-        uint32_t notificationFrames,
-        audio_session_t sessionId,
-        transfer_type transferType,
-        audio_input_flags_t flags,
-        int uid,
-        pid_t pid,
-        const audio_attributes_t* pAttributes)
-    : mActive(false),
-      mStatus(NO_INIT),
-      mOpPackageName(opPackageName),
-      mSessionId(AUDIO_SESSION_ALLOCATE),
-      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
-      mPreviousSchedulingGroup(SP_DEFAULT),
-      mProxy(NULL),
-      mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
-{
-    mStatus = set(inputSource, sampleRate, format, channelMask, frameCount, cbf, user,
-            notificationFrames, false /*threadCanCallJava*/, sessionId, transferType, flags,
-            uid, pid, pAttributes);
-}
-
-AudioRecord::~AudioRecord()
-{
-    if (mStatus == NO_ERROR) {
-        // Make sure that callback function exits in the case where
-        // it is looping on buffer empty condition in obtainBuffer().
-        // Otherwise the callback thread will never exit.
-        stop();
-        if (mAudioRecordThread != 0) {
-            mProxy->interrupt();
-            mAudioRecordThread->requestExit();  // see comment in AudioRecord.h
-            mAudioRecordThread->requestExitAndWait();
-            mAudioRecordThread.clear();
-        }
-        // No lock here: worst case we remove a NULL callback which will be a nop
-        if (mDeviceCallback != 0 && mInput != AUDIO_IO_HANDLE_NONE) {
-            AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mInput);
-        }
-        IInterface::asBinder(mAudioRecord)->unlinkToDeath(mDeathNotifier, this);
-        mAudioRecord.clear();
-        mCblkMemory.clear();
-        mBufferMemory.clear();
-        IPCThreadState::self()->flushCommands();
-        ALOGV("~AudioRecord, releasing session id %d",
-                mSessionId);
-        AudioSystem::releaseAudioSessionId(mSessionId, -1 /*pid*/);
-    }
-}
-
-status_t AudioRecord::set(
-        audio_source_t inputSource,
-        uint32_t sampleRate,
-        audio_format_t format,
-        audio_channel_mask_t channelMask,
-        size_t frameCount,
-        callback_t cbf,
-        void* user,
-        uint32_t notificationFrames,
-        bool threadCanCallJava,
-        audio_session_t sessionId,
-        transfer_type transferType,
-        audio_input_flags_t flags,
-        int uid,
-        pid_t pid,
-        const audio_attributes_t* pAttributes)
-{
-    ALOGV("set(): inputSource %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
-          "notificationFrames %u, sessionId %d, transferType %d, flags %#x, opPackageName %s "
-          "uid %d, pid %d",
-          inputSource, sampleRate, format, channelMask, frameCount, notificationFrames,
-          sessionId, transferType, flags, String8(mOpPackageName).string(), uid, pid);
-
-    switch (transferType) {
-    case TRANSFER_DEFAULT:
-        if (cbf == NULL || threadCanCallJava) {
-            transferType = TRANSFER_SYNC;
-        } else {
-            transferType = TRANSFER_CALLBACK;
-        }
-        break;
-    case TRANSFER_CALLBACK:
-        if (cbf == NULL) {
-            ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL");
-            return BAD_VALUE;
-        }
-        break;
-    case TRANSFER_OBTAIN:
-    case TRANSFER_SYNC:
-        break;
-    default:
-        ALOGE("Invalid transfer type %d", transferType);
-        return BAD_VALUE;
-    }
-    mTransfer = transferType;
-
-    // invariant that mAudioRecord != 0 is true only after set() returns successfully
-    if (mAudioRecord != 0) {
-        ALOGE("Track already in use");
-        return INVALID_OPERATION;
-    }
-
-    if (pAttributes == NULL) {
-        memset(&mAttributes, 0, sizeof(audio_attributes_t));
-        mAttributes.source = inputSource;
-    } else {
-        // stream type shouldn't be looked at, this track has audio attributes
-        memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
-        ALOGV("Building AudioRecord with attributes: source=%d flags=0x%x tags=[%s]",
-              mAttributes.source, mAttributes.flags, mAttributes.tags);
-    }
-
-    mSampleRate = sampleRate;
-
-    // these below should probably come from the audioFlinger too...
-    if (format == AUDIO_FORMAT_DEFAULT) {
-        format = AUDIO_FORMAT_PCM_16_BIT;
-    }
-
-    // validate parameters
-    // AudioFlinger capture only supports linear PCM
-    if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
-        ALOGE("Format %#x is not linear pcm", format);
-        return BAD_VALUE;
-    }
-    mFormat = format;
-
-    if (!audio_is_input_channel(channelMask)) {
-        ALOGE("Invalid channel mask %#x", channelMask);
-        return BAD_VALUE;
-    }
-    mChannelMask = channelMask;
-    uint32_t channelCount = audio_channel_count_from_in_mask(channelMask);
-    mChannelCount = channelCount;
-
-    if (audio_is_linear_pcm(format)) {
-        mFrameSize = channelCount * audio_bytes_per_sample(format);
-    } else {
-        mFrameSize = sizeof(uint8_t);
-    }
-
-    // mFrameCount is initialized in openRecord_l
-    mReqFrameCount = frameCount;
-
-    mNotificationFramesReq = notificationFrames;
-    // mNotificationFramesAct is initialized in openRecord_l
-
-    if (sessionId == AUDIO_SESSION_ALLOCATE) {
-        mSessionId = (audio_session_t) AudioSystem::newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
-    } else {
-        mSessionId = sessionId;
-    }
-    ALOGV("set(): mSessionId %d", mSessionId);
-
-    int callingpid = IPCThreadState::self()->getCallingPid();
-    int mypid = getpid();
-    if (uid == -1 || (callingpid != mypid)) {
-        mClientUid = IPCThreadState::self()->getCallingUid();
-    } else {
-        mClientUid = uid;
-    }
-    if (pid == -1 || (callingpid != mypid)) {
-        mClientPid = callingpid;
-    } else {
-        mClientPid = pid;
-    }
-
-    mOrigFlags = mFlags = flags;
-    mCbf = cbf;
-
-    if (cbf != NULL) {
-        mAudioRecordThread = new AudioRecordThread(*this, threadCanCallJava);
-        mAudioRecordThread->run("AudioRecord", ANDROID_PRIORITY_AUDIO);
-        // thread begins in paused state, and will not reference us until start()
-    }
-
-    // create the IAudioRecord
-    status_t status = openRecord_l(0 /*epoch*/, mOpPackageName);
-
-    if (status != NO_ERROR) {
-        if (mAudioRecordThread != 0) {
-            mAudioRecordThread->requestExit();   // see comment in AudioRecord.h
-            mAudioRecordThread->requestExitAndWait();
-            mAudioRecordThread.clear();
-        }
-        return status;
-    }
-
-    mStatus = NO_ERROR;
-    mUserData = user;
-    // TODO: add audio hardware input latency here
-    mLatency = (1000 * mFrameCount) / mSampleRate;
-    mMarkerPosition = 0;
-    mMarkerReached = false;
-    mNewPosition = 0;
-    mUpdatePeriod = 0;
-    AudioSystem::acquireAudioSessionId(mSessionId, -1);
-    mSequence = 1;
-    mObservedSequence = mSequence;
-    mInOverrun = false;
-    mFramesRead = 0;
-    mFramesReadServerOffset = 0;
-
-    return NO_ERROR;
-}
-
-// -------------------------------------------------------------------------
-
-status_t AudioRecord::start(AudioSystem::sync_event_t event, audio_session_t triggerSession)
-{
-    ALOGV("start, sync event %d trigger session %d", event, triggerSession);
-
-    AutoMutex lock(mLock);
-    if (mActive) {
-        return NO_ERROR;
-    }
-
-    // discard data in buffer
-    const uint32_t framesFlushed = mProxy->flush();
-    mFramesReadServerOffset -= mFramesRead + framesFlushed;
-    mFramesRead = 0;
-    mProxy->clearTimestamp();  // timestamp is invalid until next server push
-
-    // reset current position as seen by client to 0
-    mProxy->setEpoch(mProxy->getEpoch() - mProxy->getPosition());
-    // force refresh of remaining frames by processAudioBuffer() as last
-    // read before stop could be partial.
-    mRefreshRemaining = true;
-
-    mNewPosition = mProxy->getPosition() + mUpdatePeriod;
-    int32_t flags = android_atomic_acquire_load(&mCblk->mFlags);
-
-    // we reactivate markers (mMarkerPosition != 0) as the position is reset to 0.
-    // This is legacy behavior.  This is not done in stop() to avoid a race condition
-    // where the last marker event is issued twice.
-    mMarkerReached = false;
-    mActive = true;
-
-    status_t status = NO_ERROR;
-    if (!(flags & CBLK_INVALID)) {
-        status = mAudioRecord->start(event, triggerSession);
-        if (status == DEAD_OBJECT) {
-            flags |= CBLK_INVALID;
-        }
-    }
-    if (flags & CBLK_INVALID) {
-        status = restoreRecord_l("start");
-    }
-
-    if (status != NO_ERROR) {
-        mActive = false;
-        ALOGE("start() status %d", status);
-    } else {
-        sp<AudioRecordThread> t = mAudioRecordThread;
-        if (t != 0) {
-            t->resume();
-        } else {
-            mPreviousPriority = getpriority(PRIO_PROCESS, 0);
-            get_sched_policy(0, &mPreviousSchedulingGroup);
-            androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
-        }
-    }
-
-    return status;
-}
-
-void AudioRecord::stop()
-{
-    AutoMutex lock(mLock);
-    if (!mActive) {
-        return;
-    }
-
-    mActive = false;
-    mProxy->interrupt();
-    mAudioRecord->stop();
-
-    // Note: legacy handling - stop does not clear record marker and
-    // periodic update position; we update those on start().
-
-    sp<AudioRecordThread> t = mAudioRecordThread;
-    if (t != 0) {
-        t->pause();
-    } else {
-        setpriority(PRIO_PROCESS, 0, mPreviousPriority);
-        set_sched_policy(0, mPreviousSchedulingGroup);
-    }
-}
-
-bool AudioRecord::stopped() const
-{
-    AutoMutex lock(mLock);
-    return !mActive;
-}
-
-status_t AudioRecord::setMarkerPosition(uint32_t marker)
-{
-    // The only purpose of setting marker position is to get a callback
-    if (mCbf == NULL) {
-        return INVALID_OPERATION;
-    }
-
-    AutoMutex lock(mLock);
-    mMarkerPosition = marker;
-    mMarkerReached = false;
-
-    sp<AudioRecordThread> t = mAudioRecordThread;
-    if (t != 0) {
-        t->wake();
-    }
-    return NO_ERROR;
-}
-
-status_t AudioRecord::getMarkerPosition(uint32_t *marker) const
-{
-    if (marker == NULL) {
-        return BAD_VALUE;
-    }
-
-    AutoMutex lock(mLock);
-    mMarkerPosition.getValue(marker);
-
-    return NO_ERROR;
-}
-
-status_t AudioRecord::setPositionUpdatePeriod(uint32_t updatePeriod)
-{
-    // The only purpose of setting position update period is to get a callback
-    if (mCbf == NULL) {
-        return INVALID_OPERATION;
-    }
-
-    AutoMutex lock(mLock);
-    mNewPosition = mProxy->getPosition() + updatePeriod;
-    mUpdatePeriod = updatePeriod;
-
-    sp<AudioRecordThread> t = mAudioRecordThread;
-    if (t != 0) {
-        t->wake();
-    }
-    return NO_ERROR;
-}
-
-status_t AudioRecord::getPositionUpdatePeriod(uint32_t *updatePeriod) const
-{
-    if (updatePeriod == NULL) {
-        return BAD_VALUE;
-    }
-
-    AutoMutex lock(mLock);
-    *updatePeriod = mUpdatePeriod;
-
-    return NO_ERROR;
-}
-
-status_t AudioRecord::getPosition(uint32_t *position) const
-{
-    if (position == NULL) {
-        return BAD_VALUE;
-    }
-
-    AutoMutex lock(mLock);
-    mProxy->getPosition().getValue(position);
-
-    return NO_ERROR;
-}
-
-uint32_t AudioRecord::getInputFramesLost() const
-{
-    // no need to check mActive, because if inactive this will return 0, which is what we want
-    return AudioSystem::getInputFramesLost(getInputPrivate());
-}
-
-status_t AudioRecord::getTimestamp(ExtendedTimestamp *timestamp)
-{
-    if (timestamp == nullptr) {
-        return BAD_VALUE;
-    }
-    AutoMutex lock(mLock);
-    status_t status = mProxy->getTimestamp(timestamp);
-    if (status == OK) {
-        timestamp->mPosition[ExtendedTimestamp::LOCATION_CLIENT] = mFramesRead;
-        timestamp->mTimeNs[ExtendedTimestamp::LOCATION_CLIENT] = 0;
-        // server side frame offset in case AudioRecord has been restored.
-        for (int i = ExtendedTimestamp::LOCATION_SERVER;
-                i < ExtendedTimestamp::LOCATION_MAX; ++i) {
-            if (timestamp->mTimeNs[i] >= 0) {
-                timestamp->mPosition[i] += mFramesReadServerOffset;
-            }
-        }
-    }
-    return status;
-}
-
-// ---- Explicit Routing ---------------------------------------------------
-status_t AudioRecord::setInputDevice(audio_port_handle_t deviceId) {
-    AutoMutex lock(mLock);
-    if (mSelectedDeviceId != deviceId) {
-        mSelectedDeviceId = deviceId;
-        // stop capture so that audio policy manager does not reject the new instance start request
-        // as only one capture can be active at a time.
-        if (mAudioRecord != 0 && mActive) {
-            mAudioRecord->stop();
-        }
-        android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
-    }
-    return NO_ERROR;
-}
-
-audio_port_handle_t AudioRecord::getInputDevice() {
-    AutoMutex lock(mLock);
-    return mSelectedDeviceId;
-}
-
-audio_port_handle_t AudioRecord::getRoutedDeviceId() {
-    AutoMutex lock(mLock);
-    if (mInput == AUDIO_IO_HANDLE_NONE) {
-        return AUDIO_PORT_HANDLE_NONE;
-    }
-    return AudioSystem::getDeviceIdForIo(mInput);
-}
-
-// -------------------------------------------------------------------------
-
-// must be called with mLock held
-status_t AudioRecord::openRecord_l(const Modulo<uint32_t> &epoch, const String16& opPackageName)
-{
-    const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
-    if (audioFlinger == 0) {
-        ALOGE("Could not get audioflinger");
-        return NO_INIT;
-    }
-
-    if (mDeviceCallback != 0 && mInput != AUDIO_IO_HANDLE_NONE) {
-        AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mInput);
-    }
-    audio_io_handle_t input;
-
-    // mFlags (not mOrigFlags) is modified depending on whether fast request is accepted.
-    // After fast request is denied, we will request again if IAudioRecord is re-created.
-
-    status_t status;
-
-    // Not a conventional loop, but a retry loop for at most two iterations total.
-    // Try first maybe with FAST flag then try again without FAST flag if that fails.
-    // Exits loop normally via a return at the bottom, or with error via a break.
-    // The sp<> references will be dropped when re-entering scope.
-    // The lack of indentation is deliberate, to reduce code churn and ease merges.
-    for (;;) {
-
-    status = AudioSystem::getInputForAttr(&mAttributes, &input,
-                                        mSessionId,
-                                        // FIXME compare to AudioTrack
-                                        mClientPid,
-                                        mClientUid,
-                                        mSampleRate, mFormat, mChannelMask,
-                                        mFlags, mSelectedDeviceId);
-
-    if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE) {
-        ALOGE("Could not get audio input for session %d, record source %d, sample rate %u, "
-              "format %#x, channel mask %#x, flags %#x",
-              mSessionId, mAttributes.source, mSampleRate, mFormat, mChannelMask, mFlags);
-        return BAD_VALUE;
-    }
-
-    // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
-    // we must release it ourselves if anything goes wrong.
-
-#if 0
-    size_t afFrameCount;
-    status = AudioSystem::getFrameCount(input, &afFrameCount);
-    if (status != NO_ERROR) {
-        ALOGE("getFrameCount(input=%d) status %d", input, status);
-        break;
-    }
-#endif
-
-    uint32_t afSampleRate;
-    status = AudioSystem::getSamplingRate(input, &afSampleRate);
-    if (status != NO_ERROR) {
-        ALOGE("getSamplingRate(input=%d) status %d", input, status);
-        break;
-    }
-    if (mSampleRate == 0) {
-        mSampleRate = afSampleRate;
-    }
-
-    // Client can only express a preference for FAST.  Server will perform additional tests.
-    if (mFlags & AUDIO_INPUT_FLAG_FAST) {
-        bool useCaseAllowed =
-            // either of these use cases:
-            // use case 1: callback transfer mode
-            (mTransfer == TRANSFER_CALLBACK) ||
-            // use case 2: obtain/release mode
-            (mTransfer == TRANSFER_OBTAIN);
-        // sample rates must also match
-        bool fastAllowed = useCaseAllowed && (mSampleRate == afSampleRate);
-        if (!fastAllowed) {
-            ALOGW("AUDIO_INPUT_FLAG_FAST denied by client; transfer %d, "
-                "track %u Hz, input %u Hz",
-                mTransfer, mSampleRate, afSampleRate);
-            mFlags = (audio_input_flags_t) (mFlags & ~(AUDIO_INPUT_FLAG_FAST |
-                    AUDIO_INPUT_FLAG_RAW));
-            AudioSystem::releaseInput(input, mSessionId);
-            continue;   // retry
-        }
-    }
-
-    // The notification frame count is the period between callbacks, as suggested by the client
-    // but moderated by the server.  For record, the calculations are done entirely on server side.
-    size_t notificationFrames = mNotificationFramesReq;
-    size_t frameCount = mReqFrameCount;
-
-    audio_input_flags_t flags = mFlags;
-
-    pid_t tid = -1;
-    if (mFlags & AUDIO_INPUT_FLAG_FAST) {
-        if (mAudioRecordThread != 0) {
-            tid = mAudioRecordThread->getTid();
-        }
-    }
-
-    size_t temp = frameCount;   // temp may be replaced by a revised value of frameCount,
-                                // but we will still need the original value also
-    audio_session_t originalSessionId = mSessionId;
-
-    sp<IMemory> iMem;           // for cblk
-    sp<IMemory> bufferMem;
-    sp<IAudioRecord> record = audioFlinger->openRecord(input,
-                                                       mSampleRate,
-                                                       mFormat,
-                                                       mChannelMask,
-                                                       opPackageName,
-                                                       &temp,
-                                                       &flags,
-                                                       mClientPid,
-                                                       tid,
-                                                       mClientUid,
-                                                       &mSessionId,
-                                                       &notificationFrames,
-                                                       iMem,
-                                                       bufferMem,
-                                                       &status);
-    ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
-            "session ID changed from %d to %d", originalSessionId, mSessionId);
-
-    if (status != NO_ERROR) {
-        ALOGE("AudioFlinger could not create record track, status: %d", status);
-        break;
-    }
-    ALOG_ASSERT(record != 0);
-
-    // AudioFlinger now owns the reference to the I/O handle,
-    // so we are no longer responsible for releasing it.
-
-    mAwaitBoost = false;
-    if (mFlags & AUDIO_INPUT_FLAG_FAST) {
-        if (flags & AUDIO_INPUT_FLAG_FAST) {
-            ALOGI("AUDIO_INPUT_FLAG_FAST successful; frameCount %zu", frameCount);
-            mAwaitBoost = true;
-        } else {
-            ALOGW("AUDIO_INPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
-            mFlags = (audio_input_flags_t) (mFlags & ~(AUDIO_INPUT_FLAG_FAST |
-                    AUDIO_INPUT_FLAG_RAW));
-            continue;   // retry
-        }
-    }
-    mFlags = flags;
-
-    if (iMem == 0) {
-        ALOGE("Could not get control block");
-        return NO_INIT;
-    }
-    void *iMemPointer = iMem->pointer();
-    if (iMemPointer == NULL) {
-        ALOGE("Could not get control block pointer");
-        return NO_INIT;
-    }
-    audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
-
-    // Starting address of buffers in shared memory.
-    // The buffers are either immediately after the control block,
-    // or in a separate area at discretion of server.
-    void *buffers;
-    if (bufferMem == 0) {
-        buffers = cblk + 1;
-    } else {
-        buffers = bufferMem->pointer();
-        if (buffers == NULL) {
-            ALOGE("Could not get buffer pointer");
-            return NO_INIT;
-        }
-    }
-
-    // invariant that mAudioRecord != 0 is true only after set() returns successfully
-    if (mAudioRecord != 0) {
-        IInterface::asBinder(mAudioRecord)->unlinkToDeath(mDeathNotifier, this);
-        mDeathNotifier.clear();
-    }
-    mAudioRecord = record;
-    mCblkMemory = iMem;
-    mBufferMemory = bufferMem;
-    IPCThreadState::self()->flushCommands();
-
-    mCblk = cblk;
-    // note that temp is the (possibly revised) value of frameCount
-    if (temp < frameCount || (frameCount == 0 && temp == 0)) {
-        ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
-    }
-    frameCount = temp;
-
-    // Make sure that application is notified with sufficient margin before overrun.
-    // The computation is done on server side.
-    if (mNotificationFramesReq > 0 && notificationFrames != mNotificationFramesReq) {
-        ALOGW("Server adjusted notificationFrames from %u to %zu for frameCount %zu",
-                mNotificationFramesReq, notificationFrames, frameCount);
-    }
-    mNotificationFramesAct = (uint32_t) notificationFrames;
-
-    // We retain a copy of the I/O handle, but don't own the reference
-    mInput = input;
-    mRefreshRemaining = true;
-
-    mFrameCount = frameCount;
-    // If IAudioRecord is re-created, don't let the requested frameCount
-    // decrease.  This can confuse clients that cache frameCount().
-    if (frameCount > mReqFrameCount) {
-        mReqFrameCount = frameCount;
-    }
-
-    // update proxy
-    mProxy = new AudioRecordClientProxy(cblk, buffers, mFrameCount, mFrameSize);
-    mProxy->setEpoch(epoch);
-    mProxy->setMinimum(mNotificationFramesAct);
-
-    mDeathNotifier = new DeathNotifier(this);
-    IInterface::asBinder(mAudioRecord)->linkToDeath(mDeathNotifier, this);
-
-    if (mDeviceCallback != 0) {
-        AudioSystem::addAudioDeviceCallback(mDeviceCallback, mInput);
-    }
-
-    return NO_ERROR;
-
-    // End of retry loop.
-    // The lack of indentation is deliberate, to reduce code churn and ease merges.
-    }
-
-// Arrive here on error, via a break
-    AudioSystem::releaseInput(input, mSessionId);
-    if (status == NO_ERROR) {
-        status = NO_INIT;
-    }
-    return status;
-}
-
-status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
-{
-    if (audioBuffer == NULL) {
-        if (nonContig != NULL) {
-            *nonContig = 0;
-        }
-        return BAD_VALUE;
-    }
-    if (mTransfer != TRANSFER_OBTAIN) {
-        audioBuffer->frameCount = 0;
-        audioBuffer->size = 0;
-        audioBuffer->raw = NULL;
-        if (nonContig != NULL) {
-            *nonContig = 0;
-        }
-        return INVALID_OPERATION;
-    }
-
-    const struct timespec *requested;
-    struct timespec timeout;
-    if (waitCount == -1) {
-        requested = &ClientProxy::kForever;
-    } else if (waitCount == 0) {
-        requested = &ClientProxy::kNonBlocking;
-    } else if (waitCount > 0) {
-        long long ms = WAIT_PERIOD_MS * (long long) waitCount;
-        timeout.tv_sec = ms / 1000;
-        timeout.tv_nsec = (int) (ms % 1000) * 1000000;
-        requested = &timeout;
-    } else {
-        ALOGE("%s invalid waitCount %d", __func__, waitCount);
-        requested = NULL;
-    }
-    return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
-}
-
-status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
-        struct timespec *elapsed, size_t *nonContig)
-{
-    // previous and new IAudioRecord sequence numbers are used to detect track re-creation
-    uint32_t oldSequence = 0;
-    uint32_t newSequence;
-
-    Proxy::Buffer buffer;
-    status_t status = NO_ERROR;
-
-    static const int32_t kMaxTries = 5;
-    int32_t tryCounter = kMaxTries;
-
-    do {
-        // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
-        // keep them from going away if another thread re-creates the track during obtainBuffer()
-        sp<AudioRecordClientProxy> proxy;
-        sp<IMemory> iMem;
-        sp<IMemory> bufferMem;
-        {
-            // start of lock scope
-            AutoMutex lock(mLock);
-
-            newSequence = mSequence;
-            // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
-            if (status == DEAD_OBJECT) {
-                // re-create track, unless someone else has already done so
-                if (newSequence == oldSequence) {
-                    status = restoreRecord_l("obtainBuffer");
-                    if (status != NO_ERROR) {
-                        buffer.mFrameCount = 0;
-                        buffer.mRaw = NULL;
-                        buffer.mNonContig = 0;
-                        break;
-                    }
-                }
-            }
-            oldSequence = newSequence;
-
-            // Keep the extra references
-            proxy = mProxy;
-            iMem = mCblkMemory;
-            bufferMem = mBufferMemory;
-
-            // Non-blocking if track is stopped
-            if (!mActive) {
-                requested = &ClientProxy::kNonBlocking;
-            }
-
-        }   // end of lock scope
-
-        buffer.mFrameCount = audioBuffer->frameCount;
-        // FIXME starts the requested timeout and elapsed over from scratch
-        status = proxy->obtainBuffer(&buffer, requested, elapsed);
-
-    } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
-
-    audioBuffer->frameCount = buffer.mFrameCount;
-    audioBuffer->size = buffer.mFrameCount * mFrameSize;
-    audioBuffer->raw = buffer.mRaw;
-    if (nonContig != NULL) {
-        *nonContig = buffer.mNonContig;
-    }
-    return status;
-}
-
-void AudioRecord::releaseBuffer(const Buffer* audioBuffer)
-{
-    // FIXME add error checking on mode, by adding an internal version
-
-    size_t stepCount = audioBuffer->size / mFrameSize;
-    if (stepCount == 0) {
-        return;
-    }
-
-    Proxy::Buffer buffer;
-    buffer.mFrameCount = stepCount;
-    buffer.mRaw = audioBuffer->raw;
-
-    AutoMutex lock(mLock);
-    mInOverrun = false;
-    mProxy->releaseBuffer(&buffer);
-
-    // the server does not automatically disable recorder on overrun, so no need to restart
-}
-
-audio_io_handle_t AudioRecord::getInputPrivate() const
-{
-    AutoMutex lock(mLock);
-    return mInput;
-}
-
-// -------------------------------------------------------------------------
-
-ssize_t AudioRecord::read(void* buffer, size_t userSize, bool blocking)
-{
-    if (mTransfer != TRANSFER_SYNC) {
-        return INVALID_OPERATION;
-    }
-
-    if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
-        // sanity-check. user is most-likely passing an error code, and it would
-        // make the return value ambiguous (actualSize vs error).
-        ALOGE("AudioRecord::read(buffer=%p, size=%zu (%zu)", buffer, userSize, userSize);
-        return BAD_VALUE;
-    }
-
-    ssize_t read = 0;
-    Buffer audioBuffer;
-
-    while (userSize >= mFrameSize) {
-        audioBuffer.frameCount = userSize / mFrameSize;
-
-        status_t err = obtainBuffer(&audioBuffer,
-                blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
-        if (err < 0) {
-            if (read > 0) {
-                break;
-            }
-            if (err == TIMED_OUT || err == -EINTR) {
-                err = WOULD_BLOCK;
-            }
-            return ssize_t(err);
-        }
-
-        size_t bytesRead = audioBuffer.size;
-        memcpy(buffer, audioBuffer.i8, bytesRead);
-        buffer = ((char *) buffer) + bytesRead;
-        userSize -= bytesRead;
-        read += bytesRead;
-
-        releaseBuffer(&audioBuffer);
-    }
-    if (read > 0) {
-        mFramesRead += read / mFrameSize;
-        // mFramesReadTime = systemTime(SYSTEM_TIME_MONOTONIC); // not provided at this time.
-    }
-    return read;
-}
-
-// -------------------------------------------------------------------------
-
-nsecs_t AudioRecord::processAudioBuffer()
-{
-    mLock.lock();
-    if (mAwaitBoost) {
-        mAwaitBoost = false;
-        mLock.unlock();
-        static const int32_t kMaxTries = 5;
-        int32_t tryCounter = kMaxTries;
-        uint32_t pollUs = 10000;
-        do {
-            int policy = sched_getscheduler(0) & ~SCHED_RESET_ON_FORK;
-            if (policy == SCHED_FIFO || policy == SCHED_RR) {
-                break;
-            }
-            usleep(pollUs);
-            pollUs <<= 1;
-        } while (tryCounter-- > 0);
-        if (tryCounter < 0) {
-            ALOGE("did not receive expected priority boost on time");
-        }
-        // Run again immediately
-        return 0;
-    }
-
-    // Can only reference mCblk while locked
-    int32_t flags = android_atomic_and(~CBLK_OVERRUN, &mCblk->mFlags);
-
-    // Check for track invalidation
-    if (flags & CBLK_INVALID) {
-        (void) restoreRecord_l("processAudioBuffer");
-        mLock.unlock();
-        // Run again immediately, but with a new IAudioRecord
-        return 0;
-    }
-
-    bool active = mActive;
-
-    // Manage overrun callback, must be done under lock to avoid race with releaseBuffer()
-    bool newOverrun = false;
-    if (flags & CBLK_OVERRUN) {
-        if (!mInOverrun) {
-            mInOverrun = true;
-            newOverrun = true;
-        }
-    }
-
-    // Get current position of server
-    Modulo<uint32_t> position(mProxy->getPosition());
-
-    // Manage marker callback
-    bool markerReached = false;
-    Modulo<uint32_t> markerPosition(mMarkerPosition);
-    // FIXME fails for wraparound, need 64 bits
-    if (!mMarkerReached && markerPosition.value() > 0 && position >= markerPosition) {
-        mMarkerReached = markerReached = true;
-    }
-
-    // Determine the number of new position callback(s) that will be needed, while locked
-    size_t newPosCount = 0;
-    Modulo<uint32_t> newPosition(mNewPosition);
-    uint32_t updatePeriod = mUpdatePeriod;
-    // FIXME fails for wraparound, need 64 bits
-    if (updatePeriod > 0 && position >= newPosition) {
-        newPosCount = ((position - newPosition).value() / updatePeriod) + 1;
-        mNewPosition += updatePeriod * newPosCount;
-    }
-
-    // Cache other fields that will be needed soon
-    uint32_t notificationFrames = mNotificationFramesAct;
-    if (mRefreshRemaining) {
-        mRefreshRemaining = false;
-        mRemainingFrames = notificationFrames;
-        mRetryOnPartialBuffer = false;
-    }
-    size_t misalignment = mProxy->getMisalignment();
-    uint32_t sequence = mSequence;
-
-    // These fields don't need to be cached, because they are assigned only by set():
-    //      mTransfer, mCbf, mUserData, mSampleRate, mFrameSize
-
-    mLock.unlock();
-
-    // perform callbacks while unlocked
-    if (newOverrun) {
-        mCbf(EVENT_OVERRUN, mUserData, NULL);
-    }
-    if (markerReached) {
-        mCbf(EVENT_MARKER, mUserData, &markerPosition);
-    }
-    while (newPosCount > 0) {
-        size_t temp = newPosition.value(); // FIXME size_t != uint32_t
-        mCbf(EVENT_NEW_POS, mUserData, &temp);
-        newPosition += updatePeriod;
-        newPosCount--;
-    }
-    if (mObservedSequence != sequence) {
-        mObservedSequence = sequence;
-        mCbf(EVENT_NEW_IAUDIORECORD, mUserData, NULL);
-    }
-
-    // if inactive, then don't run me again until re-started
-    if (!active) {
-        return NS_INACTIVE;
-    }
-
-    // Compute the estimated time until the next timed event (position, markers)
-    uint32_t minFrames = ~0;
-    if (!markerReached && position < markerPosition) {
-        minFrames = (markerPosition - position).value();
-    }
-    if (updatePeriod > 0) {
-        uint32_t remaining = (newPosition - position).value();
-        if (remaining < minFrames) {
-            minFrames = remaining;
-        }
-    }
-
-    // If > 0, poll periodically to recover from a stuck server.  A good value is 2.
-    static const uint32_t kPoll = 0;
-    if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
-        minFrames = kPoll * notificationFrames;
-    }
-
-    // Convert frame units to time units
-    nsecs_t ns = NS_WHENEVER;
-    if (minFrames != (uint32_t) ~0) {
-        // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
-        static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
-        ns = ((minFrames * 1000000000LL) / mSampleRate) + kFudgeNs;
-    }
-
-    // If not supplying data by EVENT_MORE_DATA, then we're done
-    if (mTransfer != TRANSFER_CALLBACK) {
-        return ns;
-    }
-
-    struct timespec timeout;
-    const struct timespec *requested = &ClientProxy::kForever;
-    if (ns != NS_WHENEVER) {
-        timeout.tv_sec = ns / 1000000000LL;
-        timeout.tv_nsec = ns % 1000000000LL;
-        ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
-        requested = &timeout;
-    }
-
-    size_t readFrames = 0;
-    while (mRemainingFrames > 0) {
-
-        Buffer audioBuffer;
-        audioBuffer.frameCount = mRemainingFrames;
-        size_t nonContig;
-        status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
-        LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
-                "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
-        requested = &ClientProxy::kNonBlocking;
-        size_t avail = audioBuffer.frameCount + nonContig;
-        ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
-                mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
-        if (err != NO_ERROR) {
-            if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR) {
-                break;
-            }
-            ALOGE("Error %d obtaining an audio buffer, giving up.", err);
-            return NS_NEVER;
-        }
-
-        if (mRetryOnPartialBuffer) {
-            mRetryOnPartialBuffer = false;
-            if (avail < mRemainingFrames) {
-                int64_t myns = ((mRemainingFrames - avail) *
-                        1100000000LL) / mSampleRate;
-                if (ns < 0 || myns < ns) {
-                    ns = myns;
-                }
-                return ns;
-            }
-        }
-
-        size_t reqSize = audioBuffer.size;
-        mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
-        size_t readSize = audioBuffer.size;
-
-        // Sanity check on returned size
-        if (ssize_t(readSize) < 0 || readSize > reqSize) {
-            ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
-                    reqSize, ssize_t(readSize));
-            return NS_NEVER;
-        }
-
-        if (readSize == 0) {
-            // The callback is done consuming buffers
-            // Keep this thread going to handle timed events and
-            // still try to provide more data in intervals of WAIT_PERIOD_MS
-            // but don't just loop and block the CPU, so wait
-            return WAIT_PERIOD_MS * 1000000LL;
-        }
-
-        size_t releasedFrames = readSize / mFrameSize;
-        audioBuffer.frameCount = releasedFrames;
-        mRemainingFrames -= releasedFrames;
-        if (misalignment >= releasedFrames) {
-            misalignment -= releasedFrames;
-        } else {
-            misalignment = 0;
-        }
-
-        releaseBuffer(&audioBuffer);
-        readFrames += releasedFrames;
-
-        // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
-        // if callback doesn't like to accept the full chunk
-        if (readSize < reqSize) {
-            continue;
-        }
-
-        // There could be enough non-contiguous frames available to satisfy the remaining request
-        if (mRemainingFrames <= nonContig) {
-            continue;
-        }
-
-#if 0
-        // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
-        // sum <= notificationFrames.  It replaces that series by at most two EVENT_MORE_DATA
-        // that total to a sum == notificationFrames.
-        if (0 < misalignment && misalignment <= mRemainingFrames) {
-            mRemainingFrames = misalignment;
-            return (mRemainingFrames * 1100000000LL) / mSampleRate;
-        }
-#endif
-
-    }
-    if (readFrames > 0) {
-        AutoMutex lock(mLock);
-        mFramesRead += readFrames;
-        // mFramesReadTime = systemTime(SYSTEM_TIME_MONOTONIC); // not provided at this time.
-    }
-    mRemainingFrames = notificationFrames;
-    mRetryOnPartialBuffer = true;
-
-    // A lot has transpired since ns was calculated, so run again immediately and re-calculate
-    return 0;
-}
-
-status_t AudioRecord::restoreRecord_l(const char *from)
-{
-    ALOGW("dead IAudioRecord, creating a new one from %s()", from);
-    ++mSequence;
-
-    mFlags = mOrigFlags;
-
-    // if the new IAudioRecord is created, openRecord_l() will modify the
-    // following member variables: mAudioRecord, mCblkMemory, mCblk, mBufferMemory.
-    // It will also delete the strong references on previous IAudioRecord and IMemory
-    Modulo<uint32_t> position(mProxy->getPosition());
-    mNewPosition = position + mUpdatePeriod;
-    status_t result = openRecord_l(position, mOpPackageName);
-    if (result == NO_ERROR) {
-        if (mActive) {
-            // callback thread or sync event hasn't changed
-            // FIXME this fails if we have a new AudioFlinger instance
-            result = mAudioRecord->start(AudioSystem::SYNC_EVENT_SAME, AUDIO_SESSION_NONE);
-        }
-        mFramesReadServerOffset = mFramesRead; // server resets to zero so we need an offset.
-    }
-    if (result != NO_ERROR) {
-        ALOGW("restoreRecord_l() failed status %d", result);
-        mActive = false;
-    }
-
-    return result;
-}
-
-status_t AudioRecord::addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback)
-{
-    if (callback == 0) {
-        ALOGW("%s adding NULL callback!", __FUNCTION__);
-        return BAD_VALUE;
-    }
-    AutoMutex lock(mLock);
-    if (mDeviceCallback == callback) {
-        ALOGW("%s adding same callback!", __FUNCTION__);
-        return INVALID_OPERATION;
-    }
-    status_t status = NO_ERROR;
-    if (mInput != AUDIO_IO_HANDLE_NONE) {
-        if (mDeviceCallback != 0) {
-            ALOGW("%s callback already present!", __FUNCTION__);
-            AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mInput);
-        }
-        status = AudioSystem::addAudioDeviceCallback(callback, mInput);
-    }
-    mDeviceCallback = callback;
-    return status;
-}
-
-status_t AudioRecord::removeAudioDeviceCallback(
-        const sp<AudioSystem::AudioDeviceCallback>& callback)
-{
-    if (callback == 0) {
-        ALOGW("%s removing NULL callback!", __FUNCTION__);
-        return BAD_VALUE;
-    }
-    AutoMutex lock(mLock);
-    if (mDeviceCallback != callback) {
-        ALOGW("%s removing different callback!", __FUNCTION__);
-        return INVALID_OPERATION;
-    }
-    if (mInput != AUDIO_IO_HANDLE_NONE) {
-        AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mInput);
-    }
-    mDeviceCallback = 0;
-    return NO_ERROR;
-}
-
-// =========================================================================
-
-void AudioRecord::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
-{
-    sp<AudioRecord> audioRecord = mAudioRecord.promote();
-    if (audioRecord != 0) {
-        AutoMutex lock(audioRecord->mLock);
-        audioRecord->mProxy->binderDied();
-    }
-}
-
-// =========================================================================
-
-AudioRecord::AudioRecordThread::AudioRecordThread(AudioRecord& receiver, bool bCanCallJava)
-    : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
-      mIgnoreNextPausedInt(false)
-{
-}
-
-AudioRecord::AudioRecordThread::~AudioRecordThread()
-{
-}
-
-bool AudioRecord::AudioRecordThread::threadLoop()
-{
-    {
-        AutoMutex _l(mMyLock);
-        if (mPaused) {
-            mMyCond.wait(mMyLock);
-            // caller will check for exitPending()
-            return true;
-        }
-        if (mIgnoreNextPausedInt) {
-            mIgnoreNextPausedInt = false;
-            mPausedInt = false;
-        }
-        if (mPausedInt) {
-            if (mPausedNs > 0) {
-                (void) mMyCond.waitRelative(mMyLock, mPausedNs);
-            } else {
-                mMyCond.wait(mMyLock);
-            }
-            mPausedInt = false;
-            return true;
-        }
-    }
-    nsecs_t ns =  mReceiver.processAudioBuffer();
-    switch (ns) {
-    case 0:
-        return true;
-    case NS_INACTIVE:
-        pauseInternal();
-        return true;
-    case NS_NEVER:
-        return false;
-    case NS_WHENEVER:
-        // Event driven: call wake() when callback notifications conditions change.
-        ns = INT64_MAX;
-        // fall through
-    default:
-        LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
-        pauseInternal(ns);
-        return true;
-    }
-}
-
-void AudioRecord::AudioRecordThread::requestExit()
-{
-    // must be in this order to avoid a race condition
-    Thread::requestExit();
-    resume();
-}
-
-void AudioRecord::AudioRecordThread::pause()
-{
-    AutoMutex _l(mMyLock);
-    mPaused = true;
-}
-
-void AudioRecord::AudioRecordThread::resume()
-{
-    AutoMutex _l(mMyLock);
-    mIgnoreNextPausedInt = true;
-    if (mPaused || mPausedInt) {
-        mPaused = false;
-        mPausedInt = false;
-        mMyCond.signal();
-    }
-}
-
-void AudioRecord::AudioRecordThread::wake()
-{
-    AutoMutex _l(mMyLock);
-    if (!mPaused) {
-        // wake() might be called while servicing a callback - ignore the next
-        // pause time and call processAudioBuffer.
-        mIgnoreNextPausedInt = true;
-        if (mPausedInt && mPausedNs > 0) {
-            // audio record is active and internally paused with timeout.
-            mPausedInt = false;
-            mMyCond.signal();
-        }
-    }
-}
-
-void AudioRecord::AudioRecordThread::pauseInternal(nsecs_t ns)
-{
-    AutoMutex _l(mMyLock);
-    mPausedInt = true;
-    mPausedNs = ns;
-}
-
-// -------------------------------------------------------------------------
-
-} // namespace android
diff --git a/media/libmedia/AudioSystem.cpp b/media/libmedia/AudioSystem.cpp
deleted file mode 100644
index d45b12f..0000000
--- a/media/libmedia/AudioSystem.cpp
+++ /dev/null
@@ -1,1301 +0,0 @@
-/*
- * Copyright (C) 2006-2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "AudioSystem"
-//#define LOG_NDEBUG 0
-
-#include <utils/Log.h>
-#include <binder/IServiceManager.h>
-#include <media/AudioSystem.h>
-#include <media/IAudioFlinger.h>
-#include <media/IAudioPolicyService.h>
-#include <math.h>
-
-#include <system/audio.h>
-
-// ----------------------------------------------------------------------------
-
-namespace android {
-
-// client singleton for AudioFlinger binder interface
-Mutex AudioSystem::gLock;
-Mutex AudioSystem::gLockAPS;
-sp<IAudioFlinger> AudioSystem::gAudioFlinger;
-sp<AudioSystem::AudioFlingerClient> AudioSystem::gAudioFlingerClient;
-audio_error_callback AudioSystem::gAudioErrorCallback = NULL;
-dynamic_policy_callback AudioSystem::gDynPolicyCallback = NULL;
-record_config_callback  AudioSystem::gRecordConfigCallback = NULL;
-
-
-// establish binder interface to AudioFlinger service
-const sp<IAudioFlinger> AudioSystem::get_audio_flinger()
-{
-    sp<IAudioFlinger> af;
-    sp<AudioFlingerClient> afc;
-    {
-        Mutex::Autolock _l(gLock);
-        if (gAudioFlinger == 0) {
-            sp<IServiceManager> sm = defaultServiceManager();
-            sp<IBinder> binder;
-            do {
-                binder = sm->getService(String16("media.audio_flinger"));
-                if (binder != 0)
-                    break;
-                ALOGW("AudioFlinger not published, waiting...");
-                usleep(500000); // 0.5 s
-            } while (true);
-            if (gAudioFlingerClient == NULL) {
-                gAudioFlingerClient = new AudioFlingerClient();
-            } else {
-                if (gAudioErrorCallback) {
-                    gAudioErrorCallback(NO_ERROR);
-                }
-            }
-            binder->linkToDeath(gAudioFlingerClient);
-            gAudioFlinger = interface_cast<IAudioFlinger>(binder);
-            LOG_ALWAYS_FATAL_IF(gAudioFlinger == 0);
-            afc = gAudioFlingerClient;
-        }
-        af = gAudioFlinger;
-    }
-    if (afc != 0) {
-        af->registerClient(afc);
-    }
-    return af;
-}
-
-const sp<AudioSystem::AudioFlingerClient> AudioSystem::getAudioFlingerClient()
-{
-    // calling get_audio_flinger() will initialize gAudioFlingerClient if needed
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return 0;
-    Mutex::Autolock _l(gLock);
-    return gAudioFlingerClient;
-}
-
-sp<AudioIoDescriptor> AudioSystem::getIoDescriptor(audio_io_handle_t ioHandle)
-{
-    sp<AudioIoDescriptor> desc;
-    const sp<AudioFlingerClient> afc = getAudioFlingerClient();
-    if (afc != 0) {
-        desc = afc->getIoDescriptor(ioHandle);
-    }
-    return desc;
-}
-
-/* static */ status_t AudioSystem::checkAudioFlinger()
-{
-    if (defaultServiceManager()->checkService(String16("media.audio_flinger")) != 0) {
-        return NO_ERROR;
-    }
-    return DEAD_OBJECT;
-}
-
-// FIXME Declare in binder opcode order, similarly to IAudioFlinger.h and IAudioFlinger.cpp
-
-status_t AudioSystem::muteMicrophone(bool state)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    return af->setMicMute(state);
-}
-
-status_t AudioSystem::isMicrophoneMuted(bool* state)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    *state = af->getMicMute();
-    return NO_ERROR;
-}
-
-status_t AudioSystem::setMasterVolume(float value)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    af->setMasterVolume(value);
-    return NO_ERROR;
-}
-
-status_t AudioSystem::setMasterMute(bool mute)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    af->setMasterMute(mute);
-    return NO_ERROR;
-}
-
-status_t AudioSystem::getMasterVolume(float* volume)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    *volume = af->masterVolume();
-    return NO_ERROR;
-}
-
-status_t AudioSystem::getMasterMute(bool* mute)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    *mute = af->masterMute();
-    return NO_ERROR;
-}
-
-status_t AudioSystem::setStreamVolume(audio_stream_type_t stream, float value,
-        audio_io_handle_t output)
-{
-    if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    af->setStreamVolume(stream, value, output);
-    return NO_ERROR;
-}
-
-status_t AudioSystem::setStreamMute(audio_stream_type_t stream, bool mute)
-{
-    if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    af->setStreamMute(stream, mute);
-    return NO_ERROR;
-}
-
-status_t AudioSystem::getStreamVolume(audio_stream_type_t stream, float* volume,
-        audio_io_handle_t output)
-{
-    if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    *volume = af->streamVolume(stream, output);
-    return NO_ERROR;
-}
-
-status_t AudioSystem::getStreamMute(audio_stream_type_t stream, bool* mute)
-{
-    if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    *mute = af->streamMute(stream);
-    return NO_ERROR;
-}
-
-status_t AudioSystem::setMode(audio_mode_t mode)
-{
-    if (uint32_t(mode) >= AUDIO_MODE_CNT) return BAD_VALUE;
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    return af->setMode(mode);
-}
-
-status_t AudioSystem::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    return af->setParameters(ioHandle, keyValuePairs);
-}
-
-String8 AudioSystem::getParameters(audio_io_handle_t ioHandle, const String8& keys)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    String8 result = String8("");
-    if (af == 0) return result;
-
-    result = af->getParameters(ioHandle, keys);
-    return result;
-}
-
-status_t AudioSystem::setParameters(const String8& keyValuePairs)
-{
-    return setParameters(AUDIO_IO_HANDLE_NONE, keyValuePairs);
-}
-
-String8 AudioSystem::getParameters(const String8& keys)
-{
-    return getParameters(AUDIO_IO_HANDLE_NONE, keys);
-}
-
-// convert volume steps to natural log scale
-
-// change this value to change volume scaling
-static const float dBPerStep = 0.5f;
-// shouldn't need to touch these
-static const float dBConvert = -dBPerStep * 2.302585093f / 20.0f;
-static const float dBConvertInverse = 1.0f / dBConvert;
-
-float AudioSystem::linearToLog(int volume)
-{
-    // float v = volume ? exp(float(100 - volume) * dBConvert) : 0;
-    // ALOGD("linearToLog(%d)=%f", volume, v);
-    // return v;
-    return volume ? exp(float(100 - volume) * dBConvert) : 0;
-}
-
-int AudioSystem::logToLinear(float volume)
-{
-    // int v = volume ? 100 - int(dBConvertInverse * log(volume) + 0.5) : 0;
-    // ALOGD("logTolinear(%d)=%f", v, volume);
-    // return v;
-    return volume ? 100 - int(dBConvertInverse * log(volume) + 0.5) : 0;
-}
-
-status_t AudioSystem::getOutputSamplingRate(uint32_t* samplingRate, audio_stream_type_t streamType)
-{
-    audio_io_handle_t output;
-
-    if (streamType == AUDIO_STREAM_DEFAULT) {
-        streamType = AUDIO_STREAM_MUSIC;
-    }
-
-    output = getOutput(streamType);
-    if (output == 0) {
-        return PERMISSION_DENIED;
-    }
-
-    return getSamplingRate(output, samplingRate);
-}
-
-status_t AudioSystem::getSamplingRate(audio_io_handle_t ioHandle,
-                                      uint32_t* samplingRate)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    sp<AudioIoDescriptor> desc = getIoDescriptor(ioHandle);
-    if (desc == 0) {
-        *samplingRate = af->sampleRate(ioHandle);
-    } else {
-        *samplingRate = desc->mSamplingRate;
-    }
-    if (*samplingRate == 0) {
-        ALOGE("AudioSystem::getSamplingRate failed for ioHandle %d", ioHandle);
-        return BAD_VALUE;
-    }
-
-    ALOGV("getSamplingRate() ioHandle %d, sampling rate %u", ioHandle, *samplingRate);
-
-    return NO_ERROR;
-}
-
-status_t AudioSystem::getOutputFrameCount(size_t* frameCount, audio_stream_type_t streamType)
-{
-    audio_io_handle_t output;
-
-    if (streamType == AUDIO_STREAM_DEFAULT) {
-        streamType = AUDIO_STREAM_MUSIC;
-    }
-
-    output = getOutput(streamType);
-    if (output == AUDIO_IO_HANDLE_NONE) {
-        return PERMISSION_DENIED;
-    }
-
-    return getFrameCount(output, frameCount);
-}
-
-status_t AudioSystem::getFrameCount(audio_io_handle_t ioHandle,
-                                    size_t* frameCount)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    sp<AudioIoDescriptor> desc = getIoDescriptor(ioHandle);
-    if (desc == 0) {
-        *frameCount = af->frameCount(ioHandle);
-    } else {
-        *frameCount = desc->mFrameCount;
-    }
-    if (*frameCount == 0) {
-        ALOGE("AudioSystem::getFrameCount failed for ioHandle %d", ioHandle);
-        return BAD_VALUE;
-    }
-
-    ALOGV("getFrameCount() ioHandle %d, frameCount %zu", ioHandle, *frameCount);
-
-    return NO_ERROR;
-}
-
-status_t AudioSystem::getOutputLatency(uint32_t* latency, audio_stream_type_t streamType)
-{
-    audio_io_handle_t output;
-
-    if (streamType == AUDIO_STREAM_DEFAULT) {
-        streamType = AUDIO_STREAM_MUSIC;
-    }
-
-    output = getOutput(streamType);
-    if (output == AUDIO_IO_HANDLE_NONE) {
-        return PERMISSION_DENIED;
-    }
-
-    return getLatency(output, latency);
-}
-
-status_t AudioSystem::getLatency(audio_io_handle_t output,
-                                 uint32_t* latency)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    sp<AudioIoDescriptor> outputDesc = getIoDescriptor(output);
-    if (outputDesc == 0) {
-        *latency = af->latency(output);
-    } else {
-        *latency = outputDesc->mLatency;
-    }
-
-    ALOGV("getLatency() output %d, latency %d", output, *latency);
-
-    return NO_ERROR;
-}
-
-status_t AudioSystem::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
-        audio_channel_mask_t channelMask, size_t* buffSize)
-{
-    const sp<AudioFlingerClient> afc = getAudioFlingerClient();
-    if (afc == 0) {
-        return NO_INIT;
-    }
-    return afc->getInputBufferSize(sampleRate, format, channelMask, buffSize);
-}
-
-status_t AudioSystem::setVoiceVolume(float value)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    return af->setVoiceVolume(value);
-}
-
-status_t AudioSystem::getRenderPosition(audio_io_handle_t output, uint32_t *halFrames,
-                                        uint32_t *dspFrames)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-
-    return af->getRenderPosition(halFrames, dspFrames, output);
-}
-
-uint32_t AudioSystem::getInputFramesLost(audio_io_handle_t ioHandle)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    uint32_t result = 0;
-    if (af == 0) return result;
-    if (ioHandle == AUDIO_IO_HANDLE_NONE) return result;
-
-    result = af->getInputFramesLost(ioHandle);
-    return result;
-}
-
-audio_unique_id_t AudioSystem::newAudioUniqueId(audio_unique_id_use_t use)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return AUDIO_UNIQUE_ID_ALLOCATE;
-    return af->newAudioUniqueId(use);
-}
-
-void AudioSystem::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af != 0) {
-        af->acquireAudioSessionId(audioSession, pid);
-    }
-}
-
-void AudioSystem::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af != 0) {
-        af->releaseAudioSessionId(audioSession, pid);
-    }
-}
-
-audio_hw_sync_t AudioSystem::getAudioHwSyncForSession(audio_session_t sessionId)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return AUDIO_HW_SYNC_INVALID;
-    return af->getAudioHwSyncForSession(sessionId);
-}
-
-status_t AudioSystem::systemReady()
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return NO_INIT;
-    return af->systemReady();
-}
-
-status_t AudioSystem::getFrameCountHAL(audio_io_handle_t ioHandle,
-                                       size_t* frameCount)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    sp<AudioIoDescriptor> desc = getIoDescriptor(ioHandle);
-    if (desc == 0) {
-        *frameCount = af->frameCountHAL(ioHandle);
-    } else {
-        *frameCount = desc->mFrameCountHAL;
-    }
-    if (*frameCount == 0) {
-        ALOGE("AudioSystem::getFrameCountHAL failed for ioHandle %d", ioHandle);
-        return BAD_VALUE;
-    }
-
-    ALOGV("getFrameCountHAL() ioHandle %d, frameCount %zu", ioHandle, *frameCount);
-
-    return NO_ERROR;
-}
-
-// ---------------------------------------------------------------------------
-
-
-void AudioSystem::AudioFlingerClient::clearIoCache()
-{
-    Mutex::Autolock _l(mLock);
-    mIoDescriptors.clear();
-    mInBuffSize = 0;
-    mInSamplingRate = 0;
-    mInFormat = AUDIO_FORMAT_DEFAULT;
-    mInChannelMask = AUDIO_CHANNEL_NONE;
-}
-
-void AudioSystem::AudioFlingerClient::binderDied(const wp<IBinder>& who __unused)
-{
-    audio_error_callback cb = NULL;
-    {
-        Mutex::Autolock _l(AudioSystem::gLock);
-        AudioSystem::gAudioFlinger.clear();
-        cb = gAudioErrorCallback;
-    }
-
-    // clear output handles and stream to output map caches
-    clearIoCache();
-
-    if (cb) {
-        cb(DEAD_OBJECT);
-    }
-    ALOGW("AudioFlinger server died!");
-}
-
-void AudioSystem::AudioFlingerClient::ioConfigChanged(audio_io_config_event event,
-                                                      const sp<AudioIoDescriptor>& ioDesc) {
-    ALOGV("ioConfigChanged() event %d", event);
-
-    if (ioDesc == 0 || ioDesc->mIoHandle == AUDIO_IO_HANDLE_NONE) return;
-
-    audio_port_handle_t deviceId = AUDIO_PORT_HANDLE_NONE;
-    Vector < sp<AudioDeviceCallback> > callbacks;
-
-    {
-        Mutex::Autolock _l(mLock);
-
-        switch (event) {
-        case AUDIO_OUTPUT_OPENED:
-        case AUDIO_INPUT_OPENED: {
-            sp<AudioIoDescriptor> oldDesc = getIoDescriptor_l(ioDesc->mIoHandle);
-            if (oldDesc == 0) {
-                mIoDescriptors.add(ioDesc->mIoHandle, ioDesc);
-            } else {
-                deviceId = oldDesc->getDeviceId();
-                mIoDescriptors.replaceValueFor(ioDesc->mIoHandle, ioDesc);
-            }
-
-            if (ioDesc->getDeviceId() != AUDIO_PORT_HANDLE_NONE) {
-                deviceId = ioDesc->getDeviceId();
-                ssize_t ioIndex = mAudioDeviceCallbacks.indexOfKey(ioDesc->mIoHandle);
-                if (ioIndex >= 0) {
-                    callbacks = mAudioDeviceCallbacks.valueAt(ioIndex);
-                }
-            }
-            ALOGV("ioConfigChanged() new %s opened %d samplingRate %u, format %#x channel mask %#x "
-                    "frameCount %zu deviceId %d", event == AUDIO_OUTPUT_OPENED ? "output" : "input",
-                    ioDesc->mIoHandle, ioDesc->mSamplingRate, ioDesc->mFormat, ioDesc->mChannelMask,
-                    ioDesc->mFrameCount, ioDesc->getDeviceId());
-            } break;
-        case AUDIO_OUTPUT_CLOSED:
-        case AUDIO_INPUT_CLOSED: {
-            if (getIoDescriptor_l(ioDesc->mIoHandle) == 0) {
-                ALOGW("ioConfigChanged() closing unknown %s %d",
-                      event == AUDIO_OUTPUT_CLOSED ? "output" : "input", ioDesc->mIoHandle);
-                break;
-            }
-            ALOGV("ioConfigChanged() %s %d closed",
-                  event == AUDIO_OUTPUT_CLOSED ? "output" : "input", ioDesc->mIoHandle);
-
-            mIoDescriptors.removeItem(ioDesc->mIoHandle);
-            mAudioDeviceCallbacks.removeItem(ioDesc->mIoHandle);
-            } break;
-
-        case AUDIO_OUTPUT_CONFIG_CHANGED:
-        case AUDIO_INPUT_CONFIG_CHANGED: {
-            sp<AudioIoDescriptor> oldDesc = getIoDescriptor_l(ioDesc->mIoHandle);
-            if (oldDesc == 0) {
-                ALOGW("ioConfigChanged() modifying unknown output! %d", ioDesc->mIoHandle);
-                break;
-            }
-
-            deviceId = oldDesc->getDeviceId();
-            mIoDescriptors.replaceValueFor(ioDesc->mIoHandle, ioDesc);
-
-            if (deviceId != ioDesc->getDeviceId()) {
-                deviceId = ioDesc->getDeviceId();
-                ssize_t ioIndex = mAudioDeviceCallbacks.indexOfKey(ioDesc->mIoHandle);
-                if (ioIndex >= 0) {
-                    callbacks = mAudioDeviceCallbacks.valueAt(ioIndex);
-                }
-            }
-            ALOGV("ioConfigChanged() new config for %s %d samplingRate %u, format %#x "
-                    "channel mask %#x frameCount %zu frameCountHAL %zu deviceId %d",
-                    event == AUDIO_OUTPUT_CONFIG_CHANGED ? "output" : "input",
-                    ioDesc->mIoHandle, ioDesc->mSamplingRate, ioDesc->mFormat,
-                    ioDesc->mChannelMask, ioDesc->mFrameCount, ioDesc->mFrameCountHAL, ioDesc->getDeviceId());
-
-        } break;
-        }
-    }
-    // callbacks.size() != 0 =>  ioDesc->mIoHandle and deviceId are valid
-    for (size_t i = 0; i < callbacks.size(); i++) {
-        callbacks[i]->onAudioDeviceUpdate(ioDesc->mIoHandle, deviceId);
-    }
-}
-
-status_t AudioSystem::AudioFlingerClient::getInputBufferSize(
-                                                uint32_t sampleRate, audio_format_t format,
-                                                audio_channel_mask_t channelMask, size_t* buffSize)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) {
-        return PERMISSION_DENIED;
-    }
-    Mutex::Autolock _l(mLock);
-    // Do we have a stale mInBuffSize or are we requesting the input buffer size for new values
-    if ((mInBuffSize == 0) || (sampleRate != mInSamplingRate) || (format != mInFormat)
-        || (channelMask != mInChannelMask)) {
-        size_t inBuffSize = af->getInputBufferSize(sampleRate, format, channelMask);
-        if (inBuffSize == 0) {
-            ALOGE("AudioSystem::getInputBufferSize failed sampleRate %d format %#x channelMask %x",
-                    sampleRate, format, channelMask);
-            return BAD_VALUE;
-        }
-        // A benign race is possible here: we could overwrite a fresher cache entry
-        // save the request params
-        mInSamplingRate = sampleRate;
-        mInFormat = format;
-        mInChannelMask = channelMask;
-
-        mInBuffSize = inBuffSize;
-    }
-
-    *buffSize = mInBuffSize;
-
-    return NO_ERROR;
-}
-
-sp<AudioIoDescriptor> AudioSystem::AudioFlingerClient::getIoDescriptor_l(audio_io_handle_t ioHandle)
-{
-    sp<AudioIoDescriptor> desc;
-    ssize_t index = mIoDescriptors.indexOfKey(ioHandle);
-    if (index >= 0) {
-        desc = mIoDescriptors.valueAt(index);
-    }
-    return desc;
-}
-
-sp<AudioIoDescriptor> AudioSystem::AudioFlingerClient::getIoDescriptor(audio_io_handle_t ioHandle)
-{
-    Mutex::Autolock _l(mLock);
-    return getIoDescriptor_l(ioHandle);
-}
-
-status_t AudioSystem::AudioFlingerClient::addAudioDeviceCallback(
-        const sp<AudioDeviceCallback>& callback, audio_io_handle_t audioIo)
-{
-    Mutex::Autolock _l(mLock);
-    Vector < sp<AudioDeviceCallback> > callbacks;
-    ssize_t ioIndex = mAudioDeviceCallbacks.indexOfKey(audioIo);
-    if (ioIndex >= 0) {
-        callbacks = mAudioDeviceCallbacks.valueAt(ioIndex);
-    }
-
-    for (size_t cbIndex = 0; cbIndex < callbacks.size(); cbIndex++) {
-        if (callbacks[cbIndex] == callback) {
-            return INVALID_OPERATION;
-        }
-    }
-    callbacks.add(callback);
-
-    mAudioDeviceCallbacks.replaceValueFor(audioIo, callbacks);
-    return NO_ERROR;
-}
-
-status_t AudioSystem::AudioFlingerClient::removeAudioDeviceCallback(
-        const sp<AudioDeviceCallback>& callback, audio_io_handle_t audioIo)
-{
-    Mutex::Autolock _l(mLock);
-    ssize_t ioIndex = mAudioDeviceCallbacks.indexOfKey(audioIo);
-    if (ioIndex < 0) {
-        return INVALID_OPERATION;
-    }
-    Vector < sp<AudioDeviceCallback> > callbacks = mAudioDeviceCallbacks.valueAt(ioIndex);
-
-    size_t cbIndex;
-    for (cbIndex = 0; cbIndex < callbacks.size(); cbIndex++) {
-        if (callbacks[cbIndex] == callback) {
-            break;
-        }
-    }
-    if (cbIndex == callbacks.size()) {
-        return INVALID_OPERATION;
-    }
-    callbacks.removeAt(cbIndex);
-    if (callbacks.size() != 0) {
-        mAudioDeviceCallbacks.replaceValueFor(audioIo, callbacks);
-    } else {
-        mAudioDeviceCallbacks.removeItem(audioIo);
-    }
-    return NO_ERROR;
-}
-
-/* static */ void AudioSystem::setErrorCallback(audio_error_callback cb)
-{
-    Mutex::Autolock _l(gLock);
-    gAudioErrorCallback = cb;
-}
-
-/*static*/ void AudioSystem::setDynPolicyCallback(dynamic_policy_callback cb)
-{
-    Mutex::Autolock _l(gLock);
-    gDynPolicyCallback = cb;
-}
-
-/*static*/ void AudioSystem::setRecordConfigCallback(record_config_callback cb)
-{
-    Mutex::Autolock _l(gLock);
-    gRecordConfigCallback = cb;
-}
-
-// client singleton for AudioPolicyService binder interface
-// protected by gLockAPS
-sp<IAudioPolicyService> AudioSystem::gAudioPolicyService;
-sp<AudioSystem::AudioPolicyServiceClient> AudioSystem::gAudioPolicyServiceClient;
-
-
-// establish binder interface to AudioPolicy service
-const sp<IAudioPolicyService> AudioSystem::get_audio_policy_service()
-{
-    sp<IAudioPolicyService> ap;
-    sp<AudioPolicyServiceClient> apc;
-    {
-        Mutex::Autolock _l(gLockAPS);
-        if (gAudioPolicyService == 0) {
-            sp<IServiceManager> sm = defaultServiceManager();
-            sp<IBinder> binder;
-            do {
-                binder = sm->getService(String16("media.audio_policy"));
-                if (binder != 0)
-                    break;
-                ALOGW("AudioPolicyService not published, waiting...");
-                usleep(500000); // 0.5 s
-            } while (true);
-            if (gAudioPolicyServiceClient == NULL) {
-                gAudioPolicyServiceClient = new AudioPolicyServiceClient();
-            }
-            binder->linkToDeath(gAudioPolicyServiceClient);
-            gAudioPolicyService = interface_cast<IAudioPolicyService>(binder);
-            LOG_ALWAYS_FATAL_IF(gAudioPolicyService == 0);
-            apc = gAudioPolicyServiceClient;
-        }
-        ap = gAudioPolicyService;
-    }
-    if (apc != 0) {
-        ap->registerClient(apc);
-    }
-
-    return ap;
-}
-
-// ---------------------------------------------------------------------------
-
-status_t AudioSystem::setDeviceConnectionState(audio_devices_t device,
-                                               audio_policy_dev_state_t state,
-                                               const char *device_address,
-                                               const char *device_name)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    const char *address = "";
-    const char *name = "";
-
-    if (aps == 0) return PERMISSION_DENIED;
-
-    if (device_address != NULL) {
-        address = device_address;
-    }
-    if (device_name != NULL) {
-        name = device_name;
-    }
-    return aps->setDeviceConnectionState(device, state, address, name);
-}
-
-audio_policy_dev_state_t AudioSystem::getDeviceConnectionState(audio_devices_t device,
-                                                  const char *device_address)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
-
-    return aps->getDeviceConnectionState(device, device_address);
-}
-
-status_t AudioSystem::setPhoneState(audio_mode_t state)
-{
-    if (uint32_t(state) >= AUDIO_MODE_CNT) return BAD_VALUE;
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-
-    return aps->setPhoneState(state);
-}
-
-status_t AudioSystem::setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->setForceUse(usage, config);
-}
-
-audio_policy_forced_cfg_t AudioSystem::getForceUse(audio_policy_force_use_t usage)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return AUDIO_POLICY_FORCE_NONE;
-    return aps->getForceUse(usage);
-}
-
-
-audio_io_handle_t AudioSystem::getOutput(audio_stream_type_t stream,
-                                    uint32_t samplingRate,
-                                    audio_format_t format,
-                                    audio_channel_mask_t channelMask,
-                                    audio_output_flags_t flags,
-                                    const audio_offload_info_t *offloadInfo)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return 0;
-    return aps->getOutput(stream, samplingRate, format, channelMask, flags, offloadInfo);
-}
-
-status_t AudioSystem::getOutputForAttr(const audio_attributes_t *attr,
-                                        audio_io_handle_t *output,
-                                        audio_session_t session,
-                                        audio_stream_type_t *stream,
-                                        uid_t uid,
-                                        uint32_t samplingRate,
-                                        audio_format_t format,
-                                        audio_channel_mask_t channelMask,
-                                        audio_output_flags_t flags,
-                                        audio_port_handle_t selectedDeviceId,
-                                        const audio_offload_info_t *offloadInfo)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return NO_INIT;
-    return aps->getOutputForAttr(attr, output, session, stream, uid,
-                                 samplingRate, format, channelMask,
-                                 flags, selectedDeviceId, offloadInfo);
-}
-
-status_t AudioSystem::startOutput(audio_io_handle_t output,
-                                  audio_stream_type_t stream,
-                                  audio_session_t session)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->startOutput(output, stream, session);
-}
-
-status_t AudioSystem::stopOutput(audio_io_handle_t output,
-                                 audio_stream_type_t stream,
-                                 audio_session_t session)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->stopOutput(output, stream, session);
-}
-
-void AudioSystem::releaseOutput(audio_io_handle_t output,
-                                audio_stream_type_t stream,
-                                audio_session_t session)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return;
-    aps->releaseOutput(output, stream, session);
-}
-
-status_t AudioSystem::getInputForAttr(const audio_attributes_t *attr,
-                                audio_io_handle_t *input,
-                                audio_session_t session,
-                                pid_t pid,
-                                uid_t uid,
-                                uint32_t samplingRate,
-                                audio_format_t format,
-                                audio_channel_mask_t channelMask,
-                                audio_input_flags_t flags,
-                                audio_port_handle_t selectedDeviceId)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return NO_INIT;
-    return aps->getInputForAttr(
-            attr, input, session, pid, uid,
-            samplingRate, format, channelMask, flags, selectedDeviceId);
-}
-
-status_t AudioSystem::startInput(audio_io_handle_t input,
-                                 audio_session_t session)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->startInput(input, session);
-}
-
-status_t AudioSystem::stopInput(audio_io_handle_t input,
-                                audio_session_t session)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->stopInput(input, session);
-}
-
-void AudioSystem::releaseInput(audio_io_handle_t input,
-                               audio_session_t session)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return;
-    aps->releaseInput(input, session);
-}
-
-status_t AudioSystem::initStreamVolume(audio_stream_type_t stream,
-                                    int indexMin,
-                                    int indexMax)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->initStreamVolume(stream, indexMin, indexMax);
-}
-
-status_t AudioSystem::setStreamVolumeIndex(audio_stream_type_t stream,
-                                           int index,
-                                           audio_devices_t device)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->setStreamVolumeIndex(stream, index, device);
-}
-
-status_t AudioSystem::getStreamVolumeIndex(audio_stream_type_t stream,
-                                           int *index,
-                                           audio_devices_t device)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->getStreamVolumeIndex(stream, index, device);
-}
-
-uint32_t AudioSystem::getStrategyForStream(audio_stream_type_t stream)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return 0;
-    return aps->getStrategyForStream(stream);
-}
-
-audio_devices_t AudioSystem::getDevicesForStream(audio_stream_type_t stream)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return AUDIO_DEVICE_NONE;
-    return aps->getDevicesForStream(stream);
-}
-
-audio_io_handle_t AudioSystem::getOutputForEffect(const effect_descriptor_t *desc)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    // FIXME change return type to status_t, and return PERMISSION_DENIED here
-    if (aps == 0) return AUDIO_IO_HANDLE_NONE;
-    return aps->getOutputForEffect(desc);
-}
-
-status_t AudioSystem::registerEffect(const effect_descriptor_t *desc,
-                                audio_io_handle_t io,
-                                uint32_t strategy,
-                                audio_session_t session,
-                                int id)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->registerEffect(desc, io, strategy, session, id);
-}
-
-status_t AudioSystem::unregisterEffect(int id)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->unregisterEffect(id);
-}
-
-status_t AudioSystem::setEffectEnabled(int id, bool enabled)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->setEffectEnabled(id, enabled);
-}
-
-status_t AudioSystem::isStreamActive(audio_stream_type_t stream, bool* state, uint32_t inPastMs)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    if (state == NULL) return BAD_VALUE;
-    *state = aps->isStreamActive(stream, inPastMs);
-    return NO_ERROR;
-}
-
-status_t AudioSystem::isStreamActiveRemotely(audio_stream_type_t stream, bool* state,
-        uint32_t inPastMs)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    if (state == NULL) return BAD_VALUE;
-    *state = aps->isStreamActiveRemotely(stream, inPastMs);
-    return NO_ERROR;
-}
-
-status_t AudioSystem::isSourceActive(audio_source_t stream, bool* state)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    if (state == NULL) return BAD_VALUE;
-    *state = aps->isSourceActive(stream);
-    return NO_ERROR;
-}
-
-uint32_t AudioSystem::getPrimaryOutputSamplingRate()
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return 0;
-    return af->getPrimaryOutputSamplingRate();
-}
-
-size_t AudioSystem::getPrimaryOutputFrameCount()
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return 0;
-    return af->getPrimaryOutputFrameCount();
-}
-
-status_t AudioSystem::setLowRamDevice(bool isLowRamDevice)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    return af->setLowRamDevice(isLowRamDevice);
-}
-
-void AudioSystem::clearAudioConfigCache()
-{
-    // called by restoreTrack_l(), which needs new IAudioFlinger and IAudioPolicyService instances
-    ALOGV("clearAudioConfigCache()");
-    {
-        Mutex::Autolock _l(gLock);
-        if (gAudioFlingerClient != 0) {
-            gAudioFlingerClient->clearIoCache();
-        }
-        gAudioFlinger.clear();
-    }
-    {
-        Mutex::Autolock _l(gLockAPS);
-        gAudioPolicyService.clear();
-    }
-}
-
-bool AudioSystem::isOffloadSupported(const audio_offload_info_t& info)
-{
-    ALOGV("isOffloadSupported()");
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return false;
-    return aps->isOffloadSupported(info);
-}
-
-status_t AudioSystem::listAudioPorts(audio_port_role_t role,
-                                     audio_port_type_t type,
-                                     unsigned int *num_ports,
-                                     struct audio_port *ports,
-                                     unsigned int *generation)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->listAudioPorts(role, type, num_ports, ports, generation);
-}
-
-status_t AudioSystem::getAudioPort(struct audio_port *port)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->getAudioPort(port);
-}
-
-status_t AudioSystem::createAudioPatch(const struct audio_patch *patch,
-                                   audio_patch_handle_t *handle)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->createAudioPatch(patch, handle);
-}
-
-status_t AudioSystem::releaseAudioPatch(audio_patch_handle_t handle)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->releaseAudioPatch(handle);
-}
-
-status_t AudioSystem::listAudioPatches(unsigned int *num_patches,
-                                  struct audio_patch *patches,
-                                  unsigned int *generation)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->listAudioPatches(num_patches, patches, generation);
-}
-
-status_t AudioSystem::setAudioPortConfig(const struct audio_port_config *config)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->setAudioPortConfig(config);
-}
-
-status_t AudioSystem::addAudioPortCallback(const sp<AudioPortCallback>& callback)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-
-    Mutex::Autolock _l(gLockAPS);
-    if (gAudioPolicyServiceClient == 0) {
-        return NO_INIT;
-    }
-    int ret = gAudioPolicyServiceClient->addAudioPortCallback(callback);
-    if (ret == 1) {
-        aps->setAudioPortCallbacksEnabled(true);
-    }
-    return (ret < 0) ? INVALID_OPERATION : NO_ERROR;
-}
-
-/*static*/
-status_t AudioSystem::removeAudioPortCallback(const sp<AudioPortCallback>& callback)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-
-    Mutex::Autolock _l(gLockAPS);
-    if (gAudioPolicyServiceClient == 0) {
-        return NO_INIT;
-    }
-    int ret = gAudioPolicyServiceClient->removeAudioPortCallback(callback);
-    if (ret == 0) {
-        aps->setAudioPortCallbacksEnabled(false);
-    }
-    return (ret < 0) ? INVALID_OPERATION : NO_ERROR;
-}
-
-status_t AudioSystem::addAudioDeviceCallback(
-        const sp<AudioDeviceCallback>& callback, audio_io_handle_t audioIo)
-{
-    const sp<AudioFlingerClient> afc = getAudioFlingerClient();
-    if (afc == 0) {
-        return NO_INIT;
-    }
-    status_t status = afc->addAudioDeviceCallback(callback, audioIo);
-    if (status == NO_ERROR) {
-        const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-        if (af != 0) {
-            af->registerClient(afc);
-        }
-    }
-    return status;
-}
-
-status_t AudioSystem::removeAudioDeviceCallback(
-        const sp<AudioDeviceCallback>& callback, audio_io_handle_t audioIo)
-{
-    const sp<AudioFlingerClient> afc = getAudioFlingerClient();
-    if (afc == 0) {
-        return NO_INIT;
-    }
-    return afc->removeAudioDeviceCallback(callback, audioIo);
-}
-
-audio_port_handle_t AudioSystem::getDeviceIdForIo(audio_io_handle_t audioIo)
-{
-    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-    if (af == 0) return PERMISSION_DENIED;
-    const sp<AudioIoDescriptor> desc = getIoDescriptor(audioIo);
-    if (desc == 0) {
-        return AUDIO_PORT_HANDLE_NONE;
-    }
-    return desc->getDeviceId();
-}
-
-status_t AudioSystem::acquireSoundTriggerSession(audio_session_t *session,
-                                       audio_io_handle_t *ioHandle,
-                                       audio_devices_t *device)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->acquireSoundTriggerSession(session, ioHandle, device);
-}
-
-status_t AudioSystem::releaseSoundTriggerSession(audio_session_t session)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->releaseSoundTriggerSession(session);
-}
-
-audio_mode_t AudioSystem::getPhoneState()
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return AUDIO_MODE_INVALID;
-    return aps->getPhoneState();
-}
-
-status_t AudioSystem::registerPolicyMixes(const Vector<AudioMix>& mixes, bool registration)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->registerPolicyMixes(mixes, registration);
-}
-
-status_t AudioSystem::startAudioSource(const struct audio_port_config *source,
-                                       const audio_attributes_t *attributes,
-                                       audio_patch_handle_t *handle)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->startAudioSource(source, attributes, handle);
-}
-
-status_t AudioSystem::stopAudioSource(audio_patch_handle_t handle)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->stopAudioSource(handle);
-}
-
-status_t AudioSystem::setMasterMono(bool mono)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->setMasterMono(mono);
-}
-
-status_t AudioSystem::getMasterMono(bool *mono)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->getMasterMono(mono);
-}
-
-// ---------------------------------------------------------------------------
-
-int AudioSystem::AudioPolicyServiceClient::addAudioPortCallback(
-        const sp<AudioPortCallback>& callback)
-{
-    Mutex::Autolock _l(mLock);
-    for (size_t i = 0; i < mAudioPortCallbacks.size(); i++) {
-        if (mAudioPortCallbacks[i] == callback) {
-            return -1;
-        }
-    }
-    mAudioPortCallbacks.add(callback);
-    return mAudioPortCallbacks.size();
-}
-
-int AudioSystem::AudioPolicyServiceClient::removeAudioPortCallback(
-        const sp<AudioPortCallback>& callback)
-{
-    Mutex::Autolock _l(mLock);
-    size_t i;
-    for (i = 0; i < mAudioPortCallbacks.size(); i++) {
-        if (mAudioPortCallbacks[i] == callback) {
-            break;
-        }
-    }
-    if (i == mAudioPortCallbacks.size()) {
-        return -1;
-    }
-    mAudioPortCallbacks.removeAt(i);
-    return mAudioPortCallbacks.size();
-}
-
-
-void AudioSystem::AudioPolicyServiceClient::onAudioPortListUpdate()
-{
-    Mutex::Autolock _l(mLock);
-    for (size_t i = 0; i < mAudioPortCallbacks.size(); i++) {
-        mAudioPortCallbacks[i]->onAudioPortListUpdate();
-    }
-}
-
-void AudioSystem::AudioPolicyServiceClient::onAudioPatchListUpdate()
-{
-    Mutex::Autolock _l(mLock);
-    for (size_t i = 0; i < mAudioPortCallbacks.size(); i++) {
-        mAudioPortCallbacks[i]->onAudioPatchListUpdate();
-    }
-}
-
-void AudioSystem::AudioPolicyServiceClient::onDynamicPolicyMixStateUpdate(
-        String8 regId, int32_t state)
-{
-    ALOGV("AudioPolicyServiceClient::onDynamicPolicyMixStateUpdate(%s, %d)", regId.string(), state);
-    dynamic_policy_callback cb = NULL;
-    {
-        Mutex::Autolock _l(AudioSystem::gLock);
-        cb = gDynPolicyCallback;
-    }
-
-    if (cb != NULL) {
-        cb(DYNAMIC_POLICY_EVENT_MIX_STATE_UPDATE, regId, state);
-    }
-}
-
-void AudioSystem::AudioPolicyServiceClient::onRecordingConfigurationUpdate(
-        int event, audio_session_t session, audio_source_t source,
-        const audio_config_base_t *clientConfig, const audio_config_base_t *deviceConfig,
-        audio_patch_handle_t patchHandle) {
-    record_config_callback cb = NULL;
-    {
-        Mutex::Autolock _l(AudioSystem::gLock);
-        cb = gRecordConfigCallback;
-    }
-
-    if (cb != NULL) {
-        cb(event, session, source, clientConfig, deviceConfig, patchHandle);
-    }
-}
-
-void AudioSystem::AudioPolicyServiceClient::binderDied(const wp<IBinder>& who __unused)
-{
-    {
-        Mutex::Autolock _l(mLock);
-        for (size_t i = 0; i < mAudioPortCallbacks.size(); i++) {
-            mAudioPortCallbacks[i]->onServiceDied();
-        }
-    }
-    {
-        Mutex::Autolock _l(gLockAPS);
-        AudioSystem::gAudioPolicyService.clear();
-    }
-
-    ALOGW("AudioPolicyService server died!");
-}
-
-} // namespace android
diff --git a/media/libmedia/AudioTrack.cpp b/media/libmedia/AudioTrack.cpp
deleted file mode 100644
index 6a1e31e..0000000
--- a/media/libmedia/AudioTrack.cpp
+++ /dev/null
@@ -1,2951 +0,0 @@
-/*
-**
-** Copyright 2007, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-**     http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "AudioTrack"
-
-#include <inttypes.h>
-#include <math.h>
-#include <sys/resource.h>
-
-#include <audio_utils/primitives.h>
-#include <binder/IPCThreadState.h>
-#include <media/AudioTrack.h>
-#include <utils/Log.h>
-#include <private/media/AudioTrackShared.h>
-#include <media/IAudioFlinger.h>
-#include <media/AudioPolicyHelper.h>
-#include <media/AudioResamplerPublic.h>
-
-#define WAIT_PERIOD_MS                  10
-#define WAIT_STREAM_END_TIMEOUT_SEC     120
-static const int kMaxLoopCountNotifications = 32;
-
-namespace android {
-// ---------------------------------------------------------------------------
-
-// TODO: Move to a separate .h
-
-template <typename T>
-static inline const T &min(const T &x, const T &y) {
-    return x < y ? x : y;
-}
-
-template <typename T>
-static inline const T &max(const T &x, const T &y) {
-    return x > y ? x : y;
-}
-
-static const int32_t NANOS_PER_SECOND = 1000000000;
-
-static inline nsecs_t framesToNanoseconds(ssize_t frames, uint32_t sampleRate, float speed)
-{
-    return ((double)frames * 1000000000) / ((double)sampleRate * speed);
-}
-
-static int64_t convertTimespecToUs(const struct timespec &tv)
-{
-    return tv.tv_sec * 1000000ll + tv.tv_nsec / 1000;
-}
-
-static inline nsecs_t convertTimespecToNs(const struct timespec &tv)
-{
-    return tv.tv_sec * (long long)NANOS_PER_SECOND + tv.tv_nsec;
-}
-
-// current monotonic time in microseconds.
-static int64_t getNowUs()
-{
-    struct timespec tv;
-    (void) clock_gettime(CLOCK_MONOTONIC, &tv);
-    return convertTimespecToUs(tv);
-}
-
-// FIXME: we don't use the pitch setting in the time stretcher (not working);
-// instead we emulate it using our sample rate converter.
-static const bool kFixPitch = true; // enable pitch fix
-static inline uint32_t adjustSampleRate(uint32_t sampleRate, float pitch)
-{
-    return kFixPitch ? (sampleRate * pitch + 0.5) : sampleRate;
-}
-
-static inline float adjustSpeed(float speed, float pitch)
-{
-    return kFixPitch ? speed / max(pitch, AUDIO_TIMESTRETCH_PITCH_MIN_DELTA) : speed;
-}
-
-static inline float adjustPitch(float pitch)
-{
-    return kFixPitch ? AUDIO_TIMESTRETCH_PITCH_NORMAL : pitch;
-}
-
-// Must match similar computation in createTrack_l in Threads.cpp.
-// TODO: Move to a common library
-static size_t calculateMinFrameCount(
-        uint32_t afLatencyMs, uint32_t afFrameCount, uint32_t afSampleRate,
-        uint32_t sampleRate, float speed /*, uint32_t notificationsPerBufferReq*/)
-{
-    // Ensure that buffer depth covers at least audio hardware latency
-    uint32_t minBufCount = afLatencyMs / ((1000 * afFrameCount) / afSampleRate);
-    if (minBufCount < 2) {
-        minBufCount = 2;
-    }
-#if 0
-    // The notificationsPerBufferReq parameter is not yet used for non-fast tracks,
-    // but keeping the code here to make it easier to add later.
-    if (minBufCount < notificationsPerBufferReq) {
-        minBufCount = notificationsPerBufferReq;
-    }
-#endif
-    ALOGV("calculateMinFrameCount afLatency %u  afFrameCount %u  afSampleRate %u  "
-            "sampleRate %u  speed %f  minBufCount: %u" /*"  notificationsPerBufferReq %u"*/,
-            afLatencyMs, afFrameCount, afSampleRate, sampleRate, speed, minBufCount
-            /*, notificationsPerBufferReq*/);
-    return minBufCount * sourceFramesNeededWithTimestretch(
-            sampleRate, afFrameCount, afSampleRate, speed);
-}
-
-// static
-status_t AudioTrack::getMinFrameCount(
-        size_t* frameCount,
-        audio_stream_type_t streamType,
-        uint32_t sampleRate)
-{
-    if (frameCount == NULL) {
-        return BAD_VALUE;
-    }
-
-    // FIXME handle in server, like createTrack_l(), possible missing info:
-    //          audio_io_handle_t output
-    //          audio_format_t format
-    //          audio_channel_mask_t channelMask
-    //          audio_output_flags_t flags (FAST)
-    uint32_t afSampleRate;
-    status_t status;
-    status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
-    if (status != NO_ERROR) {
-        ALOGE("Unable to query output sample rate for stream type %d; status %d",
-                streamType, status);
-        return status;
-    }
-    size_t afFrameCount;
-    status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
-    if (status != NO_ERROR) {
-        ALOGE("Unable to query output frame count for stream type %d; status %d",
-                streamType, status);
-        return status;
-    }
-    uint32_t afLatency;
-    status = AudioSystem::getOutputLatency(&afLatency, streamType);
-    if (status != NO_ERROR) {
-        ALOGE("Unable to query output latency for stream type %d; status %d",
-                streamType, status);
-        return status;
-    }
-
-    // When called from createTrack, speed is 1.0f (normal speed).
-    // This is rechecked again on setting playback rate (TODO: on setting sample rate, too).
-    *frameCount = calculateMinFrameCount(afLatency, afFrameCount, afSampleRate, sampleRate, 1.0f
-            /*, 0 notificationsPerBufferReq*/);
-
-    // The formula above should always produce a non-zero value under normal circumstances:
-    // AudioTrack.SAMPLE_RATE_HZ_MIN <= sampleRate <= AudioTrack.SAMPLE_RATE_HZ_MAX.
-    // Return error in the unlikely event that it does not, as that's part of the API contract.
-    if (*frameCount == 0) {
-        ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %u",
-                streamType, sampleRate);
-        return BAD_VALUE;
-    }
-    ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, afSampleRate=%u, afLatency=%u",
-            *frameCount, afFrameCount, afSampleRate, afLatency);
-    return NO_ERROR;
-}
-
-// ---------------------------------------------------------------------------
-
-AudioTrack::AudioTrack()
-    : mStatus(NO_INIT),
-      mState(STATE_STOPPED),
-      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
-      mPreviousSchedulingGroup(SP_DEFAULT),
-      mPausedPosition(0),
-      mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
-{
-    mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
-    mAttributes.usage = AUDIO_USAGE_UNKNOWN;
-    mAttributes.flags = 0x0;
-    strcpy(mAttributes.tags, "");
-}
-
-AudioTrack::AudioTrack(
-        audio_stream_type_t streamType,
-        uint32_t sampleRate,
-        audio_format_t format,
-        audio_channel_mask_t channelMask,
-        size_t frameCount,
-        audio_output_flags_t flags,
-        callback_t cbf,
-        void* user,
-        int32_t notificationFrames,
-        audio_session_t sessionId,
-        transfer_type transferType,
-        const audio_offload_info_t *offloadInfo,
-        int uid,
-        pid_t pid,
-        const audio_attributes_t* pAttributes,
-        bool doNotReconnect,
-        float maxRequiredSpeed)
-    : mStatus(NO_INIT),
-      mState(STATE_STOPPED),
-      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
-      mPreviousSchedulingGroup(SP_DEFAULT),
-      mPausedPosition(0),
-      mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
-{
-    mStatus = set(streamType, sampleRate, format, channelMask,
-            frameCount, flags, cbf, user, notificationFrames,
-            0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
-            offloadInfo, uid, pid, pAttributes, doNotReconnect, maxRequiredSpeed);
-}
-
-AudioTrack::AudioTrack(
-        audio_stream_type_t streamType,
-        uint32_t sampleRate,
-        audio_format_t format,
-        audio_channel_mask_t channelMask,
-        const sp<IMemory>& sharedBuffer,
-        audio_output_flags_t flags,
-        callback_t cbf,
-        void* user,
-        int32_t notificationFrames,
-        audio_session_t sessionId,
-        transfer_type transferType,
-        const audio_offload_info_t *offloadInfo,
-        int uid,
-        pid_t pid,
-        const audio_attributes_t* pAttributes,
-        bool doNotReconnect,
-        float maxRequiredSpeed)
-    : mStatus(NO_INIT),
-      mState(STATE_STOPPED),
-      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
-      mPreviousSchedulingGroup(SP_DEFAULT),
-      mPausedPosition(0),
-      mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
-{
-    mStatus = set(streamType, sampleRate, format, channelMask,
-            0 /*frameCount*/, flags, cbf, user, notificationFrames,
-            sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
-            uid, pid, pAttributes, doNotReconnect, maxRequiredSpeed);
-}
-
-AudioTrack::~AudioTrack()
-{
-    if (mStatus == NO_ERROR) {
-        // Make sure that callback function exits in the case where
-        // it is looping on buffer full condition in obtainBuffer().
-        // Otherwise the callback thread will never exit.
-        stop();
-        if (mAudioTrackThread != 0) {
-            mProxy->interrupt();
-            mAudioTrackThread->requestExit();   // see comment in AudioTrack.h
-            mAudioTrackThread->requestExitAndWait();
-            mAudioTrackThread.clear();
-        }
-        // No lock here: worst case we remove a NULL callback which will be a nop
-        if (mDeviceCallback != 0 && mOutput != AUDIO_IO_HANDLE_NONE) {
-            AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
-        }
-        IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
-        mAudioTrack.clear();
-        mCblkMemory.clear();
-        mSharedBuffer.clear();
-        IPCThreadState::self()->flushCommands();
-        ALOGV("~AudioTrack, releasing session id %d from %d on behalf of %d",
-                mSessionId, IPCThreadState::self()->getCallingPid(), mClientPid);
-        AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
-    }
-}
-
-status_t AudioTrack::set(
-        audio_stream_type_t streamType,
-        uint32_t sampleRate,
-        audio_format_t format,
-        audio_channel_mask_t channelMask,
-        size_t frameCount,
-        audio_output_flags_t flags,
-        callback_t cbf,
-        void* user,
-        int32_t notificationFrames,
-        const sp<IMemory>& sharedBuffer,
-        bool threadCanCallJava,
-        audio_session_t sessionId,
-        transfer_type transferType,
-        const audio_offload_info_t *offloadInfo,
-        int uid,
-        pid_t pid,
-        const audio_attributes_t* pAttributes,
-        bool doNotReconnect,
-        float maxRequiredSpeed)
-{
-    ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
-          "flags #%x, notificationFrames %d, sessionId %d, transferType %d, uid %d, pid %d",
-          streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
-          sessionId, transferType, uid, pid);
-
-    mThreadCanCallJava = threadCanCallJava;
-
-    switch (transferType) {
-    case TRANSFER_DEFAULT:
-        if (sharedBuffer != 0) {
-            transferType = TRANSFER_SHARED;
-        } else if (cbf == NULL || threadCanCallJava) {
-            transferType = TRANSFER_SYNC;
-        } else {
-            transferType = TRANSFER_CALLBACK;
-        }
-        break;
-    case TRANSFER_CALLBACK:
-        if (cbf == NULL || sharedBuffer != 0) {
-            ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
-            return BAD_VALUE;
-        }
-        break;
-    case TRANSFER_OBTAIN:
-    case TRANSFER_SYNC:
-        if (sharedBuffer != 0) {
-            ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
-            return BAD_VALUE;
-        }
-        break;
-    case TRANSFER_SHARED:
-        if (sharedBuffer == 0) {
-            ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
-            return BAD_VALUE;
-        }
-        break;
-    default:
-        ALOGE("Invalid transfer type %d", transferType);
-        return BAD_VALUE;
-    }
-    mSharedBuffer = sharedBuffer;
-    mTransfer = transferType;
-    mDoNotReconnect = doNotReconnect;
-
-    ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %zu", sharedBuffer->pointer(),
-            sharedBuffer->size());
-
-    ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
-
-    // invariant that mAudioTrack != 0 is true only after set() returns successfully
-    if (mAudioTrack != 0) {
-        ALOGE("Track already in use");
-        return INVALID_OPERATION;
-    }
-
-    // handle default values first.
-    if (streamType == AUDIO_STREAM_DEFAULT) {
-        streamType = AUDIO_STREAM_MUSIC;
-    }
-    if (pAttributes == NULL) {
-        if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
-            ALOGE("Invalid stream type %d", streamType);
-            return BAD_VALUE;
-        }
-        mStreamType = streamType;
-
-    } else {
-        // stream type shouldn't be looked at, this track has audio attributes
-        memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
-        ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
-                mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
-        mStreamType = AUDIO_STREAM_DEFAULT;
-        if ((mAttributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
-            flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
-        }
-        if ((mAttributes.flags & AUDIO_FLAG_LOW_LATENCY) != 0) {
-            flags = (audio_output_flags_t) (flags | AUDIO_OUTPUT_FLAG_FAST);
-        }
-    }
-
-    // these below should probably come from the audioFlinger too...
-    if (format == AUDIO_FORMAT_DEFAULT) {
-        format = AUDIO_FORMAT_PCM_16_BIT;
-    } else if (format == AUDIO_FORMAT_IEC61937) { // HDMI pass-through?
-        mAttributes.flags |= AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO;
-    }
-
-    // validate parameters
-    if (!audio_is_valid_format(format)) {
-        ALOGE("Invalid format %#x", format);
-        return BAD_VALUE;
-    }
-    mFormat = format;
-
-    if (!audio_is_output_channel(channelMask)) {
-        ALOGE("Invalid channel mask %#x", channelMask);
-        return BAD_VALUE;
-    }
-    mChannelMask = channelMask;
-    uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
-    mChannelCount = channelCount;
-
-    // force direct flag if format is not linear PCM
-    // or offload was requested
-    if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
-            || !audio_is_linear_pcm(format)) {
-        ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
-                    ? "Offload request, forcing to Direct Output"
-                    : "Not linear PCM, forcing to Direct Output");
-        flags = (audio_output_flags_t)
-                // FIXME why can't we allow direct AND fast?
-                ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
-    }
-
-    // force direct flag if HW A/V sync requested
-    if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
-        flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
-    }
-
-    if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
-        if (audio_has_proportional_frames(format)) {
-            mFrameSize = channelCount * audio_bytes_per_sample(format);
-        } else {
-            mFrameSize = sizeof(uint8_t);
-        }
-    } else {
-        ALOG_ASSERT(audio_has_proportional_frames(format));
-        mFrameSize = channelCount * audio_bytes_per_sample(format);
-        // createTrack will return an error if PCM format is not supported by server,
-        // so no need to check for specific PCM formats here
-    }
-
-    // sampling rate must be specified for direct outputs
-    if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
-        return BAD_VALUE;
-    }
-    mSampleRate = sampleRate;
-    mOriginalSampleRate = sampleRate;
-    mPlaybackRate = AUDIO_PLAYBACK_RATE_DEFAULT;
-    // 1.0 <= mMaxRequiredSpeed <= AUDIO_TIMESTRETCH_SPEED_MAX
-    mMaxRequiredSpeed = min(max(maxRequiredSpeed, 1.0f), AUDIO_TIMESTRETCH_SPEED_MAX);
-
-    // Make copy of input parameter offloadInfo so that in the future:
-    //  (a) createTrack_l doesn't need it as an input parameter
-    //  (b) we can support re-creation of offloaded tracks
-    if (offloadInfo != NULL) {
-        mOffloadInfoCopy = *offloadInfo;
-        mOffloadInfo = &mOffloadInfoCopy;
-    } else {
-        mOffloadInfo = NULL;
-    }
-
-    mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
-    mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
-    mSendLevel = 0.0f;
-    // mFrameCount is initialized in createTrack_l
-    mReqFrameCount = frameCount;
-    if (notificationFrames >= 0) {
-        mNotificationFramesReq = notificationFrames;
-        mNotificationsPerBufferReq = 0;
-    } else {
-        if (!(flags & AUDIO_OUTPUT_FLAG_FAST)) {
-            ALOGE("notificationFrames=%d not permitted for non-fast track",
-                    notificationFrames);
-            return BAD_VALUE;
-        }
-        if (frameCount > 0) {
-            ALOGE("notificationFrames=%d not permitted with non-zero frameCount=%zu",
-                    notificationFrames, frameCount);
-            return BAD_VALUE;
-        }
-        mNotificationFramesReq = 0;
-        const uint32_t minNotificationsPerBuffer = 1;
-        const uint32_t maxNotificationsPerBuffer = 8;
-        mNotificationsPerBufferReq = min(maxNotificationsPerBuffer,
-                max((uint32_t) -notificationFrames, minNotificationsPerBuffer));
-        ALOGW_IF(mNotificationsPerBufferReq != (uint32_t) -notificationFrames,
-                "notificationFrames=%d clamped to the range -%u to -%u",
-                notificationFrames, minNotificationsPerBuffer, maxNotificationsPerBuffer);
-    }
-    mNotificationFramesAct = 0;
-    if (sessionId == AUDIO_SESSION_ALLOCATE) {
-        mSessionId = (audio_session_t) AudioSystem::newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
-    } else {
-        mSessionId = sessionId;
-    }
-    int callingpid = IPCThreadState::self()->getCallingPid();
-    int mypid = getpid();
-    if (uid == -1 || (callingpid != mypid)) {
-        mClientUid = IPCThreadState::self()->getCallingUid();
-    } else {
-        mClientUid = uid;
-    }
-    if (pid == -1 || (callingpid != mypid)) {
-        mClientPid = callingpid;
-    } else {
-        mClientPid = pid;
-    }
-    mAuxEffectId = 0;
-    mOrigFlags = mFlags = flags;
-    mCbf = cbf;
-
-    if (cbf != NULL) {
-        mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
-        mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
-        // thread begins in paused state, and will not reference us until start()
-    }
-
-    // create the IAudioTrack
-    status_t status = createTrack_l();
-
-    if (status != NO_ERROR) {
-        if (mAudioTrackThread != 0) {
-            mAudioTrackThread->requestExit();   // see comment in AudioTrack.h
-            mAudioTrackThread->requestExitAndWait();
-            mAudioTrackThread.clear();
-        }
-        return status;
-    }
-
-    mStatus = NO_ERROR;
-    mUserData = user;
-    mLoopCount = 0;
-    mLoopStart = 0;
-    mLoopEnd = 0;
-    mLoopCountNotified = 0;
-    mMarkerPosition = 0;
-    mMarkerReached = false;
-    mNewPosition = 0;
-    mUpdatePeriod = 0;
-    mPosition = 0;
-    mReleased = 0;
-    mStartUs = 0;
-    AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
-    mSequence = 1;
-    mObservedSequence = mSequence;
-    mInUnderrun = false;
-    mPreviousTimestampValid = false;
-    mTimestampStartupGlitchReported = false;
-    mRetrogradeMotionReported = false;
-    mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
-    mStartTs.mPosition = 0;
-    mUnderrunCountOffset = 0;
-    mFramesWritten = 0;
-    mFramesWrittenServerOffset = 0;
-    mFramesWrittenAtRestore = -1; // -1 is a unique initializer.
-
-    return NO_ERROR;
-}
-
-// -------------------------------------------------------------------------
-
-status_t AudioTrack::start()
-{
-    AutoMutex lock(mLock);
-
-    if (mState == STATE_ACTIVE) {
-        return INVALID_OPERATION;
-    }
-
-    mInUnderrun = true;
-
-    State previousState = mState;
-    if (previousState == STATE_PAUSED_STOPPING) {
-        mState = STATE_STOPPING;
-    } else {
-        mState = STATE_ACTIVE;
-    }
-    (void) updateAndGetPosition_l();
-
-    // save start timestamp
-    if (isOffloadedOrDirect_l()) {
-        if (getTimestamp_l(mStartTs) != OK) {
-            mStartTs.mPosition = 0;
-        }
-    } else {
-        if (getTimestamp_l(&mStartEts) != OK) {
-            mStartEts.clear();
-        }
-    }
-    if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
-        // reset current position as seen by client to 0
-        mPosition = 0;
-        mPreviousTimestampValid = false;
-        mTimestampStartupGlitchReported = false;
-        mRetrogradeMotionReported = false;
-        mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
-
-        if (!isOffloadedOrDirect_l()
-                && mStartEts.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] > 0) {
-            // Server side has consumed something, but is it finished consuming?
-            // It is possible since flush and stop are asynchronous that the server
-            // is still active at this point.
-            ALOGV("start: server read:%lld  cumulative flushed:%lld  client written:%lld",
-                    (long long)(mFramesWrittenServerOffset
-                            + mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER]),
-                    (long long)mStartEts.mFlushed,
-                    (long long)mFramesWritten);
-            mFramesWrittenServerOffset = -mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER];
-        }
-        mFramesWritten = 0;
-        mProxy->clearTimestamp(); // need new server push for valid timestamp
-        mMarkerReached = false;
-
-        // For offloaded tracks, we don't know if the hardware counters are really zero here,
-        // since the flush is asynchronous and stop may not fully drain.
-        // We save the time when the track is started to later verify whether
-        // the counters are realistic (i.e. start from zero after this time).
-        mStartUs = getNowUs();
-
-        // force refresh of remaining frames by processAudioBuffer() as last
-        // write before stop could be partial.
-        mRefreshRemaining = true;
-    }
-    mNewPosition = mPosition + mUpdatePeriod;
-    int32_t flags = android_atomic_and(~(CBLK_STREAM_END_DONE | CBLK_DISABLED), &mCblk->mFlags);
-
-    status_t status = NO_ERROR;
-    if (!(flags & CBLK_INVALID)) {
-        status = mAudioTrack->start();
-        if (status == DEAD_OBJECT) {
-            flags |= CBLK_INVALID;
-        }
-    }
-    if (flags & CBLK_INVALID) {
-        status = restoreTrack_l("start");
-    }
-
-    // resume or pause the callback thread as needed.
-    sp<AudioTrackThread> t = mAudioTrackThread;
-    if (status == NO_ERROR) {
-        if (t != 0) {
-            if (previousState == STATE_STOPPING) {
-                mProxy->interrupt();
-            } else {
-                t->resume();
-            }
-        } else {
-            mPreviousPriority = getpriority(PRIO_PROCESS, 0);
-            get_sched_policy(0, &mPreviousSchedulingGroup);
-            androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
-        }
-    } else {
-        ALOGE("start() status %d", status);
-        mState = previousState;
-        if (t != 0) {
-            if (previousState != STATE_STOPPING) {
-                t->pause();
-            }
-        } else {
-            setpriority(PRIO_PROCESS, 0, mPreviousPriority);
-            set_sched_policy(0, mPreviousSchedulingGroup);
-        }
-    }
-
-    return status;
-}
-
-void AudioTrack::stop()
-{
-    AutoMutex lock(mLock);
-    if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
-        return;
-    }
-
-    if (isOffloaded_l()) {
-        mState = STATE_STOPPING;
-    } else {
-        mState = STATE_STOPPED;
-        mReleased = 0;
-    }
-
-    mProxy->interrupt();
-    mAudioTrack->stop();
-
-    // Note: legacy handling - stop does not clear playback marker
-    // and periodic update counter, but flush does for streaming tracks.
-
-    if (mSharedBuffer != 0) {
-        // clear buffer position and loop count.
-        mStaticProxy->setBufferPositionAndLoop(0 /* position */,
-                0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
-    }
-
-    sp<AudioTrackThread> t = mAudioTrackThread;
-    if (t != 0) {
-        if (!isOffloaded_l()) {
-            t->pause();
-        }
-    } else {
-        setpriority(PRIO_PROCESS, 0, mPreviousPriority);
-        set_sched_policy(0, mPreviousSchedulingGroup);
-    }
-}
-
-bool AudioTrack::stopped() const
-{
-    AutoMutex lock(mLock);
-    return mState != STATE_ACTIVE;
-}
-
-void AudioTrack::flush()
-{
-    if (mSharedBuffer != 0) {
-        return;
-    }
-    AutoMutex lock(mLock);
-    if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
-        return;
-    }
-    flush_l();
-}
-
-void AudioTrack::flush_l()
-{
-    ALOG_ASSERT(mState != STATE_ACTIVE);
-
-    // clear playback marker and periodic update counter
-    mMarkerPosition = 0;
-    mMarkerReached = false;
-    mUpdatePeriod = 0;
-    mRefreshRemaining = true;
-
-    mState = STATE_FLUSHED;
-    mReleased = 0;
-    if (isOffloaded_l()) {
-        mProxy->interrupt();
-    }
-    mProxy->flush();
-    mAudioTrack->flush();
-}
-
-void AudioTrack::pause()
-{
-    AutoMutex lock(mLock);
-    if (mState == STATE_ACTIVE) {
-        mState = STATE_PAUSED;
-    } else if (mState == STATE_STOPPING) {
-        mState = STATE_PAUSED_STOPPING;
-    } else {
-        return;
-    }
-    mProxy->interrupt();
-    mAudioTrack->pause();
-
-    if (isOffloaded_l()) {
-        if (mOutput != AUDIO_IO_HANDLE_NONE) {
-            // An offload output can be re-used between two audio tracks having
-            // the same configuration. A timestamp query for a paused track
-            // while the other is running would return an incorrect time.
-            // To fix this, cache the playback position on a pause() and return
-            // this time when requested until the track is resumed.
-
-            // OffloadThread sends HAL pause in its threadLoop. Time saved
-            // here can be slightly off.
-
-            // TODO: check return code for getRenderPosition.
-
-            uint32_t halFrames;
-            AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
-            ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
-        }
-    }
-}
-
-status_t AudioTrack::setVolume(float left, float right)
-{
-    // This duplicates a test by AudioTrack JNI, but that is not the only caller
-    if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
-            isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
-        return BAD_VALUE;
-    }
-
-    AutoMutex lock(mLock);
-    mVolume[AUDIO_INTERLEAVE_LEFT] = left;
-    mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
-
-    mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
-
-    if (isOffloaded_l()) {
-        mAudioTrack->signal();
-    }
-    return NO_ERROR;
-}
-
-status_t AudioTrack::setVolume(float volume)
-{
-    return setVolume(volume, volume);
-}
-
-status_t AudioTrack::setAuxEffectSendLevel(float level)
-{
-    // This duplicates a test by AudioTrack JNI, but that is not the only caller
-    if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
-        return BAD_VALUE;
-    }
-
-    AutoMutex lock(mLock);
-    mSendLevel = level;
-    mProxy->setSendLevel(level);
-
-    return NO_ERROR;
-}
-
-void AudioTrack::getAuxEffectSendLevel(float* level) const
-{
-    if (level != NULL) {
-        *level = mSendLevel;
-    }
-}
-
-status_t AudioTrack::setSampleRate(uint32_t rate)
-{
-    AutoMutex lock(mLock);
-    if (rate == mSampleRate) {
-        return NO_ERROR;
-    }
-    if (isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
-        return INVALID_OPERATION;
-    }
-    if (mOutput == AUDIO_IO_HANDLE_NONE) {
-        return NO_INIT;
-    }
-    // NOTE: it is theoretically possible, but highly unlikely, that a device change
-    // could mean a previously allowed sampling rate is no longer allowed.
-    uint32_t afSamplingRate;
-    if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
-        return NO_INIT;
-    }
-    // pitch is emulated by adjusting speed and sampleRate
-    const uint32_t effectiveSampleRate = adjustSampleRate(rate, mPlaybackRate.mPitch);
-    if (rate == 0 || effectiveSampleRate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
-        return BAD_VALUE;
-    }
-    // TODO: Should we also check if the buffer size is compatible?
-
-    mSampleRate = rate;
-    mProxy->setSampleRate(effectiveSampleRate);
-
-    return NO_ERROR;
-}
-
-uint32_t AudioTrack::getSampleRate() const
-{
-    AutoMutex lock(mLock);
-
-    // sample rate can be updated during playback by the offloaded decoder so we need to
-    // query the HAL and update if needed.
-// FIXME use Proxy return channel to update the rate from server and avoid polling here
-    if (isOffloadedOrDirect_l()) {
-        if (mOutput != AUDIO_IO_HANDLE_NONE) {
-            uint32_t sampleRate = 0;
-            status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
-            if (status == NO_ERROR) {
-                mSampleRate = sampleRate;
-            }
-        }
-    }
-    return mSampleRate;
-}
-
-uint32_t AudioTrack::getOriginalSampleRate() const
-{
-    return mOriginalSampleRate;
-}
-
-status_t AudioTrack::setPlaybackRate(const AudioPlaybackRate &playbackRate)
-{
-    AutoMutex lock(mLock);
-    if (isAudioPlaybackRateEqual(playbackRate, mPlaybackRate)) {
-        return NO_ERROR;
-    }
-    if (isOffloadedOrDirect_l()) {
-        return INVALID_OPERATION;
-    }
-    if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
-        return INVALID_OPERATION;
-    }
-
-    ALOGV("setPlaybackRate (input): mSampleRate:%u  mSpeed:%f  mPitch:%f",
-            mSampleRate, playbackRate.mSpeed, playbackRate.mPitch);
-    // pitch is emulated by adjusting speed and sampleRate
-    const uint32_t effectiveRate = adjustSampleRate(mSampleRate, playbackRate.mPitch);
-    const float effectiveSpeed = adjustSpeed(playbackRate.mSpeed, playbackRate.mPitch);
-    const float effectivePitch = adjustPitch(playbackRate.mPitch);
-    AudioPlaybackRate playbackRateTemp = playbackRate;
-    playbackRateTemp.mSpeed = effectiveSpeed;
-    playbackRateTemp.mPitch = effectivePitch;
-
-    ALOGV("setPlaybackRate (effective): mSampleRate:%u  mSpeed:%f  mPitch:%f",
-            effectiveRate, effectiveSpeed, effectivePitch);
-
-    if (!isAudioPlaybackRateValid(playbackRateTemp)) {
-        ALOGV("setPlaybackRate(%f, %f) failed (effective rate out of bounds)",
-                playbackRate.mSpeed, playbackRate.mPitch);
-        return BAD_VALUE;
-    }
-    // Check if the buffer size is compatible.
-    if (!isSampleRateSpeedAllowed_l(effectiveRate, effectiveSpeed)) {
-        ALOGV("setPlaybackRate(%f, %f) failed (buffer size)",
-                playbackRate.mSpeed, playbackRate.mPitch);
-        return BAD_VALUE;
-    }
-
-    // Check resampler ratios are within bounds
-    if ((uint64_t)effectiveRate > (uint64_t)mSampleRate * (uint64_t)AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
-        ALOGV("setPlaybackRate(%f, %f) failed. Resample rate exceeds max accepted value",
-                playbackRate.mSpeed, playbackRate.mPitch);
-        return BAD_VALUE;
-    }
-
-    if ((uint64_t)effectiveRate * (uint64_t)AUDIO_RESAMPLER_UP_RATIO_MAX < (uint64_t)mSampleRate) {
-        ALOGV("setPlaybackRate(%f, %f) failed. Resample rate below min accepted value",
-                        playbackRate.mSpeed, playbackRate.mPitch);
-        return BAD_VALUE;
-    }
-    mPlaybackRate = playbackRate;
-    //set effective rates
-    mProxy->setPlaybackRate(playbackRateTemp);
-    mProxy->setSampleRate(effectiveRate); // FIXME: not quite "atomic" with setPlaybackRate
-    return NO_ERROR;
-}
-
-const AudioPlaybackRate& AudioTrack::getPlaybackRate() const
-{
-    AutoMutex lock(mLock);
-    return mPlaybackRate;
-}
-
-ssize_t AudioTrack::getBufferSizeInFrames()
-{
-    AutoMutex lock(mLock);
-    if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
-        return NO_INIT;
-    }
-    return (ssize_t) mProxy->getBufferSizeInFrames();
-}
-
-status_t AudioTrack::getBufferDurationInUs(int64_t *duration)
-{
-    if (duration == nullptr) {
-        return BAD_VALUE;
-    }
-    AutoMutex lock(mLock);
-    if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
-        return NO_INIT;
-    }
-    ssize_t bufferSizeInFrames = (ssize_t) mProxy->getBufferSizeInFrames();
-    if (bufferSizeInFrames < 0) {
-        return (status_t)bufferSizeInFrames;
-    }
-    *duration = (int64_t)((double)bufferSizeInFrames * 1000000
-            / ((double)mSampleRate * mPlaybackRate.mSpeed));
-    return NO_ERROR;
-}
-
-ssize_t AudioTrack::setBufferSizeInFrames(size_t bufferSizeInFrames)
-{
-    AutoMutex lock(mLock);
-    if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) {
-        return NO_INIT;
-    }
-    // Reject if timed track or compressed audio.
-    if (!audio_is_linear_pcm(mFormat)) {
-        return INVALID_OPERATION;
-    }
-    return (ssize_t) mProxy->setBufferSizeInFrames((uint32_t) bufferSizeInFrames);
-}
-
-status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
-{
-    if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
-        return INVALID_OPERATION;
-    }
-
-    if (loopCount == 0) {
-        ;
-    } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
-            loopEnd - loopStart >= MIN_LOOP) {
-        ;
-    } else {
-        return BAD_VALUE;
-    }
-
-    AutoMutex lock(mLock);
-    // See setPosition() regarding setting parameters such as loop points or position while active
-    if (mState == STATE_ACTIVE) {
-        return INVALID_OPERATION;
-    }
-    setLoop_l(loopStart, loopEnd, loopCount);
-    return NO_ERROR;
-}
-
-void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
-{
-    // We do not update the periodic notification point.
-    // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
-    mLoopCount = loopCount;
-    mLoopEnd = loopEnd;
-    mLoopStart = loopStart;
-    mLoopCountNotified = loopCount;
-    mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
-
-    // Waking the AudioTrackThread is not needed as this cannot be called when active.
-}
-
-status_t AudioTrack::setMarkerPosition(uint32_t marker)
-{
-    // The only purpose of setting marker position is to get a callback
-    if (mCbf == NULL || isOffloadedOrDirect()) {
-        return INVALID_OPERATION;
-    }
-
-    AutoMutex lock(mLock);
-    mMarkerPosition = marker;
-    mMarkerReached = false;
-
-    sp<AudioTrackThread> t = mAudioTrackThread;
-    if (t != 0) {
-        t->wake();
-    }
-    return NO_ERROR;
-}
-
-status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
-{
-    if (isOffloadedOrDirect()) {
-        return INVALID_OPERATION;
-    }
-    if (marker == NULL) {
-        return BAD_VALUE;
-    }
-
-    AutoMutex lock(mLock);
-    mMarkerPosition.getValue(marker);
-
-    return NO_ERROR;
-}
-
-status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
-{
-    // The only purpose of setting position update period is to get a callback
-    if (mCbf == NULL || isOffloadedOrDirect()) {
-        return INVALID_OPERATION;
-    }
-
-    AutoMutex lock(mLock);
-    mNewPosition = updateAndGetPosition_l() + updatePeriod;
-    mUpdatePeriod = updatePeriod;
-
-    sp<AudioTrackThread> t = mAudioTrackThread;
-    if (t != 0) {
-        t->wake();
-    }
-    return NO_ERROR;
-}
-
-status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
-{
-    if (isOffloadedOrDirect()) {
-        return INVALID_OPERATION;
-    }
-    if (updatePeriod == NULL) {
-        return BAD_VALUE;
-    }
-
-    AutoMutex lock(mLock);
-    *updatePeriod = mUpdatePeriod;
-
-    return NO_ERROR;
-}
-
-status_t AudioTrack::setPosition(uint32_t position)
-{
-    if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
-        return INVALID_OPERATION;
-    }
-    if (position > mFrameCount) {
-        return BAD_VALUE;
-    }
-
-    AutoMutex lock(mLock);
-    // Currently we require that the player is inactive before setting parameters such as position
-    // or loop points.  Otherwise, there could be a race condition: the application could read the
-    // current position, compute a new position or loop parameters, and then set that position or
-    // loop parameters but it would do the "wrong" thing since the position has continued to advance
-    // in the mean time.  If we ever provide a sequencer in server, we could allow a way for the app
-    // to specify how it wants to handle such scenarios.
-    if (mState == STATE_ACTIVE) {
-        return INVALID_OPERATION;
-    }
-    // After setting the position, use full update period before notification.
-    mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
-    mStaticProxy->setBufferPosition(position);
-
-    // Waking the AudioTrackThread is not needed as this cannot be called when active.
-    return NO_ERROR;
-}
-
-status_t AudioTrack::getPosition(uint32_t *position)
-{
-    if (position == NULL) {
-        return BAD_VALUE;
-    }
-
-    AutoMutex lock(mLock);
-    // FIXME: offloaded and direct tracks call into the HAL for render positions
-    // for compressed/synced data; however, we use proxy position for pure linear pcm data
-    // as we do not know the capability of the HAL for pcm position support and standby.
-    // There may be some latency differences between the HAL position and the proxy position.
-    if (isOffloadedOrDirect_l() && !isPurePcmData_l()) {
-        uint32_t dspFrames = 0;
-
-        if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
-            ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
-            *position = mPausedPosition;
-            return NO_ERROR;
-        }
-
-        if (mOutput != AUDIO_IO_HANDLE_NONE) {
-            uint32_t halFrames; // actually unused
-            (void) AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
-            // FIXME: on getRenderPosition() error, we return OK with frame position 0.
-        }
-        // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
-        // due to hardware latency. We leave this behavior for now.
-        *position = dspFrames;
-    } else {
-        if (mCblk->mFlags & CBLK_INVALID) {
-            (void) restoreTrack_l("getPosition");
-            // FIXME: for compatibility with the Java API we ignore the restoreTrack_l()
-            // error here (e.g. DEAD_OBJECT) and return OK with the last recorded server position.
-        }
-
-        // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
-        *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
-                0 : updateAndGetPosition_l().value();
-    }
-    return NO_ERROR;
-}
-
-status_t AudioTrack::getBufferPosition(uint32_t *position)
-{
-    if (mSharedBuffer == 0) {
-        return INVALID_OPERATION;
-    }
-    if (position == NULL) {
-        return BAD_VALUE;
-    }
-
-    AutoMutex lock(mLock);
-    *position = mStaticProxy->getBufferPosition();
-    return NO_ERROR;
-}
-
-status_t AudioTrack::reload()
-{
-    if (mSharedBuffer == 0 || isOffloadedOrDirect()) {
-        return INVALID_OPERATION;
-    }
-
-    AutoMutex lock(mLock);
-    // See setPosition() regarding setting parameters such as loop points or position while active
-    if (mState == STATE_ACTIVE) {
-        return INVALID_OPERATION;
-    }
-    mNewPosition = mUpdatePeriod;
-    (void) updateAndGetPosition_l();
-    mPosition = 0;
-    mPreviousTimestampValid = false;
-#if 0
-    // The documentation is not clear on the behavior of reload() and the restoration
-    // of loop count. Historically we have not restored loop count, start, end,
-    // but it makes sense if one desires to repeat playing a particular sound.
-    if (mLoopCount != 0) {
-        mLoopCountNotified = mLoopCount;
-        mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
-    }
-#endif
-    mStaticProxy->setBufferPosition(0);
-    return NO_ERROR;
-}
-
-audio_io_handle_t AudioTrack::getOutput() const
-{
-    AutoMutex lock(mLock);
-    return mOutput;
-}
-
-status_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) {
-    AutoMutex lock(mLock);
-    if (mSelectedDeviceId != deviceId) {
-        mSelectedDeviceId = deviceId;
-        android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
-    }
-    return NO_ERROR;
-}
-
-audio_port_handle_t AudioTrack::getOutputDevice() {
-    AutoMutex lock(mLock);
-    return mSelectedDeviceId;
-}
-
-audio_port_handle_t AudioTrack::getRoutedDeviceId() {
-    AutoMutex lock(mLock);
-    if (mOutput == AUDIO_IO_HANDLE_NONE) {
-        return AUDIO_PORT_HANDLE_NONE;
-    }
-    return AudioSystem::getDeviceIdForIo(mOutput);
-}
-
-status_t AudioTrack::attachAuxEffect(int effectId)
-{
-    AutoMutex lock(mLock);
-    status_t status = mAudioTrack->attachAuxEffect(effectId);
-    if (status == NO_ERROR) {
-        mAuxEffectId = effectId;
-    }
-    return status;
-}
-
-audio_stream_type_t AudioTrack::streamType() const
-{
-    if (mStreamType == AUDIO_STREAM_DEFAULT) {
-        return audio_attributes_to_stream_type(&mAttributes);
-    }
-    return mStreamType;
-}
-
-// -------------------------------------------------------------------------
-
-// must be called with mLock held
-status_t AudioTrack::createTrack_l()
-{
-    const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
-    if (audioFlinger == 0) {
-        ALOGE("Could not get audioflinger");
-        return NO_INIT;
-    }
-
-    if (mDeviceCallback != 0 && mOutput != AUDIO_IO_HANDLE_NONE) {
-        AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
-    }
-    audio_io_handle_t output;
-    audio_stream_type_t streamType = mStreamType;
-    audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
-
-    // mFlags (not mOrigFlags) is modified depending on whether fast request is accepted.
-    // After fast request is denied, we will request again if IAudioTrack is re-created.
-
-    status_t status;
-    status = AudioSystem::getOutputForAttr(attr, &output,
-                                           mSessionId, &streamType, mClientUid,
-                                           mSampleRate, mFormat, mChannelMask,
-                                           mFlags, mSelectedDeviceId, mOffloadInfo);
-
-    if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
-        ALOGE("Could not get audio output for session %d, stream type %d, usage %d, sample rate %u, format %#x,"
-              " channel mask %#x, flags %#x",
-              mSessionId, streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
-        return BAD_VALUE;
-    }
-    {
-    // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
-    // we must release it ourselves if anything goes wrong.
-
-    // Not all of these values are needed under all conditions, but it is easier to get them all
-    status = AudioSystem::getLatency(output, &mAfLatency);
-    if (status != NO_ERROR) {
-        ALOGE("getLatency(%d) failed status %d", output, status);
-        goto release;
-    }
-    ALOGV("createTrack_l() output %d afLatency %u", output, mAfLatency);
-
-    status = AudioSystem::getFrameCount(output, &mAfFrameCount);
-    if (status != NO_ERROR) {
-        ALOGE("getFrameCount(output=%d) status %d", output, status);
-        goto release;
-    }
-
-    // TODO consider making this a member variable if there are other uses for it later
-    size_t afFrameCountHAL;
-    status = AudioSystem::getFrameCountHAL(output, &afFrameCountHAL);
-    if (status != NO_ERROR) {
-        ALOGE("getFrameCountHAL(output=%d) status %d", output, status);
-        goto release;
-    }
-    ALOG_ASSERT(afFrameCountHAL > 0);
-
-    status = AudioSystem::getSamplingRate(output, &mAfSampleRate);
-    if (status != NO_ERROR) {
-        ALOGE("getSamplingRate(output=%d) status %d", output, status);
-        goto release;
-    }
-    if (mSampleRate == 0) {
-        mSampleRate = mAfSampleRate;
-        mOriginalSampleRate = mAfSampleRate;
-    }
-
-    // Client can only express a preference for FAST.  Server will perform additional tests.
-    if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
-        bool useCaseAllowed =
-            // either of these use cases:
-            // use case 1: shared buffer
-            (mSharedBuffer != 0) ||
-            // use case 2: callback transfer mode
-            (mTransfer == TRANSFER_CALLBACK) ||
-            // use case 3: obtain/release mode
-            (mTransfer == TRANSFER_OBTAIN) ||
-            // use case 4: synchronous write
-            ((mTransfer == TRANSFER_SYNC) && mThreadCanCallJava);
-        // sample rates must also match
-        bool fastAllowed = useCaseAllowed && (mSampleRate == mAfSampleRate);
-        if (!fastAllowed) {
-            ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client; transfer %d, "
-                "track %u Hz, output %u Hz",
-                mTransfer, mSampleRate, mAfSampleRate);
-            mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
-        }
-    }
-
-    mNotificationFramesAct = mNotificationFramesReq;
-
-    size_t frameCount = mReqFrameCount;
-    if (!audio_has_proportional_frames(mFormat)) {
-
-        if (mSharedBuffer != 0) {
-            // Same comment as below about ignoring frameCount parameter for set()
-            frameCount = mSharedBuffer->size();
-        } else if (frameCount == 0) {
-            frameCount = mAfFrameCount;
-        }
-        if (mNotificationFramesAct != frameCount) {
-            mNotificationFramesAct = frameCount;
-        }
-    } else if (mSharedBuffer != 0) {
-        // FIXME: Ensure client side memory buffers need
-        // not have additional alignment beyond sample
-        // (e.g. 16 bit stereo accessed as 32 bit frame).
-        size_t alignment = audio_bytes_per_sample(mFormat);
-        if (alignment & 1) {
-            // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
-            alignment = 1;
-        }
-        if (mChannelCount > 1) {
-            // More than 2 channels does not require stronger alignment than stereo
-            alignment <<= 1;
-        }
-        if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
-            ALOGE("Invalid buffer alignment: address %p, channel count %u",
-                    mSharedBuffer->pointer(), mChannelCount);
-            status = BAD_VALUE;
-            goto release;
-        }
-
-        // When initializing a shared buffer AudioTrack via constructors,
-        // there's no frameCount parameter.
-        // But when initializing a shared buffer AudioTrack via set(),
-        // there _is_ a frameCount parameter.  We silently ignore it.
-        frameCount = mSharedBuffer->size() / mFrameSize;
-    } else {
-        size_t minFrameCount = 0;
-        // For fast tracks the frame count calculations and checks are mostly done by server,
-        // but we try to respect the application's request for notifications per buffer.
-        if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
-            if (mNotificationsPerBufferReq > 0) {
-                // Avoid possible arithmetic overflow during multiplication.
-                // mNotificationsPerBuffer is clamped to a small integer earlier, so it is unlikely.
-                if (mNotificationsPerBufferReq > SIZE_MAX / afFrameCountHAL) {
-                    ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
-                            mNotificationsPerBufferReq, afFrameCountHAL);
-                } else {
-                    minFrameCount = afFrameCountHAL * mNotificationsPerBufferReq;
-                }
-            }
-        } else {
-            // for normal tracks precompute the frame count based on speed.
-            const float speed = !isPurePcmData_l() || isOffloadedOrDirect_l() ? 1.0f :
-                            max(mMaxRequiredSpeed, mPlaybackRate.mSpeed);
-            minFrameCount = calculateMinFrameCount(
-                    mAfLatency, mAfFrameCount, mAfSampleRate, mSampleRate,
-                    speed /*, 0 mNotificationsPerBufferReq*/);
-        }
-        if (frameCount < minFrameCount) {
-            frameCount = minFrameCount;
-        }
-    }
-
-    audio_output_flags_t flags = mFlags;
-
-    pid_t tid = -1;
-    if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
-        if (mAudioTrackThread != 0 && !mThreadCanCallJava) {
-            tid = mAudioTrackThread->getTid();
-        }
-    }
-
-    size_t temp = frameCount;   // temp may be replaced by a revised value of frameCount,
-                                // but we will still need the original value also
-    audio_session_t originalSessionId = mSessionId;
-    sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
-                                                      mSampleRate,
-                                                      mFormat,
-                                                      mChannelMask,
-                                                      &temp,
-                                                      &flags,
-                                                      mSharedBuffer,
-                                                      output,
-                                                      mClientPid,
-                                                      tid,
-                                                      &mSessionId,
-                                                      mClientUid,
-                                                      &status);
-    ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
-            "session ID changed from %d to %d", originalSessionId, mSessionId);
-
-    if (status != NO_ERROR) {
-        ALOGE("AudioFlinger could not create track, status: %d", status);
-        goto release;
-    }
-    ALOG_ASSERT(track != 0);
-
-    // AudioFlinger now owns the reference to the I/O handle,
-    // so we are no longer responsible for releasing it.
-
-    // FIXME compare to AudioRecord
-    sp<IMemory> iMem = track->getCblk();
-    if (iMem == 0) {
-        ALOGE("Could not get control block");
-        return NO_INIT;
-    }
-    void *iMemPointer = iMem->pointer();
-    if (iMemPointer == NULL) {
-        ALOGE("Could not get control block pointer");
-        return NO_INIT;
-    }
-    // invariant that mAudioTrack != 0 is true only after set() returns successfully
-    if (mAudioTrack != 0) {
-        IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
-        mDeathNotifier.clear();
-    }
-    mAudioTrack = track;
-    mCblkMemory = iMem;
-    IPCThreadState::self()->flushCommands();
-
-    audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
-    mCblk = cblk;
-    // note that temp is the (possibly revised) value of frameCount
-    if (temp < frameCount || (frameCount == 0 && temp == 0)) {
-        // In current design, AudioTrack client checks and ensures frame count validity before
-        // passing it to AudioFlinger so AudioFlinger should not return a different value except
-        // for fast track as it uses a special method of assigning frame count.
-        ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
-    }
-    frameCount = temp;
-
-    mAwaitBoost = false;
-    if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
-        if (flags & AUDIO_OUTPUT_FLAG_FAST) {
-            ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
-            if (!mThreadCanCallJava) {
-                mAwaitBoost = true;
-            }
-        } else {
-            ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
-        }
-    }
-    mFlags = flags;
-
-    // Make sure that application is notified with sufficient margin before underrun.
-    // The client can divide the AudioTrack buffer into sub-buffers,
-    // and expresses its desire to server as the notification frame count.
-    if (mSharedBuffer == 0 && audio_is_linear_pcm(mFormat)) {
-        size_t maxNotificationFrames;
-        if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
-            // notify every HAL buffer, regardless of the size of the track buffer
-            maxNotificationFrames = afFrameCountHAL;
-        } else {
-            // For normal tracks, use at least double-buffering if no sample rate conversion,
-            // or at least triple-buffering if there is sample rate conversion
-            const int nBuffering = mOriginalSampleRate == mAfSampleRate ? 2 : 3;
-            maxNotificationFrames = frameCount / nBuffering;
-        }
-        if (mNotificationFramesAct == 0 || mNotificationFramesAct > maxNotificationFrames) {
-            if (mNotificationFramesAct == 0) {
-                ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
-                    maxNotificationFrames, frameCount);
-            } else {
-                ALOGW("Client adjusted notificationFrames from %u to %zu for frameCount %zu",
-                    mNotificationFramesAct, maxNotificationFrames, frameCount);
-            }
-            mNotificationFramesAct = (uint32_t) maxNotificationFrames;
-        }
-    }
-
-    // We retain a copy of the I/O handle, but don't own the reference
-    mOutput = output;
-    mRefreshRemaining = true;
-
-    // Starting address of buffers in shared memory.  If there is a shared buffer, buffers
-    // is the value of pointer() for the shared buffer, otherwise buffers points
-    // immediately after the control block.  This address is for the mapping within client
-    // address space.  AudioFlinger::TrackBase::mBuffer is for the server address space.
-    void* buffers;
-    if (mSharedBuffer == 0) {
-        buffers = cblk + 1;
-    } else {
-        buffers = mSharedBuffer->pointer();
-        if (buffers == NULL) {
-            ALOGE("Could not get buffer pointer");
-            return NO_INIT;
-        }
-    }
-
-    mAudioTrack->attachAuxEffect(mAuxEffectId);
-    // FIXME doesn't take into account speed or future sample rate changes (until restoreTrack)
-    // FIXME don't believe this lie
-    mLatency = mAfLatency + (1000*frameCount) / mSampleRate;
-
-    mFrameCount = frameCount;
-    // If IAudioTrack is re-created, don't let the requested frameCount
-    // decrease.  This can confuse clients that cache frameCount().
-    if (frameCount > mReqFrameCount) {
-        mReqFrameCount = frameCount;
-    }
-
-    // reset server position to 0 as we have new cblk.
-    mServer = 0;
-
-    // update proxy
-    if (mSharedBuffer == 0) {
-        mStaticProxy.clear();
-        mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
-    } else {
-        mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
-        mProxy = mStaticProxy;
-    }
-
-    mProxy->setVolumeLR(gain_minifloat_pack(
-            gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
-            gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
-
-    mProxy->setSendLevel(mSendLevel);
-    const uint32_t effectiveSampleRate = adjustSampleRate(mSampleRate, mPlaybackRate.mPitch);
-    const float effectiveSpeed = adjustSpeed(mPlaybackRate.mSpeed, mPlaybackRate.mPitch);
-    const float effectivePitch = adjustPitch(mPlaybackRate.mPitch);
-    mProxy->setSampleRate(effectiveSampleRate);
-
-    AudioPlaybackRate playbackRateTemp = mPlaybackRate;
-    playbackRateTemp.mSpeed = effectiveSpeed;
-    playbackRateTemp.mPitch = effectivePitch;
-    mProxy->setPlaybackRate(playbackRateTemp);
-    mProxy->setMinimum(mNotificationFramesAct);
-
-    mDeathNotifier = new DeathNotifier(this);
-    IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
-
-    if (mDeviceCallback != 0) {
-        AudioSystem::addAudioDeviceCallback(mDeviceCallback, mOutput);
-    }
-
-    return NO_ERROR;
-    }
-
-release:
-    AudioSystem::releaseOutput(output, streamType, mSessionId);
-    if (status == NO_ERROR) {
-        status = NO_INIT;
-    }
-    return status;
-}
-
-status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
-{
-    if (audioBuffer == NULL) {
-        if (nonContig != NULL) {
-            *nonContig = 0;
-        }
-        return BAD_VALUE;
-    }
-    if (mTransfer != TRANSFER_OBTAIN) {
-        audioBuffer->frameCount = 0;
-        audioBuffer->size = 0;
-        audioBuffer->raw = NULL;
-        if (nonContig != NULL) {
-            *nonContig = 0;
-        }
-        return INVALID_OPERATION;
-    }
-
-    const struct timespec *requested;
-    struct timespec timeout;
-    if (waitCount == -1) {
-        requested = &ClientProxy::kForever;
-    } else if (waitCount == 0) {
-        requested = &ClientProxy::kNonBlocking;
-    } else if (waitCount > 0) {
-        long long ms = WAIT_PERIOD_MS * (long long) waitCount;
-        timeout.tv_sec = ms / 1000;
-        timeout.tv_nsec = (int) (ms % 1000) * 1000000;
-        requested = &timeout;
-    } else {
-        ALOGE("%s invalid waitCount %d", __func__, waitCount);
-        requested = NULL;
-    }
-    return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
-}
-
-status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
-        struct timespec *elapsed, size_t *nonContig)
-{
-    // previous and new IAudioTrack sequence numbers are used to detect track re-creation
-    uint32_t oldSequence = 0;
-    uint32_t newSequence;
-
-    Proxy::Buffer buffer;
-    status_t status = NO_ERROR;
-
-    static const int32_t kMaxTries = 5;
-    int32_t tryCounter = kMaxTries;
-
-    do {
-        // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
-        // keep them from going away if another thread re-creates the track during obtainBuffer()
-        sp<AudioTrackClientProxy> proxy;
-        sp<IMemory> iMem;
-
-        {   // start of lock scope
-            AutoMutex lock(mLock);
-
-            newSequence = mSequence;
-            // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
-            if (status == DEAD_OBJECT) {
-                // re-create track, unless someone else has already done so
-                if (newSequence == oldSequence) {
-                    status = restoreTrack_l("obtainBuffer");
-                    if (status != NO_ERROR) {
-                        buffer.mFrameCount = 0;
-                        buffer.mRaw = NULL;
-                        buffer.mNonContig = 0;
-                        break;
-                    }
-                }
-            }
-            oldSequence = newSequence;
-
-            if (status == NOT_ENOUGH_DATA) {
-                restartIfDisabled();
-            }
-
-            // Keep the extra references
-            proxy = mProxy;
-            iMem = mCblkMemory;
-
-            if (mState == STATE_STOPPING) {
-                status = -EINTR;
-                buffer.mFrameCount = 0;
-                buffer.mRaw = NULL;
-                buffer.mNonContig = 0;
-                break;
-            }
-
-            // Non-blocking if track is stopped or paused
-            if (mState != STATE_ACTIVE) {
-                requested = &ClientProxy::kNonBlocking;
-            }
-
-        }   // end of lock scope
-
-        buffer.mFrameCount = audioBuffer->frameCount;
-        // FIXME starts the requested timeout and elapsed over from scratch
-        status = proxy->obtainBuffer(&buffer, requested, elapsed);
-    } while (((status == DEAD_OBJECT) || (status == NOT_ENOUGH_DATA)) && (tryCounter-- > 0));
-
-    audioBuffer->frameCount = buffer.mFrameCount;
-    audioBuffer->size = buffer.mFrameCount * mFrameSize;
-    audioBuffer->raw = buffer.mRaw;
-    if (nonContig != NULL) {
-        *nonContig = buffer.mNonContig;
-    }
-    return status;
-}
-
-void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
-{
-    // FIXME add error checking on mode, by adding an internal version
-    if (mTransfer == TRANSFER_SHARED) {
-        return;
-    }
-
-    size_t stepCount = audioBuffer->size / mFrameSize;
-    if (stepCount == 0) {
-        return;
-    }
-
-    Proxy::Buffer buffer;
-    buffer.mFrameCount = stepCount;
-    buffer.mRaw = audioBuffer->raw;
-
-    AutoMutex lock(mLock);
-    mReleased += stepCount;
-    mInUnderrun = false;
-    mProxy->releaseBuffer(&buffer);
-
-    // restart track if it was disabled by audioflinger due to previous underrun
-    restartIfDisabled();
-}
-
-void AudioTrack::restartIfDisabled()
-{
-    int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
-    if ((mState == STATE_ACTIVE) && (flags & CBLK_DISABLED)) {
-        ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
-        // FIXME ignoring status
-        mAudioTrack->start();
-    }
-}
-
-// -------------------------------------------------------------------------
-
-ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
-{
-    if (mTransfer != TRANSFER_SYNC) {
-        return INVALID_OPERATION;
-    }
-
-    if (isDirect()) {
-        AutoMutex lock(mLock);
-        int32_t flags = android_atomic_and(
-                            ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
-                            &mCblk->mFlags);
-        if (flags & CBLK_INVALID) {
-            return DEAD_OBJECT;
-        }
-    }
-
-    if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
-        // Sanity-check: user is most-likely passing an error code, and it would
-        // make the return value ambiguous (actualSize vs error).
-        ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
-        return BAD_VALUE;
-    }
-
-    size_t written = 0;
-    Buffer audioBuffer;
-
-    while (userSize >= mFrameSize) {
-        audioBuffer.frameCount = userSize / mFrameSize;
-
-        status_t err = obtainBuffer(&audioBuffer,
-                blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
-        if (err < 0) {
-            if (written > 0) {
-                break;
-            }
-            if (err == TIMED_OUT || err == -EINTR) {
-                err = WOULD_BLOCK;
-            }
-            return ssize_t(err);
-        }
-
-        size_t toWrite = audioBuffer.size;
-        memcpy(audioBuffer.i8, buffer, toWrite);
-        buffer = ((const char *) buffer) + toWrite;
-        userSize -= toWrite;
-        written += toWrite;
-
-        releaseBuffer(&audioBuffer);
-    }
-
-    if (written > 0) {
-        mFramesWritten += written / mFrameSize;
-    }
-    return written;
-}
-
-// -------------------------------------------------------------------------
-
-nsecs_t AudioTrack::processAudioBuffer()
-{
-    // Currently the AudioTrack thread is not created if there are no callbacks.
-    // Would it ever make sense to run the thread, even without callbacks?
-    // If so, then replace this by checks at each use for mCbf != NULL.
-    LOG_ALWAYS_FATAL_IF(mCblk == NULL);
-
-    mLock.lock();
-    if (mAwaitBoost) {
-        mAwaitBoost = false;
-        mLock.unlock();
-        static const int32_t kMaxTries = 5;
-        int32_t tryCounter = kMaxTries;
-        uint32_t pollUs = 10000;
-        do {
-            int policy = sched_getscheduler(0) & ~SCHED_RESET_ON_FORK;
-            if (policy == SCHED_FIFO || policy == SCHED_RR) {
-                break;
-            }
-            usleep(pollUs);
-            pollUs <<= 1;
-        } while (tryCounter-- > 0);
-        if (tryCounter < 0) {
-            ALOGE("did not receive expected priority boost on time");
-        }
-        // Run again immediately
-        return 0;
-    }
-
-    // Can only reference mCblk while locked
-    int32_t flags = android_atomic_and(
-        ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
-
-    // Check for track invalidation
-    if (flags & CBLK_INVALID) {
-        // for offloaded tracks restoreTrack_l() will just update the sequence and clear
-        // AudioSystem cache. We should not exit here but after calling the callback so
-        // that the upper layers can recreate the track
-        if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
-            status_t status __unused = restoreTrack_l("processAudioBuffer");
-            // FIXME unused status
-            // after restoration, continue below to make sure that the loop and buffer events
-            // are notified because they have been cleared from mCblk->mFlags above.
-        }
-    }
-
-    bool waitStreamEnd = mState == STATE_STOPPING;
-    bool active = mState == STATE_ACTIVE;
-
-    // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
-    bool newUnderrun = false;
-    if (flags & CBLK_UNDERRUN) {
-#if 0
-        // Currently in shared buffer mode, when the server reaches the end of buffer,
-        // the track stays active in continuous underrun state.  It's up to the application
-        // to pause or stop the track, or set the position to a new offset within buffer.
-        // This was some experimental code to auto-pause on underrun.   Keeping it here
-        // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
-        if (mTransfer == TRANSFER_SHARED) {
-            mState = STATE_PAUSED;
-            active = false;
-        }
-#endif
-        if (!mInUnderrun) {
-            mInUnderrun = true;
-            newUnderrun = true;
-        }
-    }
-
-    // Get current position of server
-    Modulo<uint32_t> position(updateAndGetPosition_l());
-
-    // Manage marker callback
-    bool markerReached = false;
-    Modulo<uint32_t> markerPosition(mMarkerPosition);
-    // uses 32 bit wraparound for comparison with position.
-    if (!mMarkerReached && markerPosition.value() > 0 && position >= markerPosition) {
-        mMarkerReached = markerReached = true;
-    }
-
-    // Determine number of new position callback(s) that will be needed, while locked
-    size_t newPosCount = 0;
-    Modulo<uint32_t> newPosition(mNewPosition);
-    uint32_t updatePeriod = mUpdatePeriod;
-    // FIXME fails for wraparound, need 64 bits
-    if (updatePeriod > 0 && position >= newPosition) {
-        newPosCount = ((position - newPosition).value() / updatePeriod) + 1;
-        mNewPosition += updatePeriod * newPosCount;
-    }
-
-    // Cache other fields that will be needed soon
-    uint32_t sampleRate = mSampleRate;
-    float speed = mPlaybackRate.mSpeed;
-    const uint32_t notificationFrames = mNotificationFramesAct;
-    if (mRefreshRemaining) {
-        mRefreshRemaining = false;
-        mRemainingFrames = notificationFrames;
-        mRetryOnPartialBuffer = false;
-    }
-    size_t misalignment = mProxy->getMisalignment();
-    uint32_t sequence = mSequence;
-    sp<AudioTrackClientProxy> proxy = mProxy;
-
-    // Determine the number of new loop callback(s) that will be needed, while locked.
-    int loopCountNotifications = 0;
-    uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
-
-    if (mLoopCount > 0) {
-        int loopCount;
-        size_t bufferPosition;
-        mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
-        loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
-        loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
-        mLoopCountNotified = loopCount; // discard any excess notifications
-    } else if (mLoopCount < 0) {
-        // FIXME: We're not accurate with notification count and position with infinite looping
-        // since loopCount from server side will always return -1 (we could decrement it).
-        size_t bufferPosition = mStaticProxy->getBufferPosition();
-        loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
-        loopPeriod = mLoopEnd - bufferPosition;
-    } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
-        size_t bufferPosition = mStaticProxy->getBufferPosition();
-        loopPeriod = mFrameCount - bufferPosition;
-    }
-
-    // These fields don't need to be cached, because they are assigned only by set():
-    //     mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
-    // mFlags is also assigned by createTrack_l(), but not the bit we care about.
-
-    mLock.unlock();
-
-    // get anchor time to account for callbacks.
-    const nsecs_t timeBeforeCallbacks = systemTime();
-
-    if (waitStreamEnd) {
-        // FIXME:  Instead of blocking in proxy->waitStreamEndDone(), Callback thread
-        // should wait on proxy futex and handle CBLK_STREAM_END_DONE within this function
-        // (and make sure we don't callback for more data while we're stopping).
-        // This helps with position, marker notifications, and track invalidation.
-        struct timespec timeout;
-        timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
-        timeout.tv_nsec = 0;
-
-        status_t status = proxy->waitStreamEndDone(&timeout);
-        switch (status) {
-        case NO_ERROR:
-        case DEAD_OBJECT:
-        case TIMED_OUT:
-            if (status != DEAD_OBJECT) {
-                // for DEAD_OBJECT, we do not send a EVENT_STREAM_END after stop();
-                // instead, the application should handle the EVENT_NEW_IAUDIOTRACK.
-                mCbf(EVENT_STREAM_END, mUserData, NULL);
-            }
-            {
-                AutoMutex lock(mLock);
-                // The previously assigned value of waitStreamEnd is no longer valid,
-                // since the mutex has been unlocked and either the callback handler
-                // or another thread could have re-started the AudioTrack during that time.
-                waitStreamEnd = mState == STATE_STOPPING;
-                if (waitStreamEnd) {
-                    mState = STATE_STOPPED;
-                    mReleased = 0;
-                }
-            }
-            if (waitStreamEnd && status != DEAD_OBJECT) {
-               return NS_INACTIVE;
-            }
-            break;
-        }
-        return 0;
-    }
-
-    // perform callbacks while unlocked
-    if (newUnderrun) {
-        mCbf(EVENT_UNDERRUN, mUserData, NULL);
-    }
-    while (loopCountNotifications > 0) {
-        mCbf(EVENT_LOOP_END, mUserData, NULL);
-        --loopCountNotifications;
-    }
-    if (flags & CBLK_BUFFER_END) {
-        mCbf(EVENT_BUFFER_END, mUserData, NULL);
-    }
-    if (markerReached) {
-        mCbf(EVENT_MARKER, mUserData, &markerPosition);
-    }
-    while (newPosCount > 0) {
-        size_t temp = newPosition.value(); // FIXME size_t != uint32_t
-        mCbf(EVENT_NEW_POS, mUserData, &temp);
-        newPosition += updatePeriod;
-        newPosCount--;
-    }
-
-    if (mObservedSequence != sequence) {
-        mObservedSequence = sequence;
-        mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
-        // for offloaded tracks, just wait for the upper layers to recreate the track
-        if (isOffloadedOrDirect()) {
-            return NS_INACTIVE;
-        }
-    }
-
-    // if inactive, then don't run me again until re-started
-    if (!active) {
-        return NS_INACTIVE;
-    }
-
-    // Compute the estimated time until the next timed event (position, markers, loops)
-    // FIXME only for non-compressed audio
-    uint32_t minFrames = ~0;
-    if (!markerReached && position < markerPosition) {
-        minFrames = (markerPosition - position).value();
-    }
-    if (loopPeriod > 0 && loopPeriod < minFrames) {
-        // loopPeriod is already adjusted for actual position.
-        minFrames = loopPeriod;
-    }
-    if (updatePeriod > 0) {
-        minFrames = min(minFrames, (newPosition - position).value());
-    }
-
-    // If > 0, poll periodically to recover from a stuck server.  A good value is 2.
-    static const uint32_t kPoll = 0;
-    if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
-        minFrames = kPoll * notificationFrames;
-    }
-
-    // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
-    static const nsecs_t kWaitPeriodNs = WAIT_PERIOD_MS * 1000000LL;
-    const nsecs_t timeAfterCallbacks = systemTime();
-
-    // Convert frame units to time units
-    nsecs_t ns = NS_WHENEVER;
-    if (minFrames != (uint32_t) ~0) {
-        ns = framesToNanoseconds(minFrames, sampleRate, speed) + kWaitPeriodNs;
-        ns -= (timeAfterCallbacks - timeBeforeCallbacks);  // account for callback time
-        // TODO: Should we warn if the callback time is too long?
-        if (ns < 0) ns = 0;
-    }
-
-    // If not supplying data by EVENT_MORE_DATA, then we're done
-    if (mTransfer != TRANSFER_CALLBACK) {
-        return ns;
-    }
-
-    // EVENT_MORE_DATA callback handling.
-    // Timing for linear pcm audio data formats can be derived directly from the
-    // buffer fill level.
-    // Timing for compressed data is not directly available from the buffer fill level,
-    // rather indirectly from waiting for blocking mode callbacks or waiting for obtain()
-    // to return a certain fill level.
-
-    struct timespec timeout;
-    const struct timespec *requested = &ClientProxy::kForever;
-    if (ns != NS_WHENEVER) {
-        timeout.tv_sec = ns / 1000000000LL;
-        timeout.tv_nsec = ns % 1000000000LL;
-        ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
-        requested = &timeout;
-    }
-
-    size_t writtenFrames = 0;
-    while (mRemainingFrames > 0) {
-
-        Buffer audioBuffer;
-        audioBuffer.frameCount = mRemainingFrames;
-        size_t nonContig;
-        status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
-        LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
-                "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
-        requested = &ClientProxy::kNonBlocking;
-        size_t avail = audioBuffer.frameCount + nonContig;
-        ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
-                mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
-        if (err != NO_ERROR) {
-            if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
-                    (isOffloaded() && (err == DEAD_OBJECT))) {
-                // FIXME bug 25195759
-                return 1000000;
-            }
-            ALOGE("Error %d obtaining an audio buffer, giving up.", err);
-            return NS_NEVER;
-        }
-
-        if (mRetryOnPartialBuffer && audio_has_proportional_frames(mFormat)) {
-            mRetryOnPartialBuffer = false;
-            if (avail < mRemainingFrames) {
-                if (ns > 0) { // account for obtain time
-                    const nsecs_t timeNow = systemTime();
-                    ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
-                }
-                nsecs_t myns = framesToNanoseconds(mRemainingFrames - avail, sampleRate, speed);
-                if (ns < 0 /* NS_WHENEVER */ || myns < ns) {
-                    ns = myns;
-                }
-                return ns;
-            }
-        }
-
-        size_t reqSize = audioBuffer.size;
-        mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
-        size_t writtenSize = audioBuffer.size;
-
-        // Sanity check on returned size
-        if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
-            ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
-                    reqSize, ssize_t(writtenSize));
-            return NS_NEVER;
-        }
-
-        if (writtenSize == 0) {
-            // The callback is done filling buffers
-            // Keep this thread going to handle timed events and
-            // still try to get more data in intervals of WAIT_PERIOD_MS
-            // but don't just loop and block the CPU, so wait
-
-            // mCbf(EVENT_MORE_DATA, ...) might either
-            // (1) Block until it can fill the buffer, returning 0 size on EOS.
-            // (2) Block until it can fill the buffer, returning 0 data (silence) on EOS.
-            // (3) Return 0 size when no data is available, does not wait for more data.
-            //
-            // (1) and (2) occurs with AudioPlayer/AwesomePlayer; (3) occurs with NuPlayer.
-            // We try to compute the wait time to avoid a tight sleep-wait cycle,
-            // especially for case (3).
-            //
-            // The decision to support (1) and (2) affect the sizing of mRemainingFrames
-            // and this loop; whereas for case (3) we could simply check once with the full
-            // buffer size and skip the loop entirely.
-
-            nsecs_t myns;
-            if (audio_has_proportional_frames(mFormat)) {
-                // time to wait based on buffer occupancy
-                const nsecs_t datans = mRemainingFrames <= avail ? 0 :
-                        framesToNanoseconds(mRemainingFrames - avail, sampleRate, speed);
-                // audio flinger thread buffer size (TODO: adjust for fast tracks)
-                // FIXME: use mAfFrameCountHAL instead of mAfFrameCount below for fast tracks.
-                const nsecs_t afns = framesToNanoseconds(mAfFrameCount, mAfSampleRate, speed);
-                // add a half the AudioFlinger buffer time to avoid soaking CPU if datans is 0.
-                myns = datans + (afns / 2);
-            } else {
-                // FIXME: This could ping quite a bit if the buffer isn't full.
-                // Note that when mState is stopping we waitStreamEnd, so it never gets here.
-                myns = kWaitPeriodNs;
-            }
-            if (ns > 0) { // account for obtain and callback time
-                const nsecs_t timeNow = systemTime();
-                ns = max((nsecs_t)0, ns - (timeNow - timeAfterCallbacks));
-            }
-            if (ns < 0 /* NS_WHENEVER */ || myns < ns) {
-                ns = myns;
-            }
-            return ns;
-        }
-
-        size_t releasedFrames = writtenSize / mFrameSize;
-        audioBuffer.frameCount = releasedFrames;
-        mRemainingFrames -= releasedFrames;
-        if (misalignment >= releasedFrames) {
-            misalignment -= releasedFrames;
-        } else {
-            misalignment = 0;
-        }
-
-        releaseBuffer(&audioBuffer);
-        writtenFrames += releasedFrames;
-
-        // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
-        // if callback doesn't like to accept the full chunk
-        if (writtenSize < reqSize) {
-            continue;
-        }
-
-        // There could be enough non-contiguous frames available to satisfy the remaining request
-        if (mRemainingFrames <= nonContig) {
-            continue;
-        }
-
-#if 0
-        // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
-        // sum <= notificationFrames.  It replaces that series by at most two EVENT_MORE_DATA
-        // that total to a sum == notificationFrames.
-        if (0 < misalignment && misalignment <= mRemainingFrames) {
-            mRemainingFrames = misalignment;
-            return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
-        }
-#endif
-
-    }
-    if (writtenFrames > 0) {
-        AutoMutex lock(mLock);
-        mFramesWritten += writtenFrames;
-    }
-    mRemainingFrames = notificationFrames;
-    mRetryOnPartialBuffer = true;
-
-    // A lot has transpired since ns was calculated, so run again immediately and re-calculate
-    return 0;
-}
-
-status_t AudioTrack::restoreTrack_l(const char *from)
-{
-    ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
-          isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
-    ++mSequence;
-
-    // refresh the audio configuration cache in this process to make sure we get new
-    // output parameters and new IAudioFlinger in createTrack_l()
-    AudioSystem::clearAudioConfigCache();
-
-    if (isOffloadedOrDirect_l() || mDoNotReconnect) {
-        // FIXME re-creation of offloaded and direct tracks is not yet implemented;
-        // reconsider enabling for linear PCM encodings when position can be preserved.
-        return DEAD_OBJECT;
-    }
-
-    // Save so we can return count since creation.
-    mUnderrunCountOffset = getUnderrunCount_l();
-
-    // save the old static buffer position
-    uint32_t staticPosition = 0;
-    size_t bufferPosition = 0;
-    int loopCount = 0;
-    if (mStaticProxy != 0) {
-        mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
-        staticPosition = mStaticProxy->getPosition().unsignedValue();
-    }
-
-    mFlags = mOrigFlags;
-
-    // If a new IAudioTrack is successfully created, createTrack_l() will modify the
-    // following member variables: mAudioTrack, mCblkMemory and mCblk.
-    // It will also delete the strong references on previous IAudioTrack and IMemory.
-    // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
-    status_t result = createTrack_l();
-
-    if (result == NO_ERROR) {
-        // take the frames that will be lost by track recreation into account in saved position
-        // For streaming tracks, this is the amount we obtained from the user/client
-        // (not the number actually consumed at the server - those are already lost).
-        if (mStaticProxy == 0) {
-            mPosition = mReleased;
-        }
-        // Continue playback from last known position and restore loop.
-        if (mStaticProxy != 0) {
-            if (loopCount != 0) {
-                mStaticProxy->setBufferPositionAndLoop(bufferPosition,
-                        mLoopStart, mLoopEnd, loopCount);
-            } else {
-                mStaticProxy->setBufferPosition(bufferPosition);
-                if (bufferPosition == mFrameCount) {
-                    ALOGD("restoring track at end of static buffer");
-                }
-            }
-        }
-        if (mState == STATE_ACTIVE) {
-            result = mAudioTrack->start();
-        }
-        // server resets to zero so we offset
-        mFramesWrittenServerOffset =
-                mStaticProxy.get() != nullptr ? staticPosition : mFramesWritten;
-        mFramesWrittenAtRestore = mFramesWrittenServerOffset;
-    }
-    if (result != NO_ERROR) {
-        ALOGW("restoreTrack_l() failed status %d", result);
-        mState = STATE_STOPPED;
-        mReleased = 0;
-    }
-
-    return result;
-}
-
-Modulo<uint32_t> AudioTrack::updateAndGetPosition_l()
-{
-    // This is the sole place to read server consumed frames
-    Modulo<uint32_t> newServer(mProxy->getPosition());
-    const int32_t delta = (newServer - mServer).signedValue();
-    // TODO There is controversy about whether there can be "negative jitter" in server position.
-    //      This should be investigated further, and if possible, it should be addressed.
-    //      A more definite failure mode is infrequent polling by client.
-    //      One could call (void)getPosition_l() in releaseBuffer(),
-    //      so mReleased and mPosition are always lock-step as best possible.
-    //      That should ensure delta never goes negative for infrequent polling
-    //      unless the server has more than 2^31 frames in its buffer,
-    //      in which case the use of uint32_t for these counters has bigger issues.
-    ALOGE_IF(delta < 0,
-            "detected illegal retrograde motion by the server: mServer advanced by %d",
-            delta);
-    mServer = newServer;
-    if (delta > 0) { // avoid retrograde
-        mPosition += delta;
-    }
-    return mPosition;
-}
-
-bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed) const
-{
-    // applicable for mixing tracks only (not offloaded or direct)
-    if (mStaticProxy != 0) {
-        return true; // static tracks do not have issues with buffer sizing.
-    }
-    const size_t minFrameCount =
-            calculateMinFrameCount(mAfLatency, mAfFrameCount, mAfSampleRate, sampleRate, speed
-                /*, 0 mNotificationsPerBufferReq*/);
-    ALOGV("isSampleRateSpeedAllowed_l mFrameCount %zu  minFrameCount %zu",
-            mFrameCount, minFrameCount);
-    return mFrameCount >= minFrameCount;
-}
-
-status_t AudioTrack::setParameters(const String8& keyValuePairs)
-{
-    AutoMutex lock(mLock);
-    return mAudioTrack->setParameters(keyValuePairs);
-}
-
-status_t AudioTrack::getTimestamp(ExtendedTimestamp *timestamp)
-{
-    if (timestamp == nullptr) {
-        return BAD_VALUE;
-    }
-    AutoMutex lock(mLock);
-    return getTimestamp_l(timestamp);
-}
-
-status_t AudioTrack::getTimestamp_l(ExtendedTimestamp *timestamp)
-{
-    if (mCblk->mFlags & CBLK_INVALID) {
-        const status_t status = restoreTrack_l("getTimestampExtended");
-        if (status != OK) {
-            // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
-            // recommending that the track be recreated.
-            return DEAD_OBJECT;
-        }
-    }
-    // check for offloaded/direct here in case restoring somehow changed those flags.
-    if (isOffloadedOrDirect_l()) {
-        return INVALID_OPERATION; // not supported
-    }
-    status_t status = mProxy->getTimestamp(timestamp);
-    LOG_ALWAYS_FATAL_IF(status != OK, "status %d not allowed from proxy getTimestamp", status);
-    bool found = false;
-    timestamp->mPosition[ExtendedTimestamp::LOCATION_CLIENT] = mFramesWritten;
-    timestamp->mTimeNs[ExtendedTimestamp::LOCATION_CLIENT] = 0;
-    // server side frame offset in case AudioTrack has been restored.
-    for (int i = ExtendedTimestamp::LOCATION_SERVER;
-            i < ExtendedTimestamp::LOCATION_MAX; ++i) {
-        if (timestamp->mTimeNs[i] >= 0) {
-            // apply server offset (frames flushed is ignored
-            // so we don't report the jump when the flush occurs).
-            timestamp->mPosition[i] += mFramesWrittenServerOffset;
-            found = true;
-        }
-    }
-    return found ? OK : WOULD_BLOCK;
-}
-
-status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
-{
-    AutoMutex lock(mLock);
-    return getTimestamp_l(timestamp);
-}
-
-status_t AudioTrack::getTimestamp_l(AudioTimestamp& timestamp)
-{
-    bool previousTimestampValid = mPreviousTimestampValid;
-    // Set false here to cover all the error return cases.
-    mPreviousTimestampValid = false;
-
-    switch (mState) {
-    case STATE_ACTIVE:
-    case STATE_PAUSED:
-        break; // handle below
-    case STATE_FLUSHED:
-    case STATE_STOPPED:
-        return WOULD_BLOCK;
-    case STATE_STOPPING:
-    case STATE_PAUSED_STOPPING:
-        if (!isOffloaded_l()) {
-            return INVALID_OPERATION;
-        }
-        break; // offloaded tracks handled below
-    default:
-        LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
-        break;
-    }
-
-    if (mCblk->mFlags & CBLK_INVALID) {
-        const status_t status = restoreTrack_l("getTimestamp");
-        if (status != OK) {
-            // per getTimestamp() API doc in header, we return DEAD_OBJECT here,
-            // recommending that the track be recreated.
-            return DEAD_OBJECT;
-        }
-    }
-
-    // The presented frame count must always lag behind the consumed frame count.
-    // To avoid a race, read the presented frames first.  This ensures that presented <= consumed.
-
-    status_t status;
-    if (isOffloadedOrDirect_l()) {
-        // use Binder to get timestamp
-        status = mAudioTrack->getTimestamp(timestamp);
-    } else {
-        // read timestamp from shared memory
-        ExtendedTimestamp ets;
-        status = mProxy->getTimestamp(&ets);
-        if (status == OK) {
-            ExtendedTimestamp::Location location;
-            status = ets.getBestTimestamp(&timestamp, &location);
-
-            if (status == OK) {
-                // It is possible that the best location has moved from the kernel to the server.
-                // In this case we adjust the position from the previous computed latency.
-                if (location == ExtendedTimestamp::LOCATION_SERVER) {
-                    ALOGW_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_KERNEL,
-                            "getTimestamp() location moved from kernel to server");
-                    // check that the last kernel OK time info exists and the positions
-                    // are valid (if they predate the current track, the positions may
-                    // be zero or negative).
-                    const int64_t frames =
-                            (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
-                            ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0 ||
-                            ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] <= 0 ||
-                            ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] <= 0)
-                            ?
-                            int64_t((double)mAfLatency * mSampleRate * mPlaybackRate.mSpeed
-                                    / 1000)
-                            :
-                            (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
-                            - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK]);
-                    ALOGV("frame adjustment:%lld  timestamp:%s",
-                            (long long)frames, ets.toString().c_str());
-                    if (frames >= ets.mPosition[location]) {
-                        timestamp.mPosition = 0;
-                    } else {
-                        timestamp.mPosition = (uint32_t)(ets.mPosition[location] - frames);
-                    }
-                } else if (location == ExtendedTimestamp::LOCATION_KERNEL) {
-                    ALOGV_IF(mPreviousLocation == ExtendedTimestamp::LOCATION_SERVER,
-                            "getTimestamp() location moved from server to kernel");
-                }
-
-                // We update the timestamp time even when paused.
-                if (mState == STATE_PAUSED /* not needed: STATE_PAUSED_STOPPING */) {
-                    const int64_t now = systemTime();
-                    const int64_t at = convertTimespecToNs(timestamp.mTime);
-                    const int64_t lag =
-                            (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
-                                ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0)
-                            ? int64_t(mAfLatency * 1000000LL)
-                            : (ets.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK]
-                             - ets.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK])
-                             * NANOS_PER_SECOND / mSampleRate;
-                    const int64_t limit = now - lag; // no earlier than this limit
-                    if (at < limit) {
-                        ALOGV("timestamp pause lag:%lld adjusting from %lld to %lld",
-                                (long long)lag, (long long)at, (long long)limit);
-                        timestamp.mTime.tv_sec = limit / NANOS_PER_SECOND;
-                        timestamp.mTime.tv_nsec = limit % NANOS_PER_SECOND; // compiler opt.
-                    }
-                }
-                mPreviousLocation = location;
-            } else {
-                // right after AudioTrack is started, one may not find a timestamp
-                ALOGV("getBestTimestamp did not find timestamp");
-            }
-        }
-        if (status == INVALID_OPERATION) {
-            // INVALID_OPERATION occurs when no timestamp has been issued by the server;
-            // other failures are signaled by a negative time.
-            // If we come out of FLUSHED or STOPPED where the position is known
-            // to be zero we convert this to WOULD_BLOCK (with the implicit meaning of
-            // "zero" for NuPlayer).  We don't convert for track restoration as position
-            // does not reset.
-            ALOGV("timestamp server offset:%lld restore frames:%lld",
-                    (long long)mFramesWrittenServerOffset, (long long)mFramesWrittenAtRestore);
-            if (mFramesWrittenServerOffset != mFramesWrittenAtRestore) {
-                status = WOULD_BLOCK;
-            }
-        }
-    }
-    if (status != NO_ERROR) {
-        ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
-        return status;
-    }
-    if (isOffloadedOrDirect_l()) {
-        if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
-            // use cached paused position in case another offloaded track is running.
-            timestamp.mPosition = mPausedPosition;
-            clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
-            // TODO: adjust for delay
-            return NO_ERROR;
-        }
-
-        // Check whether a pending flush or stop has completed, as those commands may
-        // be asynchronous or return near finish or exhibit glitchy behavior.
-        //
-        // Originally this showed up as the first timestamp being a continuation of
-        // the previous song under gapless playback.
-        // However, we sometimes see zero timestamps, then a glitch of
-        // the previous song's position, and then correct timestamps afterwards.
-        if (mStartUs != 0 && mSampleRate != 0) {
-            static const int kTimeJitterUs = 100000; // 100 ms
-            static const int k1SecUs = 1000000;
-
-            const int64_t timeNow = getNowUs();
-
-            if (timeNow < mStartUs + k1SecUs) { // within first second of starting
-                const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
-                if (timestampTimeUs < mStartUs) {
-                    return WOULD_BLOCK;  // stale timestamp time, occurs before start.
-                }
-                const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
-                const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
-                        / ((double)mSampleRate * mPlaybackRate.mSpeed);
-
-                if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
-                    // Verify that the counter can't count faster than the sample rate
-                    // since the start time.  If greater, then that means we may have failed
-                    // to completely flush or stop the previous playing track.
-                    ALOGW_IF(!mTimestampStartupGlitchReported,
-                            "getTimestamp startup glitch detected"
-                            " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
-                            (long long)deltaTimeUs, (long long)deltaPositionByUs,
-                            timestamp.mPosition);
-                    mTimestampStartupGlitchReported = true;
-                    if (previousTimestampValid
-                            && mPreviousTimestamp.mPosition == 0 /* should be true if valid */) {
-                        timestamp = mPreviousTimestamp;
-                        mPreviousTimestampValid = true;
-                        return NO_ERROR;
-                    }
-                    return WOULD_BLOCK;
-                }
-                if (deltaPositionByUs != 0) {
-                    mStartUs = 0; // don't check again, we got valid nonzero position.
-                }
-            } else {
-                mStartUs = 0; // don't check again, start time expired.
-            }
-            mTimestampStartupGlitchReported = false;
-        }
-    } else {
-        // Update the mapping between local consumed (mPosition) and server consumed (mServer)
-        (void) updateAndGetPosition_l();
-        // Server consumed (mServer) and presented both use the same server time base,
-        // and server consumed is always >= presented.
-        // The delta between these represents the number of frames in the buffer pipeline.
-        // If this delta between these is greater than the client position, it means that
-        // actually presented is still stuck at the starting line (figuratively speaking),
-        // waiting for the first frame to go by.  So we can't report a valid timestamp yet.
-        // Note: We explicitly use non-Modulo comparison here - potential wrap issue when
-        // mPosition exceeds 32 bits.
-        // TODO Remove when timestamp is updated to contain pipeline status info.
-        const int32_t pipelineDepthInFrames = (mServer - timestamp.mPosition).signedValue();
-        if (pipelineDepthInFrames > 0 /* should be true, but we check anyways */
-                && (uint32_t)pipelineDepthInFrames > mPosition.value()) {
-            return INVALID_OPERATION;
-        }
-        // Convert timestamp position from server time base to client time base.
-        // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
-        // But if we change it to 64-bit then this could fail.
-        // Use Modulo computation here.
-        timestamp.mPosition = (mPosition - mServer + timestamp.mPosition).value();
-        // Immediately after a call to getPosition_l(), mPosition and
-        // mServer both represent the same frame position.  mPosition is
-        // in client's point of view, and mServer is in server's point of
-        // view.  So the difference between them is the "fudge factor"
-        // between client and server views due to stop() and/or new
-        // IAudioTrack.  And timestamp.mPosition is initially in server's
-        // point of view, so we need to apply the same fudge factor to it.
-    }
-
-    // Prevent retrograde motion in timestamp.
-    // This is sometimes caused by erratic reports of the available space in the ALSA drivers.
-    if (status == NO_ERROR) {
-        if (previousTimestampValid) {
-            const int64_t previousTimeNanos = convertTimespecToNs(mPreviousTimestamp.mTime);
-            const int64_t currentTimeNanos = convertTimespecToNs(timestamp.mTime);
-            if (currentTimeNanos < previousTimeNanos) {
-                ALOGW("retrograde timestamp time corrected, %lld < %lld",
-                        (long long)currentTimeNanos, (long long)previousTimeNanos);
-                timestamp.mTime = mPreviousTimestamp.mTime;
-            }
-
-            // Looking at signed delta will work even when the timestamps
-            // are wrapping around.
-            int32_t deltaPosition = (Modulo<uint32_t>(timestamp.mPosition)
-                    - mPreviousTimestamp.mPosition).signedValue();
-            if (deltaPosition < 0) {
-                // Only report once per position instead of spamming the log.
-                if (!mRetrogradeMotionReported) {
-                    ALOGW("retrograde timestamp position corrected, %d = %u - %u",
-                            deltaPosition,
-                            timestamp.mPosition,
-                            mPreviousTimestamp.mPosition);
-                    mRetrogradeMotionReported = true;
-                }
-            } else {
-                mRetrogradeMotionReported = false;
-            }
-            if (deltaPosition < 0) {
-                timestamp.mPosition = mPreviousTimestamp.mPosition;
-                deltaPosition = 0;
-            }
-#if 0
-            // Uncomment this to verify audio timestamp rate.
-            const int64_t deltaTime =
-                    convertTimespecToNs(timestamp.mTime) - previousTimeNanos;
-            if (deltaTime != 0) {
-                const int64_t computedSampleRate =
-                        deltaPosition * (long long)NANOS_PER_SECOND / deltaTime;
-                ALOGD("computedSampleRate:%u  sampleRate:%u",
-                        (unsigned)computedSampleRate, mSampleRate);
-            }
-#endif
-        }
-        mPreviousTimestamp = timestamp;
-        mPreviousTimestampValid = true;
-    }
-
-    return status;
-}
-
-String8 AudioTrack::getParameters(const String8& keys)
-{
-    audio_io_handle_t output = getOutput();
-    if (output != AUDIO_IO_HANDLE_NONE) {
-        return AudioSystem::getParameters(output, keys);
-    } else {
-        return String8::empty();
-    }
-}
-
-bool AudioTrack::isOffloaded() const
-{
-    AutoMutex lock(mLock);
-    return isOffloaded_l();
-}
-
-bool AudioTrack::isDirect() const
-{
-    AutoMutex lock(mLock);
-    return isDirect_l();
-}
-
-bool AudioTrack::isOffloadedOrDirect() const
-{
-    AutoMutex lock(mLock);
-    return isOffloadedOrDirect_l();
-}
-
-
-status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
-{
-
-    const size_t SIZE = 256;
-    char buffer[SIZE];
-    String8 result;
-
-    result.append(" AudioTrack::dump\n");
-    snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n", mStreamType,
-            mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
-    result.append(buffer);
-    snprintf(buffer, 255, "  format(%d), channel count(%d), frame count(%zu)\n", mFormat,
-            mChannelCount, mFrameCount);
-    result.append(buffer);
-    snprintf(buffer, 255, "  sample rate(%u), speed(%f), status(%d)\n",
-            mSampleRate, mPlaybackRate.mSpeed, mStatus);
-    result.append(buffer);
-    snprintf(buffer, 255, "  state(%d), latency (%d)\n", mState, mLatency);
-    result.append(buffer);
-    ::write(fd, result.string(), result.size());
-    return NO_ERROR;
-}
-
-uint32_t AudioTrack::getUnderrunCount() const
-{
-    AutoMutex lock(mLock);
-    return getUnderrunCount_l();
-}
-
-uint32_t AudioTrack::getUnderrunCount_l() const
-{
-    return mProxy->getUnderrunCount() + mUnderrunCountOffset;
-}
-
-uint32_t AudioTrack::getUnderrunFrames() const
-{
-    AutoMutex lock(mLock);
-    return mProxy->getUnderrunFrames();
-}
-
-status_t AudioTrack::addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback)
-{
-    if (callback == 0) {
-        ALOGW("%s adding NULL callback!", __FUNCTION__);
-        return BAD_VALUE;
-    }
-    AutoMutex lock(mLock);
-    if (mDeviceCallback == callback) {
-        ALOGW("%s adding same callback!", __FUNCTION__);
-        return INVALID_OPERATION;
-    }
-    status_t status = NO_ERROR;
-    if (mOutput != AUDIO_IO_HANDLE_NONE) {
-        if (mDeviceCallback != 0) {
-            ALOGW("%s callback already present!", __FUNCTION__);
-            AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
-        }
-        status = AudioSystem::addAudioDeviceCallback(callback, mOutput);
-    }
-    mDeviceCallback = callback;
-    return status;
-}
-
-status_t AudioTrack::removeAudioDeviceCallback(
-        const sp<AudioSystem::AudioDeviceCallback>& callback)
-{
-    if (callback == 0) {
-        ALOGW("%s removing NULL callback!", __FUNCTION__);
-        return BAD_VALUE;
-    }
-    AutoMutex lock(mLock);
-    if (mDeviceCallback != callback) {
-        ALOGW("%s removing different callback!", __FUNCTION__);
-        return INVALID_OPERATION;
-    }
-    if (mOutput != AUDIO_IO_HANDLE_NONE) {
-        AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
-    }
-    mDeviceCallback = 0;
-    return NO_ERROR;
-}
-
-status_t AudioTrack::pendingDuration(int32_t *msec, ExtendedTimestamp::Location location)
-{
-    if (msec == nullptr ||
-            (location != ExtendedTimestamp::LOCATION_SERVER
-                    && location != ExtendedTimestamp::LOCATION_KERNEL)) {
-        return BAD_VALUE;
-    }
-    AutoMutex lock(mLock);
-    // inclusive of offloaded and direct tracks.
-    //
-    // It is possible, but not enabled, to allow duration computation for non-pcm
-    // audio_has_proportional_frames() formats because currently they have
-    // the drain rate equivalent to the pcm sample rate * framesize.
-    if (!isPurePcmData_l()) {
-        return INVALID_OPERATION;
-    }
-    ExtendedTimestamp ets;
-    if (getTimestamp_l(&ets) == OK
-            && ets.mTimeNs[location] > 0) {
-        int64_t diff = ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT]
-                - ets.mPosition[location];
-        if (diff < 0) {
-            *msec = 0;
-        } else {
-            // ms is the playback time by frames
-            int64_t ms = (int64_t)((double)diff * 1000 /
-                    ((double)mSampleRate * mPlaybackRate.mSpeed));
-            // clockdiff is the timestamp age (negative)
-            int64_t clockdiff = (mState != STATE_ACTIVE) ? 0 :
-                    ets.mTimeNs[location]
-                    + ets.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_MONOTONIC]
-                    - systemTime(SYSTEM_TIME_MONOTONIC);
-
-            //ALOGV("ms: %lld  clockdiff: %lld", (long long)ms, (long long)clockdiff);
-            static const int NANOS_PER_MILLIS = 1000000;
-            *msec = (int32_t)(ms + clockdiff / NANOS_PER_MILLIS);
-        }
-        return NO_ERROR;
-    }
-    if (location != ExtendedTimestamp::LOCATION_SERVER) {
-        return INVALID_OPERATION; // LOCATION_KERNEL is not available
-    }
-    // use server position directly (offloaded and direct arrive here)
-    updateAndGetPosition_l();
-    int32_t diff = (Modulo<uint32_t>(mFramesWritten) - mPosition).signedValue();
-    *msec = (diff <= 0) ? 0
-            : (int32_t)((double)diff * 1000 / ((double)mSampleRate * mPlaybackRate.mSpeed));
-    return NO_ERROR;
-}
-
-bool AudioTrack::hasStarted()
-{
-    AutoMutex lock(mLock);
-    switch (mState) {
-    case STATE_STOPPED:
-        if (isOffloadedOrDirect_l()) {
-            // check if we have started in the past to return true.
-            return mStartUs > 0;
-        }
-        // A normal audio track may still be draining, so
-        // check if stream has ended.  This covers fasttrack position
-        // instability and start/stop without any data written.
-        if (mProxy->getStreamEndDone()) {
-            return true;
-        }
-        // fall through
-    case STATE_ACTIVE:
-    case STATE_STOPPING:
-        break;
-    case STATE_PAUSED:
-    case STATE_PAUSED_STOPPING:
-    case STATE_FLUSHED:
-        return false;  // we're not active
-    default:
-        LOG_ALWAYS_FATAL("Invalid mState in hasStarted(): %d", mState);
-        break;
-    }
-
-    // wait indicates whether we need to wait for a timestamp.
-    // This is conservatively figured - if we encounter an unexpected error
-    // then we will not wait.
-    bool wait = false;
-    if (isOffloadedOrDirect_l()) {
-        AudioTimestamp ts;
-        status_t status = getTimestamp_l(ts);
-        if (status == WOULD_BLOCK) {
-            wait = true;
-        } else if (status == OK) {
-            wait = (ts.mPosition == 0 || ts.mPosition == mStartTs.mPosition);
-        }
-        ALOGV("hasStarted wait:%d  ts:%u  start position:%lld",
-                (int)wait,
-                ts.mPosition,
-                (long long)mStartTs.mPosition);
-    } else {
-        int location = ExtendedTimestamp::LOCATION_SERVER; // for ALOG
-        ExtendedTimestamp ets;
-        status_t status = getTimestamp_l(&ets);
-        if (status == WOULD_BLOCK) {  // no SERVER or KERNEL frame info in ets
-            wait = true;
-        } else if (status == OK) {
-            for (location = ExtendedTimestamp::LOCATION_KERNEL;
-                    location >= ExtendedTimestamp::LOCATION_SERVER; --location) {
-                if (ets.mTimeNs[location] < 0 || mStartEts.mTimeNs[location] < 0) {
-                    continue;
-                }
-                wait = ets.mPosition[location] == 0
-                        || ets.mPosition[location] == mStartEts.mPosition[location];
-                break;
-            }
-        }
-        ALOGV("hasStarted wait:%d  ets:%lld  start position:%lld",
-                (int)wait,
-                (long long)ets.mPosition[location],
-                (long long)mStartEts.mPosition[location]);
-    }
-    return !wait;
-}
-
-// =========================================================================
-
-void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
-{
-    sp<AudioTrack> audioTrack = mAudioTrack.promote();
-    if (audioTrack != 0) {
-        AutoMutex lock(audioTrack->mLock);
-        audioTrack->mProxy->binderDied();
-    }
-}
-
-// =========================================================================
-
-AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
-    : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
-      mIgnoreNextPausedInt(false)
-{
-}
-
-AudioTrack::AudioTrackThread::~AudioTrackThread()
-{
-}
-
-bool AudioTrack::AudioTrackThread::threadLoop()
-{
-    {
-        AutoMutex _l(mMyLock);
-        if (mPaused) {
-            mMyCond.wait(mMyLock);
-            // caller will check for exitPending()
-            return true;
-        }
-        if (mIgnoreNextPausedInt) {
-            mIgnoreNextPausedInt = false;
-            mPausedInt = false;
-        }
-        if (mPausedInt) {
-            if (mPausedNs > 0) {
-                (void) mMyCond.waitRelative(mMyLock, mPausedNs);
-            } else {
-                mMyCond.wait(mMyLock);
-            }
-            mPausedInt = false;
-            return true;
-        }
-    }
-    if (exitPending()) {
-        return false;
-    }
-    nsecs_t ns = mReceiver.processAudioBuffer();
-    switch (ns) {
-    case 0:
-        return true;
-    case NS_INACTIVE:
-        pauseInternal();
-        return true;
-    case NS_NEVER:
-        return false;
-    case NS_WHENEVER:
-        // Event driven: call wake() when callback notifications conditions change.
-        ns = INT64_MAX;
-        // fall through
-    default:
-        LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
-        pauseInternal(ns);
-        return true;
-    }
-}
-
-void AudioTrack::AudioTrackThread::requestExit()
-{
-    // must be in this order to avoid a race condition
-    Thread::requestExit();
-    resume();
-}
-
-void AudioTrack::AudioTrackThread::pause()
-{
-    AutoMutex _l(mMyLock);
-    mPaused = true;
-}
-
-void AudioTrack::AudioTrackThread::resume()
-{
-    AutoMutex _l(mMyLock);
-    mIgnoreNextPausedInt = true;
-    if (mPaused || mPausedInt) {
-        mPaused = false;
-        mPausedInt = false;
-        mMyCond.signal();
-    }
-}
-
-void AudioTrack::AudioTrackThread::wake()
-{
-    AutoMutex _l(mMyLock);
-    if (!mPaused) {
-        // wake() might be called while servicing a callback - ignore the next
-        // pause time and call processAudioBuffer.
-        mIgnoreNextPausedInt = true;
-        if (mPausedInt && mPausedNs > 0) {
-            // audio track is active and internally paused with timeout.
-            mPausedInt = false;
-            mMyCond.signal();
-        }
-    }
-}
-
-void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
-{
-    AutoMutex _l(mMyLock);
-    mPausedInt = true;
-    mPausedNs = ns;
-}
-
-} // namespace android
diff --git a/media/libmedia/AudioTrackShared.cpp b/media/libmedia/AudioTrackShared.cpp
deleted file mode 100644
index 846f8b8..0000000
--- a/media/libmedia/AudioTrackShared.cpp
+++ /dev/null
@@ -1,1108 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "AudioTrackShared"
-//#define LOG_NDEBUG 0
-
-#include <private/media/AudioTrackShared.h>
-#include <utils/Log.h>
-
-#include <linux/futex.h>
-#include <sys/syscall.h>
-
-namespace android {
-
-// used to clamp a value to size_t.  TODO: move to another file.
-template <typename T>
-size_t clampToSize(T x) {
-    return sizeof(T) > sizeof(size_t) && x > (T) SIZE_MAX ? SIZE_MAX : x < 0 ? 0 : (size_t) x;
-}
-
-// incrementSequence is used to determine the next sequence value
-// for the loop and position sequence counters.  It should return
-// a value between "other" + 1 and "other" + INT32_MAX, the choice of
-// which needs to be the "least recently used" sequence value for "self".
-// In general, this means (new_self) returned is max(self, other) + 1.
-
-static uint32_t incrementSequence(uint32_t self, uint32_t other) {
-    int32_t diff = (int32_t) self - (int32_t) other;
-    if (diff >= 0 && diff < INT32_MAX) {
-        return self + 1; // we're already ahead of other.
-    }
-    return other + 1; // we're behind, so move just ahead of other.
-}
-
-audio_track_cblk_t::audio_track_cblk_t()
-    : mServer(0), mFutex(0), mMinimum(0)
-    , mVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY), mSampleRate(0), mSendLevel(0)
-    , mBufferSizeInFrames(0)
-    , mFlags(0)
-{
-    memset(&u, 0, sizeof(u));
-}
-
-// ---------------------------------------------------------------------------
-
-Proxy::Proxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize,
-        bool isOut, bool clientInServer)
-    : mCblk(cblk), mBuffers(buffers), mFrameCount(frameCount), mFrameSize(frameSize),
-      mFrameCountP2(roundup(frameCount)), mIsOut(isOut), mClientInServer(clientInServer),
-      mIsShutdown(false), mUnreleased(0)
-{
-}
-
-// ---------------------------------------------------------------------------
-
-ClientProxy::ClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
-        size_t frameSize, bool isOut, bool clientInServer)
-    : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer)
-    , mEpoch(0)
-    , mTimestampObserver(&cblk->mExtendedTimestampQueue)
-{
-    setBufferSizeInFrames(frameCount);
-}
-
-const struct timespec ClientProxy::kForever = {INT_MAX /*tv_sec*/, 0 /*tv_nsec*/};
-const struct timespec ClientProxy::kNonBlocking = {0 /*tv_sec*/, 0 /*tv_nsec*/};
-
-#define MEASURE_NS 10000000 // attempt to provide accurate timeouts if requested >= MEASURE_NS
-
-// To facilitate quicker recovery from server failure, this value limits the timeout per each futex
-// wait.  However it does not protect infinite timeouts.  If defined to be zero, there is no limit.
-// FIXME May not be compatible with audio tunneling requirements where timeout should be in the
-// order of minutes.
-#define MAX_SEC    5
-
-uint32_t ClientProxy::setBufferSizeInFrames(uint32_t size)
-{
-    // The minimum should be  greater than zero and less than the size
-    // at which underruns will occur.
-    const uint32_t minimum = 16; // based on AudioMixer::BLOCKSIZE
-    const uint32_t maximum = frameCount();
-    uint32_t clippedSize = size;
-    if (maximum < minimum) {
-        clippedSize = maximum;
-    } else if (clippedSize < minimum) {
-        clippedSize = minimum;
-    } else if (clippedSize > maximum) {
-        clippedSize = maximum;
-    }
-    // for server to read
-    android_atomic_release_store(clippedSize, (int32_t *)&mCblk->mBufferSizeInFrames);
-    // for client to read
-    mBufferSizeInFrames = clippedSize;
-    return clippedSize;
-}
-
-__attribute__((no_sanitize("integer")))
-status_t ClientProxy::obtainBuffer(Buffer* buffer, const struct timespec *requested,
-        struct timespec *elapsed)
-{
-    LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
-    struct timespec total;          // total elapsed time spent waiting
-    total.tv_sec = 0;
-    total.tv_nsec = 0;
-    bool measure = elapsed != NULL; // whether to measure total elapsed time spent waiting
-
-    status_t status;
-    enum {
-        TIMEOUT_ZERO,       // requested == NULL || *requested == 0
-        TIMEOUT_INFINITE,   // *requested == infinity
-        TIMEOUT_FINITE,     // 0 < *requested < infinity
-        TIMEOUT_CONTINUE,   // additional chances after TIMEOUT_FINITE
-    } timeout;
-    if (requested == NULL) {
-        timeout = TIMEOUT_ZERO;
-    } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
-        timeout = TIMEOUT_ZERO;
-    } else if (requested->tv_sec == INT_MAX) {
-        timeout = TIMEOUT_INFINITE;
-    } else {
-        timeout = TIMEOUT_FINITE;
-        if (requested->tv_sec > 0 || requested->tv_nsec >= MEASURE_NS) {
-            measure = true;
-        }
-    }
-    struct timespec before;
-    bool beforeIsValid = false;
-    audio_track_cblk_t* cblk = mCblk;
-    bool ignoreInitialPendingInterrupt = true;
-    // check for shared memory corruption
-    if (mIsShutdown) {
-        status = NO_INIT;
-        goto end;
-    }
-    for (;;) {
-        int32_t flags = android_atomic_and(~CBLK_INTERRUPT, &cblk->mFlags);
-        // check for track invalidation by server, or server death detection
-        if (flags & CBLK_INVALID) {
-            ALOGV("Track invalidated");
-            status = DEAD_OBJECT;
-            goto end;
-        }
-        if (flags & CBLK_DISABLED) {
-            ALOGV("Track disabled");
-            status = NOT_ENOUGH_DATA;
-            goto end;
-        }
-        // check for obtainBuffer interrupted by client
-        if (!ignoreInitialPendingInterrupt && (flags & CBLK_INTERRUPT)) {
-            ALOGV("obtainBuffer() interrupted by client");
-            status = -EINTR;
-            goto end;
-        }
-        ignoreInitialPendingInterrupt = false;
-        // compute number of frames available to write (AudioTrack) or read (AudioRecord)
-        int32_t front;
-        int32_t rear;
-        if (mIsOut) {
-            // The barrier following the read of mFront is probably redundant.
-            // We're about to perform a conditional branch based on 'filled',
-            // which will force the processor to observe the read of mFront
-            // prior to allowing data writes starting at mRaw.
-            // However, the processor may support speculative execution,
-            // and be unable to undo speculative writes into shared memory.
-            // The barrier will prevent such speculative execution.
-            front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
-            rear = cblk->u.mStreaming.mRear;
-        } else {
-            // On the other hand, this barrier is required.
-            rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
-            front = cblk->u.mStreaming.mFront;
-        }
-        // write to rear, read from front
-        ssize_t filled = rear - front;
-        // pipe should not be overfull
-        if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
-            if (mIsOut) {
-                ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); "
-                        "shutting down", filled, mFrameCount);
-                mIsShutdown = true;
-                status = NO_INIT;
-                goto end;
-            }
-            // for input, sync up on overrun
-            filled = 0;
-            cblk->u.mStreaming.mFront = rear;
-            (void) android_atomic_or(CBLK_OVERRUN, &cblk->mFlags);
-        }
-        // Don't allow filling pipe beyond the user settable size.
-        // The calculation for avail can go negative if the buffer size
-        // is suddenly dropped below the amount already in the buffer.
-        // So use a signed calculation to prevent a numeric overflow abort.
-        ssize_t adjustableSize = (ssize_t) getBufferSizeInFrames();
-        ssize_t avail =  (mIsOut) ? adjustableSize - filled : filled;
-        if (avail < 0) {
-            avail = 0;
-        } else if (avail > 0) {
-            // 'avail' may be non-contiguous, so return only the first contiguous chunk
-            size_t part1;
-            if (mIsOut) {
-                rear &= mFrameCountP2 - 1;
-                part1 = mFrameCountP2 - rear;
-            } else {
-                front &= mFrameCountP2 - 1;
-                part1 = mFrameCountP2 - front;
-            }
-            if (part1 > (size_t)avail) {
-                part1 = avail;
-            }
-            if (part1 > buffer->mFrameCount) {
-                part1 = buffer->mFrameCount;
-            }
-            buffer->mFrameCount = part1;
-            buffer->mRaw = part1 > 0 ?
-                    &((char *) mBuffers)[(mIsOut ? rear : front) * mFrameSize] : NULL;
-            buffer->mNonContig = avail - part1;
-            mUnreleased = part1;
-            status = NO_ERROR;
-            break;
-        }
-        struct timespec remaining;
-        const struct timespec *ts;
-        switch (timeout) {
-        case TIMEOUT_ZERO:
-            status = WOULD_BLOCK;
-            goto end;
-        case TIMEOUT_INFINITE:
-            ts = NULL;
-            break;
-        case TIMEOUT_FINITE:
-            timeout = TIMEOUT_CONTINUE;
-            if (MAX_SEC == 0) {
-                ts = requested;
-                break;
-            }
-            // fall through
-        case TIMEOUT_CONTINUE:
-            // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
-            if (!measure || requested->tv_sec < total.tv_sec ||
-                    (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
-                status = TIMED_OUT;
-                goto end;
-            }
-            remaining.tv_sec = requested->tv_sec - total.tv_sec;
-            if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
-                remaining.tv_nsec += 1000000000;
-                remaining.tv_sec++;
-            }
-            if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
-                remaining.tv_sec = MAX_SEC;
-                remaining.tv_nsec = 0;
-            }
-            ts = &remaining;
-            break;
-        default:
-            LOG_ALWAYS_FATAL("obtainBuffer() timeout=%d", timeout);
-            ts = NULL;
-            break;
-        }
-        int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
-        if (!(old & CBLK_FUTEX_WAKE)) {
-            if (measure && !beforeIsValid) {
-                clock_gettime(CLOCK_MONOTONIC, &before);
-                beforeIsValid = true;
-            }
-            errno = 0;
-            (void) syscall(__NR_futex, &cblk->mFutex,
-                    mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
-            status_t error = errno; // clock_gettime can affect errno
-            // update total elapsed time spent waiting
-            if (measure) {
-                struct timespec after;
-                clock_gettime(CLOCK_MONOTONIC, &after);
-                total.tv_sec += after.tv_sec - before.tv_sec;
-                long deltaNs = after.tv_nsec - before.tv_nsec;
-                if (deltaNs < 0) {
-                    deltaNs += 1000000000;
-                    total.tv_sec--;
-                }
-                if ((total.tv_nsec += deltaNs) >= 1000000000) {
-                    total.tv_nsec -= 1000000000;
-                    total.tv_sec++;
-                }
-                before = after;
-                beforeIsValid = true;
-            }
-            switch (error) {
-            case 0:            // normal wakeup by server, or by binderDied()
-            case EWOULDBLOCK:  // benign race condition with server
-            case EINTR:        // wait was interrupted by signal or other spurious wakeup
-            case ETIMEDOUT:    // time-out expired
-                // FIXME these error/non-0 status are being dropped
-                break;
-            default:
-                status = error;
-                ALOGE("%s unexpected error %s", __func__, strerror(status));
-                goto end;
-            }
-        }
-    }
-
-end:
-    if (status != NO_ERROR) {
-        buffer->mFrameCount = 0;
-        buffer->mRaw = NULL;
-        buffer->mNonContig = 0;
-        mUnreleased = 0;
-    }
-    if (elapsed != NULL) {
-        *elapsed = total;
-    }
-    if (requested == NULL) {
-        requested = &kNonBlocking;
-    }
-    if (measure) {
-        ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
-              requested->tv_sec, requested->tv_nsec / 1000000,
-              total.tv_sec, total.tv_nsec / 1000000);
-    }
-    return status;
-}
-
-__attribute__((no_sanitize("integer")))
-void ClientProxy::releaseBuffer(Buffer* buffer)
-{
-    LOG_ALWAYS_FATAL_IF(buffer == NULL);
-    size_t stepCount = buffer->mFrameCount;
-    if (stepCount == 0 || mIsShutdown) {
-        // prevent accidental re-use of buffer
-        buffer->mFrameCount = 0;
-        buffer->mRaw = NULL;
-        buffer->mNonContig = 0;
-        return;
-    }
-    LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
-    mUnreleased -= stepCount;
-    audio_track_cblk_t* cblk = mCblk;
-    // Both of these barriers are required
-    if (mIsOut) {
-        int32_t rear = cblk->u.mStreaming.mRear;
-        android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
-    } else {
-        int32_t front = cblk->u.mStreaming.mFront;
-        android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
-    }
-}
-
-void ClientProxy::binderDied()
-{
-    audio_track_cblk_t* cblk = mCblk;
-    if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
-        android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
-        // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
-        (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
-                1);
-    }
-}
-
-void ClientProxy::interrupt()
-{
-    audio_track_cblk_t* cblk = mCblk;
-    if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
-        android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
-        (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
-                1);
-    }
-}
-
-__attribute__((no_sanitize("integer")))
-size_t ClientProxy::getMisalignment()
-{
-    audio_track_cblk_t* cblk = mCblk;
-    return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
-            (mFrameCountP2 - 1);
-}
-
-// ---------------------------------------------------------------------------
-
-void AudioTrackClientProxy::flush()
-{
-    // This works for mFrameCountP2 <= 2^30
-    size_t increment = mFrameCountP2 << 1;
-    size_t mask = increment - 1;
-    audio_track_cblk_t* cblk = mCblk;
-    // mFlush is 32 bits concatenated as [ flush_counter ] [ newfront_offset ]
-    // Should newFlush = cblk->u.mStreaming.mRear?  Only problem is
-    // if you want to flush twice to the same rear location after a 32 bit wrap.
-    int32_t newFlush = (cblk->u.mStreaming.mRear & mask) |
-                        ((cblk->u.mStreaming.mFlush & ~mask) + increment);
-    android_atomic_release_store(newFlush, &cblk->u.mStreaming.mFlush);
-}
-
-bool AudioTrackClientProxy::clearStreamEndDone() {
-    return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
-}
-
-bool AudioTrackClientProxy::getStreamEndDone() const {
-    return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
-}
-
-status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
-{
-    struct timespec total;          // total elapsed time spent waiting
-    total.tv_sec = 0;
-    total.tv_nsec = 0;
-    audio_track_cblk_t* cblk = mCblk;
-    status_t status;
-    enum {
-        TIMEOUT_ZERO,       // requested == NULL || *requested == 0
-        TIMEOUT_INFINITE,   // *requested == infinity
-        TIMEOUT_FINITE,     // 0 < *requested < infinity
-        TIMEOUT_CONTINUE,   // additional chances after TIMEOUT_FINITE
-    } timeout;
-    if (requested == NULL) {
-        timeout = TIMEOUT_ZERO;
-    } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
-        timeout = TIMEOUT_ZERO;
-    } else if (requested->tv_sec == INT_MAX) {
-        timeout = TIMEOUT_INFINITE;
-    } else {
-        timeout = TIMEOUT_FINITE;
-    }
-    for (;;) {
-        int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
-        // check for track invalidation by server, or server death detection
-        if (flags & CBLK_INVALID) {
-            ALOGV("Track invalidated");
-            status = DEAD_OBJECT;
-            goto end;
-        }
-        // a track is not supposed to underrun at this stage but consider it done
-        if (flags & (CBLK_STREAM_END_DONE | CBLK_DISABLED)) {
-            ALOGV("stream end received");
-            status = NO_ERROR;
-            goto end;
-        }
-        // check for obtainBuffer interrupted by client
-        if (flags & CBLK_INTERRUPT) {
-            ALOGV("waitStreamEndDone() interrupted by client");
-            status = -EINTR;
-            goto end;
-        }
-        struct timespec remaining;
-        const struct timespec *ts;
-        switch (timeout) {
-        case TIMEOUT_ZERO:
-            status = WOULD_BLOCK;
-            goto end;
-        case TIMEOUT_INFINITE:
-            ts = NULL;
-            break;
-        case TIMEOUT_FINITE:
-            timeout = TIMEOUT_CONTINUE;
-            if (MAX_SEC == 0) {
-                ts = requested;
-                break;
-            }
-            // fall through
-        case TIMEOUT_CONTINUE:
-            // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
-            if (requested->tv_sec < total.tv_sec ||
-                    (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
-                status = TIMED_OUT;
-                goto end;
-            }
-            remaining.tv_sec = requested->tv_sec - total.tv_sec;
-            if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
-                remaining.tv_nsec += 1000000000;
-                remaining.tv_sec++;
-            }
-            if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
-                remaining.tv_sec = MAX_SEC;
-                remaining.tv_nsec = 0;
-            }
-            ts = &remaining;
-            break;
-        default:
-            LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
-            ts = NULL;
-            break;
-        }
-        int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
-        if (!(old & CBLK_FUTEX_WAKE)) {
-            errno = 0;
-            (void) syscall(__NR_futex, &cblk->mFutex,
-                    mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
-            switch (errno) {
-            case 0:            // normal wakeup by server, or by binderDied()
-            case EWOULDBLOCK:  // benign race condition with server
-            case EINTR:        // wait was interrupted by signal or other spurious wakeup
-            case ETIMEDOUT:    // time-out expired
-                break;
-            default:
-                status = errno;
-                ALOGE("%s unexpected error %s", __func__, strerror(status));
-                goto end;
-            }
-        }
-    }
-
-end:
-    if (requested == NULL) {
-        requested = &kNonBlocking;
-    }
-    return status;
-}
-
-// ---------------------------------------------------------------------------
-
-StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
-        size_t frameCount, size_t frameSize)
-    : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
-      mMutator(&cblk->u.mStatic.mSingleStateQueue),
-      mPosLoopObserver(&cblk->u.mStatic.mPosLoopQueue)
-{
-    memset(&mState, 0, sizeof(mState));
-    memset(&mPosLoop, 0, sizeof(mPosLoop));
-}
-
-void StaticAudioTrackClientProxy::flush()
-{
-    LOG_ALWAYS_FATAL("static flush");
-}
-
-void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
-{
-    // This can only happen on a 64-bit client
-    if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
-        // FIXME Should return an error status
-        return;
-    }
-    mState.mLoopStart = (uint32_t) loopStart;
-    mState.mLoopEnd = (uint32_t) loopEnd;
-    mState.mLoopCount = loopCount;
-    mState.mLoopSequence = incrementSequence(mState.mLoopSequence, mState.mPositionSequence);
-    // set patch-up variables until the mState is acknowledged by the ServerProxy.
-    // observed buffer position and loop count will freeze until then to give the
-    // illusion of a synchronous change.
-    getBufferPositionAndLoopCount(NULL, NULL);
-    // preserve behavior to restart at mState.mLoopStart if position exceeds mState.mLoopEnd.
-    if (mState.mLoopCount != 0 && mPosLoop.mBufferPosition >= mState.mLoopEnd) {
-        mPosLoop.mBufferPosition = mState.mLoopStart;
-    }
-    mPosLoop.mLoopCount = mState.mLoopCount;
-    (void) mMutator.push(mState);
-}
-
-void StaticAudioTrackClientProxy::setBufferPosition(size_t position)
-{
-    // This can only happen on a 64-bit client
-    if (position > UINT32_MAX) {
-        // FIXME Should return an error status
-        return;
-    }
-    mState.mPosition = (uint32_t) position;
-    mState.mPositionSequence = incrementSequence(mState.mPositionSequence, mState.mLoopSequence);
-    // set patch-up variables until the mState is acknowledged by the ServerProxy.
-    // observed buffer position and loop count will freeze until then to give the
-    // illusion of a synchronous change.
-    if (mState.mLoopCount > 0) {  // only check if loop count is changing
-        getBufferPositionAndLoopCount(NULL, NULL); // get last position
-    }
-    mPosLoop.mBufferPosition = position;
-    if (position >= mState.mLoopEnd) {
-        // no ongoing loop is possible if position is greater than loopEnd.
-        mPosLoop.mLoopCount = 0;
-    }
-    (void) mMutator.push(mState);
-}
-
-void StaticAudioTrackClientProxy::setBufferPositionAndLoop(size_t position, size_t loopStart,
-        size_t loopEnd, int loopCount)
-{
-    setLoop(loopStart, loopEnd, loopCount);
-    setBufferPosition(position);
-}
-
-size_t StaticAudioTrackClientProxy::getBufferPosition()
-{
-    getBufferPositionAndLoopCount(NULL, NULL);
-    return mPosLoop.mBufferPosition;
-}
-
-void StaticAudioTrackClientProxy::getBufferPositionAndLoopCount(
-        size_t *position, int *loopCount)
-{
-    if (mMutator.ack() == StaticAudioTrackSingleStateQueue::SSQ_DONE) {
-         if (mPosLoopObserver.poll(mPosLoop)) {
-             ; // a valid mPosLoop should be available if ackDone is true.
-         }
-    }
-    if (position != NULL) {
-        *position = mPosLoop.mBufferPosition;
-    }
-    if (loopCount != NULL) {
-        *loopCount = mPosLoop.mLoopCount;
-    }
-}
-
-// ---------------------------------------------------------------------------
-
-ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
-        size_t frameSize, bool isOut, bool clientInServer)
-    : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
-      mAvailToClient(0), mFlush(0), mReleased(0), mFlushed(0)
-    , mTimestampMutator(&cblk->mExtendedTimestampQueue)
-{
-    cblk->mBufferSizeInFrames = frameCount;
-}
-
-__attribute__((no_sanitize("integer")))
-void ServerProxy::flushBufferIfNeeded()
-{
-    audio_track_cblk_t* cblk = mCblk;
-    // The acquire_load is not really required. But since the write is a release_store in the
-    // client, using acquire_load here makes it easier for people to maintain the code,
-    // and the logic for communicating ipc variables seems somewhat standard,
-    // and there really isn't much penalty for 4 or 8 byte atomics.
-    int32_t flush = android_atomic_acquire_load(&cblk->u.mStreaming.mFlush);
-    if (flush != mFlush) {
-        ALOGV("ServerProxy::flushBufferIfNeeded() mStreaming.mFlush = 0x%x, mFlush = 0x%0x",
-                flush, mFlush);
-        int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
-        int32_t front = cblk->u.mStreaming.mFront;
-
-        // effectively obtain then release whatever is in the buffer
-        const size_t overflowBit = mFrameCountP2 << 1;
-        const size_t mask = overflowBit - 1;
-        int32_t newFront = (front & ~mask) | (flush & mask);
-        ssize_t filled = rear - newFront;
-        if (filled >= (ssize_t)overflowBit) {
-            // front and rear offsets span the overflow bit of the p2 mask
-            // so rebasing newFront on the front offset is off by the overflow bit.
-            // adjust newFront to match rear offset.
-            ALOGV("flush wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
-            newFront += overflowBit;
-            filled -= overflowBit;
-        }
-        // Rather than shutting down on a corrupt flush, just treat it as a full flush
-        if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
-            ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, "
-                    "filled %zd=%#x",
-                    mFlush, flush, front, rear,
-                    (unsigned)mask, newFront, filled, (unsigned)filled);
-            newFront = rear;
-        }
-        mFlush = flush;
-        android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
-        // There is no danger from a false positive, so err on the side of caution
-        if (true /*front != newFront*/) {
-            int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
-            if (!(old & CBLK_FUTEX_WAKE)) {
-                (void) syscall(__NR_futex, &cblk->mFutex,
-                        mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
-            }
-        }
-        mFlushed += (newFront - front) & mask;
-    }
-}
-
-__attribute__((no_sanitize("integer")))
-status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
-{
-    LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
-    if (mIsShutdown) {
-        goto no_init;
-    }
-    {
-    audio_track_cblk_t* cblk = mCblk;
-    // compute number of frames available to write (AudioTrack) or read (AudioRecord),
-    // or use previous cached value from framesReady(), with added barrier if it omits.
-    int32_t front;
-    int32_t rear;
-    // See notes on barriers at ClientProxy::obtainBuffer()
-    if (mIsOut) {
-        flushBufferIfNeeded(); // might modify mFront
-        rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
-        front = cblk->u.mStreaming.mFront;
-    } else {
-        front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
-        rear = cblk->u.mStreaming.mRear;
-    }
-    ssize_t filled = rear - front;
-    // pipe should not already be overfull
-    if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
-        ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
-        mIsShutdown = true;
-    }
-    if (mIsShutdown) {
-        goto no_init;
-    }
-    // don't allow filling pipe beyond the nominal size
-    size_t availToServer;
-    if (mIsOut) {
-        availToServer = filled;
-        mAvailToClient = mFrameCount - filled;
-    } else {
-        availToServer = mFrameCount - filled;
-        mAvailToClient = filled;
-    }
-    // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
-    size_t part1;
-    if (mIsOut) {
-        front &= mFrameCountP2 - 1;
-        part1 = mFrameCountP2 - front;
-    } else {
-        rear &= mFrameCountP2 - 1;
-        part1 = mFrameCountP2 - rear;
-    }
-    if (part1 > availToServer) {
-        part1 = availToServer;
-    }
-    size_t ask = buffer->mFrameCount;
-    if (part1 > ask) {
-        part1 = ask;
-    }
-    // is assignment redundant in some cases?
-    buffer->mFrameCount = part1;
-    buffer->mRaw = part1 > 0 ?
-            &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
-    buffer->mNonContig = availToServer - part1;
-    // After flush(), allow releaseBuffer() on a previously obtained buffer;
-    // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
-    if (!ackFlush) {
-        mUnreleased = part1;
-    }
-    return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
-    }
-no_init:
-    buffer->mFrameCount = 0;
-    buffer->mRaw = NULL;
-    buffer->mNonContig = 0;
-    mUnreleased = 0;
-    return NO_INIT;
-}
-
-__attribute__((no_sanitize("integer")))
-void ServerProxy::releaseBuffer(Buffer* buffer)
-{
-    LOG_ALWAYS_FATAL_IF(buffer == NULL);
-    size_t stepCount = buffer->mFrameCount;
-    if (stepCount == 0 || mIsShutdown) {
-        // prevent accidental re-use of buffer
-        buffer->mFrameCount = 0;
-        buffer->mRaw = NULL;
-        buffer->mNonContig = 0;
-        return;
-    }
-    LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
-    mUnreleased -= stepCount;
-    audio_track_cblk_t* cblk = mCblk;
-    if (mIsOut) {
-        int32_t front = cblk->u.mStreaming.mFront;
-        android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
-    } else {
-        int32_t rear = cblk->u.mStreaming.mRear;
-        android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
-    }
-
-    cblk->mServer += stepCount;
-    mReleased += stepCount;
-
-    size_t half = mFrameCount / 2;
-    if (half == 0) {
-        half = 1;
-    }
-    size_t minimum = (size_t) cblk->mMinimum;
-    if (minimum == 0) {
-        minimum = mIsOut ? half : 1;
-    } else if (minimum > half) {
-        minimum = half;
-    }
-    // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
-    if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
-        ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
-        int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
-        if (!(old & CBLK_FUTEX_WAKE)) {
-            (void) syscall(__NR_futex, &cblk->mFutex,
-                    mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
-        }
-    }
-
-    buffer->mFrameCount = 0;
-    buffer->mRaw = NULL;
-    buffer->mNonContig = 0;
-}
-
-// ---------------------------------------------------------------------------
-
-__attribute__((no_sanitize("integer")))
-size_t AudioTrackServerProxy::framesReady()
-{
-    LOG_ALWAYS_FATAL_IF(!mIsOut);
-
-    if (mIsShutdown) {
-        return 0;
-    }
-    audio_track_cblk_t* cblk = mCblk;
-
-    int32_t flush = cblk->u.mStreaming.mFlush;
-    if (flush != mFlush) {
-        // FIXME should return an accurate value, but over-estimate is better than under-estimate
-        return mFrameCount;
-    }
-    // the acquire might not be necessary since not doing a subsequent read
-    int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
-    ssize_t filled = rear - cblk->u.mStreaming.mFront;
-    // pipe should not already be overfull
-    if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
-        ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
-        mIsShutdown = true;
-        return 0;
-    }
-    //  cache this value for later use by obtainBuffer(), with added barrier
-    //  and racy if called by normal mixer thread
-    // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
-    return filled;
-}
-
-bool  AudioTrackServerProxy::setStreamEndDone() {
-    audio_track_cblk_t* cblk = mCblk;
-    bool old =
-            (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
-    if (!old) {
-        (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
-                1);
-    }
-    return old;
-}
-
-void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
-{
-    audio_track_cblk_t* cblk = mCblk;
-    if (frameCount > 0) {
-        cblk->u.mStreaming.mUnderrunFrames += frameCount;
-
-        if (!mUnderrunning) { // start of underrun?
-            mUnderrunCount++;
-            cblk->u.mStreaming.mUnderrunCount = mUnderrunCount;
-            mUnderrunning = true;
-            ALOGV("tallyUnderrunFrames(%3u) at uf = %u, bump mUnderrunCount = %u",
-                frameCount, cblk->u.mStreaming.mUnderrunFrames, mUnderrunCount);
-        }
-
-        // FIXME also wake futex so that underrun is noticed more quickly
-        (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
-    } else {
-        ALOGV_IF(mUnderrunning,
-            "tallyUnderrunFrames(%3u) at uf = %u, underrun finished",
-            frameCount, cblk->u.mStreaming.mUnderrunFrames);
-        mUnderrunning = false; // so we can detect the next edge
-    }
-}
-
-AudioPlaybackRate AudioTrackServerProxy::getPlaybackRate()
-{   // do not call from multiple threads without holding lock
-    mPlaybackRateObserver.poll(mPlaybackRate);
-    return mPlaybackRate;
-}
-
-// ---------------------------------------------------------------------------
-
-StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
-        size_t frameCount, size_t frameSize)
-    : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
-      mObserver(&cblk->u.mStatic.mSingleStateQueue),
-      mPosLoopMutator(&cblk->u.mStatic.mPosLoopQueue),
-      mFramesReadySafe(frameCount), mFramesReady(frameCount),
-      mFramesReadyIsCalledByMultipleThreads(false)
-{
-    memset(&mState, 0, sizeof(mState));
-}
-
-void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
-{
-    mFramesReadyIsCalledByMultipleThreads = true;
-}
-
-size_t StaticAudioTrackServerProxy::framesReady()
-{
-    // Can't call pollPosition() from multiple threads.
-    if (!mFramesReadyIsCalledByMultipleThreads) {
-        (void) pollPosition();
-    }
-    return mFramesReadySafe;
-}
-
-status_t StaticAudioTrackServerProxy::updateStateWithLoop(
-        StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
-{
-    if (localState->mLoopSequence != update.mLoopSequence) {
-        bool valid = false;
-        const size_t loopStart = update.mLoopStart;
-        const size_t loopEnd = update.mLoopEnd;
-        size_t position = localState->mPosition;
-        if (update.mLoopCount == 0) {
-            valid = true;
-        } else if (update.mLoopCount >= -1) {
-            if (loopStart < loopEnd && loopEnd <= mFrameCount &&
-                    loopEnd - loopStart >= MIN_LOOP) {
-                // If the current position is greater than the end of the loop
-                // we "wrap" to the loop start. This might cause an audible pop.
-                if (position >= loopEnd) {
-                    position = loopStart;
-                }
-                valid = true;
-            }
-        }
-        if (!valid || position > mFrameCount) {
-            return NO_INIT;
-        }
-        localState->mPosition = position;
-        localState->mLoopCount = update.mLoopCount;
-        localState->mLoopEnd = loopEnd;
-        localState->mLoopStart = loopStart;
-        localState->mLoopSequence = update.mLoopSequence;
-    }
-    return OK;
-}
-
-status_t StaticAudioTrackServerProxy::updateStateWithPosition(
-        StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
-{
-    if (localState->mPositionSequence != update.mPositionSequence) {
-        if (update.mPosition > mFrameCount) {
-            return NO_INIT;
-        } else if (localState->mLoopCount != 0 && update.mPosition >= localState->mLoopEnd) {
-            localState->mLoopCount = 0; // disable loop count if position is beyond loop end.
-        }
-        localState->mPosition = update.mPosition;
-        localState->mPositionSequence = update.mPositionSequence;
-    }
-    return OK;
-}
-
-ssize_t StaticAudioTrackServerProxy::pollPosition()
-{
-    StaticAudioTrackState state;
-    if (mObserver.poll(state)) {
-        StaticAudioTrackState trystate = mState;
-        bool result;
-        const int32_t diffSeq = (int32_t) state.mLoopSequence - (int32_t) state.mPositionSequence;
-
-        if (diffSeq < 0) {
-            result = updateStateWithLoop(&trystate, state) == OK &&
-                    updateStateWithPosition(&trystate, state) == OK;
-        } else {
-            result = updateStateWithPosition(&trystate, state) == OK &&
-                    updateStateWithLoop(&trystate, state) == OK;
-        }
-        if (!result) {
-            mObserver.done();
-            // caution: no update occurs so server state will be inconsistent with client state.
-            ALOGE("%s client pushed an invalid state, shutting down", __func__);
-            mIsShutdown = true;
-            return (ssize_t) NO_INIT;
-        }
-        mState = trystate;
-        if (mState.mLoopCount == -1) {
-            mFramesReady = INT64_MAX;
-        } else if (mState.mLoopCount == 0) {
-            mFramesReady = mFrameCount - mState.mPosition;
-        } else if (mState.mLoopCount > 0) {
-            // TODO: Later consider fixing overflow, but does not seem needed now
-            // as will not overflow if loopStart and loopEnd are Java "ints".
-            mFramesReady = int64_t(mState.mLoopCount) * (mState.mLoopEnd - mState.mLoopStart)
-                    + mFrameCount - mState.mPosition;
-        }
-        mFramesReadySafe = clampToSize(mFramesReady);
-        // This may overflow, but client is not supposed to rely on it
-        StaticAudioTrackPosLoop posLoop;
-
-        posLoop.mLoopCount = (int32_t) mState.mLoopCount;
-        posLoop.mBufferPosition = (uint32_t) mState.mPosition;
-        mPosLoopMutator.push(posLoop);
-        mObserver.done(); // safe to read mStatic variables.
-    }
-    return (ssize_t) mState.mPosition;
-}
-
-status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
-{
-    if (mIsShutdown) {
-        buffer->mFrameCount = 0;
-        buffer->mRaw = NULL;
-        buffer->mNonContig = 0;
-        mUnreleased = 0;
-        return NO_INIT;
-    }
-    ssize_t positionOrStatus = pollPosition();
-    if (positionOrStatus < 0) {
-        buffer->mFrameCount = 0;
-        buffer->mRaw = NULL;
-        buffer->mNonContig = 0;
-        mUnreleased = 0;
-        return (status_t) positionOrStatus;
-    }
-    size_t position = (size_t) positionOrStatus;
-    size_t end = mState.mLoopCount != 0 ? mState.mLoopEnd : mFrameCount;
-    size_t avail;
-    if (position < end) {
-        avail = end - position;
-        size_t wanted = buffer->mFrameCount;
-        if (avail < wanted) {
-            buffer->mFrameCount = avail;
-        } else {
-            avail = wanted;
-        }
-        buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
-    } else {
-        avail = 0;
-        buffer->mFrameCount = 0;
-        buffer->mRaw = NULL;
-    }
-    // As mFramesReady is the total remaining frames in the static audio track,
-    // it is always larger or equal to avail.
-    LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail);
-    buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
-    if (!ackFlush) {
-        mUnreleased = avail;
-    }
-    return NO_ERROR;
-}
-
-void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
-{
-    size_t stepCount = buffer->mFrameCount;
-    LOG_ALWAYS_FATAL_IF(!((int64_t) stepCount <= mFramesReady));
-    LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased));
-    if (stepCount == 0) {
-        // prevent accidental re-use of buffer
-        buffer->mRaw = NULL;
-        buffer->mNonContig = 0;
-        return;
-    }
-    mUnreleased -= stepCount;
-    audio_track_cblk_t* cblk = mCblk;
-    size_t position = mState.mPosition;
-    size_t newPosition = position + stepCount;
-    int32_t setFlags = 0;
-    if (!(position <= newPosition && newPosition <= mFrameCount)) {
-        ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position,
-                mFrameCount);
-        newPosition = mFrameCount;
-    } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
-        newPosition = mState.mLoopStart;
-        if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
-            setFlags = CBLK_LOOP_CYCLE;
-        } else {
-            setFlags = CBLK_LOOP_FINAL;
-        }
-    }
-    if (newPosition == mFrameCount) {
-        setFlags |= CBLK_BUFFER_END;
-    }
-    mState.mPosition = newPosition;
-    if (mFramesReady != INT64_MAX) {
-        mFramesReady -= stepCount;
-    }
-    mFramesReadySafe = clampToSize(mFramesReady);
-
-    cblk->mServer += stepCount;
-    mReleased += stepCount;
-
-    // This may overflow, but client is not supposed to rely on it
-    StaticAudioTrackPosLoop posLoop;
-    posLoop.mBufferPosition = mState.mPosition;
-    posLoop.mLoopCount = mState.mLoopCount;
-    mPosLoopMutator.push(posLoop);
-    if (setFlags != 0) {
-        (void) android_atomic_or(setFlags, &cblk->mFlags);
-        // this would be a good place to wake a futex
-    }
-
-    buffer->mFrameCount = 0;
-    buffer->mRaw = NULL;
-    buffer->mNonContig = 0;
-}
-
-void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
-{
-    // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
-    // we don't have a location to count underrun frames.  The underrun frame counter
-    // only exists in AudioTrackSharedStreaming.  Fortunately, underruns are not
-    // possible for static buffer tracks other than at end of buffer, so this is not a loss.
-
-    // FIXME also wake futex so that underrun is noticed more quickly
-    if (frameCount > 0) {
-        (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
-    }
-}
-
-// ---------------------------------------------------------------------------
-
-}   // namespace android
diff --git a/media/libmedia/IAudioFlinger.cpp b/media/libmedia/IAudioFlinger.cpp
deleted file mode 100644
index 65fdedb..0000000
--- a/media/libmedia/IAudioFlinger.cpp
+++ /dev/null
@@ -1,1459 +0,0 @@
-/*
-**
-** Copyright 2007, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-**     http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
-
-#define LOG_TAG "IAudioFlinger"
-//#define LOG_NDEBUG 0
-#include <utils/Log.h>
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <binder/Parcel.h>
-
-#include <media/IAudioFlinger.h>
-
-namespace android {
-
-enum {
-    CREATE_TRACK = IBinder::FIRST_CALL_TRANSACTION,
-    OPEN_RECORD,
-    SAMPLE_RATE,
-    RESERVED,   // obsolete, was CHANNEL_COUNT
-    FORMAT,
-    FRAME_COUNT,
-    LATENCY,
-    SET_MASTER_VOLUME,
-    SET_MASTER_MUTE,
-    MASTER_VOLUME,
-    MASTER_MUTE,
-    SET_STREAM_VOLUME,
-    SET_STREAM_MUTE,
-    STREAM_VOLUME,
-    STREAM_MUTE,
-    SET_MODE,
-    SET_MIC_MUTE,
-    GET_MIC_MUTE,
-    SET_PARAMETERS,
-    GET_PARAMETERS,
-    REGISTER_CLIENT,
-    GET_INPUTBUFFERSIZE,
-    OPEN_OUTPUT,
-    OPEN_DUPLICATE_OUTPUT,
-    CLOSE_OUTPUT,
-    SUSPEND_OUTPUT,
-    RESTORE_OUTPUT,
-    OPEN_INPUT,
-    CLOSE_INPUT,
-    INVALIDATE_STREAM,
-    SET_VOICE_VOLUME,
-    GET_RENDER_POSITION,
-    GET_INPUT_FRAMES_LOST,
-    NEW_AUDIO_SESSION_ID,
-    ACQUIRE_AUDIO_SESSION_ID,
-    RELEASE_AUDIO_SESSION_ID,
-    QUERY_NUM_EFFECTS,
-    QUERY_EFFECT,
-    GET_EFFECT_DESCRIPTOR,
-    CREATE_EFFECT,
-    MOVE_EFFECTS,
-    LOAD_HW_MODULE,
-    GET_PRIMARY_OUTPUT_SAMPLING_RATE,
-    GET_PRIMARY_OUTPUT_FRAME_COUNT,
-    SET_LOW_RAM_DEVICE,
-    LIST_AUDIO_PORTS,
-    GET_AUDIO_PORT,
-    CREATE_AUDIO_PATCH,
-    RELEASE_AUDIO_PATCH,
-    LIST_AUDIO_PATCHES,
-    SET_AUDIO_PORT_CONFIG,
-    GET_AUDIO_HW_SYNC,
-    SYSTEM_READY,
-    FRAME_COUNT_HAL,
-};
-
-#define MAX_ITEMS_PER_LIST 1024
-
-class BpAudioFlinger : public BpInterface<IAudioFlinger>
-{
-public:
-    explicit BpAudioFlinger(const sp<IBinder>& impl)
-        : BpInterface<IAudioFlinger>(impl)
-    {
-    }
-
-    virtual sp<IAudioTrack> createTrack(
-                                audio_stream_type_t streamType,
-                                uint32_t sampleRate,
-                                audio_format_t format,
-                                audio_channel_mask_t channelMask,
-                                size_t *pFrameCount,
-                                audio_output_flags_t *flags,
-                                const sp<IMemory>& sharedBuffer,
-                                audio_io_handle_t output,
-                                pid_t pid,
-                                pid_t tid,
-                                audio_session_t *sessionId,
-                                int clientUid,
-                                status_t *status)
-    {
-        Parcel data, reply;
-        sp<IAudioTrack> track;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) streamType);
-        data.writeInt32(sampleRate);
-        data.writeInt32(format);
-        data.writeInt32(channelMask);
-        size_t frameCount = pFrameCount != NULL ? *pFrameCount : 0;
-        data.writeInt64(frameCount);
-        audio_output_flags_t lFlags = flags != NULL ? *flags : AUDIO_OUTPUT_FLAG_NONE;
-        data.writeInt32(lFlags);
-        // haveSharedBuffer
-        if (sharedBuffer != 0) {
-            data.writeInt32(true);
-            data.writeStrongBinder(IInterface::asBinder(sharedBuffer));
-        } else {
-            data.writeInt32(false);
-        }
-        data.writeInt32((int32_t) output);
-        data.writeInt32((int32_t) pid);
-        data.writeInt32((int32_t) tid);
-        audio_session_t lSessionId = AUDIO_SESSION_ALLOCATE;
-        if (sessionId != NULL) {
-            lSessionId = *sessionId;
-        }
-        data.writeInt32(lSessionId);
-        data.writeInt32(clientUid);
-        status_t lStatus = remote()->transact(CREATE_TRACK, data, &reply);
-        if (lStatus != NO_ERROR) {
-            ALOGE("createTrack error: %s", strerror(-lStatus));
-        } else {
-            frameCount = reply.readInt64();
-            if (pFrameCount != NULL) {
-                *pFrameCount = frameCount;
-            }
-            lFlags = (audio_output_flags_t)reply.readInt32();
-            if (flags != NULL) {
-                *flags = lFlags;
-            }
-            lSessionId = (audio_session_t) reply.readInt32();
-            if (sessionId != NULL) {
-                *sessionId = lSessionId;
-            }
-            lStatus = reply.readInt32();
-            track = interface_cast<IAudioTrack>(reply.readStrongBinder());
-            if (lStatus == NO_ERROR) {
-                if (track == 0) {
-                    ALOGE("createTrack should have returned an IAudioTrack");
-                    lStatus = UNKNOWN_ERROR;
-                }
-            } else {
-                if (track != 0) {
-                    ALOGE("createTrack returned an IAudioTrack but with status %d", lStatus);
-                    track.clear();
-                }
-            }
-        }
-        if (status != NULL) {
-            *status = lStatus;
-        }
-        return track;
-    }
-
-    virtual sp<IAudioRecord> openRecord(
-                                audio_io_handle_t input,
-                                uint32_t sampleRate,
-                                audio_format_t format,
-                                audio_channel_mask_t channelMask,
-                                const String16& opPackageName,
-                                size_t *pFrameCount,
-                                audio_input_flags_t *flags,
-                                pid_t pid,
-                                pid_t tid,
-                                int clientUid,
-                                audio_session_t *sessionId,
-                                size_t *notificationFrames,
-                                sp<IMemory>& cblk,
-                                sp<IMemory>& buffers,
-                                status_t *status)
-    {
-        Parcel data, reply;
-        sp<IAudioRecord> record;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) input);
-        data.writeInt32(sampleRate);
-        data.writeInt32(format);
-        data.writeInt32(channelMask);
-        data.writeString16(opPackageName);
-        size_t frameCount = pFrameCount != NULL ? *pFrameCount : 0;
-        data.writeInt64(frameCount);
-        audio_input_flags_t lFlags = flags != NULL ? *flags : AUDIO_INPUT_FLAG_NONE;
-        data.writeInt32(lFlags);
-        data.writeInt32((int32_t) pid);
-        data.writeInt32((int32_t) tid);
-        data.writeInt32((int32_t) clientUid);
-        audio_session_t lSessionId = AUDIO_SESSION_ALLOCATE;
-        if (sessionId != NULL) {
-            lSessionId = *sessionId;
-        }
-        data.writeInt32(lSessionId);
-        data.writeInt64(notificationFrames != NULL ? *notificationFrames : 0);
-        cblk.clear();
-        buffers.clear();
-        status_t lStatus = remote()->transact(OPEN_RECORD, data, &reply);
-        if (lStatus != NO_ERROR) {
-            ALOGE("openRecord error: %s", strerror(-lStatus));
-        } else {
-            frameCount = reply.readInt64();
-            if (pFrameCount != NULL) {
-                *pFrameCount = frameCount;
-            }
-            lFlags = (audio_input_flags_t)reply.readInt32();
-            if (flags != NULL) {
-                *flags = lFlags;
-            }
-            lSessionId = (audio_session_t) reply.readInt32();
-            if (sessionId != NULL) {
-                *sessionId = lSessionId;
-            }
-            size_t lNotificationFrames = (size_t) reply.readInt64();
-            if (notificationFrames != NULL) {
-                *notificationFrames = lNotificationFrames;
-            }
-            lStatus = reply.readInt32();
-            record = interface_cast<IAudioRecord>(reply.readStrongBinder());
-            cblk = interface_cast<IMemory>(reply.readStrongBinder());
-            if (cblk != 0 && cblk->pointer() == NULL) {
-                cblk.clear();
-            }
-            buffers = interface_cast<IMemory>(reply.readStrongBinder());
-            if (buffers != 0 && buffers->pointer() == NULL) {
-                buffers.clear();
-            }
-            if (lStatus == NO_ERROR) {
-                if (record == 0) {
-                    ALOGE("openRecord should have returned an IAudioRecord");
-                    lStatus = UNKNOWN_ERROR;
-                } else if (cblk == 0) {
-                    ALOGE("openRecord should have returned a cblk");
-                    lStatus = NO_MEMORY;
-                }
-                // buffers is permitted to be 0
-            } else {
-                if (record != 0 || cblk != 0 || buffers != 0) {
-                    ALOGE("openRecord returned an IAudioRecord, cblk, "
-                          "or buffers but with status %d", lStatus);
-                }
-            }
-            if (lStatus != NO_ERROR) {
-                record.clear();
-                cblk.clear();
-                buffers.clear();
-            }
-        }
-        if (status != NULL) {
-            *status = lStatus;
-        }
-        return record;
-    }
-
-    virtual uint32_t sampleRate(audio_io_handle_t ioHandle) const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) ioHandle);
-        remote()->transact(SAMPLE_RATE, data, &reply);
-        return reply.readInt32();
-    }
-
-    // RESERVED for channelCount()
-
-    virtual audio_format_t format(audio_io_handle_t output) const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) output);
-        remote()->transact(FORMAT, data, &reply);
-        return (audio_format_t) reply.readInt32();
-    }
-
-    virtual size_t frameCount(audio_io_handle_t ioHandle) const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) ioHandle);
-        remote()->transact(FRAME_COUNT, data, &reply);
-        return reply.readInt64();
-    }
-
-    virtual uint32_t latency(audio_io_handle_t output) const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) output);
-        remote()->transact(LATENCY, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual status_t setMasterVolume(float value)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeFloat(value);
-        remote()->transact(SET_MASTER_VOLUME, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual status_t setMasterMute(bool muted)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(muted);
-        remote()->transact(SET_MASTER_MUTE, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual float masterVolume() const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        remote()->transact(MASTER_VOLUME, data, &reply);
-        return reply.readFloat();
-    }
-
-    virtual bool masterMute() const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        remote()->transact(MASTER_MUTE, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual status_t setStreamVolume(audio_stream_type_t stream, float value,
-            audio_io_handle_t output)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) stream);
-        data.writeFloat(value);
-        data.writeInt32((int32_t) output);
-        remote()->transact(SET_STREAM_VOLUME, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual status_t setStreamMute(audio_stream_type_t stream, bool muted)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) stream);
-        data.writeInt32(muted);
-        remote()->transact(SET_STREAM_MUTE, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual float streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) stream);
-        data.writeInt32((int32_t) output);
-        remote()->transact(STREAM_VOLUME, data, &reply);
-        return reply.readFloat();
-    }
-
-    virtual bool streamMute(audio_stream_type_t stream) const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) stream);
-        remote()->transact(STREAM_MUTE, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual status_t setMode(audio_mode_t mode)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(mode);
-        remote()->transact(SET_MODE, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual status_t setMicMute(bool state)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(state);
-        remote()->transact(SET_MIC_MUTE, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual bool getMicMute() const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        remote()->transact(GET_MIC_MUTE, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual status_t setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) ioHandle);
-        data.writeString8(keyValuePairs);
-        remote()->transact(SET_PARAMETERS, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual String8 getParameters(audio_io_handle_t ioHandle, const String8& keys) const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) ioHandle);
-        data.writeString8(keys);
-        remote()->transact(GET_PARAMETERS, data, &reply);
-        return reply.readString8();
-    }
-
-    virtual void registerClient(const sp<IAudioFlingerClient>& client)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeStrongBinder(IInterface::asBinder(client));
-        remote()->transact(REGISTER_CLIENT, data, &reply);
-    }
-
-    virtual size_t getInputBufferSize(uint32_t sampleRate, audio_format_t format,
-            audio_channel_mask_t channelMask) const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(sampleRate);
-        data.writeInt32(format);
-        data.writeInt32(channelMask);
-        remote()->transact(GET_INPUTBUFFERSIZE, data, &reply);
-        return reply.readInt64();
-    }
-
-    virtual status_t openOutput(audio_module_handle_t module,
-                                audio_io_handle_t *output,
-                                audio_config_t *config,
-                                audio_devices_t *devices,
-                                const String8& address,
-                                uint32_t *latencyMs,
-                                audio_output_flags_t flags)
-    {
-        if (output == NULL || config == NULL || devices == NULL || latencyMs == NULL) {
-            return BAD_VALUE;
-        }
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(module);
-        data.write(config, sizeof(audio_config_t));
-        data.writeInt32(*devices);
-        data.writeString8(address);
-        data.writeInt32((int32_t) flags);
-        status_t status = remote()->transact(OPEN_OUTPUT, data, &reply);
-        if (status != NO_ERROR) {
-            *output = AUDIO_IO_HANDLE_NONE;
-            return status;
-        }
-        status = (status_t)reply.readInt32();
-        if (status != NO_ERROR) {
-            *output = AUDIO_IO_HANDLE_NONE;
-            return status;
-        }
-        *output = (audio_io_handle_t)reply.readInt32();
-        ALOGV("openOutput() returned output, %d", *output);
-        reply.read(config, sizeof(audio_config_t));
-        *devices = (audio_devices_t)reply.readInt32();
-        *latencyMs = reply.readInt32();
-        return NO_ERROR;
-    }
-
-    virtual audio_io_handle_t openDuplicateOutput(audio_io_handle_t output1,
-            audio_io_handle_t output2)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) output1);
-        data.writeInt32((int32_t) output2);
-        remote()->transact(OPEN_DUPLICATE_OUTPUT, data, &reply);
-        return (audio_io_handle_t) reply.readInt32();
-    }
-
-    virtual status_t closeOutput(audio_io_handle_t output)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) output);
-        remote()->transact(CLOSE_OUTPUT, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual status_t suspendOutput(audio_io_handle_t output)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) output);
-        remote()->transact(SUSPEND_OUTPUT, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual status_t restoreOutput(audio_io_handle_t output)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) output);
-        remote()->transact(RESTORE_OUTPUT, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual status_t openInput(audio_module_handle_t module,
-                               audio_io_handle_t *input,
-                               audio_config_t *config,
-                               audio_devices_t *device,
-                               const String8& address,
-                               audio_source_t source,
-                               audio_input_flags_t flags)
-    {
-        if (input == NULL || config == NULL || device == NULL) {
-            return BAD_VALUE;
-        }
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(module);
-        data.writeInt32(*input);
-        data.write(config, sizeof(audio_config_t));
-        data.writeInt32(*device);
-        data.writeString8(address);
-        data.writeInt32(source);
-        data.writeInt32(flags);
-        status_t status = remote()->transact(OPEN_INPUT, data, &reply);
-        if (status != NO_ERROR) {
-            *input = AUDIO_IO_HANDLE_NONE;
-            return status;
-        }
-        status = (status_t)reply.readInt32();
-        if (status != NO_ERROR) {
-            *input = AUDIO_IO_HANDLE_NONE;
-            return status;
-        }
-        *input = (audio_io_handle_t)reply.readInt32();
-        reply.read(config, sizeof(audio_config_t));
-        *device = (audio_devices_t)reply.readInt32();
-        return NO_ERROR;
-    }
-
-    virtual status_t closeInput(int input)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(input);
-        remote()->transact(CLOSE_INPUT, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual status_t invalidateStream(audio_stream_type_t stream)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) stream);
-        remote()->transact(INVALIDATE_STREAM, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual status_t setVoiceVolume(float volume)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeFloat(volume);
-        remote()->transact(SET_VOICE_VOLUME, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
-            audio_io_handle_t output) const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) output);
-        remote()->transact(GET_RENDER_POSITION, data, &reply);
-        status_t status = reply.readInt32();
-        if (status == NO_ERROR) {
-            uint32_t tmp = reply.readInt32();
-            if (halFrames != NULL) {
-                *halFrames = tmp;
-            }
-            tmp = reply.readInt32();
-            if (dspFrames != NULL) {
-                *dspFrames = tmp;
-            }
-        }
-        return status;
-    }
-
-    virtual uint32_t getInputFramesLost(audio_io_handle_t ioHandle) const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) ioHandle);
-        status_t status = remote()->transact(GET_INPUT_FRAMES_LOST, data, &reply);
-        if (status != NO_ERROR) {
-            return 0;
-        }
-        return (uint32_t) reply.readInt32();
-    }
-
-    virtual audio_unique_id_t newAudioUniqueId(audio_unique_id_use_t use)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) use);
-        status_t status = remote()->transact(NEW_AUDIO_SESSION_ID, data, &reply);
-        audio_unique_id_t id = AUDIO_SESSION_ALLOCATE;
-        if (status == NO_ERROR) {
-            id = reply.readInt32();
-        }
-        return id;
-    }
-
-    virtual void acquireAudioSessionId(audio_session_t audioSession, int pid)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(audioSession);
-        data.writeInt32(pid);
-        remote()->transact(ACQUIRE_AUDIO_SESSION_ID, data, &reply);
-    }
-
-    virtual void releaseAudioSessionId(audio_session_t audioSession, int pid)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(audioSession);
-        data.writeInt32(pid);
-        remote()->transact(RELEASE_AUDIO_SESSION_ID, data, &reply);
-    }
-
-    virtual status_t queryNumberEffects(uint32_t *numEffects) const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        status_t status = remote()->transact(QUERY_NUM_EFFECTS, data, &reply);
-        if (status != NO_ERROR) {
-            return status;
-        }
-        status = reply.readInt32();
-        if (status != NO_ERROR) {
-            return status;
-        }
-        if (numEffects != NULL) {
-            *numEffects = (uint32_t)reply.readInt32();
-        }
-        return NO_ERROR;
-    }
-
-    virtual status_t queryEffect(uint32_t index, effect_descriptor_t *pDescriptor) const
-    {
-        if (pDescriptor == NULL) {
-            return BAD_VALUE;
-        }
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(index);
-        status_t status = remote()->transact(QUERY_EFFECT, data, &reply);
-        if (status != NO_ERROR) {
-            return status;
-        }
-        status = reply.readInt32();
-        if (status != NO_ERROR) {
-            return status;
-        }
-        reply.read(pDescriptor, sizeof(effect_descriptor_t));
-        return NO_ERROR;
-    }
-
-    virtual status_t getEffectDescriptor(const effect_uuid_t *pUuid,
-            effect_descriptor_t *pDescriptor) const
-    {
-        if (pUuid == NULL || pDescriptor == NULL) {
-            return BAD_VALUE;
-        }
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.write(pUuid, sizeof(effect_uuid_t));
-        status_t status = remote()->transact(GET_EFFECT_DESCRIPTOR, data, &reply);
-        if (status != NO_ERROR) {
-            return status;
-        }
-        status = reply.readInt32();
-        if (status != NO_ERROR) {
-            return status;
-        }
-        reply.read(pDescriptor, sizeof(effect_descriptor_t));
-        return NO_ERROR;
-    }
-
-    virtual sp<IEffect> createEffect(
-                                    effect_descriptor_t *pDesc,
-                                    const sp<IEffectClient>& client,
-                                    int32_t priority,
-                                    audio_io_handle_t output,
-                                    audio_session_t sessionId,
-                                    const String16& opPackageName,
-                                    status_t *status,
-                                    int *id,
-                                    int *enabled)
-    {
-        Parcel data, reply;
-        sp<IEffect> effect;
-
-        if (pDesc == NULL) {
-            return effect;
-            if (status != NULL) {
-                *status = BAD_VALUE;
-            }
-        }
-
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.write(pDesc, sizeof(effect_descriptor_t));
-        data.writeStrongBinder(IInterface::asBinder(client));
-        data.writeInt32(priority);
-        data.writeInt32((int32_t) output);
-        data.writeInt32(sessionId);
-        data.writeString16(opPackageName);
-
-        status_t lStatus = remote()->transact(CREATE_EFFECT, data, &reply);
-        if (lStatus != NO_ERROR) {
-            ALOGE("createEffect error: %s", strerror(-lStatus));
-        } else {
-            lStatus = reply.readInt32();
-            int tmp = reply.readInt32();
-            if (id != NULL) {
-                *id = tmp;
-            }
-            tmp = reply.readInt32();
-            if (enabled != NULL) {
-                *enabled = tmp;
-            }
-            effect = interface_cast<IEffect>(reply.readStrongBinder());
-            reply.read(pDesc, sizeof(effect_descriptor_t));
-        }
-        if (status != NULL) {
-            *status = lStatus;
-        }
-
-        return effect;
-    }
-
-    virtual status_t moveEffects(audio_session_t session, audio_io_handle_t srcOutput,
-            audio_io_handle_t dstOutput)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(session);
-        data.writeInt32((int32_t) srcOutput);
-        data.writeInt32((int32_t) dstOutput);
-        remote()->transact(MOVE_EFFECTS, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual audio_module_handle_t loadHwModule(const char *name)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeCString(name);
-        remote()->transact(LOAD_HW_MODULE, data, &reply);
-        return (audio_module_handle_t) reply.readInt32();
-    }
-
-    virtual uint32_t getPrimaryOutputSamplingRate()
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        remote()->transact(GET_PRIMARY_OUTPUT_SAMPLING_RATE, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual size_t getPrimaryOutputFrameCount()
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        remote()->transact(GET_PRIMARY_OUTPUT_FRAME_COUNT, data, &reply);
-        return reply.readInt64();
-    }
-
-    virtual status_t setLowRamDevice(bool isLowRamDevice)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int) isLowRamDevice);
-        remote()->transact(SET_LOW_RAM_DEVICE, data, &reply);
-        return reply.readInt32();
-    }
-    virtual status_t listAudioPorts(unsigned int *num_ports,
-                                    struct audio_port *ports)
-    {
-        if (num_ports == NULL || *num_ports == 0 || ports == NULL) {
-            return BAD_VALUE;
-        }
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(*num_ports);
-        status_t status = remote()->transact(LIST_AUDIO_PORTS, data, &reply);
-        if (status != NO_ERROR ||
-                (status = (status_t)reply.readInt32()) != NO_ERROR) {
-            return status;
-        }
-        *num_ports = (unsigned int)reply.readInt32();
-        reply.read(ports, *num_ports * sizeof(struct audio_port));
-        return status;
-    }
-    virtual status_t getAudioPort(struct audio_port *port)
-    {
-        if (port == NULL) {
-            return BAD_VALUE;
-        }
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.write(port, sizeof(struct audio_port));
-        status_t status = remote()->transact(GET_AUDIO_PORT, data, &reply);
-        if (status != NO_ERROR ||
-                (status = (status_t)reply.readInt32()) != NO_ERROR) {
-            return status;
-        }
-        reply.read(port, sizeof(struct audio_port));
-        return status;
-    }
-    virtual status_t createAudioPatch(const struct audio_patch *patch,
-                                       audio_patch_handle_t *handle)
-    {
-        if (patch == NULL || handle == NULL) {
-            return BAD_VALUE;
-        }
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.write(patch, sizeof(struct audio_patch));
-        data.write(handle, sizeof(audio_patch_handle_t));
-        status_t status = remote()->transact(CREATE_AUDIO_PATCH, data, &reply);
-        if (status != NO_ERROR ||
-                (status = (status_t)reply.readInt32()) != NO_ERROR) {
-            return status;
-        }
-        reply.read(handle, sizeof(audio_patch_handle_t));
-        return status;
-    }
-    virtual status_t releaseAudioPatch(audio_patch_handle_t handle)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.write(&handle, sizeof(audio_patch_handle_t));
-        status_t status = remote()->transact(RELEASE_AUDIO_PATCH, data, &reply);
-        if (status != NO_ERROR) {
-            status = (status_t)reply.readInt32();
-        }
-        return status;
-    }
-    virtual status_t listAudioPatches(unsigned int *num_patches,
-                                      struct audio_patch *patches)
-    {
-        if (num_patches == NULL || *num_patches == 0 || patches == NULL) {
-            return BAD_VALUE;
-        }
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(*num_patches);
-        status_t status = remote()->transact(LIST_AUDIO_PATCHES, data, &reply);
-        if (status != NO_ERROR ||
-                (status = (status_t)reply.readInt32()) != NO_ERROR) {
-            return status;
-        }
-        *num_patches = (unsigned int)reply.readInt32();
-        reply.read(patches, *num_patches * sizeof(struct audio_patch));
-        return status;
-    }
-    virtual status_t setAudioPortConfig(const struct audio_port_config *config)
-    {
-        if (config == NULL) {
-            return BAD_VALUE;
-        }
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.write(config, sizeof(struct audio_port_config));
-        status_t status = remote()->transact(SET_AUDIO_PORT_CONFIG, data, &reply);
-        if (status != NO_ERROR) {
-            status = (status_t)reply.readInt32();
-        }
-        return status;
-    }
-    virtual audio_hw_sync_t getAudioHwSyncForSession(audio_session_t sessionId)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(sessionId);
-        status_t status = remote()->transact(GET_AUDIO_HW_SYNC, data, &reply);
-        if (status != NO_ERROR) {
-            return AUDIO_HW_SYNC_INVALID;
-        }
-        return (audio_hw_sync_t)reply.readInt32();
-    }
-    virtual status_t systemReady()
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        return remote()->transact(SYSTEM_READY, data, &reply, IBinder::FLAG_ONEWAY);
-    }
-    virtual size_t frameCountHAL(audio_io_handle_t ioHandle) const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32((int32_t) ioHandle);
-        status_t status = remote()->transact(FRAME_COUNT_HAL, data, &reply);
-        if (status != NO_ERROR) {
-            return 0;
-        }
-        return reply.readInt64();
-    }
-
-};
-
-IMPLEMENT_META_INTERFACE(AudioFlinger, "android.media.IAudioFlinger");
-
-// ----------------------------------------------------------------------
-
-status_t BnAudioFlinger::onTransact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
-    switch (code) {
-        case CREATE_TRACK: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            int streamType = data.readInt32();
-            uint32_t sampleRate = data.readInt32();
-            audio_format_t format = (audio_format_t) data.readInt32();
-            audio_channel_mask_t channelMask = data.readInt32();
-            size_t frameCount = data.readInt64();
-            audio_output_flags_t flags = (audio_output_flags_t) data.readInt32();
-            bool haveSharedBuffer = data.readInt32() != 0;
-            sp<IMemory> buffer;
-            if (haveSharedBuffer) {
-                buffer = interface_cast<IMemory>(data.readStrongBinder());
-            }
-            audio_io_handle_t output = (audio_io_handle_t) data.readInt32();
-            pid_t pid = (pid_t) data.readInt32();
-            pid_t tid = (pid_t) data.readInt32();
-            audio_session_t sessionId = (audio_session_t) data.readInt32();
-            int clientUid = data.readInt32();
-            status_t status = NO_ERROR;
-            sp<IAudioTrack> track;
-            if ((haveSharedBuffer && (buffer == 0)) ||
-                    ((buffer != 0) && (buffer->pointer() == NULL))) {
-                ALOGW("CREATE_TRACK: cannot retrieve shared memory");
-                status = DEAD_OBJECT;
-            } else {
-                track = createTrack(
-                        (audio_stream_type_t) streamType, sampleRate, format,
-                        channelMask, &frameCount, &flags, buffer, output, pid, tid,
-                        &sessionId, clientUid, &status);
-                LOG_ALWAYS_FATAL_IF((track != 0) != (status == NO_ERROR));
-            }
-            reply->writeInt64(frameCount);
-            reply->writeInt32(flags);
-            reply->writeInt32(sessionId);
-            reply->writeInt32(status);
-            reply->writeStrongBinder(IInterface::asBinder(track));
-            return NO_ERROR;
-        } break;
-        case OPEN_RECORD: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            audio_io_handle_t input = (audio_io_handle_t) data.readInt32();
-            uint32_t sampleRate = data.readInt32();
-            audio_format_t format = (audio_format_t) data.readInt32();
-            audio_channel_mask_t channelMask = data.readInt32();
-            const String16& opPackageName = data.readString16();
-            size_t frameCount = data.readInt64();
-            audio_input_flags_t flags = (audio_input_flags_t) data.readInt32();
-            pid_t pid = (pid_t) data.readInt32();
-            pid_t tid = (pid_t) data.readInt32();
-            int clientUid = data.readInt32();
-            audio_session_t sessionId = (audio_session_t) data.readInt32();
-            size_t notificationFrames = data.readInt64();
-            sp<IMemory> cblk;
-            sp<IMemory> buffers;
-            status_t status = NO_ERROR;
-            sp<IAudioRecord> record = openRecord(input,
-                    sampleRate, format, channelMask, opPackageName, &frameCount, &flags,
-                    pid, tid, clientUid, &sessionId, &notificationFrames, cblk, buffers,
-                    &status);
-            LOG_ALWAYS_FATAL_IF((record != 0) != (status == NO_ERROR));
-            reply->writeInt64(frameCount);
-            reply->writeInt32(flags);
-            reply->writeInt32(sessionId);
-            reply->writeInt64(notificationFrames);
-            reply->writeInt32(status);
-            reply->writeStrongBinder(IInterface::asBinder(record));
-            reply->writeStrongBinder(IInterface::asBinder(cblk));
-            reply->writeStrongBinder(IInterface::asBinder(buffers));
-            return NO_ERROR;
-        } break;
-        case SAMPLE_RATE: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt32( sampleRate((audio_io_handle_t) data.readInt32()) );
-            return NO_ERROR;
-        } break;
-
-        // RESERVED for channelCount()
-
-        case FORMAT: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt32( format((audio_io_handle_t) data.readInt32()) );
-            return NO_ERROR;
-        } break;
-        case FRAME_COUNT: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt64( frameCount((audio_io_handle_t) data.readInt32()) );
-            return NO_ERROR;
-        } break;
-        case LATENCY: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt32( latency((audio_io_handle_t) data.readInt32()) );
-            return NO_ERROR;
-        } break;
-        case SET_MASTER_VOLUME: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt32( setMasterVolume(data.readFloat()) );
-            return NO_ERROR;
-        } break;
-        case SET_MASTER_MUTE: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt32( setMasterMute(data.readInt32()) );
-            return NO_ERROR;
-        } break;
-        case MASTER_VOLUME: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeFloat( masterVolume() );
-            return NO_ERROR;
-        } break;
-        case MASTER_MUTE: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt32( masterMute() );
-            return NO_ERROR;
-        } break;
-        case SET_STREAM_VOLUME: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            int stream = data.readInt32();
-            float volume = data.readFloat();
-            audio_io_handle_t output = (audio_io_handle_t) data.readInt32();
-            reply->writeInt32( setStreamVolume((audio_stream_type_t) stream, volume, output) );
-            return NO_ERROR;
-        } break;
-        case SET_STREAM_MUTE: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            int stream = data.readInt32();
-            reply->writeInt32( setStreamMute((audio_stream_type_t) stream, data.readInt32()) );
-            return NO_ERROR;
-        } break;
-        case STREAM_VOLUME: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            int stream = data.readInt32();
-            int output = data.readInt32();
-            reply->writeFloat( streamVolume((audio_stream_type_t) stream, output) );
-            return NO_ERROR;
-        } break;
-        case STREAM_MUTE: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            int stream = data.readInt32();
-            reply->writeInt32( streamMute((audio_stream_type_t) stream) );
-            return NO_ERROR;
-        } break;
-        case SET_MODE: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            audio_mode_t mode = (audio_mode_t) data.readInt32();
-            reply->writeInt32( setMode(mode) );
-            return NO_ERROR;
-        } break;
-        case SET_MIC_MUTE: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            int state = data.readInt32();
-            reply->writeInt32( setMicMute(state) );
-            return NO_ERROR;
-        } break;
-        case GET_MIC_MUTE: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt32( getMicMute() );
-            return NO_ERROR;
-        } break;
-        case SET_PARAMETERS: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            audio_io_handle_t ioHandle = (audio_io_handle_t) data.readInt32();
-            String8 keyValuePairs(data.readString8());
-            reply->writeInt32(setParameters(ioHandle, keyValuePairs));
-            return NO_ERROR;
-        } break;
-        case GET_PARAMETERS: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            audio_io_handle_t ioHandle = (audio_io_handle_t) data.readInt32();
-            String8 keys(data.readString8());
-            reply->writeString8(getParameters(ioHandle, keys));
-            return NO_ERROR;
-        } break;
-
-        case REGISTER_CLIENT: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            sp<IAudioFlingerClient> client = interface_cast<IAudioFlingerClient>(
-                    data.readStrongBinder());
-            registerClient(client);
-            return NO_ERROR;
-        } break;
-        case GET_INPUTBUFFERSIZE: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            uint32_t sampleRate = data.readInt32();
-            audio_format_t format = (audio_format_t) data.readInt32();
-            audio_channel_mask_t channelMask = data.readInt32();
-            reply->writeInt64( getInputBufferSize(sampleRate, format, channelMask) );
-            return NO_ERROR;
-        } break;
-        case OPEN_OUTPUT: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            audio_module_handle_t module = (audio_module_handle_t)data.readInt32();
-            audio_config_t config = {};
-            if (data.read(&config, sizeof(audio_config_t)) != NO_ERROR) {
-                ALOGE("b/23905951");
-            }
-            audio_devices_t devices = (audio_devices_t)data.readInt32();
-            String8 address(data.readString8());
-            audio_output_flags_t flags = (audio_output_flags_t) data.readInt32();
-            uint32_t latencyMs = 0;
-            audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
-            status_t status = openOutput(module, &output, &config,
-                                         &devices, address, &latencyMs, flags);
-            ALOGV("OPEN_OUTPUT output, %d", output);
-            reply->writeInt32((int32_t)status);
-            if (status == NO_ERROR) {
-                reply->writeInt32((int32_t)output);
-                reply->write(&config, sizeof(audio_config_t));
-                reply->writeInt32(devices);
-                reply->writeInt32(latencyMs);
-            }
-            return NO_ERROR;
-        } break;
-        case OPEN_DUPLICATE_OUTPUT: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            audio_io_handle_t output1 = (audio_io_handle_t) data.readInt32();
-            audio_io_handle_t output2 = (audio_io_handle_t) data.readInt32();
-            reply->writeInt32((int32_t) openDuplicateOutput(output1, output2));
-            return NO_ERROR;
-        } break;
-        case CLOSE_OUTPUT: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt32(closeOutput((audio_io_handle_t) data.readInt32()));
-            return NO_ERROR;
-        } break;
-        case SUSPEND_OUTPUT: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt32(suspendOutput((audio_io_handle_t) data.readInt32()));
-            return NO_ERROR;
-        } break;
-        case RESTORE_OUTPUT: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt32(restoreOutput((audio_io_handle_t) data.readInt32()));
-            return NO_ERROR;
-        } break;
-        case OPEN_INPUT: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            audio_module_handle_t module = (audio_module_handle_t)data.readInt32();
-            audio_io_handle_t input = (audio_io_handle_t)data.readInt32();
-            audio_config_t config = {};
-            if (data.read(&config, sizeof(audio_config_t)) != NO_ERROR) {
-                ALOGE("b/23905951");
-            }
-            audio_devices_t device = (audio_devices_t)data.readInt32();
-            String8 address(data.readString8());
-            audio_source_t source = (audio_source_t)data.readInt32();
-            audio_input_flags_t flags = (audio_input_flags_t) data.readInt32();
-
-            status_t status = openInput(module, &input, &config,
-                                        &device, address, source, flags);
-            reply->writeInt32((int32_t) status);
-            if (status == NO_ERROR) {
-                reply->writeInt32((int32_t) input);
-                reply->write(&config, sizeof(audio_config_t));
-                reply->writeInt32(device);
-            }
-            return NO_ERROR;
-        } break;
-        case CLOSE_INPUT: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt32(closeInput((audio_io_handle_t) data.readInt32()));
-            return NO_ERROR;
-        } break;
-        case INVALIDATE_STREAM: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            audio_stream_type_t stream = (audio_stream_type_t) data.readInt32();
-            reply->writeInt32(invalidateStream(stream));
-            return NO_ERROR;
-        } break;
-        case SET_VOICE_VOLUME: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            float volume = data.readFloat();
-            reply->writeInt32( setVoiceVolume(volume) );
-            return NO_ERROR;
-        } break;
-        case GET_RENDER_POSITION: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            audio_io_handle_t output = (audio_io_handle_t) data.readInt32();
-            uint32_t halFrames = 0;
-            uint32_t dspFrames = 0;
-            status_t status = getRenderPosition(&halFrames, &dspFrames, output);
-            reply->writeInt32(status);
-            if (status == NO_ERROR) {
-                reply->writeInt32(halFrames);
-                reply->writeInt32(dspFrames);
-            }
-            return NO_ERROR;
-        }
-        case GET_INPUT_FRAMES_LOST: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            audio_io_handle_t ioHandle = (audio_io_handle_t) data.readInt32();
-            reply->writeInt32((int32_t) getInputFramesLost(ioHandle));
-            return NO_ERROR;
-        } break;
-        case NEW_AUDIO_SESSION_ID: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt32(newAudioUniqueId((audio_unique_id_use_t) data.readInt32()));
-            return NO_ERROR;
-        } break;
-        case ACQUIRE_AUDIO_SESSION_ID: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            audio_session_t audioSession = (audio_session_t) data.readInt32();
-            int pid = data.readInt32();
-            acquireAudioSessionId(audioSession, pid);
-            return NO_ERROR;
-        } break;
-        case RELEASE_AUDIO_SESSION_ID: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            audio_session_t audioSession = (audio_session_t) data.readInt32();
-            int pid = data.readInt32();
-            releaseAudioSessionId(audioSession, pid);
-            return NO_ERROR;
-        } break;
-        case QUERY_NUM_EFFECTS: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            uint32_t numEffects = 0;
-            status_t status = queryNumberEffects(&numEffects);
-            reply->writeInt32(status);
-            if (status == NO_ERROR) {
-                reply->writeInt32((int32_t)numEffects);
-            }
-            return NO_ERROR;
-        }
-        case QUERY_EFFECT: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            effect_descriptor_t desc = {};
-            status_t status = queryEffect(data.readInt32(), &desc);
-            reply->writeInt32(status);
-            if (status == NO_ERROR) {
-                reply->write(&desc, sizeof(effect_descriptor_t));
-            }
-            return NO_ERROR;
-        }
-        case GET_EFFECT_DESCRIPTOR: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            effect_uuid_t uuid;
-            data.read(&uuid, sizeof(effect_uuid_t));
-            effect_descriptor_t desc = {};
-            status_t status = getEffectDescriptor(&uuid, &desc);
-            reply->writeInt32(status);
-            if (status == NO_ERROR) {
-                reply->write(&desc, sizeof(effect_descriptor_t));
-            }
-            return NO_ERROR;
-        }
-        case CREATE_EFFECT: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            effect_descriptor_t desc = {};
-            if (data.read(&desc, sizeof(effect_descriptor_t)) != NO_ERROR) {
-                ALOGE("b/23905951");
-            }
-            sp<IEffectClient> client = interface_cast<IEffectClient>(data.readStrongBinder());
-            int32_t priority = data.readInt32();
-            audio_io_handle_t output = (audio_io_handle_t) data.readInt32();
-            audio_session_t sessionId = (audio_session_t) data.readInt32();
-            const String16 opPackageName = data.readString16();
-            status_t status = NO_ERROR;
-            int id = 0;
-            int enabled = 0;
-
-            sp<IEffect> effect = createEffect(&desc, client, priority, output, sessionId,
-                    opPackageName, &status, &id, &enabled);
-            reply->writeInt32(status);
-            reply->writeInt32(id);
-            reply->writeInt32(enabled);
-            reply->writeStrongBinder(IInterface::asBinder(effect));
-            reply->write(&desc, sizeof(effect_descriptor_t));
-            return NO_ERROR;
-        } break;
-        case MOVE_EFFECTS: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            audio_session_t session = (audio_session_t) data.readInt32();
-            audio_io_handle_t srcOutput = (audio_io_handle_t) data.readInt32();
-            audio_io_handle_t dstOutput = (audio_io_handle_t) data.readInt32();
-            reply->writeInt32(moveEffects(session, srcOutput, dstOutput));
-            return NO_ERROR;
-        } break;
-        case LOAD_HW_MODULE: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt32(loadHwModule(data.readCString()));
-            return NO_ERROR;
-        } break;
-        case GET_PRIMARY_OUTPUT_SAMPLING_RATE: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt32(getPrimaryOutputSamplingRate());
-            return NO_ERROR;
-        } break;
-        case GET_PRIMARY_OUTPUT_FRAME_COUNT: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt64(getPrimaryOutputFrameCount());
-            return NO_ERROR;
-        } break;
-        case SET_LOW_RAM_DEVICE: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            bool isLowRamDevice = data.readInt32() != 0;
-            reply->writeInt32(setLowRamDevice(isLowRamDevice));
-            return NO_ERROR;
-        } break;
-        case LIST_AUDIO_PORTS: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            unsigned int numPortsReq = data.readInt32();
-            if (numPortsReq > MAX_ITEMS_PER_LIST) {
-                numPortsReq = MAX_ITEMS_PER_LIST;
-            }
-            unsigned int numPorts = numPortsReq;
-            struct audio_port *ports =
-                    (struct audio_port *)calloc(numPortsReq,
-                                                           sizeof(struct audio_port));
-            if (ports == NULL) {
-                reply->writeInt32(NO_MEMORY);
-                reply->writeInt32(0);
-                return NO_ERROR;
-            }
-            status_t status = listAudioPorts(&numPorts, ports);
-            reply->writeInt32(status);
-            reply->writeInt32(numPorts);
-            if (status == NO_ERROR) {
-                if (numPortsReq > numPorts) {
-                    numPortsReq = numPorts;
-                }
-                reply->write(ports, numPortsReq * sizeof(struct audio_port));
-            }
-            free(ports);
-            return NO_ERROR;
-        } break;
-        case GET_AUDIO_PORT: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            struct audio_port port = {};
-            if (data.read(&port, sizeof(struct audio_port)) != NO_ERROR) {
-                ALOGE("b/23905951");
-            }
-            status_t status = getAudioPort(&port);
-            reply->writeInt32(status);
-            if (status == NO_ERROR) {
-                reply->write(&port, sizeof(struct audio_port));
-            }
-            return NO_ERROR;
-        } break;
-        case CREATE_AUDIO_PATCH: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            struct audio_patch patch;
-            data.read(&patch, sizeof(struct audio_patch));
-            audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
-            if (data.read(&handle, sizeof(audio_patch_handle_t)) != NO_ERROR) {
-                ALOGE("b/23905951");
-            }
-            status_t status = createAudioPatch(&patch, &handle);
-            reply->writeInt32(status);
-            if (status == NO_ERROR) {
-                reply->write(&handle, sizeof(audio_patch_handle_t));
-            }
-            return NO_ERROR;
-        } break;
-        case RELEASE_AUDIO_PATCH: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            audio_patch_handle_t handle;
-            data.read(&handle, sizeof(audio_patch_handle_t));
-            status_t status = releaseAudioPatch(handle);
-            reply->writeInt32(status);
-            return NO_ERROR;
-        } break;
-        case LIST_AUDIO_PATCHES: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            unsigned int numPatchesReq = data.readInt32();
-            if (numPatchesReq > MAX_ITEMS_PER_LIST) {
-                numPatchesReq = MAX_ITEMS_PER_LIST;
-            }
-            unsigned int numPatches = numPatchesReq;
-            struct audio_patch *patches =
-                    (struct audio_patch *)calloc(numPatchesReq,
-                                                 sizeof(struct audio_patch));
-            if (patches == NULL) {
-                reply->writeInt32(NO_MEMORY);
-                reply->writeInt32(0);
-                return NO_ERROR;
-            }
-            status_t status = listAudioPatches(&numPatches, patches);
-            reply->writeInt32(status);
-            reply->writeInt32(numPatches);
-            if (status == NO_ERROR) {
-                if (numPatchesReq > numPatches) {
-                    numPatchesReq = numPatches;
-                }
-                reply->write(patches, numPatchesReq * sizeof(struct audio_patch));
-            }
-            free(patches);
-            return NO_ERROR;
-        } break;
-        case SET_AUDIO_PORT_CONFIG: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            struct audio_port_config config;
-            data.read(&config, sizeof(struct audio_port_config));
-            status_t status = setAudioPortConfig(&config);
-            reply->writeInt32(status);
-            return NO_ERROR;
-        } break;
-        case GET_AUDIO_HW_SYNC: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt32(getAudioHwSyncForSession((audio_session_t) data.readInt32()));
-            return NO_ERROR;
-        } break;
-        case SYSTEM_READY: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            systemReady();
-            return NO_ERROR;
-        } break;
-        case FRAME_COUNT_HAL: {
-            CHECK_INTERFACE(IAudioFlinger, data, reply);
-            reply->writeInt64( frameCountHAL((audio_io_handle_t) data.readInt32()) );
-            return NO_ERROR;
-        } break;
-        default:
-            return BBinder::onTransact(code, data, reply, flags);
-    }
-}
-
-// ----------------------------------------------------------------------------
-
-} // namespace android
diff --git a/media/libmedia/IAudioFlingerClient.cpp b/media/libmedia/IAudioFlingerClient.cpp
deleted file mode 100644
index b2dbc4c..0000000
--- a/media/libmedia/IAudioFlingerClient.cpp
+++ /dev/null
@@ -1,89 +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.
- */
-
-#define LOG_TAG "IAudioFlingerClient"
-#include <utils/Log.h>
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <binder/Parcel.h>
-
-#include <media/IAudioFlingerClient.h>
-#include <media/AudioSystem.h>
-
-namespace android {
-
-enum {
-    IO_CONFIG_CHANGED = IBinder::FIRST_CALL_TRANSACTION
-};
-
-class BpAudioFlingerClient : public BpInterface<IAudioFlingerClient>
-{
-public:
-    explicit BpAudioFlingerClient(const sp<IBinder>& impl)
-        : BpInterface<IAudioFlingerClient>(impl)
-    {
-    }
-
-    void ioConfigChanged(audio_io_config_event event, const sp<AudioIoDescriptor>& ioDesc)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioFlingerClient::getInterfaceDescriptor());
-        data.writeInt32(event);
-        data.writeInt32((int32_t)ioDesc->mIoHandle);
-        data.write(&ioDesc->mPatch, sizeof(struct audio_patch));
-        data.writeInt32(ioDesc->mSamplingRate);
-        data.writeInt32(ioDesc->mFormat);
-        data.writeInt32(ioDesc->mChannelMask);
-        data.writeInt64(ioDesc->mFrameCount);
-        data.writeInt64(ioDesc->mFrameCountHAL);
-        data.writeInt32(ioDesc->mLatency);
-        remote()->transact(IO_CONFIG_CHANGED, data, &reply, IBinder::FLAG_ONEWAY);
-    }
-};
-
-IMPLEMENT_META_INTERFACE(AudioFlingerClient, "android.media.IAudioFlingerClient");
-
-// ----------------------------------------------------------------------
-
-status_t BnAudioFlingerClient::onTransact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
-    switch (code) {
-    case IO_CONFIG_CHANGED: {
-            CHECK_INTERFACE(IAudioFlingerClient, data, reply);
-            audio_io_config_event event = (audio_io_config_event)data.readInt32();
-            sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
-            ioDesc->mIoHandle = (audio_io_handle_t) data.readInt32();
-            data.read(&ioDesc->mPatch, sizeof(struct audio_patch));
-            ioDesc->mSamplingRate = data.readInt32();
-            ioDesc->mFormat = (audio_format_t) data.readInt32();
-            ioDesc->mChannelMask = (audio_channel_mask_t) data.readInt32();
-            ioDesc->mFrameCount = data.readInt64();
-            ioDesc->mFrameCountHAL = data.readInt64();
-            ioDesc->mLatency = data.readInt32();
-            ioConfigChanged(event, ioDesc);
-            return NO_ERROR;
-        } break;
-        default:
-            return BBinder::onTransact(code, data, reply, flags);
-    }
-}
-
-// ----------------------------------------------------------------------------
-
-} // namespace android
diff --git a/media/libmedia/IAudioPolicyService.cpp b/media/libmedia/IAudioPolicyService.cpp
deleted file mode 100644
index 2fb2da6..0000000
--- a/media/libmedia/IAudioPolicyService.cpp
+++ /dev/null
@@ -1,1376 +0,0 @@
-/*
-**
-** Copyright 2009, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-**     http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
-
-#define LOG_TAG "IAudioPolicyService"
-#include <utils/Log.h>
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <binder/Parcel.h>
-
-#include <media/AudioEffect.h>
-#include <media/IAudioPolicyService.h>
-
-#include <system/audio.h>
-
-namespace android {
-
-enum {
-    SET_DEVICE_CONNECTION_STATE = IBinder::FIRST_CALL_TRANSACTION,
-    GET_DEVICE_CONNECTION_STATE,
-    SET_PHONE_STATE,
-    SET_RINGER_MODE,    // reserved, no longer used
-    SET_FORCE_USE,
-    GET_FORCE_USE,
-    GET_OUTPUT,
-    START_OUTPUT,
-    STOP_OUTPUT,
-    RELEASE_OUTPUT,
-    GET_INPUT_FOR_ATTR,
-    START_INPUT,
-    STOP_INPUT,
-    RELEASE_INPUT,
-    INIT_STREAM_VOLUME,
-    SET_STREAM_VOLUME,
-    GET_STREAM_VOLUME,
-    GET_STRATEGY_FOR_STREAM,
-    GET_OUTPUT_FOR_EFFECT,
-    REGISTER_EFFECT,
-    UNREGISTER_EFFECT,
-    IS_STREAM_ACTIVE,
-    IS_SOURCE_ACTIVE,
-    GET_DEVICES_FOR_STREAM,
-    QUERY_DEFAULT_PRE_PROCESSING,
-    SET_EFFECT_ENABLED,
-    IS_STREAM_ACTIVE_REMOTELY,
-    IS_OFFLOAD_SUPPORTED,
-    LIST_AUDIO_PORTS,
-    GET_AUDIO_PORT,
-    CREATE_AUDIO_PATCH,
-    RELEASE_AUDIO_PATCH,
-    LIST_AUDIO_PATCHES,
-    SET_AUDIO_PORT_CONFIG,
-    REGISTER_CLIENT,
-    GET_OUTPUT_FOR_ATTR,
-    ACQUIRE_SOUNDTRIGGER_SESSION,
-    RELEASE_SOUNDTRIGGER_SESSION,
-    GET_PHONE_STATE,
-    REGISTER_POLICY_MIXES,
-    START_AUDIO_SOURCE,
-    STOP_AUDIO_SOURCE,
-    SET_AUDIO_PORT_CALLBACK_ENABLED,
-    SET_MASTER_MONO,
-    GET_MASTER_MONO,
-};
-
-#define MAX_ITEMS_PER_LIST 1024
-
-class BpAudioPolicyService : public BpInterface<IAudioPolicyService>
-{
-public:
-    explicit BpAudioPolicyService(const sp<IBinder>& impl)
-        : BpInterface<IAudioPolicyService>(impl)
-    {
-    }
-
-    virtual status_t setDeviceConnectionState(
-                                    audio_devices_t device,
-                                    audio_policy_dev_state_t state,
-                                    const char *device_address,
-                                    const char *device_name)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(static_cast <uint32_t>(device));
-        data.writeInt32(static_cast <uint32_t>(state));
-        data.writeCString(device_address);
-        data.writeCString(device_name);
-        remote()->transact(SET_DEVICE_CONNECTION_STATE, data, &reply);
-        return static_cast <status_t> (reply.readInt32());
-    }
-
-    virtual audio_policy_dev_state_t getDeviceConnectionState(
-                                    audio_devices_t device,
-                                    const char *device_address)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(static_cast <uint32_t>(device));
-        data.writeCString(device_address);
-        remote()->transact(GET_DEVICE_CONNECTION_STATE, data, &reply);
-        return static_cast <audio_policy_dev_state_t>(reply.readInt32());
-    }
-
-    virtual status_t setPhoneState(audio_mode_t state)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(state);
-        remote()->transact(SET_PHONE_STATE, data, &reply);
-        return static_cast <status_t> (reply.readInt32());
-    }
-
-    virtual status_t setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(static_cast <uint32_t>(usage));
-        data.writeInt32(static_cast <uint32_t>(config));
-        remote()->transact(SET_FORCE_USE, data, &reply);
-        return static_cast <status_t> (reply.readInt32());
-    }
-
-    virtual audio_policy_forced_cfg_t getForceUse(audio_policy_force_use_t usage)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(static_cast <uint32_t>(usage));
-        remote()->transact(GET_FORCE_USE, data, &reply);
-        return static_cast <audio_policy_forced_cfg_t> (reply.readInt32());
-    }
-
-    virtual audio_io_handle_t getOutput(
-                                        audio_stream_type_t stream,
-                                        uint32_t samplingRate,
-                                        audio_format_t format,
-                                        audio_channel_mask_t channelMask,
-                                        audio_output_flags_t flags,
-                                        const audio_offload_info_t *offloadInfo)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(static_cast <uint32_t>(stream));
-        data.writeInt32(samplingRate);
-        data.writeInt32(static_cast <uint32_t>(format));
-        data.writeInt32(channelMask);
-        data.writeInt32(static_cast <uint32_t>(flags));
-        // hasOffloadInfo
-        if (offloadInfo == NULL) {
-            data.writeInt32(0);
-        } else {
-            data.writeInt32(1);
-            data.write(offloadInfo, sizeof(audio_offload_info_t));
-        }
-        remote()->transact(GET_OUTPUT, data, &reply);
-        return static_cast <audio_io_handle_t> (reply.readInt32());
-    }
-
-    virtual status_t getOutputForAttr(const audio_attributes_t *attr,
-                                        audio_io_handle_t *output,
-                                        audio_session_t session,
-                                        audio_stream_type_t *stream,
-                                        uid_t uid,
-                                        uint32_t samplingRate,
-                                        audio_format_t format,
-                                        audio_channel_mask_t channelMask,
-                                        audio_output_flags_t flags,
-                                        audio_port_handle_t selectedDeviceId,
-                                        const audio_offload_info_t *offloadInfo)
-        {
-            Parcel data, reply;
-            data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-            if (attr == NULL) {
-                if (stream == NULL) {
-                    ALOGE("getOutputForAttr(): NULL audio attributes and stream type");
-                    return BAD_VALUE;
-                }
-                if (*stream == AUDIO_STREAM_DEFAULT) {
-                    ALOGE("getOutputForAttr unspecified stream type");
-                    return BAD_VALUE;
-                }
-            }
-            if (output == NULL) {
-                ALOGE("getOutputForAttr NULL output - shouldn't happen");
-                return BAD_VALUE;
-            }
-            if (attr == NULL) {
-                data.writeInt32(0);
-            } else {
-                data.writeInt32(1);
-                data.write(attr, sizeof(audio_attributes_t));
-            }
-            data.writeInt32(session);
-            if (stream == NULL) {
-                data.writeInt32(0);
-            } else {
-                data.writeInt32(1);
-                data.writeInt32(*stream);
-            }
-            data.writeInt32(uid);
-            data.writeInt32(samplingRate);
-            data.writeInt32(static_cast <uint32_t>(format));
-            data.writeInt32(channelMask);
-            data.writeInt32(static_cast <uint32_t>(flags));
-            data.writeInt32(selectedDeviceId);
-            // hasOffloadInfo
-            if (offloadInfo == NULL) {
-                data.writeInt32(0);
-            } else {
-                data.writeInt32(1);
-                data.write(offloadInfo, sizeof(audio_offload_info_t));
-            }
-            status_t status = remote()->transact(GET_OUTPUT_FOR_ATTR, data, &reply);
-            if (status != NO_ERROR) {
-                return status;
-            }
-            status = (status_t)reply.readInt32();
-            if (status != NO_ERROR) {
-                return status;
-            }
-            *output = (audio_io_handle_t)reply.readInt32();
-            if (stream != NULL) {
-                *stream = (audio_stream_type_t)reply.readInt32();
-            }
-            return status;
-        }
-
-    virtual status_t startOutput(audio_io_handle_t output,
-                                 audio_stream_type_t stream,
-                                 audio_session_t session)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(output);
-        data.writeInt32((int32_t) stream);
-        data.writeInt32((int32_t) session);
-        remote()->transact(START_OUTPUT, data, &reply);
-        return static_cast <status_t> (reply.readInt32());
-    }
-
-    virtual status_t stopOutput(audio_io_handle_t output,
-                                audio_stream_type_t stream,
-                                audio_session_t session)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(output);
-        data.writeInt32((int32_t) stream);
-        data.writeInt32((int32_t) session);
-        remote()->transact(STOP_OUTPUT, data, &reply);
-        return static_cast <status_t> (reply.readInt32());
-    }
-
-    virtual void releaseOutput(audio_io_handle_t output,
-                               audio_stream_type_t stream,
-                               audio_session_t session)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(output);
-        data.writeInt32((int32_t)stream);
-        data.writeInt32((int32_t)session);
-        remote()->transact(RELEASE_OUTPUT, data, &reply);
-    }
-
-    virtual status_t getInputForAttr(const audio_attributes_t *attr,
-                                     audio_io_handle_t *input,
-                                     audio_session_t session,
-                                     pid_t pid,
-                                     uid_t uid,
-                                     uint32_t samplingRate,
-                                     audio_format_t format,
-                                     audio_channel_mask_t channelMask,
-                                     audio_input_flags_t flags,
-                                     audio_port_handle_t selectedDeviceId)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        if (attr == NULL) {
-            ALOGE("getInputForAttr NULL attr - shouldn't happen");
-            return BAD_VALUE;
-        }
-        if (input == NULL) {
-            ALOGE("getInputForAttr NULL input - shouldn't happen");
-            return BAD_VALUE;
-        }
-        data.write(attr, sizeof(audio_attributes_t));
-        data.writeInt32(session);
-        data.writeInt32(pid);
-        data.writeInt32(uid);
-        data.writeInt32(samplingRate);
-        data.writeInt32(static_cast <uint32_t>(format));
-        data.writeInt32(channelMask);
-        data.writeInt32(flags);
-        data.writeInt32(selectedDeviceId);
-        status_t status = remote()->transact(GET_INPUT_FOR_ATTR, data, &reply);
-        if (status != NO_ERROR) {
-            return status;
-        }
-        status = reply.readInt32();
-        if (status != NO_ERROR) {
-            return status;
-        }
-        *input = (audio_io_handle_t)reply.readInt32();
-        return NO_ERROR;
-    }
-
-    virtual status_t startInput(audio_io_handle_t input,
-                                audio_session_t session)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(input);
-        data.writeInt32(session);
-        remote()->transact(START_INPUT, data, &reply);
-        return static_cast <status_t> (reply.readInt32());
-    }
-
-    virtual status_t stopInput(audio_io_handle_t input,
-                               audio_session_t session)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(input);
-        data.writeInt32(session);
-        remote()->transact(STOP_INPUT, data, &reply);
-        return static_cast <status_t> (reply.readInt32());
-    }
-
-    virtual void releaseInput(audio_io_handle_t input,
-                              audio_session_t session)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(input);
-        data.writeInt32(session);
-        remote()->transact(RELEASE_INPUT, data, &reply);
-    }
-
-    virtual status_t initStreamVolume(audio_stream_type_t stream,
-                                    int indexMin,
-                                    int indexMax)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(static_cast <uint32_t>(stream));
-        data.writeInt32(indexMin);
-        data.writeInt32(indexMax);
-        remote()->transact(INIT_STREAM_VOLUME, data, &reply);
-        return static_cast <status_t> (reply.readInt32());
-    }
-
-    virtual status_t setStreamVolumeIndex(audio_stream_type_t stream,
-                                          int index,
-                                          audio_devices_t device)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(static_cast <uint32_t>(stream));
-        data.writeInt32(index);
-        data.writeInt32(static_cast <uint32_t>(device));
-        remote()->transact(SET_STREAM_VOLUME, data, &reply);
-        return static_cast <status_t> (reply.readInt32());
-    }
-
-    virtual status_t getStreamVolumeIndex(audio_stream_type_t stream,
-                                          int *index,
-                                          audio_devices_t device)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(static_cast <uint32_t>(stream));
-        data.writeInt32(static_cast <uint32_t>(device));
-
-        remote()->transact(GET_STREAM_VOLUME, data, &reply);
-        int lIndex = reply.readInt32();
-        if (index) *index = lIndex;
-        return static_cast <status_t> (reply.readInt32());
-    }
-
-    virtual uint32_t getStrategyForStream(audio_stream_type_t stream)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(static_cast <uint32_t>(stream));
-        remote()->transact(GET_STRATEGY_FOR_STREAM, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual audio_devices_t getDevicesForStream(audio_stream_type_t stream)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(static_cast <uint32_t>(stream));
-        remote()->transact(GET_DEVICES_FOR_STREAM, data, &reply);
-        return (audio_devices_t) reply.readInt32();
-    }
-
-    virtual audio_io_handle_t getOutputForEffect(const effect_descriptor_t *desc)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.write(desc, sizeof(effect_descriptor_t));
-        remote()->transact(GET_OUTPUT_FOR_EFFECT, data, &reply);
-        return static_cast <audio_io_handle_t> (reply.readInt32());
-    }
-
-    virtual status_t registerEffect(const effect_descriptor_t *desc,
-                                        audio_io_handle_t io,
-                                        uint32_t strategy,
-                                        audio_session_t session,
-                                        int id)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.write(desc, sizeof(effect_descriptor_t));
-        data.writeInt32(io);
-        data.writeInt32(strategy);
-        data.writeInt32(session);
-        data.writeInt32(id);
-        remote()->transact(REGISTER_EFFECT, data, &reply);
-        return static_cast <status_t> (reply.readInt32());
-    }
-
-    virtual status_t unregisterEffect(int id)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(id);
-        remote()->transact(UNREGISTER_EFFECT, data, &reply);
-        return static_cast <status_t> (reply.readInt32());
-    }
-
-    virtual status_t setEffectEnabled(int id, bool enabled)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(id);
-        data.writeInt32(enabled);
-        remote()->transact(SET_EFFECT_ENABLED, data, &reply);
-        return static_cast <status_t> (reply.readInt32());
-    }
-
-    virtual bool isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32((int32_t) stream);
-        data.writeInt32(inPastMs);
-        remote()->transact(IS_STREAM_ACTIVE, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual bool isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32((int32_t) stream);
-        data.writeInt32(inPastMs);
-        remote()->transact(IS_STREAM_ACTIVE_REMOTELY, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual bool isSourceActive(audio_source_t source) const
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32((int32_t) source);
-        remote()->transact(IS_SOURCE_ACTIVE, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual status_t queryDefaultPreProcessing(audio_session_t audioSession,
-                                               effect_descriptor_t *descriptors,
-                                               uint32_t *count)
-    {
-        if (descriptors == NULL || count == NULL) {
-            return BAD_VALUE;
-        }
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(audioSession);
-        data.writeInt32(*count);
-        status_t status = remote()->transact(QUERY_DEFAULT_PRE_PROCESSING, data, &reply);
-        if (status != NO_ERROR) {
-            return status;
-        }
-        status = static_cast <status_t> (reply.readInt32());
-        uint32_t retCount = reply.readInt32();
-        if (retCount != 0) {
-            uint32_t numDesc = (retCount < *count) ? retCount : *count;
-            reply.read(descriptors, sizeof(effect_descriptor_t) * numDesc);
-        }
-        *count = retCount;
-        return status;
-    }
-
-    virtual bool isOffloadSupported(const audio_offload_info_t& info)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.write(&info, sizeof(audio_offload_info_t));
-        remote()->transact(IS_OFFLOAD_SUPPORTED, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual status_t listAudioPorts(audio_port_role_t role,
-                                    audio_port_type_t type,
-                                    unsigned int *num_ports,
-                                    struct audio_port *ports,
-                                    unsigned int *generation)
-    {
-        if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
-                generation == NULL) {
-            return BAD_VALUE;
-        }
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        unsigned int numPortsReq = (ports == NULL) ? 0 : *num_ports;
-        data.writeInt32(role);
-        data.writeInt32(type);
-        data.writeInt32(numPortsReq);
-        status_t status = remote()->transact(LIST_AUDIO_PORTS, data, &reply);
-        if (status == NO_ERROR) {
-            status = (status_t)reply.readInt32();
-            *num_ports = (unsigned int)reply.readInt32();
-        }
-        if (status == NO_ERROR) {
-            if (numPortsReq > *num_ports) {
-                numPortsReq = *num_ports;
-            }
-            if (numPortsReq > 0) {
-                reply.read(ports, numPortsReq * sizeof(struct audio_port));
-            }
-            *generation = reply.readInt32();
-        }
-        return status;
-    }
-
-    virtual status_t getAudioPort(struct audio_port *port)
-    {
-        if (port == NULL) {
-            return BAD_VALUE;
-        }
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.write(port, sizeof(struct audio_port));
-        status_t status = remote()->transact(GET_AUDIO_PORT, data, &reply);
-        if (status != NO_ERROR ||
-                (status = (status_t)reply.readInt32()) != NO_ERROR) {
-            return status;
-        }
-        reply.read(port, sizeof(struct audio_port));
-        return status;
-    }
-
-    virtual status_t createAudioPatch(const struct audio_patch *patch,
-                                       audio_patch_handle_t *handle)
-    {
-        if (patch == NULL || handle == NULL) {
-            return BAD_VALUE;
-        }
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.write(patch, sizeof(struct audio_patch));
-        data.write(handle, sizeof(audio_patch_handle_t));
-        status_t status = remote()->transact(CREATE_AUDIO_PATCH, data, &reply);
-        if (status != NO_ERROR ||
-                (status = (status_t)reply.readInt32()) != NO_ERROR) {
-            return status;
-        }
-        reply.read(handle, sizeof(audio_patch_handle_t));
-        return status;
-    }
-
-    virtual status_t releaseAudioPatch(audio_patch_handle_t handle)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.write(&handle, sizeof(audio_patch_handle_t));
-        status_t status = remote()->transact(RELEASE_AUDIO_PATCH, data, &reply);
-        if (status != NO_ERROR) {
-            status = (status_t)reply.readInt32();
-        }
-        return status;
-    }
-
-    virtual status_t listAudioPatches(unsigned int *num_patches,
-                                      struct audio_patch *patches,
-                                      unsigned int *generation)
-    {
-        if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
-                generation == NULL) {
-            return BAD_VALUE;
-        }
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        unsigned int numPatchesReq = (patches == NULL) ? 0 : *num_patches;
-        data.writeInt32(numPatchesReq);
-        status_t status = remote()->transact(LIST_AUDIO_PATCHES, data, &reply);
-        if (status == NO_ERROR) {
-            status = (status_t)reply.readInt32();
-            *num_patches = (unsigned int)reply.readInt32();
-        }
-        if (status == NO_ERROR) {
-            if (numPatchesReq > *num_patches) {
-                numPatchesReq = *num_patches;
-            }
-            if (numPatchesReq > 0) {
-                reply.read(patches, numPatchesReq * sizeof(struct audio_patch));
-            }
-            *generation = reply.readInt32();
-        }
-        return status;
-    }
-
-    virtual status_t setAudioPortConfig(const struct audio_port_config *config)
-    {
-        if (config == NULL) {
-            return BAD_VALUE;
-        }
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.write(config, sizeof(struct audio_port_config));
-        status_t status = remote()->transact(SET_AUDIO_PORT_CONFIG, data, &reply);
-        if (status != NO_ERROR) {
-            status = (status_t)reply.readInt32();
-        }
-        return status;
-    }
-
-    virtual void registerClient(const sp<IAudioPolicyServiceClient>& client)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeStrongBinder(IInterface::asBinder(client));
-        remote()->transact(REGISTER_CLIENT, data, &reply);
-    }
-
-    virtual void setAudioPortCallbacksEnabled(bool enabled)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(enabled ? 1 : 0);
-        remote()->transact(SET_AUDIO_PORT_CALLBACK_ENABLED, data, &reply);
-    }
-
-    virtual status_t acquireSoundTriggerSession(audio_session_t *session,
-                                            audio_io_handle_t *ioHandle,
-                                            audio_devices_t *device)
-    {
-        if (session == NULL || ioHandle == NULL || device == NULL) {
-            return BAD_VALUE;
-        }
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        status_t status = remote()->transact(ACQUIRE_SOUNDTRIGGER_SESSION, data, &reply);
-        if (status != NO_ERROR) {
-            return status;
-        }
-        status = (status_t)reply.readInt32();
-        if (status == NO_ERROR) {
-            *session = (audio_session_t)reply.readInt32();
-            *ioHandle = (audio_io_handle_t)reply.readInt32();
-            *device = (audio_devices_t)reply.readInt32();
-        }
-        return status;
-    }
-
-    virtual status_t releaseSoundTriggerSession(audio_session_t session)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(session);
-        status_t status = remote()->transact(RELEASE_SOUNDTRIGGER_SESSION, data, &reply);
-        if (status != NO_ERROR) {
-            return status;
-        }
-        return (status_t)reply.readInt32();
-    }
-
-    virtual audio_mode_t getPhoneState()
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        status_t status = remote()->transact(GET_PHONE_STATE, data, &reply);
-        if (status != NO_ERROR) {
-            return AUDIO_MODE_INVALID;
-        }
-        return (audio_mode_t)reply.readInt32();
-    }
-
-    virtual status_t registerPolicyMixes(const Vector<AudioMix>& mixes, bool registration)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(registration ? 1 : 0);
-        size_t size = mixes.size();
-        if (size > MAX_MIXES_PER_POLICY) {
-            size = MAX_MIXES_PER_POLICY;
-        }
-        size_t sizePosition = data.dataPosition();
-        data.writeInt32(size);
-        size_t finalSize = size;
-        for (size_t i = 0; i < size; i++) {
-            size_t position = data.dataPosition();
-            if (mixes[i].writeToParcel(&data) != NO_ERROR) {
-                data.setDataPosition(position);
-                finalSize--;
-            }
-        }
-        if (size != finalSize) {
-            size_t position = data.dataPosition();
-            data.setDataPosition(sizePosition);
-            data.writeInt32(finalSize);
-            data.setDataPosition(position);
-        }
-        status_t status = remote()->transact(REGISTER_POLICY_MIXES, data, &reply);
-        if (status == NO_ERROR) {
-            status = (status_t)reply.readInt32();
-        }
-        return status;
-    }
-
-    virtual status_t startAudioSource(const struct audio_port_config *source,
-                                      const audio_attributes_t *attributes,
-                                      audio_patch_handle_t *handle)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        if (source == NULL || attributes == NULL || handle == NULL) {
-            return BAD_VALUE;
-        }
-        data.write(source, sizeof(struct audio_port_config));
-        data.write(attributes, sizeof(audio_attributes_t));
-        status_t status = remote()->transact(START_AUDIO_SOURCE, data, &reply);
-        if (status != NO_ERROR) {
-            return status;
-        }
-        status = (status_t)reply.readInt32();
-        if (status != NO_ERROR) {
-            return status;
-        }
-        *handle = (audio_patch_handle_t)reply.readInt32();
-        return status;
-    }
-
-    virtual status_t stopAudioSource(audio_patch_handle_t handle)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(handle);
-        status_t status = remote()->transact(STOP_AUDIO_SOURCE, data, &reply);
-        if (status != NO_ERROR) {
-            return status;
-        }
-        status = (status_t)reply.readInt32();
-        return status;
-    }
-
-    virtual status_t setMasterMono(bool mono)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(static_cast<int32_t>(mono));
-        status_t status = remote()->transact(SET_MASTER_MONO, data, &reply);
-        if (status != NO_ERROR) {
-            return status;
-        }
-        return static_cast<status_t>(reply.readInt32());
-    }
-
-    virtual status_t getMasterMono(bool *mono)
-    {
-        if (mono == nullptr) {
-            return BAD_VALUE;
-        }
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-
-        status_t status = remote()->transact(GET_MASTER_MONO, data, &reply);
-        if (status != NO_ERROR) {
-            return status;
-        }
-        status = static_cast<status_t>(reply.readInt32());
-        if (status == NO_ERROR) {
-            *mono = static_cast<bool>(reply.readInt32());
-        }
-        return status;
-    }
-};
-
-IMPLEMENT_META_INTERFACE(AudioPolicyService, "android.media.IAudioPolicyService");
-
-// ----------------------------------------------------------------------
-
-
-status_t BnAudioPolicyService::onTransact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
-    switch (code) {
-        case SET_DEVICE_CONNECTION_STATE: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_devices_t device =
-                    static_cast <audio_devices_t>(data.readInt32());
-            audio_policy_dev_state_t state =
-                    static_cast <audio_policy_dev_state_t>(data.readInt32());
-            const char *device_address = data.readCString();
-            const char *device_name = data.readCString();
-            reply->writeInt32(static_cast<uint32_t> (setDeviceConnectionState(device,
-                                                                              state,
-                                                                              device_address,
-                                                                              device_name)));
-            return NO_ERROR;
-        } break;
-
-        case GET_DEVICE_CONNECTION_STATE: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_devices_t device =
-                    static_cast<audio_devices_t> (data.readInt32());
-            const char *device_address = data.readCString();
-            reply->writeInt32(static_cast<uint32_t> (getDeviceConnectionState(device,
-                                                                              device_address)));
-            return NO_ERROR;
-        } break;
-
-        case SET_PHONE_STATE: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            reply->writeInt32(static_cast <uint32_t>(setPhoneState(
-                    (audio_mode_t) data.readInt32())));
-            return NO_ERROR;
-        } break;
-
-        case SET_FORCE_USE: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_policy_force_use_t usage = static_cast <audio_policy_force_use_t>(
-                    data.readInt32());
-            audio_policy_forced_cfg_t config =
-                    static_cast <audio_policy_forced_cfg_t>(data.readInt32());
-            reply->writeInt32(static_cast <uint32_t>(setForceUse(usage, config)));
-            return NO_ERROR;
-        } break;
-
-        case GET_FORCE_USE: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_policy_force_use_t usage = static_cast <audio_policy_force_use_t>(
-                    data.readInt32());
-            reply->writeInt32(static_cast <uint32_t>(getForceUse(usage)));
-            return NO_ERROR;
-        } break;
-
-        case GET_OUTPUT: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_stream_type_t stream =
-                    static_cast <audio_stream_type_t>(data.readInt32());
-            uint32_t samplingRate = data.readInt32();
-            audio_format_t format = (audio_format_t) data.readInt32();
-            audio_channel_mask_t channelMask = data.readInt32();
-            audio_output_flags_t flags =
-                    static_cast <audio_output_flags_t>(data.readInt32());
-            bool hasOffloadInfo = data.readInt32() != 0;
-            audio_offload_info_t offloadInfo;
-            if (hasOffloadInfo) {
-                data.read(&offloadInfo, sizeof(audio_offload_info_t));
-            }
-            audio_io_handle_t output = getOutput(stream,
-                                                 samplingRate,
-                                                 format,
-                                                 channelMask,
-                                                 flags,
-                                                 hasOffloadInfo ? &offloadInfo : NULL);
-            reply->writeInt32(static_cast <int>(output));
-            return NO_ERROR;
-        } break;
-
-        case GET_OUTPUT_FOR_ATTR: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_attributes_t attr;
-            bool hasAttributes = data.readInt32() != 0;
-            if (hasAttributes) {
-                data.read(&attr, sizeof(audio_attributes_t));
-            }
-            audio_session_t session = (audio_session_t)data.readInt32();
-            audio_stream_type_t stream = AUDIO_STREAM_DEFAULT;
-            bool hasStream = data.readInt32() != 0;
-            if (hasStream) {
-                stream = (audio_stream_type_t)data.readInt32();
-            }
-            uid_t uid = (uid_t)data.readInt32();
-            uint32_t samplingRate = data.readInt32();
-            audio_format_t format = (audio_format_t) data.readInt32();
-            audio_channel_mask_t channelMask = data.readInt32();
-            audio_output_flags_t flags =
-                    static_cast <audio_output_flags_t>(data.readInt32());
-            audio_port_handle_t selectedDeviceId = data.readInt32();
-            bool hasOffloadInfo = data.readInt32() != 0;
-            audio_offload_info_t offloadInfo;
-            if (hasOffloadInfo) {
-                data.read(&offloadInfo, sizeof(audio_offload_info_t));
-            }
-            audio_io_handle_t output = 0;
-            status_t status = getOutputForAttr(hasAttributes ? &attr : NULL,
-                    &output, session, &stream, uid,
-                    samplingRate, format, channelMask,
-                    flags, selectedDeviceId, hasOffloadInfo ? &offloadInfo : NULL);
-            reply->writeInt32(status);
-            reply->writeInt32(output);
-            reply->writeInt32(stream);
-            return NO_ERROR;
-        } break;
-
-        case START_OUTPUT: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_io_handle_t output = static_cast <audio_io_handle_t>(data.readInt32());
-            audio_stream_type_t stream =
-                                static_cast <audio_stream_type_t>(data.readInt32());
-            audio_session_t session = (audio_session_t)data.readInt32();
-            reply->writeInt32(static_cast <uint32_t>(startOutput(output,
-                                                                 stream,
-                                                                 session)));
-            return NO_ERROR;
-        } break;
-
-        case STOP_OUTPUT: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_io_handle_t output = static_cast <audio_io_handle_t>(data.readInt32());
-            audio_stream_type_t stream =
-                                static_cast <audio_stream_type_t>(data.readInt32());
-            audio_session_t session = (audio_session_t)data.readInt32();
-            reply->writeInt32(static_cast <uint32_t>(stopOutput(output,
-                                                                stream,
-                                                                session)));
-            return NO_ERROR;
-        } break;
-
-        case RELEASE_OUTPUT: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_io_handle_t output = static_cast <audio_io_handle_t>(data.readInt32());
-            audio_stream_type_t stream = (audio_stream_type_t)data.readInt32();
-            audio_session_t session = (audio_session_t)data.readInt32();
-            releaseOutput(output, stream, session);
-            return NO_ERROR;
-        } break;
-
-        case GET_INPUT_FOR_ATTR: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_attributes_t attr;
-            data.read(&attr, sizeof(audio_attributes_t));
-            audio_session_t session = (audio_session_t)data.readInt32();
-            pid_t pid = (pid_t)data.readInt32();
-            uid_t uid = (uid_t)data.readInt32();
-            uint32_t samplingRate = data.readInt32();
-            audio_format_t format = (audio_format_t) data.readInt32();
-            audio_channel_mask_t channelMask = data.readInt32();
-            audio_input_flags_t flags = (audio_input_flags_t) data.readInt32();
-            audio_port_handle_t selectedDeviceId = (audio_port_handle_t) data.readInt32();
-            audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
-            status_t status = getInputForAttr(&attr, &input, session, pid, uid,
-                                              samplingRate, format, channelMask,
-                                              flags, selectedDeviceId);
-            reply->writeInt32(status);
-            if (status == NO_ERROR) {
-                reply->writeInt32(input);
-            }
-            return NO_ERROR;
-        } break;
-
-        case START_INPUT: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_io_handle_t input = static_cast <audio_io_handle_t>(data.readInt32());
-            audio_session_t session = static_cast <audio_session_t>(data.readInt32());
-            reply->writeInt32(static_cast <uint32_t>(startInput(input, session)));
-            return NO_ERROR;
-        } break;
-
-        case STOP_INPUT: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_io_handle_t input = static_cast <audio_io_handle_t>(data.readInt32());
-            audio_session_t session = static_cast <audio_session_t>(data.readInt32());
-            reply->writeInt32(static_cast <uint32_t>(stopInput(input, session)));
-            return NO_ERROR;
-        } break;
-
-        case RELEASE_INPUT: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_io_handle_t input = static_cast <audio_io_handle_t>(data.readInt32());
-            audio_session_t session = static_cast <audio_session_t>(data.readInt32());
-            releaseInput(input, session);
-            return NO_ERROR;
-        } break;
-
-        case INIT_STREAM_VOLUME: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_stream_type_t stream =
-                    static_cast <audio_stream_type_t>(data.readInt32());
-            int indexMin = data.readInt32();
-            int indexMax = data.readInt32();
-            reply->writeInt32(static_cast <uint32_t>(initStreamVolume(stream, indexMin,indexMax)));
-            return NO_ERROR;
-        } break;
-
-        case SET_STREAM_VOLUME: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_stream_type_t stream =
-                    static_cast <audio_stream_type_t>(data.readInt32());
-            int index = data.readInt32();
-            audio_devices_t device = static_cast <audio_devices_t>(data.readInt32());
-            reply->writeInt32(static_cast <uint32_t>(setStreamVolumeIndex(stream,
-                                                                          index,
-                                                                          device)));
-            return NO_ERROR;
-        } break;
-
-        case GET_STREAM_VOLUME: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_stream_type_t stream =
-                    static_cast <audio_stream_type_t>(data.readInt32());
-            audio_devices_t device = static_cast <audio_devices_t>(data.readInt32());
-            int index = 0;
-            status_t status = getStreamVolumeIndex(stream, &index, device);
-            reply->writeInt32(index);
-            reply->writeInt32(static_cast <uint32_t>(status));
-            return NO_ERROR;
-        } break;
-
-        case GET_STRATEGY_FOR_STREAM: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_stream_type_t stream =
-                    static_cast <audio_stream_type_t>(data.readInt32());
-            reply->writeInt32(getStrategyForStream(stream));
-            return NO_ERROR;
-        } break;
-
-        case GET_DEVICES_FOR_STREAM: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_stream_type_t stream =
-                    static_cast <audio_stream_type_t>(data.readInt32());
-            reply->writeInt32(static_cast <int>(getDevicesForStream(stream)));
-            return NO_ERROR;
-        } break;
-
-        case GET_OUTPUT_FOR_EFFECT: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            effect_descriptor_t desc;
-            data.read(&desc, sizeof(effect_descriptor_t));
-            audio_io_handle_t output = getOutputForEffect(&desc);
-            reply->writeInt32(static_cast <int>(output));
-            return NO_ERROR;
-        } break;
-
-        case REGISTER_EFFECT: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            effect_descriptor_t desc;
-            data.read(&desc, sizeof(effect_descriptor_t));
-            audio_io_handle_t io = data.readInt32();
-            uint32_t strategy = data.readInt32();
-            audio_session_t session = (audio_session_t) data.readInt32();
-            int id = data.readInt32();
-            reply->writeInt32(static_cast <int32_t>(registerEffect(&desc,
-                                                                   io,
-                                                                   strategy,
-                                                                   session,
-                                                                   id)));
-            return NO_ERROR;
-        } break;
-
-        case UNREGISTER_EFFECT: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            int id = data.readInt32();
-            reply->writeInt32(static_cast <int32_t>(unregisterEffect(id)));
-            return NO_ERROR;
-        } break;
-
-        case SET_EFFECT_ENABLED: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            int id = data.readInt32();
-            bool enabled = static_cast <bool>(data.readInt32());
-            reply->writeInt32(static_cast <int32_t>(setEffectEnabled(id, enabled)));
-            return NO_ERROR;
-        } break;
-
-        case IS_STREAM_ACTIVE: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_stream_type_t stream = (audio_stream_type_t) data.readInt32();
-            uint32_t inPastMs = (uint32_t)data.readInt32();
-            reply->writeInt32( isStreamActive(stream, inPastMs) );
-            return NO_ERROR;
-        } break;
-
-        case IS_STREAM_ACTIVE_REMOTELY: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_stream_type_t stream = (audio_stream_type_t) data.readInt32();
-            uint32_t inPastMs = (uint32_t)data.readInt32();
-            reply->writeInt32( isStreamActiveRemotely(stream, inPastMs) );
-            return NO_ERROR;
-        } break;
-
-        case IS_SOURCE_ACTIVE: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_source_t source = (audio_source_t) data.readInt32();
-            reply->writeInt32( isSourceActive(source));
-            return NO_ERROR;
-        }
-
-        case QUERY_DEFAULT_PRE_PROCESSING: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_session_t audioSession = (audio_session_t) data.readInt32();
-            uint32_t count = data.readInt32();
-            if (count > AudioEffect::kMaxPreProcessing) {
-                count = AudioEffect::kMaxPreProcessing;
-            }
-            uint32_t retCount = count;
-            effect_descriptor_t *descriptors = new effect_descriptor_t[count];
-            status_t status = queryDefaultPreProcessing(audioSession, descriptors, &retCount);
-            reply->writeInt32(status);
-            if (status != NO_ERROR && status != NO_MEMORY) {
-                retCount = 0;
-            }
-            reply->writeInt32(retCount);
-            if (retCount != 0) {
-                if (retCount < count) {
-                    count = retCount;
-                }
-                reply->write(descriptors, sizeof(effect_descriptor_t) * count);
-            }
-            delete[] descriptors;
-            return status;
-        }
-
-        case IS_OFFLOAD_SUPPORTED: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_offload_info_t info;
-            data.read(&info, sizeof(audio_offload_info_t));
-            bool isSupported = isOffloadSupported(info);
-            reply->writeInt32(isSupported);
-            return NO_ERROR;
-        }
-
-        case LIST_AUDIO_PORTS: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_port_role_t role = (audio_port_role_t)data.readInt32();
-            audio_port_type_t type = (audio_port_type_t)data.readInt32();
-            unsigned int numPortsReq = data.readInt32();
-            if (numPortsReq > MAX_ITEMS_PER_LIST) {
-                numPortsReq = MAX_ITEMS_PER_LIST;
-            }
-            unsigned int numPorts = numPortsReq;
-            struct audio_port *ports =
-                    (struct audio_port *)calloc(numPortsReq, sizeof(struct audio_port));
-            if (ports == NULL) {
-                reply->writeInt32(NO_MEMORY);
-                reply->writeInt32(0);
-                return NO_ERROR;
-            }
-            unsigned int generation;
-            status_t status = listAudioPorts(role, type, &numPorts, ports, &generation);
-            reply->writeInt32(status);
-            reply->writeInt32(numPorts);
-
-            if (status == NO_ERROR) {
-                if (numPortsReq > numPorts) {
-                    numPortsReq = numPorts;
-                }
-                reply->write(ports, numPortsReq * sizeof(struct audio_port));
-                reply->writeInt32(generation);
-            }
-            free(ports);
-            return NO_ERROR;
-        }
-
-        case GET_AUDIO_PORT: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            struct audio_port port = {};
-            if (data.read(&port, sizeof(struct audio_port)) != NO_ERROR) {
-                ALOGE("b/23912202");
-            }
-            status_t status = getAudioPort(&port);
-            reply->writeInt32(status);
-            if (status == NO_ERROR) {
-                reply->write(&port, sizeof(struct audio_port));
-            }
-            return NO_ERROR;
-        }
-
-        case CREATE_AUDIO_PATCH: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            struct audio_patch patch;
-            data.read(&patch, sizeof(struct audio_patch));
-            audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
-            if (data.read(&handle, sizeof(audio_patch_handle_t)) != NO_ERROR) {
-                ALOGE("b/23912202");
-            }
-            status_t status = createAudioPatch(&patch, &handle);
-            reply->writeInt32(status);
-            if (status == NO_ERROR) {
-                reply->write(&handle, sizeof(audio_patch_handle_t));
-            }
-            return NO_ERROR;
-        }
-
-        case RELEASE_AUDIO_PATCH: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_patch_handle_t handle;
-            data.read(&handle, sizeof(audio_patch_handle_t));
-            status_t status = releaseAudioPatch(handle);
-            reply->writeInt32(status);
-            return NO_ERROR;
-        }
-
-        case LIST_AUDIO_PATCHES: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            unsigned int numPatchesReq = data.readInt32();
-            if (numPatchesReq > MAX_ITEMS_PER_LIST) {
-                numPatchesReq = MAX_ITEMS_PER_LIST;
-            }
-            unsigned int numPatches = numPatchesReq;
-            struct audio_patch *patches =
-                    (struct audio_patch *)calloc(numPatchesReq,
-                                                 sizeof(struct audio_patch));
-            if (patches == NULL) {
-                reply->writeInt32(NO_MEMORY);
-                reply->writeInt32(0);
-                return NO_ERROR;
-            }
-            unsigned int generation;
-            status_t status = listAudioPatches(&numPatches, patches, &generation);
-            reply->writeInt32(status);
-            reply->writeInt32(numPatches);
-            if (status == NO_ERROR) {
-                if (numPatchesReq > numPatches) {
-                    numPatchesReq = numPatches;
-                }
-                reply->write(patches, numPatchesReq * sizeof(struct audio_patch));
-                reply->writeInt32(generation);
-            }
-            free(patches);
-            return NO_ERROR;
-        }
-
-        case SET_AUDIO_PORT_CONFIG: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            struct audio_port_config config;
-            data.read(&config, sizeof(struct audio_port_config));
-            status_t status = setAudioPortConfig(&config);
-            reply->writeInt32(status);
-            return NO_ERROR;
-        }
-
-        case REGISTER_CLIENT: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            sp<IAudioPolicyServiceClient> client = interface_cast<IAudioPolicyServiceClient>(
-                    data.readStrongBinder());
-            registerClient(client);
-            return NO_ERROR;
-        } break;
-
-        case SET_AUDIO_PORT_CALLBACK_ENABLED: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            setAudioPortCallbacksEnabled(data.readInt32() == 1);
-            return NO_ERROR;
-        } break;
-
-        case ACQUIRE_SOUNDTRIGGER_SESSION: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            sp<IAudioPolicyServiceClient> client = interface_cast<IAudioPolicyServiceClient>(
-                    data.readStrongBinder());
-            audio_session_t session = AUDIO_SESSION_NONE;
-            audio_io_handle_t ioHandle = AUDIO_IO_HANDLE_NONE;
-            audio_devices_t device = AUDIO_DEVICE_NONE;
-            status_t status = acquireSoundTriggerSession(&session, &ioHandle, &device);
-            reply->writeInt32(status);
-            if (status == NO_ERROR) {
-                reply->writeInt32(session);
-                reply->writeInt32(ioHandle);
-                reply->writeInt32(device);
-            }
-            return NO_ERROR;
-        } break;
-
-        case RELEASE_SOUNDTRIGGER_SESSION: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            sp<IAudioPolicyServiceClient> client = interface_cast<IAudioPolicyServiceClient>(
-                    data.readStrongBinder());
-            audio_session_t session = (audio_session_t)data.readInt32();
-            status_t status = releaseSoundTriggerSession(session);
-            reply->writeInt32(status);
-            return NO_ERROR;
-        } break;
-
-        case GET_PHONE_STATE: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            reply->writeInt32((int32_t)getPhoneState());
-            return NO_ERROR;
-        } break;
-
-        case REGISTER_POLICY_MIXES: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            bool registration = data.readInt32() == 1;
-            Vector<AudioMix> mixes;
-            size_t size = (size_t)data.readInt32();
-            if (size > MAX_MIXES_PER_POLICY) {
-                size = MAX_MIXES_PER_POLICY;
-            }
-            for (size_t i = 0; i < size; i++) {
-                AudioMix mix;
-                if (mix.readFromParcel((Parcel*)&data) == NO_ERROR) {
-                    mixes.add(mix);
-                }
-            }
-            status_t status = registerPolicyMixes(mixes, registration);
-            reply->writeInt32(status);
-            return NO_ERROR;
-        } break;
-
-        case START_AUDIO_SOURCE: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            struct audio_port_config source;
-            data.read(&source, sizeof(struct audio_port_config));
-            audio_attributes_t attributes;
-            data.read(&attributes, sizeof(audio_attributes_t));
-            audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
-            status_t status = startAudioSource(&source, &attributes, &handle);
-            reply->writeInt32(status);
-            reply->writeInt32(handle);
-            return NO_ERROR;
-        } break;
-
-        case STOP_AUDIO_SOURCE: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            audio_patch_handle_t handle = (audio_patch_handle_t) data.readInt32();
-            status_t status = stopAudioSource(handle);
-            reply->writeInt32(status);
-            return NO_ERROR;
-        } break;
-
-        case SET_MASTER_MONO: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            bool mono = static_cast<bool>(data.readInt32());
-            status_t status = setMasterMono(mono);
-            reply->writeInt32(status);
-            return NO_ERROR;
-        } break;
-
-        case GET_MASTER_MONO: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            bool mono;
-            status_t status = getMasterMono(&mono);
-            reply->writeInt32(status);
-            if (status == NO_ERROR) {
-                reply->writeInt32(static_cast<int32_t>(mono));
-            }
-            return NO_ERROR;
-        } break;
-
-        default:
-            return BBinder::onTransact(code, data, reply, flags);
-    }
-}
-
-// ----------------------------------------------------------------------------
-
-} // namespace android
diff --git a/media/libmedia/IAudioPolicyServiceClient.cpp b/media/libmedia/IAudioPolicyServiceClient.cpp
deleted file mode 100644
index 98a0521..0000000
--- a/media/libmedia/IAudioPolicyServiceClient.cpp
+++ /dev/null
@@ -1,144 +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.
- */
-
-#define LOG_TAG "IAudioPolicyServiceClient"
-#include <utils/Log.h>
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <binder/Parcel.h>
-
-#include <media/IAudioPolicyServiceClient.h>
-#include <media/AudioSystem.h>
-
-namespace android {
-
-enum {
-    PORT_LIST_UPDATE = IBinder::FIRST_CALL_TRANSACTION,
-    PATCH_LIST_UPDATE,
-    MIX_STATE_UPDATE,
-    RECORDING_CONFIGURATION_UPDATE
-};
-
-// ----------------------------------------------------------------------
-inline void readAudioConfigBaseFromParcel(const Parcel& data, audio_config_base_t *config) {
-    config->sample_rate = data.readUint32();
-    config->channel_mask = (audio_channel_mask_t) data.readInt32();
-    config->format = (audio_format_t) data.readInt32();
-}
-
-inline void writeAudioConfigBaseToParcel(Parcel& data, const audio_config_base_t *config)
-{
-    data.writeUint32(config->sample_rate);
-    data.writeInt32((int32_t) config->channel_mask);
-    data.writeInt32((int32_t) config->format);
-}
-
-// ----------------------------------------------------------------------
-class BpAudioPolicyServiceClient : public BpInterface<IAudioPolicyServiceClient>
-{
-public:
-    explicit BpAudioPolicyServiceClient(const sp<IBinder>& impl)
-        : BpInterface<IAudioPolicyServiceClient>(impl)
-    {
-    }
-
-    void onAudioPortListUpdate()
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyServiceClient::getInterfaceDescriptor());
-        remote()->transact(PORT_LIST_UPDATE, data, &reply, IBinder::FLAG_ONEWAY);
-    }
-
-    void onAudioPatchListUpdate()
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyServiceClient::getInterfaceDescriptor());
-        remote()->transact(PATCH_LIST_UPDATE, data, &reply, IBinder::FLAG_ONEWAY);
-    }
-
-    void onDynamicPolicyMixStateUpdate(String8 regId, int32_t state)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyServiceClient::getInterfaceDescriptor());
-        data.writeString8(regId);
-        data.writeInt32(state);
-        remote()->transact(MIX_STATE_UPDATE, data, &reply, IBinder::FLAG_ONEWAY);
-    }
-
-    void onRecordingConfigurationUpdate(int event, audio_session_t session,
-            audio_source_t source, const audio_config_base_t *clientConfig,
-            const audio_config_base_t *deviceConfig, audio_patch_handle_t patchHandle) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyServiceClient::getInterfaceDescriptor());
-        data.writeInt32(event);
-        data.writeInt32(session);
-        data.writeInt32(source);
-        writeAudioConfigBaseToParcel(data, clientConfig);
-        writeAudioConfigBaseToParcel(data, deviceConfig);
-        data.writeInt32(patchHandle);
-        remote()->transact(RECORDING_CONFIGURATION_UPDATE, data, &reply, IBinder::FLAG_ONEWAY);
-    }
-};
-
-IMPLEMENT_META_INTERFACE(AudioPolicyServiceClient, "android.media.IAudioPolicyServiceClient");
-
-// ----------------------------------------------------------------------
-
-status_t BnAudioPolicyServiceClient::onTransact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
-    switch (code) {
-    case PORT_LIST_UPDATE: {
-            CHECK_INTERFACE(IAudioPolicyServiceClient, data, reply);
-            onAudioPortListUpdate();
-            return NO_ERROR;
-        } break;
-    case PATCH_LIST_UPDATE: {
-            CHECK_INTERFACE(IAudioPolicyServiceClient, data, reply);
-            onAudioPatchListUpdate();
-            return NO_ERROR;
-        } break;
-    case MIX_STATE_UPDATE: {
-            CHECK_INTERFACE(IAudioPolicyServiceClient, data, reply);
-            String8 regId = data.readString8();
-            int32_t state = data.readInt32();
-            onDynamicPolicyMixStateUpdate(regId, state);
-            return NO_ERROR;
-        } break;
-    case RECORDING_CONFIGURATION_UPDATE: {
-            CHECK_INTERFACE(IAudioPolicyServiceClient, data, reply);
-            int event = (int) data.readInt32();
-            audio_session_t session = (audio_session_t) data.readInt32();
-            audio_source_t source = (audio_source_t) data.readInt32();
-            audio_config_base_t clientConfig;
-            audio_config_base_t deviceConfig;
-            readAudioConfigBaseFromParcel(data, &clientConfig);
-            readAudioConfigBaseFromParcel(data, &deviceConfig);
-            audio_patch_handle_t patchHandle = (audio_patch_handle_t) data.readInt32();
-            onRecordingConfigurationUpdate(event, session, source, &clientConfig, &deviceConfig,
-                    patchHandle);
-            return NO_ERROR;
-        } break;
-    default:
-        return BBinder::onTransact(code, data, reply, flags);
-    }
-}
-
-// ----------------------------------------------------------------------------
-
-} // namespace android
diff --git a/media/libmedia/IAudioRecord.cpp b/media/libmedia/IAudioRecord.cpp
deleted file mode 100644
index 1331c0d..0000000
--- a/media/libmedia/IAudioRecord.cpp
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
-**
-** Copyright 2007, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-**     http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
-
-#define LOG_TAG "IAudioRecord"
-//#define LOG_NDEBUG 0
-#include <utils/Log.h>
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <binder/Parcel.h>
-
-#include <media/IAudioRecord.h>
-
-namespace android {
-
-enum {
-    UNUSED_WAS_GET_CBLK = IBinder::FIRST_CALL_TRANSACTION,
-    START,
-    STOP
-};
-
-class BpAudioRecord : public BpInterface<IAudioRecord>
-{
-public:
-    explicit BpAudioRecord(const sp<IBinder>& impl)
-        : BpInterface<IAudioRecord>(impl)
-    {
-    }
-
-    virtual status_t start(int /*AudioSystem::sync_event_t*/ event, audio_session_t triggerSession)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioRecord::getInterfaceDescriptor());
-        data.writeInt32(event);
-        data.writeInt32(triggerSession);
-        status_t status = remote()->transact(START, data, &reply);
-        if (status == NO_ERROR) {
-            status = reply.readInt32();
-        } else {
-            ALOGW("start() error: %s", strerror(-status));
-        }
-        return status;
-    }
-
-    virtual void stop()
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioRecord::getInterfaceDescriptor());
-        remote()->transact(STOP, data, &reply);
-    }
-
-};
-
-IMPLEMENT_META_INTERFACE(AudioRecord, "android.media.IAudioRecord");
-
-// ----------------------------------------------------------------------
-
-status_t BnAudioRecord::onTransact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
-    switch (code) {
-        case START: {
-            CHECK_INTERFACE(IAudioRecord, data, reply);
-            int /*AudioSystem::sync_event_t*/ event = data.readInt32();
-            audio_session_t triggerSession = (audio_session_t) data.readInt32();
-            reply->writeInt32(start(event, triggerSession));
-            return NO_ERROR;
-        } break;
-        case STOP: {
-            CHECK_INTERFACE(IAudioRecord, data, reply);
-            stop();
-            return NO_ERROR;
-        } break;
-        default:
-            return BBinder::onTransact(code, data, reply, flags);
-    }
-}
-
-} // namespace android
diff --git a/media/libmedia/IAudioTrack.cpp b/media/libmedia/IAudioTrack.cpp
deleted file mode 100644
index 89e0fcc..0000000
--- a/media/libmedia/IAudioTrack.cpp
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
-**
-** Copyright 2007, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-**     http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
-
-#define LOG_TAG "IAudioTrack"
-//#define LOG_NDEBUG 0
-#include <utils/Log.h>
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <binder/Parcel.h>
-
-#include <media/IAudioTrack.h>
-
-namespace android {
-
-enum {
-    GET_CBLK = IBinder::FIRST_CALL_TRANSACTION,
-    START,
-    STOP,
-    FLUSH,
-    RESERVED, // was MUTE
-    PAUSE,
-    ATTACH_AUX_EFFECT,
-    SET_PARAMETERS,
-    GET_TIMESTAMP,
-    SIGNAL,
-};
-
-class BpAudioTrack : public BpInterface<IAudioTrack>
-{
-public:
-    explicit BpAudioTrack(const sp<IBinder>& impl)
-        : BpInterface<IAudioTrack>(impl)
-    {
-    }
-
-    virtual sp<IMemory> getCblk() const
-    {
-        Parcel data, reply;
-        sp<IMemory> cblk;
-        data.writeInterfaceToken(IAudioTrack::getInterfaceDescriptor());
-        status_t status = remote()->transact(GET_CBLK, data, &reply);
-        if (status == NO_ERROR) {
-            cblk = interface_cast<IMemory>(reply.readStrongBinder());
-            if (cblk != 0 && cblk->pointer() == NULL) {
-                cblk.clear();
-            }
-        }
-        return cblk;
-    }
-
-    virtual status_t start()
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioTrack::getInterfaceDescriptor());
-        status_t status = remote()->transact(START, data, &reply);
-        if (status == NO_ERROR) {
-            status = reply.readInt32();
-        } else {
-            ALOGW("start() error: %s", strerror(-status));
-        }
-        return status;
-    }
-
-    virtual void stop()
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioTrack::getInterfaceDescriptor());
-        remote()->transact(STOP, data, &reply);
-    }
-
-    virtual void flush()
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioTrack::getInterfaceDescriptor());
-        remote()->transact(FLUSH, data, &reply);
-    }
-
-    virtual void pause()
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioTrack::getInterfaceDescriptor());
-        remote()->transact(PAUSE, data, &reply);
-    }
-
-    virtual status_t attachAuxEffect(int effectId)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioTrack::getInterfaceDescriptor());
-        data.writeInt32(effectId);
-        status_t status = remote()->transact(ATTACH_AUX_EFFECT, data, &reply);
-        if (status == NO_ERROR) {
-            status = reply.readInt32();
-        } else {
-            ALOGW("attachAuxEffect() error: %s", strerror(-status));
-        }
-        return status;
-    }
-
-    virtual status_t setParameters(const String8& keyValuePairs) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioTrack::getInterfaceDescriptor());
-        data.writeString8(keyValuePairs);
-        status_t status = remote()->transact(SET_PARAMETERS, data, &reply);
-        if (status == NO_ERROR) {
-            status = reply.readInt32();
-        }
-        return status;
-    }
-
-    virtual status_t getTimestamp(AudioTimestamp& timestamp) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioTrack::getInterfaceDescriptor());
-        status_t status = remote()->transact(GET_TIMESTAMP, data, &reply);
-        if (status == NO_ERROR) {
-            status = reply.readInt32();
-            if (status == NO_ERROR) {
-                timestamp.mPosition = reply.readInt32();
-                timestamp.mTime.tv_sec = reply.readInt32();
-                timestamp.mTime.tv_nsec = reply.readInt32();
-            }
-        }
-        return status;
-    }
-
-    virtual void signal() {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioTrack::getInterfaceDescriptor());
-        remote()->transact(SIGNAL, data, &reply);
-    }
-};
-
-IMPLEMENT_META_INTERFACE(AudioTrack, "android.media.IAudioTrack");
-
-// ----------------------------------------------------------------------
-
-status_t BnAudioTrack::onTransact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
-    switch (code) {
-        case GET_CBLK: {
-            CHECK_INTERFACE(IAudioTrack, data, reply);
-            reply->writeStrongBinder(IInterface::asBinder(getCblk()));
-            return NO_ERROR;
-        } break;
-        case START: {
-            CHECK_INTERFACE(IAudioTrack, data, reply);
-            reply->writeInt32(start());
-            return NO_ERROR;
-        } break;
-        case STOP: {
-            CHECK_INTERFACE(IAudioTrack, data, reply);
-            stop();
-            return NO_ERROR;
-        } break;
-        case FLUSH: {
-            CHECK_INTERFACE(IAudioTrack, data, reply);
-            flush();
-            return NO_ERROR;
-        } break;
-        case PAUSE: {
-            CHECK_INTERFACE(IAudioTrack, data, reply);
-            pause();
-            return NO_ERROR;
-        }
-        case ATTACH_AUX_EFFECT: {
-            CHECK_INTERFACE(IAudioTrack, data, reply);
-            reply->writeInt32(attachAuxEffect(data.readInt32()));
-            return NO_ERROR;
-        } break;
-        case SET_PARAMETERS: {
-            CHECK_INTERFACE(IAudioTrack, data, reply);
-            String8 keyValuePairs(data.readString8());
-            reply->writeInt32(setParameters(keyValuePairs));
-            return NO_ERROR;
-        } break;
-        case GET_TIMESTAMP: {
-            CHECK_INTERFACE(IAudioTrack, data, reply);
-            AudioTimestamp timestamp;
-            status_t status = getTimestamp(timestamp);
-            reply->writeInt32(status);
-            if (status == NO_ERROR) {
-                reply->writeInt32(timestamp.mPosition);
-                reply->writeInt32(timestamp.mTime.tv_sec);
-                reply->writeInt32(timestamp.mTime.tv_nsec);
-            }
-            return NO_ERROR;
-        } break;
-        case SIGNAL: {
-            CHECK_INTERFACE(IAudioTrack, data, reply);
-            signal();
-            return NO_ERROR;
-        } break;
-        default:
-            return BBinder::onTransact(code, data, reply, flags);
-    }
-}
-
-} // namespace android
diff --git a/media/libmedia/IEffect.cpp b/media/libmedia/IEffect.cpp
deleted file mode 100644
index 115ca75..0000000
--- a/media/libmedia/IEffect.cpp
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
-**
-** Copyright 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 "IEffect"
-#include <utils/Log.h>
-#include <stdint.h>
-#include <sys/types.h>
-#include <binder/Parcel.h>
-#include <media/IEffect.h>
-
-namespace android {
-
-enum {
-    ENABLE = IBinder::FIRST_CALL_TRANSACTION,
-    DISABLE,
-    COMMAND,
-    DISCONNECT,
-    GET_CBLK
-};
-
-class BpEffect: public BpInterface<IEffect>
-{
-public:
-    explicit BpEffect(const sp<IBinder>& impl)
-        : BpInterface<IEffect>(impl)
-    {
-    }
-
-    status_t enable()
-    {
-        ALOGV("enable");
-        Parcel data, reply;
-        data.writeInterfaceToken(IEffect::getInterfaceDescriptor());
-        remote()->transact(ENABLE, data, &reply);
-        return reply.readInt32();
-    }
-
-    status_t disable()
-    {
-        ALOGV("disable");
-        Parcel data, reply;
-        data.writeInterfaceToken(IEffect::getInterfaceDescriptor());
-        remote()->transact(DISABLE, data, &reply);
-        return reply.readInt32();
-    }
-
-    status_t command(uint32_t cmdCode,
-                     uint32_t cmdSize,
-                     void *pCmdData,
-                     uint32_t *pReplySize,
-                     void *pReplyData)
-    {
-        ALOGV("command");
-        Parcel data, reply;
-        data.writeInterfaceToken(IEffect::getInterfaceDescriptor());
-        data.writeInt32(cmdCode);
-        int size = cmdSize;
-        if (pCmdData == NULL) {
-            size = 0;
-        }
-        data.writeInt32(size);
-        if (size) {
-            data.write(pCmdData, size);
-        }
-        if (pReplySize == NULL) {
-            size = 0;
-        } else {
-            size = *pReplySize;
-        }
-        data.writeInt32(size);
-
-        status_t status = remote()->transact(COMMAND, data, &reply);
-        if (status == NO_ERROR) {
-            status = reply.readInt32();
-        }
-        if (status != NO_ERROR) {
-            if (pReplySize != NULL)
-                *pReplySize = 0;
-            return status;
-        }
-
-        size = reply.readInt32();
-        if (size != 0 && pReplyData != NULL && pReplySize != NULL) {
-            reply.read(pReplyData, size);
-            *pReplySize = size;
-        }
-        return status;
-    }
-
-    void disconnect()
-    {
-        ALOGV("disconnect");
-        Parcel data, reply;
-        data.writeInterfaceToken(IEffect::getInterfaceDescriptor());
-        remote()->transact(DISCONNECT, data, &reply);
-        return;
-    }
-
-    virtual sp<IMemory> getCblk() const
-    {
-        Parcel data, reply;
-        sp<IMemory> cblk;
-        data.writeInterfaceToken(IEffect::getInterfaceDescriptor());
-        status_t status = remote()->transact(GET_CBLK, data, &reply);
-        if (status == NO_ERROR) {
-            cblk = interface_cast<IMemory>(reply.readStrongBinder());
-            if (cblk != 0 && cblk->pointer() == NULL) {
-                cblk.clear();
-            }
-        }
-        return cblk;
-    }
- };
-
-IMPLEMENT_META_INTERFACE(Effect, "android.media.IEffect");
-
-// ----------------------------------------------------------------------
-
-status_t BnEffect::onTransact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
-    switch (code) {
-        case ENABLE: {
-            ALOGV("ENABLE");
-            CHECK_INTERFACE(IEffect, data, reply);
-            reply->writeInt32(enable());
-            return NO_ERROR;
-        } break;
-
-        case DISABLE: {
-            ALOGV("DISABLE");
-            CHECK_INTERFACE(IEffect, data, reply);
-            reply->writeInt32(disable());
-            return NO_ERROR;
-        } break;
-
-        case COMMAND: {
-            ALOGV("COMMAND");
-            CHECK_INTERFACE(IEffect, data, reply);
-            uint32_t cmdCode = data.readInt32();
-            uint32_t cmdSize = data.readInt32();
-            char *cmd = NULL;
-            if (cmdSize) {
-                cmd = (char *)calloc(cmdSize, 1);
-                if (cmd == NULL) {
-                    reply->writeInt32(NO_MEMORY);
-                    return NO_ERROR;
-                }
-                data.read(cmd, cmdSize);
-            }
-            uint32_t replySize = data.readInt32();
-            uint32_t replySz = replySize;
-            char *resp = NULL;
-            if (replySize) {
-                resp = (char *)calloc(replySize, 1);
-                if (resp == NULL) {
-                    free(cmd);
-                    reply->writeInt32(NO_MEMORY);
-                    return NO_ERROR;
-                }
-            }
-            status_t status = command(cmdCode, cmdSize, cmd, &replySz, resp);
-            reply->writeInt32(status);
-            if (status == NO_ERROR) {
-                if (replySz < replySize) {
-                    replySize = replySz;
-                }
-                reply->writeInt32(replySize);
-                if (replySize) {
-                    reply->write(resp, replySize);
-                }
-            }
-            if (cmd) {
-                free(cmd);
-            }
-            if (resp) {
-                free(resp);
-            }
-            return NO_ERROR;
-        } break;
-
-        case DISCONNECT: {
-            ALOGV("DISCONNECT");
-            CHECK_INTERFACE(IEffect, data, reply);
-            disconnect();
-            return NO_ERROR;
-        } break;
-
-        case GET_CBLK: {
-            CHECK_INTERFACE(IEffect, data, reply);
-            reply->writeStrongBinder(IInterface::asBinder(getCblk()));
-            return NO_ERROR;
-        } break;
-
-        default:
-            return BBinder::onTransact(code, data, reply, flags);
-    }
-}
-
-// ----------------------------------------------------------------------------
-
-} // namespace android
diff --git a/media/libmedia/IEffectClient.cpp b/media/libmedia/IEffectClient.cpp
deleted file mode 100644
index 3f2c67d..0000000
--- a/media/libmedia/IEffectClient.cpp
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
-**
-** Copyright 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 "IEffectClient"
-#include <utils/Log.h>
-#include <stdint.h>
-#include <sys/types.h>
-#include <media/IEffectClient.h>
-
-namespace android {
-
-enum {
-    CONTROL_STATUS_CHANGED = IBinder::FIRST_CALL_TRANSACTION,
-    ENABLE_STATUS_CHANGED,
-    COMMAND_EXECUTED
-};
-
-class BpEffectClient: public BpInterface<IEffectClient>
-{
-public:
-    explicit BpEffectClient(const sp<IBinder>& impl)
-        : BpInterface<IEffectClient>(impl)
-    {
-    }
-
-    void controlStatusChanged(bool controlGranted)
-    {
-        ALOGV("controlStatusChanged");
-        Parcel data, reply;
-        data.writeInterfaceToken(IEffectClient::getInterfaceDescriptor());
-        data.writeInt32((uint32_t)controlGranted);
-        remote()->transact(CONTROL_STATUS_CHANGED, data, &reply, IBinder::FLAG_ONEWAY);
-    }
-
-    void enableStatusChanged(bool enabled)
-    {
-        ALOGV("enableStatusChanged");
-        Parcel data, reply;
-        data.writeInterfaceToken(IEffectClient::getInterfaceDescriptor());
-        data.writeInt32((uint32_t)enabled);
-        remote()->transact(ENABLE_STATUS_CHANGED, data, &reply, IBinder::FLAG_ONEWAY);
-    }
-
-    void commandExecuted(uint32_t cmdCode,
-                         uint32_t cmdSize,
-                         void *pCmdData,
-                         uint32_t replySize,
-                         void *pReplyData)
-    {
-        ALOGV("commandExecuted");
-        Parcel data, reply;
-        data.writeInterfaceToken(IEffectClient::getInterfaceDescriptor());
-        data.writeInt32(cmdCode);
-        int size = cmdSize;
-        if (pCmdData == NULL) {
-            size = 0;
-        }
-        data.writeInt32(size);
-        if (size) {
-            data.write(pCmdData, size);
-        }
-        size = replySize;
-        if (pReplyData == NULL) {
-            size = 0;
-        }
-        data.writeInt32(size);
-        if (size) {
-            data.write(pReplyData, size);
-        }
-        remote()->transact(COMMAND_EXECUTED, data, &reply, IBinder::FLAG_ONEWAY);
-    }
-
-};
-
-IMPLEMENT_META_INTERFACE(EffectClient, "android.media.IEffectClient");
-
-// ----------------------------------------------------------------------
-
-status_t BnEffectClient::onTransact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
-    switch (code) {
-        case CONTROL_STATUS_CHANGED: {
-            ALOGV("CONTROL_STATUS_CHANGED");
-            CHECK_INTERFACE(IEffectClient, data, reply);
-            bool hasControl = (bool)data.readInt32();
-            controlStatusChanged(hasControl);
-            return NO_ERROR;
-        } break;
-        case ENABLE_STATUS_CHANGED: {
-            ALOGV("ENABLE_STATUS_CHANGED");
-            CHECK_INTERFACE(IEffectClient, data, reply);
-            bool enabled = (bool)data.readInt32();
-            enableStatusChanged(enabled);
-            return NO_ERROR;
-        } break;
-        case COMMAND_EXECUTED: {
-            ALOGV("COMMAND_EXECUTED");
-            CHECK_INTERFACE(IEffectClient, data, reply);
-            uint32_t cmdCode = data.readInt32();
-            uint32_t cmdSize = data.readInt32();
-            char *cmd = NULL;
-            if (cmdSize) {
-                cmd = (char *)malloc(cmdSize);
-                data.read(cmd, cmdSize);
-            }
-            uint32_t replySize = data.readInt32();
-            char *resp = NULL;
-            if (replySize) {
-                resp = (char *)malloc(replySize);
-                data.read(resp, replySize);
-            }
-            commandExecuted(cmdCode, cmdSize, cmd, replySize, resp);
-            if (cmd) {
-                free(cmd);
-            }
-            if (resp) {
-                free(resp);
-            }
-            return NO_ERROR;
-        } break;
-        default:
-            return BBinder::onTransact(code, data, reply, flags);
-    }
-}
-
-// ----------------------------------------------------------------------------
-
-} // namespace android
diff --git a/media/libmedia/MemoryLeakTrackUtil.cpp b/media/libmedia/MemoryLeakTrackUtil.cpp
deleted file mode 100644
index 18f5f25..0000000
--- a/media/libmedia/MemoryLeakTrackUtil.cpp
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * 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.
- */
-
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "MemoryLeackTrackUtil"
-#include <utils/Log.h>
-
-#include "media/MemoryLeakTrackUtil.h"
-#include <sstream>
-
-/*
- * The code here originally resided in MediaPlayerService.cpp
- */
-
-// Figure out the abi based on defined macros.
-#if defined(__arm__)
-#define ABI_STRING "arm"
-#elif defined(__aarch64__)
-#define ABI_STRING "arm64"
-#elif defined(__mips__) && !defined(__LP64__)
-#define ABI_STRING "mips"
-#elif defined(__mips__) && defined(__LP64__)
-#define ABI_STRING "mips64"
-#elif defined(__i386__)
-#define ABI_STRING "x86"
-#elif defined(__x86_64__)
-#define ABI_STRING "x86_64"
-#else
-#error "Unsupported ABI"
-#endif
-
-extern std::string backtrace_string(const uintptr_t* frames, size_t frame_count);
-
-namespace android {
-
-extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
-        size_t* infoSize, size_t* totalMemory, size_t* backtraceSize);
-
-extern "C" void free_malloc_leak_info(uint8_t* info);
-
-std::string dumpMemoryAddresses(size_t limit)
-{
-    uint8_t *info;
-    size_t overallSize;
-    size_t infoSize;
-    size_t totalMemory;
-    size_t backtraceSize;
-    get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory, &backtraceSize);
-
-    size_t count;
-    if (info == nullptr || overallSize == 0 || infoSize == 0
-            || (count = overallSize / infoSize) == 0) {
-        ALOGD("no malloc info, libc.debug.malloc.program property should be set");
-        return std::string();
-    }
-
-    std::ostringstream oss;
-    oss << totalMemory << " bytes in " << count << " allocations\n";
-    oss << "  ABI: '" ABI_STRING "'" << "\n\n";
-    if (count > limit) count = limit;
-
-    // The memory is sorted based on total size which is useful for finding
-    // worst memory offenders. For diffs, sometimes it is preferable to sort
-    // based on the backtrace.
-    for (size_t i = 0; i < count; i++) {
-        struct AllocEntry {
-            size_t size;  // bit 31 is set if this is zygote allocated memory
-            size_t allocations;
-            uintptr_t backtrace[];
-        };
-
-        const AllocEntry * const e = (AllocEntry *)(info + i * infoSize);
-
-        oss << (e->size * e->allocations)
-                << " bytes ( " << e->size << " bytes * " << e->allocations << " allocations )\n";
-        oss << backtrace_string(e->backtrace, backtraceSize) << "\n";
-    }
-    oss << "\n";
-    free_malloc_leak_info(info);
-    return oss.str();
-}
-
-}  // namespace android
diff --git a/media/libmedia/ToneGenerator.cpp b/media/libmedia/ToneGenerator.cpp
deleted file mode 100644
index 7a72237..0000000
--- a/media/libmedia/ToneGenerator.cpp
+++ /dev/null
@@ -1,1656 +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.
- */
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "ToneGenerator"
-
-#include <math.h>
-#include <utils/Log.h>
-#include <cutils/properties.h>
-#include "media/ToneGenerator.h"
-
-
-namespace android {
-
-
-// Descriptors for all available tones (See ToneGenerator::ToneDescriptor class declaration for details)
-const ToneGenerator::ToneDescriptor ToneGenerator::sToneDescriptors[] = {
-        { .segments = { { .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 1336, 941, 0 }, 0, 0},
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_DTMF_0
-        { .segments = { { .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 1209, 697, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_DTMF_1
-        { .segments = { { .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 1336, 697, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_DTMF_2
-        { .segments = { { .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 1477, 697, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_DTMF_3
-        { .segments = { { .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 1209, 770, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_DTMF_4
-        { .segments = { { .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 1336, 770, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_DTMF_5
-        { .segments = { { .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 1477, 770, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_DTMF_6
-        { .segments = { { .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 1209, 852, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_DTMF_7
-        { .segments = { { .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 1336, 852, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_DTMF_8
-        { .segments = { { .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 1477, 852, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_DTMF_9
-        { .segments = { { .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 1209, 941, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_DTMF_S
-        { .segments = { { .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 1477, 941, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_DTMF_P
-        { .segments = { { .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 1633, 697, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_DTMF_A
-        { .segments = { { .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 1633, 770, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                             // TONE_DTMF_B
-        { .segments = { { .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 1633, 852, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_DTMF_C
-        { .segments = { { .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 1633, 941, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_DTMF_D
-        { .segments = { { .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 425, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_SUP_DIAL
-        { .segments = { { .duration = 500 , .waveFreq = { 425, 0 }, 0, 0},
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0},
-                           { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_SUP_BUSY
-        { .segments = { { .duration = 200, .waveFreq = { 425, 0 }, 0, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_SUP_CONGESTION
-        { .segments = { { .duration = 200, .waveFreq = { 425, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                              // TONE_SUP_RADIO_ACK
-        { .segments = { { .duration = 200, .waveFreq = { 425, 0 }, 0, 0},
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0},
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = 2,
-          .repeatSegment = 0 },                              // TONE_SUP_RADIO_NOTAVAIL
-        { .segments = { { .duration = 330, .waveFreq = { 950, 1400, 1800, 0 }, 0, 0},
-                        { .duration = 1000, .waveFreq = { 0 }, 0, 0},
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_SUP_ERROR
-        { .segments = { { .duration = 200, .waveFreq = { 425, 0 }, 0, 0 },
-                        { .duration = 600, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 200, .waveFreq = { 425, 0 }, 0, 0 },
-                        { .duration = 3000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_SUP_CALL_WAITING
-        { .segments = { { .duration = 1000, .waveFreq = { 425, 0 }, 0, 0 },
-                        { .duration = 4000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_SUP_RINGTONE
-        { .segments = { { .duration = 40, .waveFreq = { 400, 1200, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                              // TONE_PROP_BEEP
-        { .segments = { { .duration = 100, .waveFreq = { 1200, 0 }, 0, 0 },
-                        { .duration = 100, .waveFreq = { 0 }, 0, 0  },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = 1,
-          .repeatSegment = 0 },                              // TONE_PROP_ACK
-        { .segments = { { .duration = 400, .waveFreq = { 300, 400, 500, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                              // TONE_PROP_NACK
-        { .segments = { { .duration = 200, .waveFreq = { 400, 1200, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                              // TONE_PROP_PROMPT
-        { .segments = { { .duration = 40, .waveFreq = { 400, 1200, 0 }, 0, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 40, .waveFreq = { 400, 1200, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                             // TONE_PROP_BEEP2
-        { .segments = { { .duration = 250, .waveFreq = { 440, 0 }, 0, 0 },
-                        { .duration = 250, .waveFreq = { 620, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_SUP_INTERCEPT
-        { .segments = { { .duration = 250, .waveFreq = { 440, 0 }, 0, 0 },
-                        { .duration = 250, .waveFreq = { 620, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = 7,
-          .repeatSegment = 0 },                             // TONE_SUP_INTERCEPT_ABBREV
-        { .segments = { { .duration = 250, .waveFreq = { 480, 620, 0 }, 0, 0 },
-                        { .duration = 250, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = 7,
-          .repeatSegment = 0 },                             // TONE_SUP_CONGESTION_ABBREV
-        { .segments = { { .duration = 100, .waveFreq = { 350, 440, 0 }, 0, 0 },
-                        { .duration = 100, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = 2,
-          .repeatSegment = 0 },                             // TONE_SUP_CONFIRM
-        { .segments = { { .duration = 100, .waveFreq = { 480, 0 }, 0, 0 },
-                        { .duration = 100, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = 3,
-          .repeatSegment = 0 },                              // TONE_SUP_PIP
-        { .segments = {{ .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 425, 0 }, 0, 0},
-                       { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_CDMA_DIAL_TONE_LITE
-        { .segments = { { .duration = 2000, .waveFreq = { 440, 480, 0 }, 0, 0 },
-                        { .duration = 4000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_CDMA_NETWORK_USA_RINGBACK
-        { .segments = { { .duration = 250, .waveFreq = { 440, 0 }, 0, 0 },
-                        { .duration = 250, .waveFreq = { 620, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt =  ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                             // TONE_CDMA_INTERCEPT
-        { .segments = { { .duration = 250, .waveFreq = { 440, 0 }, 0, 0 },
-                        { .duration = 250, .waveFreq = { 620, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt =  0,
-          .repeatSegment = 0 },                             // TONE_CDMA_ABBR_INTERCEPT
-        { .segments = { { .duration = 250, .waveFreq = { 480, 620, 0 }, 0, 0 },
-                        { .duration = 250, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_CDMA_REORDER
-        { .segments = { { .duration = 250, .waveFreq = { 480, 620, 0 }, 0, 0 },
-                        { .duration = 250, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = 7,
-          .repeatSegment = 0 },                              // TONE_CDMA_ABBR_REORDER
-        { .segments = { { .duration = 500, .waveFreq = { 480, 620, 0 }, 0, 0 },
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_CDMA_NETWORK_BUSY
-        { .segments = { { .duration = 100, .waveFreq = { 350, 440, 0 }, 0, 0 },
-                        { .duration = 100, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = 2,
-          .repeatSegment = 0 },                              // TONE_CDMA_CONFIRM
-        { .segments = { { .duration = 500, .waveFreq = { 660, 1000, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                              // TONE_CDMA_ANSWER
-        { .segments = { { .duration = 300, .waveFreq = { 440, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                              // TONE_CDMA_NETWORK_CALLWAITING
-        { .segments = { { .duration = 100, .waveFreq = { 480, 0 }, 0, 0 },
-                        { .duration = 100, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = 3,
-          .repeatSegment = 0 },                              // TONE_CDMA_PIP
-
-        { .segments = { { .duration = 32, .waveFreq = { 2091, 0}, 0, 0 },
-                        { .duration = 64, .waveFreq = { 2556, 0}, 19, 0},
-                        { .duration = 32, .waveFreq = { 2091, 0}, 0, 0},
-                        { .duration = 48, .waveFreq = { 2556, 0}, 0, 0},
-                        { .duration = 4000, .waveFreq = { 0 }, 0, 0},
-                        { .duration = 0,  .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                             // TONE_CDMA_CALL_SIGNAL_ISDN_NORMAL
-        { .segments = { { .duration = 32, .waveFreq = { 2091, 0}, 0, 0 },
-                        { .duration = 64, .waveFreq = { 2556, 0}, 7, 0 },
-                        { .duration = 32, .waveFreq = { 2091, 0}, 0, 0 },
-                        { .duration = 400, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 32,  .waveFreq = { 2091, 0}, 0, 0 },
-                        { .duration = 64,  .waveFreq = { 2556, 0}, 7, 4 },
-                        { .duration = 32,  .waveFreq = { 2091, 0}, 0, 0 },
-                        { .duration = 4000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0,    .waveFreq = { 0 }, 0, 0 } },
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                              // TONE_CDMA_CALL_SIGNAL_ISDN_INTERGROUP
-        { .segments = { { .duration = 32, .waveFreq = { 2091, 0}, 0, 0 },
-                        { .duration = 64, .waveFreq = { 2556, 0}, 3, 0 },
-                        { .duration = 16, .waveFreq = { 2091, 0}, 0, 0 },
-                        { .duration = 200, .waveFreq = { 0 },     0, 0 },
-                        { .duration = 32, .waveFreq = { 2091, 0}, 0, 0 },
-                        { .duration = 64, .waveFreq = { 2556, 0}, 3, 4 },
-                        { .duration = 16, .waveFreq = { 2091, 0}, 0, 0 },
-                        { .duration = 200, .waveFreq = { 0 },     0, 0 },
-                        { .duration = 0,   .waveFreq = { 0 },     0, 0 } },
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                            // TONE_CDMA_CALL_SIGNAL_ISDN_SP_PRI
-        { .segments = { { .duration = 0,  .waveFreq = { 0 }, 0, 0} },
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                            // TONE_CDMA_CALL_SIGNAL_ISDN_PAT3
-        { .segments = { { .duration = 32, .waveFreq = { 2091, 0 }, 0, 0 },
-                        { .duration = 64, .waveFreq = { 2556, 0 }, 4, 0 },
-                        { .duration = 20, .waveFreq = { 2091, 0 }, 0, 0 },
-                        { .duration = 0,  .waveFreq = { 0 }      , 0, 0 } },
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                             // TONE_CDMA_CALL_SIGNAL_ISDN_PING_RING
-        { .segments = { { .duration = 0,  .waveFreq = { 0 }, 0, 0} },
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                             // TONE_CDMA_CALL_SIGNAL_ISDN_PAT5
-        { .segments = { { .duration = 0,  .waveFreq = { 0 }, 0, 0} },
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                             // TONE_CDMA_CALL_SIGNAL_ISDN_PAT6
-        { .segments = { { .duration = 0,  .waveFreq = { 0 }, 0, 0} },
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                             // TONE_CDMA_CALL_SIGNAL_ISDN_PAT7
-
-        { .segments = { { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 39, 0 },
-                        { .duration = 4000, .waveFreq = { 0 },     0, 0 },
-                        { .duration = 0,    .waveFreq = { 0 },     0, 0 } },
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_HIGH_L
-        { .segments = { { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 39, 0 },
-                        { .duration = 4000, .waveFreq = { 0 },     0, 0 },
-                        { .duration = 0,    .waveFreq = { 0 },     0, 0 } },
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_MED_L
-        { .segments = { { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 39, 0 },
-                        { .duration = 4000, .waveFreq = { 0 },     0, 0 },
-                        { .duration = 0,    .waveFreq = { 0 },     0, 0 } },
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_LOW_L
-        { .segments = { { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 15, 0 },
-                        { .duration = 400, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 } },
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_HIGH_SS
-        { .segments = { { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 15, 0 },
-                        { .duration = 400, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_MED_SS
-        { .segments = { { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 15, 0 },
-                        { .duration = 400, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_LOW_SS
-        { .segments = { { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 7, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 7, 3 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 15, 6 },
-                        { .duration = 4000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_HIGH_SSL
-        { .segments = { { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 7, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 7, 3 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 15, 6 },
-                        { .duration = 4000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_MED_SSL
-        { .segments = { { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 7, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 7, 3 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 15, 6 },
-                        { .duration = 4000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_LOW_SSL
-        { .segments = { { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                          { .duration = 25, .waveFreq = { 4000, 0 }, 19, 0 },
-                        { .duration = 1000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 19, 3 },
-                        { .duration = 3000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_HIGH_SS_2
-        { .segments = { { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 19, 0 },
-                        { .duration = 1000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 19, 3 },
-                        { .duration = 3000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_MED_SS_2
-        { .segments = { { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 19, 0 },
-                        { .duration = 1000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 19, 3 },
-                        { .duration = 3000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_LOW_SS_2
-        { .segments = { { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 9, 0 },
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 19, 3 },
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 9, 6 },
-                        { .duration = 3000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_HIGH_SLS
-        { .segments = { { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 9, 0 },
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 19, 3 },
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 9, 6 },
-                        { .duration = 3000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_MED_SLS
-        { .segments = { { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 9, 0 },
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 19, 3 },
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 9, 6 },
-                        { .duration = 3000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_LOW_SLS
-        { .segments = { { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 9, 0 },
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 9, 3 },
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 9, 6 },
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 9, 9 },
-                        { .duration = 2500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_HIGH_S_X4
-        { .segments = { { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 9, 0 },
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 9, 3 },
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 9, 6 },
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 9, 9 },
-                        { .duration = 2500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_MED_S_X4
-        { .segments = { { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 9, 0 },
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 9, 3 },
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 9, 6 },
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 9, 9 },
-                        { .duration = 2500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_LOW_S_X4
-        { .segments = { { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 19, 0 },
-                        { .duration = 2000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_HIGH_PBX_L
-        { .segments = { { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 19, 0 },
-                        { .duration = 2000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_MED_PBX_L
-        { .segments = { { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 19, 0 },
-                        { .duration = 2000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_LOW_PBX_L
-        { .segments = { { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 7, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 7, 3 },
-                        { .duration = 2000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_HIGH_PBX_SS
-        { .segments = { { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 7, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 7, 3 },
-                        { .duration = 2000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_MED_PBX_SS
-        { .segments = { { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 7, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 7, 3 },
-                        { .duration = 2000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_LOW_PBX_SS
-        { .segments = { { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 7, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 7, 3 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 15, 6 },
-                        { .duration = 1000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_HIGH_PBX_SSL
-        { .segments = { { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 7, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 7, 3 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 15, 6 },
-                        { .duration = 1000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_MED_PBX_SSL
-        { .segments = { { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 7, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 7, 3 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 15, 6 },
-                        { .duration = 1000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_LOW_PBX_SSL
-        { .segments = { { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 7, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 15, 3 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 7, 6 },
-                        { .duration = 1000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_HIGH_PBX_SLS
-        { .segments = { { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 7, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 15, 3 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 7, 6 },
-                        { .duration = 1000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_MED_PBX_SLS
-        { .segments = { { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 7, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 15, 3 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 7, 6 },
-                        { .duration = 1000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-           .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_LOW_PBX_SLS
-        { .segments = { { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 7, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 7, 3 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 7, 6 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 3700, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 4000, 0 }, 7, 9 },
-                        { .duration = 800, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_HIGH_PBX_S_X4
-        { .segments = { { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 7, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 7, 3 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 7, 6 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2600, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 2900, 0 }, 7, 9 },
-                        { .duration = 800, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_MED_PBX_S_X4
-        { .segments = { { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 7, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 7, 3 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 7, 6 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1300, 0 }, 0, 0 },
-                        { .duration = 25, .waveFreq = { 1450, 0 }, 7, 9 },
-                        { .duration = 800, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                           // TONE_CDMA_LOW_PBX_S_X4
-
-        { .segments = { { .duration = 62, .waveFreq = { 1109, 0 }, 0, 0 },
-                        { .duration = 62, .waveFreq = { 784, 0 },  0, 0 },
-                        { .duration = 62, .waveFreq = { 740, 0 },  0, 0 },
-                        { .duration = 62, .waveFreq = { 622, 0 },  0, 0 },
-                        { .duration = 62, .waveFreq = { 1109, 0 }, 0, 0 },
-                        { .duration = 0,  .waveFreq = { 0 },       0, 0 } },
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                            // TONE_CDMA_ALERT_NETWORK_LITE
-        { .segments = { { .duration = 62, .waveFreq = { 1245, 0 }, 0, 0 },
-                        { .duration = 62, .waveFreq = { 659, 0 },  2, 0 },
-                        { .duration = 62, .waveFreq = { 1245, 0 }, 0, 0 },
-                        { .duration = 0,  .waveFreq = { 0 },       0, 0 } },
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                            // TONE_CDMA_ALERT_AUTOREDIAL_LITE
-        { .segments = { { .duration = 400, .waveFreq = { 1150, 770, 0 }, 0, 0 },
-                        { .duration = 0,   .waveFreq = { 0 },            0, 0 } },
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                            // TONE_CDMA_ONE_MIN_BEEP
-        { .segments = { { .duration = 120, .waveFreq = { 941, 1477, 0 }, 0, 0 },
-                        { .duration = 0,   .waveFreq = { 0 },            0, 0 } },
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                            // TONE_CDMA_KEYPAD_VOLUME_KEY_LITE
-        { .segments = { { .duration = 375, .waveFreq = { 587, 0 }, 0, 0 },
-                        { .duration = 125, .waveFreq = { 1175, 0 }, 0, 0 },
-                        { .duration = 0,   .waveFreq = { 0 },       0, 0 } },
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                            // TONE_CDMA_PRESSHOLDKEY_LITE
-        { .segments = { { .duration = 62, .waveFreq = { 587, 0 }, 0, 0 },
-                        { .duration = 62, .waveFreq = { 784, 0 }, 0, 0 },
-                        { .duration = 62, .waveFreq = { 831, 0 }, 0, 0 },
-                        { .duration = 62, .waveFreq = { 784, 0 }, 0, 0 },
-                        { .duration = 62, .waveFreq = { 1109, 0 }, 0, 0 },
-                        { .duration = 62, .waveFreq = { 784, 0 }, 0, 0 },
-                        { .duration = 62, .waveFreq = { 831, 0 }, 0, 0 },
-                        { .duration = 62, .waveFreq = { 784, 0 }, 0, 0 },
-                        { .duration = 0,  .waveFreq = { 0 },      0, 0 } },
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                             // TONE_CDMA_ALERT_INCALL_LITE
-        { .segments = { { .duration = 125, .waveFreq = { 941, 0 }, 0, 0 },
-                        { .duration = 10,  .waveFreq = { 0 },      2, 0 },
-                        { .duration = 4990, .waveFreq = { 0 },     0, 0 },
-                        { .duration = 0,    .waveFreq = { 0 },     0, 0 } },
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                            // TONE_CDMA_EMERGENCY_RINGBACK
-        { .segments = { { .duration = 125, .waveFreq = { 1319, 0 }, 0, 0 },
-                        { .duration = 125, .waveFreq = { 0 },       0, 0 },
-                        { .duration = 0,   .waveFreq = { 0 },       0, 0 } },
-          .repeatCnt = 2,
-          .repeatSegment = 0 },                            // TONE_CDMA_ALERT_CALL_GUARD
-        { .segments = { { .duration = 125, .waveFreq = { 1047, 0 }, 0, 0 },
-                        { .duration = 125, .waveFreq = { 370,  0 }, 0, 0 },
-                        { .duration = 0,   .waveFreq = { 0 },       0, 0 } },
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                            // TONE_CDMA_SOFT_ERROR_LITE
-        { .segments = { { .duration = 125, .waveFreq = { 1480, 0 }, 0, 0 },
-                        { .duration = 125, .waveFreq = { 1397, 0 }, 0, 0 },
-                        { .duration = 125, .waveFreq = { 784, 0 },  0, 0 },
-                        { .duration = 0,   .waveFreq = { 0 },       0, 0 } },
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                            // TONE_CDMA_CALLDROP_LITE
-
-        { .segments = { { .duration = 500, .waveFreq = { 425, 0 }, 0, 0 },
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                           // TONE_CDMA_NETWORK_BUSY_ONE_SHOT
-        { .segments = { { .duration = 400, .waveFreq = { 1150, 770 }, 0, 0 },
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                           // TONE_CDMA_ABBR_ALERT
-          { .segments = { { .duration = 0, .waveFreq = { 0 }, 0, 0 }},
-          .repeatCnt = 0,
-          .repeatSegment = 0 },                            // TONE_CDMA_SIGNAL_OFF
-
-        { .segments = { { .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 350, 440, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_ANSI_DIAL
-        { .segments = { { .duration = 500, .waveFreq = { 480, 620, 0 }, 0, 0 },
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_ANSI_BUSY
-        { .segments = { { .duration = 250, .waveFreq = { 480, 620, 0 }, 0, 0 },
-                        { .duration = 250, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_ANSI_CONGESTION
-        { .segments = { { .duration = 300, .waveFreq = { 440, 0 }, 0, 0 },
-                        { .duration = 9700, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 100, .waveFreq = { 440, 0 }, 0, 0 },
-                        { .duration = 100, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 100, .waveFreq = { 440, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 1 },                              // TONE_ANSI_CALL_WAITING
-        { .segments = { { .duration = 2000, .waveFreq = { 440, 480, 0 }, 0, 0 },
-                        { .duration = 4000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_ANSI_RINGTONE
-        { .segments = { { .duration = ToneGenerator::TONEGEN_INF, .waveFreq = { 400, 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_JAPAN_DIAL
-        { .segments = { { .duration = 500, .waveFreq = { 400, 0 }, 0, 0 },
-                        { .duration = 500, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_JAPAN_BUSY
-        { .segments = { { .duration = 1000, .waveFreq = { 400, 0 }, 0, 0 },
-                        { .duration = 2000, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_JAPAN_RADIO_ACK
-        { .segments = { { .duration = 400, .waveFreq = { 400, 450, 0 }, 0, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 400, .waveFreq = { 400, 450, 0 }, 0, 0 },
-                        { .duration = 2000, .waveFreq = { 0 }, 0, 0},
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_GB_RINGTONE
-        { .segments = { { .duration = 400, .waveFreq = { 400, 450, 0 }, 0, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 400, .waveFreq = { 400, 450, 0 }, 0, 0 },
-                        { .duration = 2000, .waveFreq = { 0 }, 0, 0},
-                        { .duration = 0, .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_AUSTRALIA_RINGTONE
-        { .segments = { { .duration = 375, .waveFreq = { 425, 0 }, 0, 0 },
-                        { .duration = 375, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_AUSTRALIA_BUSY
-        { .segments = { { .duration = 200, .waveFreq = { 425, 0 }, 0, 0 },
-                        { .duration = 200, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 200, .waveFreq = { 425, 0 }, 0, 0 },
-                        { .duration = 4400, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_AUSTRALIA_CALL_WAITING
-        { .segments = { { .duration = 375, .waveFreq = { 425, 0 }, 0, 0 },
-                        { .duration = 375, .waveFreq = { 0 }, 0, 0 },
-                        { .duration = 0 , .waveFreq = { 0 }, 0, 0}},
-          .repeatCnt = ToneGenerator::TONEGEN_INF,
-          .repeatSegment = 0 },                              // TONE_AUSTRALIA_CONGESTION
-};
-
-// Used by ToneGenerator::getToneForRegion() to convert user specified supervisory tone type
-// to actual tone for current region.
-const unsigned char /*tone_type*/ ToneGenerator::sToneMappingTable[NUM_REGIONS-1][NUM_SUP_TONES] = {
-        {   // ANSI
-            TONE_ANSI_DIAL,             // TONE_SUP_DIAL
-            TONE_ANSI_BUSY,             // TONE_SUP_BUSY
-            TONE_ANSI_CONGESTION,       // TONE_SUP_CONGESTION
-            TONE_SUP_RADIO_ACK,         // TONE_SUP_RADIO_ACK
-            TONE_SUP_RADIO_NOTAVAIL,    // TONE_SUP_RADIO_NOTAVAIL
-            TONE_SUP_ERROR,             // TONE_SUP_ERROR
-            TONE_ANSI_CALL_WAITING,     // TONE_SUP_CALL_WAITING
-            TONE_ANSI_RINGTONE          // TONE_SUP_RINGTONE
-        },
-        {   // JAPAN
-            TONE_JAPAN_DIAL,             // TONE_SUP_DIAL
-            TONE_JAPAN_BUSY,             // TONE_SUP_BUSY
-            TONE_SUP_CONGESTION,         // TONE_SUP_CONGESTION
-            TONE_JAPAN_RADIO_ACK,        // TONE_SUP_RADIO_ACK
-            TONE_SUP_RADIO_NOTAVAIL,     // TONE_SUP_RADIO_NOTAVAIL
-            TONE_SUP_ERROR,              // TONE_SUP_ERROR
-            TONE_SUP_CALL_WAITING,       // TONE_SUP_CALL_WAITING
-            TONE_SUP_RINGTONE            // TONE_SUP_RINGTONE
-        },
-        {   // GB
-            TONE_SUP_DIAL,               // TONE_SUP_DIAL
-            TONE_SUP_BUSY,               // TONE_SUP_BUSY
-            TONE_SUP_CONGESTION,         // TONE_SUP_CONGESTION
-            TONE_SUP_RADIO_ACK,          // TONE_SUP_RADIO_ACK
-            TONE_SUP_RADIO_NOTAVAIL,     // TONE_SUP_RADIO_NOTAVAIL
-            TONE_SUP_ERROR,              // TONE_SUP_ERROR
-            TONE_SUP_CALL_WAITING,       // TONE_SUP_CALL_WAITING
-            TONE_GB_RINGTONE             // TONE_SUP_RINGTONE
-        },
-        {   // AUSTRALIA
-            TONE_ANSI_DIAL,             // TONE_SUP_DIAL
-            TONE_AUSTRALIA_BUSY,        // TONE_SUP_BUSY
-            TONE_AUSTRALIA_CONGESTION,  // TONE_SUP_CONGESTION
-            TONE_SUP_RADIO_ACK,         // TONE_SUP_RADIO_ACK
-            TONE_SUP_RADIO_NOTAVAIL,    // TONE_SUP_RADIO_NOTAVAIL
-            TONE_SUP_ERROR,             // TONE_SUP_ERROR
-            TONE_AUSTRALIA_CALL_WAITING,// TONE_SUP_CALL_WAITING
-            TONE_AUSTRALIA_RINGTONE     // TONE_SUP_RINGTONE
-        }
-};
-
-
-////////////////////////////////////////////////////////////////////////////////
-//                           ToneGenerator class Implementation
-////////////////////////////////////////////////////////////////////////////////
-
-
-//---------------------------------- public methods ----------------------------
-
-
-////////////////////////////////////////////////////////////////////////////////
-//
-//    Method:        ToneGenerator::ToneGenerator()
-//
-//    Description:    Constructor. Initializes the tone sequencer, intantiates required sine wave
-//        generators, instantiates output audio track.
-//
-//    Input:
-//        streamType:        Type of stream used for tone playback
-//        volume:            volume applied to tone (0.0 to 1.0)
-//
-//    Output:
-//        none
-//
-////////////////////////////////////////////////////////////////////////////////
-ToneGenerator::ToneGenerator(audio_stream_type_t streamType, float volume, bool threadCanCallJava) {
-
-    ALOGV("ToneGenerator constructor: streamType=%d, volume=%f", streamType, volume);
-
-    mState = TONE_IDLE;
-
-    if (AudioSystem::getOutputSamplingRate(&mSamplingRate, streamType) != NO_ERROR) {
-        ALOGE("Unable to marshal AudioFlinger");
-        return;
-    }
-    mThreadCanCallJava = threadCanCallJava;
-    mStreamType = streamType;
-    mVolume = volume;
-    mpToneDesc = NULL;
-    mpNewToneDesc = NULL;
-    // Generate tone by chunks of 20 ms to keep cadencing precision
-    mProcessSize = (mSamplingRate * 20) / 1000;
-
-    char value[PROPERTY_VALUE_MAX];
-    if (property_get("gsm.operator.iso-country", value, "") == 0) {
-        property_get("gsm.sim.operator.iso-country", value, "");
-    }
-    if (strstr(value, "us") != NULL ||
-        strstr(value, "ca") != NULL) {
-        mRegion = ANSI;
-    } else if (strstr(value, "jp") != NULL) {
-        mRegion = JAPAN;
-    } else if (strstr(value, "gb") != NULL) {
-        mRegion = GB;
-    } else if (strstr(value, "au") != NULL) {
-        mRegion = AUSTRALIA;
-    } else {
-        mRegion = CEPT;
-    }
-
-    if (initAudioTrack()) {
-        ALOGV("ToneGenerator INIT OK, time: %d", (unsigned int)(systemTime()/1000000));
-    } else {
-        ALOGV("!!!ToneGenerator INIT FAILED!!!");
-    }
-}
-
-
-
-
-////////////////////////////////////////////////////////////////////////////////
-//
-//    Method:        ToneGenerator::~ToneGenerator()
-//
-//    Description:    Destructor. Stop sound playback and delete audio track if
-//      needed and delete sine wave generators.
-//
-//    Input:
-//        none
-//
-//    Output:
-//        none
-//
-////////////////////////////////////////////////////////////////////////////////
-ToneGenerator::~ToneGenerator() {
-    ALOGV("ToneGenerator destructor");
-
-    if (mpAudioTrack != 0) {
-        stopTone();
-        ALOGV("Delete Track: %p", mpAudioTrack.get());
-        mpAudioTrack.clear();
-    }
-    clearWaveGens();
-}
-
-////////////////////////////////////////////////////////////////////////////////
-//
-//    Method:        ToneGenerator::startTone()
-//
-//    Description:    Starts tone playback.
-//
-//    Input:
-//        toneType:        Type of tone generated (values in enum tone_type)
-//        durationMs:      The tone duration in milliseconds. If the tone is limited in time by definition,
-//              the actual duration will be the minimum of durationMs and the defined tone duration.
-//              Ommiting or setting durationMs to -1 does not limit tone duration.
-//
-//    Output:
-//        none
-//
-////////////////////////////////////////////////////////////////////////////////
-bool ToneGenerator::startTone(tone_type toneType, int durationMs) {
-    bool lResult = false;
-    status_t lStatus;
-
-    if ((toneType < 0) || (toneType >= NUM_TONES))
-        return lResult;
-
-    toneType = getToneForRegion(toneType);
-    if (toneType == TONE_CDMA_SIGNAL_OFF) {
-        return true;
-    }
-
-    if (mState == TONE_IDLE) {
-        ALOGV("startTone: try to re-init AudioTrack");
-        if (!initAudioTrack()) {
-            return lResult;
-        }
-    }
-
-    ALOGV("startTone");
-
-    mLock.lock();
-
-    // Get descriptor for requested tone
-    mpNewToneDesc = &sToneDescriptors[toneType];
-
-    mDurationMs = durationMs;
-
-    if (mState == TONE_STOPPED) {
-        ALOGV("Start waiting for previous tone to stop");
-        lStatus = mWaitCbkCond.waitRelative(mLock, seconds(3));
-        if (lStatus != NO_ERROR) {
-            ALOGE("--- start wait for stop timed out, status %d", lStatus);
-            mState = TONE_IDLE;
-            mLock.unlock();
-            return lResult;
-        }
-    }
-
-    if (mState == TONE_INIT) {
-        if (prepareWave()) {
-            ALOGV("Immediate start, time %d", (unsigned int)(systemTime()/1000000));
-            lResult = true;
-            mState = TONE_STARTING;
-            if (clock_gettime(CLOCK_MONOTONIC, &mStartTime) != 0) {
-                mStartTime.tv_sec = 0;
-            }
-            mLock.unlock();
-            mpAudioTrack->start();
-            mLock.lock();
-            if (mState == TONE_STARTING) {
-                ALOGV("Wait for start callback");
-                lStatus = mWaitCbkCond.waitRelative(mLock, seconds(3));
-                if (lStatus != NO_ERROR) {
-                    ALOGE("--- Immediate start timed out, status %d", lStatus);
-                    mState = TONE_IDLE;
-                    lResult = false;
-                }
-            }
-        } else {
-            mState = TONE_IDLE;
-        }
-    } else {
-        ALOGV("Delayed start");
-        mState = TONE_RESTARTING;
-        mStartTime.tv_sec = 0;
-        lStatus = mWaitCbkCond.waitRelative(mLock, seconds(3));
-        if (lStatus == NO_ERROR) {
-            if (mState != TONE_IDLE) {
-                lResult = true;
-            }
-            ALOGV("cond received");
-        } else {
-            ALOGE("--- Delayed start timed out, status %d", lStatus);
-            mState = TONE_IDLE;
-        }
-    }
-    mLock.unlock();
-
-    ALOGV_IF(lResult, "Tone started, time %d", (unsigned int)(systemTime()/1000000));
-    ALOGW_IF(!lResult, "Tone start failed!!!, time %d", (unsigned int)(systemTime()/1000000));
-
-    return lResult;
-}
-
-////////////////////////////////////////////////////////////////////////////////
-//
-//    Method:        ToneGenerator::stopTone()
-//
-//    Description:    Stops tone playback.
-//
-//    Input:
-//        none
-//
-//    Output:
-//        none
-//
-////////////////////////////////////////////////////////////////////////////////
-void ToneGenerator::stopTone() {
-    ALOGV("stopTone");
-
-    mLock.lock();
-    if (mState != TONE_IDLE && mState != TONE_INIT) {
-        if (mState == TONE_PLAYING || mState == TONE_STARTING || mState == TONE_RESTARTING) {
-            struct timespec stopTime;
-            // If the start time is valid, make sure that the number of audio samples produced
-            // corresponds at least to the time between the start and stop commands.
-            // This is needed in case of cold start of the output stream.
-            if ((mStartTime.tv_sec != 0) && (clock_gettime(CLOCK_MONOTONIC, &stopTime) == 0)) {
-                time_t sec = stopTime.tv_sec - mStartTime.tv_sec;
-                long nsec = stopTime.tv_nsec - mStartTime.tv_nsec;
-                if (nsec < 0) {
-                    --sec;
-                    nsec += 1000000000;
-                }
-
-                if ((sec + 1) > ((long)(INT_MAX / mSamplingRate))) {
-                    mMaxSmp = sec * mSamplingRate;
-                } else {
-                    // mSamplingRate is always > 1000
-                    sec = sec * 1000 + nsec / 1000000; // duration in milliseconds
-                    mMaxSmp = (unsigned int)(((int64_t)sec * mSamplingRate) / 1000);
-                }
-                ALOGV("stopTone() forcing mMaxSmp to %d, total for far %d", mMaxSmp,  mTotalSmp);
-            } else {
-                mState = TONE_STOPPING;
-            }
-        }
-        ALOGV("waiting cond");
-        status_t lStatus = mWaitCbkCond.waitRelative(mLock, seconds(3));
-        if (lStatus == NO_ERROR) {
-            // If the tone was restarted exit now before calling clearWaveGens();
-            if (mState != TONE_INIT) {
-                mLock.unlock();
-                return;
-            }
-            ALOGV("track stop complete, time %d", (unsigned int)(systemTime()/1000000));
-        } else {
-            ALOGE("--- Stop timed out");
-            mState = TONE_IDLE;
-            mpAudioTrack->stop();
-        }
-        clearWaveGens();
-    }
-
-    mLock.unlock();
-}
-
-//---------------------------------- private methods ---------------------------
-
-
-
-
-////////////////////////////////////////////////////////////////////////////////
-//
-//    Method:        ToneGenerator::initAudioTrack()
-//
-//    Description:    Allocates and configures AudioTrack used for PCM output.
-//
-//    Input:
-//        none
-//
-//    Output:
-//        none
-//
-////////////////////////////////////////////////////////////////////////////////
-bool ToneGenerator::initAudioTrack() {
-    // Open audio track in mono, PCM 16bit, default sampling rate.
-    mpAudioTrack = new AudioTrack();
-    ALOGV("AudioTrack(%p) created", mpAudioTrack.get());
-
-    const size_t frameCount = mProcessSize;
-    status_t status = mpAudioTrack->set(
-            mStreamType,
-            0,    // sampleRate
-            AUDIO_FORMAT_PCM_16_BIT,
-            AUDIO_CHANNEL_OUT_MONO,
-            frameCount,
-            AUDIO_OUTPUT_FLAG_FAST,
-            audioCallback,
-            this, // user
-            0,    // notificationFrames
-            0,    // sharedBuffer
-            mThreadCanCallJava,
-            AUDIO_SESSION_ALLOCATE,
-            AudioTrack::TRANSFER_CALLBACK);
-
-    if (status != NO_ERROR) {
-        ALOGE("AudioTrack(%p) set failed with error %d", mpAudioTrack.get(), status);
-        mpAudioTrack.clear();
-        return false;
-    }
-
-    mpAudioTrack->setVolume(mVolume);
-    mState = TONE_INIT;
-    return true;
-}
-
-////////////////////////////////////////////////////////////////////////////////
-//
-//    Method:        ToneGenerator::audioCallback()
-//
-//    Description:    AudioTrack callback implementation. Generates a block of
-//        PCM samples
-//        and manages tone generator sequencer: tones pulses, tone duration...
-//
-//    Input:
-//        user    reference (pointer to our ToneGenerator)
-//        info    audio buffer descriptor
-//
-//    Output:
-//        returned value: always true.
-//
-////////////////////////////////////////////////////////////////////////////////
-void ToneGenerator::audioCallback(int event, void* user, void *info) {
-
-    if (event != AudioTrack::EVENT_MORE_DATA) return;
-
-    AudioTrack::Buffer *buffer = static_cast<AudioTrack::Buffer *>(info);
-    ToneGenerator *lpToneGen = static_cast<ToneGenerator *>(user);
-    short *lpOut = buffer->i16;
-    unsigned int lNumSmp = buffer->size/sizeof(short);
-    const ToneDescriptor *lpToneDesc = lpToneGen->mpToneDesc;
-
-    if (buffer->size == 0) return;
-
-
-    // Clear output buffer: WaveGenerator accumulates into lpOut buffer
-    memset(lpOut, 0, buffer->size);
-
-    while (lNumSmp) {
-        unsigned int lReqSmp = lNumSmp < lpToneGen->mProcessSize*2 ? lNumSmp : lpToneGen->mProcessSize;
-        unsigned int lGenSmp;
-        unsigned int lWaveCmd = WaveGenerator::WAVEGEN_CONT;
-        bool lSignal = false;
-
-        lpToneGen->mLock.lock();
-
-
-        // Update pcm frame count and end time (current time at the end of this process)
-        lpToneGen->mTotalSmp += lReqSmp;
-
-        // Update tone gen state machine and select wave gen command
-        switch (lpToneGen->mState) {
-        case TONE_PLAYING:
-            lWaveCmd = WaveGenerator::WAVEGEN_CONT;
-            break;
-        case TONE_STARTING:
-            ALOGV("Starting Cbk");
-
-            lWaveCmd = WaveGenerator::WAVEGEN_START;
-            break;
-        case TONE_STOPPING:
-        case TONE_RESTARTING:
-            ALOGV("Stop/restart Cbk");
-
-            lWaveCmd = WaveGenerator::WAVEGEN_STOP;
-            lpToneGen->mNextSegSmp = TONEGEN_INF; // forced to skip state machine management below
-            break;
-        case TONE_STOPPED:
-            ALOGV("Stopped Cbk");
-            goto audioCallback_EndLoop;
-        default:
-            ALOGV("Extra Cbk");
-            goto audioCallback_EndLoop;
-        }
-
-        // Exit if tone sequence is over
-        if (lpToneDesc->segments[lpToneGen->mCurSegment].duration == 0 ||
-            lpToneGen->mTotalSmp > lpToneGen->mMaxSmp) {
-            if (lpToneGen->mState == TONE_PLAYING) {
-                lpToneGen->mState = TONE_STOPPING;
-            }
-            if (lpToneDesc->segments[lpToneGen->mCurSegment].duration == 0) {
-                goto audioCallback_EndLoop;
-            }
-            // fade out before stopping if maximum duration reached
-            lWaveCmd = WaveGenerator::WAVEGEN_STOP;
-            lpToneGen->mNextSegSmp = TONEGEN_INF; // forced to skip state machine management below
-        }
-
-        if (lpToneGen->mTotalSmp > lpToneGen->mNextSegSmp) {
-            // Time to go to next sequence segment
-
-            ALOGV("End Segment, time: %d", (unsigned int)(systemTime()/1000000));
-
-            lGenSmp = lReqSmp;
-
-            // If segment,  ON -> OFF transition : ramp volume down
-            if (lpToneDesc->segments[lpToneGen->mCurSegment].waveFreq[0] != 0) {
-                lWaveCmd = WaveGenerator::WAVEGEN_STOP;
-                unsigned int lFreqIdx = 0;
-                unsigned short lFrequency = lpToneDesc->segments[lpToneGen->mCurSegment].waveFreq[lFreqIdx];
-
-                while (lFrequency != 0) {
-                    WaveGenerator *lpWaveGen = lpToneGen->mWaveGens.valueFor(lFrequency);
-                    lpWaveGen->getSamples(lpOut, lGenSmp, lWaveCmd);
-                    lFrequency = lpToneDesc->segments[lpToneGen->mCurSegment].waveFreq[++lFreqIdx];
-                }
-                ALOGV("ON->OFF, lGenSmp: %d, lReqSmp: %d", lGenSmp, lReqSmp);
-            }
-
-            // check if we need to loop and loop for the reqd times
-            if (lpToneDesc->segments[lpToneGen->mCurSegment].loopCnt) {
-                if (lpToneGen->mLoopCounter < lpToneDesc->segments[lpToneGen->mCurSegment].loopCnt) {
-                    ALOGV ("in if loop loopCnt(%d) loopctr(%d), CurSeg(%d)",
-                          lpToneDesc->segments[lpToneGen->mCurSegment].loopCnt,
-                          lpToneGen->mLoopCounter,
-                          lpToneGen->mCurSegment);
-                    lpToneGen->mCurSegment = lpToneDesc->segments[lpToneGen->mCurSegment].loopIndx;
-                    ++lpToneGen->mLoopCounter;
-                } else {
-                    // completed loop. go to next segment
-                    lpToneGen->mLoopCounter = 0;
-                    lpToneGen->mCurSegment++;
-                    ALOGV ("in else loop loopCnt(%d) loopctr(%d), CurSeg(%d)",
-                          lpToneDesc->segments[lpToneGen->mCurSegment].loopCnt,
-                          lpToneGen->mLoopCounter,
-                          lpToneGen->mCurSegment);
-                }
-            } else {
-                lpToneGen->mCurSegment++;
-                ALOGV ("Goto next seg loopCnt(%d) loopctr(%d), CurSeg(%d)",
-                      lpToneDesc->segments[lpToneGen->mCurSegment].loopCnt,
-                      lpToneGen->mLoopCounter,
-                      lpToneGen->mCurSegment);
-
-            }
-
-            // Handle loop if last segment reached
-            if (lpToneDesc->segments[lpToneGen->mCurSegment].duration == 0) {
-                ALOGV("Last Seg: %d", lpToneGen->mCurSegment);
-
-                // Pre increment loop count and restart if total count not reached. Stop sequence otherwise
-                if (++lpToneGen->mCurCount <= lpToneDesc->repeatCnt) {
-                    ALOGV("Repeating Count: %d", lpToneGen->mCurCount);
-
-                    lpToneGen->mCurSegment = lpToneDesc->repeatSegment;
-                    if (lpToneDesc->segments[lpToneDesc->repeatSegment].waveFreq[0] != 0) {
-                        lWaveCmd = WaveGenerator::WAVEGEN_START;
-                    }
-
-                    ALOGV("New segment %d, Next Time: %d", lpToneGen->mCurSegment,
-                            (lpToneGen->mNextSegSmp*1000)/lpToneGen->mSamplingRate);
-
-                } else {
-                    lGenSmp = 0;
-                    ALOGV("End repeat, time: %d", (unsigned int)(systemTime()/1000000));
-                }
-            } else {
-                ALOGV("New segment %d, Next Time: %d", lpToneGen->mCurSegment,
-                        (lpToneGen->mNextSegSmp*1000)/lpToneGen->mSamplingRate);
-                if (lpToneDesc->segments[lpToneGen->mCurSegment].waveFreq[0] != 0) {
-                    // If next segment is not silent,  OFF -> ON transition : reset wave generator
-                    lWaveCmd = WaveGenerator::WAVEGEN_START;
-
-                    ALOGV("OFF->ON, lGenSmp: %d, lReqSmp: %d", lGenSmp, lReqSmp);
-                } else {
-                    lGenSmp = 0;
-                }
-            }
-
-            // Update next segment transition position. No harm to do it also for last segment as lpToneGen->mNextSegSmp won't be used any more
-            lpToneGen->mNextSegSmp
-                    += (lpToneDesc->segments[lpToneGen->mCurSegment].duration * lpToneGen->mSamplingRate) / 1000;
-
-        } else {
-            // Inside a segment keep tone ON or OFF
-            if (lpToneDesc->segments[lpToneGen->mCurSegment].waveFreq[0] == 0) {
-                lGenSmp = 0;  // If odd segment, tone is currently OFF
-            } else {
-                lGenSmp = lReqSmp;  // If event segment, tone is currently ON
-            }
-        }
-
-        if (lGenSmp) {
-            // If samples must be generated, call all active wave generators and acumulate waves in lpOut
-            unsigned int lFreqIdx = 0;
-            unsigned short lFrequency = lpToneDesc->segments[lpToneGen->mCurSegment].waveFreq[lFreqIdx];
-
-            while (lFrequency != 0) {
-                WaveGenerator *lpWaveGen = lpToneGen->mWaveGens.valueFor(lFrequency);
-                lpWaveGen->getSamples(lpOut, lGenSmp, lWaveCmd);
-                lFrequency = lpToneDesc->segments[lpToneGen->mCurSegment].waveFreq[++lFreqIdx];
-            }
-        }
-
-        lNumSmp -= lReqSmp;
-        lpOut += lReqSmp;
-
-audioCallback_EndLoop:
-
-        switch (lpToneGen->mState) {
-        case TONE_RESTARTING:
-            ALOGV("Cbk restarting track");
-            if (lpToneGen->prepareWave()) {
-                lpToneGen->mState = TONE_STARTING;
-                if (clock_gettime(CLOCK_MONOTONIC, &lpToneGen->mStartTime) != 0) {
-                    lpToneGen->mStartTime.tv_sec = 0;
-                }
-                // must reload lpToneDesc as prepareWave() may change mpToneDesc
-                lpToneDesc = lpToneGen->mpToneDesc;
-            } else {
-                ALOGW("Cbk restarting prepareWave() failed");
-                lpToneGen->mState = TONE_IDLE;
-                lpToneGen->mpAudioTrack->stop();
-                // Force loop exit
-                lNumSmp = 0;
-            }
-            lSignal = true;
-            break;
-        case TONE_STOPPING:
-            ALOGV("Cbk Stopping");
-            lpToneGen->mState = TONE_STOPPED;
-            // Force loop exit
-            lNumSmp = 0;
-            break;
-        case TONE_STOPPED:
-            lpToneGen->mState = TONE_INIT;
-            ALOGV("Cbk Stopped track");
-            lpToneGen->mpAudioTrack->stop();
-            // Force loop exit
-            lNumSmp = 0;
-            buffer->size = 0;
-            lSignal = true;
-            break;
-        case TONE_STARTING:
-            ALOGV("Cbk starting track");
-            lpToneGen->mState = TONE_PLAYING;
-            lSignal = true;
-            break;
-        case TONE_PLAYING:
-            break;
-        default:
-            // Force loop exit
-            lNumSmp = 0;
-            buffer->size = 0;
-            break;
-        }
-
-        if (lSignal)
-            lpToneGen->mWaitCbkCond.broadcast();
-        lpToneGen->mLock.unlock();
-    }
-}
-
-
-////////////////////////////////////////////////////////////////////////////////
-//
-//    Method:        ToneGenerator::prepareWave()
-//
-//    Description:    Prepare wave generators and reset tone sequencer state machine.
-//      mpNewToneDesc must have been initialized before calling this function.
-//    Input:
-//        none
-//
-//    Output:
-//        returned value:   true if wave generators have been created, false otherwise
-//
-////////////////////////////////////////////////////////////////////////////////
-bool ToneGenerator::prepareWave() {
-    unsigned int segmentIdx = 0;
-
-    if (mpNewToneDesc == NULL) {
-        return false;
-    }
-
-    // Remove existing wave generators if any
-    clearWaveGens();
-
-    mpToneDesc = mpNewToneDesc;
-
-    if (mDurationMs == -1) {
-        mMaxSmp = TONEGEN_INF;
-    } else {
-        if (mDurationMs > (int)(TONEGEN_INF / mSamplingRate)) {
-            mMaxSmp = (mDurationMs / 1000) * mSamplingRate;
-        } else {
-            mMaxSmp = (mDurationMs * mSamplingRate) / 1000;
-        }
-        ALOGV("prepareWave, duration limited to %d ms", mDurationMs);
-    }
-
-    while (mpToneDesc->segments[segmentIdx].duration) {
-        // Get total number of sine waves: needed to adapt sine wave gain.
-        unsigned int lNumWaves = numWaves(segmentIdx);
-        unsigned int freqIdx = 0;
-        unsigned int frequency = mpToneDesc->segments[segmentIdx].waveFreq[freqIdx];
-        while (frequency) {
-            // Instantiate a wave generator if  ot already done for this frequency
-            if (mWaveGens.indexOfKey(frequency) == NAME_NOT_FOUND) {
-                ToneGenerator::WaveGenerator *lpWaveGen =
-                        new ToneGenerator::WaveGenerator((unsigned short)mSamplingRate,
-                                frequency,
-                                TONEGEN_GAIN/lNumWaves);
-                mWaveGens.add(frequency, lpWaveGen);
-            }
-            frequency = mpNewToneDesc->segments[segmentIdx].waveFreq[++freqIdx];
-        }
-        segmentIdx++;
-    }
-
-    // Initialize tone sequencer
-    mTotalSmp = 0;
-    mCurSegment = 0;
-    mCurCount = 0;
-    mLoopCounter = 0;
-    if (mpToneDesc->segments[0].duration == TONEGEN_INF) {
-        mNextSegSmp = TONEGEN_INF;
-    } else{
-        mNextSegSmp = (mpToneDesc->segments[0].duration * mSamplingRate) / 1000;
-    }
-
-    return true;
-}
-
-
-////////////////////////////////////////////////////////////////////////////////
-//
-//    Method:        ToneGenerator::numWaves()
-//
-//    Description:    Count number of sine waves needed to generate a tone segment (e.g 2 for DTMF).
-//
-//    Input:
-//        segmentIdx        tone segment index
-//
-//    Output:
-//        returned value:    nummber of sine waves
-//
-////////////////////////////////////////////////////////////////////////////////
-unsigned int ToneGenerator::numWaves(unsigned int segmentIdx) {
-    unsigned int lCnt = 0;
-
-    if (mpToneDesc->segments[segmentIdx].duration) {
-        while (mpToneDesc->segments[segmentIdx].waveFreq[lCnt]) {
-            lCnt++;
-        }
-        lCnt++;
-    }
-
-    return lCnt;
-}
-
-
-////////////////////////////////////////////////////////////////////////////////
-//
-//    Method:        ToneGenerator::clearWaveGens()
-//
-//    Description:    Removes all wave generators.
-//
-//    Input:
-//        none
-//
-//    Output:
-//        none
-//
-////////////////////////////////////////////////////////////////////////////////
-void ToneGenerator::clearWaveGens() {
-    ALOGV("Clearing mWaveGens:");
-
-    for (size_t lIdx = 0; lIdx < mWaveGens.size(); lIdx++) {
-        delete mWaveGens.valueAt(lIdx);
-    }
-    mWaveGens.clear();
-}
-
-////////////////////////////////////////////////////////////////////////////////
-//
-//    Method:       ToneGenerator::getToneForRegion()
-//
-//    Description:  Get correct ringtone type according to current region.
-//      The corrected ring tone type is the tone descriptor index in sToneDescriptors[].
-//
-//    Input:
-//        none
-//
-//    Output:
-//        none
-//
-////////////////////////////////////////////////////////////////////////////////
-ToneGenerator::tone_type ToneGenerator::getToneForRegion(tone_type toneType) {
-    tone_type regionTone;
-
-    if (mRegion == CEPT || toneType < FIRST_SUP_TONE || toneType > LAST_SUP_TONE) {
-        regionTone = toneType;
-    } else {
-        regionTone = (tone_type) sToneMappingTable[mRegion][toneType - FIRST_SUP_TONE];
-    }
-
-    ALOGV("getToneForRegion, tone %d, region %d, regionTone %d", toneType, mRegion, regionTone);
-
-    return regionTone;
-}
-
-
-////////////////////////////////////////////////////////////////////////////////
-//                WaveGenerator::WaveGenerator class    Implementation
-////////////////////////////////////////////////////////////////////////////////
-
-//---------------------------------- public methods ----------------------------
-
-////////////////////////////////////////////////////////////////////////////////
-//
-//    Method:        WaveGenerator::WaveGenerator()
-//
-//    Description:    Constructor.
-//
-//    Input:
-//        samplingRate:    Output sampling rate in Hz
-//        frequency:       Frequency of the sine wave to generate in Hz
-//        volume:          volume (0.0 to 1.0)
-//
-//    Output:
-//        none
-//
-////////////////////////////////////////////////////////////////////////////////
-ToneGenerator::WaveGenerator::WaveGenerator(unsigned short samplingRate,
-        unsigned short frequency, float volume) {
-    double d0;
-    double F_div_Fs;  // frequency / samplingRate
-
-    F_div_Fs = frequency / (double)samplingRate;
-    d0 = - (float)GEN_AMP * sin(2 * M_PI * F_div_Fs);
-    mS2_0 = (short)d0;
-    mS1 = 0;
-    mS2 = mS2_0;
-
-    mAmplitude_Q15 = (short)(32767. * 32767. * volume / GEN_AMP);
-    // take some margin for amplitude fluctuation
-    if (mAmplitude_Q15 > 32500)
-        mAmplitude_Q15 = 32500;
-
-    d0 = 32768.0 * cos(2 * M_PI * F_div_Fs);  // Q14*2*cos()
-    if (d0 > 32767)
-        d0 = 32767;
-    mA1_Q14 = (short) d0;
-
-    ALOGV("WaveGenerator init, mA1_Q14: %d, mS2_0: %d, mAmplitude_Q15: %d",
-            mA1_Q14, mS2_0, mAmplitude_Q15);
-}
-
-////////////////////////////////////////////////////////////////////////////////
-//
-//    Method:        WaveGenerator::~WaveGenerator()
-//
-//    Description:    Destructor.
-//
-//    Input:
-//        none
-//
-//    Output:
-//        none
-//
-////////////////////////////////////////////////////////////////////////////////
-ToneGenerator::WaveGenerator::~WaveGenerator() {
-}
-
-////////////////////////////////////////////////////////////////////////////////
-//
-//    Method:        WaveGenerator::getSamples()
-//
-//    Description:    Generates count samples of a sine wave and accumulates
-//        result in outBuffer.
-//
-//    Input:
-//        outBuffer:      Output buffer where to accumulate samples.
-//        count:          number of samples to produce.
-//        command:        special action requested (see enum gen_command).
-//
-//    Output:
-//        none
-//
-////////////////////////////////////////////////////////////////////////////////
-void ToneGenerator::WaveGenerator::getSamples(short *outBuffer,
-        unsigned int count, unsigned int command) {
-    long lS1, lS2;
-    long lA1, lAmplitude;
-    long Sample;  // current sample
-
-    // init local
-    if (command == WAVEGEN_START) {
-        lS1 = (long)0;
-        lS2 = (long)mS2_0;
-    } else {
-        lS1 = mS1;
-        lS2 = mS2;
-    }
-    lA1 = (long)mA1_Q14;
-    lAmplitude = (long)mAmplitude_Q15;
-
-    if (command == WAVEGEN_STOP) {
-        lAmplitude <<= 16;
-        if (count == 0) {
-            return;
-        }
-        long dec = lAmplitude/count;
-        // loop generation
-        while (count) {
-            count--;
-            Sample = ((lA1 * lS1) >> S_Q14) - lS2;
-            // shift delay
-            lS2 = lS1;
-            lS1 = Sample;
-            Sample = ((lAmplitude>>16) * Sample) >> S_Q15;
-            *(outBuffer++) += (short)Sample;  // put result in buffer
-            lAmplitude -= dec;
-        }
-    } else {
-        // loop generation
-        while (count) {
-            count--;
-            Sample = ((lA1 * lS1) >> S_Q14) - lS2;
-            // shift delay
-            lS2 = lS1;
-            lS1 = Sample;
-            Sample = (lAmplitude * Sample) >> S_Q15;
-            *(outBuffer++) += (short)Sample;  // put result in buffer
-        }
-    }
-
-    // save status
-    mS1 = lS1;
-    mS2 = lS2;
-}
-
-}  // end namespace android