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