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