Home | History | Annotate | Download | only in audioflinger
      1 /*
      2 **
      3 ** Copyright 2007, The Android Open Source Project
      4 **
      5 ** Licensed under the Apache License, Version 2.0 (the "License");
      6 ** you may not use this file except in compliance with the License.
      7 ** You may obtain a copy of the License at
      8 **
      9 **     http://www.apache.org/licenses/LICENSE-2.0
     10 **
     11 ** Unless required by applicable law or agreed to in writing, software
     12 ** distributed under the License is distributed on an "AS IS" BASIS,
     13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14 ** See the License for the specific language governing permissions and
     15 ** limitations under the License.
     16 */
     17 
     18 
     19 #define LOG_TAG "AudioFlinger"
     20 //#define LOG_NDEBUG 0
     21 
     22 #include "Configuration.h"
     23 #include <dirent.h>
     24 #include <math.h>
     25 #include <signal.h>
     26 #include <string>
     27 #include <sys/time.h>
     28 #include <sys/resource.h>
     29 
     30 #include <android/os/IExternalVibratorService.h>
     31 #include <binder/IPCThreadState.h>
     32 #include <binder/IServiceManager.h>
     33 #include <utils/Log.h>
     34 #include <utils/Trace.h>
     35 #include <binder/Parcel.h>
     36 #include <media/audiohal/DeviceHalInterface.h>
     37 #include <media/audiohal/DevicesFactoryHalInterface.h>
     38 #include <media/audiohal/EffectsFactoryHalInterface.h>
     39 #include <media/AudioParameter.h>
     40 #include <media/TypeConverter.h>
     41 #include <memunreachable/memunreachable.h>
     42 #include <utils/String16.h>
     43 #include <utils/threads.h>
     44 
     45 #include <cutils/atomic.h>
     46 #include <cutils/properties.h>
     47 
     48 #include <system/audio.h>
     49 #include <audiomanager/AudioManager.h>
     50 
     51 #include "AudioFlinger.h"
     52 #include "NBAIO_Tee.h"
     53 
     54 #include <media/AudioResamplerPublic.h>
     55 
     56 #include <system/audio_effects/effect_visualizer.h>
     57 #include <system/audio_effects/effect_ns.h>
     58 #include <system/audio_effects/effect_aec.h>
     59 
     60 #include <audio_utils/primitives.h>
     61 
     62 #include <powermanager/PowerManager.h>
     63 
     64 #include <media/IMediaLogService.h>
     65 #include <media/MemoryLeakTrackUtil.h>
     66 #include <media/nbaio/Pipe.h>
     67 #include <media/nbaio/PipeReader.h>
     68 #include <mediautils/BatteryNotifier.h>
     69 #include <mediautils/ServiceUtilities.h>
     70 #include <private/android_filesystem_config.h>
     71 
     72 //#define BUFLOG_NDEBUG 0
     73 #include <BufLog.h>
     74 
     75 #include "TypedLogger.h"
     76 
     77 // ----------------------------------------------------------------------------
     78 
     79 // Note: the following macro is used for extremely verbose logging message.  In
     80 // order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
     81 // 0; but one side effect of this is to turn all LOGV's as well.  Some messages
     82 // are so verbose that we want to suppress them even when we have ALOG_ASSERT
     83 // turned on.  Do not uncomment the #def below unless you really know what you
     84 // are doing and want to see all of the extremely verbose messages.
     85 //#define VERY_VERY_VERBOSE_LOGGING
     86 #ifdef VERY_VERY_VERBOSE_LOGGING
     87 #define ALOGVV ALOGV
     88 #else
     89 #define ALOGVV(a...) do { } while(0)
     90 #endif
     91 
     92 namespace android {
     93 
     94 static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
     95 static const char kHardwareLockedString[] = "Hardware lock is taken\n";
     96 static const char kClientLockedString[] = "Client lock is taken\n";
     97 static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
     98 
     99 
    100 nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
    101 
    102 uint32_t AudioFlinger::mScreenState;
    103 
    104 // In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
    105 // we define a minimum time during which a global effect is considered enabled.
    106 static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
    107 
    108 Mutex gLock;
    109 wp<AudioFlinger> gAudioFlinger;
    110 
    111 // Keep a strong reference to media.log service around forever.
    112 // The service is within our parent process so it can never die in a way that we could observe.
    113 // These two variables are const after initialization.
    114 static sp<IBinder> sMediaLogServiceAsBinder;
    115 static sp<IMediaLogService> sMediaLogService;
    116 
    117 static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
    118 
    119 static void sMediaLogInit()
    120 {
    121     sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
    122     if (sMediaLogServiceAsBinder != 0) {
    123         sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
    124     }
    125 }
    126 
    127 // Keep a strong reference to external vibrator service
    128 static sp<os::IExternalVibratorService> sExternalVibratorService;
    129 
    130 static sp<os::IExternalVibratorService> getExternalVibratorService() {
    131     if (sExternalVibratorService == 0) {
    132         sp <IBinder> binder = defaultServiceManager()->getService(
    133             String16("external_vibrator_service"));
    134         if (binder != 0) {
    135             sExternalVibratorService =
    136                 interface_cast<os::IExternalVibratorService>(binder);
    137         }
    138     }
    139     return sExternalVibratorService;
    140 }
    141 
    142 // ----------------------------------------------------------------------------
    143 
    144 std::string formatToString(audio_format_t format) {
    145     std::string result;
    146     FormatConverter::toString(format, result);
    147     return result;
    148 }
    149 
    150 // ----------------------------------------------------------------------------
    151 
    152 AudioFlinger::AudioFlinger()
    153     : BnAudioFlinger(),
    154       mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
    155       mPrimaryHardwareDev(NULL),
    156       mAudioHwDevs(NULL),
    157       mHardwareStatus(AUDIO_HW_IDLE),
    158       mMasterVolume(1.0f),
    159       mMasterMute(false),
    160       // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
    161       mMode(AUDIO_MODE_INVALID),
    162       mBtNrecIsOff(false),
    163       mIsLowRamDevice(true),
    164       mIsDeviceTypeKnown(false),
    165       mTotalMemory(0),
    166       mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
    167       mGlobalEffectEnableTime(0),
    168       mPatchPanel(this),
    169       mSystemReady(false)
    170 {
    171     // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
    172     for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
    173         // zero ID has a special meaning, so unavailable
    174         mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
    175     }
    176 
    177     const bool doLog = property_get_bool("ro.test_harness", false);
    178     if (doLog) {
    179         mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
    180                 MemoryHeapBase::READ_ONLY);
    181         (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
    182     }
    183 
    184     // reset battery stats.
    185     // if the audio service has crashed, battery stats could be left
    186     // in bad state, reset the state upon service start.
    187     BatteryNotifier::getInstance().noteResetAudio();
    188 
    189     mDevicesFactoryHal = DevicesFactoryHalInterface::create();
    190     mEffectsFactoryHal = EffectsFactoryHalInterface::create();
    191 
    192     mMediaLogNotifier->run("MediaLogNotifier");
    193 }
    194 
    195 void AudioFlinger::onFirstRef()
    196 {
    197     Mutex::Autolock _l(mLock);
    198 
    199     /* TODO: move all this work into an Init() function */
    200     char val_str[PROPERTY_VALUE_MAX] = { 0 };
    201     if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
    202         uint32_t int_val;
    203         if (1 == sscanf(val_str, "%u", &int_val)) {
    204             mStandbyTimeInNsecs = milliseconds(int_val);
    205             ALOGI("Using %u mSec as standby time.", int_val);
    206         } else {
    207             mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
    208             ALOGI("Using default %u mSec as standby time.",
    209                     (uint32_t)(mStandbyTimeInNsecs / 1000000));
    210         }
    211     }
    212 
    213     mMode = AUDIO_MODE_NORMAL;
    214 
    215     gAudioFlinger = this;
    216 }
    217 
    218 AudioFlinger::~AudioFlinger()
    219 {
    220     while (!mRecordThreads.isEmpty()) {
    221         // closeInput_nonvirtual() will remove specified entry from mRecordThreads
    222         closeInput_nonvirtual(mRecordThreads.keyAt(0));
    223     }
    224     while (!mPlaybackThreads.isEmpty()) {
    225         // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
    226         closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
    227     }
    228     while (!mMmapThreads.isEmpty()) {
    229         const audio_io_handle_t io = mMmapThreads.keyAt(0);
    230         if (mMmapThreads.valueAt(0)->isOutput()) {
    231             closeOutput_nonvirtual(io); // removes entry from mMmapThreads
    232         } else {
    233             closeInput_nonvirtual(io);  // removes entry from mMmapThreads
    234         }
    235     }
    236 
    237     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
    238         // no mHardwareLock needed, as there are no other references to this
    239         delete mAudioHwDevs.valueAt(i);
    240     }
    241 
    242     // Tell media.log service about any old writers that still need to be unregistered
    243     if (sMediaLogService != 0) {
    244         for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
    245             sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
    246             mUnregisteredWriters.pop();
    247             sMediaLogService->unregisterWriter(iMemory);
    248         }
    249     }
    250 }
    251 
    252 //static
    253 __attribute__ ((visibility ("default")))
    254 status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
    255                                              const audio_attributes_t *attr,
    256                                              audio_config_base_t *config,
    257                                              const AudioClient& client,
    258                                              audio_port_handle_t *deviceId,
    259                                              audio_session_t *sessionId,
    260                                              const sp<MmapStreamCallback>& callback,
    261                                              sp<MmapStreamInterface>& interface,
    262                                              audio_port_handle_t *handle)
    263 {
    264     sp<AudioFlinger> af;
    265     {
    266         Mutex::Autolock _l(gLock);
    267         af = gAudioFlinger.promote();
    268     }
    269     status_t ret = NO_INIT;
    270     if (af != 0) {
    271         ret = af->openMmapStream(
    272                 direction, attr, config, client, deviceId,
    273                 sessionId, callback, interface, handle);
    274     }
    275     return ret;
    276 }
    277 
    278 status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
    279                                       const audio_attributes_t *attr,
    280                                       audio_config_base_t *config,
    281                                       const AudioClient& client,
    282                                       audio_port_handle_t *deviceId,
    283                                       audio_session_t *sessionId,
    284                                       const sp<MmapStreamCallback>& callback,
    285                                       sp<MmapStreamInterface>& interface,
    286                                       audio_port_handle_t *handle)
    287 {
    288     status_t ret = initCheck();
    289     if (ret != NO_ERROR) {
    290         return ret;
    291     }
    292     audio_session_t actualSessionId = *sessionId;
    293     if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
    294         actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
    295     }
    296     audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
    297     audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
    298     audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
    299     audio_attributes_t localAttr = *attr;
    300     if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
    301         audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
    302         fullConfig.sample_rate = config->sample_rate;
    303         fullConfig.channel_mask = config->channel_mask;
    304         fullConfig.format = config->format;
    305         std::vector<audio_io_handle_t> secondaryOutputs;
    306 
    307         ret = AudioSystem::getOutputForAttr(&localAttr, &io,
    308                                             actualSessionId,
    309                                             &streamType, client.clientPid, client.clientUid,
    310                                             &fullConfig,
    311                                             (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
    312                                                     AUDIO_OUTPUT_FLAG_DIRECT),
    313                                             deviceId, &portId, &secondaryOutputs);
    314         ALOGW_IF(!secondaryOutputs.empty(),
    315                  "%s does not support secondary outputs, ignoring them", __func__);
    316     } else {
    317         ret = AudioSystem::getInputForAttr(&localAttr, &io,
    318                                               RECORD_RIID_INVALID,
    319                                               actualSessionId,
    320                                               client.clientPid,
    321                                               client.clientUid,
    322                                               client.packageName,
    323                                               config,
    324                                               AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
    325     }
    326     if (ret != NO_ERROR) {
    327         return ret;
    328     }
    329 
    330     // at this stage, a MmapThread was created when openOutput() or openInput() was called by
    331     // audio policy manager and we can retrieve it
    332     sp<MmapThread> thread = mMmapThreads.valueFor(io);
    333     if (thread != 0) {
    334         interface = new MmapThreadHandle(thread);
    335         thread->configure(&localAttr, streamType, actualSessionId, callback, *deviceId, portId);
    336         *handle = portId;
    337         *sessionId = actualSessionId;
    338     } else {
    339         if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
    340             AudioSystem::releaseOutput(portId);
    341         } else {
    342             AudioSystem::releaseInput(portId);
    343         }
    344         ret = NO_INIT;
    345     }
    346 
    347     ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
    348 
    349     return ret;
    350 }
    351 
    352 /* static */
    353 int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
    354     sp<os::IExternalVibratorService> evs = getExternalVibratorService();
    355     if (evs != 0) {
    356         int32_t ret;
    357         binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
    358         if (status.isOk()) {
    359             return ret;
    360         }
    361     }
    362     return AudioMixer::HAPTIC_SCALE_MUTE;
    363 }
    364 
    365 /* static */
    366 void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
    367     sp<os::IExternalVibratorService> evs = getExternalVibratorService();
    368     if (evs != 0) {
    369         evs->onExternalVibrationStop(*externalVibration);
    370     }
    371 }
    372 
    373 static const char * const audio_interfaces[] = {
    374     AUDIO_HARDWARE_MODULE_ID_PRIMARY,
    375     AUDIO_HARDWARE_MODULE_ID_A2DP,
    376     AUDIO_HARDWARE_MODULE_ID_USB,
    377 };
    378 
    379 AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
    380         audio_module_handle_t module,
    381         audio_devices_t devices)
    382 {
    383     // if module is 0, the request comes from an old policy manager and we should load
    384     // well known modules
    385     if (module == 0) {
    386         ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
    387         for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
    388             loadHwModule_l(audio_interfaces[i]);
    389         }
    390         // then try to find a module supporting the requested device.
    391         for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
    392             AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
    393             sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
    394             uint32_t supportedDevices;
    395             if (dev->getSupportedDevices(&supportedDevices) == OK &&
    396                     (supportedDevices & devices) == devices) {
    397                 return audioHwDevice;
    398             }
    399         }
    400     } else {
    401         // check a match for the requested module handle
    402         AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
    403         if (audioHwDevice != NULL) {
    404             return audioHwDevice;
    405         }
    406     }
    407 
    408     return NULL;
    409 }
    410 
    411 void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
    412 {
    413     const size_t SIZE = 256;
    414     char buffer[SIZE];
    415     String8 result;
    416 
    417     result.append("Clients:\n");
    418     for (size_t i = 0; i < mClients.size(); ++i) {
    419         sp<Client> client = mClients.valueAt(i).promote();
    420         if (client != 0) {
    421             snprintf(buffer, SIZE, "  pid: %d\n", client->pid());
    422             result.append(buffer);
    423         }
    424     }
    425 
    426     result.append("Notification Clients:\n");
    427     for (size_t i = 0; i < mNotificationClients.size(); ++i) {
    428         snprintf(buffer, SIZE, "  pid: %d\n", mNotificationClients.keyAt(i));
    429         result.append(buffer);
    430     }
    431 
    432     result.append("Global session refs:\n");
    433     result.append("  session   pid count\n");
    434     for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
    435         AudioSessionRef *r = mAudioSessionRefs[i];
    436         snprintf(buffer, SIZE, "  %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
    437         result.append(buffer);
    438     }
    439     write(fd, result.string(), result.size());
    440 }
    441 
    442 
    443 void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
    444 {
    445     const size_t SIZE = 256;
    446     char buffer[SIZE];
    447     String8 result;
    448     hardware_call_state hardwareStatus = mHardwareStatus;
    449 
    450     snprintf(buffer, SIZE, "Hardware status: %d\n"
    451                            "Standby Time mSec: %u\n",
    452                             hardwareStatus,
    453                             (uint32_t)(mStandbyTimeInNsecs / 1000000));
    454     result.append(buffer);
    455     write(fd, result.string(), result.size());
    456 }
    457 
    458 void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
    459 {
    460     const size_t SIZE = 256;
    461     char buffer[SIZE];
    462     String8 result;
    463     snprintf(buffer, SIZE, "Permission Denial: "
    464             "can't dump AudioFlinger from pid=%d, uid=%d\n",
    465             IPCThreadState::self()->getCallingPid(),
    466             IPCThreadState::self()->getCallingUid());
    467     result.append(buffer);
    468     write(fd, result.string(), result.size());
    469 }
    470 
    471 bool AudioFlinger::dumpTryLock(Mutex& mutex)
    472 {
    473     status_t err = mutex.timedLock(kDumpLockTimeoutNs);
    474     return err == NO_ERROR;
    475 }
    476 
    477 status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
    478 {
    479     if (!dumpAllowed()) {
    480         dumpPermissionDenial(fd, args);
    481     } else {
    482         // get state of hardware lock
    483         bool hardwareLocked = dumpTryLock(mHardwareLock);
    484         if (!hardwareLocked) {
    485             String8 result(kHardwareLockedString);
    486             write(fd, result.string(), result.size());
    487         } else {
    488             mHardwareLock.unlock();
    489         }
    490 
    491         const bool locked = dumpTryLock(mLock);
    492 
    493         // failed to lock - AudioFlinger is probably deadlocked
    494         if (!locked) {
    495             String8 result(kDeadlockedString);
    496             write(fd, result.string(), result.size());
    497         }
    498 
    499         bool clientLocked = dumpTryLock(mClientLock);
    500         if (!clientLocked) {
    501             String8 result(kClientLockedString);
    502             write(fd, result.string(), result.size());
    503         }
    504 
    505         if (mEffectsFactoryHal != 0) {
    506             mEffectsFactoryHal->dumpEffects(fd);
    507         } else {
    508             String8 result(kNoEffectsFactory);
    509             write(fd, result.string(), result.size());
    510         }
    511 
    512         dumpClients(fd, args);
    513         if (clientLocked) {
    514             mClientLock.unlock();
    515         }
    516 
    517         dumpInternals(fd, args);
    518 
    519         // dump playback threads
    520         for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
    521             mPlaybackThreads.valueAt(i)->dump(fd, args);
    522         }
    523 
    524         // dump record threads
    525         for (size_t i = 0; i < mRecordThreads.size(); i++) {
    526             mRecordThreads.valueAt(i)->dump(fd, args);
    527         }
    528 
    529         // dump mmap threads
    530         for (size_t i = 0; i < mMmapThreads.size(); i++) {
    531             mMmapThreads.valueAt(i)->dump(fd, args);
    532         }
    533 
    534         // dump orphan effect chains
    535         if (mOrphanEffectChains.size() != 0) {
    536             write(fd, "  Orphan Effect Chains\n", strlen("  Orphan Effect Chains\n"));
    537             for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
    538                 mOrphanEffectChains.valueAt(i)->dump(fd, args);
    539             }
    540         }
    541         // dump all hardware devs
    542         for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
    543             sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
    544             dev->dump(fd);
    545         }
    546 
    547         mPatchPanel.dump(fd);
    548 
    549         // dump external setParameters
    550         auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
    551             dprintf(fd, "\n%s setParameters:\n", name);
    552             logger.dump(fd, "    " /* prefix */);
    553         };
    554         dumpLogger(mRejectedSetParameterLog, "Rejected");
    555         dumpLogger(mAppSetParameterLog, "App");
    556         dumpLogger(mSystemSetParameterLog, "System");
    557 
    558         // dump historical threads in the last 10 seconds
    559         const std::string threadLog = mThreadLog.dumpToString(
    560                 "Historical Thread Log ", 0 /* lines */,
    561                 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
    562         write(fd, threadLog.c_str(), threadLog.size());
    563 
    564         BUFLOG_RESET;
    565 
    566         if (locked) {
    567             mLock.unlock();
    568         }
    569 
    570 #ifdef TEE_SINK
    571         // NBAIO_Tee dump is safe to call outside of AF lock.
    572         NBAIO_Tee::dumpAll(fd, "_DUMP");
    573 #endif
    574         // append a copy of media.log here by forwarding fd to it, but don't attempt
    575         // to lookup the service if it's not running, as it will block for a second
    576         if (sMediaLogServiceAsBinder != 0) {
    577             dprintf(fd, "\nmedia.log:\n");
    578             Vector<String16> args;
    579             sMediaLogServiceAsBinder->dump(fd, args);
    580         }
    581 
    582         // check for optional arguments
    583         bool dumpMem = false;
    584         bool unreachableMemory = false;
    585         for (const auto &arg : args) {
    586             if (arg == String16("-m")) {
    587                 dumpMem = true;
    588             } else if (arg == String16("--unreachable")) {
    589                 unreachableMemory = true;
    590             }
    591         }
    592 
    593         if (dumpMem) {
    594             dprintf(fd, "\nDumping memory:\n");
    595             std::string s = dumpMemoryAddresses(100 /* limit */);
    596             write(fd, s.c_str(), s.size());
    597         }
    598         if (unreachableMemory) {
    599             dprintf(fd, "\nDumping unreachable memory:\n");
    600             // TODO - should limit be an argument parameter?
    601             std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
    602             write(fd, s.c_str(), s.size());
    603         }
    604     }
    605     return NO_ERROR;
    606 }
    607 
    608 sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
    609 {
    610     Mutex::Autolock _cl(mClientLock);
    611     // If pid is already in the mClients wp<> map, then use that entry
    612     // (for which promote() is always != 0), otherwise create a new entry and Client.
    613     sp<Client> client = mClients.valueFor(pid).promote();
    614     if (client == 0) {
    615         client = new Client(this, pid);
    616         mClients.add(pid, client);
    617     }
    618 
    619     return client;
    620 }
    621 
    622 sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
    623 {
    624     // If there is no memory allocated for logs, return a dummy writer that does nothing.
    625     // Similarly if we can't contact the media.log service, also return a dummy writer.
    626     if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
    627         return new NBLog::Writer();
    628     }
    629     sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
    630     // If allocation fails, consult the vector of previously unregistered writers
    631     // and garbage-collect one or more them until an allocation succeeds
    632     if (shared == 0) {
    633         Mutex::Autolock _l(mUnregisteredWritersLock);
    634         for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
    635             {
    636                 // Pick the oldest stale writer to garbage-collect
    637                 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
    638                 mUnregisteredWriters.removeAt(0);
    639                 sMediaLogService->unregisterWriter(iMemory);
    640                 // Now the media.log remote reference to IMemory is gone.  When our last local
    641                 // reference to IMemory also drops to zero at end of this block,
    642                 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
    643             }
    644             // Re-attempt the allocation
    645             shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
    646             if (shared != 0) {
    647                 goto success;
    648             }
    649         }
    650         // Even after garbage-collecting all old writers, there is still not enough memory,
    651         // so return a dummy writer
    652         return new NBLog::Writer();
    653     }
    654 success:
    655     NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
    656     new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
    657                                                 // explicit destructor not needed since it is POD
    658     sMediaLogService->registerWriter(shared, size, name);
    659     return new NBLog::Writer(shared, size);
    660 }
    661 
    662 void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
    663 {
    664     if (writer == 0) {
    665         return;
    666     }
    667     sp<IMemory> iMemory(writer->getIMemory());
    668     if (iMemory == 0) {
    669         return;
    670     }
    671     // Rather than removing the writer immediately, append it to a queue of old writers to
    672     // be garbage-collected later.  This allows us to continue to view old logs for a while.
    673     Mutex::Autolock _l(mUnregisteredWritersLock);
    674     mUnregisteredWriters.push(writer);
    675 }
    676 
    677 // IAudioFlinger interface
    678 
    679 sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
    680                                           CreateTrackOutput& output,
    681                                           status_t *status)
    682 {
    683     sp<PlaybackThread::Track> track;
    684     sp<TrackHandle> trackHandle;
    685     sp<Client> client;
    686     status_t lStatus;
    687     audio_stream_type_t streamType;
    688     audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
    689     std::vector<audio_io_handle_t> secondaryOutputs;
    690 
    691     bool updatePid = (input.clientInfo.clientPid == -1);
    692     const uid_t callingUid = IPCThreadState::self()->getCallingUid();
    693     uid_t clientUid = input.clientInfo.clientUid;
    694     audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
    695     std::vector<int> effectIds;
    696     audio_attributes_t localAttr = input.attr;
    697 
    698     if (!isAudioServerOrMediaServerUid(callingUid)) {
    699         ALOGW_IF(clientUid != callingUid,
    700                 "%s uid %d tried to pass itself off as %d",
    701                 __FUNCTION__, callingUid, clientUid);
    702         clientUid = callingUid;
    703         updatePid = true;
    704     }
    705     pid_t clientPid = input.clientInfo.clientPid;
    706     const pid_t callingPid = IPCThreadState::self()->getCallingPid();
    707     if (updatePid) {
    708         ALOGW_IF(clientPid != -1 && clientPid != callingPid,
    709                  "%s uid %d pid %d tried to pass itself off as pid %d",
    710                  __func__, callingUid, callingPid, clientPid);
    711         clientPid = callingPid;
    712     }
    713 
    714     audio_session_t sessionId = input.sessionId;
    715     if (sessionId == AUDIO_SESSION_ALLOCATE) {
    716         sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
    717     } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
    718         lStatus = BAD_VALUE;
    719         goto Exit;
    720     }
    721 
    722     output.sessionId = sessionId;
    723     output.outputId = AUDIO_IO_HANDLE_NONE;
    724     output.selectedDeviceId = input.selectedDeviceId;
    725     lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
    726                                             clientPid, clientUid, &input.config, input.flags,
    727                                             &output.selectedDeviceId, &portId, &secondaryOutputs);
    728 
    729     if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
    730         ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
    731         goto Exit;
    732     }
    733     // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
    734     // but if someone uses binder directly they could bypass that and cause us to crash
    735     if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
    736         ALOGE("createTrack() invalid stream type %d", streamType);
    737         lStatus = BAD_VALUE;
    738         goto Exit;
    739     }
    740 
    741     // further channel mask checks are performed by createTrack_l() depending on the thread type
    742     if (!audio_is_output_channel(input.config.channel_mask)) {
    743         ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
    744         lStatus = BAD_VALUE;
    745         goto Exit;
    746     }
    747 
    748     // further format checks are performed by createTrack_l() depending on the thread type
    749     if (!audio_is_valid_format(input.config.format)) {
    750         ALOGE("createTrack() invalid format %#x", input.config.format);
    751         lStatus = BAD_VALUE;
    752         goto Exit;
    753     }
    754 
    755     {
    756         Mutex::Autolock _l(mLock);
    757         PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
    758         if (thread == NULL) {
    759             ALOGE("no playback thread found for output handle %d", output.outputId);
    760             lStatus = BAD_VALUE;
    761             goto Exit;
    762         }
    763 
    764         client = registerPid(clientPid);
    765 
    766         PlaybackThread *effectThread = NULL;
    767         // check if an effect chain with the same session ID is present on another
    768         // output thread and move it here.
    769         for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
    770             sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
    771             if (mPlaybackThreads.keyAt(i) != output.outputId) {
    772                 uint32_t sessions = t->hasAudioSession(sessionId);
    773                 if (sessions & ThreadBase::EFFECT_SESSION) {
    774                     effectThread = t.get();
    775                     break;
    776                 }
    777             }
    778         }
    779         ALOGV("createTrack() sessionId: %d", sessionId);
    780 
    781         output.sampleRate = input.config.sample_rate;
    782         output.frameCount = input.frameCount;
    783         output.notificationFrameCount = input.notificationFrameCount;
    784         output.flags = input.flags;
    785 
    786         track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
    787                                       input.config.format, input.config.channel_mask,
    788                                       &output.frameCount, &output.notificationFrameCount,
    789                                       input.notificationsPerBuffer, input.speed,
    790                                       input.sharedBuffer, sessionId, &output.flags,
    791                                       callingPid, input.clientInfo.clientTid, clientUid,
    792                                       &lStatus, portId);
    793         LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
    794         // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
    795 
    796         output.afFrameCount = thread->frameCount();
    797         output.afSampleRate = thread->sampleRate();
    798         output.afLatencyMs = thread->latency();
    799         output.portId = portId;
    800 
    801         if (lStatus == NO_ERROR) {
    802             // Connect secondary outputs. Failure on a secondary output must not imped the primary
    803             // Any secondary output setup failure will lead to a desync between the AP and AF until
    804             // the track is destroyed.
    805             TeePatches teePatches;
    806             for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
    807                 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
    808                 if (secondaryThread == NULL) {
    809                     ALOGE("no playback thread found for secondary output %d", output.outputId);
    810                     continue;
    811                 }
    812 
    813                 size_t frameCount = std::lcm(thread->frameCount(), secondaryThread->frameCount());
    814 
    815                 using namespace std::chrono_literals;
    816                 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
    817                 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
    818                                                                output.sampleRate,
    819                                                                inChannelMask,
    820                                                                input.config.format,
    821                                                                frameCount,
    822                                                                NULL /* buffer */,
    823                                                                (size_t)0 /* bufferSize */,
    824                                                                AUDIO_INPUT_FLAG_DIRECT,
    825                                                                0ns /* timeout */);
    826                 status_t status = patchRecord->initCheck();
    827                 if (status != NO_ERROR) {
    828                     ALOGE("Secondary output patchRecord init failed: %d", status);
    829                     continue;
    830                 }
    831 
    832                 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
    833                 // for fast usage: thread has fast mixer, sample rate matches, etc.;
    834                 // for now, we exclude fast tracks by removing the Fast flag.
    835                 const audio_output_flags_t outputFlags =
    836                         (audio_output_flags_t)(output.flags & ~AUDIO_OUTPUT_FLAG_FAST);
    837                 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
    838                                                                streamType,
    839                                                                output.sampleRate,
    840                                                                input.config.channel_mask,
    841                                                                input.config.format,
    842                                                                frameCount,
    843                                                                patchRecord->buffer(),
    844                                                                patchRecord->bufferSize(),
    845                                                                outputFlags,
    846                                                                0ns /* timeout */);
    847                 status = patchTrack->initCheck();
    848                 if (status != NO_ERROR) {
    849                     ALOGE("Secondary output patchTrack init failed: %d", status);
    850                     continue;
    851                 }
    852                 teePatches.push_back({patchRecord, patchTrack});
    853                 secondaryThread->addPatchTrack(patchTrack);
    854                 // In case the downstream patchTrack on the secondaryThread temporarily outlives
    855                 // our created track, ensure the corresponding patchRecord is still alive.
    856                 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
    857                 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
    858             }
    859             track->setTeePatches(std::move(teePatches));
    860         }
    861 
    862         // move effect chain to this output thread if an effect on same session was waiting
    863         // for a track to be created
    864         if (lStatus == NO_ERROR && effectThread != NULL) {
    865             // no risk of deadlock because AudioFlinger::mLock is held
    866             Mutex::Autolock _dl(thread->mLock);
    867             Mutex::Autolock _sl(effectThread->mLock);
    868             if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
    869                 effectThreadId = thread->id();
    870                 effectIds = thread->getEffectIds_l(sessionId);
    871             }
    872         }
    873 
    874         // Look for sync events awaiting for a session to be used.
    875         for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
    876             if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
    877                 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
    878                     if (lStatus == NO_ERROR) {
    879                         (void) track->setSyncEvent(mPendingSyncEvents[i]);
    880                     } else {
    881                         mPendingSyncEvents[i]->cancel();
    882                     }
    883                     mPendingSyncEvents.removeAt(i);
    884                     i--;
    885                 }
    886             }
    887         }
    888 
    889         setAudioHwSyncForSession_l(thread, sessionId);
    890     }
    891 
    892     if (lStatus != NO_ERROR) {
    893         // remove local strong reference to Client before deleting the Track so that the
    894         // Client destructor is called by the TrackBase destructor with mClientLock held
    895         // Don't hold mClientLock when releasing the reference on the track as the
    896         // destructor will acquire it.
    897         {
    898             Mutex::Autolock _cl(mClientLock);
    899             client.clear();
    900         }
    901         track.clear();
    902         goto Exit;
    903     }
    904 
    905     // effectThreadId is not NONE if an effect chain corresponding to the track session
    906     // was found on another thread and must be moved on this thread
    907     if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
    908         AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
    909     }
    910 
    911     // return handle to client
    912     trackHandle = new TrackHandle(track);
    913 
    914 Exit:
    915     if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
    916         AudioSystem::releaseOutput(portId);
    917     }
    918     *status = lStatus;
    919     return trackHandle;
    920 }
    921 
    922 uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
    923 {
    924     Mutex::Autolock _l(mLock);
    925     ThreadBase *thread = checkThread_l(ioHandle);
    926     if (thread == NULL) {
    927         ALOGW("sampleRate() unknown thread %d", ioHandle);
    928         return 0;
    929     }
    930     return thread->sampleRate();
    931 }
    932 
    933 audio_format_t AudioFlinger::format(audio_io_handle_t output) const
    934 {
    935     Mutex::Autolock _l(mLock);
    936     PlaybackThread *thread = checkPlaybackThread_l(output);
    937     if (thread == NULL) {
    938         ALOGW("format() unknown thread %d", output);
    939         return AUDIO_FORMAT_INVALID;
    940     }
    941     return thread->format();
    942 }
    943 
    944 size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
    945 {
    946     Mutex::Autolock _l(mLock);
    947     ThreadBase *thread = checkThread_l(ioHandle);
    948     if (thread == NULL) {
    949         ALOGW("frameCount() unknown thread %d", ioHandle);
    950         return 0;
    951     }
    952     // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
    953     //       should examine all callers and fix them to handle smaller counts
    954     return thread->frameCount();
    955 }
    956 
    957 size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
    958 {
    959     Mutex::Autolock _l(mLock);
    960     ThreadBase *thread = checkThread_l(ioHandle);
    961     if (thread == NULL) {
    962         ALOGW("frameCountHAL() unknown thread %d", ioHandle);
    963         return 0;
    964     }
    965     return thread->frameCountHAL();
    966 }
    967 
    968 uint32_t AudioFlinger::latency(audio_io_handle_t output) const
    969 {
    970     Mutex::Autolock _l(mLock);
    971     PlaybackThread *thread = checkPlaybackThread_l(output);
    972     if (thread == NULL) {
    973         ALOGW("latency(): no playback thread found for output handle %d", output);
    974         return 0;
    975     }
    976     return thread->latency();
    977 }
    978 
    979 status_t AudioFlinger::setMasterVolume(float value)
    980 {
    981     status_t ret = initCheck();
    982     if (ret != NO_ERROR) {
    983         return ret;
    984     }
    985 
    986     // check calling permissions
    987     if (!settingsAllowed()) {
    988         return PERMISSION_DENIED;
    989     }
    990 
    991     Mutex::Autolock _l(mLock);
    992     mMasterVolume = value;
    993 
    994     // Set master volume in the HALs which support it.
    995     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
    996         AutoMutex lock(mHardwareLock);
    997         AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
    998 
    999         mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
   1000         if (dev->canSetMasterVolume()) {
   1001             dev->hwDevice()->setMasterVolume(value);
   1002         }
   1003         mHardwareStatus = AUDIO_HW_IDLE;
   1004     }
   1005 
   1006     // Now set the master volume in each playback thread.  Playback threads
   1007     // assigned to HALs which do not have master volume support will apply
   1008     // master volume during the mix operation.  Threads with HALs which do
   1009     // support master volume will simply ignore the setting.
   1010     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   1011         if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
   1012             continue;
   1013         }
   1014         mPlaybackThreads.valueAt(i)->setMasterVolume(value);
   1015     }
   1016 
   1017     return NO_ERROR;
   1018 }
   1019 
   1020 status_t AudioFlinger::setMasterBalance(float balance)
   1021 {
   1022     status_t ret = initCheck();
   1023     if (ret != NO_ERROR) {
   1024         return ret;
   1025     }
   1026 
   1027     // check calling permissions
   1028     if (!settingsAllowed()) {
   1029         return PERMISSION_DENIED;
   1030     }
   1031 
   1032     // check range
   1033     if (isnan(balance) || fabs(balance) > 1.f) {
   1034         return BAD_VALUE;
   1035     }
   1036 
   1037     Mutex::Autolock _l(mLock);
   1038 
   1039     // short cut.
   1040     if (mMasterBalance == balance) return NO_ERROR;
   1041 
   1042     mMasterBalance = balance;
   1043 
   1044     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   1045         if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
   1046             continue;
   1047         }
   1048         mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
   1049     }
   1050 
   1051     return NO_ERROR;
   1052 }
   1053 
   1054 status_t AudioFlinger::setMode(audio_mode_t mode)
   1055 {
   1056     status_t ret = initCheck();
   1057     if (ret != NO_ERROR) {
   1058         return ret;
   1059     }
   1060 
   1061     // check calling permissions
   1062     if (!settingsAllowed()) {
   1063         return PERMISSION_DENIED;
   1064     }
   1065     if (uint32_t(mode) >= AUDIO_MODE_CNT) {
   1066         ALOGW("Illegal value: setMode(%d)", mode);
   1067         return BAD_VALUE;
   1068     }
   1069 
   1070     { // scope for the lock
   1071         AutoMutex lock(mHardwareLock);
   1072         sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
   1073         mHardwareStatus = AUDIO_HW_SET_MODE;
   1074         ret = dev->setMode(mode);
   1075         mHardwareStatus = AUDIO_HW_IDLE;
   1076     }
   1077 
   1078     if (NO_ERROR == ret) {
   1079         Mutex::Autolock _l(mLock);
   1080         mMode = mode;
   1081         for (size_t i = 0; i < mPlaybackThreads.size(); i++)
   1082             mPlaybackThreads.valueAt(i)->setMode(mode);
   1083     }
   1084 
   1085     return ret;
   1086 }
   1087 
   1088 status_t AudioFlinger::setMicMute(bool state)
   1089 {
   1090     status_t ret = initCheck();
   1091     if (ret != NO_ERROR) {
   1092         return ret;
   1093     }
   1094 
   1095     // check calling permissions
   1096     if (!settingsAllowed()) {
   1097         return PERMISSION_DENIED;
   1098     }
   1099 
   1100     AutoMutex lock(mHardwareLock);
   1101     mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
   1102     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
   1103         sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
   1104         status_t result = dev->setMicMute(state);
   1105         if (result != NO_ERROR) {
   1106             ret = result;
   1107         }
   1108     }
   1109     mHardwareStatus = AUDIO_HW_IDLE;
   1110     return ret;
   1111 }
   1112 
   1113 bool AudioFlinger::getMicMute() const
   1114 {
   1115     status_t ret = initCheck();
   1116     if (ret != NO_ERROR) {
   1117         return false;
   1118     }
   1119     bool mute = true;
   1120     bool state = AUDIO_MODE_INVALID;
   1121     AutoMutex lock(mHardwareLock);
   1122     mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
   1123     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
   1124         sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
   1125         status_t result = dev->getMicMute(&state);
   1126         if (result == NO_ERROR) {
   1127             mute = mute && state;
   1128         }
   1129     }
   1130     mHardwareStatus = AUDIO_HW_IDLE;
   1131 
   1132     return mute;
   1133 }
   1134 
   1135 void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
   1136 {
   1137     ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
   1138 
   1139     AutoMutex lock(mLock);
   1140     for (size_t i = 0; i < mRecordThreads.size(); i++) {
   1141         mRecordThreads[i]->setRecordSilenced(uid, silenced);
   1142     }
   1143     for (size_t i = 0; i < mMmapThreads.size(); i++) {
   1144         mMmapThreads[i]->setRecordSilenced(uid, silenced);
   1145     }
   1146 }
   1147 
   1148 status_t AudioFlinger::setMasterMute(bool muted)
   1149 {
   1150     status_t ret = initCheck();
   1151     if (ret != NO_ERROR) {
   1152         return ret;
   1153     }
   1154 
   1155     // check calling permissions
   1156     if (!settingsAllowed()) {
   1157         return PERMISSION_DENIED;
   1158     }
   1159 
   1160     Mutex::Autolock _l(mLock);
   1161     mMasterMute = muted;
   1162 
   1163     // Set master mute in the HALs which support it.
   1164     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
   1165         AutoMutex lock(mHardwareLock);
   1166         AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
   1167 
   1168         mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
   1169         if (dev->canSetMasterMute()) {
   1170             dev->hwDevice()->setMasterMute(muted);
   1171         }
   1172         mHardwareStatus = AUDIO_HW_IDLE;
   1173     }
   1174 
   1175     // Now set the master mute in each playback thread.  Playback threads
   1176     // assigned to HALs which do not have master mute support will apply master
   1177     // mute during the mix operation.  Threads with HALs which do support master
   1178     // mute will simply ignore the setting.
   1179     Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
   1180     for (size_t i = 0; i < volumeInterfaces.size(); i++) {
   1181         volumeInterfaces[i]->setMasterMute(muted);
   1182     }
   1183 
   1184     return NO_ERROR;
   1185 }
   1186 
   1187 float AudioFlinger::masterVolume() const
   1188 {
   1189     Mutex::Autolock _l(mLock);
   1190     return masterVolume_l();
   1191 }
   1192 
   1193 status_t AudioFlinger::getMasterBalance(float *balance) const
   1194 {
   1195     Mutex::Autolock _l(mLock);
   1196     *balance = getMasterBalance_l();
   1197     return NO_ERROR; // if called through binder, may return a transactional error
   1198 }
   1199 
   1200 bool AudioFlinger::masterMute() const
   1201 {
   1202     Mutex::Autolock _l(mLock);
   1203     return masterMute_l();
   1204 }
   1205 
   1206 float AudioFlinger::masterVolume_l() const
   1207 {
   1208     return mMasterVolume;
   1209 }
   1210 
   1211 float AudioFlinger::getMasterBalance_l() const
   1212 {
   1213     return mMasterBalance;
   1214 }
   1215 
   1216 bool AudioFlinger::masterMute_l() const
   1217 {
   1218     return mMasterMute;
   1219 }
   1220 
   1221 status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
   1222 {
   1223     if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
   1224         ALOGW("checkStreamType() invalid stream %d", stream);
   1225         return BAD_VALUE;
   1226     }
   1227     const uid_t callerUid = IPCThreadState::self()->getCallingUid();
   1228     if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
   1229         ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
   1230         return PERMISSION_DENIED;
   1231     }
   1232 
   1233     return NO_ERROR;
   1234 }
   1235 
   1236 status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
   1237         audio_io_handle_t output)
   1238 {
   1239     // check calling permissions
   1240     if (!settingsAllowed()) {
   1241         return PERMISSION_DENIED;
   1242     }
   1243 
   1244     status_t status = checkStreamType(stream);
   1245     if (status != NO_ERROR) {
   1246         return status;
   1247     }
   1248     if (output == AUDIO_IO_HANDLE_NONE) {
   1249         return BAD_VALUE;
   1250     }
   1251     LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
   1252                         "AUDIO_STREAM_PATCH must have full scale volume");
   1253 
   1254     AutoMutex lock(mLock);
   1255     VolumeInterface *volumeInterface = getVolumeInterface_l(output);
   1256     if (volumeInterface == NULL) {
   1257         return BAD_VALUE;
   1258     }
   1259     volumeInterface->setStreamVolume(stream, value);
   1260 
   1261     return NO_ERROR;
   1262 }
   1263 
   1264 status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
   1265 {
   1266     // check calling permissions
   1267     if (!settingsAllowed()) {
   1268         return PERMISSION_DENIED;
   1269     }
   1270 
   1271     status_t status = checkStreamType(stream);
   1272     if (status != NO_ERROR) {
   1273         return status;
   1274     }
   1275     ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
   1276 
   1277     if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
   1278         ALOGE("setStreamMute() invalid stream %d", stream);
   1279         return BAD_VALUE;
   1280     }
   1281 
   1282     AutoMutex lock(mLock);
   1283     mStreamTypes[stream].mute = muted;
   1284     Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
   1285     for (size_t i = 0; i < volumeInterfaces.size(); i++) {
   1286         volumeInterfaces[i]->setStreamMute(stream, muted);
   1287     }
   1288 
   1289     return NO_ERROR;
   1290 }
   1291 
   1292 float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
   1293 {
   1294     status_t status = checkStreamType(stream);
   1295     if (status != NO_ERROR) {
   1296         return 0.0f;
   1297     }
   1298     if (output == AUDIO_IO_HANDLE_NONE) {
   1299         return 0.0f;
   1300     }
   1301 
   1302     AutoMutex lock(mLock);
   1303     VolumeInterface *volumeInterface = getVolumeInterface_l(output);
   1304     if (volumeInterface == NULL) {
   1305         return 0.0f;
   1306     }
   1307 
   1308     return volumeInterface->streamVolume(stream);
   1309 }
   1310 
   1311 bool AudioFlinger::streamMute(audio_stream_type_t stream) const
   1312 {
   1313     status_t status = checkStreamType(stream);
   1314     if (status != NO_ERROR) {
   1315         return true;
   1316     }
   1317 
   1318     AutoMutex lock(mLock);
   1319     return streamMute_l(stream);
   1320 }
   1321 
   1322 
   1323 void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
   1324 {
   1325     for (size_t i = 0; i < mRecordThreads.size(); i++) {
   1326         mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
   1327     }
   1328 }
   1329 
   1330 // forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
   1331 void AudioFlinger::forwardParametersToDownstreamPatches_l(
   1332         audio_io_handle_t upStream, const String8& keyValuePairs,
   1333         std::function<bool(const sp<PlaybackThread>&)> useThread)
   1334 {
   1335     std::vector<PatchPanel::SoftwarePatch> swPatches;
   1336     if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
   1337     ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
   1338             __func__, swPatches.size(), upStream);
   1339     for (const auto& swPatch : swPatches) {
   1340         sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
   1341         if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
   1342             downStream->setParameters(keyValuePairs);
   1343         }
   1344     }
   1345 }
   1346 
   1347 // Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
   1348 // Some keys are used for audio routing and audio path configuration and should be reserved for use
   1349 // by audio policy and audio flinger for functional, privacy and security reasons.
   1350 void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
   1351 {
   1352     static const String8 kReservedParameters[] = {
   1353         String8(AudioParameter::keyRouting),
   1354         String8(AudioParameter::keySamplingRate),
   1355         String8(AudioParameter::keyFormat),
   1356         String8(AudioParameter::keyChannels),
   1357         String8(AudioParameter::keyFrameCount),
   1358         String8(AudioParameter::keyInputSource),
   1359         String8(AudioParameter::keyMonoOutput),
   1360         String8(AudioParameter::keyStreamConnect),
   1361         String8(AudioParameter::keyStreamDisconnect),
   1362         String8(AudioParameter::keyStreamSupportedFormats),
   1363         String8(AudioParameter::keyStreamSupportedChannels),
   1364         String8(AudioParameter::keyStreamSupportedSamplingRates),
   1365     };
   1366 
   1367     if (isAudioServerUid(callingUid)) {
   1368         return; // no need to filter if audioserver.
   1369     }
   1370 
   1371     AudioParameter param = AudioParameter(keyValuePairs);
   1372     String8 value;
   1373     AudioParameter rejectedParam;
   1374     for (auto& key : kReservedParameters) {
   1375         if (param.get(key, value) == NO_ERROR) {
   1376             rejectedParam.add(key, value);
   1377             param.remove(key);
   1378         }
   1379     }
   1380     logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
   1381                           rejectedParam.size(), rejectedParam.toString(), callingUid);
   1382     keyValuePairs = param.toString();
   1383 }
   1384 
   1385 void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
   1386                                          size_t rejectedKVPSize, const String8& rejectedKVPs,
   1387                                          uid_t callingUid) {
   1388     auto prefix = String8::format("UID %5d", callingUid);
   1389     auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
   1390     if (rejectedKVPSize != 0) {
   1391         auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
   1392         ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
   1393         mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
   1394     } else {
   1395         auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
   1396         logger.log("%s, %s", prefix.c_str(), suffix.c_str());
   1397     }
   1398 }
   1399 
   1400 status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
   1401 {
   1402     ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
   1403             ioHandle, keyValuePairs.string(),
   1404             IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
   1405 
   1406     // check calling permissions
   1407     if (!settingsAllowed()) {
   1408         return PERMISSION_DENIED;
   1409     }
   1410 
   1411     String8 filteredKeyValuePairs = keyValuePairs;
   1412     filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
   1413 
   1414     ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
   1415 
   1416     // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
   1417     if (ioHandle == AUDIO_IO_HANDLE_NONE) {
   1418         Mutex::Autolock _l(mLock);
   1419         // result will remain NO_INIT if no audio device is present
   1420         status_t final_result = NO_INIT;
   1421         {
   1422             AutoMutex lock(mHardwareLock);
   1423             mHardwareStatus = AUDIO_HW_SET_PARAMETER;
   1424             for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
   1425                 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
   1426                 status_t result = dev->setParameters(filteredKeyValuePairs);
   1427                 // return success if at least one audio device accepts the parameters as not all
   1428                 // HALs are requested to support all parameters. If no audio device supports the
   1429                 // requested parameters, the last error is reported.
   1430                 if (final_result != NO_ERROR) {
   1431                     final_result = result;
   1432                 }
   1433             }
   1434             mHardwareStatus = AUDIO_HW_IDLE;
   1435         }
   1436         // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
   1437         AudioParameter param = AudioParameter(filteredKeyValuePairs);
   1438         String8 value;
   1439         if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
   1440             bool btNrecIsOff = (value == AudioParameter::valueOff);
   1441             if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
   1442                 for (size_t i = 0; i < mRecordThreads.size(); i++) {
   1443                     mRecordThreads.valueAt(i)->checkBtNrec();
   1444                 }
   1445             }
   1446         }
   1447         String8 screenState;
   1448         if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
   1449             bool isOff = (screenState == AudioParameter::valueOff);
   1450             if (isOff != (AudioFlinger::mScreenState & 1)) {
   1451                 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
   1452             }
   1453         }
   1454         return final_result;
   1455     }
   1456 
   1457     // hold a strong ref on thread in case closeOutput() or closeInput() is called
   1458     // and the thread is exited once the lock is released
   1459     sp<ThreadBase> thread;
   1460     {
   1461         Mutex::Autolock _l(mLock);
   1462         thread = checkPlaybackThread_l(ioHandle);
   1463         if (thread == 0) {
   1464             thread = checkRecordThread_l(ioHandle);
   1465             if (thread == 0) {
   1466                 thread = checkMmapThread_l(ioHandle);
   1467             }
   1468         } else if (thread == primaryPlaybackThread_l()) {
   1469             // indicate output device change to all input threads for pre processing
   1470             AudioParameter param = AudioParameter(filteredKeyValuePairs);
   1471             int value;
   1472             if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
   1473                     (value != 0)) {
   1474                 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
   1475             }
   1476         }
   1477     }
   1478     if (thread != 0) {
   1479         status_t result = thread->setParameters(filteredKeyValuePairs);
   1480         forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
   1481         return result;
   1482     }
   1483     return BAD_VALUE;
   1484 }
   1485 
   1486 String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
   1487 {
   1488     ALOGVV("getParameters() io %d, keys %s, calling pid %d",
   1489             ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
   1490 
   1491     Mutex::Autolock _l(mLock);
   1492 
   1493     if (ioHandle == AUDIO_IO_HANDLE_NONE) {
   1494         String8 out_s8;
   1495 
   1496         for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
   1497             String8 s;
   1498             status_t result;
   1499             {
   1500             AutoMutex lock(mHardwareLock);
   1501             mHardwareStatus = AUDIO_HW_GET_PARAMETER;
   1502             sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
   1503             result = dev->getParameters(keys, &s);
   1504             mHardwareStatus = AUDIO_HW_IDLE;
   1505             }
   1506             if (result == OK) out_s8 += s;
   1507         }
   1508         return out_s8;
   1509     }
   1510 
   1511     ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
   1512     if (thread == NULL) {
   1513         thread = (ThreadBase *)checkRecordThread_l(ioHandle);
   1514         if (thread == NULL) {
   1515             thread = (ThreadBase *)checkMmapThread_l(ioHandle);
   1516             if (thread == NULL) {
   1517                 return String8("");
   1518             }
   1519         }
   1520     }
   1521     return thread->getParameters(keys);
   1522 }
   1523 
   1524 size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
   1525         audio_channel_mask_t channelMask) const
   1526 {
   1527     status_t ret = initCheck();
   1528     if (ret != NO_ERROR) {
   1529         return 0;
   1530     }
   1531     if ((sampleRate == 0) ||
   1532             !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
   1533             !audio_is_input_channel(channelMask)) {
   1534         return 0;
   1535     }
   1536 
   1537     AutoMutex lock(mHardwareLock);
   1538     mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
   1539     audio_config_t config, proposed;
   1540     memset(&proposed, 0, sizeof(proposed));
   1541     proposed.sample_rate = sampleRate;
   1542     proposed.channel_mask = channelMask;
   1543     proposed.format = format;
   1544 
   1545     sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
   1546     size_t frames;
   1547     for (;;) {
   1548         // Note: config is currently a const parameter for get_input_buffer_size()
   1549         // but we use a copy from proposed in case config changes from the call.
   1550         config = proposed;
   1551         status_t result = dev->getInputBufferSize(&config, &frames);
   1552         if (result == OK && frames != 0) {
   1553             break; // hal success, config is the result
   1554         }
   1555         // change one parameter of the configuration each iteration to a more "common" value
   1556         // to see if the device will support it.
   1557         if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
   1558             proposed.format = AUDIO_FORMAT_PCM_16_BIT;
   1559         } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
   1560             proposed.sample_rate = 44100;           // legacy AudioRecord.java. TODO: Query hw?
   1561         } else {
   1562             ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
   1563                     "format %#x, channelMask 0x%X",
   1564                     sampleRate, format, channelMask);
   1565             break; // retries failed, break out of loop with frames == 0.
   1566         }
   1567     }
   1568     mHardwareStatus = AUDIO_HW_IDLE;
   1569     if (frames > 0 && config.sample_rate != sampleRate) {
   1570         frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
   1571     }
   1572     return frames; // may be converted to bytes at the Java level.
   1573 }
   1574 
   1575 uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
   1576 {
   1577     Mutex::Autolock _l(mLock);
   1578 
   1579     RecordThread *recordThread = checkRecordThread_l(ioHandle);
   1580     if (recordThread != NULL) {
   1581         return recordThread->getInputFramesLost();
   1582     }
   1583     return 0;
   1584 }
   1585 
   1586 status_t AudioFlinger::setVoiceVolume(float value)
   1587 {
   1588     status_t ret = initCheck();
   1589     if (ret != NO_ERROR) {
   1590         return ret;
   1591     }
   1592 
   1593     // check calling permissions
   1594     if (!settingsAllowed()) {
   1595         return PERMISSION_DENIED;
   1596     }
   1597 
   1598     AutoMutex lock(mHardwareLock);
   1599     sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
   1600     mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
   1601     ret = dev->setVoiceVolume(value);
   1602     mHardwareStatus = AUDIO_HW_IDLE;
   1603 
   1604     return ret;
   1605 }
   1606 
   1607 status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
   1608         audio_io_handle_t output) const
   1609 {
   1610     Mutex::Autolock _l(mLock);
   1611 
   1612     PlaybackThread *playbackThread = checkPlaybackThread_l(output);
   1613     if (playbackThread != NULL) {
   1614         return playbackThread->getRenderPosition(halFrames, dspFrames);
   1615     }
   1616 
   1617     return BAD_VALUE;
   1618 }
   1619 
   1620 void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
   1621 {
   1622     Mutex::Autolock _l(mLock);
   1623     if (client == 0) {
   1624         return;
   1625     }
   1626     pid_t pid = IPCThreadState::self()->getCallingPid();
   1627     {
   1628         Mutex::Autolock _cl(mClientLock);
   1629         if (mNotificationClients.indexOfKey(pid) < 0) {
   1630             sp<NotificationClient> notificationClient = new NotificationClient(this,
   1631                                                                                 client,
   1632                                                                                 pid);
   1633             ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
   1634 
   1635             mNotificationClients.add(pid, notificationClient);
   1636 
   1637             sp<IBinder> binder = IInterface::asBinder(client);
   1638             binder->linkToDeath(notificationClient);
   1639         }
   1640     }
   1641 
   1642     // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
   1643     // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
   1644     // the config change is always sent from playback or record threads to avoid deadlock
   1645     // with AudioSystem::gLock
   1646     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   1647         mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
   1648     }
   1649 
   1650     for (size_t i = 0; i < mRecordThreads.size(); i++) {
   1651         mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
   1652     }
   1653 }
   1654 
   1655 void AudioFlinger::removeNotificationClient(pid_t pid)
   1656 {
   1657     std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
   1658     {
   1659         Mutex::Autolock _l(mLock);
   1660         {
   1661             Mutex::Autolock _cl(mClientLock);
   1662             mNotificationClients.removeItem(pid);
   1663         }
   1664 
   1665         ALOGV("%d died, releasing its sessions", pid);
   1666         size_t num = mAudioSessionRefs.size();
   1667         bool removed = false;
   1668         for (size_t i = 0; i < num; ) {
   1669             AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
   1670             ALOGV(" pid %d @ %zu", ref->mPid, i);
   1671             if (ref->mPid == pid) {
   1672                 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
   1673                 mAudioSessionRefs.removeAt(i);
   1674                 delete ref;
   1675                 removed = true;
   1676                 num--;
   1677             } else {
   1678                 i++;
   1679             }
   1680         }
   1681         if (removed) {
   1682             removedEffects = purgeStaleEffects_l();
   1683         }
   1684     }
   1685     for (auto& effect : removedEffects) {
   1686         effect->updatePolicyState();
   1687     }
   1688 }
   1689 
   1690 void AudioFlinger::ioConfigChanged(audio_io_config_event event,
   1691                                    const sp<AudioIoDescriptor>& ioDesc,
   1692                                    pid_t pid)
   1693 {
   1694     Mutex::Autolock _l(mClientLock);
   1695     size_t size = mNotificationClients.size();
   1696     for (size_t i = 0; i < size; i++) {
   1697         if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
   1698             mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
   1699         }
   1700     }
   1701 }
   1702 
   1703 // removeClient_l() must be called with AudioFlinger::mClientLock held
   1704 void AudioFlinger::removeClient_l(pid_t pid)
   1705 {
   1706     ALOGV("removeClient_l() pid %d, calling pid %d", pid,
   1707             IPCThreadState::self()->getCallingPid());
   1708     mClients.removeItem(pid);
   1709 }
   1710 
   1711 // getEffectThread_l() must be called with AudioFlinger::mLock held
   1712 sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
   1713         int effectId)
   1714 {
   1715     sp<ThreadBase> thread;
   1716 
   1717     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   1718         if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
   1719             ALOG_ASSERT(thread == 0);
   1720             thread = mPlaybackThreads.valueAt(i);
   1721         }
   1722     }
   1723     if (thread != nullptr) {
   1724         return thread;
   1725     }
   1726     for (size_t i = 0; i < mRecordThreads.size(); i++) {
   1727         if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
   1728             ALOG_ASSERT(thread == 0);
   1729             thread = mRecordThreads.valueAt(i);
   1730         }
   1731     }
   1732     if (thread != nullptr) {
   1733         return thread;
   1734     }
   1735     for (size_t i = 0; i < mMmapThreads.size(); i++) {
   1736         if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
   1737             ALOG_ASSERT(thread == 0);
   1738             thread = mMmapThreads.valueAt(i);
   1739         }
   1740     }
   1741     return thread;
   1742 }
   1743 
   1744 
   1745 
   1746 // ----------------------------------------------------------------------------
   1747 
   1748 AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
   1749     :   RefBase(),
   1750         mAudioFlinger(audioFlinger),
   1751         mPid(pid)
   1752 {
   1753     mMemoryDealer = new MemoryDealer(
   1754             audioFlinger->getClientSharedHeapSize(),
   1755             (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
   1756 }
   1757 
   1758 // Client destructor must be called with AudioFlinger::mClientLock held
   1759 AudioFlinger::Client::~Client()
   1760 {
   1761     mAudioFlinger->removeClient_l(mPid);
   1762 }
   1763 
   1764 sp<MemoryDealer> AudioFlinger::Client::heap() const
   1765 {
   1766     return mMemoryDealer;
   1767 }
   1768 
   1769 // ----------------------------------------------------------------------------
   1770 
   1771 AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
   1772                                                      const sp<IAudioFlingerClient>& client,
   1773                                                      pid_t pid)
   1774     : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
   1775 {
   1776 }
   1777 
   1778 AudioFlinger::NotificationClient::~NotificationClient()
   1779 {
   1780 }
   1781 
   1782 void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
   1783 {
   1784     sp<NotificationClient> keep(this);
   1785     mAudioFlinger->removeNotificationClient(mPid);
   1786 }
   1787 
   1788 // ----------------------------------------------------------------------------
   1789 AudioFlinger::MediaLogNotifier::MediaLogNotifier()
   1790     : mPendingRequests(false) {}
   1791 
   1792 
   1793 void AudioFlinger::MediaLogNotifier::requestMerge() {
   1794     AutoMutex _l(mMutex);
   1795     mPendingRequests = true;
   1796     mCond.signal();
   1797 }
   1798 
   1799 bool AudioFlinger::MediaLogNotifier::threadLoop() {
   1800     // Should already have been checked, but just in case
   1801     if (sMediaLogService == 0) {
   1802         return false;
   1803     }
   1804     // Wait until there are pending requests
   1805     {
   1806         AutoMutex _l(mMutex);
   1807         mPendingRequests = false; // to ignore past requests
   1808         while (!mPendingRequests) {
   1809             mCond.wait(mMutex);
   1810             // TODO may also need an exitPending check
   1811         }
   1812         mPendingRequests = false;
   1813     }
   1814     // Execute the actual MediaLogService binder call and ignore extra requests for a while
   1815     sMediaLogService->requestMergeWakeup();
   1816     usleep(kPostTriggerSleepPeriod);
   1817     return true;
   1818 }
   1819 
   1820 void AudioFlinger::requestLogMerge() {
   1821     mMediaLogNotifier->requestMerge();
   1822 }
   1823 
   1824 // ----------------------------------------------------------------------------
   1825 
   1826 sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
   1827                                                    CreateRecordOutput& output,
   1828                                                    status_t *status)
   1829 {
   1830     sp<RecordThread::RecordTrack> recordTrack;
   1831     sp<RecordHandle> recordHandle;
   1832     sp<Client> client;
   1833     status_t lStatus;
   1834     audio_session_t sessionId = input.sessionId;
   1835     audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
   1836 
   1837     output.cblk.clear();
   1838     output.buffers.clear();
   1839     output.inputId = AUDIO_IO_HANDLE_NONE;
   1840 
   1841     bool updatePid = (input.clientInfo.clientPid == -1);
   1842     const uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1843     uid_t clientUid = input.clientInfo.clientUid;
   1844     if (!isAudioServerOrMediaServerUid(callingUid)) {
   1845         ALOGW_IF(clientUid != callingUid,
   1846                 "%s uid %d tried to pass itself off as %d",
   1847                 __FUNCTION__, callingUid, clientUid);
   1848         clientUid = callingUid;
   1849         updatePid = true;
   1850     }
   1851     pid_t clientPid = input.clientInfo.clientPid;
   1852     const pid_t callingPid = IPCThreadState::self()->getCallingPid();
   1853     if (updatePid) {
   1854         ALOGW_IF(clientPid != -1 && clientPid != callingPid,
   1855                  "%s uid %d pid %d tried to pass itself off as pid %d",
   1856                  __func__, callingUid, callingPid, clientPid);
   1857         clientPid = callingPid;
   1858     }
   1859 
   1860     // we don't yet support anything other than linear PCM
   1861     if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
   1862         ALOGE("createRecord() invalid format %#x", input.config.format);
   1863         lStatus = BAD_VALUE;
   1864         goto Exit;
   1865     }
   1866 
   1867     // further channel mask checks are performed by createRecordTrack_l()
   1868     if (!audio_is_input_channel(input.config.channel_mask)) {
   1869         ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
   1870         lStatus = BAD_VALUE;
   1871         goto Exit;
   1872     }
   1873 
   1874     if (sessionId == AUDIO_SESSION_ALLOCATE) {
   1875         sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
   1876     } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
   1877         lStatus = BAD_VALUE;
   1878         goto Exit;
   1879     }
   1880 
   1881     output.sessionId = sessionId;
   1882     output.selectedDeviceId = input.selectedDeviceId;
   1883     output.flags = input.flags;
   1884 
   1885     client = registerPid(clientPid);
   1886 
   1887     // Not a conventional loop, but a retry loop for at most two iterations total.
   1888     // Try first maybe with FAST flag then try again without FAST flag if that fails.
   1889     // Exits loop via break on no error of got exit on error
   1890     // The sp<> references will be dropped when re-entering scope.
   1891     // The lack of indentation is deliberate, to reduce code churn and ease merges.
   1892     for (;;) {
   1893     // release previously opened input if retrying.
   1894     if (output.inputId != AUDIO_IO_HANDLE_NONE) {
   1895         recordTrack.clear();
   1896         AudioSystem::releaseInput(portId);
   1897         output.inputId = AUDIO_IO_HANDLE_NONE;
   1898         output.selectedDeviceId = input.selectedDeviceId;
   1899         portId = AUDIO_PORT_HANDLE_NONE;
   1900     }
   1901     lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
   1902                                       input.riid,
   1903                                       sessionId,
   1904                                     // FIXME compare to AudioTrack
   1905                                       clientPid,
   1906                                       clientUid,
   1907                                       input.opPackageName,
   1908                                       &input.config,
   1909                                       output.flags, &output.selectedDeviceId, &portId);
   1910     if (lStatus != NO_ERROR) {
   1911         ALOGE("createRecord() getInputForAttr return error %d", lStatus);
   1912         goto Exit;
   1913     }
   1914 
   1915     {
   1916         Mutex::Autolock _l(mLock);
   1917         RecordThread *thread = checkRecordThread_l(output.inputId);
   1918         if (thread == NULL) {
   1919             ALOGE("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
   1920             lStatus = BAD_VALUE;
   1921             goto Exit;
   1922         }
   1923 
   1924         ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
   1925 
   1926         output.sampleRate = input.config.sample_rate;
   1927         output.frameCount = input.frameCount;
   1928         output.notificationFrameCount = input.notificationFrameCount;
   1929 
   1930         recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
   1931                                                   input.config.format, input.config.channel_mask,
   1932                                                   &output.frameCount, sessionId,
   1933                                                   &output.notificationFrameCount,
   1934                                                   callingPid, clientUid, &output.flags,
   1935                                                   input.clientInfo.clientTid,
   1936                                                   &lStatus, portId);
   1937         LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
   1938 
   1939         // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
   1940         // audio policy manager without FAST constraint
   1941         if (lStatus == BAD_TYPE) {
   1942             continue;
   1943         }
   1944 
   1945         if (lStatus != NO_ERROR) {
   1946             goto Exit;
   1947         }
   1948 
   1949         // Check if one effect chain was awaiting for an AudioRecord to be created on this
   1950         // session and move it to this thread.
   1951         sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
   1952         if (chain != 0) {
   1953             Mutex::Autolock _l(thread->mLock);
   1954             thread->addEffectChain_l(chain);
   1955         }
   1956         break;
   1957     }
   1958     // End of retry loop.
   1959     // The lack of indentation is deliberate, to reduce code churn and ease merges.
   1960     }
   1961 
   1962     output.cblk = recordTrack->getCblk();
   1963     output.buffers = recordTrack->getBuffers();
   1964     output.portId = portId;
   1965 
   1966     // return handle to client
   1967     recordHandle = new RecordHandle(recordTrack);
   1968 
   1969 Exit:
   1970     if (lStatus != NO_ERROR) {
   1971         // remove local strong reference to Client before deleting the RecordTrack so that the
   1972         // Client destructor is called by the TrackBase destructor with mClientLock held
   1973         // Don't hold mClientLock when releasing the reference on the track as the
   1974         // destructor will acquire it.
   1975         {
   1976             Mutex::Autolock _cl(mClientLock);
   1977             client.clear();
   1978         }
   1979         recordTrack.clear();
   1980         if (output.inputId != AUDIO_IO_HANDLE_NONE) {
   1981             AudioSystem::releaseInput(portId);
   1982         }
   1983     }
   1984 
   1985     *status = lStatus;
   1986     return recordHandle;
   1987 }
   1988 
   1989 
   1990 
   1991 // ----------------------------------------------------------------------------
   1992 
   1993 audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
   1994 {
   1995     if (name == NULL) {
   1996         return AUDIO_MODULE_HANDLE_NONE;
   1997     }
   1998     if (!settingsAllowed()) {
   1999         return AUDIO_MODULE_HANDLE_NONE;
   2000     }
   2001     Mutex::Autolock _l(mLock);
   2002     return loadHwModule_l(name);
   2003 }
   2004 
   2005 // loadHwModule_l() must be called with AudioFlinger::mLock held
   2006 audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
   2007 {
   2008     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
   2009         if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
   2010             ALOGW("loadHwModule() module %s already loaded", name);
   2011             return mAudioHwDevs.keyAt(i);
   2012         }
   2013     }
   2014 
   2015     sp<DeviceHalInterface> dev;
   2016 
   2017     int rc = mDevicesFactoryHal->openDevice(name, &dev);
   2018     if (rc) {
   2019         ALOGE("loadHwModule() error %d loading module %s", rc, name);
   2020         return AUDIO_MODULE_HANDLE_NONE;
   2021     }
   2022 
   2023     mHardwareStatus = AUDIO_HW_INIT;
   2024     rc = dev->initCheck();
   2025     mHardwareStatus = AUDIO_HW_IDLE;
   2026     if (rc) {
   2027         ALOGE("loadHwModule() init check error %d for module %s", rc, name);
   2028         return AUDIO_MODULE_HANDLE_NONE;
   2029     }
   2030 
   2031     // Check and cache this HAL's level of support for master mute and master
   2032     // volume.  If this is the first HAL opened, and it supports the get
   2033     // methods, use the initial values provided by the HAL as the current
   2034     // master mute and volume settings.
   2035 
   2036     AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
   2037     {  // scope for auto-lock pattern
   2038         AutoMutex lock(mHardwareLock);
   2039 
   2040         if (0 == mAudioHwDevs.size()) {
   2041             mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
   2042             float mv;
   2043             if (OK == dev->getMasterVolume(&mv)) {
   2044                 mMasterVolume = mv;
   2045             }
   2046 
   2047             mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
   2048             bool mm;
   2049             if (OK == dev->getMasterMute(&mm)) {
   2050                 mMasterMute = mm;
   2051             }
   2052         }
   2053 
   2054         mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
   2055         if (OK == dev->setMasterVolume(mMasterVolume)) {
   2056             flags = static_cast<AudioHwDevice::Flags>(flags |
   2057                     AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
   2058         }
   2059 
   2060         mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
   2061         if (OK == dev->setMasterMute(mMasterMute)) {
   2062             flags = static_cast<AudioHwDevice::Flags>(flags |
   2063                     AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
   2064         }
   2065 
   2066         mHardwareStatus = AUDIO_HW_IDLE;
   2067     }
   2068     if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
   2069         // An MSD module is inserted before hardware modules in order to mix encoded streams.
   2070         flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
   2071     }
   2072 
   2073     audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
   2074     mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
   2075 
   2076     ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
   2077 
   2078     return handle;
   2079 
   2080 }
   2081 
   2082 // ----------------------------------------------------------------------------
   2083 
   2084 uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
   2085 {
   2086     Mutex::Autolock _l(mLock);
   2087     PlaybackThread *thread = fastPlaybackThread_l();
   2088     return thread != NULL ? thread->sampleRate() : 0;
   2089 }
   2090 
   2091 size_t AudioFlinger::getPrimaryOutputFrameCount()
   2092 {
   2093     Mutex::Autolock _l(mLock);
   2094     PlaybackThread *thread = fastPlaybackThread_l();
   2095     return thread != NULL ? thread->frameCountHAL() : 0;
   2096 }
   2097 
   2098 // ----------------------------------------------------------------------------
   2099 
   2100 status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
   2101 {
   2102     uid_t uid = IPCThreadState::self()->getCallingUid();
   2103     if (!isAudioServerOrSystemServerUid(uid)) {
   2104         return PERMISSION_DENIED;
   2105     }
   2106     Mutex::Autolock _l(mLock);
   2107     if (mIsDeviceTypeKnown) {
   2108         return INVALID_OPERATION;
   2109     }
   2110     mIsLowRamDevice = isLowRamDevice;
   2111     mTotalMemory = totalMemory;
   2112     // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
   2113     // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
   2114     // mIsLowRamDevice generally represent devices with less than 1GB of memory,
   2115     // though actual setting is determined through device configuration.
   2116     constexpr int64_t GB = 1024 * 1024 * 1024;
   2117     mClientSharedHeapSize =
   2118             isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
   2119                     : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
   2120                     : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
   2121                     : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
   2122                     : 32 * kMinimumClientSharedHeapSizeBytes;
   2123     mIsDeviceTypeKnown = true;
   2124 
   2125     // TODO: Cache the client shared heap size in a persistent property.
   2126     // It's possible that a native process or Java service or app accesses audioserver
   2127     // after it is registered by system server, but before AudioService updates
   2128     // the memory info.  This would occur immediately after boot or an audioserver
   2129     // crash and restore. Before update from AudioService, the client would get the
   2130     // minimum heap size.
   2131 
   2132     ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
   2133             (isLowRamDevice ? "true" : "false"),
   2134             (long long)mTotalMemory,
   2135             mClientSharedHeapSize.load());
   2136     return NO_ERROR;
   2137 }
   2138 
   2139 size_t AudioFlinger::getClientSharedHeapSize() const
   2140 {
   2141     size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
   2142     if (heapSizeInBytes != 0) { // read-only property overrides all.
   2143         return heapSizeInBytes;
   2144     }
   2145     return mClientSharedHeapSize;
   2146 }
   2147 
   2148 status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
   2149 {
   2150     ALOGV(__func__);
   2151 
   2152     audio_module_handle_t module;
   2153     if (config->type == AUDIO_PORT_TYPE_DEVICE) {
   2154         module = config->ext.device.hw_module;
   2155     } else {
   2156         module = config->ext.mix.hw_module;
   2157     }
   2158 
   2159     Mutex::Autolock _l(mLock);
   2160     ssize_t index = mAudioHwDevs.indexOfKey(module);
   2161     if (index < 0) {
   2162         ALOGW("%s() bad hw module %d", __func__, module);
   2163         return BAD_VALUE;
   2164     }
   2165 
   2166     AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
   2167     return audioHwDevice->hwDevice()->setAudioPortConfig(config);
   2168 }
   2169 
   2170 audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
   2171 {
   2172     Mutex::Autolock _l(mLock);
   2173 
   2174     ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
   2175     if (index >= 0) {
   2176         ALOGV("getAudioHwSyncForSession found ID %d for session %d",
   2177               mHwAvSyncIds.valueAt(index), sessionId);
   2178         return mHwAvSyncIds.valueAt(index);
   2179     }
   2180 
   2181     sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
   2182     if (dev == NULL) {
   2183         return AUDIO_HW_SYNC_INVALID;
   2184     }
   2185     String8 reply;
   2186     AudioParameter param;
   2187     if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
   2188         param = AudioParameter(reply);
   2189     }
   2190 
   2191     int value;
   2192     if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
   2193         ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
   2194         return AUDIO_HW_SYNC_INVALID;
   2195     }
   2196 
   2197     // allow only one session for a given HW A/V sync ID.
   2198     for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
   2199         if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
   2200             ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
   2201                   value, mHwAvSyncIds.keyAt(i));
   2202             mHwAvSyncIds.removeItemsAt(i);
   2203             break;
   2204         }
   2205     }
   2206 
   2207     mHwAvSyncIds.add(sessionId, value);
   2208 
   2209     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   2210         sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
   2211         uint32_t sessions = thread->hasAudioSession(sessionId);
   2212         if (sessions & ThreadBase::TRACK_SESSION) {
   2213             AudioParameter param = AudioParameter();
   2214             param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
   2215             String8 keyValuePairs = param.toString();
   2216             thread->setParameters(keyValuePairs);
   2217             forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
   2218                     [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
   2219             break;
   2220         }
   2221     }
   2222 
   2223     ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
   2224     return (audio_hw_sync_t)value;
   2225 }
   2226 
   2227 status_t AudioFlinger::systemReady()
   2228 {
   2229     Mutex::Autolock _l(mLock);
   2230     ALOGI("%s", __FUNCTION__);
   2231     if (mSystemReady) {
   2232         ALOGW("%s called twice", __FUNCTION__);
   2233         return NO_ERROR;
   2234     }
   2235     mSystemReady = true;
   2236     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   2237         ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
   2238         thread->systemReady();
   2239     }
   2240     for (size_t i = 0; i < mRecordThreads.size(); i++) {
   2241         ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
   2242         thread->systemReady();
   2243     }
   2244     return NO_ERROR;
   2245 }
   2246 
   2247 status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
   2248 {
   2249     AutoMutex lock(mHardwareLock);
   2250     sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
   2251     status_t status = dev->getMicrophones(microphones);
   2252     return status;
   2253 }
   2254 
   2255 // setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
   2256 void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
   2257 {
   2258     ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
   2259     if (index >= 0) {
   2260         audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
   2261         ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
   2262         AudioParameter param = AudioParameter();
   2263         param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
   2264         String8 keyValuePairs = param.toString();
   2265         thread->setParameters(keyValuePairs);
   2266         forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
   2267                 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
   2268     }
   2269 }
   2270 
   2271 
   2272 // ----------------------------------------------------------------------------
   2273 
   2274 
   2275 sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
   2276                                                             audio_io_handle_t *output,
   2277                                                             audio_config_t *config,
   2278                                                             audio_devices_t devices,
   2279                                                             const String8& address,
   2280                                                             audio_output_flags_t flags)
   2281 {
   2282     AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
   2283     if (outHwDev == NULL) {
   2284         return 0;
   2285     }
   2286 
   2287     if (*output == AUDIO_IO_HANDLE_NONE) {
   2288         *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
   2289     } else {
   2290         // Audio Policy does not currently request a specific output handle.
   2291         // If this is ever needed, see openInput_l() for example code.
   2292         ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
   2293         return 0;
   2294     }
   2295 
   2296     mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
   2297 
   2298     // FOR TESTING ONLY:
   2299     // This if statement allows overriding the audio policy settings
   2300     // and forcing a specific format or channel mask to the HAL/Sink device for testing.
   2301     if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
   2302         // Check only for Normal Mixing mode
   2303         if (kEnableExtendedPrecision) {
   2304             // Specify format (uncomment one below to choose)
   2305             //config->format = AUDIO_FORMAT_PCM_FLOAT;
   2306             //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
   2307             //config->format = AUDIO_FORMAT_PCM_32_BIT;
   2308             //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
   2309             // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
   2310         }
   2311         if (kEnableExtendedChannels) {
   2312             // Specify channel mask (uncomment one below to choose)
   2313             //config->channel_mask = audio_channel_out_mask_from_count(4);  // for USB 4ch
   2314             //config->channel_mask = audio_channel_mask_from_representation_and_bits(
   2315             //        AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1);  // another 4ch example
   2316         }
   2317     }
   2318 
   2319     AudioStreamOut *outputStream = NULL;
   2320     status_t status = outHwDev->openOutputStream(
   2321             &outputStream,
   2322             *output,
   2323             devices,
   2324             flags,
   2325             config,
   2326             address.string());
   2327 
   2328     mHardwareStatus = AUDIO_HW_IDLE;
   2329 
   2330     if (status == NO_ERROR) {
   2331         if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
   2332             sp<MmapPlaybackThread> thread =
   2333                     new MmapPlaybackThread(this, *output, outHwDev, outputStream,
   2334                                           devices, AUDIO_DEVICE_NONE, mSystemReady);
   2335             mMmapThreads.add(*output, thread);
   2336             ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
   2337                   *output, thread.get());
   2338             return thread;
   2339         } else {
   2340             sp<PlaybackThread> thread;
   2341             if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
   2342                 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
   2343                 ALOGV("openOutput_l() created offload output: ID %d thread %p",
   2344                       *output, thread.get());
   2345             } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
   2346                     || !isValidPcmSinkFormat(config->format)
   2347                     || !isValidPcmSinkChannelMask(config->channel_mask)) {
   2348                 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
   2349                 ALOGV("openOutput_l() created direct output: ID %d thread %p",
   2350                       *output, thread.get());
   2351             } else {
   2352                 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
   2353                 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
   2354                       *output, thread.get());
   2355             }
   2356             mPlaybackThreads.add(*output, thread);
   2357             mPatchPanel.notifyStreamOpened(outHwDev, *output);
   2358             return thread;
   2359         }
   2360     }
   2361 
   2362     return 0;
   2363 }
   2364 
   2365 status_t AudioFlinger::openOutput(audio_module_handle_t module,
   2366                                   audio_io_handle_t *output,
   2367                                   audio_config_t *config,
   2368                                   audio_devices_t *devices,
   2369                                   const String8& address,
   2370                                   uint32_t *latencyMs,
   2371                                   audio_output_flags_t flags)
   2372 {
   2373     ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
   2374               "Channels %#x, flags %#x",
   2375               this, module,
   2376               (devices != NULL) ? *devices : 0,
   2377               config->sample_rate,
   2378               config->format,
   2379               config->channel_mask,
   2380               flags);
   2381 
   2382     if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
   2383         return BAD_VALUE;
   2384     }
   2385 
   2386     Mutex::Autolock _l(mLock);
   2387 
   2388     sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
   2389     if (thread != 0) {
   2390         if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
   2391             PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
   2392             *latencyMs = playbackThread->latency();
   2393 
   2394             // notify client processes of the new output creation
   2395             playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
   2396 
   2397             // the first primary output opened designates the primary hw device
   2398             if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
   2399                 ALOGI("Using module %d as the primary audio interface", module);
   2400                 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
   2401 
   2402                 AutoMutex lock(mHardwareLock);
   2403                 mHardwareStatus = AUDIO_HW_SET_MODE;
   2404                 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
   2405                 mHardwareStatus = AUDIO_HW_IDLE;
   2406             }
   2407         } else {
   2408             MmapThread *mmapThread = (MmapThread *)thread.get();
   2409             mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
   2410         }
   2411         return NO_ERROR;
   2412     }
   2413 
   2414     return NO_INIT;
   2415 }
   2416 
   2417 audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
   2418         audio_io_handle_t output2)
   2419 {
   2420     Mutex::Autolock _l(mLock);
   2421     MixerThread *thread1 = checkMixerThread_l(output1);
   2422     MixerThread *thread2 = checkMixerThread_l(output2);
   2423 
   2424     if (thread1 == NULL || thread2 == NULL) {
   2425         ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
   2426                 output2);
   2427         return AUDIO_IO_HANDLE_NONE;
   2428     }
   2429 
   2430     audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
   2431     DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
   2432     thread->addOutputTrack(thread2);
   2433     mPlaybackThreads.add(id, thread);
   2434     // notify client processes of the new output creation
   2435     thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
   2436     return id;
   2437 }
   2438 
   2439 status_t AudioFlinger::closeOutput(audio_io_handle_t output)
   2440 {
   2441     return closeOutput_nonvirtual(output);
   2442 }
   2443 
   2444 status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
   2445 {
   2446     // keep strong reference on the playback thread so that
   2447     // it is not destroyed while exit() is executed
   2448     sp<PlaybackThread> playbackThread;
   2449     sp<MmapPlaybackThread> mmapThread;
   2450     {
   2451         Mutex::Autolock _l(mLock);
   2452         playbackThread = checkPlaybackThread_l(output);
   2453         if (playbackThread != NULL) {
   2454             ALOGV("closeOutput() %d", output);
   2455 
   2456             dumpToThreadLog_l(playbackThread);
   2457 
   2458             if (playbackThread->type() == ThreadBase::MIXER) {
   2459                 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   2460                     if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
   2461                         DuplicatingThread *dupThread =
   2462                                 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
   2463                         dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
   2464                     }
   2465                 }
   2466             }
   2467 
   2468 
   2469             mPlaybackThreads.removeItem(output);
   2470             // save all effects to the default thread
   2471             if (mPlaybackThreads.size()) {
   2472                 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
   2473                 if (dstThread != NULL) {
   2474                     // audioflinger lock is held so order of thread lock acquisition doesn't matter
   2475                     Mutex::Autolock _dl(dstThread->mLock);
   2476                     Mutex::Autolock _sl(playbackThread->mLock);
   2477                     Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
   2478                     for (size_t i = 0; i < effectChains.size(); i ++) {
   2479                         moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
   2480                                 dstThread);
   2481                     }
   2482                 }
   2483             }
   2484         } else {
   2485             mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
   2486             if (mmapThread == 0) {
   2487                 return BAD_VALUE;
   2488             }
   2489             dumpToThreadLog_l(mmapThread);
   2490             mMmapThreads.removeItem(output);
   2491             ALOGD("closing mmapThread %p", mmapThread.get());
   2492         }
   2493         const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
   2494         ioDesc->mIoHandle = output;
   2495         ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
   2496         mPatchPanel.notifyStreamClosed(output);
   2497     }
   2498     // The thread entity (active unit of execution) is no longer running here,
   2499     // but the ThreadBase container still exists.
   2500 
   2501     if (playbackThread != 0) {
   2502         playbackThread->exit();
   2503         if (!playbackThread->isDuplicating()) {
   2504             closeOutputFinish(playbackThread);
   2505         }
   2506     } else if (mmapThread != 0) {
   2507         ALOGD("mmapThread exit()");
   2508         mmapThread->exit();
   2509         AudioStreamOut *out = mmapThread->clearOutput();
   2510         ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
   2511         // from now on thread->mOutput is NULL
   2512         delete out;
   2513     }
   2514     return NO_ERROR;
   2515 }
   2516 
   2517 void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
   2518 {
   2519     AudioStreamOut *out = thread->clearOutput();
   2520     ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
   2521     // from now on thread->mOutput is NULL
   2522     delete out;
   2523 }
   2524 
   2525 void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
   2526 {
   2527     mPlaybackThreads.removeItem(thread->mId);
   2528     thread->exit();
   2529     closeOutputFinish(thread);
   2530 }
   2531 
   2532 status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
   2533 {
   2534     Mutex::Autolock _l(mLock);
   2535     PlaybackThread *thread = checkPlaybackThread_l(output);
   2536 
   2537     if (thread == NULL) {
   2538         return BAD_VALUE;
   2539     }
   2540 
   2541     ALOGV("suspendOutput() %d", output);
   2542     thread->suspend();
   2543 
   2544     return NO_ERROR;
   2545 }
   2546 
   2547 status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
   2548 {
   2549     Mutex::Autolock _l(mLock);
   2550     PlaybackThread *thread = checkPlaybackThread_l(output);
   2551 
   2552     if (thread == NULL) {
   2553         return BAD_VALUE;
   2554     }
   2555 
   2556     ALOGV("restoreOutput() %d", output);
   2557 
   2558     thread->restore();
   2559 
   2560     return NO_ERROR;
   2561 }
   2562 
   2563 status_t AudioFlinger::openInput(audio_module_handle_t module,
   2564                                           audio_io_handle_t *input,
   2565                                           audio_config_t *config,
   2566                                           audio_devices_t *devices,
   2567                                           const String8& address,
   2568                                           audio_source_t source,
   2569                                           audio_input_flags_t flags)
   2570 {
   2571     Mutex::Autolock _l(mLock);
   2572 
   2573     if (*devices == AUDIO_DEVICE_NONE) {
   2574         return BAD_VALUE;
   2575     }
   2576 
   2577     sp<ThreadBase> thread = openInput_l(
   2578             module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
   2579 
   2580     if (thread != 0) {
   2581         // notify client processes of the new input creation
   2582         thread->ioConfigChanged(AUDIO_INPUT_OPENED);
   2583         return NO_ERROR;
   2584     }
   2585     return NO_INIT;
   2586 }
   2587 
   2588 sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
   2589                                                          audio_io_handle_t *input,
   2590                                                          audio_config_t *config,
   2591                                                          audio_devices_t devices,
   2592                                                          const String8& address,
   2593                                                          audio_source_t source,
   2594                                                          audio_input_flags_t flags,
   2595                                                          audio_devices_t outputDevice,
   2596                                                          const String8& outputDeviceAddress)
   2597 {
   2598     AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
   2599     if (inHwDev == NULL) {
   2600         *input = AUDIO_IO_HANDLE_NONE;
   2601         return 0;
   2602     }
   2603 
   2604     // Some flags are specific to framework and must not leak to the HAL.
   2605     flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FRAMEWORK_FLAGS);
   2606 
   2607     // Audio Policy can request a specific handle for hardware hotword.
   2608     // The goal here is not to re-open an already opened input.
   2609     // It is to use a pre-assigned I/O handle.
   2610     if (*input == AUDIO_IO_HANDLE_NONE) {
   2611         *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
   2612     } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
   2613         ALOGE("openInput_l() requested input handle %d is invalid", *input);
   2614         return 0;
   2615     } else if (mRecordThreads.indexOfKey(*input) >= 0) {
   2616         // This should not happen in a transient state with current design.
   2617         ALOGE("openInput_l() requested input handle %d is already assigned", *input);
   2618         return 0;
   2619     }
   2620 
   2621     audio_config_t halconfig = *config;
   2622     sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
   2623     sp<StreamInHalInterface> inStream;
   2624     status_t status = inHwHal->openInputStream(
   2625             *input, devices, &halconfig, flags, address.string(), source,
   2626             outputDevice, outputDeviceAddress, &inStream);
   2627     ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
   2628            ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
   2629             inStream.get(),
   2630             devices,
   2631             halconfig.sample_rate,
   2632             halconfig.format,
   2633             halconfig.channel_mask,
   2634             flags,
   2635             status, address.string());
   2636 
   2637     // If the input could not be opened with the requested parameters and we can handle the
   2638     // conversion internally, try to open again with the proposed parameters.
   2639     if (status == BAD_VALUE &&
   2640         audio_is_linear_pcm(config->format) &&
   2641         audio_is_linear_pcm(halconfig.format) &&
   2642         (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
   2643         (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
   2644         (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
   2645         // FIXME describe the change proposed by HAL (save old values so we can log them here)
   2646         ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
   2647         inStream.clear();
   2648         status = inHwHal->openInputStream(
   2649                 *input, devices, &halconfig, flags, address.string(), source,
   2650                 outputDevice, outputDeviceAddress, &inStream);
   2651         // FIXME log this new status; HAL should not propose any further changes
   2652     }
   2653 
   2654     if (status == NO_ERROR && inStream != 0) {
   2655         AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
   2656         if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
   2657             sp<MmapCaptureThread> thread =
   2658                     new MmapCaptureThread(this, *input,
   2659                                           inHwDev, inputStream,
   2660                                           primaryOutputDevice_l(), devices, mSystemReady);
   2661             mMmapThreads.add(*input, thread);
   2662             ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
   2663                     thread.get());
   2664             return thread;
   2665         } else {
   2666             // Start record thread
   2667             // RecordThread requires both input and output device indication to forward to audio
   2668             // pre processing modules
   2669             sp<RecordThread> thread = new RecordThread(this,
   2670                                       inputStream,
   2671                                       *input,
   2672                                       primaryOutputDevice_l(),
   2673                                       devices,
   2674                                       mSystemReady
   2675                                       );
   2676             mRecordThreads.add(*input, thread);
   2677             ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
   2678             return thread;
   2679         }
   2680     }
   2681 
   2682     *input = AUDIO_IO_HANDLE_NONE;
   2683     return 0;
   2684 }
   2685 
   2686 status_t AudioFlinger::closeInput(audio_io_handle_t input)
   2687 {
   2688     return closeInput_nonvirtual(input);
   2689 }
   2690 
   2691 status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
   2692 {
   2693     // keep strong reference on the record thread so that
   2694     // it is not destroyed while exit() is executed
   2695     sp<RecordThread> recordThread;
   2696     sp<MmapCaptureThread> mmapThread;
   2697     {
   2698         Mutex::Autolock _l(mLock);
   2699         recordThread = checkRecordThread_l(input);
   2700         if (recordThread != 0) {
   2701             ALOGV("closeInput() %d", input);
   2702 
   2703             dumpToThreadLog_l(recordThread);
   2704 
   2705             // If we still have effect chains, it means that a client still holds a handle
   2706             // on at least one effect. We must either move the chain to an existing thread with the
   2707             // same session ID or put it aside in case a new record thread is opened for a
   2708             // new capture on the same session
   2709             sp<EffectChain> chain;
   2710             {
   2711                 Mutex::Autolock _sl(recordThread->mLock);
   2712                 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
   2713                 // Note: maximum one chain per record thread
   2714                 if (effectChains.size() != 0) {
   2715                     chain = effectChains[0];
   2716                 }
   2717             }
   2718             if (chain != 0) {
   2719                 // first check if a record thread is already opened with a client on same session.
   2720                 // This should only happen in case of overlap between one thread tear down and the
   2721                 // creation of its replacement
   2722                 size_t i;
   2723                 for (i = 0; i < mRecordThreads.size(); i++) {
   2724                     sp<RecordThread> t = mRecordThreads.valueAt(i);
   2725                     if (t == recordThread) {
   2726                         continue;
   2727                     }
   2728                     if (t->hasAudioSession(chain->sessionId()) != 0) {
   2729                         Mutex::Autolock _l(t->mLock);
   2730                         ALOGV("closeInput() found thread %d for effect session %d",
   2731                               t->id(), chain->sessionId());
   2732                         t->addEffectChain_l(chain);
   2733                         break;
   2734                     }
   2735                 }
   2736                 // put the chain aside if we could not find a record thread with the same session id
   2737                 if (i == mRecordThreads.size()) {
   2738                     putOrphanEffectChain_l(chain);
   2739                 }
   2740             }
   2741             mRecordThreads.removeItem(input);
   2742         } else {
   2743             mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
   2744             if (mmapThread == 0) {
   2745                 return BAD_VALUE;
   2746             }
   2747             dumpToThreadLog_l(mmapThread);
   2748             mMmapThreads.removeItem(input);
   2749         }
   2750         const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
   2751         ioDesc->mIoHandle = input;
   2752         ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
   2753     }
   2754     // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
   2755     // we have a different lock for notification client
   2756     if (recordThread != 0) {
   2757         closeInputFinish(recordThread);
   2758     } else if (mmapThread != 0) {
   2759         mmapThread->exit();
   2760         AudioStreamIn *in = mmapThread->clearInput();
   2761         ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
   2762         // from now on thread->mInput is NULL
   2763         delete in;
   2764     }
   2765     return NO_ERROR;
   2766 }
   2767 
   2768 void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
   2769 {
   2770     thread->exit();
   2771     AudioStreamIn *in = thread->clearInput();
   2772     ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
   2773     // from now on thread->mInput is NULL
   2774     delete in;
   2775 }
   2776 
   2777 void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
   2778 {
   2779     mRecordThreads.removeItem(thread->mId);
   2780     closeInputFinish(thread);
   2781 }
   2782 
   2783 status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
   2784 {
   2785     Mutex::Autolock _l(mLock);
   2786     ALOGV("invalidateStream() stream %d", stream);
   2787 
   2788     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   2789         PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
   2790         thread->invalidateTracks(stream);
   2791     }
   2792     for (size_t i = 0; i < mMmapThreads.size(); i++) {
   2793         mMmapThreads[i]->invalidateTracks(stream);
   2794     }
   2795     return NO_ERROR;
   2796 }
   2797 
   2798 
   2799 audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
   2800 {
   2801     // This is a binder API, so a malicious client could pass in a bad parameter.
   2802     // Check for that before calling the internal API nextUniqueId().
   2803     if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
   2804         ALOGE("newAudioUniqueId invalid use %d", use);
   2805         return AUDIO_UNIQUE_ID_ALLOCATE;
   2806     }
   2807     return nextUniqueId(use);
   2808 }
   2809 
   2810 void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
   2811 {
   2812     Mutex::Autolock _l(mLock);
   2813     pid_t caller = IPCThreadState::self()->getCallingPid();
   2814     ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
   2815     const uid_t callerUid = IPCThreadState::self()->getCallingUid();
   2816     if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
   2817         caller = pid;
   2818     }
   2819 
   2820     {
   2821         Mutex::Autolock _cl(mClientLock);
   2822         // Ignore requests received from processes not known as notification client. The request
   2823         // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
   2824         // called from a different pid leaving a stale session reference.  Also we don't know how
   2825         // to clear this reference if the client process dies.
   2826         if (mNotificationClients.indexOfKey(caller) < 0) {
   2827             ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
   2828             return;
   2829         }
   2830     }
   2831 
   2832     size_t num = mAudioSessionRefs.size();
   2833     for (size_t i = 0; i < num; i++) {
   2834         AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
   2835         if (ref->mSessionid == audioSession && ref->mPid == caller) {
   2836             ref->mCnt++;
   2837             ALOGV(" incremented refcount to %d", ref->mCnt);
   2838             return;
   2839         }
   2840     }
   2841     mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
   2842     ALOGV(" added new entry for %d", audioSession);
   2843 }
   2844 
   2845 void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
   2846 {
   2847     std::vector< sp<EffectModule> > removedEffects;
   2848     {
   2849         Mutex::Autolock _l(mLock);
   2850         pid_t caller = IPCThreadState::self()->getCallingPid();
   2851         ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
   2852         const uid_t callerUid = IPCThreadState::self()->getCallingUid();
   2853         if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
   2854             caller = pid;
   2855         }
   2856         size_t num = mAudioSessionRefs.size();
   2857         for (size_t i = 0; i < num; i++) {
   2858             AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
   2859             if (ref->mSessionid == audioSession && ref->mPid == caller) {
   2860                 ref->mCnt--;
   2861                 ALOGV(" decremented refcount to %d", ref->mCnt);
   2862                 if (ref->mCnt == 0) {
   2863                     mAudioSessionRefs.removeAt(i);
   2864                     delete ref;
   2865                     std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
   2866                     removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
   2867                 }
   2868                 goto Exit;
   2869             }
   2870         }
   2871         // If the caller is audioserver it is likely that the session being released was acquired
   2872         // on behalf of a process not in notification clients and we ignore the warning.
   2873         ALOGW_IF(!isAudioServerUid(callerUid),
   2874                  "session id %d not found for pid %d", audioSession, caller);
   2875     }
   2876 
   2877 Exit:
   2878     for (auto& effect : removedEffects) {
   2879         effect->updatePolicyState();
   2880     }
   2881 }
   2882 
   2883 bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
   2884 {
   2885     size_t num = mAudioSessionRefs.size();
   2886     for (size_t i = 0; i < num; i++) {
   2887         AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
   2888         if (ref->mSessionid == audioSession) {
   2889             return true;
   2890         }
   2891     }
   2892     return false;
   2893 }
   2894 
   2895 std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
   2896 
   2897     ALOGV("purging stale effects");
   2898 
   2899     Vector< sp<EffectChain> > chains;
   2900     std::vector< sp<EffectModule> > removedEffects;
   2901 
   2902     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   2903         sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
   2904         Mutex::Autolock _l(t->mLock);
   2905         for (size_t j = 0; j < t->mEffectChains.size(); j++) {
   2906             sp<EffectChain> ec = t->mEffectChains[j];
   2907             if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
   2908                 chains.push(ec);
   2909             }
   2910         }
   2911     }
   2912 
   2913     for (size_t i = 0; i < mRecordThreads.size(); i++) {
   2914         sp<RecordThread> t = mRecordThreads.valueAt(i);
   2915         Mutex::Autolock _l(t->mLock);
   2916         for (size_t j = 0; j < t->mEffectChains.size(); j++) {
   2917             sp<EffectChain> ec = t->mEffectChains[j];
   2918             chains.push(ec);
   2919         }
   2920     }
   2921 
   2922     for (size_t i = 0; i < mMmapThreads.size(); i++) {
   2923         sp<MmapThread> t = mMmapThreads.valueAt(i);
   2924         Mutex::Autolock _l(t->mLock);
   2925         for (size_t j = 0; j < t->mEffectChains.size(); j++) {
   2926             sp<EffectChain> ec = t->mEffectChains[j];
   2927             chains.push(ec);
   2928         }
   2929     }
   2930 
   2931     for (size_t i = 0; i < chains.size(); i++) {
   2932         sp<EffectChain> ec = chains[i];
   2933         int sessionid = ec->sessionId();
   2934         sp<ThreadBase> t = ec->mThread.promote();
   2935         if (t == 0) {
   2936             continue;
   2937         }
   2938         size_t numsessionrefs = mAudioSessionRefs.size();
   2939         bool found = false;
   2940         for (size_t k = 0; k < numsessionrefs; k++) {
   2941             AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
   2942             if (ref->mSessionid == sessionid) {
   2943                 ALOGV(" session %d still exists for %d with %d refs",
   2944                     sessionid, ref->mPid, ref->mCnt);
   2945                 found = true;
   2946                 break;
   2947             }
   2948         }
   2949         if (!found) {
   2950             Mutex::Autolock _l(t->mLock);
   2951             // remove all effects from the chain
   2952             while (ec->mEffects.size()) {
   2953                 sp<EffectModule> effect = ec->mEffects[0];
   2954                 effect->unPin();
   2955                 t->removeEffect_l(effect, /*release*/ true);
   2956                 if (effect->purgeHandles()) {
   2957                     t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
   2958                 }
   2959                 removedEffects.push_back(effect);
   2960             }
   2961         }
   2962     }
   2963     return removedEffects;
   2964 }
   2965 
   2966 // dumpToThreadLog_l() must be called with AudioFlinger::mLock held
   2967 void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
   2968 {
   2969     audio_utils::FdToString fdToString;
   2970     const int fd = fdToString.fd();
   2971     if (fd >= 0) {
   2972         thread->dump(fd, {} /* args */);
   2973         mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
   2974     }
   2975 }
   2976 
   2977 // checkThread_l() must be called with AudioFlinger::mLock held
   2978 AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
   2979 {
   2980     ThreadBase *thread = checkMmapThread_l(ioHandle);
   2981     if (thread == 0) {
   2982         switch (audio_unique_id_get_use(ioHandle)) {
   2983         case AUDIO_UNIQUE_ID_USE_OUTPUT:
   2984             thread = checkPlaybackThread_l(ioHandle);
   2985             break;
   2986         case AUDIO_UNIQUE_ID_USE_INPUT:
   2987             thread = checkRecordThread_l(ioHandle);
   2988             break;
   2989         default:
   2990             break;
   2991         }
   2992     }
   2993     return thread;
   2994 }
   2995 
   2996 // checkPlaybackThread_l() must be called with AudioFlinger::mLock held
   2997 AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
   2998 {
   2999     return mPlaybackThreads.valueFor(output).get();
   3000 }
   3001 
   3002 // checkMixerThread_l() must be called with AudioFlinger::mLock held
   3003 AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
   3004 {
   3005     PlaybackThread *thread = checkPlaybackThread_l(output);
   3006     return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
   3007 }
   3008 
   3009 // checkRecordThread_l() must be called with AudioFlinger::mLock held
   3010 AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
   3011 {
   3012     return mRecordThreads.valueFor(input).get();
   3013 }
   3014 
   3015 // checkMmapThread_l() must be called with AudioFlinger::mLock held
   3016 AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
   3017 {
   3018     return mMmapThreads.valueFor(io).get();
   3019 }
   3020 
   3021 
   3022 // checkPlaybackThread_l() must be called with AudioFlinger::mLock held
   3023 AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
   3024 {
   3025     VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
   3026     if (volumeInterface == nullptr) {
   3027         MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
   3028         if (mmapThread != nullptr) {
   3029             if (mmapThread->isOutput()) {
   3030                 MmapPlaybackThread *mmapPlaybackThread =
   3031                         static_cast<MmapPlaybackThread *>(mmapThread);
   3032                 volumeInterface = mmapPlaybackThread;
   3033             }
   3034         }
   3035     }
   3036     return volumeInterface;
   3037 }
   3038 
   3039 Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
   3040 {
   3041     Vector <VolumeInterface *> volumeInterfaces;
   3042     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   3043         volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
   3044     }
   3045     for (size_t i = 0; i < mMmapThreads.size(); i++) {
   3046         if (mMmapThreads.valueAt(i)->isOutput()) {
   3047             MmapPlaybackThread *mmapPlaybackThread =
   3048                     static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
   3049             volumeInterfaces.add(mmapPlaybackThread);
   3050         }
   3051     }
   3052     return volumeInterfaces;
   3053 }
   3054 
   3055 audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
   3056 {
   3057     // This is the internal API, so it is OK to assert on bad parameter.
   3058     LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
   3059     const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
   3060     for (int retry = 0; retry < maxRetries; retry++) {
   3061         // The cast allows wraparound from max positive to min negative instead of abort
   3062         uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
   3063                 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
   3064         ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
   3065         // allow wrap by skipping 0 and -1 for session ids
   3066         if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
   3067             ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
   3068             return (audio_unique_id_t) (base | use);
   3069         }
   3070     }
   3071     // We have no way of recovering from wraparound
   3072     LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
   3073     // TODO Use a floor after wraparound.  This may need a mutex.
   3074 }
   3075 
   3076 AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
   3077 {
   3078     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   3079         PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
   3080         if(thread->isDuplicating()) {
   3081             continue;
   3082         }
   3083         AudioStreamOut *output = thread->getOutput();
   3084         if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
   3085             return thread;
   3086         }
   3087     }
   3088     return NULL;
   3089 }
   3090 
   3091 audio_devices_t AudioFlinger::primaryOutputDevice_l() const
   3092 {
   3093     PlaybackThread *thread = primaryPlaybackThread_l();
   3094 
   3095     if (thread == NULL) {
   3096         return 0;
   3097     }
   3098 
   3099     return thread->outDevice();
   3100 }
   3101 
   3102 AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
   3103 {
   3104     size_t minFrameCount = 0;
   3105     PlaybackThread *minThread = NULL;
   3106     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   3107         PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
   3108         if (!thread->isDuplicating()) {
   3109             size_t frameCount = thread->frameCountHAL();
   3110             if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
   3111                     (frameCount == minFrameCount && thread->hasFastMixer() &&
   3112                     /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
   3113                 minFrameCount = frameCount;
   3114                 minThread = thread;
   3115             }
   3116         }
   3117     }
   3118     return minThread;
   3119 }
   3120 
   3121 sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
   3122                                     audio_session_t triggerSession,
   3123                                     audio_session_t listenerSession,
   3124                                     sync_event_callback_t callBack,
   3125                                     const wp<RefBase>& cookie)
   3126 {
   3127     Mutex::Autolock _l(mLock);
   3128 
   3129     sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
   3130     status_t playStatus = NAME_NOT_FOUND;
   3131     status_t recStatus = NAME_NOT_FOUND;
   3132     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   3133         playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
   3134         if (playStatus == NO_ERROR) {
   3135             return event;
   3136         }
   3137     }
   3138     for (size_t i = 0; i < mRecordThreads.size(); i++) {
   3139         recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
   3140         if (recStatus == NO_ERROR) {
   3141             return event;
   3142         }
   3143     }
   3144     if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
   3145         mPendingSyncEvents.add(event);
   3146     } else {
   3147         ALOGV("createSyncEvent() invalid event %d", event->type());
   3148         event.clear();
   3149     }
   3150     return event;
   3151 }
   3152 
   3153 // ----------------------------------------------------------------------------
   3154 //  Effect management
   3155 // ----------------------------------------------------------------------------
   3156 
   3157 sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
   3158     return mEffectsFactoryHal;
   3159 }
   3160 
   3161 status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
   3162 {
   3163     Mutex::Autolock _l(mLock);
   3164     if (mEffectsFactoryHal.get()) {
   3165         return mEffectsFactoryHal->queryNumberEffects(numEffects);
   3166     } else {
   3167         return -ENODEV;
   3168     }
   3169 }
   3170 
   3171 status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
   3172 {
   3173     Mutex::Autolock _l(mLock);
   3174     if (mEffectsFactoryHal.get()) {
   3175         return mEffectsFactoryHal->getDescriptor(index, descriptor);
   3176     } else {
   3177         return -ENODEV;
   3178     }
   3179 }
   3180 
   3181 status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
   3182                                            const effect_uuid_t *pTypeUuid,
   3183                                            uint32_t preferredTypeFlag,
   3184                                            effect_descriptor_t *descriptor) const
   3185 {
   3186     if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
   3187         return BAD_VALUE;
   3188     }
   3189 
   3190     Mutex::Autolock _l(mLock);
   3191 
   3192     if (!mEffectsFactoryHal.get()) {
   3193         return -ENODEV;
   3194     }
   3195 
   3196     status_t status = NO_ERROR;
   3197     if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
   3198         // If uuid is specified, request effect descriptor from that.
   3199         status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
   3200     } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
   3201         // If uuid is not specified, look for an available implementation
   3202         // of the required type instead.
   3203 
   3204         // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
   3205         effect_descriptor_t desc;
   3206         desc.flags = 0; // prevent compiler warning
   3207 
   3208         uint32_t numEffects = 0;
   3209         status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
   3210         if (status < 0) {
   3211             ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
   3212             return status;
   3213         }
   3214 
   3215         bool found = false;
   3216         for (uint32_t i = 0; i < numEffects; i++) {
   3217             status = mEffectsFactoryHal->getDescriptor(i, &desc);
   3218             if (status < 0) {
   3219                 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
   3220                 continue;
   3221             }
   3222             if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
   3223                 // If matching type found save effect descriptor.
   3224                 found = true;
   3225                 *descriptor = desc;
   3226 
   3227                 // If there's no preferred flag or this descriptor matches the preferred
   3228                 // flag, success! If this descriptor doesn't match the preferred
   3229                 // flag, continue enumeration in case a better matching version of this
   3230                 // effect type is available. Note that this means if no effect with a
   3231                 // correct flag is found, the descriptor returned will correspond to the
   3232                 // last effect that at least had a matching type uuid (if any).
   3233                 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
   3234                     (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
   3235                     break;
   3236                 }
   3237             }
   3238         }
   3239 
   3240         if (!found) {
   3241             status = NAME_NOT_FOUND;
   3242             ALOGW("getEffectDescriptor(): Effect not found by type.");
   3243         }
   3244     } else {
   3245         status = BAD_VALUE;
   3246         ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
   3247     }
   3248     return status;
   3249 }
   3250 
   3251 sp<IEffect> AudioFlinger::createEffect(
   3252         effect_descriptor_t *pDesc,
   3253         const sp<IEffectClient>& effectClient,
   3254         int32_t priority,
   3255         audio_io_handle_t io,
   3256         audio_session_t sessionId,
   3257         const String16& opPackageName,
   3258         pid_t pid,
   3259         status_t *status,
   3260         int *id,
   3261         int *enabled)
   3262 {
   3263     status_t lStatus = NO_ERROR;
   3264     sp<EffectHandle> handle;
   3265     effect_descriptor_t desc;
   3266 
   3267     const uid_t callingUid = IPCThreadState::self()->getCallingUid();
   3268     if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
   3269         const pid_t callingPid = IPCThreadState::self()->getCallingPid();
   3270         ALOGW_IF(pid != -1 && pid != callingPid,
   3271                  "%s uid %d pid %d tried to pass itself off as pid %d",
   3272                  __func__, callingUid, callingPid, pid);
   3273         pid = callingPid;
   3274     }
   3275 
   3276     ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
   3277             pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
   3278 
   3279     if (pDesc == NULL) {
   3280         lStatus = BAD_VALUE;
   3281         goto Exit;
   3282     }
   3283 
   3284     if (mEffectsFactoryHal == 0) {
   3285         ALOGE("%s: no effects factory hal", __func__);
   3286         lStatus = NO_INIT;
   3287         goto Exit;
   3288     }
   3289 
   3290     // check audio settings permission for global effects
   3291     if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
   3292         if (!settingsAllowed()) {
   3293             ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
   3294             lStatus = PERMISSION_DENIED;
   3295             goto Exit;
   3296         }
   3297     } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
   3298         if (!isAudioServerUid(callingUid)) {
   3299             ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
   3300             lStatus = PERMISSION_DENIED;
   3301             goto Exit;
   3302         }
   3303 
   3304         if (io == AUDIO_IO_HANDLE_NONE) {
   3305             ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
   3306             lStatus = BAD_VALUE;
   3307             goto Exit;
   3308         }
   3309     } else {
   3310         // general sessionId.
   3311 
   3312         if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
   3313             ALOGE("%s: invalid sessionId %d", __func__, sessionId);
   3314             lStatus = BAD_VALUE;
   3315             goto Exit;
   3316         }
   3317 
   3318         // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
   3319         // to prevent creating an effect when one doesn't actually have track with that session?
   3320     }
   3321 
   3322     {
   3323         // Get the full effect descriptor from the uuid/type.
   3324         // If the session is the output mix, prefer an auxiliary effect,
   3325         // otherwise no preference.
   3326         uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
   3327                                   EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
   3328         lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
   3329         if (lStatus < 0) {
   3330             ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
   3331             goto Exit;
   3332         }
   3333 
   3334         // Do not allow auxiliary effects on a session different from 0 (output mix)
   3335         if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
   3336              (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
   3337             lStatus = INVALID_OPERATION;
   3338             goto Exit;
   3339         }
   3340 
   3341         // check recording permission for visualizer
   3342         if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
   3343             // TODO: Do we need to start/stop op - i.e. is there recording being performed?
   3344             !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
   3345             lStatus = PERMISSION_DENIED;
   3346             goto Exit;
   3347         }
   3348 
   3349         // return effect descriptor
   3350         *pDesc = desc;
   3351         if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
   3352             // if the output returned by getOutputForEffect() is removed before we lock the
   3353             // mutex below, the call to checkPlaybackThread_l(io) below will detect it
   3354             // and we will exit safely
   3355             io = AudioSystem::getOutputForEffect(&desc);
   3356             ALOGV("createEffect got output %d", io);
   3357         }
   3358 
   3359         Mutex::Autolock _l(mLock);
   3360 
   3361         // If output is not specified try to find a matching audio session ID in one of the
   3362         // output threads.
   3363         // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
   3364         // because of code checking output when entering the function.
   3365         // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
   3366         // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
   3367         if (io == AUDIO_IO_HANDLE_NONE) {
   3368             // look for the thread where the specified audio session is present
   3369             io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
   3370             if (io == AUDIO_IO_HANDLE_NONE) {
   3371                 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
   3372             }
   3373             if (io == AUDIO_IO_HANDLE_NONE) {
   3374                 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
   3375             }
   3376 
   3377             // If you wish to create a Record preprocessing AudioEffect in Java,
   3378             // you MUST create an AudioRecord first and keep it alive so it is picked up above.
   3379             // Otherwise it will fail when created on a Playback thread by legacy
   3380             // handling below.  Ditto with Mmap, the associated Mmap track must be created
   3381             // before creating the AudioEffect or the io handle must be specified.
   3382             //
   3383             // Detect if the effect is created after an AudioRecord is destroyed.
   3384             if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
   3385                 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
   3386                         " for session %d no longer exists",
   3387                          __func__, desc.name, sessionId);
   3388                 lStatus = PERMISSION_DENIED;
   3389                 goto Exit;
   3390             }
   3391 
   3392             // Legacy handling of creating an effect on an expired or made-up
   3393             // session id.  We think that it is a Playback effect.
   3394             //
   3395             // If no output thread contains the requested session ID, default to
   3396             // first output. The effect chain will be moved to the correct output
   3397             // thread when a track with the same session ID is created
   3398             if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
   3399                 io = mPlaybackThreads.keyAt(0);
   3400             }
   3401             ALOGV("createEffect() got io %d for effect %s", io, desc.name);
   3402         } else if (checkPlaybackThread_l(io) != nullptr) {
   3403             // allow only one effect chain per sessionId on mPlaybackThreads.
   3404             for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   3405                 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
   3406                 if (io == checkIo) continue;
   3407                 const uint32_t sessionType =
   3408                         mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
   3409                 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
   3410                     ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
   3411                             __func__, desc.name, (int)io, (int)sessionId, (int)checkIo);
   3412                     android_errorWriteLog(0x534e4554, "123237974");
   3413                     lStatus = BAD_VALUE;
   3414                     goto Exit;
   3415                 }
   3416             }
   3417         }
   3418         ThreadBase *thread = checkRecordThread_l(io);
   3419         if (thread == NULL) {
   3420             thread = checkPlaybackThread_l(io);
   3421             if (thread == NULL) {
   3422                 thread = checkMmapThread_l(io);
   3423                 if (thread == NULL) {
   3424                     ALOGE("createEffect() unknown output thread");
   3425                     lStatus = BAD_VALUE;
   3426                     goto Exit;
   3427                 }
   3428             }
   3429         } else {
   3430             // Check if one effect chain was awaiting for an effect to be created on this
   3431             // session and used it instead of creating a new one.
   3432             sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
   3433             if (chain != 0) {
   3434                 Mutex::Autolock _l(thread->mLock);
   3435                 thread->addEffectChain_l(chain);
   3436             }
   3437         }
   3438 
   3439         sp<Client> client = registerPid(pid);
   3440 
   3441         // create effect on selected output thread
   3442         bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
   3443         handle = thread->createEffect_l(client, effectClient, priority, sessionId,
   3444                 &desc, enabled, &lStatus, pinned);
   3445         if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
   3446             // remove local strong reference to Client with mClientLock held
   3447             Mutex::Autolock _cl(mClientLock);
   3448             client.clear();
   3449         } else {
   3450             // handle must be valid here, but check again to be safe.
   3451             if (handle.get() != nullptr && id != nullptr) *id = handle->id();
   3452         }
   3453     }
   3454 
   3455     if (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS) {
   3456         // Check CPU and memory usage
   3457         sp<EffectModule> effect = handle->effect().promote();
   3458         if (effect != nullptr) {
   3459             status_t rStatus = effect->updatePolicyState();
   3460             if (rStatus != NO_ERROR) {
   3461                 lStatus = rStatus;
   3462             }
   3463         }
   3464     } else {
   3465         handle.clear();
   3466     }
   3467 
   3468 Exit:
   3469     *status = lStatus;
   3470     return handle;
   3471 }
   3472 
   3473 status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
   3474         audio_io_handle_t dstOutput)
   3475 {
   3476     ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
   3477             sessionId, srcOutput, dstOutput);
   3478     Mutex::Autolock _l(mLock);
   3479     if (srcOutput == dstOutput) {
   3480         ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
   3481         return NO_ERROR;
   3482     }
   3483     PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
   3484     if (srcThread == NULL) {
   3485         ALOGW("moveEffects() bad srcOutput %d", srcOutput);
   3486         return BAD_VALUE;
   3487     }
   3488     PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
   3489     if (dstThread == NULL) {
   3490         ALOGW("moveEffects() bad dstOutput %d", dstOutput);
   3491         return BAD_VALUE;
   3492     }
   3493 
   3494     Mutex::Autolock _dl(dstThread->mLock);
   3495     Mutex::Autolock _sl(srcThread->mLock);
   3496     return moveEffectChain_l(sessionId, srcThread, dstThread);
   3497 }
   3498 
   3499 
   3500 void AudioFlinger::setEffectSuspended(int effectId,
   3501                                 audio_session_t sessionId,
   3502                                 bool suspended)
   3503 {
   3504     Mutex::Autolock _l(mLock);
   3505 
   3506     sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
   3507     if (thread == nullptr) {
   3508       return;
   3509     }
   3510     Mutex::Autolock _sl(thread->mLock);
   3511     sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
   3512     thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
   3513 }
   3514 
   3515 
   3516 // moveEffectChain_l must be called with both srcThread and dstThread mLocks held
   3517 status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
   3518                                    AudioFlinger::PlaybackThread *srcThread,
   3519                                    AudioFlinger::PlaybackThread *dstThread)
   3520 {
   3521     ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
   3522             sessionId, srcThread, dstThread);
   3523 
   3524     sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
   3525     if (chain == 0) {
   3526         ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
   3527                 sessionId, srcThread);
   3528         return INVALID_OPERATION;
   3529     }
   3530 
   3531     // Check whether the destination thread and all effects in the chain are compatible
   3532     if (!chain->isCompatibleWithThread_l(dstThread)) {
   3533         ALOGW("moveEffectChain_l() effect chain failed because"
   3534                 " destination thread %p is not compatible with effects in the chain",
   3535                 dstThread);
   3536         return INVALID_OPERATION;
   3537     }
   3538 
   3539     // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
   3540     // so that a new chain is created with correct parameters when first effect is added. This is
   3541     // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
   3542     // removed.
   3543     srcThread->removeEffectChain_l(chain);
   3544 
   3545     // transfer all effects one by one so that new effect chain is created on new thread with
   3546     // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
   3547     sp<EffectChain> dstChain;
   3548     uint32_t strategy = 0; // prevent compiler warning
   3549     sp<EffectModule> effect = chain->getEffectFromId_l(0);
   3550     Vector< sp<EffectModule> > removed;
   3551     status_t status = NO_ERROR;
   3552     while (effect != 0) {
   3553         srcThread->removeEffect_l(effect);
   3554         removed.add(effect);
   3555         status = dstThread->addEffect_l(effect);
   3556         if (status != NO_ERROR) {
   3557             break;
   3558         }
   3559         // removeEffect_l() has stopped the effect if it was active so it must be restarted
   3560         if (effect->state() == EffectModule::ACTIVE ||
   3561                 effect->state() == EffectModule::STOPPING) {
   3562             effect->start();
   3563         }
   3564         // if the move request is not received from audio policy manager, the effect must be
   3565         // re-registered with the new strategy and output
   3566         if (dstChain == 0) {
   3567             dstChain = effect->chain().promote();
   3568             if (dstChain == 0) {
   3569                 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
   3570                 status = NO_INIT;
   3571                 break;
   3572             }
   3573             strategy = dstChain->strategy();
   3574         }
   3575         effect = chain->getEffectFromId_l(0);
   3576     }
   3577 
   3578     if (status != NO_ERROR) {
   3579         for (size_t i = 0; i < removed.size(); i++) {
   3580             srcThread->addEffect_l(removed[i]);
   3581         }
   3582     }
   3583 
   3584     return status;
   3585 }
   3586 
   3587 status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
   3588                                          const sp<PlaybackThread>& dstThread,
   3589                                          sp<PlaybackThread> *srcThread)
   3590 {
   3591     status_t status = NO_ERROR;
   3592     Mutex::Autolock _l(mLock);
   3593     sp<PlaybackThread> thread =
   3594         static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
   3595 
   3596     if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
   3597         Mutex::Autolock _dl(dstThread->mLock);
   3598         Mutex::Autolock _sl(thread->mLock);
   3599         sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
   3600         sp<EffectChain> dstChain;
   3601         if (srcChain == 0) {
   3602             return INVALID_OPERATION;
   3603         }
   3604 
   3605         sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
   3606         if (effect == 0) {
   3607             return INVALID_OPERATION;
   3608         }
   3609         thread->removeEffect_l(effect);
   3610         status = dstThread->addEffect_l(effect);
   3611         if (status != NO_ERROR) {
   3612             thread->addEffect_l(effect);
   3613             status = INVALID_OPERATION;
   3614             goto Exit;
   3615         }
   3616 
   3617         dstChain = effect->chain().promote();
   3618         if (dstChain == 0) {
   3619             thread->addEffect_l(effect);
   3620             status = INVALID_OPERATION;
   3621         }
   3622 
   3623 Exit:
   3624         // removeEffect_l() has stopped the effect if it was active so it must be restarted
   3625         if (effect->state() == EffectModule::ACTIVE ||
   3626             effect->state() == EffectModule::STOPPING) {
   3627             effect->start();
   3628         }
   3629     }
   3630 
   3631     if (status == NO_ERROR && srcThread != nullptr) {
   3632         *srcThread = thread;
   3633     }
   3634     return status;
   3635 }
   3636 
   3637 bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
   3638 {
   3639     if (mGlobalEffectEnableTime != 0 &&
   3640             ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
   3641         return true;
   3642     }
   3643 
   3644     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   3645         sp<EffectChain> ec =
   3646                 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
   3647         if (ec != 0 && ec->isNonOffloadableEnabled()) {
   3648             return true;
   3649         }
   3650     }
   3651     return false;
   3652 }
   3653 
   3654 void AudioFlinger::onNonOffloadableGlobalEffectEnable()
   3655 {
   3656     Mutex::Autolock _l(mLock);
   3657 
   3658     mGlobalEffectEnableTime = systemTime();
   3659 
   3660     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   3661         sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
   3662         if (t->mType == ThreadBase::OFFLOAD) {
   3663             t->invalidateTracks(AUDIO_STREAM_MUSIC);
   3664         }
   3665     }
   3666 
   3667 }
   3668 
   3669 status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
   3670 {
   3671     // clear possible suspended state before parking the chain so that it starts in default state
   3672     // when attached to a new record thread
   3673     chain->setEffectSuspended_l(FX_IID_AEC, false);
   3674     chain->setEffectSuspended_l(FX_IID_NS, false);
   3675 
   3676     audio_session_t session = chain->sessionId();
   3677     ssize_t index = mOrphanEffectChains.indexOfKey(session);
   3678     ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
   3679     if (index >= 0) {
   3680         ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
   3681         return ALREADY_EXISTS;
   3682     }
   3683     mOrphanEffectChains.add(session, chain);
   3684     return NO_ERROR;
   3685 }
   3686 
   3687 sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
   3688 {
   3689     sp<EffectChain> chain;
   3690     ssize_t index = mOrphanEffectChains.indexOfKey(session);
   3691     ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
   3692     if (index >= 0) {
   3693         chain = mOrphanEffectChains.valueAt(index);
   3694         mOrphanEffectChains.removeItemsAt(index);
   3695     }
   3696     return chain;
   3697 }
   3698 
   3699 bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
   3700 {
   3701     Mutex::Autolock _l(mLock);
   3702     audio_session_t session = effect->sessionId();
   3703     ssize_t index = mOrphanEffectChains.indexOfKey(session);
   3704     ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
   3705     if (index >= 0) {
   3706         sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
   3707         if (chain->removeEffect_l(effect, true) == 0) {
   3708             ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
   3709             mOrphanEffectChains.removeItemsAt(index);
   3710         }
   3711         return true;
   3712     }
   3713     return false;
   3714 }
   3715 
   3716 
   3717 // ----------------------------------------------------------------------------
   3718 
   3719 status_t AudioFlinger::onTransact(
   3720         uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
   3721 {
   3722     return BnAudioFlinger::onTransact(code, data, reply, flags);
   3723 }
   3724 
   3725 } // namespace android
   3726