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