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