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