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 <sys/time.h>
     27 #include <sys/resource.h>
     28 
     29 #include <binder/IPCThreadState.h>
     30 #include <binder/IServiceManager.h>
     31 #include <utils/Log.h>
     32 #include <utils/Trace.h>
     33 #include <binder/Parcel.h>
     34 #include <utils/String16.h>
     35 #include <utils/threads.h>
     36 #include <utils/Atomic.h>
     37 
     38 #include <cutils/bitops.h>
     39 #include <cutils/properties.h>
     40 
     41 #include <system/audio.h>
     42 #include <hardware/audio.h>
     43 
     44 #include "AudioMixer.h"
     45 #include "AudioFlinger.h"
     46 #include "ServiceUtilities.h"
     47 
     48 #include <media/EffectsFactoryApi.h>
     49 #include <audio_effects/effect_visualizer.h>
     50 #include <audio_effects/effect_ns.h>
     51 #include <audio_effects/effect_aec.h>
     52 
     53 #include <audio_utils/primitives.h>
     54 
     55 #include <powermanager/PowerManager.h>
     56 
     57 #include <common_time/cc_helper.h>
     58 
     59 #include <media/IMediaLogService.h>
     60 
     61 #include <media/nbaio/Pipe.h>
     62 #include <media/nbaio/PipeReader.h>
     63 #include <media/AudioParameter.h>
     64 #include <private/android_filesystem_config.h>
     65 
     66 // ----------------------------------------------------------------------------
     67 
     68 // Note: the following macro is used for extremely verbose logging message.  In
     69 // order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
     70 // 0; but one side effect of this is to turn all LOGV's as well.  Some messages
     71 // are so verbose that we want to suppress them even when we have ALOG_ASSERT
     72 // turned on.  Do not uncomment the #def below unless you really know what you
     73 // are doing and want to see all of the extremely verbose messages.
     74 //#define VERY_VERY_VERBOSE_LOGGING
     75 #ifdef VERY_VERY_VERBOSE_LOGGING
     76 #define ALOGVV ALOGV
     77 #else
     78 #define ALOGVV(a...) do { } while(0)
     79 #endif
     80 
     81 namespace android {
     82 
     83 static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
     84 static const char kHardwareLockedString[] = "Hardware lock is taken\n";
     85 
     86 
     87 nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
     88 
     89 uint32_t AudioFlinger::mScreenState;
     90 
     91 #ifdef TEE_SINK
     92 bool AudioFlinger::mTeeSinkInputEnabled = false;
     93 bool AudioFlinger::mTeeSinkOutputEnabled = false;
     94 bool AudioFlinger::mTeeSinkTrackEnabled = false;
     95 
     96 size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
     97 size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
     98 size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
     99 #endif
    100 
    101 // In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
    102 // we define a minimum time during which a global effect is considered enabled.
    103 static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
    104 
    105 // ----------------------------------------------------------------------------
    106 
    107 static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
    108 {
    109     const hw_module_t *mod;
    110     int rc;
    111 
    112     rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
    113     ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
    114                  AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
    115     if (rc) {
    116         goto out;
    117     }
    118     rc = audio_hw_device_open(mod, dev);
    119     ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
    120                  AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
    121     if (rc) {
    122         goto out;
    123     }
    124     if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
    125         ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
    126         rc = BAD_VALUE;
    127         goto out;
    128     }
    129     return 0;
    130 
    131 out:
    132     *dev = NULL;
    133     return rc;
    134 }
    135 
    136 // ----------------------------------------------------------------------------
    137 
    138 AudioFlinger::AudioFlinger()
    139     : BnAudioFlinger(),
    140       mPrimaryHardwareDev(NULL),
    141       mHardwareStatus(AUDIO_HW_IDLE),
    142       mMasterVolume(1.0f),
    143       mMasterMute(false),
    144       mNextUniqueId(1),
    145       mMode(AUDIO_MODE_INVALID),
    146       mBtNrecIsOff(false),
    147       mIsLowRamDevice(true),
    148       mIsDeviceTypeKnown(false),
    149       mGlobalEffectEnableTime(0)
    150 {
    151     getpid_cached = getpid();
    152     char value[PROPERTY_VALUE_MAX];
    153     bool doLog = (property_get("ro.test_harness", value, "0") > 0) && (atoi(value) == 1);
    154     if (doLog) {
    155         mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters");
    156     }
    157 #ifdef TEE_SINK
    158     (void) property_get("ro.debuggable", value, "0");
    159     int debuggable = atoi(value);
    160     int teeEnabled = 0;
    161     if (debuggable) {
    162         (void) property_get("af.tee", value, "0");
    163         teeEnabled = atoi(value);
    164     }
    165     if (teeEnabled & 1)
    166         mTeeSinkInputEnabled = true;
    167     if (teeEnabled & 2)
    168         mTeeSinkOutputEnabled = true;
    169     if (teeEnabled & 4)
    170         mTeeSinkTrackEnabled = true;
    171 #endif
    172 }
    173 
    174 void AudioFlinger::onFirstRef()
    175 {
    176     int rc = 0;
    177 
    178     Mutex::Autolock _l(mLock);
    179 
    180     /* TODO: move all this work into an Init() function */
    181     char val_str[PROPERTY_VALUE_MAX] = { 0 };
    182     if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
    183         uint32_t int_val;
    184         if (1 == sscanf(val_str, "%u", &int_val)) {
    185             mStandbyTimeInNsecs = milliseconds(int_val);
    186             ALOGI("Using %u mSec as standby time.", int_val);
    187         } else {
    188             mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
    189             ALOGI("Using default %u mSec as standby time.",
    190                     (uint32_t)(mStandbyTimeInNsecs / 1000000));
    191         }
    192     }
    193 
    194     mMode = AUDIO_MODE_NORMAL;
    195 }
    196 
    197 AudioFlinger::~AudioFlinger()
    198 {
    199     while (!mRecordThreads.isEmpty()) {
    200         // closeInput_nonvirtual() will remove specified entry from mRecordThreads
    201         closeInput_nonvirtual(mRecordThreads.keyAt(0));
    202     }
    203     while (!mPlaybackThreads.isEmpty()) {
    204         // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
    205         closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
    206     }
    207 
    208     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
    209         // no mHardwareLock needed, as there are no other references to this
    210         audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
    211         delete mAudioHwDevs.valueAt(i);
    212     }
    213 }
    214 
    215 static const char * const audio_interfaces[] = {
    216     AUDIO_HARDWARE_MODULE_ID_PRIMARY,
    217     AUDIO_HARDWARE_MODULE_ID_A2DP,
    218     AUDIO_HARDWARE_MODULE_ID_USB,
    219 };
    220 #define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
    221 
    222 AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
    223         audio_module_handle_t module,
    224         audio_devices_t devices)
    225 {
    226     // if module is 0, the request comes from an old policy manager and we should load
    227     // well known modules
    228     if (module == 0) {
    229         ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
    230         for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
    231             loadHwModule_l(audio_interfaces[i]);
    232         }
    233         // then try to find a module supporting the requested device.
    234         for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
    235             AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
    236             audio_hw_device_t *dev = audioHwDevice->hwDevice();
    237             if ((dev->get_supported_devices != NULL) &&
    238                     (dev->get_supported_devices(dev) & devices) == devices)
    239                 return audioHwDevice;
    240         }
    241     } else {
    242         // check a match for the requested module handle
    243         AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
    244         if (audioHwDevice != NULL) {
    245             return audioHwDevice;
    246         }
    247     }
    248 
    249     return NULL;
    250 }
    251 
    252 void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
    253 {
    254     const size_t SIZE = 256;
    255     char buffer[SIZE];
    256     String8 result;
    257 
    258     result.append("Clients:\n");
    259     for (size_t i = 0; i < mClients.size(); ++i) {
    260         sp<Client> client = mClients.valueAt(i).promote();
    261         if (client != 0) {
    262             snprintf(buffer, SIZE, "  pid: %d\n", client->pid());
    263             result.append(buffer);
    264         }
    265     }
    266 
    267     result.append("Notification Clients:\n");
    268     for (size_t i = 0; i < mNotificationClients.size(); ++i) {
    269         snprintf(buffer, SIZE, "  pid: %d\n", mNotificationClients.keyAt(i));
    270         result.append(buffer);
    271     }
    272 
    273     result.append("Global session refs:\n");
    274     result.append(" session pid count\n");
    275     for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
    276         AudioSessionRef *r = mAudioSessionRefs[i];
    277         snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
    278         result.append(buffer);
    279     }
    280     write(fd, result.string(), result.size());
    281 }
    282 
    283 
    284 void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
    285 {
    286     const size_t SIZE = 256;
    287     char buffer[SIZE];
    288     String8 result;
    289     hardware_call_state hardwareStatus = mHardwareStatus;
    290 
    291     snprintf(buffer, SIZE, "Hardware status: %d\n"
    292                            "Standby Time mSec: %u\n",
    293                             hardwareStatus,
    294                             (uint32_t)(mStandbyTimeInNsecs / 1000000));
    295     result.append(buffer);
    296     write(fd, result.string(), result.size());
    297 }
    298 
    299 void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
    300 {
    301     const size_t SIZE = 256;
    302     char buffer[SIZE];
    303     String8 result;
    304     snprintf(buffer, SIZE, "Permission Denial: "
    305             "can't dump AudioFlinger from pid=%d, uid=%d\n",
    306             IPCThreadState::self()->getCallingPid(),
    307             IPCThreadState::self()->getCallingUid());
    308     result.append(buffer);
    309     write(fd, result.string(), result.size());
    310 }
    311 
    312 bool AudioFlinger::dumpTryLock(Mutex& mutex)
    313 {
    314     bool locked = false;
    315     for (int i = 0; i < kDumpLockRetries; ++i) {
    316         if (mutex.tryLock() == NO_ERROR) {
    317             locked = true;
    318             break;
    319         }
    320         usleep(kDumpLockSleepUs);
    321     }
    322     return locked;
    323 }
    324 
    325 status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
    326 {
    327     if (!dumpAllowed()) {
    328         dumpPermissionDenial(fd, args);
    329     } else {
    330         // get state of hardware lock
    331         bool hardwareLocked = dumpTryLock(mHardwareLock);
    332         if (!hardwareLocked) {
    333             String8 result(kHardwareLockedString);
    334             write(fd, result.string(), result.size());
    335         } else {
    336             mHardwareLock.unlock();
    337         }
    338 
    339         bool locked = dumpTryLock(mLock);
    340 
    341         // failed to lock - AudioFlinger is probably deadlocked
    342         if (!locked) {
    343             String8 result(kDeadlockedString);
    344             write(fd, result.string(), result.size());
    345         }
    346 
    347         dumpClients(fd, args);
    348         dumpInternals(fd, args);
    349 
    350         // dump playback threads
    351         for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
    352             mPlaybackThreads.valueAt(i)->dump(fd, args);
    353         }
    354 
    355         // dump record threads
    356         for (size_t i = 0; i < mRecordThreads.size(); i++) {
    357             mRecordThreads.valueAt(i)->dump(fd, args);
    358         }
    359 
    360         // dump all hardware devs
    361         for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
    362             audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
    363             dev->dump(dev, fd);
    364         }
    365 
    366 #ifdef TEE_SINK
    367         // dump the serially shared record tee sink
    368         if (mRecordTeeSource != 0) {
    369             dumpTee(fd, mRecordTeeSource);
    370         }
    371 #endif
    372 
    373         if (locked) {
    374             mLock.unlock();
    375         }
    376 
    377         // append a copy of media.log here by forwarding fd to it, but don't attempt
    378         // to lookup the service if it's not running, as it will block for a second
    379         if (mLogMemoryDealer != 0) {
    380             sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
    381             if (binder != 0) {
    382                 fdprintf(fd, "\nmedia.log:\n");
    383                 Vector<String16> args;
    384                 binder->dump(fd, args);
    385             }
    386         }
    387     }
    388     return NO_ERROR;
    389 }
    390 
    391 sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
    392 {
    393     // If pid is already in the mClients wp<> map, then use that entry
    394     // (for which promote() is always != 0), otherwise create a new entry and Client.
    395     sp<Client> client = mClients.valueFor(pid).promote();
    396     if (client == 0) {
    397         client = new Client(this, pid);
    398         mClients.add(pid, client);
    399     }
    400 
    401     return client;
    402 }
    403 
    404 sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
    405 {
    406     if (mLogMemoryDealer == 0) {
    407         return new NBLog::Writer();
    408     }
    409     sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
    410     sp<NBLog::Writer> writer = new NBLog::Writer(size, shared);
    411     sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
    412     if (binder != 0) {
    413         interface_cast<IMediaLogService>(binder)->registerWriter(shared, size, name);
    414     }
    415     return writer;
    416 }
    417 
    418 void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
    419 {
    420     if (writer == 0) {
    421         return;
    422     }
    423     sp<IMemory> iMemory(writer->getIMemory());
    424     if (iMemory == 0) {
    425         return;
    426     }
    427     sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
    428     if (binder != 0) {
    429         interface_cast<IMediaLogService>(binder)->unregisterWriter(iMemory);
    430         // Now the media.log remote reference to IMemory is gone.
    431         // When our last local reference to IMemory also drops to zero,
    432         // the IMemory destructor will deallocate the region from mMemoryDealer.
    433     }
    434 }
    435 
    436 // IAudioFlinger interface
    437 
    438 
    439 sp<IAudioTrack> AudioFlinger::createTrack(
    440         audio_stream_type_t streamType,
    441         uint32_t sampleRate,
    442         audio_format_t format,
    443         audio_channel_mask_t channelMask,
    444         size_t frameCount,
    445         IAudioFlinger::track_flags_t *flags,
    446         const sp<IMemory>& sharedBuffer,
    447         audio_io_handle_t output,
    448         pid_t tid,
    449         int *sessionId,
    450         String8& name,
    451         int clientUid,
    452         status_t *status)
    453 {
    454     sp<PlaybackThread::Track> track;
    455     sp<TrackHandle> trackHandle;
    456     sp<Client> client;
    457     status_t lStatus;
    458     int lSessionId;
    459 
    460     // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
    461     // but if someone uses binder directly they could bypass that and cause us to crash
    462     if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
    463         ALOGE("createTrack() invalid stream type %d", streamType);
    464         lStatus = BAD_VALUE;
    465         goto Exit;
    466     }
    467 
    468     // client is responsible for conversion of 8-bit PCM to 16-bit PCM,
    469     // and we don't yet support 8.24 or 32-bit PCM
    470     if (audio_is_linear_pcm(format) && format != AUDIO_FORMAT_PCM_16_BIT) {
    471         ALOGE("createTrack() invalid format %d", format);
    472         lStatus = BAD_VALUE;
    473         goto Exit;
    474     }
    475 
    476     {
    477         Mutex::Autolock _l(mLock);
    478         PlaybackThread *thread = checkPlaybackThread_l(output);
    479         PlaybackThread *effectThread = NULL;
    480         if (thread == NULL) {
    481             ALOGE("no playback thread found for output handle %d", output);
    482             lStatus = BAD_VALUE;
    483             goto Exit;
    484         }
    485 
    486         pid_t pid = IPCThreadState::self()->getCallingPid();
    487 
    488         client = registerPid_l(pid);
    489 
    490         ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
    491         if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
    492             // check if an effect chain with the same session ID is present on another
    493             // output thread and move it here.
    494             for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
    495                 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
    496                 if (mPlaybackThreads.keyAt(i) != output) {
    497                     uint32_t sessions = t->hasAudioSession(*sessionId);
    498                     if (sessions & PlaybackThread::EFFECT_SESSION) {
    499                         effectThread = t.get();
    500                         break;
    501                     }
    502                 }
    503             }
    504             lSessionId = *sessionId;
    505         } else {
    506             // if no audio session id is provided, create one here
    507             lSessionId = nextUniqueId();
    508             if (sessionId != NULL) {
    509                 *sessionId = lSessionId;
    510             }
    511         }
    512         ALOGV("createTrack() lSessionId: %d", lSessionId);
    513 
    514         track = thread->createTrack_l(client, streamType, sampleRate, format,
    515                 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, clientUid, &lStatus);
    516 
    517         // move effect chain to this output thread if an effect on same session was waiting
    518         // for a track to be created
    519         if (lStatus == NO_ERROR && effectThread != NULL) {
    520             Mutex::Autolock _dl(thread->mLock);
    521             Mutex::Autolock _sl(effectThread->mLock);
    522             moveEffectChain_l(lSessionId, effectThread, thread, true);
    523         }
    524 
    525         // Look for sync events awaiting for a session to be used.
    526         for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
    527             if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
    528                 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
    529                     if (lStatus == NO_ERROR) {
    530                         (void) track->setSyncEvent(mPendingSyncEvents[i]);
    531                     } else {
    532                         mPendingSyncEvents[i]->cancel();
    533                     }
    534                     mPendingSyncEvents.removeAt(i);
    535                     i--;
    536                 }
    537             }
    538         }
    539     }
    540     if (lStatus == NO_ERROR) {
    541         // s for server's pid, n for normal mixer name, f for fast index
    542         name = String8::format("s:%d;n:%d;f:%d", getpid_cached, track->name() - AudioMixer::TRACK0,
    543                 track->fastIndex());
    544         trackHandle = new TrackHandle(track);
    545     } else {
    546         // remove local strong reference to Client before deleting the Track so that the Client
    547         // destructor is called by the TrackBase destructor with mLock held
    548         client.clear();
    549         track.clear();
    550     }
    551 
    552 Exit:
    553     if (status != NULL) {
    554         *status = lStatus;
    555     }
    556     return trackHandle;
    557 }
    558 
    559 uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
    560 {
    561     Mutex::Autolock _l(mLock);
    562     PlaybackThread *thread = checkPlaybackThread_l(output);
    563     if (thread == NULL) {
    564         ALOGW("sampleRate() unknown thread %d", output);
    565         return 0;
    566     }
    567     return thread->sampleRate();
    568 }
    569 
    570 int AudioFlinger::channelCount(audio_io_handle_t output) const
    571 {
    572     Mutex::Autolock _l(mLock);
    573     PlaybackThread *thread = checkPlaybackThread_l(output);
    574     if (thread == NULL) {
    575         ALOGW("channelCount() unknown thread %d", output);
    576         return 0;
    577     }
    578     return thread->channelCount();
    579 }
    580 
    581 audio_format_t AudioFlinger::format(audio_io_handle_t output) const
    582 {
    583     Mutex::Autolock _l(mLock);
    584     PlaybackThread *thread = checkPlaybackThread_l(output);
    585     if (thread == NULL) {
    586         ALOGW("format() unknown thread %d", output);
    587         return AUDIO_FORMAT_INVALID;
    588     }
    589     return thread->format();
    590 }
    591 
    592 size_t AudioFlinger::frameCount(audio_io_handle_t output) const
    593 {
    594     Mutex::Autolock _l(mLock);
    595     PlaybackThread *thread = checkPlaybackThread_l(output);
    596     if (thread == NULL) {
    597         ALOGW("frameCount() unknown thread %d", output);
    598         return 0;
    599     }
    600     // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
    601     //       should examine all callers and fix them to handle smaller counts
    602     return thread->frameCount();
    603 }
    604 
    605 uint32_t AudioFlinger::latency(audio_io_handle_t output) const
    606 {
    607     Mutex::Autolock _l(mLock);
    608     PlaybackThread *thread = checkPlaybackThread_l(output);
    609     if (thread == NULL) {
    610         ALOGW("latency(): no playback thread found for output handle %d", output);
    611         return 0;
    612     }
    613     return thread->latency();
    614 }
    615 
    616 status_t AudioFlinger::setMasterVolume(float value)
    617 {
    618     status_t ret = initCheck();
    619     if (ret != NO_ERROR) {
    620         return ret;
    621     }
    622 
    623     // check calling permissions
    624     if (!settingsAllowed()) {
    625         return PERMISSION_DENIED;
    626     }
    627 
    628     Mutex::Autolock _l(mLock);
    629     mMasterVolume = value;
    630 
    631     // Set master volume in the HALs which support it.
    632     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
    633         AutoMutex lock(mHardwareLock);
    634         AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
    635 
    636         mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
    637         if (dev->canSetMasterVolume()) {
    638             dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
    639         }
    640         mHardwareStatus = AUDIO_HW_IDLE;
    641     }
    642 
    643     // Now set the master volume in each playback thread.  Playback threads
    644     // assigned to HALs which do not have master volume support will apply
    645     // master volume during the mix operation.  Threads with HALs which do
    646     // support master volume will simply ignore the setting.
    647     for (size_t i = 0; i < mPlaybackThreads.size(); i++)
    648         mPlaybackThreads.valueAt(i)->setMasterVolume(value);
    649 
    650     return NO_ERROR;
    651 }
    652 
    653 status_t AudioFlinger::setMode(audio_mode_t mode)
    654 {
    655     status_t ret = initCheck();
    656     if (ret != NO_ERROR) {
    657         return ret;
    658     }
    659 
    660     // check calling permissions
    661     if (!settingsAllowed()) {
    662         return PERMISSION_DENIED;
    663     }
    664     if (uint32_t(mode) >= AUDIO_MODE_CNT) {
    665         ALOGW("Illegal value: setMode(%d)", mode);
    666         return BAD_VALUE;
    667     }
    668 
    669     { // scope for the lock
    670         AutoMutex lock(mHardwareLock);
    671         audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
    672         mHardwareStatus = AUDIO_HW_SET_MODE;
    673         ret = dev->set_mode(dev, mode);
    674         mHardwareStatus = AUDIO_HW_IDLE;
    675     }
    676 
    677     if (NO_ERROR == ret) {
    678         Mutex::Autolock _l(mLock);
    679         mMode = mode;
    680         for (size_t i = 0; i < mPlaybackThreads.size(); i++)
    681             mPlaybackThreads.valueAt(i)->setMode(mode);
    682     }
    683 
    684     return ret;
    685 }
    686 
    687 status_t AudioFlinger::setMicMute(bool state)
    688 {
    689     status_t ret = initCheck();
    690     if (ret != NO_ERROR) {
    691         return ret;
    692     }
    693 
    694     // check calling permissions
    695     if (!settingsAllowed()) {
    696         return PERMISSION_DENIED;
    697     }
    698 
    699     AutoMutex lock(mHardwareLock);
    700     audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
    701     mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
    702     ret = dev->set_mic_mute(dev, state);
    703     mHardwareStatus = AUDIO_HW_IDLE;
    704     return ret;
    705 }
    706 
    707 bool AudioFlinger::getMicMute() const
    708 {
    709     status_t ret = initCheck();
    710     if (ret != NO_ERROR) {
    711         return false;
    712     }
    713 
    714     bool state = AUDIO_MODE_INVALID;
    715     AutoMutex lock(mHardwareLock);
    716     audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
    717     mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
    718     dev->get_mic_mute(dev, &state);
    719     mHardwareStatus = AUDIO_HW_IDLE;
    720     return state;
    721 }
    722 
    723 status_t AudioFlinger::setMasterMute(bool muted)
    724 {
    725     status_t ret = initCheck();
    726     if (ret != NO_ERROR) {
    727         return ret;
    728     }
    729 
    730     // check calling permissions
    731     if (!settingsAllowed()) {
    732         return PERMISSION_DENIED;
    733     }
    734 
    735     Mutex::Autolock _l(mLock);
    736     mMasterMute = muted;
    737 
    738     // Set master mute in the HALs which support it.
    739     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
    740         AutoMutex lock(mHardwareLock);
    741         AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
    742 
    743         mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
    744         if (dev->canSetMasterMute()) {
    745             dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
    746         }
    747         mHardwareStatus = AUDIO_HW_IDLE;
    748     }
    749 
    750     // Now set the master mute in each playback thread.  Playback threads
    751     // assigned to HALs which do not have master mute support will apply master
    752     // mute during the mix operation.  Threads with HALs which do support master
    753     // mute will simply ignore the setting.
    754     for (size_t i = 0; i < mPlaybackThreads.size(); i++)
    755         mPlaybackThreads.valueAt(i)->setMasterMute(muted);
    756 
    757     return NO_ERROR;
    758 }
    759 
    760 float AudioFlinger::masterVolume() const
    761 {
    762     Mutex::Autolock _l(mLock);
    763     return masterVolume_l();
    764 }
    765 
    766 bool AudioFlinger::masterMute() const
    767 {
    768     Mutex::Autolock _l(mLock);
    769     return masterMute_l();
    770 }
    771 
    772 float AudioFlinger::masterVolume_l() const
    773 {
    774     return mMasterVolume;
    775 }
    776 
    777 bool AudioFlinger::masterMute_l() const
    778 {
    779     return mMasterMute;
    780 }
    781 
    782 status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
    783         audio_io_handle_t output)
    784 {
    785     // check calling permissions
    786     if (!settingsAllowed()) {
    787         return PERMISSION_DENIED;
    788     }
    789 
    790     if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
    791         ALOGE("setStreamVolume() invalid stream %d", stream);
    792         return BAD_VALUE;
    793     }
    794 
    795     AutoMutex lock(mLock);
    796     PlaybackThread *thread = NULL;
    797     if (output) {
    798         thread = checkPlaybackThread_l(output);
    799         if (thread == NULL) {
    800             return BAD_VALUE;
    801         }
    802     }
    803 
    804     mStreamTypes[stream].volume = value;
    805 
    806     if (thread == NULL) {
    807         for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
    808             mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
    809         }
    810     } else {
    811         thread->setStreamVolume(stream, value);
    812     }
    813 
    814     return NO_ERROR;
    815 }
    816 
    817 status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
    818 {
    819     // check calling permissions
    820     if (!settingsAllowed()) {
    821         return PERMISSION_DENIED;
    822     }
    823 
    824     if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
    825         uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
    826         ALOGE("setStreamMute() invalid stream %d", stream);
    827         return BAD_VALUE;
    828     }
    829 
    830     AutoMutex lock(mLock);
    831     mStreamTypes[stream].mute = muted;
    832     for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
    833         mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
    834 
    835     return NO_ERROR;
    836 }
    837 
    838 float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
    839 {
    840     if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
    841         return 0.0f;
    842     }
    843 
    844     AutoMutex lock(mLock);
    845     float volume;
    846     if (output) {
    847         PlaybackThread *thread = checkPlaybackThread_l(output);
    848         if (thread == NULL) {
    849             return 0.0f;
    850         }
    851         volume = thread->streamVolume(stream);
    852     } else {
    853         volume = streamVolume_l(stream);
    854     }
    855 
    856     return volume;
    857 }
    858 
    859 bool AudioFlinger::streamMute(audio_stream_type_t stream) const
    860 {
    861     if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
    862         return true;
    863     }
    864 
    865     AutoMutex lock(mLock);
    866     return streamMute_l(stream);
    867 }
    868 
    869 status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
    870 {
    871     ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
    872             ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
    873 
    874     // check calling permissions
    875     if (!settingsAllowed()) {
    876         return PERMISSION_DENIED;
    877     }
    878 
    879     // ioHandle == 0 means the parameters are global to the audio hardware interface
    880     if (ioHandle == 0) {
    881         Mutex::Autolock _l(mLock);
    882         status_t final_result = NO_ERROR;
    883         {
    884             AutoMutex lock(mHardwareLock);
    885             mHardwareStatus = AUDIO_HW_SET_PARAMETER;
    886             for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
    887                 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
    888                 status_t result = dev->set_parameters(dev, keyValuePairs.string());
    889                 final_result = result ?: final_result;
    890             }
    891             mHardwareStatus = AUDIO_HW_IDLE;
    892         }
    893         // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
    894         AudioParameter param = AudioParameter(keyValuePairs);
    895         String8 value;
    896         if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
    897             bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
    898             if (mBtNrecIsOff != btNrecIsOff) {
    899                 for (size_t i = 0; i < mRecordThreads.size(); i++) {
    900                     sp<RecordThread> thread = mRecordThreads.valueAt(i);
    901                     audio_devices_t device = thread->inDevice();
    902                     bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
    903                     // collect all of the thread's session IDs
    904                     KeyedVector<int, bool> ids = thread->sessionIds();
    905                     // suspend effects associated with those session IDs
    906                     for (size_t j = 0; j < ids.size(); ++j) {
    907                         int sessionId = ids.keyAt(j);
    908                         thread->setEffectSuspended(FX_IID_AEC,
    909                                                    suspend,
    910                                                    sessionId);
    911                         thread->setEffectSuspended(FX_IID_NS,
    912                                                    suspend,
    913                                                    sessionId);
    914                     }
    915                 }
    916                 mBtNrecIsOff = btNrecIsOff;
    917             }
    918         }
    919         String8 screenState;
    920         if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
    921             bool isOff = screenState == "off";
    922             if (isOff != (AudioFlinger::mScreenState & 1)) {
    923                 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
    924             }
    925         }
    926         return final_result;
    927     }
    928 
    929     // hold a strong ref on thread in case closeOutput() or closeInput() is called
    930     // and the thread is exited once the lock is released
    931     sp<ThreadBase> thread;
    932     {
    933         Mutex::Autolock _l(mLock);
    934         thread = checkPlaybackThread_l(ioHandle);
    935         if (thread == 0) {
    936             thread = checkRecordThread_l(ioHandle);
    937         } else if (thread == primaryPlaybackThread_l()) {
    938             // indicate output device change to all input threads for pre processing
    939             AudioParameter param = AudioParameter(keyValuePairs);
    940             int value;
    941             if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
    942                     (value != 0)) {
    943                 for (size_t i = 0; i < mRecordThreads.size(); i++) {
    944                     mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
    945                 }
    946             }
    947         }
    948     }
    949     if (thread != 0) {
    950         return thread->setParameters(keyValuePairs);
    951     }
    952     return BAD_VALUE;
    953 }
    954 
    955 String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
    956 {
    957     ALOGVV("getParameters() io %d, keys %s, calling pid %d",
    958             ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
    959 
    960     Mutex::Autolock _l(mLock);
    961 
    962     if (ioHandle == 0) {
    963         String8 out_s8;
    964 
    965         for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
    966             char *s;
    967             {
    968             AutoMutex lock(mHardwareLock);
    969             mHardwareStatus = AUDIO_HW_GET_PARAMETER;
    970             audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
    971             s = dev->get_parameters(dev, keys.string());
    972             mHardwareStatus = AUDIO_HW_IDLE;
    973             }
    974             out_s8 += String8(s ? s : "");
    975             free(s);
    976         }
    977         return out_s8;
    978     }
    979 
    980     PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
    981     if (playbackThread != NULL) {
    982         return playbackThread->getParameters(keys);
    983     }
    984     RecordThread *recordThread = checkRecordThread_l(ioHandle);
    985     if (recordThread != NULL) {
    986         return recordThread->getParameters(keys);
    987     }
    988     return String8("");
    989 }
    990 
    991 size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
    992         audio_channel_mask_t channelMask) const
    993 {
    994     status_t ret = initCheck();
    995     if (ret != NO_ERROR) {
    996         return 0;
    997     }
    998 
    999     AutoMutex lock(mHardwareLock);
   1000     mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
   1001     struct audio_config config;
   1002     memset(&config, 0, sizeof(config));
   1003     config.sample_rate = sampleRate;
   1004     config.channel_mask = channelMask;
   1005     config.format = format;
   1006 
   1007     audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
   1008     size_t size = dev->get_input_buffer_size(dev, &config);
   1009     mHardwareStatus = AUDIO_HW_IDLE;
   1010     return size;
   1011 }
   1012 
   1013 unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
   1014 {
   1015     Mutex::Autolock _l(mLock);
   1016 
   1017     RecordThread *recordThread = checkRecordThread_l(ioHandle);
   1018     if (recordThread != NULL) {
   1019         return recordThread->getInputFramesLost();
   1020     }
   1021     return 0;
   1022 }
   1023 
   1024 status_t AudioFlinger::setVoiceVolume(float value)
   1025 {
   1026     status_t ret = initCheck();
   1027     if (ret != NO_ERROR) {
   1028         return ret;
   1029     }
   1030 
   1031     // check calling permissions
   1032     if (!settingsAllowed()) {
   1033         return PERMISSION_DENIED;
   1034     }
   1035 
   1036     AutoMutex lock(mHardwareLock);
   1037     audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
   1038     mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
   1039     ret = dev->set_voice_volume(dev, value);
   1040     mHardwareStatus = AUDIO_HW_IDLE;
   1041 
   1042     return ret;
   1043 }
   1044 
   1045 status_t AudioFlinger::getRenderPosition(size_t *halFrames, size_t *dspFrames,
   1046         audio_io_handle_t output) const
   1047 {
   1048     status_t status;
   1049 
   1050     Mutex::Autolock _l(mLock);
   1051 
   1052     PlaybackThread *playbackThread = checkPlaybackThread_l(output);
   1053     if (playbackThread != NULL) {
   1054         return playbackThread->getRenderPosition(halFrames, dspFrames);
   1055     }
   1056 
   1057     return BAD_VALUE;
   1058 }
   1059 
   1060 void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
   1061 {
   1062 
   1063     Mutex::Autolock _l(mLock);
   1064 
   1065     pid_t pid = IPCThreadState::self()->getCallingPid();
   1066     if (mNotificationClients.indexOfKey(pid) < 0) {
   1067         sp<NotificationClient> notificationClient = new NotificationClient(this,
   1068                                                                             client,
   1069                                                                             pid);
   1070         ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
   1071 
   1072         mNotificationClients.add(pid, notificationClient);
   1073 
   1074         sp<IBinder> binder = client->asBinder();
   1075         binder->linkToDeath(notificationClient);
   1076 
   1077         // the config change is always sent from playback or record threads to avoid deadlock
   1078         // with AudioSystem::gLock
   1079         for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   1080             mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
   1081         }
   1082 
   1083         for (size_t i = 0; i < mRecordThreads.size(); i++) {
   1084             mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
   1085         }
   1086     }
   1087 }
   1088 
   1089 void AudioFlinger::removeNotificationClient(pid_t pid)
   1090 {
   1091     Mutex::Autolock _l(mLock);
   1092 
   1093     mNotificationClients.removeItem(pid);
   1094 
   1095     ALOGV("%d died, releasing its sessions", pid);
   1096     size_t num = mAudioSessionRefs.size();
   1097     bool removed = false;
   1098     for (size_t i = 0; i< num; ) {
   1099         AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
   1100         ALOGV(" pid %d @ %d", ref->mPid, i);
   1101         if (ref->mPid == pid) {
   1102             ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
   1103             mAudioSessionRefs.removeAt(i);
   1104             delete ref;
   1105             removed = true;
   1106             num--;
   1107         } else {
   1108             i++;
   1109         }
   1110     }
   1111     if (removed) {
   1112         purgeStaleEffects_l();
   1113     }
   1114 }
   1115 
   1116 // audioConfigChanged_l() must be called with AudioFlinger::mLock held
   1117 void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
   1118 {
   1119     size_t size = mNotificationClients.size();
   1120     for (size_t i = 0; i < size; i++) {
   1121         mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
   1122                                                                                param2);
   1123     }
   1124 }
   1125 
   1126 // removeClient_l() must be called with AudioFlinger::mLock held
   1127 void AudioFlinger::removeClient_l(pid_t pid)
   1128 {
   1129     ALOGV("removeClient_l() pid %d, calling pid %d", pid,
   1130             IPCThreadState::self()->getCallingPid());
   1131     mClients.removeItem(pid);
   1132 }
   1133 
   1134 // getEffectThread_l() must be called with AudioFlinger::mLock held
   1135 sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
   1136 {
   1137     sp<PlaybackThread> thread;
   1138 
   1139     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   1140         if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
   1141             ALOG_ASSERT(thread == 0);
   1142             thread = mPlaybackThreads.valueAt(i);
   1143         }
   1144     }
   1145 
   1146     return thread;
   1147 }
   1148 
   1149 
   1150 
   1151 // ----------------------------------------------------------------------------
   1152 
   1153 AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
   1154     :   RefBase(),
   1155         mAudioFlinger(audioFlinger),
   1156         // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
   1157         mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
   1158         mPid(pid),
   1159         mTimedTrackCount(0)
   1160 {
   1161     // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
   1162 }
   1163 
   1164 // Client destructor must be called with AudioFlinger::mLock held
   1165 AudioFlinger::Client::~Client()
   1166 {
   1167     mAudioFlinger->removeClient_l(mPid);
   1168 }
   1169 
   1170 sp<MemoryDealer> AudioFlinger::Client::heap() const
   1171 {
   1172     return mMemoryDealer;
   1173 }
   1174 
   1175 // Reserve one of the limited slots for a timed audio track associated
   1176 // with this client
   1177 bool AudioFlinger::Client::reserveTimedTrack()
   1178 {
   1179     const int kMaxTimedTracksPerClient = 4;
   1180 
   1181     Mutex::Autolock _l(mTimedTrackLock);
   1182 
   1183     if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
   1184         ALOGW("can not create timed track - pid %d has exceeded the limit",
   1185              mPid);
   1186         return false;
   1187     }
   1188 
   1189     mTimedTrackCount++;
   1190     return true;
   1191 }
   1192 
   1193 // Release a slot for a timed audio track
   1194 void AudioFlinger::Client::releaseTimedTrack()
   1195 {
   1196     Mutex::Autolock _l(mTimedTrackLock);
   1197     mTimedTrackCount--;
   1198 }
   1199 
   1200 // ----------------------------------------------------------------------------
   1201 
   1202 AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
   1203                                                      const sp<IAudioFlingerClient>& client,
   1204                                                      pid_t pid)
   1205     : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
   1206 {
   1207 }
   1208 
   1209 AudioFlinger::NotificationClient::~NotificationClient()
   1210 {
   1211 }
   1212 
   1213 void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
   1214 {
   1215     sp<NotificationClient> keep(this);
   1216     mAudioFlinger->removeNotificationClient(mPid);
   1217 }
   1218 
   1219 
   1220 // ----------------------------------------------------------------------------
   1221 
   1222 static bool deviceRequiresCaptureAudioOutputPermission(audio_devices_t inDevice) {
   1223     return audio_is_remote_submix_device(inDevice);
   1224 }
   1225 
   1226 sp<IAudioRecord> AudioFlinger::openRecord(
   1227         audio_io_handle_t input,
   1228         uint32_t sampleRate,
   1229         audio_format_t format,
   1230         audio_channel_mask_t channelMask,
   1231         size_t frameCount,
   1232         IAudioFlinger::track_flags_t *flags,
   1233         pid_t tid,
   1234         int *sessionId,
   1235         status_t *status)
   1236 {
   1237     sp<RecordThread::RecordTrack> recordTrack;
   1238     sp<RecordHandle> recordHandle;
   1239     sp<Client> client;
   1240     status_t lStatus;
   1241     RecordThread *thread;
   1242     size_t inFrameCount;
   1243     int lSessionId;
   1244 
   1245     // check calling permissions
   1246     if (!recordingAllowed()) {
   1247         ALOGE("openRecord() permission denied: recording not allowed");
   1248         lStatus = PERMISSION_DENIED;
   1249         goto Exit;
   1250     }
   1251 
   1252     if (format != AUDIO_FORMAT_PCM_16_BIT) {
   1253         ALOGE("openRecord() invalid format %d", format);
   1254         lStatus = BAD_VALUE;
   1255         goto Exit;
   1256     }
   1257 
   1258     // add client to list
   1259     { // scope for mLock
   1260         Mutex::Autolock _l(mLock);
   1261         thread = checkRecordThread_l(input);
   1262         if (thread == NULL) {
   1263             ALOGE("openRecord() checkRecordThread_l failed");
   1264             lStatus = BAD_VALUE;
   1265             goto Exit;
   1266         }
   1267 
   1268         if (deviceRequiresCaptureAudioOutputPermission(thread->inDevice())
   1269                 && !captureAudioOutputAllowed()) {
   1270             ALOGE("openRecord() permission denied: capture not allowed");
   1271             lStatus = PERMISSION_DENIED;
   1272             goto Exit;
   1273         }
   1274 
   1275         pid_t pid = IPCThreadState::self()->getCallingPid();
   1276         client = registerPid_l(pid);
   1277 
   1278         // If no audio session id is provided, create one here
   1279         if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
   1280             lSessionId = *sessionId;
   1281         } else {
   1282             lSessionId = nextUniqueId();
   1283             if (sessionId != NULL) {
   1284                 *sessionId = lSessionId;
   1285             }
   1286         }
   1287         // create new record track.
   1288         // The record track uses one track in mHardwareMixerThread by convention.
   1289         // TODO: the uid should be passed in as a parameter to openRecord
   1290         recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
   1291                                                   frameCount, lSessionId,
   1292                                                   IPCThreadState::self()->getCallingUid(),
   1293                                                   flags, tid, &lStatus);
   1294         LOG_ALWAYS_FATAL_IF((recordTrack != 0) != (lStatus == NO_ERROR));
   1295     }
   1296     if (lStatus != NO_ERROR) {
   1297         // remove local strong reference to Client before deleting the RecordTrack so that the
   1298         // Client destructor is called by the TrackBase destructor with mLock held
   1299         client.clear();
   1300         recordTrack.clear();
   1301         goto Exit;
   1302     }
   1303 
   1304     // return to handle to client
   1305     recordHandle = new RecordHandle(recordTrack);
   1306     lStatus = NO_ERROR;
   1307 
   1308 Exit:
   1309     if (status) {
   1310         *status = lStatus;
   1311     }
   1312     return recordHandle;
   1313 }
   1314 
   1315 
   1316 
   1317 // ----------------------------------------------------------------------------
   1318 
   1319 audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
   1320 {
   1321     if (!settingsAllowed()) {
   1322         return 0;
   1323     }
   1324     Mutex::Autolock _l(mLock);
   1325     return loadHwModule_l(name);
   1326 }
   1327 
   1328 // loadHwModule_l() must be called with AudioFlinger::mLock held
   1329 audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
   1330 {
   1331     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
   1332         if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
   1333             ALOGW("loadHwModule() module %s already loaded", name);
   1334             return mAudioHwDevs.keyAt(i);
   1335         }
   1336     }
   1337 
   1338     audio_hw_device_t *dev;
   1339 
   1340     int rc = load_audio_interface(name, &dev);
   1341     if (rc) {
   1342         ALOGI("loadHwModule() error %d loading module %s ", rc, name);
   1343         return 0;
   1344     }
   1345 
   1346     mHardwareStatus = AUDIO_HW_INIT;
   1347     rc = dev->init_check(dev);
   1348     mHardwareStatus = AUDIO_HW_IDLE;
   1349     if (rc) {
   1350         ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
   1351         return 0;
   1352     }
   1353 
   1354     // Check and cache this HAL's level of support for master mute and master
   1355     // volume.  If this is the first HAL opened, and it supports the get
   1356     // methods, use the initial values provided by the HAL as the current
   1357     // master mute and volume settings.
   1358 
   1359     AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
   1360     {  // scope for auto-lock pattern
   1361         AutoMutex lock(mHardwareLock);
   1362 
   1363         if (0 == mAudioHwDevs.size()) {
   1364             mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
   1365             if (NULL != dev->get_master_volume) {
   1366                 float mv;
   1367                 if (OK == dev->get_master_volume(dev, &mv)) {
   1368                     mMasterVolume = mv;
   1369                 }
   1370             }
   1371 
   1372             mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
   1373             if (NULL != dev->get_master_mute) {
   1374                 bool mm;
   1375                 if (OK == dev->get_master_mute(dev, &mm)) {
   1376                     mMasterMute = mm;
   1377                 }
   1378             }
   1379         }
   1380 
   1381         mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
   1382         if ((NULL != dev->set_master_volume) &&
   1383             (OK == dev->set_master_volume(dev, mMasterVolume))) {
   1384             flags = static_cast<AudioHwDevice::Flags>(flags |
   1385                     AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
   1386         }
   1387 
   1388         mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
   1389         if ((NULL != dev->set_master_mute) &&
   1390             (OK == dev->set_master_mute(dev, mMasterMute))) {
   1391             flags = static_cast<AudioHwDevice::Flags>(flags |
   1392                     AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
   1393         }
   1394 
   1395         mHardwareStatus = AUDIO_HW_IDLE;
   1396     }
   1397 
   1398     audio_module_handle_t handle = nextUniqueId();
   1399     mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
   1400 
   1401     ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
   1402           name, dev->common.module->name, dev->common.module->id, handle);
   1403 
   1404     return handle;
   1405 
   1406 }
   1407 
   1408 // ----------------------------------------------------------------------------
   1409 
   1410 uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
   1411 {
   1412     Mutex::Autolock _l(mLock);
   1413     PlaybackThread *thread = primaryPlaybackThread_l();
   1414     return thread != NULL ? thread->sampleRate() : 0;
   1415 }
   1416 
   1417 size_t AudioFlinger::getPrimaryOutputFrameCount()
   1418 {
   1419     Mutex::Autolock _l(mLock);
   1420     PlaybackThread *thread = primaryPlaybackThread_l();
   1421     return thread != NULL ? thread->frameCountHAL() : 0;
   1422 }
   1423 
   1424 // ----------------------------------------------------------------------------
   1425 
   1426 status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
   1427 {
   1428     uid_t uid = IPCThreadState::self()->getCallingUid();
   1429     if (uid != AID_SYSTEM) {
   1430         return PERMISSION_DENIED;
   1431     }
   1432     Mutex::Autolock _l(mLock);
   1433     if (mIsDeviceTypeKnown) {
   1434         return INVALID_OPERATION;
   1435     }
   1436     mIsLowRamDevice = isLowRamDevice;
   1437     mIsDeviceTypeKnown = true;
   1438     return NO_ERROR;
   1439 }
   1440 
   1441 // ----------------------------------------------------------------------------
   1442 
   1443 audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
   1444                                            audio_devices_t *pDevices,
   1445                                            uint32_t *pSamplingRate,
   1446                                            audio_format_t *pFormat,
   1447                                            audio_channel_mask_t *pChannelMask,
   1448                                            uint32_t *pLatencyMs,
   1449                                            audio_output_flags_t flags,
   1450                                            const audio_offload_info_t *offloadInfo)
   1451 {
   1452     PlaybackThread *thread = NULL;
   1453     struct audio_config config;
   1454     config.sample_rate = (pSamplingRate != NULL) ? *pSamplingRate : 0;
   1455     config.channel_mask = (pChannelMask != NULL) ? *pChannelMask : 0;
   1456     config.format = (pFormat != NULL) ? *pFormat : AUDIO_FORMAT_DEFAULT;
   1457     if (offloadInfo) {
   1458         config.offload_info = *offloadInfo;
   1459     }
   1460 
   1461     audio_stream_out_t *outStream = NULL;
   1462     AudioHwDevice *outHwDev;
   1463 
   1464     ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
   1465               module,
   1466               (pDevices != NULL) ? *pDevices : 0,
   1467               config.sample_rate,
   1468               config.format,
   1469               config.channel_mask,
   1470               flags);
   1471     ALOGV("openOutput(), offloadInfo %p version 0x%04x",
   1472           offloadInfo, offloadInfo == NULL ? -1 : offloadInfo->version );
   1473 
   1474     if (pDevices == NULL || *pDevices == 0) {
   1475         return 0;
   1476     }
   1477 
   1478     Mutex::Autolock _l(mLock);
   1479 
   1480     outHwDev = findSuitableHwDev_l(module, *pDevices);
   1481     if (outHwDev == NULL)
   1482         return 0;
   1483 
   1484     audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
   1485     audio_io_handle_t id = nextUniqueId();
   1486 
   1487     mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
   1488 
   1489     status_t status = hwDevHal->open_output_stream(hwDevHal,
   1490                                           id,
   1491                                           *pDevices,
   1492                                           (audio_output_flags_t)flags,
   1493                                           &config,
   1494                                           &outStream);
   1495 
   1496     mHardwareStatus = AUDIO_HW_IDLE;
   1497     ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %#08x, "
   1498             "Channels %x, status %d",
   1499             outStream,
   1500             config.sample_rate,
   1501             config.format,
   1502             config.channel_mask,
   1503             status);
   1504 
   1505     if (status == NO_ERROR && outStream != NULL) {
   1506         AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream, flags);
   1507 
   1508         if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
   1509             thread = new OffloadThread(this, output, id, *pDevices);
   1510             ALOGV("openOutput() created offload output: ID %d thread %p", id, thread);
   1511         } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
   1512             (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
   1513             (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
   1514             thread = new DirectOutputThread(this, output, id, *pDevices);
   1515             ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
   1516         } else {
   1517             thread = new MixerThread(this, output, id, *pDevices);
   1518             ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
   1519         }
   1520         mPlaybackThreads.add(id, thread);
   1521 
   1522         if (pSamplingRate != NULL) {
   1523             *pSamplingRate = config.sample_rate;
   1524         }
   1525         if (pFormat != NULL) {
   1526             *pFormat = config.format;
   1527         }
   1528         if (pChannelMask != NULL) {
   1529             *pChannelMask = config.channel_mask;
   1530         }
   1531         if (pLatencyMs != NULL) {
   1532             *pLatencyMs = thread->latency();
   1533         }
   1534 
   1535         // notify client processes of the new output creation
   1536         thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
   1537 
   1538         // the first primary output opened designates the primary hw device
   1539         if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
   1540             ALOGI("Using module %d has the primary audio interface", module);
   1541             mPrimaryHardwareDev = outHwDev;
   1542 
   1543             AutoMutex lock(mHardwareLock);
   1544             mHardwareStatus = AUDIO_HW_SET_MODE;
   1545             hwDevHal->set_mode(hwDevHal, mMode);
   1546             mHardwareStatus = AUDIO_HW_IDLE;
   1547         }
   1548         return id;
   1549     }
   1550 
   1551     return 0;
   1552 }
   1553 
   1554 audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
   1555         audio_io_handle_t output2)
   1556 {
   1557     Mutex::Autolock _l(mLock);
   1558     MixerThread *thread1 = checkMixerThread_l(output1);
   1559     MixerThread *thread2 = checkMixerThread_l(output2);
   1560 
   1561     if (thread1 == NULL || thread2 == NULL) {
   1562         ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
   1563                 output2);
   1564         return 0;
   1565     }
   1566 
   1567     audio_io_handle_t id = nextUniqueId();
   1568     DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
   1569     thread->addOutputTrack(thread2);
   1570     mPlaybackThreads.add(id, thread);
   1571     // notify client processes of the new output creation
   1572     thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
   1573     return id;
   1574 }
   1575 
   1576 status_t AudioFlinger::closeOutput(audio_io_handle_t output)
   1577 {
   1578     return closeOutput_nonvirtual(output);
   1579 }
   1580 
   1581 status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
   1582 {
   1583     // keep strong reference on the playback thread so that
   1584     // it is not destroyed while exit() is executed
   1585     sp<PlaybackThread> thread;
   1586     {
   1587         Mutex::Autolock _l(mLock);
   1588         thread = checkPlaybackThread_l(output);
   1589         if (thread == NULL) {
   1590             return BAD_VALUE;
   1591         }
   1592 
   1593         ALOGV("closeOutput() %d", output);
   1594 
   1595         if (thread->type() == ThreadBase::MIXER) {
   1596             for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   1597                 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
   1598                     DuplicatingThread *dupThread =
   1599                             (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
   1600                     dupThread->removeOutputTrack((MixerThread *)thread.get());
   1601 
   1602                 }
   1603             }
   1604         }
   1605 
   1606 
   1607         mPlaybackThreads.removeItem(output);
   1608         // save all effects to the default thread
   1609         if (mPlaybackThreads.size()) {
   1610             PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
   1611             if (dstThread != NULL) {
   1612                 // audioflinger lock is held here so the acquisition order of thread locks does not
   1613                 // matter
   1614                 Mutex::Autolock _dl(dstThread->mLock);
   1615                 Mutex::Autolock _sl(thread->mLock);
   1616                 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
   1617                 for (size_t i = 0; i < effectChains.size(); i ++) {
   1618                     moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true);
   1619                 }
   1620             }
   1621         }
   1622         audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
   1623     }
   1624     thread->exit();
   1625     // The thread entity (active unit of execution) is no longer running here,
   1626     // but the ThreadBase container still exists.
   1627 
   1628     if (thread->type() != ThreadBase::DUPLICATING) {
   1629         AudioStreamOut *out = thread->clearOutput();
   1630         ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
   1631         // from now on thread->mOutput is NULL
   1632         out->hwDev()->close_output_stream(out->hwDev(), out->stream);
   1633         delete out;
   1634     }
   1635     return NO_ERROR;
   1636 }
   1637 
   1638 status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
   1639 {
   1640     Mutex::Autolock _l(mLock);
   1641     PlaybackThread *thread = checkPlaybackThread_l(output);
   1642 
   1643     if (thread == NULL) {
   1644         return BAD_VALUE;
   1645     }
   1646 
   1647     ALOGV("suspendOutput() %d", output);
   1648     thread->suspend();
   1649 
   1650     return NO_ERROR;
   1651 }
   1652 
   1653 status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
   1654 {
   1655     Mutex::Autolock _l(mLock);
   1656     PlaybackThread *thread = checkPlaybackThread_l(output);
   1657 
   1658     if (thread == NULL) {
   1659         return BAD_VALUE;
   1660     }
   1661 
   1662     ALOGV("restoreOutput() %d", output);
   1663 
   1664     thread->restore();
   1665 
   1666     return NO_ERROR;
   1667 }
   1668 
   1669 audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
   1670                                           audio_devices_t *pDevices,
   1671                                           uint32_t *pSamplingRate,
   1672                                           audio_format_t *pFormat,
   1673                                           audio_channel_mask_t *pChannelMask)
   1674 {
   1675     status_t status;
   1676     RecordThread *thread = NULL;
   1677     struct audio_config config;
   1678     config.sample_rate = (pSamplingRate != NULL) ? *pSamplingRate : 0;
   1679     config.channel_mask = (pChannelMask != NULL) ? *pChannelMask : 0;
   1680     config.format = (pFormat != NULL) ? *pFormat : AUDIO_FORMAT_DEFAULT;
   1681 
   1682     uint32_t reqSamplingRate = config.sample_rate;
   1683     audio_format_t reqFormat = config.format;
   1684     audio_channel_mask_t reqChannels = config.channel_mask;
   1685     audio_stream_in_t *inStream = NULL;
   1686     AudioHwDevice *inHwDev;
   1687 
   1688     if (pDevices == NULL || *pDevices == 0) {
   1689         return 0;
   1690     }
   1691 
   1692     Mutex::Autolock _l(mLock);
   1693 
   1694     inHwDev = findSuitableHwDev_l(module, *pDevices);
   1695     if (inHwDev == NULL)
   1696         return 0;
   1697 
   1698     audio_hw_device_t *inHwHal = inHwDev->hwDevice();
   1699     audio_io_handle_t id = nextUniqueId();
   1700 
   1701     status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
   1702                                         &inStream);
   1703     ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, "
   1704             "status %d",
   1705             inStream,
   1706             config.sample_rate,
   1707             config.format,
   1708             config.channel_mask,
   1709             status);
   1710 
   1711     // If the input could not be opened with the requested parameters and we can handle the
   1712     // conversion internally, try to open again with the proposed parameters. The AudioFlinger can
   1713     // resample the input and do mono to stereo or stereo to mono conversions on 16 bit PCM inputs.
   1714     if (status == BAD_VALUE &&
   1715         reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
   1716         (config.sample_rate <= 2 * reqSamplingRate) &&
   1717         (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
   1718         ALOGV("openInput() reopening with proposed sampling rate and channel mask");
   1719         inStream = NULL;
   1720         status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
   1721     }
   1722 
   1723     if (status == NO_ERROR && inStream != NULL) {
   1724 
   1725 #ifdef TEE_SINK
   1726         // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
   1727         // or (re-)create if current Pipe is idle and does not match the new format
   1728         sp<NBAIO_Sink> teeSink;
   1729         enum {
   1730             TEE_SINK_NO,    // don't copy input
   1731             TEE_SINK_NEW,   // copy input using a new pipe
   1732             TEE_SINK_OLD,   // copy input using an existing pipe
   1733         } kind;
   1734         NBAIO_Format format = Format_from_SR_C(inStream->common.get_sample_rate(&inStream->common),
   1735                                         popcount(inStream->common.get_channels(&inStream->common)));
   1736         if (!mTeeSinkInputEnabled) {
   1737             kind = TEE_SINK_NO;
   1738         } else if (format == Format_Invalid) {
   1739             kind = TEE_SINK_NO;
   1740         } else if (mRecordTeeSink == 0) {
   1741             kind = TEE_SINK_NEW;
   1742         } else if (mRecordTeeSink->getStrongCount() != 1) {
   1743             kind = TEE_SINK_NO;
   1744         } else if (format == mRecordTeeSink->format()) {
   1745             kind = TEE_SINK_OLD;
   1746         } else {
   1747             kind = TEE_SINK_NEW;
   1748         }
   1749         switch (kind) {
   1750         case TEE_SINK_NEW: {
   1751             Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
   1752             size_t numCounterOffers = 0;
   1753             const NBAIO_Format offers[1] = {format};
   1754             ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
   1755             ALOG_ASSERT(index == 0);
   1756             PipeReader *pipeReader = new PipeReader(*pipe);
   1757             numCounterOffers = 0;
   1758             index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
   1759             ALOG_ASSERT(index == 0);
   1760             mRecordTeeSink = pipe;
   1761             mRecordTeeSource = pipeReader;
   1762             teeSink = pipe;
   1763             }
   1764             break;
   1765         case TEE_SINK_OLD:
   1766             teeSink = mRecordTeeSink;
   1767             break;
   1768         case TEE_SINK_NO:
   1769         default:
   1770             break;
   1771         }
   1772 #endif
   1773 
   1774         AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
   1775 
   1776         // Start record thread
   1777         // RecordThread requires both input and output device indication to forward to audio
   1778         // pre processing modules
   1779         thread = new RecordThread(this,
   1780                                   input,
   1781                                   reqSamplingRate,
   1782                                   reqChannels,
   1783                                   id,
   1784                                   primaryOutputDevice_l(),
   1785                                   *pDevices
   1786 #ifdef TEE_SINK
   1787                                   , teeSink
   1788 #endif
   1789                                   );
   1790         mRecordThreads.add(id, thread);
   1791         ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
   1792         if (pSamplingRate != NULL) {
   1793             *pSamplingRate = reqSamplingRate;
   1794         }
   1795         if (pFormat != NULL) {
   1796             *pFormat = config.format;
   1797         }
   1798         if (pChannelMask != NULL) {
   1799             *pChannelMask = reqChannels;
   1800         }
   1801 
   1802         // notify client processes of the new input creation
   1803         thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
   1804         return id;
   1805     }
   1806 
   1807     return 0;
   1808 }
   1809 
   1810 status_t AudioFlinger::closeInput(audio_io_handle_t input)
   1811 {
   1812     return closeInput_nonvirtual(input);
   1813 }
   1814 
   1815 status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
   1816 {
   1817     // keep strong reference on the record thread so that
   1818     // it is not destroyed while exit() is executed
   1819     sp<RecordThread> thread;
   1820     {
   1821         Mutex::Autolock _l(mLock);
   1822         thread = checkRecordThread_l(input);
   1823         if (thread == 0) {
   1824             return BAD_VALUE;
   1825         }
   1826 
   1827         ALOGV("closeInput() %d", input);
   1828         audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
   1829         mRecordThreads.removeItem(input);
   1830     }
   1831     thread->exit();
   1832     // The thread entity (active unit of execution) is no longer running here,
   1833     // but the ThreadBase container still exists.
   1834 
   1835     AudioStreamIn *in = thread->clearInput();
   1836     ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
   1837     // from now on thread->mInput is NULL
   1838     in->hwDev()->close_input_stream(in->hwDev(), in->stream);
   1839     delete in;
   1840 
   1841     return NO_ERROR;
   1842 }
   1843 
   1844 status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
   1845 {
   1846     Mutex::Autolock _l(mLock);
   1847     ALOGV("setStreamOutput() stream %d to output %d", stream, output);
   1848 
   1849     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   1850         PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
   1851         thread->invalidateTracks(stream);
   1852     }
   1853 
   1854     return NO_ERROR;
   1855 }
   1856 
   1857 
   1858 int AudioFlinger::newAudioSessionId()
   1859 {
   1860     return nextUniqueId();
   1861 }
   1862 
   1863 void AudioFlinger::acquireAudioSessionId(int audioSession)
   1864 {
   1865     Mutex::Autolock _l(mLock);
   1866     pid_t caller = IPCThreadState::self()->getCallingPid();
   1867     ALOGV("acquiring %d from %d", audioSession, caller);
   1868 
   1869     // Ignore requests received from processes not known as notification client. The request
   1870     // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
   1871     // called from a different pid leaving a stale session reference.  Also we don't know how
   1872     // to clear this reference if the client process dies.
   1873     if (mNotificationClients.indexOfKey(caller) < 0) {
   1874         ALOGV("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
   1875         return;
   1876     }
   1877 
   1878     size_t num = mAudioSessionRefs.size();
   1879     for (size_t i = 0; i< num; i++) {
   1880         AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
   1881         if (ref->mSessionid == audioSession && ref->mPid == caller) {
   1882             ref->mCnt++;
   1883             ALOGV(" incremented refcount to %d", ref->mCnt);
   1884             return;
   1885         }
   1886     }
   1887     mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
   1888     ALOGV(" added new entry for %d", audioSession);
   1889 }
   1890 
   1891 void AudioFlinger::releaseAudioSessionId(int audioSession)
   1892 {
   1893     Mutex::Autolock _l(mLock);
   1894     pid_t caller = IPCThreadState::self()->getCallingPid();
   1895     ALOGV("releasing %d from %d", audioSession, caller);
   1896     size_t num = mAudioSessionRefs.size();
   1897     for (size_t i = 0; i< num; i++) {
   1898         AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
   1899         if (ref->mSessionid == audioSession && ref->mPid == caller) {
   1900             ref->mCnt--;
   1901             ALOGV(" decremented refcount to %d", ref->mCnt);
   1902             if (ref->mCnt == 0) {
   1903                 mAudioSessionRefs.removeAt(i);
   1904                 delete ref;
   1905                 purgeStaleEffects_l();
   1906             }
   1907             return;
   1908         }
   1909     }
   1910     // If the caller is mediaserver it is likely that the session being released was acquired
   1911     // on behalf of a process not in notification clients and we ignore the warning.
   1912     ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
   1913 }
   1914 
   1915 void AudioFlinger::purgeStaleEffects_l() {
   1916 
   1917     ALOGV("purging stale effects");
   1918 
   1919     Vector< sp<EffectChain> > chains;
   1920 
   1921     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   1922         sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
   1923         for (size_t j = 0; j < t->mEffectChains.size(); j++) {
   1924             sp<EffectChain> ec = t->mEffectChains[j];
   1925             if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
   1926                 chains.push(ec);
   1927             }
   1928         }
   1929     }
   1930     for (size_t i = 0; i < mRecordThreads.size(); i++) {
   1931         sp<RecordThread> t = mRecordThreads.valueAt(i);
   1932         for (size_t j = 0; j < t->mEffectChains.size(); j++) {
   1933             sp<EffectChain> ec = t->mEffectChains[j];
   1934             chains.push(ec);
   1935         }
   1936     }
   1937 
   1938     for (size_t i = 0; i < chains.size(); i++) {
   1939         sp<EffectChain> ec = chains[i];
   1940         int sessionid = ec->sessionId();
   1941         sp<ThreadBase> t = ec->mThread.promote();
   1942         if (t == 0) {
   1943             continue;
   1944         }
   1945         size_t numsessionrefs = mAudioSessionRefs.size();
   1946         bool found = false;
   1947         for (size_t k = 0; k < numsessionrefs; k++) {
   1948             AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
   1949             if (ref->mSessionid == sessionid) {
   1950                 ALOGV(" session %d still exists for %d with %d refs",
   1951                     sessionid, ref->mPid, ref->mCnt);
   1952                 found = true;
   1953                 break;
   1954             }
   1955         }
   1956         if (!found) {
   1957             Mutex::Autolock _l (t->mLock);
   1958             // remove all effects from the chain
   1959             while (ec->mEffects.size()) {
   1960                 sp<EffectModule> effect = ec->mEffects[0];
   1961                 effect->unPin();
   1962                 t->removeEffect_l(effect);
   1963                 if (effect->purgeHandles()) {
   1964                     t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
   1965                 }
   1966                 AudioSystem::unregisterEffect(effect->id());
   1967             }
   1968         }
   1969     }
   1970     return;
   1971 }
   1972 
   1973 // checkPlaybackThread_l() must be called with AudioFlinger::mLock held
   1974 AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
   1975 {
   1976     return mPlaybackThreads.valueFor(output).get();
   1977 }
   1978 
   1979 // checkMixerThread_l() must be called with AudioFlinger::mLock held
   1980 AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
   1981 {
   1982     PlaybackThread *thread = checkPlaybackThread_l(output);
   1983     return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
   1984 }
   1985 
   1986 // checkRecordThread_l() must be called with AudioFlinger::mLock held
   1987 AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
   1988 {
   1989     return mRecordThreads.valueFor(input).get();
   1990 }
   1991 
   1992 uint32_t AudioFlinger::nextUniqueId()
   1993 {
   1994     return android_atomic_inc(&mNextUniqueId);
   1995 }
   1996 
   1997 AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
   1998 {
   1999     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   2000         PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
   2001         AudioStreamOut *output = thread->getOutput();
   2002         if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
   2003             return thread;
   2004         }
   2005     }
   2006     return NULL;
   2007 }
   2008 
   2009 audio_devices_t AudioFlinger::primaryOutputDevice_l() const
   2010 {
   2011     PlaybackThread *thread = primaryPlaybackThread_l();
   2012 
   2013     if (thread == NULL) {
   2014         return 0;
   2015     }
   2016 
   2017     return thread->outDevice();
   2018 }
   2019 
   2020 sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
   2021                                     int triggerSession,
   2022                                     int listenerSession,
   2023                                     sync_event_callback_t callBack,
   2024                                     void *cookie)
   2025 {
   2026     Mutex::Autolock _l(mLock);
   2027 
   2028     sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
   2029     status_t playStatus = NAME_NOT_FOUND;
   2030     status_t recStatus = NAME_NOT_FOUND;
   2031     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   2032         playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
   2033         if (playStatus == NO_ERROR) {
   2034             return event;
   2035         }
   2036     }
   2037     for (size_t i = 0; i < mRecordThreads.size(); i++) {
   2038         recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
   2039         if (recStatus == NO_ERROR) {
   2040             return event;
   2041         }
   2042     }
   2043     if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
   2044         mPendingSyncEvents.add(event);
   2045     } else {
   2046         ALOGV("createSyncEvent() invalid event %d", event->type());
   2047         event.clear();
   2048     }
   2049     return event;
   2050 }
   2051 
   2052 // ----------------------------------------------------------------------------
   2053 //  Effect management
   2054 // ----------------------------------------------------------------------------
   2055 
   2056 
   2057 status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
   2058 {
   2059     Mutex::Autolock _l(mLock);
   2060     return EffectQueryNumberEffects(numEffects);
   2061 }
   2062 
   2063 status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
   2064 {
   2065     Mutex::Autolock _l(mLock);
   2066     return EffectQueryEffect(index, descriptor);
   2067 }
   2068 
   2069 status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
   2070         effect_descriptor_t *descriptor) const
   2071 {
   2072     Mutex::Autolock _l(mLock);
   2073     return EffectGetDescriptor(pUuid, descriptor);
   2074 }
   2075 
   2076 
   2077 sp<IEffect> AudioFlinger::createEffect(
   2078         effect_descriptor_t *pDesc,
   2079         const sp<IEffectClient>& effectClient,
   2080         int32_t priority,
   2081         audio_io_handle_t io,
   2082         int sessionId,
   2083         status_t *status,
   2084         int *id,
   2085         int *enabled)
   2086 {
   2087     status_t lStatus = NO_ERROR;
   2088     sp<EffectHandle> handle;
   2089     effect_descriptor_t desc;
   2090 
   2091     pid_t pid = IPCThreadState::self()->getCallingPid();
   2092     ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
   2093             pid, effectClient.get(), priority, sessionId, io);
   2094 
   2095     if (pDesc == NULL) {
   2096         lStatus = BAD_VALUE;
   2097         goto Exit;
   2098     }
   2099 
   2100     // check audio settings permission for global effects
   2101     if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
   2102         lStatus = PERMISSION_DENIED;
   2103         goto Exit;
   2104     }
   2105 
   2106     // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
   2107     // that can only be created by audio policy manager (running in same process)
   2108     if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
   2109         lStatus = PERMISSION_DENIED;
   2110         goto Exit;
   2111     }
   2112 
   2113     {
   2114         if (!EffectIsNullUuid(&pDesc->uuid)) {
   2115             // if uuid is specified, request effect descriptor
   2116             lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
   2117             if (lStatus < 0) {
   2118                 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
   2119                 goto Exit;
   2120             }
   2121         } else {
   2122             // if uuid is not specified, look for an available implementation
   2123             // of the required type in effect factory
   2124             if (EffectIsNullUuid(&pDesc->type)) {
   2125                 ALOGW("createEffect() no effect type");
   2126                 lStatus = BAD_VALUE;
   2127                 goto Exit;
   2128             }
   2129             uint32_t numEffects = 0;
   2130             effect_descriptor_t d;
   2131             d.flags = 0; // prevent compiler warning
   2132             bool found = false;
   2133 
   2134             lStatus = EffectQueryNumberEffects(&numEffects);
   2135             if (lStatus < 0) {
   2136                 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
   2137                 goto Exit;
   2138             }
   2139             for (uint32_t i = 0; i < numEffects; i++) {
   2140                 lStatus = EffectQueryEffect(i, &desc);
   2141                 if (lStatus < 0) {
   2142                     ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
   2143                     continue;
   2144                 }
   2145                 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
   2146                     // If matching type found save effect descriptor. If the session is
   2147                     // 0 and the effect is not auxiliary, continue enumeration in case
   2148                     // an auxiliary version of this effect type is available
   2149                     found = true;
   2150                     d = desc;
   2151                     if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
   2152                             (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
   2153                         break;
   2154                     }
   2155                 }
   2156             }
   2157             if (!found) {
   2158                 lStatus = BAD_VALUE;
   2159                 ALOGW("createEffect() effect not found");
   2160                 goto Exit;
   2161             }
   2162             // For same effect type, chose auxiliary version over insert version if
   2163             // connect to output mix (Compliance to OpenSL ES)
   2164             if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
   2165                     (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
   2166                 desc = d;
   2167             }
   2168         }
   2169 
   2170         // Do not allow auxiliary effects on a session different from 0 (output mix)
   2171         if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
   2172              (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
   2173             lStatus = INVALID_OPERATION;
   2174             goto Exit;
   2175         }
   2176 
   2177         // check recording permission for visualizer
   2178         if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
   2179             !recordingAllowed()) {
   2180             lStatus = PERMISSION_DENIED;
   2181             goto Exit;
   2182         }
   2183 
   2184         // return effect descriptor
   2185         *pDesc = desc;
   2186         if (io == 0 && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
   2187             // if the output returned by getOutputForEffect() is removed before we lock the
   2188             // mutex below, the call to checkPlaybackThread_l(io) below will detect it
   2189             // and we will exit safely
   2190             io = AudioSystem::getOutputForEffect(&desc);
   2191             ALOGV("createEffect got output %d", io);
   2192         }
   2193 
   2194         Mutex::Autolock _l(mLock);
   2195 
   2196         // If output is not specified try to find a matching audio session ID in one of the
   2197         // output threads.
   2198         // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
   2199         // because of code checking output when entering the function.
   2200         // Note: io is never 0 when creating an effect on an input
   2201         if (io == 0) {
   2202             if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
   2203                 // output must be specified by AudioPolicyManager when using session
   2204                 // AUDIO_SESSION_OUTPUT_STAGE
   2205                 lStatus = BAD_VALUE;
   2206                 goto Exit;
   2207             }
   2208             // look for the thread where the specified audio session is present
   2209             for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   2210                 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
   2211                     io = mPlaybackThreads.keyAt(i);
   2212                     break;
   2213                 }
   2214             }
   2215             if (io == 0) {
   2216                 for (size_t i = 0; i < mRecordThreads.size(); i++) {
   2217                     if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
   2218                         io = mRecordThreads.keyAt(i);
   2219                         break;
   2220                     }
   2221                 }
   2222             }
   2223             // If no output thread contains the requested session ID, default to
   2224             // first output. The effect chain will be moved to the correct output
   2225             // thread when a track with the same session ID is created
   2226             if (io == 0 && mPlaybackThreads.size()) {
   2227                 io = mPlaybackThreads.keyAt(0);
   2228             }
   2229             ALOGV("createEffect() got io %d for effect %s", io, desc.name);
   2230         }
   2231         ThreadBase *thread = checkRecordThread_l(io);
   2232         if (thread == NULL) {
   2233             thread = checkPlaybackThread_l(io);
   2234             if (thread == NULL) {
   2235                 ALOGE("createEffect() unknown output thread");
   2236                 lStatus = BAD_VALUE;
   2237                 goto Exit;
   2238             }
   2239         }
   2240 
   2241         sp<Client> client = registerPid_l(pid);
   2242 
   2243         // create effect on selected output thread
   2244         handle = thread->createEffect_l(client, effectClient, priority, sessionId,
   2245                 &desc, enabled, &lStatus);
   2246         if (handle != 0 && id != NULL) {
   2247             *id = handle->id();
   2248         }
   2249     }
   2250 
   2251 Exit:
   2252     if (status != NULL) {
   2253         *status = lStatus;
   2254     }
   2255     return handle;
   2256 }
   2257 
   2258 status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
   2259         audio_io_handle_t dstOutput)
   2260 {
   2261     ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
   2262             sessionId, srcOutput, dstOutput);
   2263     Mutex::Autolock _l(mLock);
   2264     if (srcOutput == dstOutput) {
   2265         ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
   2266         return NO_ERROR;
   2267     }
   2268     PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
   2269     if (srcThread == NULL) {
   2270         ALOGW("moveEffects() bad srcOutput %d", srcOutput);
   2271         return BAD_VALUE;
   2272     }
   2273     PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
   2274     if (dstThread == NULL) {
   2275         ALOGW("moveEffects() bad dstOutput %d", dstOutput);
   2276         return BAD_VALUE;
   2277     }
   2278 
   2279     Mutex::Autolock _dl(dstThread->mLock);
   2280     Mutex::Autolock _sl(srcThread->mLock);
   2281     return moveEffectChain_l(sessionId, srcThread, dstThread, false);
   2282 }
   2283 
   2284 // moveEffectChain_l must be called with both srcThread and dstThread mLocks held
   2285 status_t AudioFlinger::moveEffectChain_l(int sessionId,
   2286                                    AudioFlinger::PlaybackThread *srcThread,
   2287                                    AudioFlinger::PlaybackThread *dstThread,
   2288                                    bool reRegister)
   2289 {
   2290     ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
   2291             sessionId, srcThread, dstThread);
   2292 
   2293     sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
   2294     if (chain == 0) {
   2295         ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
   2296                 sessionId, srcThread);
   2297         return INVALID_OPERATION;
   2298     }
   2299 
   2300     // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
   2301     // so that a new chain is created with correct parameters when first effect is added. This is
   2302     // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
   2303     // removed.
   2304     srcThread->removeEffectChain_l(chain);
   2305 
   2306     // transfer all effects one by one so that new effect chain is created on new thread with
   2307     // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
   2308     sp<EffectChain> dstChain;
   2309     uint32_t strategy = 0; // prevent compiler warning
   2310     sp<EffectModule> effect = chain->getEffectFromId_l(0);
   2311     Vector< sp<EffectModule> > removed;
   2312     status_t status = NO_ERROR;
   2313     while (effect != 0) {
   2314         srcThread->removeEffect_l(effect);
   2315         removed.add(effect);
   2316         status = dstThread->addEffect_l(effect);
   2317         if (status != NO_ERROR) {
   2318             break;
   2319         }
   2320         // removeEffect_l() has stopped the effect if it was active so it must be restarted
   2321         if (effect->state() == EffectModule::ACTIVE ||
   2322                 effect->state() == EffectModule::STOPPING) {
   2323             effect->start();
   2324         }
   2325         // if the move request is not received from audio policy manager, the effect must be
   2326         // re-registered with the new strategy and output
   2327         if (dstChain == 0) {
   2328             dstChain = effect->chain().promote();
   2329             if (dstChain == 0) {
   2330                 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
   2331                 status = NO_INIT;
   2332                 break;
   2333             }
   2334             strategy = dstChain->strategy();
   2335         }
   2336         if (reRegister) {
   2337             AudioSystem::unregisterEffect(effect->id());
   2338             AudioSystem::registerEffect(&effect->desc(),
   2339                                         dstThread->id(),
   2340                                         strategy,
   2341                                         sessionId,
   2342                                         effect->id());
   2343             AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
   2344         }
   2345         effect = chain->getEffectFromId_l(0);
   2346     }
   2347 
   2348     if (status != NO_ERROR) {
   2349         for (size_t i = 0; i < removed.size(); i++) {
   2350             srcThread->addEffect_l(removed[i]);
   2351             if (dstChain != 0 && reRegister) {
   2352                 AudioSystem::unregisterEffect(removed[i]->id());
   2353                 AudioSystem::registerEffect(&removed[i]->desc(),
   2354                                             srcThread->id(),
   2355                                             strategy,
   2356                                             sessionId,
   2357                                             removed[i]->id());
   2358                 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
   2359             }
   2360         }
   2361     }
   2362 
   2363     return status;
   2364 }
   2365 
   2366 bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
   2367 {
   2368     if (mGlobalEffectEnableTime != 0 &&
   2369             ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
   2370         return true;
   2371     }
   2372 
   2373     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   2374         sp<EffectChain> ec =
   2375                 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
   2376         if (ec != 0 && ec->isNonOffloadableEnabled()) {
   2377             return true;
   2378         }
   2379     }
   2380     return false;
   2381 }
   2382 
   2383 void AudioFlinger::onNonOffloadableGlobalEffectEnable()
   2384 {
   2385     Mutex::Autolock _l(mLock);
   2386 
   2387     mGlobalEffectEnableTime = systemTime();
   2388 
   2389     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
   2390         sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
   2391         if (t->mType == ThreadBase::OFFLOAD) {
   2392             t->invalidateTracks(AUDIO_STREAM_MUSIC);
   2393         }
   2394     }
   2395 
   2396 }
   2397 
   2398 struct Entry {
   2399 #define MAX_NAME 32     // %Y%m%d%H%M%S_%d.wav
   2400     char mName[MAX_NAME];
   2401 };
   2402 
   2403 int comparEntry(const void *p1, const void *p2)
   2404 {
   2405     return strcmp(((const Entry *) p1)->mName, ((const Entry *) p2)->mName);
   2406 }
   2407 
   2408 #ifdef TEE_SINK
   2409 void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
   2410 {
   2411     NBAIO_Source *teeSource = source.get();
   2412     if (teeSource != NULL) {
   2413         // .wav rotation
   2414         // There is a benign race condition if 2 threads call this simultaneously.
   2415         // They would both traverse the directory, but the result would simply be
   2416         // failures at unlink() which are ignored.  It's also unlikely since
   2417         // normally dumpsys is only done by bugreport or from the command line.
   2418         char teePath[32+256];
   2419         strcpy(teePath, "/data/misc/media");
   2420         size_t teePathLen = strlen(teePath);
   2421         DIR *dir = opendir(teePath);
   2422         teePath[teePathLen++] = '/';
   2423         if (dir != NULL) {
   2424 #define MAX_SORT 20 // number of entries to sort
   2425 #define MAX_KEEP 10 // number of entries to keep
   2426             struct Entry entries[MAX_SORT];
   2427             size_t entryCount = 0;
   2428             while (entryCount < MAX_SORT) {
   2429                 struct dirent de;
   2430                 struct dirent *result = NULL;
   2431                 int rc = readdir_r(dir, &de, &result);
   2432                 if (rc != 0) {
   2433                     ALOGW("readdir_r failed %d", rc);
   2434                     break;
   2435                 }
   2436                 if (result == NULL) {
   2437                     break;
   2438                 }
   2439                 if (result != &de) {
   2440                     ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
   2441                     break;
   2442                 }
   2443                 // ignore non .wav file entries
   2444                 size_t nameLen = strlen(de.d_name);
   2445                 if (nameLen <= 4 || nameLen >= MAX_NAME ||
   2446                         strcmp(&de.d_name[nameLen - 4], ".wav")) {
   2447                     continue;
   2448                 }
   2449                 strcpy(entries[entryCount++].mName, de.d_name);
   2450             }
   2451             (void) closedir(dir);
   2452             if (entryCount > MAX_KEEP) {
   2453                 qsort(entries, entryCount, sizeof(Entry), comparEntry);
   2454                 for (size_t i = 0; i < entryCount - MAX_KEEP; ++i) {
   2455                     strcpy(&teePath[teePathLen], entries[i].mName);
   2456                     (void) unlink(teePath);
   2457                 }
   2458             }
   2459         } else {
   2460             if (fd >= 0) {
   2461                 fdprintf(fd, "unable to rotate tees in %s: %s\n", teePath, strerror(errno));
   2462             }
   2463         }
   2464         char teeTime[16];
   2465         struct timeval tv;
   2466         gettimeofday(&tv, NULL);
   2467         struct tm tm;
   2468         localtime_r(&tv.tv_sec, &tm);
   2469         strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
   2470         snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
   2471         // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
   2472         int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
   2473         if (teeFd >= 0) {
   2474             char wavHeader[44];
   2475             memcpy(wavHeader,
   2476                 "RIFF\0\0\0\0WAVEfmt \20\0\0\0\1\0\2\0\104\254\0\0\0\0\0\0\4\0\20\0data\0\0\0\0",
   2477                 sizeof(wavHeader));
   2478             NBAIO_Format format = teeSource->format();
   2479             unsigned channelCount = Format_channelCount(format);
   2480             ALOG_ASSERT(channelCount <= FCC_2);
   2481             uint32_t sampleRate = Format_sampleRate(format);
   2482             wavHeader[22] = channelCount;       // number of channels
   2483             wavHeader[24] = sampleRate;         // sample rate
   2484             wavHeader[25] = sampleRate >> 8;
   2485             wavHeader[32] = channelCount * 2;   // block alignment
   2486             write(teeFd, wavHeader, sizeof(wavHeader));
   2487             size_t total = 0;
   2488             bool firstRead = true;
   2489             for (;;) {
   2490 #define TEE_SINK_READ 1024
   2491                 short buffer[TEE_SINK_READ * FCC_2];
   2492                 size_t count = TEE_SINK_READ;
   2493                 ssize_t actual = teeSource->read(buffer, count,
   2494                         AudioBufferProvider::kInvalidPTS);
   2495                 bool wasFirstRead = firstRead;
   2496                 firstRead = false;
   2497                 if (actual <= 0) {
   2498                     if (actual == (ssize_t) OVERRUN && wasFirstRead) {
   2499                         continue;
   2500                     }
   2501                     break;
   2502                 }
   2503                 ALOG_ASSERT(actual <= (ssize_t)count);
   2504                 write(teeFd, buffer, actual * channelCount * sizeof(short));
   2505                 total += actual;
   2506             }
   2507             lseek(teeFd, (off_t) 4, SEEK_SET);
   2508             uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
   2509             write(teeFd, &temp, sizeof(temp));
   2510             lseek(teeFd, (off_t) 40, SEEK_SET);
   2511             temp =  total * channelCount * sizeof(short);
   2512             write(teeFd, &temp, sizeof(temp));
   2513             close(teeFd);
   2514             if (fd >= 0) {
   2515                 fdprintf(fd, "tee copied to %s\n", teePath);
   2516             }
   2517         } else {
   2518             if (fd >= 0) {
   2519                 fdprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
   2520             }
   2521         }
   2522     }
   2523 }
   2524 #endif
   2525 
   2526 // ----------------------------------------------------------------------------
   2527 
   2528 status_t AudioFlinger::onTransact(
   2529         uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
   2530 {
   2531     return BnAudioFlinger::onTransact(code, data, reply, flags);
   2532 }
   2533 
   2534 }; // namespace android
   2535