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