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