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 <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
27#include <binder/IPCThreadState.h>
28#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <utils/Trace.h>
31#include <binder/Parcel.h>
32#include <binder/IPCThreadState.h>
33#include <utils/String16.h>
34#include <utils/threads.h>
35#include <utils/Atomic.h>
36
37#include <cutils/bitops.h>
38#include <cutils/properties.h>
39#include <cutils/compiler.h>
40
41#undef ADD_BATTERY_DATA
42
43#ifdef ADD_BATTERY_DATA
44#include <media/IMediaPlayerService.h>
45#include <media/IMediaDeathNotifier.h>
46#endif
47
48#include <private/media/AudioTrackShared.h>
49#include <private/media/AudioEffectShared.h>
50
51#include <system/audio.h>
52#include <hardware/audio.h>
53
54#include "AudioMixer.h"
55#include "AudioFlinger.h"
56#include "ServiceUtilities.h"
57
58#include <media/EffectsFactoryApi.h>
59#include <audio_effects/effect_visualizer.h>
60#include <audio_effects/effect_ns.h>
61#include <audio_effects/effect_aec.h>
62
63#include <audio_utils/primitives.h>
64
65#include <powermanager/PowerManager.h>
66
67// #define DEBUG_CPU_USAGE 10  // log statistics every n wall clock seconds
68#ifdef DEBUG_CPU_USAGE
69#include <cpustats/CentralTendencyStatistics.h>
70#include <cpustats/ThreadCpuUsage.h>
71#endif
72
73#include <common_time/cc_helper.h>
74#include <common_time/local_clock.h>
75
76#include "FastMixer.h"
77
78// NBAIO implementations
79#include <media/nbaio/AudioStreamOutSink.h>
80#include <media/nbaio/MonoPipe.h>
81#include <media/nbaio/MonoPipeReader.h>
82#include <media/nbaio/Pipe.h>
83#include <media/nbaio/PipeReader.h>
84#include <media/nbaio/SourceAudioBufferProvider.h>
85
86#include "SchedulingPolicyService.h"
87
88// ----------------------------------------------------------------------------
89
90// Note: the following macro is used for extremely verbose logging message.  In
91// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
92// 0; but one side effect of this is to turn all LOGV's as well.  Some messages
93// are so verbose that we want to suppress them even when we have ALOG_ASSERT
94// turned on.  Do not uncomment the #def below unless you really know what you
95// are doing and want to see all of the extremely verbose messages.
96//#define VERY_VERY_VERBOSE_LOGGING
97#ifdef VERY_VERY_VERBOSE_LOGGING
98#define ALOGVV ALOGV
99#else
100#define ALOGVV(a...) do { } while(0)
101#endif
102
103namespace android {
104
105static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
106static const char kHardwareLockedString[] = "Hardware lock is taken\n";
107
108static const float MAX_GAIN = 4096.0f;
109static const uint32_t MAX_GAIN_INT = 0x1000;
110
111// retry counts for buffer fill timeout
112// 50 * ~20msecs = 1 second
113static const int8_t kMaxTrackRetries = 50;
114static const int8_t kMaxTrackStartupRetries = 50;
115// allow less retry attempts on direct output thread.
116// direct outputs can be a scarce resource in audio hardware and should
117// be released as quickly as possible.
118static const int8_t kMaxTrackRetriesDirect = 2;
119
120static const int kDumpLockRetries = 50;
121static const int kDumpLockSleepUs = 20000;
122
123// don't warn about blocked writes or record buffer overflows more often than this
124static const nsecs_t kWarningThrottleNs = seconds(5);
125
126// RecordThread loop sleep time upon application overrun or audio HAL read error
127static const int kRecordThreadSleepUs = 5000;
128
129// maximum time to wait for setParameters to complete
130static const nsecs_t kSetParametersTimeoutNs = seconds(2);
131
132// minimum sleep time for the mixer thread loop when tracks are active but in underrun
133static const uint32_t kMinThreadSleepTimeUs = 5000;
134// maximum divider applied to the active sleep time in the mixer thread loop
135static const uint32_t kMaxThreadSleepTimeShift = 2;
136
137// minimum normal mix buffer size, expressed in milliseconds rather than frames
138static const uint32_t kMinNormalMixBufferSizeMs = 20;
139// maximum normal mix buffer size
140static const uint32_t kMaxNormalMixBufferSizeMs = 24;
141
142nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
143
144// Whether to use fast mixer
145static const enum {
146    FastMixer_Never,    // never initialize or use: for debugging only
147    FastMixer_Always,   // always initialize and use, even if not needed: for debugging only
148                        // normal mixer multiplier is 1
149    FastMixer_Static,   // initialize if needed, then use all the time if initialized,
150                        // multiplier is calculated based on min & max normal mixer buffer size
151    FastMixer_Dynamic,  // initialize if needed, then use dynamically depending on track load,
152                        // multiplier is calculated based on min & max normal mixer buffer size
153    // FIXME for FastMixer_Dynamic:
154    //  Supporting this option will require fixing HALs that can't handle large writes.
155    //  For example, one HAL implementation returns an error from a large write,
156    //  and another HAL implementation corrupts memory, possibly in the sample rate converter.
157    //  We could either fix the HAL implementations, or provide a wrapper that breaks
158    //  up large writes into smaller ones, and the wrapper would need to deal with scheduler.
159} kUseFastMixer = FastMixer_Static;
160
161static uint32_t gScreenState; // incremented by 2 when screen state changes, bit 0 == 1 means "off"
162                              // AudioFlinger::setParameters() updates, other threads read w/o lock
163
164// Priorities for requestPriority
165static const int kPriorityAudioApp = 2;
166static const int kPriorityFastMixer = 3;
167
168// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
169// for the track.  The client then sub-divides this into smaller buffers for its use.
170// Currently the client uses double-buffering by default, but doesn't tell us about that.
171// So for now we just assume that client is double-buffered.
172// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
173// N-buffering, so AudioFlinger could allocate the right amount of memory.
174// See the client's minBufCount and mNotificationFramesAct calculations for details.
175static const int kFastTrackMultiplier = 2;
176
177// ----------------------------------------------------------------------------
178
179#ifdef ADD_BATTERY_DATA
180// To collect the amplifier usage
181static void addBatteryData(uint32_t params) {
182    sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
183    if (service == NULL) {
184        // it already logged
185        return;
186    }
187
188    service->addBatteryData(params);
189}
190#endif
191
192static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
193{
194    const hw_module_t *mod;
195    int rc;
196
197    rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
198    ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
199                 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
200    if (rc) {
201        goto out;
202    }
203    rc = audio_hw_device_open(mod, dev);
204    ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
205                 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
206    if (rc) {
207        goto out;
208    }
209    if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
210        ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
211        rc = BAD_VALUE;
212        goto out;
213    }
214    return 0;
215
216out:
217    *dev = NULL;
218    return rc;
219}
220
221// ----------------------------------------------------------------------------
222
223AudioFlinger::AudioFlinger()
224    : BnAudioFlinger(),
225      mPrimaryHardwareDev(NULL),
226      mHardwareStatus(AUDIO_HW_IDLE),
227      mMasterVolume(1.0f),
228      mMasterMute(false),
229      mNextUniqueId(1),
230      mMode(AUDIO_MODE_INVALID),
231      mBtNrecIsOff(false)
232{
233}
234
235void AudioFlinger::onFirstRef()
236{
237    int rc = 0;
238
239    Mutex::Autolock _l(mLock);
240
241    /* TODO: move all this work into an Init() function */
242    char val_str[PROPERTY_VALUE_MAX] = { 0 };
243    if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
244        uint32_t int_val;
245        if (1 == sscanf(val_str, "%u", &int_val)) {
246            mStandbyTimeInNsecs = milliseconds(int_val);
247            ALOGI("Using %u mSec as standby time.", int_val);
248        } else {
249            mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
250            ALOGI("Using default %u mSec as standby time.",
251                    (uint32_t)(mStandbyTimeInNsecs / 1000000));
252        }
253    }
254
255    mMode = AUDIO_MODE_NORMAL;
256}
257
258AudioFlinger::~AudioFlinger()
259{
260    while (!mRecordThreads.isEmpty()) {
261        // closeInput_nonvirtual() will remove specified entry from mRecordThreads
262        closeInput_nonvirtual(mRecordThreads.keyAt(0));
263    }
264    while (!mPlaybackThreads.isEmpty()) {
265        // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
266        closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
267    }
268
269    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
270        // no mHardwareLock needed, as there are no other references to this
271        audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
272        delete mAudioHwDevs.valueAt(i);
273    }
274}
275
276static const char * const audio_interfaces[] = {
277    AUDIO_HARDWARE_MODULE_ID_PRIMARY,
278    AUDIO_HARDWARE_MODULE_ID_A2DP,
279    AUDIO_HARDWARE_MODULE_ID_USB,
280};
281#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
282
283AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
284        audio_module_handle_t module,
285        audio_devices_t devices)
286{
287    // if module is 0, the request comes from an old policy manager and we should load
288    // well known modules
289    if (module == 0) {
290        ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
291        for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
292            loadHwModule_l(audio_interfaces[i]);
293        }
294        // then try to find a module supporting the requested device.
295        for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
296            AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
297            audio_hw_device_t *dev = audioHwDevice->hwDevice();
298            if ((dev->get_supported_devices != NULL) &&
299                    (dev->get_supported_devices(dev) & devices) == devices)
300                return audioHwDevice;
301        }
302    } else {
303        // check a match for the requested module handle
304        AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
305        if (audioHwDevice != NULL) {
306            return audioHwDevice;
307        }
308    }
309
310    return NULL;
311}
312
313void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
314{
315    const size_t SIZE = 256;
316    char buffer[SIZE];
317    String8 result;
318
319    result.append("Clients:\n");
320    for (size_t i = 0; i < mClients.size(); ++i) {
321        sp<Client> client = mClients.valueAt(i).promote();
322        if (client != 0) {
323            snprintf(buffer, SIZE, "  pid: %d\n", client->pid());
324            result.append(buffer);
325        }
326    }
327
328    result.append("Global session refs:\n");
329    result.append(" session pid count\n");
330    for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
331        AudioSessionRef *r = mAudioSessionRefs[i];
332        snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
333        result.append(buffer);
334    }
335    write(fd, result.string(), result.size());
336}
337
338
339void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
340{
341    const size_t SIZE = 256;
342    char buffer[SIZE];
343    String8 result;
344    hardware_call_state hardwareStatus = mHardwareStatus;
345
346    snprintf(buffer, SIZE, "Hardware status: %d\n"
347                           "Standby Time mSec: %u\n",
348                            hardwareStatus,
349                            (uint32_t)(mStandbyTimeInNsecs / 1000000));
350    result.append(buffer);
351    write(fd, result.string(), result.size());
352}
353
354void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
355{
356    const size_t SIZE = 256;
357    char buffer[SIZE];
358    String8 result;
359    snprintf(buffer, SIZE, "Permission Denial: "
360            "can't dump AudioFlinger from pid=%d, uid=%d\n",
361            IPCThreadState::self()->getCallingPid(),
362            IPCThreadState::self()->getCallingUid());
363    result.append(buffer);
364    write(fd, result.string(), result.size());
365}
366
367static bool tryLock(Mutex& mutex)
368{
369    bool locked = false;
370    for (int i = 0; i < kDumpLockRetries; ++i) {
371        if (mutex.tryLock() == NO_ERROR) {
372            locked = true;
373            break;
374        }
375        usleep(kDumpLockSleepUs);
376    }
377    return locked;
378}
379
380status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
381{
382    if (!dumpAllowed()) {
383        dumpPermissionDenial(fd, args);
384    } else {
385        // get state of hardware lock
386        bool hardwareLocked = tryLock(mHardwareLock);
387        if (!hardwareLocked) {
388            String8 result(kHardwareLockedString);
389            write(fd, result.string(), result.size());
390        } else {
391            mHardwareLock.unlock();
392        }
393
394        bool locked = tryLock(mLock);
395
396        // failed to lock - AudioFlinger is probably deadlocked
397        if (!locked) {
398            String8 result(kDeadlockedString);
399            write(fd, result.string(), result.size());
400        }
401
402        dumpClients(fd, args);
403        dumpInternals(fd, args);
404
405        // dump playback threads
406        for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
407            mPlaybackThreads.valueAt(i)->dump(fd, args);
408        }
409
410        // dump record threads
411        for (size_t i = 0; i < mRecordThreads.size(); i++) {
412            mRecordThreads.valueAt(i)->dump(fd, args);
413        }
414
415        // dump all hardware devs
416        for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
417            audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
418            dev->dump(dev, fd);
419        }
420        if (locked) mLock.unlock();
421    }
422    return NO_ERROR;
423}
424
425sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
426{
427    // If pid is already in the mClients wp<> map, then use that entry
428    // (for which promote() is always != 0), otherwise create a new entry and Client.
429    sp<Client> client = mClients.valueFor(pid).promote();
430    if (client == 0) {
431        client = new Client(this, pid);
432        mClients.add(pid, client);
433    }
434
435    return client;
436}
437
438// IAudioFlinger interface
439
440
441sp<IAudioTrack> AudioFlinger::createTrack(
442        pid_t pid,
443        audio_stream_type_t streamType,
444        uint32_t sampleRate,
445        audio_format_t format,
446        audio_channel_mask_t channelMask,
447        int frameCount,
448        IAudioFlinger::track_flags_t flags,
449        const sp<IMemory>& sharedBuffer,
450        audio_io_handle_t output,
451        pid_t tid,
452        int *sessionId,
453        status_t *status)
454{
455    sp<PlaybackThread::Track> track;
456    sp<TrackHandle> trackHandle;
457    sp<Client> client;
458    status_t lStatus;
459    int lSessionId;
460
461    // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
462    // but if someone uses binder directly they could bypass that and cause us to crash
463    if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
464        ALOGE("createTrack() invalid stream type %d", streamType);
465        lStatus = BAD_VALUE;
466        goto Exit;
467    }
468
469    {
470        Mutex::Autolock _l(mLock);
471        PlaybackThread *thread = checkPlaybackThread_l(output);
472        PlaybackThread *effectThread = NULL;
473        if (thread == NULL) {
474            ALOGE("unknown output thread");
475            lStatus = BAD_VALUE;
476            goto Exit;
477        }
478
479        client = registerPid_l(pid);
480
481        ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
482        if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
483            // check if an effect chain with the same session ID is present on another
484            // output thread and move it here.
485            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
486                sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
487                if (mPlaybackThreads.keyAt(i) != output) {
488                    uint32_t sessions = t->hasAudioSession(*sessionId);
489                    if (sessions & PlaybackThread::EFFECT_SESSION) {
490                        effectThread = t.get();
491                        break;
492                    }
493                }
494            }
495            lSessionId = *sessionId;
496        } else {
497            // if no audio session id is provided, create one here
498            lSessionId = nextUniqueId();
499            if (sessionId != NULL) {
500                *sessionId = lSessionId;
501            }
502        }
503        ALOGV("createTrack() lSessionId: %d", lSessionId);
504
505        track = thread->createTrack_l(client, streamType, sampleRate, format,
506                channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
507
508        // move effect chain to this output thread if an effect on same session was waiting
509        // for a track to be created
510        if (lStatus == NO_ERROR && effectThread != NULL) {
511            Mutex::Autolock _dl(thread->mLock);
512            Mutex::Autolock _sl(effectThread->mLock);
513            moveEffectChain_l(lSessionId, effectThread, thread, true);
514        }
515
516        // Look for sync events awaiting for a session to be used.
517        for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
518            if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
519                if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
520                    if (lStatus == NO_ERROR) {
521                        (void) track->setSyncEvent(mPendingSyncEvents[i]);
522                    } else {
523                        mPendingSyncEvents[i]->cancel();
524                    }
525                    mPendingSyncEvents.removeAt(i);
526                    i--;
527                }
528            }
529        }
530    }
531    if (lStatus == NO_ERROR) {
532        trackHandle = new TrackHandle(track);
533    } else {
534        // remove local strong reference to Client before deleting the Track so that the Client
535        // destructor is called by the TrackBase destructor with mLock held
536        client.clear();
537        track.clear();
538    }
539
540Exit:
541    if (status != NULL) {
542        *status = lStatus;
543    }
544    return trackHandle;
545}
546
547uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
548{
549    Mutex::Autolock _l(mLock);
550    PlaybackThread *thread = checkPlaybackThread_l(output);
551    if (thread == NULL) {
552        ALOGW("sampleRate() unknown thread %d", output);
553        return 0;
554    }
555    return thread->sampleRate();
556}
557
558int AudioFlinger::channelCount(audio_io_handle_t output) const
559{
560    Mutex::Autolock _l(mLock);
561    PlaybackThread *thread = checkPlaybackThread_l(output);
562    if (thread == NULL) {
563        ALOGW("channelCount() unknown thread %d", output);
564        return 0;
565    }
566    return thread->channelCount();
567}
568
569audio_format_t AudioFlinger::format(audio_io_handle_t output) const
570{
571    Mutex::Autolock _l(mLock);
572    PlaybackThread *thread = checkPlaybackThread_l(output);
573    if (thread == NULL) {
574        ALOGW("format() unknown thread %d", output);
575        return AUDIO_FORMAT_INVALID;
576    }
577    return thread->format();
578}
579
580size_t AudioFlinger::frameCount(audio_io_handle_t output) const
581{
582    Mutex::Autolock _l(mLock);
583    PlaybackThread *thread = checkPlaybackThread_l(output);
584    if (thread == NULL) {
585        ALOGW("frameCount() unknown thread %d", output);
586        return 0;
587    }
588    // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
589    //       should examine all callers and fix them to handle smaller counts
590    return thread->frameCount();
591}
592
593uint32_t AudioFlinger::latency(audio_io_handle_t output) const
594{
595    Mutex::Autolock _l(mLock);
596    PlaybackThread *thread = checkPlaybackThread_l(output);
597    if (thread == NULL) {
598        ALOGW("latency() unknown thread %d", output);
599        return 0;
600    }
601    return thread->latency();
602}
603
604status_t AudioFlinger::setMasterVolume(float value)
605{
606    status_t ret = initCheck();
607    if (ret != NO_ERROR) {
608        return ret;
609    }
610
611    // check calling permissions
612    if (!settingsAllowed()) {
613        return PERMISSION_DENIED;
614    }
615
616    Mutex::Autolock _l(mLock);
617    mMasterVolume = value;
618
619    // Set master volume in the HALs which support it.
620    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
621        AutoMutex lock(mHardwareLock);
622        AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
623
624        mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
625        if (dev->canSetMasterVolume()) {
626            dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
627        }
628        mHardwareStatus = AUDIO_HW_IDLE;
629    }
630
631    // Now set the master volume in each playback thread.  Playback threads
632    // assigned to HALs which do not have master volume support will apply
633    // master volume during the mix operation.  Threads with HALs which do
634    // support master volume will simply ignore the setting.
635    for (size_t i = 0; i < mPlaybackThreads.size(); i++)
636        mPlaybackThreads.valueAt(i)->setMasterVolume(value);
637
638    return NO_ERROR;
639}
640
641status_t AudioFlinger::setMode(audio_mode_t mode)
642{
643    status_t ret = initCheck();
644    if (ret != NO_ERROR) {
645        return ret;
646    }
647
648    // check calling permissions
649    if (!settingsAllowed()) {
650        return PERMISSION_DENIED;
651    }
652    if (uint32_t(mode) >= AUDIO_MODE_CNT) {
653        ALOGW("Illegal value: setMode(%d)", mode);
654        return BAD_VALUE;
655    }
656
657    { // scope for the lock
658        AutoMutex lock(mHardwareLock);
659        audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
660        mHardwareStatus = AUDIO_HW_SET_MODE;
661        ret = dev->set_mode(dev, mode);
662        mHardwareStatus = AUDIO_HW_IDLE;
663    }
664
665    if (NO_ERROR == ret) {
666        Mutex::Autolock _l(mLock);
667        mMode = mode;
668        for (size_t i = 0; i < mPlaybackThreads.size(); i++)
669            mPlaybackThreads.valueAt(i)->setMode(mode);
670    }
671
672    return ret;
673}
674
675status_t AudioFlinger::setMicMute(bool state)
676{
677    status_t ret = initCheck();
678    if (ret != NO_ERROR) {
679        return ret;
680    }
681
682    // check calling permissions
683    if (!settingsAllowed()) {
684        return PERMISSION_DENIED;
685    }
686
687    AutoMutex lock(mHardwareLock);
688    audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
689    mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
690    ret = dev->set_mic_mute(dev, state);
691    mHardwareStatus = AUDIO_HW_IDLE;
692    return ret;
693}
694
695bool AudioFlinger::getMicMute() const
696{
697    status_t ret = initCheck();
698    if (ret != NO_ERROR) {
699        return false;
700    }
701
702    bool state = AUDIO_MODE_INVALID;
703    AutoMutex lock(mHardwareLock);
704    audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
705    mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
706    dev->get_mic_mute(dev, &state);
707    mHardwareStatus = AUDIO_HW_IDLE;
708    return state;
709}
710
711status_t AudioFlinger::setMasterMute(bool muted)
712{
713    status_t ret = initCheck();
714    if (ret != NO_ERROR) {
715        return ret;
716    }
717
718    // check calling permissions
719    if (!settingsAllowed()) {
720        return PERMISSION_DENIED;
721    }
722
723    Mutex::Autolock _l(mLock);
724    mMasterMute = muted;
725
726    // Set master mute in the HALs which support it.
727    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
728        AutoMutex lock(mHardwareLock);
729        AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
730
731        mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
732        if (dev->canSetMasterMute()) {
733            dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
734        }
735        mHardwareStatus = AUDIO_HW_IDLE;
736    }
737
738    // Now set the master mute in each playback thread.  Playback threads
739    // assigned to HALs which do not have master mute support will apply master
740    // mute during the mix operation.  Threads with HALs which do support master
741    // mute will simply ignore the setting.
742    for (size_t i = 0; i < mPlaybackThreads.size(); i++)
743        mPlaybackThreads.valueAt(i)->setMasterMute(muted);
744
745    return NO_ERROR;
746}
747
748float AudioFlinger::masterVolume() const
749{
750    Mutex::Autolock _l(mLock);
751    return masterVolume_l();
752}
753
754bool AudioFlinger::masterMute() const
755{
756    Mutex::Autolock _l(mLock);
757    return masterMute_l();
758}
759
760float AudioFlinger::masterVolume_l() const
761{
762    return mMasterVolume;
763}
764
765bool AudioFlinger::masterMute_l() const
766{
767    return mMasterMute;
768}
769
770status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
771        audio_io_handle_t output)
772{
773    // check calling permissions
774    if (!settingsAllowed()) {
775        return PERMISSION_DENIED;
776    }
777
778    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
779        ALOGE("setStreamVolume() invalid stream %d", stream);
780        return BAD_VALUE;
781    }
782
783    AutoMutex lock(mLock);
784    PlaybackThread *thread = NULL;
785    if (output) {
786        thread = checkPlaybackThread_l(output);
787        if (thread == NULL) {
788            return BAD_VALUE;
789        }
790    }
791
792    mStreamTypes[stream].volume = value;
793
794    if (thread == NULL) {
795        for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
796            mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
797        }
798    } else {
799        thread->setStreamVolume(stream, value);
800    }
801
802    return NO_ERROR;
803}
804
805status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
806{
807    // check calling permissions
808    if (!settingsAllowed()) {
809        return PERMISSION_DENIED;
810    }
811
812    if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
813        uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
814        ALOGE("setStreamMute() invalid stream %d", stream);
815        return BAD_VALUE;
816    }
817
818    AutoMutex lock(mLock);
819    mStreamTypes[stream].mute = muted;
820    for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
821        mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
822
823    return NO_ERROR;
824}
825
826float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
827{
828    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
829        return 0.0f;
830    }
831
832    AutoMutex lock(mLock);
833    float volume;
834    if (output) {
835        PlaybackThread *thread = checkPlaybackThread_l(output);
836        if (thread == NULL) {
837            return 0.0f;
838        }
839        volume = thread->streamVolume(stream);
840    } else {
841        volume = streamVolume_l(stream);
842    }
843
844    return volume;
845}
846
847bool AudioFlinger::streamMute(audio_stream_type_t stream) const
848{
849    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
850        return true;
851    }
852
853    AutoMutex lock(mLock);
854    return streamMute_l(stream);
855}
856
857status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
858{
859    ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
860            ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
861    // check calling permissions
862    if (!settingsAllowed()) {
863        return PERMISSION_DENIED;
864    }
865
866    // ioHandle == 0 means the parameters are global to the audio hardware interface
867    if (ioHandle == 0) {
868        Mutex::Autolock _l(mLock);
869        status_t final_result = NO_ERROR;
870        {
871            AutoMutex lock(mHardwareLock);
872            mHardwareStatus = AUDIO_HW_SET_PARAMETER;
873            for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
874                audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
875                status_t result = dev->set_parameters(dev, keyValuePairs.string());
876                final_result = result ?: final_result;
877            }
878            mHardwareStatus = AUDIO_HW_IDLE;
879        }
880        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
881        AudioParameter param = AudioParameter(keyValuePairs);
882        String8 value;
883        if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
884            bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
885            if (mBtNrecIsOff != btNrecIsOff) {
886                for (size_t i = 0; i < mRecordThreads.size(); i++) {
887                    sp<RecordThread> thread = mRecordThreads.valueAt(i);
888                    audio_devices_t device = thread->inDevice();
889                    bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
890                    // collect all of the thread's session IDs
891                    KeyedVector<int, bool> ids = thread->sessionIds();
892                    // suspend effects associated with those session IDs
893                    for (size_t j = 0; j < ids.size(); ++j) {
894                        int sessionId = ids.keyAt(j);
895                        thread->setEffectSuspended(FX_IID_AEC,
896                                                   suspend,
897                                                   sessionId);
898                        thread->setEffectSuspended(FX_IID_NS,
899                                                   suspend,
900                                                   sessionId);
901                    }
902                }
903                mBtNrecIsOff = btNrecIsOff;
904            }
905        }
906        String8 screenState;
907        if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
908            bool isOff = screenState == "off";
909            if (isOff != (gScreenState & 1)) {
910                gScreenState = ((gScreenState & ~1) + 2) | isOff;
911            }
912        }
913        return final_result;
914    }
915
916    // hold a strong ref on thread in case closeOutput() or closeInput() is called
917    // and the thread is exited once the lock is released
918    sp<ThreadBase> thread;
919    {
920        Mutex::Autolock _l(mLock);
921        thread = checkPlaybackThread_l(ioHandle);
922        if (thread == 0) {
923            thread = checkRecordThread_l(ioHandle);
924        } else if (thread == primaryPlaybackThread_l()) {
925            // indicate output device change to all input threads for pre processing
926            AudioParameter param = AudioParameter(keyValuePairs);
927            int value;
928            if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
929                    (value != 0)) {
930                for (size_t i = 0; i < mRecordThreads.size(); i++) {
931                    mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
932                }
933            }
934        }
935    }
936    if (thread != 0) {
937        return thread->setParameters(keyValuePairs);
938    }
939    return BAD_VALUE;
940}
941
942String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
943{
944//    ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
945//            ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
946
947    Mutex::Autolock _l(mLock);
948
949    if (ioHandle == 0) {
950        String8 out_s8;
951
952        for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
953            char *s;
954            {
955            AutoMutex lock(mHardwareLock);
956            mHardwareStatus = AUDIO_HW_GET_PARAMETER;
957            audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
958            s = dev->get_parameters(dev, keys.string());
959            mHardwareStatus = AUDIO_HW_IDLE;
960            }
961            out_s8 += String8(s ? s : "");
962            free(s);
963        }
964        return out_s8;
965    }
966
967    PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
968    if (playbackThread != NULL) {
969        return playbackThread->getParameters(keys);
970    }
971    RecordThread *recordThread = checkRecordThread_l(ioHandle);
972    if (recordThread != NULL) {
973        return recordThread->getParameters(keys);
974    }
975    return String8("");
976}
977
978size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
979        audio_channel_mask_t channelMask) const
980{
981    status_t ret = initCheck();
982    if (ret != NO_ERROR) {
983        return 0;
984    }
985
986    AutoMutex lock(mHardwareLock);
987    mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
988    struct audio_config config = {
989        sample_rate: sampleRate,
990        channel_mask: channelMask,
991        format: format,
992    };
993    audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
994    size_t size = dev->get_input_buffer_size(dev, &config);
995    mHardwareStatus = AUDIO_HW_IDLE;
996    return size;
997}
998
999unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
1000{
1001    Mutex::Autolock _l(mLock);
1002
1003    RecordThread *recordThread = checkRecordThread_l(ioHandle);
1004    if (recordThread != NULL) {
1005        return recordThread->getInputFramesLost();
1006    }
1007    return 0;
1008}
1009
1010status_t AudioFlinger::setVoiceVolume(float value)
1011{
1012    status_t ret = initCheck();
1013    if (ret != NO_ERROR) {
1014        return ret;
1015    }
1016
1017    // check calling permissions
1018    if (!settingsAllowed()) {
1019        return PERMISSION_DENIED;
1020    }
1021
1022    AutoMutex lock(mHardwareLock);
1023    audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1024    mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
1025    ret = dev->set_voice_volume(dev, value);
1026    mHardwareStatus = AUDIO_HW_IDLE;
1027
1028    return ret;
1029}
1030
1031status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1032        audio_io_handle_t output) const
1033{
1034    status_t status;
1035
1036    Mutex::Autolock _l(mLock);
1037
1038    PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1039    if (playbackThread != NULL) {
1040        return playbackThread->getRenderPosition(halFrames, dspFrames);
1041    }
1042
1043    return BAD_VALUE;
1044}
1045
1046void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1047{
1048
1049    Mutex::Autolock _l(mLock);
1050
1051    pid_t pid = IPCThreadState::self()->getCallingPid();
1052    if (mNotificationClients.indexOfKey(pid) < 0) {
1053        sp<NotificationClient> notificationClient = new NotificationClient(this,
1054                                                                            client,
1055                                                                            pid);
1056        ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
1057
1058        mNotificationClients.add(pid, notificationClient);
1059
1060        sp<IBinder> binder = client->asBinder();
1061        binder->linkToDeath(notificationClient);
1062
1063        // the config change is always sent from playback or record threads to avoid deadlock
1064        // with AudioSystem::gLock
1065        for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1066            mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
1067        }
1068
1069        for (size_t i = 0; i < mRecordThreads.size(); i++) {
1070            mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
1071        }
1072    }
1073}
1074
1075void AudioFlinger::removeNotificationClient(pid_t pid)
1076{
1077    Mutex::Autolock _l(mLock);
1078
1079    mNotificationClients.removeItem(pid);
1080
1081    ALOGV("%d died, releasing its sessions", pid);
1082    size_t num = mAudioSessionRefs.size();
1083    bool removed = false;
1084    for (size_t i = 0; i< num; ) {
1085        AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1086        ALOGV(" pid %d @ %d", ref->mPid, i);
1087        if (ref->mPid == pid) {
1088            ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1089            mAudioSessionRefs.removeAt(i);
1090            delete ref;
1091            removed = true;
1092            num--;
1093        } else {
1094            i++;
1095        }
1096    }
1097    if (removed) {
1098        purgeStaleEffects_l();
1099    }
1100}
1101
1102// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1103void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
1104{
1105    size_t size = mNotificationClients.size();
1106    for (size_t i = 0; i < size; i++) {
1107        mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1108                                                                               param2);
1109    }
1110}
1111
1112// removeClient_l() must be called with AudioFlinger::mLock held
1113void AudioFlinger::removeClient_l(pid_t pid)
1114{
1115    ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
1116    mClients.removeItem(pid);
1117}
1118
1119// getEffectThread_l() must be called with AudioFlinger::mLock held
1120sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1121{
1122    sp<PlaybackThread> thread;
1123
1124    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1125        if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1126            ALOG_ASSERT(thread == 0);
1127            thread = mPlaybackThreads.valueAt(i);
1128        }
1129    }
1130
1131    return thread;
1132}
1133
1134// ----------------------------------------------------------------------------
1135
1136AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1137        audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
1138    :   Thread(false /*canCallJava*/),
1139        mType(type),
1140        mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
1141        // mChannelMask
1142        mChannelCount(0),
1143        mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1144        mParamStatus(NO_ERROR),
1145        mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
1146        mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
1147        // mName will be set by concrete (non-virtual) subclass
1148        mDeathRecipient(new PMDeathRecipient(this))
1149{
1150}
1151
1152AudioFlinger::ThreadBase::~ThreadBase()
1153{
1154    mParamCond.broadcast();
1155    // do not lock the mutex in destructor
1156    releaseWakeLock_l();
1157    if (mPowerManager != 0) {
1158        sp<IBinder> binder = mPowerManager->asBinder();
1159        binder->unlinkToDeath(mDeathRecipient);
1160    }
1161}
1162
1163void AudioFlinger::ThreadBase::exit()
1164{
1165    ALOGV("ThreadBase::exit");
1166    // do any cleanup required for exit to succeed
1167    preExit();
1168    {
1169        // This lock prevents the following race in thread (uniprocessor for illustration):
1170        //  if (!exitPending()) {
1171        //      // context switch from here to exit()
1172        //      // exit() calls requestExit(), what exitPending() observes
1173        //      // exit() calls signal(), which is dropped since no waiters
1174        //      // context switch back from exit() to here
1175        //      mWaitWorkCV.wait(...);
1176        //      // now thread is hung
1177        //  }
1178        AutoMutex lock(mLock);
1179        requestExit();
1180        mWaitWorkCV.broadcast();
1181    }
1182    // When Thread::requestExitAndWait is made virtual and this method is renamed to
1183    // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
1184    requestExitAndWait();
1185}
1186
1187status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1188{
1189    status_t status;
1190
1191    ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
1192    Mutex::Autolock _l(mLock);
1193
1194    mNewParameters.add(keyValuePairs);
1195    mWaitWorkCV.signal();
1196    // wait condition with timeout in case the thread loop has exited
1197    // before the request could be processed
1198    if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
1199        status = mParamStatus;
1200        mWaitWorkCV.signal();
1201    } else {
1202        status = TIMED_OUT;
1203    }
1204    return status;
1205}
1206
1207void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
1208{
1209    Mutex::Autolock _l(mLock);
1210    sendIoConfigEvent_l(event, param);
1211}
1212
1213// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
1214void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
1215{
1216    IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
1217    mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
1218    ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1219    mWaitWorkCV.signal();
1220}
1221
1222// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
1223void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
1224{
1225    PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
1226    mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
1227    ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
1228          mConfigEvents.size(), pid, tid, prio);
1229    mWaitWorkCV.signal();
1230}
1231
1232void AudioFlinger::ThreadBase::processConfigEvents()
1233{
1234    mLock.lock();
1235    while (!mConfigEvents.isEmpty()) {
1236        ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
1237        ConfigEvent *event = mConfigEvents[0];
1238        mConfigEvents.removeAt(0);
1239        // release mLock before locking AudioFlinger mLock: lock order is always
1240        // AudioFlinger then ThreadBase to avoid cross deadlock
1241        mLock.unlock();
1242        switch(event->type()) {
1243            case CFG_EVENT_PRIO: {
1244                PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
1245                int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio());
1246                if (err != 0) {
1247                    ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1248                          prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
1249                }
1250            } break;
1251            case CFG_EVENT_IO: {
1252                IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
1253                mAudioFlinger->mLock.lock();
1254                audioConfigChanged_l(ioEvent->event(), ioEvent->param());
1255                mAudioFlinger->mLock.unlock();
1256            } break;
1257            default:
1258                ALOGE("processConfigEvents() unknown event type %d", event->type());
1259                break;
1260        }
1261        delete event;
1262        mLock.lock();
1263    }
1264    mLock.unlock();
1265}
1266
1267void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1268{
1269    const size_t SIZE = 256;
1270    char buffer[SIZE];
1271    String8 result;
1272
1273    bool locked = tryLock(mLock);
1274    if (!locked) {
1275        snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1276        write(fd, buffer, strlen(buffer));
1277    }
1278
1279    snprintf(buffer, SIZE, "io handle: %d\n", mId);
1280    result.append(buffer);
1281    snprintf(buffer, SIZE, "TID: %d\n", getTid());
1282    result.append(buffer);
1283    snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1284    result.append(buffer);
1285    snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1286    result.append(buffer);
1287    snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1288    result.append(buffer);
1289    snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1290    result.append(buffer);
1291    snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1292    result.append(buffer);
1293    snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1294    result.append(buffer);
1295    snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1296    result.append(buffer);
1297    snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
1298    result.append(buffer);
1299
1300    snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1301    result.append(buffer);
1302    result.append(" Index Command");
1303    for (size_t i = 0; i < mNewParameters.size(); ++i) {
1304        snprintf(buffer, SIZE, "\n %02d    ", i);
1305        result.append(buffer);
1306        result.append(mNewParameters[i]);
1307    }
1308
1309    snprintf(buffer, SIZE, "\n\nPending config events: \n");
1310    result.append(buffer);
1311    for (size_t i = 0; i < mConfigEvents.size(); i++) {
1312        mConfigEvents[i]->dump(buffer, SIZE);
1313        result.append(buffer);
1314    }
1315    result.append("\n");
1316
1317    write(fd, result.string(), result.size());
1318
1319    if (locked) {
1320        mLock.unlock();
1321    }
1322}
1323
1324void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1325{
1326    const size_t SIZE = 256;
1327    char buffer[SIZE];
1328    String8 result;
1329
1330    snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1331    write(fd, buffer, strlen(buffer));
1332
1333    for (size_t i = 0; i < mEffectChains.size(); ++i) {
1334        sp<EffectChain> chain = mEffectChains[i];
1335        if (chain != 0) {
1336            chain->dump(fd, args);
1337        }
1338    }
1339}
1340
1341void AudioFlinger::ThreadBase::acquireWakeLock()
1342{
1343    Mutex::Autolock _l(mLock);
1344    acquireWakeLock_l();
1345}
1346
1347void AudioFlinger::ThreadBase::acquireWakeLock_l()
1348{
1349    if (mPowerManager == 0) {
1350        // use checkService() to avoid blocking if power service is not up yet
1351        sp<IBinder> binder =
1352            defaultServiceManager()->checkService(String16("power"));
1353        if (binder == 0) {
1354            ALOGW("Thread %s cannot connect to the power manager service", mName);
1355        } else {
1356            mPowerManager = interface_cast<IPowerManager>(binder);
1357            binder->linkToDeath(mDeathRecipient);
1358        }
1359    }
1360    if (mPowerManager != 0) {
1361        sp<IBinder> binder = new BBinder();
1362        status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1363                                                         binder,
1364                                                         String16(mName));
1365        if (status == NO_ERROR) {
1366            mWakeLockToken = binder;
1367        }
1368        ALOGV("acquireWakeLock_l() %s status %d", mName, status);
1369    }
1370}
1371
1372void AudioFlinger::ThreadBase::releaseWakeLock()
1373{
1374    Mutex::Autolock _l(mLock);
1375    releaseWakeLock_l();
1376}
1377
1378void AudioFlinger::ThreadBase::releaseWakeLock_l()
1379{
1380    if (mWakeLockToken != 0) {
1381        ALOGV("releaseWakeLock_l() %s", mName);
1382        if (mPowerManager != 0) {
1383            mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1384        }
1385        mWakeLockToken.clear();
1386    }
1387}
1388
1389void AudioFlinger::ThreadBase::clearPowerManager()
1390{
1391    Mutex::Autolock _l(mLock);
1392    releaseWakeLock_l();
1393    mPowerManager.clear();
1394}
1395
1396void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1397{
1398    sp<ThreadBase> thread = mThread.promote();
1399    if (thread != 0) {
1400        thread->clearPowerManager();
1401    }
1402    ALOGW("power manager service died !!!");
1403}
1404
1405void AudioFlinger::ThreadBase::setEffectSuspended(
1406        const effect_uuid_t *type, bool suspend, int sessionId)
1407{
1408    Mutex::Autolock _l(mLock);
1409    setEffectSuspended_l(type, suspend, sessionId);
1410}
1411
1412void AudioFlinger::ThreadBase::setEffectSuspended_l(
1413        const effect_uuid_t *type, bool suspend, int sessionId)
1414{
1415    sp<EffectChain> chain = getEffectChain_l(sessionId);
1416    if (chain != 0) {
1417        if (type != NULL) {
1418            chain->setEffectSuspended_l(type, suspend);
1419        } else {
1420            chain->setEffectSuspendedAll_l(suspend);
1421        }
1422    }
1423
1424    updateSuspendedSessions_l(type, suspend, sessionId);
1425}
1426
1427void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1428{
1429    ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1430    if (index < 0) {
1431        return;
1432    }
1433
1434    const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1435            mSuspendedSessions.valueAt(index);
1436
1437    for (size_t i = 0; i < sessionEffects.size(); i++) {
1438        sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1439        for (int j = 0; j < desc->mRefCount; j++) {
1440            if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1441                chain->setEffectSuspendedAll_l(true);
1442            } else {
1443                ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1444                    desc->mType.timeLow);
1445                chain->setEffectSuspended_l(&desc->mType, true);
1446            }
1447        }
1448    }
1449}
1450
1451void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1452                                                         bool suspend,
1453                                                         int sessionId)
1454{
1455    ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1456
1457    KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1458
1459    if (suspend) {
1460        if (index >= 0) {
1461            sessionEffects = mSuspendedSessions.valueAt(index);
1462        } else {
1463            mSuspendedSessions.add(sessionId, sessionEffects);
1464        }
1465    } else {
1466        if (index < 0) {
1467            return;
1468        }
1469        sessionEffects = mSuspendedSessions.valueAt(index);
1470    }
1471
1472
1473    int key = EffectChain::kKeyForSuspendAll;
1474    if (type != NULL) {
1475        key = type->timeLow;
1476    }
1477    index = sessionEffects.indexOfKey(key);
1478
1479    sp<SuspendedSessionDesc> desc;
1480    if (suspend) {
1481        if (index >= 0) {
1482            desc = sessionEffects.valueAt(index);
1483        } else {
1484            desc = new SuspendedSessionDesc();
1485            if (type != NULL) {
1486                desc->mType = *type;
1487            }
1488            sessionEffects.add(key, desc);
1489            ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1490        }
1491        desc->mRefCount++;
1492    } else {
1493        if (index < 0) {
1494            return;
1495        }
1496        desc = sessionEffects.valueAt(index);
1497        if (--desc->mRefCount == 0) {
1498            ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1499            sessionEffects.removeItemsAt(index);
1500            if (sessionEffects.isEmpty()) {
1501                ALOGV("updateSuspendedSessions_l() restore removing session %d",
1502                                 sessionId);
1503                mSuspendedSessions.removeItem(sessionId);
1504            }
1505        }
1506    }
1507    if (!sessionEffects.isEmpty()) {
1508        mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1509    }
1510}
1511
1512void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1513                                                            bool enabled,
1514                                                            int sessionId)
1515{
1516    Mutex::Autolock _l(mLock);
1517    checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1518}
1519
1520void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1521                                                            bool enabled,
1522                                                            int sessionId)
1523{
1524    if (mType != RECORD) {
1525        // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1526        // another session. This gives the priority to well behaved effect control panels
1527        // and applications not using global effects.
1528        // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1529        // global effects
1530        if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1531            setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1532        }
1533    }
1534
1535    sp<EffectChain> chain = getEffectChain_l(sessionId);
1536    if (chain != 0) {
1537        chain->checkSuspendOnEffectEnabled(effect, enabled);
1538    }
1539}
1540
1541// ----------------------------------------------------------------------------
1542
1543AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1544                                             AudioStreamOut* output,
1545                                             audio_io_handle_t id,
1546                                             audio_devices_t device,
1547                                             type_t type)
1548    :   ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
1549        mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1550        // mStreamTypes[] initialized in constructor body
1551        mOutput(output),
1552        mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1553        mMixerStatus(MIXER_IDLE),
1554        mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1555        standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
1556        mScreenState(gScreenState),
1557        // index 0 is reserved for normal mixer's submix
1558        mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
1559{
1560    snprintf(mName, kNameLength, "AudioOut_%X", id);
1561
1562    // Assumes constructor is called by AudioFlinger with it's mLock held, but
1563    // it would be safer to explicitly pass initial masterVolume/masterMute as
1564    // parameter.
1565    //
1566    // If the HAL we are using has support for master volume or master mute,
1567    // then do not attenuate or mute during mixing (just leave the volume at 1.0
1568    // and the mute set to false).
1569    mMasterVolume = audioFlinger->masterVolume_l();
1570    mMasterMute = audioFlinger->masterMute_l();
1571    if (mOutput && mOutput->audioHwDev) {
1572        if (mOutput->audioHwDev->canSetMasterVolume()) {
1573            mMasterVolume = 1.0;
1574        }
1575
1576        if (mOutput->audioHwDev->canSetMasterMute()) {
1577            mMasterMute = false;
1578        }
1579    }
1580
1581    readOutputParameters();
1582
1583    // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1584    // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1585    for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1586            stream = (audio_stream_type_t) (stream + 1)) {
1587        mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1588        mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1589    }
1590    // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1591    // because mAudioFlinger doesn't have one to copy from
1592}
1593
1594AudioFlinger::PlaybackThread::~PlaybackThread()
1595{
1596    delete [] mMixBuffer;
1597}
1598
1599void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1600{
1601    dumpInternals(fd, args);
1602    dumpTracks(fd, args);
1603    dumpEffectChains(fd, args);
1604}
1605
1606void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1607{
1608    const size_t SIZE = 256;
1609    char buffer[SIZE];
1610    String8 result;
1611
1612    result.appendFormat("Output thread %p stream volumes in dB:\n    ", this);
1613    for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1614        const stream_type_t *st = &mStreamTypes[i];
1615        if (i > 0) {
1616            result.appendFormat(", ");
1617        }
1618        result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1619        if (st->mute) {
1620            result.append("M");
1621        }
1622    }
1623    result.append("\n");
1624    write(fd, result.string(), result.length());
1625    result.clear();
1626
1627    snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1628    result.append(buffer);
1629    Track::appendDumpHeader(result);
1630    for (size_t i = 0; i < mTracks.size(); ++i) {
1631        sp<Track> track = mTracks[i];
1632        if (track != 0) {
1633            track->dump(buffer, SIZE);
1634            result.append(buffer);
1635        }
1636    }
1637
1638    snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1639    result.append(buffer);
1640    Track::appendDumpHeader(result);
1641    for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1642        sp<Track> track = mActiveTracks[i].promote();
1643        if (track != 0) {
1644            track->dump(buffer, SIZE);
1645            result.append(buffer);
1646        }
1647    }
1648    write(fd, result.string(), result.size());
1649
1650    // These values are "raw"; they will wrap around.  See prepareTracks_l() for a better way.
1651    FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1652    fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1653            underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1654}
1655
1656void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1657{
1658    const size_t SIZE = 256;
1659    char buffer[SIZE];
1660    String8 result;
1661
1662    snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1663    result.append(buffer);
1664    snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1665    result.append(buffer);
1666    snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1667    result.append(buffer);
1668    snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1669    result.append(buffer);
1670    snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1671    result.append(buffer);
1672    snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1673    result.append(buffer);
1674    snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1675    result.append(buffer);
1676    write(fd, result.string(), result.size());
1677    fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1678
1679    dumpBase(fd, args);
1680}
1681
1682// Thread virtuals
1683status_t AudioFlinger::PlaybackThread::readyToRun()
1684{
1685    status_t status = initCheck();
1686    if (status == NO_ERROR) {
1687        ALOGI("AudioFlinger's thread %p ready to run", this);
1688    } else {
1689        ALOGE("No working audio driver found.");
1690    }
1691    return status;
1692}
1693
1694void AudioFlinger::PlaybackThread::onFirstRef()
1695{
1696    run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1697}
1698
1699// ThreadBase virtuals
1700void AudioFlinger::PlaybackThread::preExit()
1701{
1702    ALOGV("  preExit()");
1703    // FIXME this is using hard-coded strings but in the future, this functionality will be
1704    //       converted to use audio HAL extensions required to support tunneling
1705    mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1706}
1707
1708// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1709sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1710        const sp<AudioFlinger::Client>& client,
1711        audio_stream_type_t streamType,
1712        uint32_t sampleRate,
1713        audio_format_t format,
1714        audio_channel_mask_t channelMask,
1715        int frameCount,
1716        const sp<IMemory>& sharedBuffer,
1717        int sessionId,
1718        IAudioFlinger::track_flags_t flags,
1719        pid_t tid,
1720        status_t *status)
1721{
1722    sp<Track> track;
1723    status_t lStatus;
1724
1725    bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1726
1727    // client expresses a preference for FAST, but we get the final say
1728    if (flags & IAudioFlinger::TRACK_FAST) {
1729      if (
1730            // not timed
1731            (!isTimed) &&
1732            // either of these use cases:
1733            (
1734              // use case 1: shared buffer with any frame count
1735              (
1736                (sharedBuffer != 0)
1737              ) ||
1738              // use case 2: callback handler and frame count is default or at least as large as HAL
1739              (
1740                (tid != -1) &&
1741                ((frameCount == 0) ||
1742                (frameCount >= (int) (mFrameCount * kFastTrackMultiplier)))
1743              )
1744            ) &&
1745            // PCM data
1746            audio_is_linear_pcm(format) &&
1747            // mono or stereo
1748            ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1749              (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1750#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1751            // hardware sample rate
1752            (sampleRate == mSampleRate) &&
1753#endif
1754            // normal mixer has an associated fast mixer
1755            hasFastMixer() &&
1756            // there are sufficient fast track slots available
1757            (mFastTrackAvailMask != 0)
1758            // FIXME test that MixerThread for this fast track has a capable output HAL
1759            // FIXME add a permission test also?
1760        ) {
1761        // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1762        if (frameCount == 0) {
1763            frameCount = mFrameCount * kFastTrackMultiplier;
1764        }
1765        ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1766                frameCount, mFrameCount);
1767      } else {
1768        ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1769                "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
1770                "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1771                isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1772                audio_is_linear_pcm(format),
1773                channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1774        flags &= ~IAudioFlinger::TRACK_FAST;
1775        // For compatibility with AudioTrack calculation, buffer depth is forced
1776        // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1777        // This is probably too conservative, but legacy application code may depend on it.
1778        // If you change this calculation, also review the start threshold which is related.
1779        uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1780        uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1781        if (minBufCount < 2) {
1782            minBufCount = 2;
1783        }
1784        int minFrameCount = mNormalFrameCount * minBufCount;
1785        if (frameCount < minFrameCount) {
1786            frameCount = minFrameCount;
1787        }
1788      }
1789    }
1790
1791    if (mType == DIRECT) {
1792        if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1793            if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1794                ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1795                        "for output %p with format %d",
1796                        sampleRate, format, channelMask, mOutput, mFormat);
1797                lStatus = BAD_VALUE;
1798                goto Exit;
1799            }
1800        }
1801    } else {
1802        // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1803        if (sampleRate > mSampleRate*2) {
1804            ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1805            lStatus = BAD_VALUE;
1806            goto Exit;
1807        }
1808    }
1809
1810    lStatus = initCheck();
1811    if (lStatus != NO_ERROR) {
1812        ALOGE("Audio driver not initialized.");
1813        goto Exit;
1814    }
1815
1816    { // scope for mLock
1817        Mutex::Autolock _l(mLock);
1818
1819        // all tracks in same audio session must share the same routing strategy otherwise
1820        // conflicts will happen when tracks are moved from one output to another by audio policy
1821        // manager
1822        uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1823        for (size_t i = 0; i < mTracks.size(); ++i) {
1824            sp<Track> t = mTracks[i];
1825            if (t != 0 && !t->isOutputTrack()) {
1826                uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1827                if (sessionId == t->sessionId() && strategy != actual) {
1828                    ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1829                            strategy, actual);
1830                    lStatus = BAD_VALUE;
1831                    goto Exit;
1832                }
1833            }
1834        }
1835
1836        if (!isTimed) {
1837            track = new Track(this, client, streamType, sampleRate, format,
1838                    channelMask, frameCount, sharedBuffer, sessionId, flags);
1839        } else {
1840            track = TimedTrack::create(this, client, streamType, sampleRate, format,
1841                    channelMask, frameCount, sharedBuffer, sessionId);
1842        }
1843        if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
1844            lStatus = NO_MEMORY;
1845            goto Exit;
1846        }
1847        mTracks.add(track);
1848
1849        sp<EffectChain> chain = getEffectChain_l(sessionId);
1850        if (chain != 0) {
1851            ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1852            track->setMainBuffer(chain->inBuffer());
1853            chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1854            chain->incTrackCnt();
1855        }
1856
1857        if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1858            pid_t callingPid = IPCThreadState::self()->getCallingPid();
1859            // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1860            // so ask activity manager to do this on our behalf
1861            sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1862        }
1863    }
1864
1865    lStatus = NO_ERROR;
1866
1867Exit:
1868    if (status) {
1869        *status = lStatus;
1870    }
1871    return track;
1872}
1873
1874uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1875{
1876    if (mFastMixer != NULL) {
1877        MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1878        latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1879    }
1880    return latency;
1881}
1882
1883uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1884{
1885    return latency;
1886}
1887
1888uint32_t AudioFlinger::PlaybackThread::latency() const
1889{
1890    Mutex::Autolock _l(mLock);
1891    return latency_l();
1892}
1893uint32_t AudioFlinger::PlaybackThread::latency_l() const
1894{
1895    if (initCheck() == NO_ERROR) {
1896        return correctLatency(mOutput->stream->get_latency(mOutput->stream));
1897    } else {
1898        return 0;
1899    }
1900}
1901
1902void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1903{
1904    Mutex::Autolock _l(mLock);
1905    // Don't apply master volume in SW if our HAL can do it for us.
1906    if (mOutput && mOutput->audioHwDev &&
1907        mOutput->audioHwDev->canSetMasterVolume()) {
1908        mMasterVolume = 1.0;
1909    } else {
1910        mMasterVolume = value;
1911    }
1912}
1913
1914void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1915{
1916    Mutex::Autolock _l(mLock);
1917    // Don't apply master mute in SW if our HAL can do it for us.
1918    if (mOutput && mOutput->audioHwDev &&
1919        mOutput->audioHwDev->canSetMasterMute()) {
1920        mMasterMute = false;
1921    } else {
1922        mMasterMute = muted;
1923    }
1924}
1925
1926void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1927{
1928    Mutex::Autolock _l(mLock);
1929    mStreamTypes[stream].volume = value;
1930}
1931
1932void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1933{
1934    Mutex::Autolock _l(mLock);
1935    mStreamTypes[stream].mute = muted;
1936}
1937
1938float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1939{
1940    Mutex::Autolock _l(mLock);
1941    return mStreamTypes[stream].volume;
1942}
1943
1944// addTrack_l() must be called with ThreadBase::mLock held
1945status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1946{
1947    status_t status = ALREADY_EXISTS;
1948
1949    // set retry count for buffer fill
1950    track->mRetryCount = kMaxTrackStartupRetries;
1951    if (mActiveTracks.indexOf(track) < 0) {
1952        // the track is newly added, make sure it fills up all its
1953        // buffers before playing. This is to ensure the client will
1954        // effectively get the latency it requested.
1955        track->mFillingUpStatus = Track::FS_FILLING;
1956        track->mResetDone = false;
1957        track->mPresentationCompleteFrames = 0;
1958        mActiveTracks.add(track);
1959        if (track->mainBuffer() != mMixBuffer) {
1960            sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1961            if (chain != 0) {
1962                ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
1963                chain->incActiveTrackCnt();
1964            }
1965        }
1966
1967        status = NO_ERROR;
1968    }
1969
1970    ALOGV("mWaitWorkCV.broadcast");
1971    mWaitWorkCV.broadcast();
1972
1973    return status;
1974}
1975
1976// destroyTrack_l() must be called with ThreadBase::mLock held
1977void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1978{
1979    track->mState = TrackBase::TERMINATED;
1980    // active tracks are removed by threadLoop()
1981    if (mActiveTracks.indexOf(track) < 0) {
1982        removeTrack_l(track);
1983    }
1984}
1985
1986void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1987{
1988    track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1989    mTracks.remove(track);
1990    deleteTrackName_l(track->name());
1991    // redundant as track is about to be destroyed, for dumpsys only
1992    track->mName = -1;
1993    if (track->isFastTrack()) {
1994        int index = track->mFastIndex;
1995        ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1996        ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1997        mFastTrackAvailMask |= 1 << index;
1998        // redundant as track is about to be destroyed, for dumpsys only
1999        track->mFastIndex = -1;
2000    }
2001    sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2002    if (chain != 0) {
2003        chain->decTrackCnt();
2004    }
2005}
2006
2007String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2008{
2009    String8 out_s8 = String8("");
2010    char *s;
2011
2012    Mutex::Autolock _l(mLock);
2013    if (initCheck() != NO_ERROR) {
2014        return out_s8;
2015    }
2016
2017    s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2018    out_s8 = String8(s);
2019    free(s);
2020    return out_s8;
2021}
2022
2023// audioConfigChanged_l() must be called with AudioFlinger::mLock held
2024void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
2025    AudioSystem::OutputDescriptor desc;
2026    void *param2 = NULL;
2027
2028    ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
2029
2030    switch (event) {
2031    case AudioSystem::OUTPUT_OPENED:
2032    case AudioSystem::OUTPUT_CONFIG_CHANGED:
2033        desc.channels = mChannelMask;
2034        desc.samplingRate = mSampleRate;
2035        desc.format = mFormat;
2036        desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
2037        desc.latency = latency();
2038        param2 = &desc;
2039        break;
2040
2041    case AudioSystem::STREAM_CONFIG_CHANGED:
2042        param2 = &param;
2043    case AudioSystem::OUTPUT_CLOSED:
2044    default:
2045        break;
2046    }
2047    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2048}
2049
2050void AudioFlinger::PlaybackThread::readOutputParameters()
2051{
2052    mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
2053    mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2054    mChannelCount = (uint16_t)popcount(mChannelMask);
2055    mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2056    mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
2057    mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
2058    if (mFrameCount & 15) {
2059        ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2060                mFrameCount);
2061    }
2062
2063    // Calculate size of normal mix buffer relative to the HAL output buffer size
2064    double multiplier = 1.0;
2065    if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
2066        size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
2067        size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2068        // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2069        minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2070        maxNormalFrameCount = maxNormalFrameCount & ~15;
2071        if (maxNormalFrameCount < minNormalFrameCount) {
2072            maxNormalFrameCount = minNormalFrameCount;
2073        }
2074        multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2075        if (multiplier <= 1.0) {
2076            multiplier = 1.0;
2077        } else if (multiplier <= 2.0) {
2078            if (2 * mFrameCount <= maxNormalFrameCount) {
2079                multiplier = 2.0;
2080            } else {
2081                multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2082            }
2083        } else {
2084            // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2085            // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2086            // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2087            // FIXME this rounding up should not be done if no HAL SRC
2088            uint32_t truncMult = (uint32_t) multiplier;
2089            if ((truncMult & 1)) {
2090                if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2091                    ++truncMult;
2092                }
2093            }
2094            multiplier = (double) truncMult;
2095        }
2096    }
2097    mNormalFrameCount = multiplier * mFrameCount;
2098    // round up to nearest 16 frames to satisfy AudioMixer
2099    mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2100    ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
2101
2102    delete[] mMixBuffer;
2103    mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2104    memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
2105
2106    // force reconfiguration of effect chains and engines to take new buffer size and audio
2107    // parameters into account
2108    // Note that mLock is not held when readOutputParameters() is called from the constructor
2109    // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2110    // matter.
2111    // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2112    Vector< sp<EffectChain> > effectChains = mEffectChains;
2113    for (size_t i = 0; i < effectChains.size(); i ++) {
2114        mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2115    }
2116}
2117
2118
2119status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2120{
2121    if (halFrames == NULL || dspFrames == NULL) {
2122        return BAD_VALUE;
2123    }
2124    Mutex::Autolock _l(mLock);
2125    if (initCheck() != NO_ERROR) {
2126        return INVALID_OPERATION;
2127    }
2128    *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2129
2130    if (isSuspended()) {
2131        // return an estimation of rendered frames when the output is suspended
2132        int32_t frames = mBytesWritten - latency_l();
2133        if (frames < 0) {
2134            frames = 0;
2135        }
2136        *dspFrames = (uint32_t)frames;
2137        return NO_ERROR;
2138    } else {
2139        return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
2140    }
2141}
2142
2143uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2144{
2145    Mutex::Autolock _l(mLock);
2146    uint32_t result = 0;
2147    if (getEffectChain_l(sessionId) != 0) {
2148        result = EFFECT_SESSION;
2149    }
2150
2151    for (size_t i = 0; i < mTracks.size(); ++i) {
2152        sp<Track> track = mTracks[i];
2153        if (sessionId == track->sessionId() &&
2154                !(track->mCblk->flags & CBLK_INVALID_MSK)) {
2155            result |= TRACK_SESSION;
2156            break;
2157        }
2158    }
2159
2160    return result;
2161}
2162
2163uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2164{
2165    // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2166    // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2167    if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2168        return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2169    }
2170    for (size_t i = 0; i < mTracks.size(); i++) {
2171        sp<Track> track = mTracks[i];
2172        if (sessionId == track->sessionId() &&
2173                !(track->mCblk->flags & CBLK_INVALID_MSK)) {
2174            return AudioSystem::getStrategyForStream(track->streamType());
2175        }
2176    }
2177    return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2178}
2179
2180
2181AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2182{
2183    Mutex::Autolock _l(mLock);
2184    return mOutput;
2185}
2186
2187AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2188{
2189    Mutex::Autolock _l(mLock);
2190    AudioStreamOut *output = mOutput;
2191    mOutput = NULL;
2192    // FIXME FastMixer might also have a raw ptr to mOutputSink;
2193    //       must push a NULL and wait for ack
2194    mOutputSink.clear();
2195    mPipeSink.clear();
2196    mNormalSink.clear();
2197    return output;
2198}
2199
2200// this method must always be called either with ThreadBase mLock held or inside the thread loop
2201audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2202{
2203    if (mOutput == NULL) {
2204        return NULL;
2205    }
2206    return &mOutput->stream->common;
2207}
2208
2209uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2210{
2211    return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2212}
2213
2214status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2215{
2216    if (!isValidSyncEvent(event)) {
2217        return BAD_VALUE;
2218    }
2219
2220    Mutex::Autolock _l(mLock);
2221
2222    for (size_t i = 0; i < mTracks.size(); ++i) {
2223        sp<Track> track = mTracks[i];
2224        if (event->triggerSession() == track->sessionId()) {
2225            (void) track->setSyncEvent(event);
2226            return NO_ERROR;
2227        }
2228    }
2229
2230    return NAME_NOT_FOUND;
2231}
2232
2233bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2234{
2235    return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2236}
2237
2238void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2239{
2240    size_t count = tracksToRemove.size();
2241    if (CC_UNLIKELY(count)) {
2242        for (size_t i = 0 ; i < count ; i++) {
2243            const sp<Track>& track = tracksToRemove.itemAt(i);
2244            if ((track->sharedBuffer() != 0) &&
2245                    (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2246                AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2247            }
2248        }
2249    }
2250
2251}
2252
2253// ----------------------------------------------------------------------------
2254
2255AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2256        audio_io_handle_t id, audio_devices_t device, type_t type)
2257    :   PlaybackThread(audioFlinger, output, id, device, type),
2258        // mAudioMixer below
2259        // mFastMixer below
2260        mFastMixerFutex(0)
2261        // mOutputSink below
2262        // mPipeSink below
2263        // mNormalSink below
2264{
2265    ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
2266    ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2267            "mFrameCount=%d, mNormalFrameCount=%d",
2268            mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2269            mNormalFrameCount);
2270    mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2271
2272    // FIXME - Current mixer implementation only supports stereo output
2273    if (mChannelCount != FCC_2) {
2274        ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2275    }
2276
2277    // create an NBAIO sink for the HAL output stream, and negotiate
2278    mOutputSink = new AudioStreamOutSink(output->stream);
2279    size_t numCounterOffers = 0;
2280    const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2281    ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2282    ALOG_ASSERT(index == 0);
2283
2284    // initialize fast mixer depending on configuration
2285    bool initFastMixer;
2286    switch (kUseFastMixer) {
2287    case FastMixer_Never:
2288        initFastMixer = false;
2289        break;
2290    case FastMixer_Always:
2291        initFastMixer = true;
2292        break;
2293    case FastMixer_Static:
2294    case FastMixer_Dynamic:
2295        initFastMixer = mFrameCount < mNormalFrameCount;
2296        break;
2297    }
2298    if (initFastMixer) {
2299
2300        // create a MonoPipe to connect our submix to FastMixer
2301        NBAIO_Format format = mOutputSink->format();
2302        // This pipe depth compensates for scheduling latency of the normal mixer thread.
2303        // When it wakes up after a maximum latency, it runs a few cycles quickly before
2304        // finally blocking.  Note the pipe implementation rounds up the request to a power of 2.
2305        MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2306        const NBAIO_Format offers[1] = {format};
2307        size_t numCounterOffers = 0;
2308        ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2309        ALOG_ASSERT(index == 0);
2310        monoPipe->setAvgFrames((mScreenState & 1) ?
2311                (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2312        mPipeSink = monoPipe;
2313
2314#ifdef TEE_SINK_FRAMES
2315        // create a Pipe to archive a copy of FastMixer's output for dumpsys
2316        Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2317        numCounterOffers = 0;
2318        index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2319        ALOG_ASSERT(index == 0);
2320        mTeeSink = teeSink;
2321        PipeReader *teeSource = new PipeReader(*teeSink);
2322        numCounterOffers = 0;
2323        index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2324        ALOG_ASSERT(index == 0);
2325        mTeeSource = teeSource;
2326#endif
2327
2328        // create fast mixer and configure it initially with just one fast track for our submix
2329        mFastMixer = new FastMixer();
2330        FastMixerStateQueue *sq = mFastMixer->sq();
2331#ifdef STATE_QUEUE_DUMP
2332        sq->setObserverDump(&mStateQueueObserverDump);
2333        sq->setMutatorDump(&mStateQueueMutatorDump);
2334#endif
2335        FastMixerState *state = sq->begin();
2336        FastTrack *fastTrack = &state->mFastTracks[0];
2337        // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2338        fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2339        fastTrack->mVolumeProvider = NULL;
2340        fastTrack->mGeneration++;
2341        state->mFastTracksGen++;
2342        state->mTrackMask = 1;
2343        // fast mixer will use the HAL output sink
2344        state->mOutputSink = mOutputSink.get();
2345        state->mOutputSinkGen++;
2346        state->mFrameCount = mFrameCount;
2347        state->mCommand = FastMixerState::COLD_IDLE;
2348        // already done in constructor initialization list
2349        //mFastMixerFutex = 0;
2350        state->mColdFutexAddr = &mFastMixerFutex;
2351        state->mColdGen++;
2352        state->mDumpState = &mFastMixerDumpState;
2353        state->mTeeSink = mTeeSink.get();
2354        sq->end();
2355        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2356
2357        // start the fast mixer
2358        mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2359        pid_t tid = mFastMixer->getTid();
2360        int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2361        if (err != 0) {
2362            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2363                    kPriorityFastMixer, getpid_cached, tid, err);
2364        }
2365
2366#ifdef AUDIO_WATCHDOG
2367        // create and start the watchdog
2368        mAudioWatchdog = new AudioWatchdog();
2369        mAudioWatchdog->setDump(&mAudioWatchdogDump);
2370        mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2371        tid = mAudioWatchdog->getTid();
2372        err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2373        if (err != 0) {
2374            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2375                    kPriorityFastMixer, getpid_cached, tid, err);
2376        }
2377#endif
2378
2379    } else {
2380        mFastMixer = NULL;
2381    }
2382
2383    switch (kUseFastMixer) {
2384    case FastMixer_Never:
2385    case FastMixer_Dynamic:
2386        mNormalSink = mOutputSink;
2387        break;
2388    case FastMixer_Always:
2389        mNormalSink = mPipeSink;
2390        break;
2391    case FastMixer_Static:
2392        mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2393        break;
2394    }
2395}
2396
2397AudioFlinger::MixerThread::~MixerThread()
2398{
2399    if (mFastMixer != NULL) {
2400        FastMixerStateQueue *sq = mFastMixer->sq();
2401        FastMixerState *state = sq->begin();
2402        if (state->mCommand == FastMixerState::COLD_IDLE) {
2403            int32_t old = android_atomic_inc(&mFastMixerFutex);
2404            if (old == -1) {
2405                __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2406            }
2407        }
2408        state->mCommand = FastMixerState::EXIT;
2409        sq->end();
2410        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2411        mFastMixer->join();
2412        // Though the fast mixer thread has exited, it's state queue is still valid.
2413        // We'll use that extract the final state which contains one remaining fast track
2414        // corresponding to our sub-mix.
2415        state = sq->begin();
2416        ALOG_ASSERT(state->mTrackMask == 1);
2417        FastTrack *fastTrack = &state->mFastTracks[0];
2418        ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2419        delete fastTrack->mBufferProvider;
2420        sq->end(false /*didModify*/);
2421        delete mFastMixer;
2422#ifdef AUDIO_WATCHDOG
2423        if (mAudioWatchdog != 0) {
2424            mAudioWatchdog->requestExit();
2425            mAudioWatchdog->requestExitAndWait();
2426            mAudioWatchdog.clear();
2427        }
2428#endif
2429    }
2430    delete mAudioMixer;
2431}
2432
2433class CpuStats {
2434public:
2435    CpuStats();
2436    void sample(const String8 &title);
2437#ifdef DEBUG_CPU_USAGE
2438private:
2439    ThreadCpuUsage mCpuUsage;           // instantaneous thread CPU usage in wall clock ns
2440    CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2441
2442    CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2443
2444    int mCpuNum;                        // thread's current CPU number
2445    int mCpukHz;                        // frequency of thread's current CPU in kHz
2446#endif
2447};
2448
2449CpuStats::CpuStats()
2450#ifdef DEBUG_CPU_USAGE
2451    : mCpuNum(-1), mCpukHz(-1)
2452#endif
2453{
2454}
2455
2456void CpuStats::sample(const String8 &title) {
2457#ifdef DEBUG_CPU_USAGE
2458    // get current thread's delta CPU time in wall clock ns
2459    double wcNs;
2460    bool valid = mCpuUsage.sampleAndEnable(wcNs);
2461
2462    // record sample for wall clock statistics
2463    if (valid) {
2464        mWcStats.sample(wcNs);
2465    }
2466
2467    // get the current CPU number
2468    int cpuNum = sched_getcpu();
2469
2470    // get the current CPU frequency in kHz
2471    int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2472
2473    // check if either CPU number or frequency changed
2474    if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2475        mCpuNum = cpuNum;
2476        mCpukHz = cpukHz;
2477        // ignore sample for purposes of cycles
2478        valid = false;
2479    }
2480
2481    // if no change in CPU number or frequency, then record sample for cycle statistics
2482    if (valid && mCpukHz > 0) {
2483        double cycles = wcNs * cpukHz * 0.000001;
2484        mHzStats.sample(cycles);
2485    }
2486
2487    unsigned n = mWcStats.n();
2488    // mCpuUsage.elapsed() is expensive, so don't call it every loop
2489    if ((n & 127) == 1) {
2490        long long elapsed = mCpuUsage.elapsed();
2491        if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2492            double perLoop = elapsed / (double) n;
2493            double perLoop100 = perLoop * 0.01;
2494            double perLoop1k = perLoop * 0.001;
2495            double mean = mWcStats.mean();
2496            double stddev = mWcStats.stddev();
2497            double minimum = mWcStats.minimum();
2498            double maximum = mWcStats.maximum();
2499            double meanCycles = mHzStats.mean();
2500            double stddevCycles = mHzStats.stddev();
2501            double minCycles = mHzStats.minimum();
2502            double maxCycles = mHzStats.maximum();
2503            mCpuUsage.resetElapsed();
2504            mWcStats.reset();
2505            mHzStats.reset();
2506            ALOGD("CPU usage for %s over past %.1f secs\n"
2507                "  (%u mixer loops at %.1f mean ms per loop):\n"
2508                "  us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2509                "  %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2510                "  MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2511                    title.string(),
2512                    elapsed * .000000001, n, perLoop * .000001,
2513                    mean * .001,
2514                    stddev * .001,
2515                    minimum * .001,
2516                    maximum * .001,
2517                    mean / perLoop100,
2518                    stddev / perLoop100,
2519                    minimum / perLoop100,
2520                    maximum / perLoop100,
2521                    meanCycles / perLoop1k,
2522                    stddevCycles / perLoop1k,
2523                    minCycles / perLoop1k,
2524                    maxCycles / perLoop1k);
2525
2526        }
2527    }
2528#endif
2529};
2530
2531void AudioFlinger::PlaybackThread::checkSilentMode_l()
2532{
2533    if (!mMasterMute) {
2534        char value[PROPERTY_VALUE_MAX];
2535        if (property_get("ro.audio.silent", value, "0") > 0) {
2536            char *endptr;
2537            unsigned long ul = strtoul(value, &endptr, 0);
2538            if (*endptr == '\0' && ul != 0) {
2539                ALOGD("Silence is golden");
2540                // The setprop command will not allow a property to be changed after
2541                // the first time it is set, so we don't have to worry about un-muting.
2542                setMasterMute_l(true);
2543            }
2544        }
2545    }
2546}
2547
2548bool AudioFlinger::PlaybackThread::threadLoop()
2549{
2550    Vector< sp<Track> > tracksToRemove;
2551
2552    standbyTime = systemTime();
2553
2554    // MIXER
2555    nsecs_t lastWarning = 0;
2556
2557    // DUPLICATING
2558    // FIXME could this be made local to while loop?
2559    writeFrames = 0;
2560
2561    cacheParameters_l();
2562    sleepTime = idleSleepTime;
2563
2564    if (mType == MIXER) {
2565        sleepTimeShift = 0;
2566    }
2567
2568    CpuStats cpuStats;
2569    const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2570
2571    acquireWakeLock();
2572
2573    while (!exitPending())
2574    {
2575        cpuStats.sample(myName);
2576
2577        Vector< sp<EffectChain> > effectChains;
2578
2579        processConfigEvents();
2580
2581        { // scope for mLock
2582
2583            Mutex::Autolock _l(mLock);
2584
2585            if (checkForNewParameters_l()) {
2586                cacheParameters_l();
2587            }
2588
2589            saveOutputTracks();
2590
2591            // put audio hardware into standby after short delay
2592            if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2593                        isSuspended())) {
2594                if (!mStandby) {
2595
2596                    threadLoop_standby();
2597
2598                    mStandby = true;
2599                }
2600
2601                if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2602                    // we're about to wait, flush the binder command buffer
2603                    IPCThreadState::self()->flushCommands();
2604
2605                    clearOutputTracks();
2606
2607                    if (exitPending()) break;
2608
2609                    releaseWakeLock_l();
2610                    // wait until we have something to do...
2611                    ALOGV("%s going to sleep", myName.string());
2612                    mWaitWorkCV.wait(mLock);
2613                    ALOGV("%s waking up", myName.string());
2614                    acquireWakeLock_l();
2615
2616                    mMixerStatus = MIXER_IDLE;
2617                    mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2618                    mBytesWritten = 0;
2619
2620                    checkSilentMode_l();
2621
2622                    standbyTime = systemTime() + standbyDelay;
2623                    sleepTime = idleSleepTime;
2624                    if (mType == MIXER) {
2625                        sleepTimeShift = 0;
2626                    }
2627
2628                    continue;
2629                }
2630            }
2631
2632            // mMixerStatusIgnoringFastTracks is also updated internally
2633            mMixerStatus = prepareTracks_l(&tracksToRemove);
2634
2635            // prevent any changes in effect chain list and in each effect chain
2636            // during mixing and effect process as the audio buffers could be deleted
2637            // or modified if an effect is created or deleted
2638            lockEffectChains_l(effectChains);
2639        }
2640
2641        if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
2642            threadLoop_mix();
2643        } else {
2644            threadLoop_sleepTime();
2645        }
2646
2647        if (isSuspended()) {
2648            sleepTime = suspendSleepTimeUs();
2649            mBytesWritten += mixBufferSize;
2650        }
2651
2652        // only process effects if we're going to write
2653        if (sleepTime == 0) {
2654            for (size_t i = 0; i < effectChains.size(); i ++) {
2655                effectChains[i]->process_l();
2656            }
2657        }
2658
2659        // enable changes in effect chain
2660        unlockEffectChains(effectChains);
2661
2662        // sleepTime == 0 means we must write to audio hardware
2663        if (sleepTime == 0) {
2664
2665            threadLoop_write();
2666
2667if (mType == MIXER) {
2668            // write blocked detection
2669            nsecs_t now = systemTime();
2670            nsecs_t delta = now - mLastWriteTime;
2671            if (!mStandby && delta > maxPeriod) {
2672                mNumDelayedWrites++;
2673                if ((now - lastWarning) > kWarningThrottleNs) {
2674#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
2675                    ScopedTrace st(ATRACE_TAG, "underrun");
2676#endif
2677                    ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2678                            ns2ms(delta), mNumDelayedWrites, this);
2679                    lastWarning = now;
2680                }
2681            }
2682}
2683
2684            mStandby = false;
2685        } else {
2686            usleep(sleepTime);
2687        }
2688
2689        // Finally let go of removed track(s), without the lock held
2690        // since we can't guarantee the destructors won't acquire that
2691        // same lock.  This will also mutate and push a new fast mixer state.
2692        threadLoop_removeTracks(tracksToRemove);
2693        tracksToRemove.clear();
2694
2695        // FIXME I don't understand the need for this here;
2696        //       it was in the original code but maybe the
2697        //       assignment in saveOutputTracks() makes this unnecessary?
2698        clearOutputTracks();
2699
2700        // Effect chains will be actually deleted here if they were removed from
2701        // mEffectChains list during mixing or effects processing
2702        effectChains.clear();
2703
2704        // FIXME Note that the above .clear() is no longer necessary since effectChains
2705        // is now local to this block, but will keep it for now (at least until merge done).
2706    }
2707
2708    // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2709    if (mType == MIXER || mType == DIRECT) {
2710        // put output stream into standby mode
2711        if (!mStandby) {
2712            mOutput->stream->common.standby(&mOutput->stream->common);
2713        }
2714    }
2715
2716    releaseWakeLock();
2717
2718    ALOGV("Thread %p type %d exiting", this, mType);
2719    return false;
2720}
2721
2722void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2723{
2724    PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2725}
2726
2727void AudioFlinger::MixerThread::threadLoop_write()
2728{
2729    // FIXME we should only do one push per cycle; confirm this is true
2730    // Start the fast mixer if it's not already running
2731    if (mFastMixer != NULL) {
2732        FastMixerStateQueue *sq = mFastMixer->sq();
2733        FastMixerState *state = sq->begin();
2734        if (state->mCommand != FastMixerState::MIX_WRITE &&
2735                (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2736            if (state->mCommand == FastMixerState::COLD_IDLE) {
2737                int32_t old = android_atomic_inc(&mFastMixerFutex);
2738                if (old == -1) {
2739                    __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2740                }
2741#ifdef AUDIO_WATCHDOG
2742                if (mAudioWatchdog != 0) {
2743                    mAudioWatchdog->resume();
2744                }
2745#endif
2746            }
2747            state->mCommand = FastMixerState::MIX_WRITE;
2748            sq->end();
2749            sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2750            if (kUseFastMixer == FastMixer_Dynamic) {
2751                mNormalSink = mPipeSink;
2752            }
2753        } else {
2754            sq->end(false /*didModify*/);
2755        }
2756    }
2757    PlaybackThread::threadLoop_write();
2758}
2759
2760// shared by MIXER and DIRECT, overridden by DUPLICATING
2761void AudioFlinger::PlaybackThread::threadLoop_write()
2762{
2763    // FIXME rewrite to reduce number of system calls
2764    mLastWriteTime = systemTime();
2765    mInWrite = true;
2766    int bytesWritten;
2767
2768    // If an NBAIO sink is present, use it to write the normal mixer's submix
2769    if (mNormalSink != 0) {
2770#define mBitShift 2 // FIXME
2771        size_t count = mixBufferSize >> mBitShift;
2772#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
2773        Tracer::traceBegin(ATRACE_TAG, "write");
2774#endif
2775        // update the setpoint when gScreenState changes
2776        uint32_t screenState = gScreenState;
2777        if (screenState != mScreenState) {
2778            mScreenState = screenState;
2779            MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2780            if (pipe != NULL) {
2781                pipe->setAvgFrames((mScreenState & 1) ?
2782                        (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2783            }
2784        }
2785        ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
2786#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
2787        Tracer::traceEnd(ATRACE_TAG);
2788#endif
2789        if (framesWritten > 0) {
2790            bytesWritten = framesWritten << mBitShift;
2791        } else {
2792            bytesWritten = framesWritten;
2793        }
2794    // otherwise use the HAL / AudioStreamOut directly
2795    } else {
2796        // Direct output thread.
2797        bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2798    }
2799
2800    if (bytesWritten > 0) mBytesWritten += mixBufferSize;
2801    mNumWrites++;
2802    mInWrite = false;
2803}
2804
2805void AudioFlinger::MixerThread::threadLoop_standby()
2806{
2807    // Idle the fast mixer if it's currently running
2808    if (mFastMixer != NULL) {
2809        FastMixerStateQueue *sq = mFastMixer->sq();
2810        FastMixerState *state = sq->begin();
2811        if (!(state->mCommand & FastMixerState::IDLE)) {
2812            state->mCommand = FastMixerState::COLD_IDLE;
2813            state->mColdFutexAddr = &mFastMixerFutex;
2814            state->mColdGen++;
2815            mFastMixerFutex = 0;
2816            sq->end();
2817            // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2818            sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2819            if (kUseFastMixer == FastMixer_Dynamic) {
2820                mNormalSink = mOutputSink;
2821            }
2822#ifdef AUDIO_WATCHDOG
2823            if (mAudioWatchdog != 0) {
2824                mAudioWatchdog->pause();
2825            }
2826#endif
2827        } else {
2828            sq->end(false /*didModify*/);
2829        }
2830    }
2831    PlaybackThread::threadLoop_standby();
2832}
2833
2834// shared by MIXER and DIRECT, overridden by DUPLICATING
2835void AudioFlinger::PlaybackThread::threadLoop_standby()
2836{
2837    ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2838    mOutput->stream->common.standby(&mOutput->stream->common);
2839}
2840
2841void AudioFlinger::MixerThread::threadLoop_mix()
2842{
2843    // obtain the presentation timestamp of the next output buffer
2844    int64_t pts;
2845    status_t status = INVALID_OPERATION;
2846
2847    if (mNormalSink != 0) {
2848        status = mNormalSink->getNextWriteTimestamp(&pts);
2849    } else {
2850        status = mOutputSink->getNextWriteTimestamp(&pts);
2851    }
2852
2853    if (status != NO_ERROR) {
2854        pts = AudioBufferProvider::kInvalidPTS;
2855    }
2856
2857    // mix buffers...
2858    mAudioMixer->process(pts);
2859    // increase sleep time progressively when application underrun condition clears.
2860    // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2861    // that a steady state of alternating ready/not ready conditions keeps the sleep time
2862    // such that we would underrun the audio HAL.
2863    if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2864        sleepTimeShift--;
2865    }
2866    sleepTime = 0;
2867    standbyTime = systemTime() + standbyDelay;
2868    //TODO: delay standby when effects have a tail
2869}
2870
2871void AudioFlinger::MixerThread::threadLoop_sleepTime()
2872{
2873    // If no tracks are ready, sleep once for the duration of an output
2874    // buffer size, then write 0s to the output
2875    if (sleepTime == 0) {
2876        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2877            sleepTime = activeSleepTime >> sleepTimeShift;
2878            if (sleepTime < kMinThreadSleepTimeUs) {
2879                sleepTime = kMinThreadSleepTimeUs;
2880            }
2881            // reduce sleep time in case of consecutive application underruns to avoid
2882            // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2883            // duration we would end up writing less data than needed by the audio HAL if
2884            // the condition persists.
2885            if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2886                sleepTimeShift++;
2887            }
2888        } else {
2889            sleepTime = idleSleepTime;
2890        }
2891    } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
2892        memset (mMixBuffer, 0, mixBufferSize);
2893        sleepTime = 0;
2894        ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
2895    }
2896    // TODO add standby time extension fct of effect tail
2897}
2898
2899// prepareTracks_l() must be called with ThreadBase::mLock held
2900AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2901        Vector< sp<Track> > *tracksToRemove)
2902{
2903
2904    mixer_state mixerStatus = MIXER_IDLE;
2905    // find out which tracks need to be processed
2906    size_t count = mActiveTracks.size();
2907    size_t mixedTracks = 0;
2908    size_t tracksWithEffect = 0;
2909    // counts only _active_ fast tracks
2910    size_t fastTracks = 0;
2911    uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2912
2913    float masterVolume = mMasterVolume;
2914    bool masterMute = mMasterMute;
2915
2916    if (masterMute) {
2917        masterVolume = 0;
2918    }
2919    // Delegate master volume control to effect in output mix effect chain if needed
2920    sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2921    if (chain != 0) {
2922        uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2923        chain->setVolume_l(&v, &v);
2924        masterVolume = (float)((v + (1 << 23)) >> 24);
2925        chain.clear();
2926    }
2927
2928    // prepare a new state to push
2929    FastMixerStateQueue *sq = NULL;
2930    FastMixerState *state = NULL;
2931    bool didModify = false;
2932    FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2933    if (mFastMixer != NULL) {
2934        sq = mFastMixer->sq();
2935        state = sq->begin();
2936    }
2937
2938    for (size_t i=0 ; i<count ; i++) {
2939        sp<Track> t = mActiveTracks[i].promote();
2940        if (t == 0) continue;
2941
2942        // this const just means the local variable doesn't change
2943        Track* const track = t.get();
2944
2945        // process fast tracks
2946        if (track->isFastTrack()) {
2947
2948            // It's theoretically possible (though unlikely) for a fast track to be created
2949            // and then removed within the same normal mix cycle.  This is not a problem, as
2950            // the track never becomes active so it's fast mixer slot is never touched.
2951            // The converse, of removing an (active) track and then creating a new track
2952            // at the identical fast mixer slot within the same normal mix cycle,
2953            // is impossible because the slot isn't marked available until the end of each cycle.
2954            int j = track->mFastIndex;
2955            ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2956            ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2957            FastTrack *fastTrack = &state->mFastTracks[j];
2958
2959            // Determine whether the track is currently in underrun condition,
2960            // and whether it had a recent underrun.
2961            FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2962            FastTrackUnderruns underruns = ftDump->mUnderruns;
2963            uint32_t recentFull = (underruns.mBitFields.mFull -
2964                    track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2965            uint32_t recentPartial = (underruns.mBitFields.mPartial -
2966                    track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2967            uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2968                    track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2969            uint32_t recentUnderruns = recentPartial + recentEmpty;
2970            track->mObservedUnderruns = underruns;
2971            // don't count underruns that occur while stopping or pausing
2972            // or stopped which can occur when flush() is called while active
2973            if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
2974                track->mUnderrunCount += recentUnderruns;
2975            }
2976
2977            // This is similar to the state machine for normal tracks,
2978            // with a few modifications for fast tracks.
2979            bool isActive = true;
2980            switch (track->mState) {
2981            case TrackBase::STOPPING_1:
2982                // track stays active in STOPPING_1 state until first underrun
2983                if (recentUnderruns > 0) {
2984                    track->mState = TrackBase::STOPPING_2;
2985                }
2986                break;
2987            case TrackBase::PAUSING:
2988                // ramp down is not yet implemented
2989                track->setPaused();
2990                break;
2991            case TrackBase::RESUMING:
2992                // ramp up is not yet implemented
2993                track->mState = TrackBase::ACTIVE;
2994                break;
2995            case TrackBase::ACTIVE:
2996                if (recentFull > 0 || recentPartial > 0) {
2997                    // track has provided at least some frames recently: reset retry count
2998                    track->mRetryCount = kMaxTrackRetries;
2999                }
3000                if (recentUnderruns == 0) {
3001                    // no recent underruns: stay active
3002                    break;
3003                }
3004                // there has recently been an underrun of some kind
3005                if (track->sharedBuffer() == 0) {
3006                    // were any of the recent underruns "empty" (no frames available)?
3007                    if (recentEmpty == 0) {
3008                        // no, then ignore the partial underruns as they are allowed indefinitely
3009                        break;
3010                    }
3011                    // there has recently been an "empty" underrun: decrement the retry counter
3012                    if (--(track->mRetryCount) > 0) {
3013                        break;
3014                    }
3015                    // indicate to client process that the track was disabled because of underrun;
3016                    // it will then automatically call start() when data is available
3017                    android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
3018                    // remove from active list, but state remains ACTIVE [confusing but true]
3019                    isActive = false;
3020                    break;
3021                }
3022                // fall through
3023            case TrackBase::STOPPING_2:
3024            case TrackBase::PAUSED:
3025            case TrackBase::TERMINATED:
3026            case TrackBase::STOPPED:
3027            case TrackBase::FLUSHED:   // flush() while active
3028                // Check for presentation complete if track is inactive
3029                // We have consumed all the buffers of this track.
3030                // This would be incomplete if we auto-paused on underrun
3031                {
3032                    size_t audioHALFrames =
3033                            (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3034                    size_t framesWritten =
3035                            mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3036                    if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3037                        // track stays in active list until presentation is complete
3038                        break;
3039                    }
3040                }
3041                if (track->isStopping_2()) {
3042                    track->mState = TrackBase::STOPPED;
3043                }
3044                if (track->isStopped()) {
3045                    // Can't reset directly, as fast mixer is still polling this track
3046                    //   track->reset();
3047                    // So instead mark this track as needing to be reset after push with ack
3048                    resetMask |= 1 << i;
3049                }
3050                isActive = false;
3051                break;
3052            case TrackBase::IDLE:
3053            default:
3054                LOG_FATAL("unexpected track state %d", track->mState);
3055            }
3056
3057            if (isActive) {
3058                // was it previously inactive?
3059                if (!(state->mTrackMask & (1 << j))) {
3060                    ExtendedAudioBufferProvider *eabp = track;
3061                    VolumeProvider *vp = track;
3062                    fastTrack->mBufferProvider = eabp;
3063                    fastTrack->mVolumeProvider = vp;
3064                    fastTrack->mSampleRate = track->mSampleRate;
3065                    fastTrack->mChannelMask = track->mChannelMask;
3066                    fastTrack->mGeneration++;
3067                    state->mTrackMask |= 1 << j;
3068                    didModify = true;
3069                    // no acknowledgement required for newly active tracks
3070                }
3071                // cache the combined master volume and stream type volume for fast mixer; this
3072                // lacks any synchronization or barrier so VolumeProvider may read a stale value
3073                track->mCachedVolume = track->isMuted() ?
3074                        0 : masterVolume * mStreamTypes[track->streamType()].volume;
3075                ++fastTracks;
3076            } else {
3077                // was it previously active?
3078                if (state->mTrackMask & (1 << j)) {
3079                    fastTrack->mBufferProvider = NULL;
3080                    fastTrack->mGeneration++;
3081                    state->mTrackMask &= ~(1 << j);
3082                    didModify = true;
3083                    // If any fast tracks were removed, we must wait for acknowledgement
3084                    // because we're about to decrement the last sp<> on those tracks.
3085                    block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3086                } else {
3087                    LOG_FATAL("fast track %d should have been active", j);
3088                }
3089                tracksToRemove->add(track);
3090                // Avoids a misleading display in dumpsys
3091                track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3092            }
3093            continue;
3094        }
3095
3096        {   // local variable scope to avoid goto warning
3097
3098        audio_track_cblk_t* cblk = track->cblk();
3099
3100        // The first time a track is added we wait
3101        // for all its buffers to be filled before processing it
3102        int name = track->name();
3103        // make sure that we have enough frames to mix one full buffer.
3104        // enforce this condition only once to enable draining the buffer in case the client
3105        // app does not call stop() and relies on underrun to stop:
3106        // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3107        // during last round
3108        uint32_t minFrames = 1;
3109        if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3110                (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
3111            if (t->sampleRate() == (int)mSampleRate) {
3112                minFrames = mNormalFrameCount;
3113            } else {
3114                // +1 for rounding and +1 for additional sample needed for interpolation
3115                minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
3116                // add frames already consumed but not yet released by the resampler
3117                // because cblk->framesReady() will include these frames
3118                minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3119                // the minimum track buffer size is normally twice the number of frames necessary
3120                // to fill one buffer and the resampler should not leave more than one buffer worth
3121                // of unreleased frames after each pass, but just in case...
3122                ALOG_ASSERT(minFrames <= cblk->frameCount);
3123            }
3124        }
3125        if ((track->framesReady() >= minFrames) && track->isReady() &&
3126                !track->isPaused() && !track->isTerminated())
3127        {
3128            //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
3129
3130            mixedTracks++;
3131
3132            // track->mainBuffer() != mMixBuffer means there is an effect chain
3133            // connected to the track
3134            chain.clear();
3135            if (track->mainBuffer() != mMixBuffer) {
3136                chain = getEffectChain_l(track->sessionId());
3137                // Delegate volume control to effect in track effect chain if needed
3138                if (chain != 0) {
3139                    tracksWithEffect++;
3140                } else {
3141                    ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
3142                            name, track->sessionId());
3143                }
3144            }
3145
3146
3147            int param = AudioMixer::VOLUME;
3148            if (track->mFillingUpStatus == Track::FS_FILLED) {
3149                // no ramp for the first volume setting
3150                track->mFillingUpStatus = Track::FS_ACTIVE;
3151                if (track->mState == TrackBase::RESUMING) {
3152                    track->mState = TrackBase::ACTIVE;
3153                    param = AudioMixer::RAMP_VOLUME;
3154                }
3155                mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
3156            } else if (cblk->server != 0) {
3157                // If the track is stopped before the first frame was mixed,
3158                // do not apply ramp
3159                param = AudioMixer::RAMP_VOLUME;
3160            }
3161
3162            // compute volume for this track
3163            uint32_t vl, vr, va;
3164            if (track->isMuted() || track->isPausing() ||
3165                mStreamTypes[track->streamType()].mute) {
3166                vl = vr = va = 0;
3167                if (track->isPausing()) {
3168                    track->setPaused();
3169                }
3170            } else {
3171
3172                // read original volumes with volume control
3173                float typeVolume = mStreamTypes[track->streamType()].volume;
3174                float v = masterVolume * typeVolume;
3175                uint32_t vlr = cblk->getVolumeLR();
3176                vl = vlr & 0xFFFF;
3177                vr = vlr >> 16;
3178                // track volumes come from shared memory, so can't be trusted and must be clamped
3179                if (vl > MAX_GAIN_INT) {
3180                    ALOGV("Track left volume out of range: %04X", vl);
3181                    vl = MAX_GAIN_INT;
3182                }
3183                if (vr > MAX_GAIN_INT) {
3184                    ALOGV("Track right volume out of range: %04X", vr);
3185                    vr = MAX_GAIN_INT;
3186                }
3187                // now apply the master volume and stream type volume
3188                vl = (uint32_t)(v * vl) << 12;
3189                vr = (uint32_t)(v * vr) << 12;
3190                // assuming master volume and stream type volume each go up to 1.0,
3191                // vl and vr are now in 8.24 format
3192
3193                uint16_t sendLevel = cblk->getSendLevel_U4_12();
3194                // send level comes from shared memory and so may be corrupt
3195                if (sendLevel > MAX_GAIN_INT) {
3196                    ALOGV("Track send level out of range: %04X", sendLevel);
3197                    sendLevel = MAX_GAIN_INT;
3198                }
3199                va = (uint32_t)(v * sendLevel);
3200            }
3201            // Delegate volume control to effect in track effect chain if needed
3202            if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3203                // Do not ramp volume if volume is controlled by effect
3204                param = AudioMixer::VOLUME;
3205                track->mHasVolumeController = true;
3206            } else {
3207                // force no volume ramp when volume controller was just disabled or removed
3208                // from effect chain to avoid volume spike
3209                if (track->mHasVolumeController) {
3210                    param = AudioMixer::VOLUME;
3211                }
3212                track->mHasVolumeController = false;
3213            }
3214
3215            // Convert volumes from 8.24 to 4.12 format
3216            // This additional clamping is needed in case chain->setVolume_l() overshot
3217            vl = (vl + (1 << 11)) >> 12;
3218            if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3219            vr = (vr + (1 << 11)) >> 12;
3220            if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
3221
3222            if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;   // va is uint32_t, so no need to check for -
3223
3224            // XXX: these things DON'T need to be done each time
3225            mAudioMixer->setBufferProvider(name, track);
3226            mAudioMixer->enable(name);
3227
3228            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3229            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3230            mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3231            mAudioMixer->setParameter(
3232                name,
3233                AudioMixer::TRACK,
3234                AudioMixer::FORMAT, (void *)track->format());
3235            mAudioMixer->setParameter(
3236                name,
3237                AudioMixer::TRACK,
3238                AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
3239            mAudioMixer->setParameter(
3240                name,
3241                AudioMixer::RESAMPLE,
3242                AudioMixer::SAMPLE_RATE,
3243                (void *)(cblk->sampleRate));
3244            mAudioMixer->setParameter(
3245                name,
3246                AudioMixer::TRACK,
3247                AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3248            mAudioMixer->setParameter(
3249                name,
3250                AudioMixer::TRACK,
3251                AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3252
3253            // reset retry count
3254            track->mRetryCount = kMaxTrackRetries;
3255
3256            // If one track is ready, set the mixer ready if:
3257            //  - the mixer was not ready during previous round OR
3258            //  - no other track is not ready
3259            if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3260                    mixerStatus != MIXER_TRACKS_ENABLED) {
3261                mixerStatus = MIXER_TRACKS_READY;
3262            }
3263        } else {
3264            // clear effect chain input buffer if an active track underruns to avoid sending
3265            // previous audio buffer again to effects
3266            chain = getEffectChain_l(track->sessionId());
3267            if (chain != 0) {
3268                chain->clearInputBuffer();
3269            }
3270
3271            //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
3272            if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3273                    track->isStopped() || track->isPaused()) {
3274                // We have consumed all the buffers of this track.
3275                // Remove it from the list of active tracks.
3276                // TODO: use actual buffer filling status instead of latency when available from
3277                // audio HAL
3278                size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3279                size_t framesWritten =
3280                        mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3281                if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3282                    if (track->isStopped()) {
3283                        track->reset();
3284                    }
3285                    tracksToRemove->add(track);
3286                }
3287            } else {
3288                track->mUnderrunCount++;
3289                // No buffers for this track. Give it a few chances to
3290                // fill a buffer, then remove it from active list.
3291                if (--(track->mRetryCount) <= 0) {
3292                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
3293                    tracksToRemove->add(track);
3294                    // indicate to client process that the track was disabled because of underrun;
3295                    // it will then automatically call start() when data is available
3296                    android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
3297                // If one track is not ready, mark the mixer also not ready if:
3298                //  - the mixer was ready during previous round OR
3299                //  - no other track is ready
3300                } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3301                                mixerStatus != MIXER_TRACKS_READY) {
3302                    mixerStatus = MIXER_TRACKS_ENABLED;
3303                }
3304            }
3305            mAudioMixer->disable(name);
3306        }
3307
3308        }   // local variable scope to avoid goto warning
3309track_is_ready: ;
3310
3311    }
3312
3313    // Push the new FastMixer state if necessary
3314    bool pauseAudioWatchdog = false;
3315    if (didModify) {
3316        state->mFastTracksGen++;
3317        // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3318        if (kUseFastMixer == FastMixer_Dynamic &&
3319                state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3320            state->mCommand = FastMixerState::COLD_IDLE;
3321            state->mColdFutexAddr = &mFastMixerFutex;
3322            state->mColdGen++;
3323            mFastMixerFutex = 0;
3324            if (kUseFastMixer == FastMixer_Dynamic) {
3325                mNormalSink = mOutputSink;
3326            }
3327            // If we go into cold idle, need to wait for acknowledgement
3328            // so that fast mixer stops doing I/O.
3329            block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3330            pauseAudioWatchdog = true;
3331        }
3332        sq->end();
3333    }
3334    if (sq != NULL) {
3335        sq->end(didModify);
3336        sq->push(block);
3337    }
3338#ifdef AUDIO_WATCHDOG
3339    if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3340        mAudioWatchdog->pause();
3341    }
3342#endif
3343
3344    // Now perform the deferred reset on fast tracks that have stopped
3345    while (resetMask != 0) {
3346        size_t i = __builtin_ctz(resetMask);
3347        ALOG_ASSERT(i < count);
3348        resetMask &= ~(1 << i);
3349        sp<Track> t = mActiveTracks[i].promote();
3350        if (t == 0) continue;
3351        Track* track = t.get();
3352        ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3353        track->reset();
3354    }
3355
3356    // remove all the tracks that need to be...
3357    count = tracksToRemove->size();
3358    if (CC_UNLIKELY(count)) {
3359        for (size_t i=0 ; i<count ; i++) {
3360            const sp<Track>& track = tracksToRemove->itemAt(i);
3361            mActiveTracks.remove(track);
3362            if (track->mainBuffer() != mMixBuffer) {
3363                chain = getEffectChain_l(track->sessionId());
3364                if (chain != 0) {
3365                    ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
3366                    chain->decActiveTrackCnt();
3367                }
3368            }
3369            if (track->isTerminated()) {
3370                removeTrack_l(track);
3371            }
3372        }
3373    }
3374
3375    // mix buffer must be cleared if all tracks are connected to an
3376    // effect chain as in this case the mixer will not write to
3377    // mix buffer and track effects will accumulate into it
3378    if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3379        // FIXME as a performance optimization, should remember previous zero status
3380        memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3381    }
3382
3383    // if any fast tracks, then status is ready
3384    mMixerStatusIgnoringFastTracks = mixerStatus;
3385    if (fastTracks > 0) {
3386        mixerStatus = MIXER_TRACKS_READY;
3387    }
3388    return mixerStatus;
3389}
3390
3391/*
3392The derived values that are cached:
3393 - mixBufferSize from frame count * frame size
3394 - activeSleepTime from activeSleepTimeUs()
3395 - idleSleepTime from idleSleepTimeUs()
3396 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3397 - maxPeriod from frame count and sample rate (MIXER only)
3398
3399The parameters that affect these derived values are:
3400 - frame count
3401 - frame size
3402 - sample rate
3403 - device type: A2DP or not
3404 - device latency
3405 - format: PCM or not
3406 - active sleep time
3407 - idle sleep time
3408*/
3409
3410void AudioFlinger::PlaybackThread::cacheParameters_l()
3411{
3412    mixBufferSize = mNormalFrameCount * mFrameSize;
3413    activeSleepTime = activeSleepTimeUs();
3414    idleSleepTime = idleSleepTimeUs();
3415}
3416
3417void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3418{
3419    ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
3420            this,  streamType, mTracks.size());
3421    Mutex::Autolock _l(mLock);
3422
3423    size_t size = mTracks.size();
3424    for (size_t i = 0; i < size; i++) {
3425        sp<Track> t = mTracks[i];
3426        if (t->streamType() == streamType) {
3427            android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
3428            t->mCblk->cv.signal();
3429        }
3430    }
3431}
3432
3433// getTrackName_l() must be called with ThreadBase::mLock held
3434int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3435{
3436    return mAudioMixer->getTrackName(channelMask, sessionId);
3437}
3438
3439// deleteTrackName_l() must be called with ThreadBase::mLock held
3440void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3441{
3442    ALOGV("remove track (%d) and delete from mixer", name);
3443    mAudioMixer->deleteTrackName(name);
3444}
3445
3446// checkForNewParameters_l() must be called with ThreadBase::mLock held
3447bool AudioFlinger::MixerThread::checkForNewParameters_l()
3448{
3449    // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3450    FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3451    bool reconfig = false;
3452
3453    while (!mNewParameters.isEmpty()) {
3454
3455        if (mFastMixer != NULL) {
3456            FastMixerStateQueue *sq = mFastMixer->sq();
3457            FastMixerState *state = sq->begin();
3458            if (!(state->mCommand & FastMixerState::IDLE)) {
3459                previousCommand = state->mCommand;
3460                state->mCommand = FastMixerState::HOT_IDLE;
3461                sq->end();
3462                sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3463            } else {
3464                sq->end(false /*didModify*/);
3465            }
3466        }
3467
3468        status_t status = NO_ERROR;
3469        String8 keyValuePair = mNewParameters[0];
3470        AudioParameter param = AudioParameter(keyValuePair);
3471        int value;
3472
3473        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3474            reconfig = true;
3475        }
3476        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3477            if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3478                status = BAD_VALUE;
3479            } else {
3480                reconfig = true;
3481            }
3482        }
3483        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3484            if (value != AUDIO_CHANNEL_OUT_STEREO) {
3485                status = BAD_VALUE;
3486            } else {
3487                reconfig = true;
3488            }
3489        }
3490        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3491            // do not accept frame count changes if tracks are open as the track buffer
3492            // size depends on frame count and correct behavior would not be guaranteed
3493            // if frame count is changed after track creation
3494            if (!mTracks.isEmpty()) {
3495                status = INVALID_OPERATION;
3496            } else {
3497                reconfig = true;
3498            }
3499        }
3500        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3501#ifdef ADD_BATTERY_DATA
3502            // when changing the audio output device, call addBatteryData to notify
3503            // the change
3504            if (mOutDevice != value) {
3505                uint32_t params = 0;
3506                // check whether speaker is on
3507                if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3508                    params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3509                }
3510
3511                audio_devices_t deviceWithoutSpeaker
3512                    = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3513                // check if any other device (except speaker) is on
3514                if (value & deviceWithoutSpeaker ) {
3515                    params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3516                }
3517
3518                if (params != 0) {
3519                    addBatteryData(params);
3520                }
3521            }
3522#endif
3523
3524            // forward device change to effects that have requested to be
3525            // aware of attached audio device.
3526            mOutDevice = value;
3527            for (size_t i = 0; i < mEffectChains.size(); i++) {
3528                mEffectChains[i]->setDevice_l(mOutDevice);
3529            }
3530        }
3531
3532        if (status == NO_ERROR) {
3533            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3534                                                    keyValuePair.string());
3535            if (!mStandby && status == INVALID_OPERATION) {
3536                mOutput->stream->common.standby(&mOutput->stream->common);
3537                mStandby = true;
3538                mBytesWritten = 0;
3539                status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3540                                                       keyValuePair.string());
3541            }
3542            if (status == NO_ERROR && reconfig) {
3543                delete mAudioMixer;
3544                // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3545                mAudioMixer = NULL;
3546                readOutputParameters();
3547                mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3548                for (size_t i = 0; i < mTracks.size() ; i++) {
3549                    int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3550                    if (name < 0) break;
3551                    mTracks[i]->mName = name;
3552                    // limit track sample rate to 2 x new output sample rate
3553                    if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3554                        mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3555                    }
3556                }
3557                sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3558            }
3559        }
3560
3561        mNewParameters.removeAt(0);
3562
3563        mParamStatus = status;
3564        mParamCond.signal();
3565        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3566        // already timed out waiting for the status and will never signal the condition.
3567        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3568    }
3569
3570    if (!(previousCommand & FastMixerState::IDLE)) {
3571