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