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