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