AudioFlinger.cpp revision cf7863ea8d9137aadf6bfd9756eb07ebd1c81b5c
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    mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
807    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
808        audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
809        status_t result = dev->set_mic_mute(dev, state);
810        if (result != NO_ERROR) {
811            ret = result;
812        }
813    }
814    mHardwareStatus = AUDIO_HW_IDLE;
815    return ret;
816}
817
818bool AudioFlinger::getMicMute() const
819{
820    status_t ret = initCheck();
821    if (ret != NO_ERROR) {
822        return false;
823    }
824
825    bool state = AUDIO_MODE_INVALID;
826    AutoMutex lock(mHardwareLock);
827    audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
828    mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
829    dev->get_mic_mute(dev, &state);
830    mHardwareStatus = AUDIO_HW_IDLE;
831    return state;
832}
833
834status_t AudioFlinger::setMasterMute(bool muted)
835{
836    status_t ret = initCheck();
837    if (ret != NO_ERROR) {
838        return ret;
839    }
840
841    // check calling permissions
842    if (!settingsAllowed()) {
843        return PERMISSION_DENIED;
844    }
845
846    Mutex::Autolock _l(mLock);
847    mMasterMute = muted;
848
849    // Set master mute in the HALs which support it.
850    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
851        AutoMutex lock(mHardwareLock);
852        AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
853
854        mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
855        if (dev->canSetMasterMute()) {
856            dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
857        }
858        mHardwareStatus = AUDIO_HW_IDLE;
859    }
860
861    // Now set the master mute in each playback thread.  Playback threads
862    // assigned to HALs which do not have master mute support will apply master
863    // mute during the mix operation.  Threads with HALs which do support master
864    // mute will simply ignore the setting.
865    for (size_t i = 0; i < mPlaybackThreads.size(); i++)
866        mPlaybackThreads.valueAt(i)->setMasterMute(muted);
867
868    return NO_ERROR;
869}
870
871float AudioFlinger::masterVolume() const
872{
873    Mutex::Autolock _l(mLock);
874    return masterVolume_l();
875}
876
877bool AudioFlinger::masterMute() const
878{
879    Mutex::Autolock _l(mLock);
880    return masterMute_l();
881}
882
883float AudioFlinger::masterVolume_l() const
884{
885    return mMasterVolume;
886}
887
888bool AudioFlinger::masterMute_l() const
889{
890    return mMasterMute;
891}
892
893status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
894        audio_io_handle_t output)
895{
896    // check calling permissions
897    if (!settingsAllowed()) {
898        return PERMISSION_DENIED;
899    }
900
901    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
902        ALOGE("setStreamVolume() invalid stream %d", stream);
903        return BAD_VALUE;
904    }
905
906    AutoMutex lock(mLock);
907    PlaybackThread *thread = NULL;
908    if (output != AUDIO_IO_HANDLE_NONE) {
909        thread = checkPlaybackThread_l(output);
910        if (thread == NULL) {
911            return BAD_VALUE;
912        }
913    }
914
915    mStreamTypes[stream].volume = value;
916
917    if (thread == NULL) {
918        for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
919            mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
920        }
921    } else {
922        thread->setStreamVolume(stream, value);
923    }
924
925    return NO_ERROR;
926}
927
928status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
929{
930    // check calling permissions
931    if (!settingsAllowed()) {
932        return PERMISSION_DENIED;
933    }
934
935    if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
936        uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
937        ALOGE("setStreamMute() invalid stream %d", stream);
938        return BAD_VALUE;
939    }
940
941    AutoMutex lock(mLock);
942    mStreamTypes[stream].mute = muted;
943    for (size_t i = 0; i < mPlaybackThreads.size(); i++)
944        mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
945
946    return NO_ERROR;
947}
948
949float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
950{
951    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
952        return 0.0f;
953    }
954
955    AutoMutex lock(mLock);
956    float volume;
957    if (output != AUDIO_IO_HANDLE_NONE) {
958        PlaybackThread *thread = checkPlaybackThread_l(output);
959        if (thread == NULL) {
960            return 0.0f;
961        }
962        volume = thread->streamVolume(stream);
963    } else {
964        volume = streamVolume_l(stream);
965    }
966
967    return volume;
968}
969
970bool AudioFlinger::streamMute(audio_stream_type_t stream) const
971{
972    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
973        return true;
974    }
975
976    AutoMutex lock(mLock);
977    return streamMute_l(stream);
978}
979
980status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
981{
982    ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
983            ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
984
985    // check calling permissions
986    if (!settingsAllowed()) {
987        return PERMISSION_DENIED;
988    }
989
990    // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
991    if (ioHandle == AUDIO_IO_HANDLE_NONE) {
992        Mutex::Autolock _l(mLock);
993        status_t final_result = NO_ERROR;
994        {
995            AutoMutex lock(mHardwareLock);
996            mHardwareStatus = AUDIO_HW_SET_PARAMETER;
997            for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
998                audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
999                status_t result = dev->set_parameters(dev, keyValuePairs.string());
1000                final_result = result ?: final_result;
1001            }
1002            mHardwareStatus = AUDIO_HW_IDLE;
1003        }
1004        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1005        AudioParameter param = AudioParameter(keyValuePairs);
1006        String8 value;
1007        if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
1008            bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
1009            if (mBtNrecIsOff != btNrecIsOff) {
1010                for (size_t i = 0; i < mRecordThreads.size(); i++) {
1011                    sp<RecordThread> thread = mRecordThreads.valueAt(i);
1012                    audio_devices_t device = thread->inDevice();
1013                    bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1014                    // collect all of the thread's session IDs
1015                    KeyedVector<int, bool> ids = thread->sessionIds();
1016                    // suspend effects associated with those session IDs
1017                    for (size_t j = 0; j < ids.size(); ++j) {
1018                        int sessionId = ids.keyAt(j);
1019                        thread->setEffectSuspended(FX_IID_AEC,
1020                                                   suspend,
1021                                                   sessionId);
1022                        thread->setEffectSuspended(FX_IID_NS,
1023                                                   suspend,
1024                                                   sessionId);
1025                    }
1026                }
1027                mBtNrecIsOff = btNrecIsOff;
1028            }
1029        }
1030        String8 screenState;
1031        if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1032            bool isOff = screenState == "off";
1033            if (isOff != (AudioFlinger::mScreenState & 1)) {
1034                AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
1035            }
1036        }
1037        return final_result;
1038    }
1039
1040    // hold a strong ref on thread in case closeOutput() or closeInput() is called
1041    // and the thread is exited once the lock is released
1042    sp<ThreadBase> thread;
1043    {
1044        Mutex::Autolock _l(mLock);
1045        thread = checkPlaybackThread_l(ioHandle);
1046        if (thread == 0) {
1047            thread = checkRecordThread_l(ioHandle);
1048        } else if (thread == primaryPlaybackThread_l()) {
1049            // indicate output device change to all input threads for pre processing
1050            AudioParameter param = AudioParameter(keyValuePairs);
1051            int value;
1052            if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1053                    (value != 0)) {
1054                for (size_t i = 0; i < mRecordThreads.size(); i++) {
1055                    mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1056                }
1057            }
1058        }
1059    }
1060    if (thread != 0) {
1061        return thread->setParameters(keyValuePairs);
1062    }
1063    return BAD_VALUE;
1064}
1065
1066String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
1067{
1068    ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1069            ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
1070
1071    Mutex::Autolock _l(mLock);
1072
1073    if (ioHandle == AUDIO_IO_HANDLE_NONE) {
1074        String8 out_s8;
1075
1076        for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1077            char *s;
1078            {
1079            AutoMutex lock(mHardwareLock);
1080            mHardwareStatus = AUDIO_HW_GET_PARAMETER;
1081            audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
1082            s = dev->get_parameters(dev, keys.string());
1083            mHardwareStatus = AUDIO_HW_IDLE;
1084            }
1085            out_s8 += String8(s ? s : "");
1086            free(s);
1087        }
1088        return out_s8;
1089    }
1090
1091    PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1092    if (playbackThread != NULL) {
1093        return playbackThread->getParameters(keys);
1094    }
1095    RecordThread *recordThread = checkRecordThread_l(ioHandle);
1096    if (recordThread != NULL) {
1097        return recordThread->getParameters(keys);
1098    }
1099    return String8("");
1100}
1101
1102size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1103        audio_channel_mask_t channelMask) const
1104{
1105    status_t ret = initCheck();
1106    if (ret != NO_ERROR) {
1107        return 0;
1108    }
1109
1110    AutoMutex lock(mHardwareLock);
1111    mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
1112    audio_config_t config;
1113    memset(&config, 0, sizeof(config));
1114    config.sample_rate = sampleRate;
1115    config.channel_mask = channelMask;
1116    config.format = format;
1117
1118    audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1119    size_t size = dev->get_input_buffer_size(dev, &config);
1120    mHardwareStatus = AUDIO_HW_IDLE;
1121    return size;
1122}
1123
1124uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
1125{
1126    Mutex::Autolock _l(mLock);
1127
1128    RecordThread *recordThread = checkRecordThread_l(ioHandle);
1129    if (recordThread != NULL) {
1130        return recordThread->getInputFramesLost();
1131    }
1132    return 0;
1133}
1134
1135status_t AudioFlinger::setVoiceVolume(float value)
1136{
1137    status_t ret = initCheck();
1138    if (ret != NO_ERROR) {
1139        return ret;
1140    }
1141
1142    // check calling permissions
1143    if (!settingsAllowed()) {
1144        return PERMISSION_DENIED;
1145    }
1146
1147    AutoMutex lock(mHardwareLock);
1148    audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1149    mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
1150    ret = dev->set_voice_volume(dev, value);
1151    mHardwareStatus = AUDIO_HW_IDLE;
1152
1153    return ret;
1154}
1155
1156status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1157        audio_io_handle_t output) const
1158{
1159    status_t status;
1160
1161    Mutex::Autolock _l(mLock);
1162
1163    PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1164    if (playbackThread != NULL) {
1165        return playbackThread->getRenderPosition(halFrames, dspFrames);
1166    }
1167
1168    return BAD_VALUE;
1169}
1170
1171void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1172{
1173    Mutex::Autolock _l(mLock);
1174    if (client == 0) {
1175        return;
1176    }
1177    bool clientAdded = false;
1178    {
1179        Mutex::Autolock _cl(mClientLock);
1180
1181        pid_t pid = IPCThreadState::self()->getCallingPid();
1182        if (mNotificationClients.indexOfKey(pid) < 0) {
1183            sp<NotificationClient> notificationClient = new NotificationClient(this,
1184                                                                                client,
1185                                                                                pid);
1186            ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
1187
1188            mNotificationClients.add(pid, notificationClient);
1189
1190            sp<IBinder> binder = client->asBinder();
1191            binder->linkToDeath(notificationClient);
1192            clientAdded = true;
1193        }
1194    }
1195
1196    // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
1197    // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
1198    if (clientAdded) {
1199        // the config change is always sent from playback or record threads to avoid deadlock
1200        // with AudioSystem::gLock
1201        for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1202            mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
1203        }
1204
1205        for (size_t i = 0; i < mRecordThreads.size(); i++) {
1206            mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
1207        }
1208    }
1209}
1210
1211void AudioFlinger::removeNotificationClient(pid_t pid)
1212{
1213    Mutex::Autolock _l(mLock);
1214    {
1215        Mutex::Autolock _cl(mClientLock);
1216        mNotificationClients.removeItem(pid);
1217    }
1218
1219    ALOGV("%d died, releasing its sessions", pid);
1220    size_t num = mAudioSessionRefs.size();
1221    bool removed = false;
1222    for (size_t i = 0; i< num; ) {
1223        AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1224        ALOGV(" pid %d @ %d", ref->mPid, i);
1225        if (ref->mPid == pid) {
1226            ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1227            mAudioSessionRefs.removeAt(i);
1228            delete ref;
1229            removed = true;
1230            num--;
1231        } else {
1232            i++;
1233        }
1234    }
1235    if (removed) {
1236        purgeStaleEffects_l();
1237    }
1238}
1239
1240void AudioFlinger::audioConfigChanged(int event, audio_io_handle_t ioHandle, const void *param2)
1241{
1242    Mutex::Autolock _l(mClientLock);
1243    size_t size = mNotificationClients.size();
1244    for (size_t i = 0; i < size; i++) {
1245        mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event,
1246                                                                              ioHandle,
1247                                                                              param2);
1248    }
1249}
1250
1251// removeClient_l() must be called with AudioFlinger::mClientLock held
1252void AudioFlinger::removeClient_l(pid_t pid)
1253{
1254    ALOGV("removeClient_l() pid %d, calling pid %d", pid,
1255            IPCThreadState::self()->getCallingPid());
1256    mClients.removeItem(pid);
1257}
1258
1259// getEffectThread_l() must be called with AudioFlinger::mLock held
1260sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1261{
1262    sp<PlaybackThread> thread;
1263
1264    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1265        if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1266            ALOG_ASSERT(thread == 0);
1267            thread = mPlaybackThreads.valueAt(i);
1268        }
1269    }
1270
1271    return thread;
1272}
1273
1274
1275
1276// ----------------------------------------------------------------------------
1277
1278AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1279    :   RefBase(),
1280        mAudioFlinger(audioFlinger),
1281        // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
1282        mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
1283        mPid(pid),
1284        mTimedTrackCount(0)
1285{
1286    // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
1287}
1288
1289// Client destructor must be called with AudioFlinger::mClientLock held
1290AudioFlinger::Client::~Client()
1291{
1292    mAudioFlinger->removeClient_l(mPid);
1293}
1294
1295sp<MemoryDealer> AudioFlinger::Client::heap() const
1296{
1297    return mMemoryDealer;
1298}
1299
1300// Reserve one of the limited slots for a timed audio track associated
1301// with this client
1302bool AudioFlinger::Client::reserveTimedTrack()
1303{
1304    const int kMaxTimedTracksPerClient = 4;
1305
1306    Mutex::Autolock _l(mTimedTrackLock);
1307
1308    if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
1309        ALOGW("can not create timed track - pid %d has exceeded the limit",
1310             mPid);
1311        return false;
1312    }
1313
1314    mTimedTrackCount++;
1315    return true;
1316}
1317
1318// Release a slot for a timed audio track
1319void AudioFlinger::Client::releaseTimedTrack()
1320{
1321    Mutex::Autolock _l(mTimedTrackLock);
1322    mTimedTrackCount--;
1323}
1324
1325// ----------------------------------------------------------------------------
1326
1327AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1328                                                     const sp<IAudioFlingerClient>& client,
1329                                                     pid_t pid)
1330    : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
1331{
1332}
1333
1334AudioFlinger::NotificationClient::~NotificationClient()
1335{
1336}
1337
1338void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
1339{
1340    sp<NotificationClient> keep(this);
1341    mAudioFlinger->removeNotificationClient(mPid);
1342}
1343
1344
1345// ----------------------------------------------------------------------------
1346
1347static bool deviceRequiresCaptureAudioOutputPermission(audio_devices_t inDevice) {
1348    return audio_is_remote_submix_device(inDevice);
1349}
1350
1351sp<IAudioRecord> AudioFlinger::openRecord(
1352        audio_io_handle_t input,
1353        uint32_t sampleRate,
1354        audio_format_t format,
1355        audio_channel_mask_t channelMask,
1356        size_t *frameCount,
1357        IAudioFlinger::track_flags_t *flags,
1358        pid_t tid,
1359        int *sessionId,
1360        size_t *notificationFrames,
1361        sp<IMemory>& cblk,
1362        sp<IMemory>& buffers,
1363        status_t *status)
1364{
1365    sp<RecordThread::RecordTrack> recordTrack;
1366    sp<RecordHandle> recordHandle;
1367    sp<Client> client;
1368    status_t lStatus;
1369    int lSessionId;
1370
1371    cblk.clear();
1372    buffers.clear();
1373
1374    // check calling permissions
1375    if (!recordingAllowed()) {
1376        ALOGE("openRecord() permission denied: recording not allowed");
1377        lStatus = PERMISSION_DENIED;
1378        goto Exit;
1379    }
1380
1381    // further sample rate checks are performed by createRecordTrack_l()
1382    if (sampleRate == 0) {
1383        ALOGE("openRecord() invalid sample rate %u", sampleRate);
1384        lStatus = BAD_VALUE;
1385        goto Exit;
1386    }
1387
1388    // we don't yet support anything other than 16-bit PCM
1389    if (!(audio_is_valid_format(format) &&
1390            audio_is_linear_pcm(format) && format == AUDIO_FORMAT_PCM_16_BIT)) {
1391        ALOGE("openRecord() invalid format %#x", format);
1392        lStatus = BAD_VALUE;
1393        goto Exit;
1394    }
1395
1396    // further channel mask checks are performed by createRecordTrack_l()
1397    if (!audio_is_input_channel(channelMask)) {
1398        ALOGE("openRecord() invalid channel mask %#x", channelMask);
1399        lStatus = BAD_VALUE;
1400        goto Exit;
1401    }
1402
1403    {
1404        Mutex::Autolock _l(mLock);
1405        RecordThread *thread = checkRecordThread_l(input);
1406        if (thread == NULL) {
1407            ALOGE("openRecord() checkRecordThread_l failed");
1408            lStatus = BAD_VALUE;
1409            goto Exit;
1410        }
1411
1412        if (deviceRequiresCaptureAudioOutputPermission(thread->inDevice())
1413                && !captureAudioOutputAllowed()) {
1414            ALOGE("openRecord() permission denied: capture not allowed");
1415            lStatus = PERMISSION_DENIED;
1416            goto Exit;
1417        }
1418
1419        pid_t pid = IPCThreadState::self()->getCallingPid();
1420        client = registerPid(pid);
1421
1422        if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
1423            lSessionId = *sessionId;
1424        } else {
1425            // if no audio session id is provided, create one here
1426            lSessionId = nextUniqueId();
1427            if (sessionId != NULL) {
1428                *sessionId = lSessionId;
1429            }
1430        }
1431        ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
1432
1433        // TODO: the uid should be passed in as a parameter to openRecord
1434        recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
1435                                                  frameCount, lSessionId, notificationFrames,
1436                                                  IPCThreadState::self()->getCallingUid(),
1437                                                  flags, tid, &lStatus);
1438        LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
1439    }
1440
1441    if (lStatus != NO_ERROR) {
1442        // remove local strong reference to Client before deleting the RecordTrack so that the
1443        // Client destructor is called by the TrackBase destructor with mClientLock held
1444        // Don't hold mClientLock when releasing the reference on the track as the
1445        // destructor will acquire it.
1446        {
1447            Mutex::Autolock _cl(mClientLock);
1448            client.clear();
1449        }
1450        recordTrack.clear();
1451        goto Exit;
1452    }
1453
1454    cblk = recordTrack->getCblk();
1455    buffers = recordTrack->getBuffers();
1456
1457    // return handle to client
1458    recordHandle = new RecordHandle(recordTrack);
1459
1460Exit:
1461    *status = lStatus;
1462    return recordHandle;
1463}
1464
1465
1466
1467// ----------------------------------------------------------------------------
1468
1469audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1470{
1471    if (name == NULL) {
1472        return 0;
1473    }
1474    if (!settingsAllowed()) {
1475        return 0;
1476    }
1477    Mutex::Autolock _l(mLock);
1478    return loadHwModule_l(name);
1479}
1480
1481// loadHwModule_l() must be called with AudioFlinger::mLock held
1482audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1483{
1484    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1485        if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1486            ALOGW("loadHwModule() module %s already loaded", name);
1487            return mAudioHwDevs.keyAt(i);
1488        }
1489    }
1490
1491    audio_hw_device_t *dev;
1492
1493    int rc = load_audio_interface(name, &dev);
1494    if (rc) {
1495        ALOGI("loadHwModule() error %d loading module %s ", rc, name);
1496        return 0;
1497    }
1498
1499    mHardwareStatus = AUDIO_HW_INIT;
1500    rc = dev->init_check(dev);
1501    mHardwareStatus = AUDIO_HW_IDLE;
1502    if (rc) {
1503        ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
1504        return 0;
1505    }
1506
1507    // Check and cache this HAL's level of support for master mute and master
1508    // volume.  If this is the first HAL opened, and it supports the get
1509    // methods, use the initial values provided by the HAL as the current
1510    // master mute and volume settings.
1511
1512    AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1513    {  // scope for auto-lock pattern
1514        AutoMutex lock(mHardwareLock);
1515
1516        if (0 == mAudioHwDevs.size()) {
1517            mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
1518            if (NULL != dev->get_master_volume) {
1519                float mv;
1520                if (OK == dev->get_master_volume(dev, &mv)) {
1521                    mMasterVolume = mv;
1522                }
1523            }
1524
1525            mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
1526            if (NULL != dev->get_master_mute) {
1527                bool mm;
1528                if (OK == dev->get_master_mute(dev, &mm)) {
1529                    mMasterMute = mm;
1530                }
1531            }
1532        }
1533
1534        mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1535        if ((NULL != dev->set_master_volume) &&
1536            (OK == dev->set_master_volume(dev, mMasterVolume))) {
1537            flags = static_cast<AudioHwDevice::Flags>(flags |
1538                    AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1539        }
1540
1541        mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1542        if ((NULL != dev->set_master_mute) &&
1543            (OK == dev->set_master_mute(dev, mMasterMute))) {
1544            flags = static_cast<AudioHwDevice::Flags>(flags |
1545                    AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1546        }
1547
1548        mHardwareStatus = AUDIO_HW_IDLE;
1549    }
1550
1551    audio_module_handle_t handle = nextUniqueId();
1552    mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
1553
1554    ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
1555          name, dev->common.module->name, dev->common.module->id, handle);
1556
1557    return handle;
1558
1559}
1560
1561// ----------------------------------------------------------------------------
1562
1563uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
1564{
1565    Mutex::Autolock _l(mLock);
1566    PlaybackThread *thread = primaryPlaybackThread_l();
1567    return thread != NULL ? thread->sampleRate() : 0;
1568}
1569
1570size_t AudioFlinger::getPrimaryOutputFrameCount()
1571{
1572    Mutex::Autolock _l(mLock);
1573    PlaybackThread *thread = primaryPlaybackThread_l();
1574    return thread != NULL ? thread->frameCountHAL() : 0;
1575}
1576
1577// ----------------------------------------------------------------------------
1578
1579status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1580{
1581    uid_t uid = IPCThreadState::self()->getCallingUid();
1582    if (uid != AID_SYSTEM) {
1583        return PERMISSION_DENIED;
1584    }
1585    Mutex::Autolock _l(mLock);
1586    if (mIsDeviceTypeKnown) {
1587        return INVALID_OPERATION;
1588    }
1589    mIsLowRamDevice = isLowRamDevice;
1590    mIsDeviceTypeKnown = true;
1591    return NO_ERROR;
1592}
1593
1594audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1595{
1596    Mutex::Autolock _l(mLock);
1597    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1598        sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1599        if ((thread->hasAudioSession(sessionId) & ThreadBase::TRACK_SESSION) != 0) {
1600            // A session can only be on one thread, so exit after first match
1601            String8 reply = thread->getParameters(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC));
1602            AudioParameter param = AudioParameter(reply);
1603            int value;
1604            if (param.getInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), value) == NO_ERROR) {
1605                return value;
1606            }
1607            break;
1608        }
1609    }
1610    return AUDIO_HW_SYNC_INVALID;
1611}
1612
1613// ----------------------------------------------------------------------------
1614
1615
1616sp<AudioFlinger::PlaybackThread> AudioFlinger::openOutput_l(audio_module_handle_t module,
1617                                                            audio_io_handle_t *output,
1618                                                            audio_config_t *config,
1619                                                            audio_devices_t devices,
1620                                                            const String8& address,
1621                                                            audio_output_flags_t flags)
1622{
1623    AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
1624    if (outHwDev == NULL) {
1625        return 0;
1626    }
1627
1628    audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
1629    if (*output == AUDIO_IO_HANDLE_NONE) {
1630        *output = nextUniqueId();
1631    }
1632
1633    mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1634
1635    audio_stream_out_t *outStream = NULL;
1636
1637    // FOR TESTING ONLY:
1638    // This if statement allows overriding the audio policy settings
1639    // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1640    if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1641        // Check only for Normal Mixing mode
1642        if (kEnableExtendedPrecision) {
1643            // Specify format (uncomment one below to choose)
1644            //config->format = AUDIO_FORMAT_PCM_FLOAT;
1645            //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1646            //config->format = AUDIO_FORMAT_PCM_32_BIT;
1647            //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
1648            // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
1649        }
1650        if (kEnableExtendedChannels) {
1651            // Specify channel mask (uncomment one below to choose)
1652            //config->channel_mask = audio_channel_out_mask_from_count(4);  // for USB 4ch
1653            //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1654            //        AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1);  // another 4ch example
1655        }
1656    }
1657
1658    status_t status = hwDevHal->open_output_stream(hwDevHal,
1659                                                   *output,
1660                                                   devices,
1661                                                   flags,
1662                                                   config,
1663                                                   &outStream,
1664                                                   address.string());
1665
1666    mHardwareStatus = AUDIO_HW_IDLE;
1667    ALOGV("openOutput_l() openOutputStream returned output %p, sampleRate %d, Format %#x, "
1668            "channelMask %#x, status %d",
1669            outStream,
1670            config->sample_rate,
1671            config->format,
1672            config->channel_mask,
1673            status);
1674
1675    if (status == NO_ERROR && outStream != NULL) {
1676        AudioStreamOut *outputStream = new AudioStreamOut(outHwDev, outStream, flags);
1677
1678        PlaybackThread *thread;
1679        if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
1680            thread = new OffloadThread(this, outputStream, *output, devices);
1681            ALOGV("openOutput_l() created offload output: ID %d thread %p", *output, thread);
1682        } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1683                || !isValidPcmSinkFormat(config->format)
1684                || !isValidPcmSinkChannelMask(config->channel_mask)) {
1685            thread = new DirectOutputThread(this, outputStream, *output, devices);
1686            ALOGV("openOutput_l() created direct output: ID %d thread %p", *output, thread);
1687        } else {
1688            thread = new MixerThread(this, outputStream, *output, devices);
1689            ALOGV("openOutput_l() created mixer output: ID %d thread %p", *output, thread);
1690        }
1691        mPlaybackThreads.add(*output, thread);
1692        return thread;
1693    }
1694
1695    return 0;
1696}
1697
1698status_t AudioFlinger::openOutput(audio_module_handle_t module,
1699                                  audio_io_handle_t *output,
1700                                  audio_config_t *config,
1701                                  audio_devices_t *devices,
1702                                  const String8& address,
1703                                  uint32_t *latencyMs,
1704                                  audio_output_flags_t flags)
1705{
1706    ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
1707              module,
1708              (devices != NULL) ? *devices : 0,
1709              config->sample_rate,
1710              config->format,
1711              config->channel_mask,
1712              flags);
1713
1714    if (*devices == AUDIO_DEVICE_NONE) {
1715        return BAD_VALUE;
1716    }
1717
1718    Mutex::Autolock _l(mLock);
1719
1720    sp<PlaybackThread> thread = openOutput_l(module, output, config, *devices, address, flags);
1721    if (thread != 0) {
1722        *latencyMs = thread->latency();
1723
1724        // notify client processes of the new output creation
1725        thread->audioConfigChanged(AudioSystem::OUTPUT_OPENED);
1726
1727        // the first primary output opened designates the primary hw device
1728        if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
1729            ALOGI("Using module %d has the primary audio interface", module);
1730            mPrimaryHardwareDev = thread->getOutput()->audioHwDev;
1731
1732            AutoMutex lock(mHardwareLock);
1733            mHardwareStatus = AUDIO_HW_SET_MODE;
1734            mPrimaryHardwareDev->hwDevice()->set_mode(mPrimaryHardwareDev->hwDevice(), mMode);
1735            mHardwareStatus = AUDIO_HW_IDLE;
1736
1737            mPrimaryOutputSampleRate = config->sample_rate;
1738        }
1739        return NO_ERROR;
1740    }
1741
1742    return NO_INIT;
1743}
1744
1745audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
1746        audio_io_handle_t output2)
1747{
1748    Mutex::Autolock _l(mLock);
1749    MixerThread *thread1 = checkMixerThread_l(output1);
1750    MixerThread *thread2 = checkMixerThread_l(output2);
1751
1752    if (thread1 == NULL || thread2 == NULL) {
1753        ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
1754                output2);
1755        return AUDIO_IO_HANDLE_NONE;
1756    }
1757
1758    audio_io_handle_t id = nextUniqueId();
1759    DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
1760    thread->addOutputTrack(thread2);
1761    mPlaybackThreads.add(id, thread);
1762    // notify client processes of the new output creation
1763    thread->audioConfigChanged(AudioSystem::OUTPUT_OPENED);
1764    return id;
1765}
1766
1767status_t AudioFlinger::closeOutput(audio_io_handle_t output)
1768{
1769    return closeOutput_nonvirtual(output);
1770}
1771
1772status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
1773{
1774    // keep strong reference on the playback thread so that
1775    // it is not destroyed while exit() is executed
1776    sp<PlaybackThread> thread;
1777    {
1778        Mutex::Autolock _l(mLock);
1779        thread = checkPlaybackThread_l(output);
1780        if (thread == NULL) {
1781            return BAD_VALUE;
1782        }
1783
1784        ALOGV("closeOutput() %d", output);
1785
1786        if (thread->type() == ThreadBase::MIXER) {
1787            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1788                if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
1789                    DuplicatingThread *dupThread =
1790                            (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
1791                    dupThread->removeOutputTrack((MixerThread *)thread.get());
1792
1793                }
1794            }
1795        }
1796
1797
1798        mPlaybackThreads.removeItem(output);
1799        // save all effects to the default thread
1800        if (mPlaybackThreads.size()) {
1801            PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
1802            if (dstThread != NULL) {
1803                // audioflinger lock is held here so the acquisition order of thread locks does not
1804                // matter
1805                Mutex::Autolock _dl(dstThread->mLock);
1806                Mutex::Autolock _sl(thread->mLock);
1807                Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
1808                for (size_t i = 0; i < effectChains.size(); i ++) {
1809                    moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true);
1810                }
1811            }
1812        }
1813        audioConfigChanged(AudioSystem::OUTPUT_CLOSED, output, NULL);
1814    }
1815    thread->exit();
1816    // The thread entity (active unit of execution) is no longer running here,
1817    // but the ThreadBase container still exists.
1818
1819    if (thread->type() != ThreadBase::DUPLICATING) {
1820        closeOutputFinish(thread);
1821    }
1822
1823    return NO_ERROR;
1824}
1825
1826void AudioFlinger::closeOutputFinish(sp<PlaybackThread> thread)
1827{
1828    AudioStreamOut *out = thread->clearOutput();
1829    ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
1830    // from now on thread->mOutput is NULL
1831    out->hwDev()->close_output_stream(out->hwDev(), out->stream);
1832    delete out;
1833}
1834
1835void AudioFlinger::closeOutputInternal_l(sp<PlaybackThread> thread)
1836{
1837    mPlaybackThreads.removeItem(thread->mId);
1838    thread->exit();
1839    closeOutputFinish(thread);
1840}
1841
1842status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
1843{
1844    Mutex::Autolock _l(mLock);
1845    PlaybackThread *thread = checkPlaybackThread_l(output);
1846
1847    if (thread == NULL) {
1848        return BAD_VALUE;
1849    }
1850
1851    ALOGV("suspendOutput() %d", output);
1852    thread->suspend();
1853
1854    return NO_ERROR;
1855}
1856
1857status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
1858{
1859    Mutex::Autolock _l(mLock);
1860    PlaybackThread *thread = checkPlaybackThread_l(output);
1861
1862    if (thread == NULL) {
1863        return BAD_VALUE;
1864    }
1865
1866    ALOGV("restoreOutput() %d", output);
1867
1868    thread->restore();
1869
1870    return NO_ERROR;
1871}
1872
1873status_t AudioFlinger::openInput(audio_module_handle_t module,
1874                                          audio_io_handle_t *input,
1875                                          audio_config_t *config,
1876                                          audio_devices_t *device,
1877                                          const String8& address,
1878                                          audio_source_t source,
1879                                          audio_input_flags_t flags)
1880{
1881    Mutex::Autolock _l(mLock);
1882
1883    if (*device == AUDIO_DEVICE_NONE) {
1884        return BAD_VALUE;
1885    }
1886
1887    sp<RecordThread> thread = openInput_l(module, input, config, *device, address, source, flags);
1888
1889    if (thread != 0) {
1890        // notify client processes of the new input creation
1891        thread->audioConfigChanged(AudioSystem::INPUT_OPENED);
1892        return NO_ERROR;
1893    }
1894    return NO_INIT;
1895}
1896
1897sp<AudioFlinger::RecordThread> AudioFlinger::openInput_l(audio_module_handle_t module,
1898                                                         audio_io_handle_t *input,
1899                                                         audio_config_t *config,
1900                                                         audio_devices_t device,
1901                                                         const String8& address,
1902                                                         audio_source_t source,
1903                                                         audio_input_flags_t flags)
1904{
1905    AudioHwDevice *inHwDev = findSuitableHwDev_l(module, device);
1906    if (inHwDev == NULL) {
1907        *input = AUDIO_IO_HANDLE_NONE;
1908        return 0;
1909    }
1910
1911    if (*input == AUDIO_IO_HANDLE_NONE) {
1912        *input = nextUniqueId();
1913    }
1914
1915    audio_config_t halconfig = *config;
1916    audio_hw_device_t *inHwHal = inHwDev->hwDevice();
1917    audio_stream_in_t *inStream = NULL;
1918    status_t status = inHwHal->open_input_stream(inHwHal, *input, device, &halconfig,
1919                                        &inStream, flags, address.string(), source);
1920    ALOGV("openInput_l() openInputStream returned input %p, SamplingRate %d"
1921           ", Format %#x, Channels %x, flags %#x, status %d",
1922            inStream,
1923            halconfig.sample_rate,
1924            halconfig.format,
1925            halconfig.channel_mask,
1926            flags,
1927            status);
1928
1929    // If the input could not be opened with the requested parameters and we can handle the
1930    // conversion internally, try to open again with the proposed parameters. The AudioFlinger can
1931    // resample the input and do mono to stereo or stereo to mono conversions on 16 bit PCM inputs.
1932    if (status == BAD_VALUE &&
1933            config->format == halconfig.format && halconfig.format == AUDIO_FORMAT_PCM_16_BIT &&
1934        (halconfig.sample_rate <= 2 * config->sample_rate) &&
1935        (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_2) &&
1936        (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_2)) {
1937        // FIXME describe the change proposed by HAL (save old values so we can log them here)
1938        ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
1939        inStream = NULL;
1940        status = inHwHal->open_input_stream(inHwHal, *input, device, &halconfig,
1941                                            &inStream, flags, address.string(), source);
1942        // FIXME log this new status; HAL should not propose any further changes
1943    }
1944
1945    if (status == NO_ERROR && inStream != NULL) {
1946
1947#ifdef TEE_SINK
1948        // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
1949        // or (re-)create if current Pipe is idle and does not match the new format
1950        sp<NBAIO_Sink> teeSink;
1951        enum {
1952            TEE_SINK_NO,    // don't copy input
1953            TEE_SINK_NEW,   // copy input using a new pipe
1954            TEE_SINK_OLD,   // copy input using an existing pipe
1955        } kind;
1956        NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
1957                audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
1958        if (!mTeeSinkInputEnabled) {
1959            kind = TEE_SINK_NO;
1960        } else if (!Format_isValid(format)) {
1961            kind = TEE_SINK_NO;
1962        } else if (mRecordTeeSink == 0) {
1963            kind = TEE_SINK_NEW;
1964        } else if (mRecordTeeSink->getStrongCount() != 1) {
1965            kind = TEE_SINK_NO;
1966        } else if (Format_isEqual(format, mRecordTeeSink->format())) {
1967            kind = TEE_SINK_OLD;
1968        } else {
1969            kind = TEE_SINK_NEW;
1970        }
1971        switch (kind) {
1972        case TEE_SINK_NEW: {
1973            Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
1974            size_t numCounterOffers = 0;
1975            const NBAIO_Format offers[1] = {format};
1976            ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
1977            ALOG_ASSERT(index == 0);
1978            PipeReader *pipeReader = new PipeReader(*pipe);
1979            numCounterOffers = 0;
1980            index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
1981            ALOG_ASSERT(index == 0);
1982            mRecordTeeSink = pipe;
1983            mRecordTeeSource = pipeReader;
1984            teeSink = pipe;
1985            }
1986            break;
1987        case TEE_SINK_OLD:
1988            teeSink = mRecordTeeSink;
1989            break;
1990        case TEE_SINK_NO:
1991        default:
1992            break;
1993        }
1994#endif
1995
1996        AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream);
1997
1998        // Start record thread
1999        // RecordThread requires both input and output device indication to forward to audio
2000        // pre processing modules
2001        sp<RecordThread> thread = new RecordThread(this,
2002                                  inputStream,
2003                                  *input,
2004                                  primaryOutputDevice_l(),
2005                                  device
2006#ifdef TEE_SINK
2007                                  , teeSink
2008#endif
2009                                  );
2010        mRecordThreads.add(*input, thread);
2011        ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2012        return thread;
2013    }
2014
2015    *input = AUDIO_IO_HANDLE_NONE;
2016    return 0;
2017}
2018
2019status_t AudioFlinger::closeInput(audio_io_handle_t input)
2020{
2021    return closeInput_nonvirtual(input);
2022}
2023
2024status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2025{
2026    // keep strong reference on the record thread so that
2027    // it is not destroyed while exit() is executed
2028    sp<RecordThread> thread;
2029    {
2030        Mutex::Autolock _l(mLock);
2031        thread = checkRecordThread_l(input);
2032        if (thread == 0) {
2033            return BAD_VALUE;
2034        }
2035
2036        ALOGV("closeInput() %d", input);
2037        {
2038            // If we still have effect chains, it means that a client still holds a handle
2039            // on at least one effect. We must keep the chain alive in case a new record
2040            // thread is opened for a new capture on the same session
2041            Mutex::Autolock _sl(thread->mLock);
2042            Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
2043            for (size_t i = 0; i < effectChains.size(); i++) {
2044                putOrphanEffectChain_l(effectChains[i]);
2045            }
2046        }
2047        audioConfigChanged(AudioSystem::INPUT_CLOSED, input, NULL);
2048        mRecordThreads.removeItem(input);
2049    }
2050    // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2051    // we have a different lock for notification client
2052    closeInputFinish(thread);
2053    return NO_ERROR;
2054}
2055
2056void AudioFlinger::closeInputFinish(sp<RecordThread> thread)
2057{
2058    thread->exit();
2059    AudioStreamIn *in = thread->clearInput();
2060    ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2061    // from now on thread->mInput is NULL
2062    in->hwDev()->close_input_stream(in->hwDev(), in->stream);
2063    delete in;
2064}
2065
2066void AudioFlinger::closeInputInternal_l(sp<RecordThread> thread)
2067{
2068    mRecordThreads.removeItem(thread->mId);
2069    closeInputFinish(thread);
2070}
2071
2072status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
2073{
2074    Mutex::Autolock _l(mLock);
2075    ALOGV("invalidateStream() stream %d", stream);
2076
2077    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2078        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2079        thread->invalidateTracks(stream);
2080    }
2081
2082    return NO_ERROR;
2083}
2084
2085
2086audio_unique_id_t AudioFlinger::newAudioUniqueId()
2087{
2088    return nextUniqueId();
2089}
2090
2091void AudioFlinger::acquireAudioSessionId(int audioSession, pid_t pid)
2092{
2093    Mutex::Autolock _l(mLock);
2094    pid_t caller = IPCThreadState::self()->getCallingPid();
2095    ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2096    if (pid != -1 && (caller == getpid_cached)) {
2097        caller = pid;
2098    }
2099
2100    {
2101        Mutex::Autolock _cl(mClientLock);
2102        // Ignore requests received from processes not known as notification client. The request
2103        // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2104        // called from a different pid leaving a stale session reference.  Also we don't know how
2105        // to clear this reference if the client process dies.
2106        if (mNotificationClients.indexOfKey(caller) < 0) {
2107            ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2108            return;
2109        }
2110    }
2111
2112    size_t num = mAudioSessionRefs.size();
2113    for (size_t i = 0; i< num; i++) {
2114        AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
2115        if (ref->mSessionid == audioSession && ref->mPid == caller) {
2116            ref->mCnt++;
2117            ALOGV(" incremented refcount to %d", ref->mCnt);
2118            return;
2119        }
2120    }
2121    mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2122    ALOGV(" added new entry for %d", audioSession);
2123}
2124
2125void AudioFlinger::releaseAudioSessionId(int audioSession, pid_t pid)
2126{
2127    Mutex::Autolock _l(mLock);
2128    pid_t caller = IPCThreadState::self()->getCallingPid();
2129    ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2130    if (pid != -1 && (caller == getpid_cached)) {
2131        caller = pid;
2132    }
2133    size_t num = mAudioSessionRefs.size();
2134    for (size_t i = 0; i< num; i++) {
2135        AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2136        if (ref->mSessionid == audioSession && ref->mPid == caller) {
2137            ref->mCnt--;
2138            ALOGV(" decremented refcount to %d", ref->mCnt);
2139            if (ref->mCnt == 0) {
2140                mAudioSessionRefs.removeAt(i);
2141                delete ref;
2142                purgeStaleEffects_l();
2143            }
2144            return;
2145        }
2146    }
2147    // If the caller is mediaserver it is likely that the session being released was acquired
2148    // on behalf of a process not in notification clients and we ignore the warning.
2149    ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
2150}
2151
2152void AudioFlinger::purgeStaleEffects_l() {
2153
2154    ALOGV("purging stale effects");
2155
2156    Vector< sp<EffectChain> > chains;
2157
2158    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2159        sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2160        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2161            sp<EffectChain> ec = t->mEffectChains[j];
2162            if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2163                chains.push(ec);
2164            }
2165        }
2166    }
2167    for (size_t i = 0; i < mRecordThreads.size(); i++) {
2168        sp<RecordThread> t = mRecordThreads.valueAt(i);
2169        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2170            sp<EffectChain> ec = t->mEffectChains[j];
2171            chains.push(ec);
2172        }
2173    }
2174
2175    for (size_t i = 0; i < chains.size(); i++) {
2176        sp<EffectChain> ec = chains[i];
2177        int sessionid = ec->sessionId();
2178        sp<ThreadBase> t = ec->mThread.promote();
2179        if (t == 0) {
2180            continue;
2181        }
2182        size_t numsessionrefs = mAudioSessionRefs.size();
2183        bool found = false;
2184        for (size_t k = 0; k < numsessionrefs; k++) {
2185            AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
2186            if (ref->mSessionid == sessionid) {
2187                ALOGV(" session %d still exists for %d with %d refs",
2188                    sessionid, ref->mPid, ref->mCnt);
2189                found = true;
2190                break;
2191            }
2192        }
2193        if (!found) {
2194            Mutex::Autolock _l(t->mLock);
2195            // remove all effects from the chain
2196            while (ec->mEffects.size()) {
2197                sp<EffectModule> effect = ec->mEffects[0];
2198                effect->unPin();
2199                t->removeEffect_l(effect);
2200                if (effect->purgeHandles()) {
2201                    t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
2202                }
2203                AudioSystem::unregisterEffect(effect->id());
2204            }
2205        }
2206    }
2207    return;
2208}
2209
2210// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2211AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
2212{
2213    return mPlaybackThreads.valueFor(output).get();
2214}
2215
2216// checkMixerThread_l() must be called with AudioFlinger::mLock held
2217AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
2218{
2219    PlaybackThread *thread = checkPlaybackThread_l(output);
2220    return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
2221}
2222
2223// checkRecordThread_l() must be called with AudioFlinger::mLock held
2224AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
2225{
2226    return mRecordThreads.valueFor(input).get();
2227}
2228
2229uint32_t AudioFlinger::nextUniqueId()
2230{
2231    return (uint32_t) android_atomic_inc(&mNextUniqueId);
2232}
2233
2234AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
2235{
2236    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2237        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2238        AudioStreamOut *output = thread->getOutput();
2239        if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
2240            return thread;
2241        }
2242    }
2243    return NULL;
2244}
2245
2246audio_devices_t AudioFlinger::primaryOutputDevice_l() const
2247{
2248    PlaybackThread *thread = primaryPlaybackThread_l();
2249
2250    if (thread == NULL) {
2251        return 0;
2252    }
2253
2254    return thread->outDevice();
2255}
2256
2257sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
2258                                    int triggerSession,
2259                                    int listenerSession,
2260                                    sync_event_callback_t callBack,
2261                                    wp<RefBase> cookie)
2262{
2263    Mutex::Autolock _l(mLock);
2264
2265    sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2266    status_t playStatus = NAME_NOT_FOUND;
2267    status_t recStatus = NAME_NOT_FOUND;
2268    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2269        playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2270        if (playStatus == NO_ERROR) {
2271            return event;
2272        }
2273    }
2274    for (size_t i = 0; i < mRecordThreads.size(); i++) {
2275        recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2276        if (recStatus == NO_ERROR) {
2277            return event;
2278        }
2279    }
2280    if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2281        mPendingSyncEvents.add(event);
2282    } else {
2283        ALOGV("createSyncEvent() invalid event %d", event->type());
2284        event.clear();
2285    }
2286    return event;
2287}
2288
2289// ----------------------------------------------------------------------------
2290//  Effect management
2291// ----------------------------------------------------------------------------
2292
2293
2294status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
2295{
2296    Mutex::Autolock _l(mLock);
2297    return EffectQueryNumberEffects(numEffects);
2298}
2299
2300status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
2301{
2302    Mutex::Autolock _l(mLock);
2303    return EffectQueryEffect(index, descriptor);
2304}
2305
2306status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
2307        effect_descriptor_t *descriptor) const
2308{
2309    Mutex::Autolock _l(mLock);
2310    return EffectGetDescriptor(pUuid, descriptor);
2311}
2312
2313
2314sp<IEffect> AudioFlinger::createEffect(
2315        effect_descriptor_t *pDesc,
2316        const sp<IEffectClient>& effectClient,
2317        int32_t priority,
2318        audio_io_handle_t io,
2319        int sessionId,
2320        status_t *status,
2321        int *id,
2322        int *enabled)
2323{
2324    status_t lStatus = NO_ERROR;
2325    sp<EffectHandle> handle;
2326    effect_descriptor_t desc;
2327
2328    pid_t pid = IPCThreadState::self()->getCallingPid();
2329    ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
2330            pid, effectClient.get(), priority, sessionId, io);
2331
2332    if (pDesc == NULL) {
2333        lStatus = BAD_VALUE;
2334        goto Exit;
2335    }
2336
2337    // check audio settings permission for global effects
2338    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
2339        lStatus = PERMISSION_DENIED;
2340        goto Exit;
2341    }
2342
2343    // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
2344    // that can only be created by audio policy manager (running in same process)
2345    if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
2346        lStatus = PERMISSION_DENIED;
2347        goto Exit;
2348    }
2349
2350    {
2351        if (!EffectIsNullUuid(&pDesc->uuid)) {
2352            // if uuid is specified, request effect descriptor
2353            lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
2354            if (lStatus < 0) {
2355                ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
2356                goto Exit;
2357            }
2358        } else {
2359            // if uuid is not specified, look for an available implementation
2360            // of the required type in effect factory
2361            if (EffectIsNullUuid(&pDesc->type)) {
2362                ALOGW("createEffect() no effect type");
2363                lStatus = BAD_VALUE;
2364                goto Exit;
2365            }
2366            uint32_t numEffects = 0;
2367            effect_descriptor_t d;
2368            d.flags = 0; // prevent compiler warning
2369            bool found = false;
2370
2371            lStatus = EffectQueryNumberEffects(&numEffects);
2372            if (lStatus < 0) {
2373                ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
2374                goto Exit;
2375            }
2376            for (uint32_t i = 0; i < numEffects; i++) {
2377                lStatus = EffectQueryEffect(i, &desc);
2378                if (lStatus < 0) {
2379                    ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
2380                    continue;
2381                }
2382                if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2383                    // If matching type found save effect descriptor. If the session is
2384                    // 0 and the effect is not auxiliary, continue enumeration in case
2385                    // an auxiliary version of this effect type is available
2386                    found = true;
2387                    d = desc;
2388                    if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
2389                            (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2390                        break;
2391                    }
2392                }
2393            }
2394            if (!found) {
2395                lStatus = BAD_VALUE;
2396                ALOGW("createEffect() effect not found");
2397                goto Exit;
2398            }
2399            // For same effect type, chose auxiliary version over insert version if
2400            // connect to output mix (Compliance to OpenSL ES)
2401            if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
2402                    (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
2403                desc = d;
2404            }
2405        }
2406
2407        // Do not allow auxiliary effects on a session different from 0 (output mix)
2408        if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
2409             (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2410            lStatus = INVALID_OPERATION;
2411            goto Exit;
2412        }
2413
2414        // check recording permission for visualizer
2415        if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
2416            !recordingAllowed()) {
2417            lStatus = PERMISSION_DENIED;
2418            goto Exit;
2419        }
2420
2421        // return effect descriptor
2422        *pDesc = desc;
2423        if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2424            // if the output returned by getOutputForEffect() is removed before we lock the
2425            // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2426            // and we will exit safely
2427            io = AudioSystem::getOutputForEffect(&desc);
2428            ALOGV("createEffect got output %d", io);
2429        }
2430
2431        Mutex::Autolock _l(mLock);
2432
2433        // If output is not specified try to find a matching audio session ID in one of the
2434        // output threads.
2435        // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2436        // because of code checking output when entering the function.
2437        // Note: io is never 0 when creating an effect on an input
2438        if (io == AUDIO_IO_HANDLE_NONE) {
2439            if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2440                // output must be specified by AudioPolicyManager when using session
2441                // AUDIO_SESSION_OUTPUT_STAGE
2442                lStatus = BAD_VALUE;
2443                goto Exit;
2444            }
2445            // look for the thread where the specified audio session is present
2446            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2447                if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2448                    io = mPlaybackThreads.keyAt(i);
2449                    break;
2450                }
2451            }
2452            if (io == 0) {
2453                for (size_t i = 0; i < mRecordThreads.size(); i++) {
2454                    if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2455                        io = mRecordThreads.keyAt(i);
2456                        break;
2457                    }
2458                }
2459            }
2460            // If no output thread contains the requested session ID, default to
2461            // first output. The effect chain will be moved to the correct output
2462            // thread when a track with the same session ID is created
2463            if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
2464                io = mPlaybackThreads.keyAt(0);
2465            }
2466            ALOGV("createEffect() got io %d for effect %s", io, desc.name);
2467        }
2468        ThreadBase *thread = checkRecordThread_l(io);
2469        if (thread == NULL) {
2470            thread = checkPlaybackThread_l(io);
2471            if (thread == NULL) {
2472                ALOGE("createEffect() unknown output thread");
2473                lStatus = BAD_VALUE;
2474                goto Exit;
2475            }
2476        } else {
2477            // Check if one effect chain was awaiting for an effect to be created on this
2478            // session and used it instead of creating a new one.
2479            sp<EffectChain> chain = getOrphanEffectChain_l((audio_session_t)sessionId);
2480            if (chain != 0) {
2481                thread->addEffectChain_l(chain);
2482            }
2483        }
2484
2485        sp<Client> client = registerPid(pid);
2486
2487        // create effect on selected output thread
2488        handle = thread->createEffect_l(client, effectClient, priority, sessionId,
2489                &desc, enabled, &lStatus);
2490        if (handle != 0 && id != NULL) {
2491            *id = handle->id();
2492        }
2493        if (handle == 0) {
2494            // remove local strong reference to Client with mClientLock held
2495            Mutex::Autolock _cl(mClientLock);
2496            client.clear();
2497        }
2498    }
2499
2500Exit:
2501    *status = lStatus;
2502    return handle;
2503}
2504
2505status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
2506        audio_io_handle_t dstOutput)
2507{
2508    ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
2509            sessionId, srcOutput, dstOutput);
2510    Mutex::Autolock _l(mLock);
2511    if (srcOutput == dstOutput) {
2512        ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
2513        return NO_ERROR;
2514    }
2515    PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
2516    if (srcThread == NULL) {
2517        ALOGW("moveEffects() bad srcOutput %d", srcOutput);
2518        return BAD_VALUE;
2519    }
2520    PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
2521    if (dstThread == NULL) {
2522        ALOGW("moveEffects() bad dstOutput %d", dstOutput);
2523        return BAD_VALUE;
2524    }
2525
2526    Mutex::Autolock _dl(dstThread->mLock);
2527    Mutex::Autolock _sl(srcThread->mLock);
2528    return moveEffectChain_l(sessionId, srcThread, dstThread, false);
2529}
2530
2531// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
2532status_t AudioFlinger::moveEffectChain_l(int sessionId,
2533                                   AudioFlinger::PlaybackThread *srcThread,
2534                                   AudioFlinger::PlaybackThread *dstThread,
2535                                   bool reRegister)
2536{
2537    ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
2538            sessionId, srcThread, dstThread);
2539
2540    sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
2541    if (chain == 0) {
2542        ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
2543                sessionId, srcThread);
2544        return INVALID_OPERATION;
2545    }
2546
2547    // Check whether the destination thread has a channel count of FCC_2, which is
2548    // currently required for (most) effects. Prevent moving the effect chain here rather
2549    // than disabling the addEffect_l() call in dstThread below.
2550    if (dstThread->mChannelCount != FCC_2) {
2551        ALOGW("moveEffectChain_l() effect chain failed because"
2552                " destination thread %p channel count(%u) != %u",
2553                dstThread, dstThread->mChannelCount, FCC_2);
2554        return INVALID_OPERATION;
2555    }
2556
2557    // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
2558    // so that a new chain is created with correct parameters when first effect is added. This is
2559    // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
2560    // removed.
2561    srcThread->removeEffectChain_l(chain);
2562
2563    // transfer all effects one by one so that new effect chain is created on new thread with
2564    // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
2565    sp<EffectChain> dstChain;
2566    uint32_t strategy = 0; // prevent compiler warning
2567    sp<EffectModule> effect = chain->getEffectFromId_l(0);
2568    Vector< sp<EffectModule> > removed;
2569    status_t status = NO_ERROR;
2570    while (effect != 0) {
2571        srcThread->removeEffect_l(effect);
2572        removed.add(effect);
2573        status = dstThread->addEffect_l(effect);
2574        if (status != NO_ERROR) {
2575            break;
2576        }
2577        // removeEffect_l() has stopped the effect if it was active so it must be restarted
2578        if (effect->state() == EffectModule::ACTIVE ||
2579                effect->state() == EffectModule::STOPPING) {
2580            effect->start();
2581        }
2582        // if the move request is not received from audio policy manager, the effect must be
2583        // re-registered with the new strategy and output
2584        if (dstChain == 0) {
2585            dstChain = effect->chain().promote();
2586            if (dstChain == 0) {
2587                ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
2588                status = NO_INIT;
2589                break;
2590            }
2591            strategy = dstChain->strategy();
2592        }
2593        if (reRegister) {
2594            AudioSystem::unregisterEffect(effect->id());
2595            AudioSystem::registerEffect(&effect->desc(),
2596                                        dstThread->id(),
2597                                        strategy,
2598                                        sessionId,
2599                                        effect->id());
2600            AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
2601        }
2602        effect = chain->getEffectFromId_l(0);
2603    }
2604
2605    if (status != NO_ERROR) {
2606        for (size_t i = 0; i < removed.size(); i++) {
2607            srcThread->addEffect_l(removed[i]);
2608            if (dstChain != 0 && reRegister) {
2609                AudioSystem::unregisterEffect(removed[i]->id());
2610                AudioSystem::registerEffect(&removed[i]->desc(),
2611                                            srcThread->id(),
2612                                            strategy,
2613                                            sessionId,
2614                                            removed[i]->id());
2615                AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
2616            }
2617        }
2618    }
2619
2620    return status;
2621}
2622
2623bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
2624{
2625    if (mGlobalEffectEnableTime != 0 &&
2626            ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
2627        return true;
2628    }
2629
2630    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2631        sp<EffectChain> ec =
2632                mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2633        if (ec != 0 && ec->isNonOffloadableEnabled()) {
2634            return true;
2635        }
2636    }
2637    return false;
2638}
2639
2640void AudioFlinger::onNonOffloadableGlobalEffectEnable()
2641{
2642    Mutex::Autolock _l(mLock);
2643
2644    mGlobalEffectEnableTime = systemTime();
2645
2646    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2647        sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2648        if (t->mType == ThreadBase::OFFLOAD) {
2649            t->invalidateTracks(AUDIO_STREAM_MUSIC);
2650        }
2651    }
2652
2653}
2654
2655status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
2656{
2657    audio_session_t session = (audio_session_t)chain->sessionId();
2658    ssize_t index = mOrphanEffectChains.indexOfKey(session);
2659    ALOGV("putOrphanEffectChain_l session %d index %d", session, index);
2660    if (index >= 0) {
2661        ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
2662        return ALREADY_EXISTS;
2663    }
2664    mOrphanEffectChains.add(session, chain);
2665    return NO_ERROR;
2666}
2667
2668sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
2669{
2670    sp<EffectChain> chain;
2671    ssize_t index = mOrphanEffectChains.indexOfKey(session);
2672    ALOGV("getOrphanEffectChain_l session %d index %d", session, index);
2673    if (index >= 0) {
2674        chain = mOrphanEffectChains.valueAt(index);
2675        mOrphanEffectChains.removeItemsAt(index);
2676    }
2677    return chain;
2678}
2679
2680bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
2681{
2682    Mutex::Autolock _l(mLock);
2683    audio_session_t session = (audio_session_t)effect->sessionId();
2684    ssize_t index = mOrphanEffectChains.indexOfKey(session);
2685    ALOGV("updateOrphanEffectChains session %d index %d", session, index);
2686    if (index >= 0) {
2687        sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
2688        if (chain->removeEffect_l(effect) == 0) {
2689            ALOGV("updateOrphanEffectChains removing effect chain at index %d", index);
2690            mOrphanEffectChains.removeItemsAt(index);
2691        }
2692        return true;
2693    }
2694    return false;
2695}
2696
2697
2698struct Entry {
2699#define MAX_NAME 32     // %Y%m%d%H%M%S_%d.wav
2700    char mName[MAX_NAME];
2701};
2702
2703int comparEntry(const void *p1, const void *p2)
2704{
2705    return strcmp(((const Entry *) p1)->mName, ((const Entry *) p2)->mName);
2706}
2707
2708#ifdef TEE_SINK
2709void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
2710{
2711    NBAIO_Source *teeSource = source.get();
2712    if (teeSource != NULL) {
2713        // .wav rotation
2714        // There is a benign race condition if 2 threads call this simultaneously.
2715        // They would both traverse the directory, but the result would simply be
2716        // failures at unlink() which are ignored.  It's also unlikely since
2717        // normally dumpsys is only done by bugreport or from the command line.
2718        char teePath[32+256];
2719        strcpy(teePath, "/data/misc/media");
2720        size_t teePathLen = strlen(teePath);
2721        DIR *dir = opendir(teePath);
2722        teePath[teePathLen++] = '/';
2723        if (dir != NULL) {
2724#define MAX_SORT 20 // number of entries to sort
2725#define MAX_KEEP 10 // number of entries to keep
2726            struct Entry entries[MAX_SORT];
2727            size_t entryCount = 0;
2728            while (entryCount < MAX_SORT) {
2729                struct dirent de;
2730                struct dirent *result = NULL;
2731                int rc = readdir_r(dir, &de, &result);
2732                if (rc != 0) {
2733                    ALOGW("readdir_r failed %d", rc);
2734                    break;
2735                }
2736                if (result == NULL) {
2737                    break;
2738                }
2739                if (result != &de) {
2740                    ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
2741                    break;
2742                }
2743                // ignore non .wav file entries
2744                size_t nameLen = strlen(de.d_name);
2745                if (nameLen <= 4 || nameLen >= MAX_NAME ||
2746                        strcmp(&de.d_name[nameLen - 4], ".wav")) {
2747                    continue;
2748                }
2749                strcpy(entries[entryCount++].mName, de.d_name);
2750            }
2751            (void) closedir(dir);
2752            if (entryCount > MAX_KEEP) {
2753                qsort(entries, entryCount, sizeof(Entry), comparEntry);
2754                for (size_t i = 0; i < entryCount - MAX_KEEP; ++i) {
2755                    strcpy(&teePath[teePathLen], entries[i].mName);
2756                    (void) unlink(teePath);
2757                }
2758            }
2759        } else {
2760            if (fd >= 0) {
2761                dprintf(fd, "unable to rotate tees in %s: %s\n", teePath, strerror(errno));
2762            }
2763        }
2764        char teeTime[16];
2765        struct timeval tv;
2766        gettimeofday(&tv, NULL);
2767        struct tm tm;
2768        localtime_r(&tv.tv_sec, &tm);
2769        strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
2770        snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
2771        // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
2772        int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
2773        if (teeFd >= 0) {
2774            // FIXME use libsndfile
2775            char wavHeader[44];
2776            memcpy(wavHeader,
2777                "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",
2778                sizeof(wavHeader));
2779            NBAIO_Format format = teeSource->format();
2780            unsigned channelCount = Format_channelCount(format);
2781            uint32_t sampleRate = Format_sampleRate(format);
2782            size_t frameSize = Format_frameSize(format);
2783            wavHeader[22] = channelCount;       // number of channels
2784            wavHeader[24] = sampleRate;         // sample rate
2785            wavHeader[25] = sampleRate >> 8;
2786            wavHeader[32] = frameSize;          // block alignment
2787            wavHeader[33] = frameSize >> 8;
2788            write(teeFd, wavHeader, sizeof(wavHeader));
2789            size_t total = 0;
2790            bool firstRead = true;
2791#define TEE_SINK_READ 1024                      // frames per I/O operation
2792            void *buffer = malloc(TEE_SINK_READ * frameSize);
2793            for (;;) {
2794                size_t count = TEE_SINK_READ;
2795                ssize_t actual = teeSource->read(buffer, count,
2796                        AudioBufferProvider::kInvalidPTS);
2797                bool wasFirstRead = firstRead;
2798                firstRead = false;
2799                if (actual <= 0) {
2800                    if (actual == (ssize_t) OVERRUN && wasFirstRead) {
2801                        continue;
2802                    }
2803                    break;
2804                }
2805                ALOG_ASSERT(actual <= (ssize_t)count);
2806                write(teeFd, buffer, actual * frameSize);
2807                total += actual;
2808            }
2809            free(buffer);
2810            lseek(teeFd, (off_t) 4, SEEK_SET);
2811            uint32_t temp = 44 + total * frameSize - 8;
2812            // FIXME not big-endian safe
2813            write(teeFd, &temp, sizeof(temp));
2814            lseek(teeFd, (off_t) 40, SEEK_SET);
2815            temp =  total * frameSize;
2816            // FIXME not big-endian safe
2817            write(teeFd, &temp, sizeof(temp));
2818            close(teeFd);
2819            if (fd >= 0) {
2820                dprintf(fd, "tee copied to %s\n", teePath);
2821            }
2822        } else {
2823            if (fd >= 0) {
2824                dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
2825            }
2826        }
2827    }
2828}
2829#endif
2830
2831// ----------------------------------------------------------------------------
2832
2833status_t AudioFlinger::onTransact(
2834        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2835{
2836    return BnAudioFlinger::onTransact(code, data, reply, flags);
2837}
2838
2839}; // namespace android
2840