AudioFlinger.cpp revision fd4e20c226eca185fc789de761beae64855bfbbb
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 "AudioStreamOutSink.h"
80#include "MonoPipe.h"
81#include "MonoPipeReader.h"
82#include "Pipe.h"
83#include "PipeReader.h"
84#include "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// ----------------------------------------------------------------------------
169
170#ifdef ADD_BATTERY_DATA
171// To collect the amplifier usage
172static void addBatteryData(uint32_t params) {
173    sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
174    if (service == NULL) {
175        // it already logged
176        return;
177    }
178
179    service->addBatteryData(params);
180}
181#endif
182
183static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
184{
185    const hw_module_t *mod;
186    int rc;
187
188    rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
189    ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
190                 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
191    if (rc) {
192        goto out;
193    }
194    rc = audio_hw_device_open(mod, dev);
195    ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
196                 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
197    if (rc) {
198        goto out;
199    }
200    if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
201        ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
202        rc = BAD_VALUE;
203        goto out;
204    }
205    return 0;
206
207out:
208    *dev = NULL;
209    return rc;
210}
211
212// ----------------------------------------------------------------------------
213
214AudioFlinger::AudioFlinger()
215    : BnAudioFlinger(),
216      mPrimaryHardwareDev(NULL),
217      mHardwareStatus(AUDIO_HW_IDLE),
218      mMasterVolume(1.0f),
219      mMasterVolumeSW(1.0f),
220      mMasterVolumeSupportLvl(MVS_NONE),
221      mMasterMute(false),
222      mNextUniqueId(1),
223      mMode(AUDIO_MODE_INVALID),
224      mBtNrecIsOff(false)
225{
226}
227
228void AudioFlinger::onFirstRef()
229{
230    int rc = 0;
231
232    Mutex::Autolock _l(mLock);
233
234    /* TODO: move all this work into an Init() function */
235    char val_str[PROPERTY_VALUE_MAX] = { 0 };
236    if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
237        uint32_t int_val;
238        if (1 == sscanf(val_str, "%u", &int_val)) {
239            mStandbyTimeInNsecs = milliseconds(int_val);
240            ALOGI("Using %u mSec as standby time.", int_val);
241        } else {
242            mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
243            ALOGI("Using default %u mSec as standby time.",
244                    (uint32_t)(mStandbyTimeInNsecs / 1000000));
245        }
246    }
247
248    mMode = AUDIO_MODE_NORMAL;
249}
250
251AudioFlinger::~AudioFlinger()
252{
253    while (!mRecordThreads.isEmpty()) {
254        // closeInput() will remove first entry from mRecordThreads
255        closeInput_nonvirtual(mRecordThreads.keyAt(0));
256    }
257    while (!mPlaybackThreads.isEmpty()) {
258        // closeOutput() will remove first entry from mPlaybackThreads
259        closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
260    }
261
262    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
263        // no mHardwareLock needed, as there are no other references to this
264        audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
265        delete mAudioHwDevs.valueAt(i);
266    }
267}
268
269static const char * const audio_interfaces[] = {
270    AUDIO_HARDWARE_MODULE_ID_PRIMARY,
271    AUDIO_HARDWARE_MODULE_ID_A2DP,
272    AUDIO_HARDWARE_MODULE_ID_USB,
273};
274#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
275
276audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, uint32_t devices)
277{
278    // if module is 0, the request comes from an old policy manager and we should load
279    // well known modules
280    if (module == 0) {
281        ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
282        for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
283            loadHwModule_l(audio_interfaces[i]);
284        }
285    } else {
286        // check a match for the requested module handle
287        AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
288        if (audioHwdevice != NULL) {
289            return audioHwdevice->hwDevice();
290        }
291    }
292    // then try to find a module supporting the requested device.
293    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
294        audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
295        if ((dev->get_supported_devices(dev) & devices) == devices)
296            return dev;
297    }
298
299    return NULL;
300}
301
302status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
303{
304    const size_t SIZE = 256;
305    char buffer[SIZE];
306    String8 result;
307
308    result.append("Clients:\n");
309    for (size_t i = 0; i < mClients.size(); ++i) {
310        sp<Client> client = mClients.valueAt(i).promote();
311        if (client != 0) {
312            snprintf(buffer, SIZE, "  pid: %d\n", client->pid());
313            result.append(buffer);
314        }
315    }
316
317    result.append("Global session refs:\n");
318    result.append(" session pid count\n");
319    for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
320        AudioSessionRef *r = mAudioSessionRefs[i];
321        snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
322        result.append(buffer);
323    }
324    write(fd, result.string(), result.size());
325    return NO_ERROR;
326}
327
328
329status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
330{
331    const size_t SIZE = 256;
332    char buffer[SIZE];
333    String8 result;
334    hardware_call_state hardwareStatus = mHardwareStatus;
335
336    snprintf(buffer, SIZE, "Hardware status: %d\n"
337                           "Standby Time mSec: %u\n",
338                            hardwareStatus,
339                            (uint32_t)(mStandbyTimeInNsecs / 1000000));
340    result.append(buffer);
341    write(fd, result.string(), result.size());
342    return NO_ERROR;
343}
344
345status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
346{
347    const size_t SIZE = 256;
348    char buffer[SIZE];
349    String8 result;
350    snprintf(buffer, SIZE, "Permission Denial: "
351            "can't dump AudioFlinger from pid=%d, uid=%d\n",
352            IPCThreadState::self()->getCallingPid(),
353            IPCThreadState::self()->getCallingUid());
354    result.append(buffer);
355    write(fd, result.string(), result.size());
356    return NO_ERROR;
357}
358
359static bool tryLock(Mutex& mutex)
360{
361    bool locked = false;
362    for (int i = 0; i < kDumpLockRetries; ++i) {
363        if (mutex.tryLock() == NO_ERROR) {
364            locked = true;
365            break;
366        }
367        usleep(kDumpLockSleepUs);
368    }
369    return locked;
370}
371
372status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
373{
374    if (!dumpAllowed()) {
375        dumpPermissionDenial(fd, args);
376    } else {
377        // get state of hardware lock
378        bool hardwareLocked = tryLock(mHardwareLock);
379        if (!hardwareLocked) {
380            String8 result(kHardwareLockedString);
381            write(fd, result.string(), result.size());
382        } else {
383            mHardwareLock.unlock();
384        }
385
386        bool locked = tryLock(mLock);
387
388        // failed to lock - AudioFlinger is probably deadlocked
389        if (!locked) {
390            String8 result(kDeadlockedString);
391            write(fd, result.string(), result.size());
392        }
393
394        dumpClients(fd, args);
395        dumpInternals(fd, args);
396
397        // dump playback threads
398        for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
399            mPlaybackThreads.valueAt(i)->dump(fd, args);
400        }
401
402        // dump record threads
403        for (size_t i = 0; i < mRecordThreads.size(); i++) {
404            mRecordThreads.valueAt(i)->dump(fd, args);
405        }
406
407        // dump all hardware devs
408        for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
409            audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
410            dev->dump(dev, fd);
411        }
412        if (locked) mLock.unlock();
413    }
414    return NO_ERROR;
415}
416
417sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
418{
419    // If pid is already in the mClients wp<> map, then use that entry
420    // (for which promote() is always != 0), otherwise create a new entry and Client.
421    sp<Client> client = mClients.valueFor(pid).promote();
422    if (client == 0) {
423        client = new Client(this, pid);
424        mClients.add(pid, client);
425    }
426
427    return client;
428}
429
430// IAudioFlinger interface
431
432
433sp<IAudioTrack> AudioFlinger::createTrack(
434        pid_t pid,
435        audio_stream_type_t streamType,
436        uint32_t sampleRate,
437        audio_format_t format,
438        audio_channel_mask_t channelMask,
439        int frameCount,
440        IAudioFlinger::track_flags_t flags,
441        const sp<IMemory>& sharedBuffer,
442        audio_io_handle_t output,
443        pid_t tid,
444        int *sessionId,
445        status_t *status)
446{
447    sp<PlaybackThread::Track> track;
448    sp<TrackHandle> trackHandle;
449    sp<Client> client;
450    status_t lStatus;
451    int lSessionId;
452
453    // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
454    // but if someone uses binder directly they could bypass that and cause us to crash
455    if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
456        ALOGE("createTrack() invalid stream type %d", streamType);
457        lStatus = BAD_VALUE;
458        goto Exit;
459    }
460
461    {
462        Mutex::Autolock _l(mLock);
463        PlaybackThread *thread = checkPlaybackThread_l(output);
464        PlaybackThread *effectThread = NULL;
465        if (thread == NULL) {
466            ALOGE("unknown output thread");
467            lStatus = BAD_VALUE;
468            goto Exit;
469        }
470
471        client = registerPid_l(pid);
472
473        ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
474        if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
475            // check if an effect chain with the same session ID is present on another
476            // output thread and move it here.
477            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
478                sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
479                if (mPlaybackThreads.keyAt(i) != output) {
480                    uint32_t sessions = t->hasAudioSession(*sessionId);
481                    if (sessions & PlaybackThread::EFFECT_SESSION) {
482                        effectThread = t.get();
483                        break;
484                    }
485                }
486            }
487            lSessionId = *sessionId;
488        } else {
489            // if no audio session id is provided, create one here
490            lSessionId = nextUniqueId();
491            if (sessionId != NULL) {
492                *sessionId = lSessionId;
493            }
494        }
495        ALOGV("createTrack() lSessionId: %d", lSessionId);
496
497        track = thread->createTrack_l(client, streamType, sampleRate, format,
498                channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
499
500        // move effect chain to this output thread if an effect on same session was waiting
501        // for a track to be created
502        if (lStatus == NO_ERROR && effectThread != NULL) {
503            Mutex::Autolock _dl(thread->mLock);
504            Mutex::Autolock _sl(effectThread->mLock);
505            moveEffectChain_l(lSessionId, effectThread, thread, true);
506        }
507
508        // Look for sync events awaiting for a session to be used.
509        for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
510            if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
511                if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
512                    if (lStatus == NO_ERROR) {
513                        track->setSyncEvent(mPendingSyncEvents[i]);
514                    } else {
515                        mPendingSyncEvents[i]->cancel();
516                    }
517                    mPendingSyncEvents.removeAt(i);
518                    i--;
519                }
520            }
521        }
522    }
523    if (lStatus == NO_ERROR) {
524        trackHandle = new TrackHandle(track);
525    } else {
526        // remove local strong reference to Client before deleting the Track so that the Client
527        // destructor is called by the TrackBase destructor with mLock held
528        client.clear();
529        track.clear();
530    }
531
532Exit:
533    if (status != NULL) {
534        *status = lStatus;
535    }
536    return trackHandle;
537}
538
539uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
540{
541    Mutex::Autolock _l(mLock);
542    PlaybackThread *thread = checkPlaybackThread_l(output);
543    if (thread == NULL) {
544        ALOGW("sampleRate() unknown thread %d", output);
545        return 0;
546    }
547    return thread->sampleRate();
548}
549
550int AudioFlinger::channelCount(audio_io_handle_t output) const
551{
552    Mutex::Autolock _l(mLock);
553    PlaybackThread *thread = checkPlaybackThread_l(output);
554    if (thread == NULL) {
555        ALOGW("channelCount() unknown thread %d", output);
556        return 0;
557    }
558    return thread->channelCount();
559}
560
561audio_format_t AudioFlinger::format(audio_io_handle_t output) const
562{
563    Mutex::Autolock _l(mLock);
564    PlaybackThread *thread = checkPlaybackThread_l(output);
565    if (thread == NULL) {
566        ALOGW("format() unknown thread %d", output);
567        return AUDIO_FORMAT_INVALID;
568    }
569    return thread->format();
570}
571
572size_t AudioFlinger::frameCount(audio_io_handle_t output) const
573{
574    Mutex::Autolock _l(mLock);
575    PlaybackThread *thread = checkPlaybackThread_l(output);
576    if (thread == NULL) {
577        ALOGW("frameCount() unknown thread %d", output);
578        return 0;
579    }
580    // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
581    //       should examine all callers and fix them to handle smaller counts
582    return thread->frameCount();
583}
584
585uint32_t AudioFlinger::latency(audio_io_handle_t output) const
586{
587    Mutex::Autolock _l(mLock);
588    PlaybackThread *thread = checkPlaybackThread_l(output);
589    if (thread == NULL) {
590        ALOGW("latency() unknown thread %d", output);
591        return 0;
592    }
593    return thread->latency();
594}
595
596status_t AudioFlinger::setMasterVolume(float value)
597{
598    status_t ret = initCheck();
599    if (ret != NO_ERROR) {
600        return ret;
601    }
602
603    // check calling permissions
604    if (!settingsAllowed()) {
605        return PERMISSION_DENIED;
606    }
607
608    float swmv = value;
609
610    Mutex::Autolock _l(mLock);
611
612    // when hw supports master volume, don't scale in sw mixer
613    if (MVS_NONE != mMasterVolumeSupportLvl) {
614        for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
615            AutoMutex lock(mHardwareLock);
616            audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
617
618            mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
619            if (NULL != dev->set_master_volume) {
620                dev->set_master_volume(dev, value);
621            }
622            mHardwareStatus = AUDIO_HW_IDLE;
623        }
624
625        swmv = 1.0;
626    }
627
628    mMasterVolume   = value;
629    mMasterVolumeSW = swmv;
630    for (size_t i = 0; i < mPlaybackThreads.size(); i++)
631        mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
632
633    return NO_ERROR;
634}
635
636status_t AudioFlinger::setMode(audio_mode_t mode)
637{
638    status_t ret = initCheck();
639    if (ret != NO_ERROR) {
640        return ret;
641    }
642
643    // check calling permissions
644    if (!settingsAllowed()) {
645        return PERMISSION_DENIED;
646    }
647    if (uint32_t(mode) >= AUDIO_MODE_CNT) {
648        ALOGW("Illegal value: setMode(%d)", mode);
649        return BAD_VALUE;
650    }
651
652    { // scope for the lock
653        AutoMutex lock(mHardwareLock);
654        mHardwareStatus = AUDIO_HW_SET_MODE;
655        ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
656        mHardwareStatus = AUDIO_HW_IDLE;
657    }
658
659    if (NO_ERROR == ret) {
660        Mutex::Autolock _l(mLock);
661        mMode = mode;
662        for (size_t i = 0; i < mPlaybackThreads.size(); i++)
663            mPlaybackThreads.valueAt(i)->setMode(mode);
664    }
665
666    return ret;
667}
668
669status_t AudioFlinger::setMicMute(bool state)
670{
671    status_t ret = initCheck();
672    if (ret != NO_ERROR) {
673        return ret;
674    }
675
676    // check calling permissions
677    if (!settingsAllowed()) {
678        return PERMISSION_DENIED;
679    }
680
681    AutoMutex lock(mHardwareLock);
682    mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
683    ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
684    mHardwareStatus = AUDIO_HW_IDLE;
685    return ret;
686}
687
688bool AudioFlinger::getMicMute() const
689{
690    status_t ret = initCheck();
691    if (ret != NO_ERROR) {
692        return false;
693    }
694
695    bool state = AUDIO_MODE_INVALID;
696    AutoMutex lock(mHardwareLock);
697    mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
698    mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
699    mHardwareStatus = AUDIO_HW_IDLE;
700    return state;
701}
702
703status_t AudioFlinger::setMasterMute(bool muted)
704{
705    // check calling permissions
706    if (!settingsAllowed()) {
707        return PERMISSION_DENIED;
708    }
709
710    Mutex::Autolock _l(mLock);
711    // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
712    mMasterMute = muted;
713    for (size_t i = 0; i < mPlaybackThreads.size(); i++)
714        mPlaybackThreads.valueAt(i)->setMasterMute(muted);
715
716    return NO_ERROR;
717}
718
719float AudioFlinger::masterVolume() const
720{
721    Mutex::Autolock _l(mLock);
722    return masterVolume_l();
723}
724
725float AudioFlinger::masterVolumeSW() const
726{
727    Mutex::Autolock _l(mLock);
728    return masterVolumeSW_l();
729}
730
731bool AudioFlinger::masterMute() const
732{
733    Mutex::Autolock _l(mLock);
734    return masterMute_l();
735}
736
737float AudioFlinger::masterVolume_l() const
738{
739    if (MVS_FULL == mMasterVolumeSupportLvl) {
740        float ret_val;
741        AutoMutex lock(mHardwareLock);
742
743        mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
744        ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
745                    (NULL != mPrimaryHardwareDev->get_master_volume),
746                "can't get master volume");
747
748        mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
749        mHardwareStatus = AUDIO_HW_IDLE;
750        return ret_val;
751    }
752
753    return mMasterVolume;
754}
755
756status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
757        audio_io_handle_t output)
758{
759    // check calling permissions
760    if (!settingsAllowed()) {
761        return PERMISSION_DENIED;
762    }
763
764    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
765        ALOGE("setStreamVolume() invalid stream %d", stream);
766        return BAD_VALUE;
767    }
768
769    AutoMutex lock(mLock);
770    PlaybackThread *thread = NULL;
771    if (output) {
772        thread = checkPlaybackThread_l(output);
773        if (thread == NULL) {
774            return BAD_VALUE;
775        }
776    }
777
778    mStreamTypes[stream].volume = value;
779
780    if (thread == NULL) {
781        for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
782            mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
783        }
784    } else {
785        thread->setStreamVolume(stream, value);
786    }
787
788    return NO_ERROR;
789}
790
791status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
792{
793    // check calling permissions
794    if (!settingsAllowed()) {
795        return PERMISSION_DENIED;
796    }
797
798    if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
799        uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
800        ALOGE("setStreamMute() invalid stream %d", stream);
801        return BAD_VALUE;
802    }
803
804    AutoMutex lock(mLock);
805    mStreamTypes[stream].mute = muted;
806    for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
807        mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
808
809    return NO_ERROR;
810}
811
812float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
813{
814    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
815        return 0.0f;
816    }
817
818    AutoMutex lock(mLock);
819    float volume;
820    if (output) {
821        PlaybackThread *thread = checkPlaybackThread_l(output);
822        if (thread == NULL) {
823            return 0.0f;
824        }
825        volume = thread->streamVolume(stream);
826    } else {
827        volume = streamVolume_l(stream);
828    }
829
830    return volume;
831}
832
833bool AudioFlinger::streamMute(audio_stream_type_t stream) const
834{
835    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
836        return true;
837    }
838
839    AutoMutex lock(mLock);
840    return streamMute_l(stream);
841}
842
843status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
844{
845    ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
846            ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
847    // check calling permissions
848    if (!settingsAllowed()) {
849        return PERMISSION_DENIED;
850    }
851
852    // ioHandle == 0 means the parameters are global to the audio hardware interface
853    if (ioHandle == 0) {
854        Mutex::Autolock _l(mLock);
855        status_t final_result = NO_ERROR;
856        {
857            AutoMutex lock(mHardwareLock);
858            mHardwareStatus = AUDIO_HW_SET_PARAMETER;
859            for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
860                audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
861                status_t result = dev->set_parameters(dev, keyValuePairs.string());
862                final_result = result ?: final_result;
863            }
864            mHardwareStatus = AUDIO_HW_IDLE;
865        }
866        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
867        AudioParameter param = AudioParameter(keyValuePairs);
868        String8 value;
869        if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
870            bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
871            if (mBtNrecIsOff != btNrecIsOff) {
872                for (size_t i = 0; i < mRecordThreads.size(); i++) {
873                    sp<RecordThread> thread = mRecordThreads.valueAt(i);
874                    RecordThread::RecordTrack *track = thread->track();
875                    if (track != NULL) {
876                        audio_devices_t device = (audio_devices_t)(
877                                thread->device() & AUDIO_DEVICE_IN_ALL);
878                        bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
879                        thread->setEffectSuspended(FX_IID_AEC,
880                                                   suspend,
881                                                   track->sessionId());
882                        thread->setEffectSuspended(FX_IID_NS,
883                                                   suspend,
884                                                   track->sessionId());
885                    }
886                }
887                mBtNrecIsOff = btNrecIsOff;
888            }
889        }
890        String8 screenState;
891        if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
892            bool isOff = screenState == "off";
893            if (isOff != (gScreenState & 1)) {
894                gScreenState = ((gScreenState & ~1) + 2) | isOff;
895            }
896        }
897        return final_result;
898    }
899
900    // hold a strong ref on thread in case closeOutput() or closeInput() is called
901    // and the thread is exited once the lock is released
902    sp<ThreadBase> thread;
903    {
904        Mutex::Autolock _l(mLock);
905        thread = checkPlaybackThread_l(ioHandle);
906        if (thread == 0) {
907            thread = checkRecordThread_l(ioHandle);
908        } else if (thread == primaryPlaybackThread_l()) {
909            // indicate output device change to all input threads for pre processing
910            AudioParameter param = AudioParameter(keyValuePairs);
911            int value;
912            if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
913                    (value != 0)) {
914                for (size_t i = 0; i < mRecordThreads.size(); i++) {
915                    mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
916                }
917            }
918        }
919    }
920    if (thread != 0) {
921        return thread->setParameters(keyValuePairs);
922    }
923    return BAD_VALUE;
924}
925
926String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
927{
928//    ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
929//            ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
930
931    Mutex::Autolock _l(mLock);
932
933    if (ioHandle == 0) {
934        String8 out_s8;
935
936        for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
937            char *s;
938            {
939            AutoMutex lock(mHardwareLock);
940            mHardwareStatus = AUDIO_HW_GET_PARAMETER;
941            audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
942            s = dev->get_parameters(dev, keys.string());
943            mHardwareStatus = AUDIO_HW_IDLE;
944            }
945            out_s8 += String8(s ? s : "");
946            free(s);
947        }
948        return out_s8;
949    }
950
951    PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
952    if (playbackThread != NULL) {
953        return playbackThread->getParameters(keys);
954    }
955    RecordThread *recordThread = checkRecordThread_l(ioHandle);
956    if (recordThread != NULL) {
957        return recordThread->getParameters(keys);
958    }
959    return String8("");
960}
961
962size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
963        audio_channel_mask_t channelMask) const
964{
965    status_t ret = initCheck();
966    if (ret != NO_ERROR) {
967        return 0;
968    }
969
970    AutoMutex lock(mHardwareLock);
971    mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
972    struct audio_config config = {
973        sample_rate: sampleRate,
974        channel_mask: channelMask,
975        format: format,
976    };
977    size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
978    mHardwareStatus = AUDIO_HW_IDLE;
979    return size;
980}
981
982unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
983{
984    Mutex::Autolock _l(mLock);
985
986    RecordThread *recordThread = checkRecordThread_l(ioHandle);
987    if (recordThread != NULL) {
988        return recordThread->getInputFramesLost();
989    }
990    return 0;
991}
992
993status_t AudioFlinger::setVoiceVolume(float value)
994{
995    status_t ret = initCheck();
996    if (ret != NO_ERROR) {
997        return ret;
998    }
999
1000    // check calling permissions
1001    if (!settingsAllowed()) {
1002        return PERMISSION_DENIED;
1003    }
1004
1005    AutoMutex lock(mHardwareLock);
1006    mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
1007    ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
1008    mHardwareStatus = AUDIO_HW_IDLE;
1009
1010    return ret;
1011}
1012
1013status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1014        audio_io_handle_t output) const
1015{
1016    status_t status;
1017
1018    Mutex::Autolock _l(mLock);
1019
1020    PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1021    if (playbackThread != NULL) {
1022        return playbackThread->getRenderPosition(halFrames, dspFrames);
1023    }
1024
1025    return BAD_VALUE;
1026}
1027
1028void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1029{
1030
1031    Mutex::Autolock _l(mLock);
1032
1033    pid_t pid = IPCThreadState::self()->getCallingPid();
1034    if (mNotificationClients.indexOfKey(pid) < 0) {
1035        sp<NotificationClient> notificationClient = new NotificationClient(this,
1036                                                                            client,
1037                                                                            pid);
1038        ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
1039
1040        mNotificationClients.add(pid, notificationClient);
1041
1042        sp<IBinder> binder = client->asBinder();
1043        binder->linkToDeath(notificationClient);
1044
1045        // the config change is always sent from playback or record threads to avoid deadlock
1046        // with AudioSystem::gLock
1047        for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1048            mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1049        }
1050
1051        for (size_t i = 0; i < mRecordThreads.size(); i++) {
1052            mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1053        }
1054    }
1055}
1056
1057void AudioFlinger::removeNotificationClient(pid_t pid)
1058{
1059    Mutex::Autolock _l(mLock);
1060
1061    mNotificationClients.removeItem(pid);
1062
1063    ALOGV("%d died, releasing its sessions", pid);
1064    size_t num = mAudioSessionRefs.size();
1065    bool removed = false;
1066    for (size_t i = 0; i< num; ) {
1067        AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1068        ALOGV(" pid %d @ %d", ref->mPid, i);
1069        if (ref->mPid == pid) {
1070            ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1071            mAudioSessionRefs.removeAt(i);
1072            delete ref;
1073            removed = true;
1074            num--;
1075        } else {
1076            i++;
1077        }
1078    }
1079    if (removed) {
1080        purgeStaleEffects_l();
1081    }
1082}
1083
1084// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1085void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
1086{
1087    size_t size = mNotificationClients.size();
1088    for (size_t i = 0; i < size; i++) {
1089        mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1090                                                                               param2);
1091    }
1092}
1093
1094// removeClient_l() must be called with AudioFlinger::mLock held
1095void AudioFlinger::removeClient_l(pid_t pid)
1096{
1097    ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
1098    mClients.removeItem(pid);
1099}
1100
1101// getEffectThread_l() must be called with AudioFlinger::mLock held
1102sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1103{
1104    sp<PlaybackThread> thread;
1105
1106    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1107        if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1108            ALOG_ASSERT(thread == 0);
1109            thread = mPlaybackThreads.valueAt(i);
1110        }
1111    }
1112
1113    return thread;
1114}
1115
1116// ----------------------------------------------------------------------------
1117
1118AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1119        uint32_t device, type_t type)
1120    :   Thread(false),
1121        mType(type),
1122        mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
1123        // mChannelMask
1124        mChannelCount(0),
1125        mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1126        mParamStatus(NO_ERROR),
1127        mStandby(false), mDevice((audio_devices_t) device), mId(id),
1128        mDeathRecipient(new PMDeathRecipient(this))
1129{
1130}
1131
1132AudioFlinger::ThreadBase::~ThreadBase()
1133{
1134    mParamCond.broadcast();
1135    // do not lock the mutex in destructor
1136    releaseWakeLock_l();
1137    if (mPowerManager != 0) {
1138        sp<IBinder> binder = mPowerManager->asBinder();
1139        binder->unlinkToDeath(mDeathRecipient);
1140    }
1141}
1142
1143void AudioFlinger::ThreadBase::exit()
1144{
1145    ALOGV("ThreadBase::exit");
1146    {
1147        // This lock prevents the following race in thread (uniprocessor for illustration):
1148        //  if (!exitPending()) {
1149        //      // context switch from here to exit()
1150        //      // exit() calls requestExit(), what exitPending() observes
1151        //      // exit() calls signal(), which is dropped since no waiters
1152        //      // context switch back from exit() to here
1153        //      mWaitWorkCV.wait(...);
1154        //      // now thread is hung
1155        //  }
1156        AutoMutex lock(mLock);
1157        requestExit();
1158        mWaitWorkCV.signal();
1159    }
1160    // When Thread::requestExitAndWait is made virtual and this method is renamed to
1161    // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
1162    requestExitAndWait();
1163}
1164
1165status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1166{
1167    status_t status;
1168
1169    ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
1170    Mutex::Autolock _l(mLock);
1171
1172    mNewParameters.add(keyValuePairs);
1173    mWaitWorkCV.signal();
1174    // wait condition with timeout in case the thread loop has exited
1175    // before the request could be processed
1176    if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
1177        status = mParamStatus;
1178        mWaitWorkCV.signal();
1179    } else {
1180        status = TIMED_OUT;
1181    }
1182    return status;
1183}
1184
1185void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1186{
1187    Mutex::Autolock _l(mLock);
1188    sendConfigEvent_l(event, param);
1189}
1190
1191// sendConfigEvent_l() must be called with ThreadBase::mLock held
1192void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1193{
1194    ConfigEvent configEvent;
1195    configEvent.mEvent = event;
1196    configEvent.mParam = param;
1197    mConfigEvents.add(configEvent);
1198    ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1199    mWaitWorkCV.signal();
1200}
1201
1202void AudioFlinger::ThreadBase::processConfigEvents()
1203{
1204    mLock.lock();
1205    while (!mConfigEvents.isEmpty()) {
1206        ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
1207        ConfigEvent configEvent = mConfigEvents[0];
1208        mConfigEvents.removeAt(0);
1209        // release mLock before locking AudioFlinger mLock: lock order is always
1210        // AudioFlinger then ThreadBase to avoid cross deadlock
1211        mLock.unlock();
1212        mAudioFlinger->mLock.lock();
1213        audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
1214        mAudioFlinger->mLock.unlock();
1215        mLock.lock();
1216    }
1217    mLock.unlock();
1218}
1219
1220status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1221{
1222    const size_t SIZE = 256;
1223    char buffer[SIZE];
1224    String8 result;
1225
1226    bool locked = tryLock(mLock);
1227    if (!locked) {
1228        snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1229        write(fd, buffer, strlen(buffer));
1230    }
1231
1232    snprintf(buffer, SIZE, "io handle: %d\n", mId);
1233    result.append(buffer);
1234    snprintf(buffer, SIZE, "TID: %d\n", getTid());
1235    result.append(buffer);
1236    snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1237    result.append(buffer);
1238    snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1239    result.append(buffer);
1240    snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1241    result.append(buffer);
1242    snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1243    result.append(buffer);
1244    snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1245    result.append(buffer);
1246    snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1247    result.append(buffer);
1248    snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1249    result.append(buffer);
1250    snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
1251    result.append(buffer);
1252
1253    snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1254    result.append(buffer);
1255    result.append(" Index Command");
1256    for (size_t i = 0; i < mNewParameters.size(); ++i) {
1257        snprintf(buffer, SIZE, "\n %02d    ", i);
1258        result.append(buffer);
1259        result.append(mNewParameters[i]);
1260    }
1261
1262    snprintf(buffer, SIZE, "\n\nPending config events: \n");
1263    result.append(buffer);
1264    snprintf(buffer, SIZE, " Index event param\n");
1265    result.append(buffer);
1266    for (size_t i = 0; i < mConfigEvents.size(); i++) {
1267        snprintf(buffer, SIZE, " %02d    %02d    %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
1268        result.append(buffer);
1269    }
1270    result.append("\n");
1271
1272    write(fd, result.string(), result.size());
1273
1274    if (locked) {
1275        mLock.unlock();
1276    }
1277    return NO_ERROR;
1278}
1279
1280status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1281{
1282    const size_t SIZE = 256;
1283    char buffer[SIZE];
1284    String8 result;
1285
1286    snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1287    write(fd, buffer, strlen(buffer));
1288
1289    for (size_t i = 0; i < mEffectChains.size(); ++i) {
1290        sp<EffectChain> chain = mEffectChains[i];
1291        if (chain != 0) {
1292            chain->dump(fd, args);
1293        }
1294    }
1295    return NO_ERROR;
1296}
1297
1298void AudioFlinger::ThreadBase::acquireWakeLock()
1299{
1300    Mutex::Autolock _l(mLock);
1301    acquireWakeLock_l();
1302}
1303
1304void AudioFlinger::ThreadBase::acquireWakeLock_l()
1305{
1306    if (mPowerManager == 0) {
1307        // use checkService() to avoid blocking if power service is not up yet
1308        sp<IBinder> binder =
1309            defaultServiceManager()->checkService(String16("power"));
1310        if (binder == 0) {
1311            ALOGW("Thread %s cannot connect to the power manager service", mName);
1312        } else {
1313            mPowerManager = interface_cast<IPowerManager>(binder);
1314            binder->linkToDeath(mDeathRecipient);
1315        }
1316    }
1317    if (mPowerManager != 0) {
1318        sp<IBinder> binder = new BBinder();
1319        status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1320                                                         binder,
1321                                                         String16(mName));
1322        if (status == NO_ERROR) {
1323            mWakeLockToken = binder;
1324        }
1325        ALOGV("acquireWakeLock_l() %s status %d", mName, status);
1326    }
1327}
1328
1329void AudioFlinger::ThreadBase::releaseWakeLock()
1330{
1331    Mutex::Autolock _l(mLock);
1332    releaseWakeLock_l();
1333}
1334
1335void AudioFlinger::ThreadBase::releaseWakeLock_l()
1336{
1337    if (mWakeLockToken != 0) {
1338        ALOGV("releaseWakeLock_l() %s", mName);
1339        if (mPowerManager != 0) {
1340            mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1341        }
1342        mWakeLockToken.clear();
1343    }
1344}
1345
1346void AudioFlinger::ThreadBase::clearPowerManager()
1347{
1348    Mutex::Autolock _l(mLock);
1349    releaseWakeLock_l();
1350    mPowerManager.clear();
1351}
1352
1353void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1354{
1355    sp<ThreadBase> thread = mThread.promote();
1356    if (thread != 0) {
1357        thread->clearPowerManager();
1358    }
1359    ALOGW("power manager service died !!!");
1360}
1361
1362void AudioFlinger::ThreadBase::setEffectSuspended(
1363        const effect_uuid_t *type, bool suspend, int sessionId)
1364{
1365    Mutex::Autolock _l(mLock);
1366    setEffectSuspended_l(type, suspend, sessionId);
1367}
1368
1369void AudioFlinger::ThreadBase::setEffectSuspended_l(
1370        const effect_uuid_t *type, bool suspend, int sessionId)
1371{
1372    sp<EffectChain> chain = getEffectChain_l(sessionId);
1373    if (chain != 0) {
1374        if (type != NULL) {
1375            chain->setEffectSuspended_l(type, suspend);
1376        } else {
1377            chain->setEffectSuspendedAll_l(suspend);
1378        }
1379    }
1380
1381    updateSuspendedSessions_l(type, suspend, sessionId);
1382}
1383
1384void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1385{
1386    ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1387    if (index < 0) {
1388        return;
1389    }
1390
1391    KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1392            mSuspendedSessions.editValueAt(index);
1393
1394    for (size_t i = 0; i < sessionEffects.size(); i++) {
1395        sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1396        for (int j = 0; j < desc->mRefCount; j++) {
1397            if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1398                chain->setEffectSuspendedAll_l(true);
1399            } else {
1400                ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1401                    desc->mType.timeLow);
1402                chain->setEffectSuspended_l(&desc->mType, true);
1403            }
1404        }
1405    }
1406}
1407
1408void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1409                                                         bool suspend,
1410                                                         int sessionId)
1411{
1412    ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1413
1414    KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1415
1416    if (suspend) {
1417        if (index >= 0) {
1418            sessionEffects = mSuspendedSessions.editValueAt(index);
1419        } else {
1420            mSuspendedSessions.add(sessionId, sessionEffects);
1421        }
1422    } else {
1423        if (index < 0) {
1424            return;
1425        }
1426        sessionEffects = mSuspendedSessions.editValueAt(index);
1427    }
1428
1429
1430    int key = EffectChain::kKeyForSuspendAll;
1431    if (type != NULL) {
1432        key = type->timeLow;
1433    }
1434    index = sessionEffects.indexOfKey(key);
1435
1436    sp<SuspendedSessionDesc> desc;
1437    if (suspend) {
1438        if (index >= 0) {
1439            desc = sessionEffects.valueAt(index);
1440        } else {
1441            desc = new SuspendedSessionDesc();
1442            if (type != NULL) {
1443                memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1444            }
1445            sessionEffects.add(key, desc);
1446            ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1447        }
1448        desc->mRefCount++;
1449    } else {
1450        if (index < 0) {
1451            return;
1452        }
1453        desc = sessionEffects.valueAt(index);
1454        if (--desc->mRefCount == 0) {
1455            ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1456            sessionEffects.removeItemsAt(index);
1457            if (sessionEffects.isEmpty()) {
1458                ALOGV("updateSuspendedSessions_l() restore removing session %d",
1459                                 sessionId);
1460                mSuspendedSessions.removeItem(sessionId);
1461            }
1462        }
1463    }
1464    if (!sessionEffects.isEmpty()) {
1465        mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1466    }
1467}
1468
1469void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1470                                                            bool enabled,
1471                                                            int sessionId)
1472{
1473    Mutex::Autolock _l(mLock);
1474    checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1475}
1476
1477void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1478                                                            bool enabled,
1479                                                            int sessionId)
1480{
1481    if (mType != RECORD) {
1482        // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1483        // another session. This gives the priority to well behaved effect control panels
1484        // and applications not using global effects.
1485        // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1486        // global effects
1487        if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1488            setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1489        }
1490    }
1491
1492    sp<EffectChain> chain = getEffectChain_l(sessionId);
1493    if (chain != 0) {
1494        chain->checkSuspendOnEffectEnabled(effect, enabled);
1495    }
1496}
1497
1498// ----------------------------------------------------------------------------
1499
1500AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1501                                             AudioStreamOut* output,
1502                                             audio_io_handle_t id,
1503                                             uint32_t device,
1504                                             type_t type)
1505    :   ThreadBase(audioFlinger, id, device, type),
1506        mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1507        // Assumes constructor is called by AudioFlinger with it's mLock held,
1508        // but it would be safer to explicitly pass initial masterMute as parameter
1509        mMasterMute(audioFlinger->masterMute_l()),
1510        // mStreamTypes[] initialized in constructor body
1511        mOutput(output),
1512        // Assumes constructor is called by AudioFlinger with it's mLock held,
1513        // but it would be safer to explicitly pass initial masterVolume as parameter
1514        mMasterVolume(audioFlinger->masterVolumeSW_l()),
1515        mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1516        mMixerStatus(MIXER_IDLE),
1517        mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1518        standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
1519        mScreenState(gScreenState),
1520        // index 0 is reserved for normal mixer's submix
1521        mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
1522{
1523    snprintf(mName, kNameLength, "AudioOut_%X", id);
1524
1525    readOutputParameters();
1526
1527    // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1528    // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1529    for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1530            stream = (audio_stream_type_t) (stream + 1)) {
1531        mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1532        mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1533    }
1534    // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1535    // because mAudioFlinger doesn't have one to copy from
1536}
1537
1538AudioFlinger::PlaybackThread::~PlaybackThread()
1539{
1540    delete [] mMixBuffer;
1541}
1542
1543status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1544{
1545    dumpInternals(fd, args);
1546    dumpTracks(fd, args);
1547    dumpEffectChains(fd, args);
1548    return NO_ERROR;
1549}
1550
1551status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1552{
1553    const size_t SIZE = 256;
1554    char buffer[SIZE];
1555    String8 result;
1556
1557    result.appendFormat("Output thread %p stream volumes in dB:\n    ", this);
1558    for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1559        const stream_type_t *st = &mStreamTypes[i];
1560        if (i > 0) {
1561            result.appendFormat(", ");
1562        }
1563        result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1564        if (st->mute) {
1565            result.append("M");
1566        }
1567    }
1568    result.append("\n");
1569    write(fd, result.string(), result.length());
1570    result.clear();
1571
1572    snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1573    result.append(buffer);
1574    Track::appendDumpHeader(result);
1575    for (size_t i = 0; i < mTracks.size(); ++i) {
1576        sp<Track> track = mTracks[i];
1577        if (track != 0) {
1578            track->dump(buffer, SIZE);
1579            result.append(buffer);
1580        }
1581    }
1582
1583    snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1584    result.append(buffer);
1585    Track::appendDumpHeader(result);
1586    for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1587        sp<Track> track = mActiveTracks[i].promote();
1588        if (track != 0) {
1589            track->dump(buffer, SIZE);
1590            result.append(buffer);
1591        }
1592    }
1593    write(fd, result.string(), result.size());
1594
1595    // These values are "raw"; they will wrap around.  See prepareTracks_l() for a better way.
1596    FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1597    fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1598            underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1599
1600    return NO_ERROR;
1601}
1602
1603status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1604{
1605    const size_t SIZE = 256;
1606    char buffer[SIZE];
1607    String8 result;
1608
1609    snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1610    result.append(buffer);
1611    snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1612    result.append(buffer);
1613    snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1614    result.append(buffer);
1615    snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1616    result.append(buffer);
1617    snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1618    result.append(buffer);
1619    snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1620    result.append(buffer);
1621    snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1622    result.append(buffer);
1623    write(fd, result.string(), result.size());
1624    fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1625
1626    dumpBase(fd, args);
1627
1628    return NO_ERROR;
1629}
1630
1631// Thread virtuals
1632status_t AudioFlinger::PlaybackThread::readyToRun()
1633{
1634    status_t status = initCheck();
1635    if (status == NO_ERROR) {
1636        ALOGI("AudioFlinger's thread %p ready to run", this);
1637    } else {
1638        ALOGE("No working audio driver found.");
1639    }
1640    return status;
1641}
1642
1643void AudioFlinger::PlaybackThread::onFirstRef()
1644{
1645    run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1646}
1647
1648// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1649sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1650        const sp<AudioFlinger::Client>& client,
1651        audio_stream_type_t streamType,
1652        uint32_t sampleRate,
1653        audio_format_t format,
1654        audio_channel_mask_t channelMask,
1655        int frameCount,
1656        const sp<IMemory>& sharedBuffer,
1657        int sessionId,
1658        IAudioFlinger::track_flags_t flags,
1659        pid_t tid,
1660        status_t *status)
1661{
1662    sp<Track> track;
1663    status_t lStatus;
1664
1665    bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1666
1667    // client expresses a preference for FAST, but we get the final say
1668    if (flags & IAudioFlinger::TRACK_FAST) {
1669      if (
1670            // not timed
1671            (!isTimed) &&
1672            // either of these use cases:
1673            (
1674              // use case 1: shared buffer with any frame count
1675              (
1676                (sharedBuffer != 0)
1677              ) ||
1678              // use case 2: callback handler and frame count is default or at least as large as HAL
1679              (
1680                (tid != -1) &&
1681                ((frameCount == 0) ||
1682                (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
1683              )
1684            ) &&
1685            // PCM data
1686            audio_is_linear_pcm(format) &&
1687            // mono or stereo
1688            ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1689              (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1690#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1691            // hardware sample rate
1692            (sampleRate == mSampleRate) &&
1693#endif
1694            // normal mixer has an associated fast mixer
1695            hasFastMixer() &&
1696            // there are sufficient fast track slots available
1697            (mFastTrackAvailMask != 0)
1698            // FIXME test that MixerThread for this fast track has a capable output HAL
1699            // FIXME add a permission test also?
1700        ) {
1701        // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1702        if (frameCount == 0) {
1703            frameCount = mFrameCount * 2;   // FIXME * 2 is due to SRC jitter, should be computed
1704        }
1705        ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1706                frameCount, mFrameCount);
1707      } else {
1708        ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1709                "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
1710                "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1711                isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1712                audio_is_linear_pcm(format),
1713                channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1714        flags &= ~IAudioFlinger::TRACK_FAST;
1715        // For compatibility with AudioTrack calculation, buffer depth is forced
1716        // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1717        // This is probably too conservative, but legacy application code may depend on it.
1718        // If you change this calculation, also review the start threshold which is related.
1719        uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1720        uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1721        if (minBufCount < 2) {
1722            minBufCount = 2;
1723        }
1724        int minFrameCount = mNormalFrameCount * minBufCount;
1725        if (frameCount < minFrameCount) {
1726            frameCount = minFrameCount;
1727        }
1728      }
1729    }
1730
1731    if (mType == DIRECT) {
1732        if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1733            if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1734                ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1735                        "for output %p with format %d",
1736                        sampleRate, format, channelMask, mOutput, mFormat);
1737                lStatus = BAD_VALUE;
1738                goto Exit;
1739            }
1740        }
1741    } else {
1742        // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1743        if (sampleRate > mSampleRate*2) {
1744            ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1745            lStatus = BAD_VALUE;
1746            goto Exit;
1747        }
1748    }
1749
1750    lStatus = initCheck();
1751    if (lStatus != NO_ERROR) {
1752        ALOGE("Audio driver not initialized.");
1753        goto Exit;
1754    }
1755
1756    { // scope for mLock
1757        Mutex::Autolock _l(mLock);
1758
1759        // all tracks in same audio session must share the same routing strategy otherwise
1760        // conflicts will happen when tracks are moved from one output to another by audio policy
1761        // manager
1762        uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1763        for (size_t i = 0; i < mTracks.size(); ++i) {
1764            sp<Track> t = mTracks[i];
1765            if (t != 0 && !t->isOutputTrack()) {
1766                uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1767                if (sessionId == t->sessionId() && strategy != actual) {
1768                    ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1769                            strategy, actual);
1770                    lStatus = BAD_VALUE;
1771                    goto Exit;
1772                }
1773            }
1774        }
1775
1776        if (!isTimed) {
1777            track = new Track(this, client, streamType, sampleRate, format,
1778                    channelMask, frameCount, sharedBuffer, sessionId, flags);
1779        } else {
1780            track = TimedTrack::create(this, client, streamType, sampleRate, format,
1781                    channelMask, frameCount, sharedBuffer, sessionId);
1782        }
1783        if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
1784            lStatus = NO_MEMORY;
1785            goto Exit;
1786        }
1787        mTracks.add(track);
1788
1789        sp<EffectChain> chain = getEffectChain_l(sessionId);
1790        if (chain != 0) {
1791            ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1792            track->setMainBuffer(chain->inBuffer());
1793            chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1794            chain->incTrackCnt();
1795        }
1796    }
1797
1798    if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1799        pid_t callingPid = IPCThreadState::self()->getCallingPid();
1800        // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1801        // so ask activity manager to do this on our behalf
1802        int err = requestPriority(callingPid, tid, kPriorityAudioApp);
1803        if (err != 0) {
1804            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1805                    kPriorityAudioApp, callingPid, tid, err);
1806        }
1807    }
1808
1809    lStatus = NO_ERROR;
1810
1811Exit:
1812    if (status) {
1813        *status = lStatus;
1814    }
1815    return track;
1816}
1817
1818uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1819{
1820    if (mFastMixer != NULL) {
1821        MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1822        latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1823    }
1824    return latency;
1825}
1826
1827uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1828{
1829    return latency;
1830}
1831
1832uint32_t AudioFlinger::PlaybackThread::latency() const
1833{
1834    Mutex::Autolock _l(mLock);
1835    return latency_l();
1836}
1837uint32_t AudioFlinger::PlaybackThread::latency_l() const
1838{
1839    if (initCheck() == NO_ERROR) {
1840        return correctLatency(mOutput->stream->get_latency(mOutput->stream));
1841    } else {
1842        return 0;
1843    }
1844}
1845
1846void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1847{
1848    Mutex::Autolock _l(mLock);
1849    mMasterVolume = value;
1850}
1851
1852void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1853{
1854    Mutex::Autolock _l(mLock);
1855    setMasterMute_l(muted);
1856}
1857
1858void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1859{
1860    Mutex::Autolock _l(mLock);
1861    mStreamTypes[stream].volume = value;
1862}
1863
1864void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1865{
1866    Mutex::Autolock _l(mLock);
1867    mStreamTypes[stream].mute = muted;
1868}
1869
1870float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1871{
1872    Mutex::Autolock _l(mLock);
1873    return mStreamTypes[stream].volume;
1874}
1875
1876// addTrack_l() must be called with ThreadBase::mLock held
1877status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1878{
1879    status_t status = ALREADY_EXISTS;
1880
1881    // set retry count for buffer fill
1882    track->mRetryCount = kMaxTrackStartupRetries;
1883    if (mActiveTracks.indexOf(track) < 0) {
1884        // the track is newly added, make sure it fills up all its
1885        // buffers before playing. This is to ensure the client will
1886        // effectively get the latency it requested.
1887        track->mFillingUpStatus = Track::FS_FILLING;
1888        track->mResetDone = false;
1889        track->mPresentationCompleteFrames = 0;
1890        mActiveTracks.add(track);
1891        if (track->mainBuffer() != mMixBuffer) {
1892            sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1893            if (chain != 0) {
1894                ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
1895                chain->incActiveTrackCnt();
1896            }
1897        }
1898
1899        status = NO_ERROR;
1900    }
1901
1902    ALOGV("mWaitWorkCV.broadcast");
1903    mWaitWorkCV.broadcast();
1904
1905    return status;
1906}
1907
1908// destroyTrack_l() must be called with ThreadBase::mLock held
1909void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1910{
1911    track->mState = TrackBase::TERMINATED;
1912    // active tracks are removed by threadLoop()
1913    if (mActiveTracks.indexOf(track) < 0) {
1914        removeTrack_l(track);
1915    }
1916}
1917
1918void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1919{
1920    track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1921    mTracks.remove(track);
1922    deleteTrackName_l(track->name());
1923    // redundant as track is about to be destroyed, for dumpsys only
1924    track->mName = -1;
1925    if (track->isFastTrack()) {
1926        int index = track->mFastIndex;
1927        ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1928        ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1929        mFastTrackAvailMask |= 1 << index;
1930        // redundant as track is about to be destroyed, for dumpsys only
1931        track->mFastIndex = -1;
1932    }
1933    sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1934    if (chain != 0) {
1935        chain->decTrackCnt();
1936    }
1937}
1938
1939String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1940{
1941    String8 out_s8 = String8("");
1942    char *s;
1943
1944    Mutex::Autolock _l(mLock);
1945    if (initCheck() != NO_ERROR) {
1946        return out_s8;
1947    }
1948
1949    s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1950    out_s8 = String8(s);
1951    free(s);
1952    return out_s8;
1953}
1954
1955// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1956void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1957    AudioSystem::OutputDescriptor desc;
1958    void *param2 = NULL;
1959
1960    ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
1961
1962    switch (event) {
1963    case AudioSystem::OUTPUT_OPENED:
1964    case AudioSystem::OUTPUT_CONFIG_CHANGED:
1965        desc.channels = mChannelMask;
1966        desc.samplingRate = mSampleRate;
1967        desc.format = mFormat;
1968        desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
1969        desc.latency = latency();
1970        param2 = &desc;
1971        break;
1972
1973    case AudioSystem::STREAM_CONFIG_CHANGED:
1974        param2 = &param;
1975    case AudioSystem::OUTPUT_CLOSED:
1976    default:
1977        break;
1978    }
1979    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1980}
1981
1982void AudioFlinger::PlaybackThread::readOutputParameters()
1983{
1984    mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1985    mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1986    mChannelCount = (uint16_t)popcount(mChannelMask);
1987    mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1988    mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
1989    mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
1990    if (mFrameCount & 15) {
1991        ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1992                mFrameCount);
1993    }
1994
1995    // Calculate size of normal mix buffer relative to the HAL output buffer size
1996    double multiplier = 1.0;
1997    if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
1998        size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1999        size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2000        // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2001        minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2002        maxNormalFrameCount = maxNormalFrameCount & ~15;
2003        if (maxNormalFrameCount < minNormalFrameCount) {
2004            maxNormalFrameCount = minNormalFrameCount;
2005        }
2006        multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2007        if (multiplier <= 1.0) {
2008            multiplier = 1.0;
2009        } else if (multiplier <= 2.0) {
2010            if (2 * mFrameCount <= maxNormalFrameCount) {
2011                multiplier = 2.0;
2012            } else {
2013                multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2014            }
2015        } else {
2016            // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2017            // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2018            // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2019            // FIXME this rounding up should not be done if no HAL SRC
2020            uint32_t truncMult = (uint32_t) multiplier;
2021            if ((truncMult & 1)) {
2022                if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2023                    ++truncMult;
2024                }
2025            }
2026            multiplier = (double) truncMult;
2027        }
2028    }
2029    mNormalFrameCount = multiplier * mFrameCount;
2030    // round up to nearest 16 frames to satisfy AudioMixer
2031    mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2032    ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
2033
2034    delete[] mMixBuffer;
2035    mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2036    memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
2037
2038    // force reconfiguration of effect chains and engines to take new buffer size and audio
2039    // parameters into account
2040    // Note that mLock is not held when readOutputParameters() is called from the constructor
2041    // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2042    // matter.
2043    // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2044    Vector< sp<EffectChain> > effectChains = mEffectChains;
2045    for (size_t i = 0; i < effectChains.size(); i ++) {
2046        mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2047    }
2048}
2049
2050
2051status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2052{
2053    if (halFrames == NULL || dspFrames == NULL) {
2054        return BAD_VALUE;
2055    }
2056    Mutex::Autolock _l(mLock);
2057    if (initCheck() != NO_ERROR) {
2058        return INVALID_OPERATION;
2059    }
2060    *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2061
2062    return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
2063}
2064
2065uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
2066{
2067    Mutex::Autolock _l(mLock);
2068    uint32_t result = 0;
2069    if (getEffectChain_l(sessionId) != 0) {
2070        result = EFFECT_SESSION;
2071    }
2072
2073    for (size_t i = 0; i < mTracks.size(); ++i) {
2074        sp<Track> track = mTracks[i];
2075        if (sessionId == track->sessionId() &&
2076                !(track->mCblk->flags & CBLK_INVALID_MSK)) {
2077            result |= TRACK_SESSION;
2078            break;
2079        }
2080    }
2081
2082    return result;
2083}
2084
2085uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2086{
2087    // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2088    // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2089    if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2090        return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2091    }
2092    for (size_t i = 0; i < mTracks.size(); i++) {
2093        sp<Track> track = mTracks[i];
2094        if (sessionId == track->sessionId() &&
2095                !(track->mCblk->flags & CBLK_INVALID_MSK)) {
2096            return AudioSystem::getStrategyForStream(track->streamType());
2097        }
2098    }
2099    return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2100}
2101
2102
2103AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2104{
2105    Mutex::Autolock _l(mLock);
2106    return mOutput;
2107}
2108
2109AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2110{
2111    Mutex::Autolock _l(mLock);
2112    AudioStreamOut *output = mOutput;
2113    mOutput = NULL;
2114    // FIXME FastMixer might also have a raw ptr to mOutputSink;
2115    //       must push a NULL and wait for ack
2116    mOutputSink.clear();
2117    mPipeSink.clear();
2118    mNormalSink.clear();
2119    return output;
2120}
2121
2122// this method must always be called either with ThreadBase mLock held or inside the thread loop
2123audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2124{
2125    if (mOutput == NULL) {
2126        return NULL;
2127    }
2128    return &mOutput->stream->common;
2129}
2130
2131uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2132{
2133    return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2134}
2135
2136status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2137{
2138    if (!isValidSyncEvent(event)) {
2139        return BAD_VALUE;
2140    }
2141
2142    Mutex::Autolock _l(mLock);
2143
2144    for (size_t i = 0; i < mTracks.size(); ++i) {
2145        sp<Track> track = mTracks[i];
2146        if (event->triggerSession() == track->sessionId()) {
2147            track->setSyncEvent(event);
2148            return NO_ERROR;
2149        }
2150    }
2151
2152    return NAME_NOT_FOUND;
2153}
2154
2155bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2156{
2157    switch (event->type()) {
2158    case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2159        return true;
2160    default:
2161        break;
2162    }
2163    return false;
2164}
2165
2166void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2167{
2168    size_t count = tracksToRemove.size();
2169    if (CC_UNLIKELY(count)) {
2170        for (size_t i = 0 ; i < count ; i++) {
2171            const sp<Track>& track = tracksToRemove.itemAt(i);
2172            if ((track->sharedBuffer() != 0) &&
2173                    (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2174                AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2175            }
2176        }
2177    }
2178
2179}
2180
2181// ----------------------------------------------------------------------------
2182
2183AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2184        audio_io_handle_t id, uint32_t device, type_t type)
2185    :   PlaybackThread(audioFlinger, output, id, device, type),
2186        // mAudioMixer below
2187        // mFastMixer below
2188        mFastMixerFutex(0)
2189        // mOutputSink below
2190        // mPipeSink below
2191        // mNormalSink below
2192{
2193    ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2194    ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2195            "mFrameCount=%d, mNormalFrameCount=%d",
2196            mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2197            mNormalFrameCount);
2198    mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2199
2200    // FIXME - Current mixer implementation only supports stereo output
2201    if (mChannelCount != FCC_2) {
2202        ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2203    }
2204
2205    // create an NBAIO sink for the HAL output stream, and negotiate
2206    mOutputSink = new AudioStreamOutSink(output->stream);
2207    size_t numCounterOffers = 0;
2208    const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2209    ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2210    ALOG_ASSERT(index == 0);
2211
2212    // initialize fast mixer depending on configuration
2213    bool initFastMixer;
2214    switch (kUseFastMixer) {
2215    case FastMixer_Never:
2216        initFastMixer = false;
2217        break;
2218    case FastMixer_Always:
2219        initFastMixer = true;
2220        break;
2221    case FastMixer_Static:
2222    case FastMixer_Dynamic:
2223        initFastMixer = mFrameCount < mNormalFrameCount;
2224        break;
2225    }
2226    if (initFastMixer) {
2227
2228        // create a MonoPipe to connect our submix to FastMixer
2229        NBAIO_Format format = mOutputSink->format();
2230        // This pipe depth compensates for scheduling latency of the normal mixer thread.
2231        // When it wakes up after a maximum latency, it runs a few cycles quickly before
2232        // finally blocking.  Note the pipe implementation rounds up the request to a power of 2.
2233        MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2234        const NBAIO_Format offers[1] = {format};
2235        size_t numCounterOffers = 0;
2236        ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2237        ALOG_ASSERT(index == 0);
2238        monoPipe->setAvgFrames((mScreenState & 1) ?
2239                (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2240        mPipeSink = monoPipe;
2241
2242#ifdef TEE_SINK_FRAMES
2243        // create a Pipe to archive a copy of FastMixer's output for dumpsys
2244        Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2245        numCounterOffers = 0;
2246        index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2247        ALOG_ASSERT(index == 0);
2248        mTeeSink = teeSink;
2249        PipeReader *teeSource = new PipeReader(*teeSink);
2250        numCounterOffers = 0;
2251        index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2252        ALOG_ASSERT(index == 0);
2253        mTeeSource = teeSource;
2254#endif
2255
2256        // create fast mixer and configure it initially with just one fast track for our submix
2257        mFastMixer = new FastMixer();
2258        FastMixerStateQueue *sq = mFastMixer->sq();
2259#ifdef STATE_QUEUE_DUMP
2260        sq->setObserverDump(&mStateQueueObserverDump);
2261        sq->setMutatorDump(&mStateQueueMutatorDump);
2262#endif
2263        FastMixerState *state = sq->begin();
2264        FastTrack *fastTrack = &state->mFastTracks[0];
2265        // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2266        fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2267        fastTrack->mVolumeProvider = NULL;
2268        fastTrack->mGeneration++;
2269        state->mFastTracksGen++;
2270        state->mTrackMask = 1;
2271        // fast mixer will use the HAL output sink
2272        state->mOutputSink = mOutputSink.get();
2273        state->mOutputSinkGen++;
2274        state->mFrameCount = mFrameCount;
2275        state->mCommand = FastMixerState::COLD_IDLE;
2276        // already done in constructor initialization list
2277        //mFastMixerFutex = 0;
2278        state->mColdFutexAddr = &mFastMixerFutex;
2279        state->mColdGen++;
2280        state->mDumpState = &mFastMixerDumpState;
2281        state->mTeeSink = mTeeSink.get();
2282        sq->end();
2283        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2284
2285        // start the fast mixer
2286        mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2287        pid_t tid = mFastMixer->getTid();
2288        int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2289        if (err != 0) {
2290            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2291                    kPriorityFastMixer, getpid_cached, tid, err);
2292        }
2293
2294#ifdef AUDIO_WATCHDOG
2295        // create and start the watchdog
2296        mAudioWatchdog = new AudioWatchdog();
2297        mAudioWatchdog->setDump(&mAudioWatchdogDump);
2298        mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2299        tid = mAudioWatchdog->getTid();
2300        err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2301        if (err != 0) {
2302            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2303                    kPriorityFastMixer, getpid_cached, tid, err);
2304        }
2305#endif
2306
2307    } else {
2308        mFastMixer = NULL;
2309    }
2310
2311    switch (kUseFastMixer) {
2312    case FastMixer_Never:
2313    case FastMixer_Dynamic:
2314        mNormalSink = mOutputSink;
2315        break;
2316    case FastMixer_Always:
2317        mNormalSink = mPipeSink;
2318        break;
2319    case FastMixer_Static:
2320        mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2321        break;
2322    }
2323}
2324
2325AudioFlinger::MixerThread::~MixerThread()
2326{
2327    if (mFastMixer != NULL) {
2328        FastMixerStateQueue *sq = mFastMixer->sq();
2329        FastMixerState *state = sq->begin();
2330        if (state->mCommand == FastMixerState::COLD_IDLE) {
2331            int32_t old = android_atomic_inc(&mFastMixerFutex);
2332            if (old == -1) {
2333                __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2334            }
2335        }
2336        state->mCommand = FastMixerState::EXIT;
2337        sq->end();
2338        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2339        mFastMixer->join();
2340        // Though the fast mixer thread has exited, it's state queue is still valid.
2341        // We'll use that extract the final state which contains one remaining fast track
2342        // corresponding to our sub-mix.
2343        state = sq->begin();
2344        ALOG_ASSERT(state->mTrackMask == 1);
2345        FastTrack *fastTrack = &state->mFastTracks[0];
2346        ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2347        delete fastTrack->mBufferProvider;
2348        sq->end(false /*didModify*/);
2349        delete mFastMixer;
2350        if (mAudioWatchdog != 0) {
2351            mAudioWatchdog->requestExit();
2352            mAudioWatchdog->requestExitAndWait();
2353            mAudioWatchdog.clear();
2354        }
2355    }
2356    delete mAudioMixer;
2357}
2358
2359class CpuStats {
2360public:
2361    CpuStats();
2362    void sample(const String8 &title);
2363#ifdef DEBUG_CPU_USAGE
2364private:
2365    ThreadCpuUsage mCpuUsage;           // instantaneous thread CPU usage in wall clock ns
2366    CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2367
2368    CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2369
2370    int mCpuNum;                        // thread's current CPU number
2371    int mCpukHz;                        // frequency of thread's current CPU in kHz
2372#endif
2373};
2374
2375CpuStats::CpuStats()
2376#ifdef DEBUG_CPU_USAGE
2377    : mCpuNum(-1), mCpukHz(-1)
2378#endif
2379{
2380}
2381
2382void CpuStats::sample(const String8 &title) {
2383#ifdef DEBUG_CPU_USAGE
2384    // get current thread's delta CPU time in wall clock ns
2385    double wcNs;
2386    bool valid = mCpuUsage.sampleAndEnable(wcNs);
2387
2388    // record sample for wall clock statistics
2389    if (valid) {
2390        mWcStats.sample(wcNs);
2391    }
2392
2393    // get the current CPU number
2394    int cpuNum = sched_getcpu();
2395
2396    // get the current CPU frequency in kHz
2397    int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2398
2399    // check if either CPU number or frequency changed
2400    if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2401        mCpuNum = cpuNum;
2402        mCpukHz = cpukHz;
2403        // ignore sample for purposes of cycles
2404        valid = false;
2405    }
2406
2407    // if no change in CPU number or frequency, then record sample for cycle statistics
2408    if (valid && mCpukHz > 0) {
2409        double cycles = wcNs * cpukHz * 0.000001;
2410        mHzStats.sample(cycles);
2411    }
2412
2413    unsigned n = mWcStats.n();
2414    // mCpuUsage.elapsed() is expensive, so don't call it every loop
2415    if ((n & 127) == 1) {
2416        long long elapsed = mCpuUsage.elapsed();
2417        if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2418            double perLoop = elapsed / (double) n;
2419            double perLoop100 = perLoop * 0.01;
2420            double perLoop1k = perLoop * 0.001;
2421            double mean = mWcStats.mean();
2422            double stddev = mWcStats.stddev();
2423            double minimum = mWcStats.minimum();
2424            double maximum = mWcStats.maximum();
2425            double meanCycles = mHzStats.mean();
2426            double stddevCycles = mHzStats.stddev();
2427            double minCycles = mHzStats.minimum();
2428            double maxCycles = mHzStats.maximum();
2429            mCpuUsage.resetElapsed();
2430            mWcStats.reset();
2431            mHzStats.reset();
2432            ALOGD("CPU usage for %s over past %.1f secs\n"
2433                "  (%u mixer loops at %.1f mean ms per loop):\n"
2434                "  us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2435                "  %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2436                "  MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2437                    title.string(),
2438                    elapsed * .000000001, n, perLoop * .000001,
2439                    mean * .001,
2440                    stddev * .001,
2441                    minimum * .001,
2442                    maximum * .001,
2443                    mean / perLoop100,
2444                    stddev / perLoop100,
2445                    minimum / perLoop100,
2446                    maximum / perLoop100,
2447                    meanCycles / perLoop1k,
2448                    stddevCycles / perLoop1k,
2449                    minCycles / perLoop1k,
2450                    maxCycles / perLoop1k);
2451
2452        }
2453    }
2454#endif
2455};
2456
2457void AudioFlinger::PlaybackThread::checkSilentMode_l()
2458{
2459    if (!mMasterMute) {
2460        char value[PROPERTY_VALUE_MAX];
2461        if (property_get("ro.audio.silent", value, "0") > 0) {
2462            char *endptr;
2463            unsigned long ul = strtoul(value, &endptr, 0);
2464            if (*endptr == '\0' && ul != 0) {
2465                ALOGD("Silence is golden");
2466                // The setprop command will not allow a property to be changed after
2467                // the first time it is set, so we don't have to worry about un-muting.
2468                setMasterMute_l(true);
2469            }
2470        }
2471    }
2472}
2473
2474bool AudioFlinger::PlaybackThread::threadLoop()
2475{
2476    Vector< sp<Track> > tracksToRemove;
2477
2478    standbyTime = systemTime();
2479
2480    // MIXER
2481    nsecs_t lastWarning = 0;
2482
2483    // DUPLICATING
2484    // FIXME could this be made local to while loop?
2485    writeFrames = 0;
2486
2487    cacheParameters_l();
2488    sleepTime = idleSleepTime;
2489
2490    if (mType == MIXER) {
2491        sleepTimeShift = 0;
2492    }
2493
2494    CpuStats cpuStats;
2495    const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2496
2497    acquireWakeLock();
2498
2499    while (!exitPending())
2500    {
2501        cpuStats.sample(myName);
2502
2503        Vector< sp<EffectChain> > effectChains;
2504
2505        processConfigEvents();
2506
2507        { // scope for mLock
2508
2509            Mutex::Autolock _l(mLock);
2510
2511            if (checkForNewParameters_l()) {
2512                cacheParameters_l();
2513            }
2514
2515            saveOutputTracks();
2516
2517            // put audio hardware into standby after short delay
2518            if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2519                        isSuspended())) {
2520                if (!mStandby) {
2521
2522                    threadLoop_standby();
2523
2524                    mStandby = true;
2525                    mBytesWritten = 0;
2526                }
2527
2528                if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2529                    // we're about to wait, flush the binder command buffer
2530                    IPCThreadState::self()->flushCommands();
2531
2532                    clearOutputTracks();
2533
2534                    if (exitPending()) break;
2535
2536                    releaseWakeLock_l();
2537                    // wait until we have something to do...
2538                    ALOGV("%s going to sleep", myName.string());
2539                    mWaitWorkCV.wait(mLock);
2540                    ALOGV("%s waking up", myName.string());
2541                    acquireWakeLock_l();
2542
2543                    mMixerStatus = MIXER_IDLE;
2544                    mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2545
2546                    checkSilentMode_l();
2547
2548                    standbyTime = systemTime() + standbyDelay;
2549                    sleepTime = idleSleepTime;
2550                    if (mType == MIXER) {
2551                        sleepTimeShift = 0;
2552                    }
2553
2554                    continue;
2555                }
2556            }
2557
2558            // mMixerStatusIgnoringFastTracks is also updated internally
2559            mMixerStatus = prepareTracks_l(&tracksToRemove);
2560
2561            // prevent any changes in effect chain list and in each effect chain
2562            // during mixing and effect process as the audio buffers could be deleted
2563            // or modified if an effect is created or deleted
2564            lockEffectChains_l(effectChains);
2565        }
2566
2567        if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
2568            threadLoop_mix();
2569        } else {
2570            threadLoop_sleepTime();
2571        }
2572
2573        if (isSuspended()) {
2574            sleepTime = suspendSleepTimeUs();
2575        }
2576
2577        // only process effects if we're going to write
2578        if (sleepTime == 0) {
2579            for (size_t i = 0; i < effectChains.size(); i ++) {
2580                effectChains[i]->process_l();
2581            }
2582        }
2583
2584        // enable changes in effect chain
2585        unlockEffectChains(effectChains);
2586
2587        // sleepTime == 0 means we must write to audio hardware
2588        if (sleepTime == 0) {
2589
2590            threadLoop_write();
2591
2592if (mType == MIXER) {
2593            // write blocked detection
2594            nsecs_t now = systemTime();
2595            nsecs_t delta = now - mLastWriteTime;
2596            if (!mStandby && delta > maxPeriod) {
2597                mNumDelayedWrites++;
2598                if ((now - lastWarning) > kWarningThrottleNs) {
2599#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
2600                    ScopedTrace st(ATRACE_TAG, "underrun");
2601#endif
2602                    ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2603                            ns2ms(delta), mNumDelayedWrites, this);
2604                    lastWarning = now;
2605                }
2606            }
2607}
2608
2609            mStandby = false;
2610        } else {
2611            usleep(sleepTime);
2612        }
2613
2614        // Finally let go of removed track(s), without the lock held
2615        // since we can't guarantee the destructors won't acquire that
2616        // same lock.  This will also mutate and push a new fast mixer state.
2617        threadLoop_removeTracks(tracksToRemove);
2618        tracksToRemove.clear();
2619
2620        // FIXME I don't understand the need for this here;
2621        //       it was in the original code but maybe the
2622        //       assignment in saveOutputTracks() makes this unnecessary?
2623        clearOutputTracks();
2624
2625        // Effect chains will be actually deleted here if they were removed from
2626        // mEffectChains list during mixing or effects processing
2627        effectChains.clear();
2628
2629        // FIXME Note that the above .clear() is no longer necessary since effectChains
2630        // is now local to this block, but will keep it for now (at least until merge done).
2631    }
2632
2633    // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2634    if (mType == MIXER || mType == DIRECT) {
2635        // put output stream into standby mode
2636        if (!mStandby) {
2637            mOutput->stream->common.standby(&mOutput->stream->common);
2638        }
2639    }
2640
2641    releaseWakeLock();
2642
2643    ALOGV("Thread %p type %d exiting", this, mType);
2644    return false;
2645}
2646
2647void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2648{
2649    PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2650}
2651
2652void AudioFlinger::MixerThread::threadLoop_write()
2653{
2654    // FIXME we should only do one push per cycle; confirm this is true
2655    // Start the fast mixer if it's not already running
2656    if (mFastMixer != NULL) {
2657        FastMixerStateQueue *sq = mFastMixer->sq();
2658        FastMixerState *state = sq->begin();
2659        if (state->mCommand != FastMixerState::MIX_WRITE &&
2660                (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2661            if (state->mCommand == FastMixerState::COLD_IDLE) {
2662                int32_t old = android_atomic_inc(&mFastMixerFutex);
2663                if (old == -1) {
2664                    __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2665                }
2666                if (mAudioWatchdog != 0) {
2667                    mAudioWatchdog->resume();
2668                }
2669            }
2670            state->mCommand = FastMixerState::MIX_WRITE;
2671            sq->end();
2672            sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2673            if (kUseFastMixer == FastMixer_Dynamic) {
2674                mNormalSink = mPipeSink;
2675            }
2676        } else {
2677            sq->end(false /*didModify*/);
2678        }
2679    }
2680    PlaybackThread::threadLoop_write();
2681}
2682
2683// shared by MIXER and DIRECT, overridden by DUPLICATING
2684void AudioFlinger::PlaybackThread::threadLoop_write()
2685{
2686    // FIXME rewrite to reduce number of system calls
2687    mLastWriteTime = systemTime();
2688    mInWrite = true;
2689    int bytesWritten;
2690
2691    // If an NBAIO sink is present, use it to write the normal mixer's submix
2692    if (mNormalSink != 0) {
2693#define mBitShift 2 // FIXME
2694        size_t count = mixBufferSize >> mBitShift;
2695#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
2696        Tracer::traceBegin(ATRACE_TAG, "write");
2697#endif
2698        // update the setpoint when gScreenState changes
2699        uint32_t screenState = gScreenState;
2700        if (screenState != mScreenState) {
2701            mScreenState = screenState;
2702            MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2703            if (pipe != NULL) {
2704                pipe->setAvgFrames((mScreenState & 1) ?
2705                        (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2706            }
2707        }
2708        ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
2709#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
2710        Tracer::traceEnd(ATRACE_TAG);
2711#endif
2712        if (framesWritten > 0) {
2713            bytesWritten = framesWritten << mBitShift;
2714        } else {
2715            bytesWritten = framesWritten;
2716        }
2717    // otherwise use the HAL / AudioStreamOut directly
2718    } else {
2719        // Direct output thread.
2720        bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2721    }
2722
2723    if (bytesWritten > 0) mBytesWritten += mixBufferSize;
2724    mNumWrites++;
2725    mInWrite = false;
2726}
2727
2728void AudioFlinger::MixerThread::threadLoop_standby()
2729{
2730    // Idle the fast mixer if it's currently running
2731    if (mFastMixer != NULL) {
2732        FastMixerStateQueue *sq = mFastMixer->sq();
2733        FastMixerState *state = sq->begin();
2734        if (!(state->mCommand & FastMixerState::IDLE)) {
2735            state->mCommand = FastMixerState::COLD_IDLE;
2736            state->mColdFutexAddr = &mFastMixerFutex;
2737            state->mColdGen++;
2738            mFastMixerFutex = 0;
2739            sq->end();
2740            // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2741            sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2742            if (kUseFastMixer == FastMixer_Dynamic) {
2743                mNormalSink = mOutputSink;
2744            }
2745            if (mAudioWatchdog != 0) {
2746                mAudioWatchdog->pause();
2747            }
2748        } else {
2749            sq->end(false /*didModify*/);
2750        }
2751    }
2752    PlaybackThread::threadLoop_standby();
2753}
2754
2755// shared by MIXER and DIRECT, overridden by DUPLICATING
2756void AudioFlinger::PlaybackThread::threadLoop_standby()
2757{
2758    ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2759    mOutput->stream->common.standby(&mOutput->stream->common);
2760}
2761
2762void AudioFlinger::MixerThread::threadLoop_mix()
2763{
2764    // obtain the presentation timestamp of the next output buffer
2765    int64_t pts;
2766    status_t status = INVALID_OPERATION;
2767
2768    if (NULL != mOutput->stream->get_next_write_timestamp) {
2769        status = mOutput->stream->get_next_write_timestamp(
2770                mOutput->stream, &pts);
2771    }
2772
2773    if (status != NO_ERROR) {
2774        pts = AudioBufferProvider::kInvalidPTS;
2775    }
2776
2777    // mix buffers...
2778    mAudioMixer->process(pts);
2779    // increase sleep time progressively when application underrun condition clears.
2780    // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2781    // that a steady state of alternating ready/not ready conditions keeps the sleep time
2782    // such that we would underrun the audio HAL.
2783    if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2784        sleepTimeShift--;
2785    }
2786    sleepTime = 0;
2787    standbyTime = systemTime() + standbyDelay;
2788    //TODO: delay standby when effects have a tail
2789}
2790
2791void AudioFlinger::MixerThread::threadLoop_sleepTime()
2792{
2793    // If no tracks are ready, sleep once for the duration of an output
2794    // buffer size, then write 0s to the output
2795    if (sleepTime == 0) {
2796        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2797            sleepTime = activeSleepTime >> sleepTimeShift;
2798            if (sleepTime < kMinThreadSleepTimeUs) {
2799                sleepTime = kMinThreadSleepTimeUs;
2800            }
2801            // reduce sleep time in case of consecutive application underruns to avoid
2802            // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2803            // duration we would end up writing less data than needed by the audio HAL if
2804            // the condition persists.
2805            if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2806                sleepTimeShift++;
2807            }
2808        } else {
2809            sleepTime = idleSleepTime;
2810        }
2811    } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
2812        memset (mMixBuffer, 0, mixBufferSize);
2813        sleepTime = 0;
2814        ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
2815    }
2816    // TODO add standby time extension fct of effect tail
2817}
2818
2819// prepareTracks_l() must be called with ThreadBase::mLock held
2820AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2821        Vector< sp<Track> > *tracksToRemove)
2822{
2823
2824    mixer_state mixerStatus = MIXER_IDLE;
2825    // find out which tracks need to be processed
2826    size_t count = mActiveTracks.size();
2827    size_t mixedTracks = 0;
2828    size_t tracksWithEffect = 0;
2829    // counts only _active_ fast tracks
2830    size_t fastTracks = 0;
2831    uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2832
2833    float masterVolume = mMasterVolume;
2834    bool masterMute = mMasterMute;
2835
2836    if (masterMute) {
2837        masterVolume = 0;
2838    }
2839    // Delegate master volume control to effect in output mix effect chain if needed
2840    sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2841    if (chain != 0) {
2842        uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2843        chain->setVolume_l(&v, &v);
2844        masterVolume = (float)((v + (1 << 23)) >> 24);
2845        chain.clear();
2846    }
2847
2848    // prepare a new state to push
2849    FastMixerStateQueue *sq = NULL;
2850    FastMixerState *state = NULL;
2851    bool didModify = false;
2852    FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2853    if (mFastMixer != NULL) {
2854        sq = mFastMixer->sq();
2855        state = sq->begin();
2856    }
2857
2858    for (size_t i=0 ; i<count ; i++) {
2859        sp<Track> t = mActiveTracks[i].promote();
2860        if (t == 0) continue;
2861
2862        // this const just means the local variable doesn't change
2863        Track* const track = t.get();
2864
2865        // process fast tracks
2866        if (track->isFastTrack()) {
2867
2868            // It's theoretically possible (though unlikely) for a fast track to be created
2869            // and then removed within the same normal mix cycle.  This is not a problem, as
2870            // the track never becomes active so it's fast mixer slot is never touched.
2871            // The converse, of removing an (active) track and then creating a new track
2872            // at the identical fast mixer slot within the same normal mix cycle,
2873            // is impossible because the slot isn't marked available until the end of each cycle.
2874            int j = track->mFastIndex;
2875            ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2876            ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2877            FastTrack *fastTrack = &state->mFastTracks[j];
2878
2879            // Determine whether the track is currently in underrun condition,
2880            // and whether it had a recent underrun.
2881            FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2882            FastTrackUnderruns underruns = ftDump->mUnderruns;
2883            uint32_t recentFull = (underruns.mBitFields.mFull -
2884                    track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2885            uint32_t recentPartial = (underruns.mBitFields.mPartial -
2886                    track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2887            uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2888                    track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2889            uint32_t recentUnderruns = recentPartial + recentEmpty;
2890            track->mObservedUnderruns = underruns;
2891            // don't count underruns that occur while stopping or pausing
2892            // or stopped which can occur when flush() is called while active
2893            if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
2894                track->mUnderrunCount += recentUnderruns;
2895            }
2896
2897            // This is similar to the state machine for normal tracks,
2898            // with a few modifications for fast tracks.
2899            bool isActive = true;
2900            switch (track->mState) {
2901            case TrackBase::STOPPING_1:
2902                // track stays active in STOPPING_1 state until first underrun
2903                if (recentUnderruns > 0) {
2904                    track->mState = TrackBase::STOPPING_2;
2905                }
2906                break;
2907            case TrackBase::PAUSING:
2908                // ramp down is not yet implemented
2909                track->setPaused();
2910                break;
2911            case TrackBase::RESUMING:
2912                // ramp up is not yet implemented
2913                track->mState = TrackBase::ACTIVE;
2914                break;
2915            case TrackBase::ACTIVE:
2916                if (recentFull > 0 || recentPartial > 0) {
2917                    // track has provided at least some frames recently: reset retry count
2918                    track->mRetryCount = kMaxTrackRetries;
2919                }
2920                if (recentUnderruns == 0) {
2921                    // no recent underruns: stay active
2922                    break;
2923                }
2924                // there has recently been an underrun of some kind
2925                if (track->sharedBuffer() == 0) {
2926                    // were any of the recent underruns "empty" (no frames available)?
2927                    if (recentEmpty == 0) {
2928                        // no, then ignore the partial underruns as they are allowed indefinitely
2929                        break;
2930                    }
2931                    // there has recently been an "empty" underrun: decrement the retry counter
2932                    if (--(track->mRetryCount) > 0) {
2933                        break;
2934                    }
2935                    // indicate to client process that the track was disabled because of underrun;
2936                    // it will then automatically call start() when data is available
2937                    android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2938                    // remove from active list, but state remains ACTIVE [confusing but true]
2939                    isActive = false;
2940                    break;
2941                }
2942                // fall through
2943            case TrackBase::STOPPING_2:
2944            case TrackBase::PAUSED:
2945            case TrackBase::TERMINATED:
2946            case TrackBase::STOPPED:
2947            case TrackBase::FLUSHED:   // flush() while active
2948                // Check for presentation complete if track is inactive
2949                // We have consumed all the buffers of this track.
2950                // This would be incomplete if we auto-paused on underrun
2951                {
2952                    size_t audioHALFrames =
2953                            (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2954                    size_t framesWritten =
2955                            mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2956                    if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2957                        // track stays in active list until presentation is complete
2958                        break;
2959                    }
2960                }
2961                if (track->isStopping_2()) {
2962                    track->mState = TrackBase::STOPPED;
2963                }
2964                if (track->isStopped()) {
2965                    // Can't reset directly, as fast mixer is still polling this track
2966                    //   track->reset();
2967                    // So instead mark this track as needing to be reset after push with ack
2968                    resetMask |= 1 << i;
2969                }
2970                isActive = false;
2971                break;
2972            case TrackBase::IDLE:
2973            default:
2974                LOG_FATAL("unexpected track state %d", track->mState);
2975            }
2976
2977            if (isActive) {
2978                // was it previously inactive?
2979                if (!(state->mTrackMask & (1 << j))) {
2980                    ExtendedAudioBufferProvider *eabp = track;
2981                    VolumeProvider *vp = track;
2982                    fastTrack->mBufferProvider = eabp;
2983                    fastTrack->mVolumeProvider = vp;
2984                    fastTrack->mSampleRate = track->mSampleRate;
2985                    fastTrack->mChannelMask = track->mChannelMask;
2986                    fastTrack->mGeneration++;
2987                    state->mTrackMask |= 1 << j;
2988                    didModify = true;
2989                    // no acknowledgement required for newly active tracks
2990                }
2991                // cache the combined master volume and stream type volume for fast mixer; this
2992                // lacks any synchronization or barrier so VolumeProvider may read a stale value
2993                track->mCachedVolume = track->isMuted() ?
2994                        0 : masterVolume * mStreamTypes[track->streamType()].volume;
2995                ++fastTracks;
2996            } else {
2997                // was it previously active?
2998                if (state->mTrackMask & (1 << j)) {
2999                    fastTrack->mBufferProvider = NULL;
3000                    fastTrack->mGeneration++;
3001                    state->mTrackMask &= ~(1 << j);
3002                    didModify = true;
3003                    // If any fast tracks were removed, we must wait for acknowledgement
3004                    // because we're about to decrement the last sp<> on those tracks.
3005                    block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3006                } else {
3007                    LOG_FATAL("fast track %d should have been active", j);
3008                }
3009                tracksToRemove->add(track);
3010                // Avoids a misleading display in dumpsys
3011                track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3012            }
3013            continue;
3014        }
3015
3016        {   // local variable scope to avoid goto warning
3017
3018        audio_track_cblk_t* cblk = track->cblk();
3019
3020        // The first time a track is added we wait
3021        // for all its buffers to be filled before processing it
3022        int name = track->name();
3023        // make sure that we have enough frames to mix one full buffer.
3024        // enforce this condition only once to enable draining the buffer in case the client
3025        // app does not call stop() and relies on underrun to stop:
3026        // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3027        // during last round
3028        uint32_t minFrames = 1;
3029        if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3030                (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
3031            if (t->sampleRate() == (int)mSampleRate) {
3032                minFrames = mNormalFrameCount;
3033            } else {
3034                // +1 for rounding and +1 for additional sample needed for interpolation
3035                minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
3036                // add frames already consumed but not yet released by the resampler
3037                // because cblk->framesReady() will include these frames
3038                minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3039                // the minimum track buffer size is normally twice the number of frames necessary
3040                // to fill one buffer and the resampler should not leave more than one buffer worth
3041                // of unreleased frames after each pass, but just in case...
3042                ALOG_ASSERT(minFrames <= cblk->frameCount);
3043            }
3044        }
3045        if ((track->framesReady() >= minFrames) && track->isReady() &&
3046                !track->isPaused() && !track->isTerminated())
3047        {
3048            //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
3049
3050            mixedTracks++;
3051
3052            // track->mainBuffer() != mMixBuffer means there is an effect chain
3053            // connected to the track
3054            chain.clear();
3055            if (track->mainBuffer() != mMixBuffer) {
3056                chain = getEffectChain_l(track->sessionId());
3057                // Delegate volume control to effect in track effect chain if needed
3058                if (chain != 0) {
3059                    tracksWithEffect++;
3060                } else {
3061                    ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
3062                            name, track->sessionId());
3063                }
3064            }
3065
3066
3067            int param = AudioMixer::VOLUME;
3068            if (track->mFillingUpStatus == Track::FS_FILLED) {
3069                // no ramp for the first volume setting
3070                track->mFillingUpStatus = Track::FS_ACTIVE;
3071                if (track->mState == TrackBase::RESUMING) {
3072                    track->mState = TrackBase::ACTIVE;
3073                    param = AudioMixer::RAMP_VOLUME;
3074                }
3075                mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
3076            } else if (cblk->server != 0) {
3077                // If the track is stopped before the first frame was mixed,
3078                // do not apply ramp
3079                param = AudioMixer::RAMP_VOLUME;
3080            }
3081
3082            // compute volume for this track
3083            uint32_t vl, vr, va;
3084            if (track->isMuted() || track->isPausing() ||
3085                mStreamTypes[track->streamType()].mute) {
3086                vl = vr = va = 0;
3087                if (track->isPausing()) {
3088                    track->setPaused();
3089                }
3090            } else {
3091
3092                // read original volumes with volume control
3093                float typeVolume = mStreamTypes[track->streamType()].volume;
3094                float v = masterVolume * typeVolume;
3095                uint32_t vlr = cblk->getVolumeLR();
3096                vl = vlr & 0xFFFF;
3097                vr = vlr >> 16;
3098                // track volumes come from shared memory, so can't be trusted and must be clamped
3099                if (vl > MAX_GAIN_INT) {
3100                    ALOGV("Track left volume out of range: %04X", vl);
3101                    vl = MAX_GAIN_INT;
3102                }
3103                if (vr > MAX_GAIN_INT) {
3104                    ALOGV("Track right volume out of range: %04X", vr);
3105                    vr = MAX_GAIN_INT;
3106                }
3107                // now apply the master volume and stream type volume
3108                vl = (uint32_t)(v * vl) << 12;
3109                vr = (uint32_t)(v * vr) << 12;
3110                // assuming master volume and stream type volume each go up to 1.0,
3111                // vl and vr are now in 8.24 format
3112
3113                uint16_t sendLevel = cblk->getSendLevel_U4_12();
3114                // send level comes from shared memory and so may be corrupt
3115                if (sendLevel > MAX_GAIN_INT) {
3116                    ALOGV("Track send level out of range: %04X", sendLevel);
3117                    sendLevel = MAX_GAIN_INT;
3118                }
3119                va = (uint32_t)(v * sendLevel);
3120            }
3121            // Delegate volume control to effect in track effect chain if needed
3122            if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3123                // Do not ramp volume if volume is controlled by effect
3124                param = AudioMixer::VOLUME;
3125                track->mHasVolumeController = true;
3126            } else {
3127                // force no volume ramp when volume controller was just disabled or removed
3128                // from effect chain to avoid volume spike
3129                if (track->mHasVolumeController) {
3130                    param = AudioMixer::VOLUME;
3131                }
3132                track->mHasVolumeController = false;
3133            }
3134
3135            // Convert volumes from 8.24 to 4.12 format
3136            // This additional clamping is needed in case chain->setVolume_l() overshot
3137            vl = (vl + (1 << 11)) >> 12;
3138            if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3139            vr = (vr + (1 << 11)) >> 12;
3140            if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
3141
3142            if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;   // va is uint32_t, so no need to check for -
3143
3144            // XXX: these things DON'T need to be done each time
3145            mAudioMixer->setBufferProvider(name, track);
3146            mAudioMixer->enable(name);
3147
3148            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3149            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3150            mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3151            mAudioMixer->setParameter(
3152                name,
3153                AudioMixer::TRACK,
3154                AudioMixer::FORMAT, (void *)track->format());
3155            mAudioMixer->setParameter(
3156                name,
3157                AudioMixer::TRACK,
3158                AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
3159            mAudioMixer->setParameter(
3160                name,
3161                AudioMixer::RESAMPLE,
3162                AudioMixer::SAMPLE_RATE,
3163                (void *)(cblk->sampleRate));
3164            mAudioMixer->setParameter(
3165                name,
3166                AudioMixer::TRACK,
3167                AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3168            mAudioMixer->setParameter(
3169                name,
3170                AudioMixer::TRACK,
3171                AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3172
3173            // reset retry count
3174            track->mRetryCount = kMaxTrackRetries;
3175
3176            // If one track is ready, set the mixer ready if:
3177            //  - the mixer was not ready during previous round OR
3178            //  - no other track is not ready
3179            if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3180                    mixerStatus != MIXER_TRACKS_ENABLED) {
3181                mixerStatus = MIXER_TRACKS_READY;
3182            }
3183        } else {
3184            // clear effect chain input buffer if an active track underruns to avoid sending
3185            // previous audio buffer again to effects
3186            chain = getEffectChain_l(track->sessionId());
3187            if (chain != 0) {
3188                chain->clearInputBuffer();
3189            }
3190
3191            //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
3192            if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3193                    track->isStopped() || track->isPaused()) {
3194                // We have consumed all the buffers of this track.
3195                // Remove it from the list of active tracks.
3196                // TODO: use actual buffer filling status instead of latency when available from
3197                // audio HAL
3198                size_t audioHALFrames =
3199                        (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3200                size_t framesWritten =
3201                        mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3202                if (track->presentationComplete(framesWritten, audioHALFrames)) {
3203                    if (track->isStopped()) {
3204                        track->reset();
3205                    }
3206                    tracksToRemove->add(track);
3207                }
3208            } else {
3209                track->mUnderrunCount++;
3210                // No buffers for this track. Give it a few chances to
3211                // fill a buffer, then remove it from active list.
3212                if (--(track->mRetryCount) <= 0) {
3213                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
3214                    tracksToRemove->add(track);
3215                    // indicate to client process that the track was disabled because of underrun;
3216                    // it will then automatically call start() when data is available
3217                    android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
3218                // If one track is not ready, mark the mixer also not ready if:
3219                //  - the mixer was ready during previous round OR
3220                //  - no other track is ready
3221                } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3222                                mixerStatus != MIXER_TRACKS_READY) {
3223                    mixerStatus = MIXER_TRACKS_ENABLED;
3224                }
3225            }
3226            mAudioMixer->disable(name);
3227        }
3228
3229        }   // local variable scope to avoid goto warning
3230track_is_ready: ;
3231
3232    }
3233
3234    // Push the new FastMixer state if necessary
3235    bool pauseAudioWatchdog = false;
3236    if (didModify) {
3237        state->mFastTracksGen++;
3238        // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3239        if (kUseFastMixer == FastMixer_Dynamic &&
3240                state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3241            state->mCommand = FastMixerState::COLD_IDLE;
3242            state->mColdFutexAddr = &mFastMixerFutex;
3243            state->mColdGen++;
3244            mFastMixerFutex = 0;
3245            if (kUseFastMixer == FastMixer_Dynamic) {
3246                mNormalSink = mOutputSink;
3247            }
3248            // If we go into cold idle, need to wait for acknowledgement
3249            // so that fast mixer stops doing I/O.
3250            block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3251            pauseAudioWatchdog = true;
3252        }
3253        sq->end();
3254    }
3255    if (sq != NULL) {
3256        sq->end(didModify);
3257        sq->push(block);
3258    }
3259    if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3260        mAudioWatchdog->pause();
3261    }
3262
3263    // Now perform the deferred reset on fast tracks that have stopped
3264    while (resetMask != 0) {
3265        size_t i = __builtin_ctz(resetMask);
3266        ALOG_ASSERT(i < count);
3267        resetMask &= ~(1 << i);
3268        sp<Track> t = mActiveTracks[i].promote();
3269        if (t == 0) continue;
3270        Track* track = t.get();
3271        ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3272        track->reset();
3273    }
3274
3275    // remove all the tracks that need to be...
3276    count = tracksToRemove->size();
3277    if (CC_UNLIKELY(count)) {
3278        for (size_t i=0 ; i<count ; i++) {
3279            const sp<Track>& track = tracksToRemove->itemAt(i);
3280            mActiveTracks.remove(track);
3281            if (track->mainBuffer() != mMixBuffer) {
3282                chain = getEffectChain_l(track->sessionId());
3283                if (chain != 0) {
3284                    ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
3285                    chain->decActiveTrackCnt();
3286                }
3287            }
3288            if (track->isTerminated()) {
3289                removeTrack_l(track);
3290            }
3291        }
3292    }
3293
3294    // mix buffer must be cleared if all tracks are connected to an
3295    // effect chain as in this case the mixer will not write to
3296    // mix buffer and track effects will accumulate into it
3297    if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3298        // FIXME as a performance optimization, should remember previous zero status
3299        memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3300    }
3301
3302    // if any fast tracks, then status is ready
3303    mMixerStatusIgnoringFastTracks = mixerStatus;
3304    if (fastTracks > 0) {
3305        mixerStatus = MIXER_TRACKS_READY;
3306    }
3307    return mixerStatus;
3308}
3309
3310/*
3311The derived values that are cached:
3312 - mixBufferSize from frame count * frame size
3313 - activeSleepTime from activeSleepTimeUs()
3314 - idleSleepTime from idleSleepTimeUs()
3315 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3316 - maxPeriod from frame count and sample rate (MIXER only)
3317
3318The parameters that affect these derived values are:
3319 - frame count
3320 - frame size
3321 - sample rate
3322 - device type: A2DP or not
3323 - device latency
3324 - format: PCM or not
3325 - active sleep time
3326 - idle sleep time
3327*/
3328
3329void AudioFlinger::PlaybackThread::cacheParameters_l()
3330{
3331    mixBufferSize = mNormalFrameCount * mFrameSize;
3332    activeSleepTime = activeSleepTimeUs();
3333    idleSleepTime = idleSleepTimeUs();
3334}
3335
3336void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3337{
3338    ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
3339            this,  streamType, mTracks.size());
3340    Mutex::Autolock _l(mLock);
3341
3342    size_t size = mTracks.size();
3343    for (size_t i = 0; i < size; i++) {
3344        sp<Track> t = mTracks[i];
3345        if (t->streamType() == streamType) {
3346            android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
3347            t->mCblk->cv.signal();
3348        }
3349    }
3350}
3351
3352// getTrackName_l() must be called with ThreadBase::mLock held
3353int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
3354{
3355    return mAudioMixer->getTrackName(channelMask);
3356}
3357
3358// deleteTrackName_l() must be called with ThreadBase::mLock held
3359void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3360{
3361    ALOGV("remove track (%d) and delete from mixer", name);
3362    mAudioMixer->deleteTrackName(name);
3363}
3364
3365// checkForNewParameters_l() must be called with ThreadBase::mLock held
3366bool AudioFlinger::MixerThread::checkForNewParameters_l()
3367{
3368    // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3369    FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3370    bool reconfig = false;
3371
3372    while (!mNewParameters.isEmpty()) {
3373
3374        if (mFastMixer != NULL) {
3375            FastMixerStateQueue *sq = mFastMixer->sq();
3376            FastMixerState *state = sq->begin();
3377            if (!(state->mCommand & FastMixerState::IDLE)) {
3378                previousCommand = state->mCommand;
3379                state->mCommand = FastMixerState::HOT_IDLE;
3380                sq->end();
3381                sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3382            } else {
3383                sq->end(false /*didModify*/);
3384            }
3385        }
3386
3387        status_t status = NO_ERROR;
3388        String8 keyValuePair = mNewParameters[0];
3389        AudioParameter param = AudioParameter(keyValuePair);
3390        int value;
3391
3392        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3393            reconfig = true;
3394        }
3395        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3396            if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3397                status = BAD_VALUE;
3398            } else {
3399                reconfig = true;
3400            }
3401        }
3402        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3403            if (value != AUDIO_CHANNEL_OUT_STEREO) {
3404                status = BAD_VALUE;
3405            } else {
3406                reconfig = true;
3407            }
3408        }
3409        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3410            // do not accept frame count changes if tracks are open as the track buffer
3411            // size depends on frame count and correct behavior would not be guaranteed
3412            // if frame count is changed after track creation
3413            if (!mTracks.isEmpty()) {
3414                status = INVALID_OPERATION;
3415            } else {
3416                reconfig = true;
3417            }
3418        }
3419        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3420#ifdef ADD_BATTERY_DATA
3421            // when changing the audio output device, call addBatteryData to notify
3422            // the change
3423            if ((int)mDevice != value) {
3424                uint32_t params = 0;
3425                // check whether speaker is on
3426                if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3427                    params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3428                }
3429
3430                int deviceWithoutSpeaker
3431                    = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3432                // check if any other device (except speaker) is on
3433                if (value & deviceWithoutSpeaker ) {
3434                    params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3435                }
3436
3437                if (params != 0) {
3438                    addBatteryData(params);
3439                }
3440            }
3441#endif
3442
3443            // forward device change to effects that have requested to be
3444            // aware of attached audio device.
3445            mDevice = (audio_devices_t) value;
3446            for (size_t i = 0; i < mEffectChains.size(); i++) {
3447                mEffectChains[i]->setDevice_l(mDevice);
3448            }
3449        }
3450
3451        if (status == NO_ERROR) {
3452            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3453                                                    keyValuePair.string());
3454            if (!mStandby && status == INVALID_OPERATION) {
3455                mOutput->stream->common.standby(&mOutput->stream->common);
3456                mStandby = true;
3457                mBytesWritten = 0;
3458                status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3459                                                       keyValuePair.string());
3460            }
3461            if (status == NO_ERROR && reconfig) {
3462                delete mAudioMixer;
3463                // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3464                mAudioMixer = NULL;
3465                readOutputParameters();
3466                mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3467                for (size_t i = 0; i < mTracks.size() ; i++) {
3468                    int name = getTrackName_l(mTracks[i]->mChannelMask);
3469                    if (name < 0) break;
3470                    mTracks[i]->mName = name;
3471                    // limit track sample rate to 2 x new output sample rate
3472                    if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3473                        mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3474                    }
3475                }
3476                sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3477            }
3478        }
3479
3480        mNewParameters.removeAt(0);
3481
3482        mParamStatus = status;
3483        mParamCond.signal();
3484        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3485        // already timed out waiting for the status and will never signal the condition.
3486        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3487    }
3488
3489    if (!(previousCommand & FastMixerState::IDLE)) {
3490        ALOG_ASSERT(mFastMixer != NULL);
3491        FastMixerStateQueue *sq = mFastMixer->sq();
3492        FastMixerState *state = sq->begin();
3493        ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3494        state->mCommand = previousCommand;
3495        sq->end();
3496        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3497    }
3498
3499    return reconfig;
3500}
3501
3502status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3503{
3504    const size_t SIZE = 256;
3505    char buffer[SIZE];
3506    String8 result;
3507
3508    PlaybackThread::dumpInternals(fd, args);
3509
3510    snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3511    result.append(buffer);
3512    write(fd, result.string(), result.size());
3513
3514    // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3515    FastMixerDumpState copy = mFastMixerDumpState;
3516    copy.dump(fd);
3517
3518#ifdef STATE_QUEUE_DUMP
3519    // Similar for state queue
3520    StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3521    observerCopy.dump(fd);
3522    StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3523    mutatorCopy.dump(fd);
3524#endif
3525
3526    // Write the tee output to a .wav file
3527    NBAIO_Source *teeSource = mTeeSource.get();
3528    if (teeSource != NULL) {
3529        char teePath[64];
3530        struct timeval tv;
3531        gettimeofday(&tv, NULL);
3532        struct tm tm;
3533        localtime_r(&tv.tv_sec, &tm);
3534        strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3535        int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3536        if (teeFd >= 0) {
3537            char wavHeader[44];
3538            memcpy(wavHeader,
3539                "RIFF\0\0\0\0WAVEfmt \20\0\0\0\1\0\2\0\104\254\0\0\0\0\0\0\4\0\20\0data\0\0\0\0",
3540                sizeof(wavHeader));
3541            NBAIO_Format format = teeSource->format();
3542            unsigned channelCount = Format_channelCount(format);
3543            ALOG_ASSERT(channelCount <= FCC_2);
3544            unsigned sampleRate = Format_sampleRate(format);
3545            wavHeader[22] = channelCount;       // number of channels
3546            wavHeader[24] = sampleRate;         // sample rate
3547            wavHeader[25] = sampleRate >> 8;
3548            wavHeader[32] = channelCount * 2;   // block alignment
3549            write(teeFd, wavHeader, sizeof(wavHeader));
3550            size_t total = 0;
3551            bool firstRead = true;
3552            for (;;) {
3553#define TEE_SINK_READ 1024
3554                short buffer[TEE_SINK_READ * FCC_2];
3555                size_t count = TEE_SINK_READ;
3556                ssize_t actual = teeSource->read(buffer, count);
3557                bool wasFirstRead = firstRead;
3558                firstRead = false;
3559                if (actual <= 0) {
3560                    if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3561                        continue;
3562                    }
3563                    break;
3564                }
3565                ALOG_ASSERT(actual <= (ssize_t)count);
3566                write(teeFd, buffer, actual * channelCount * sizeof(short));
3567                total += actual;
3568            }
3569            lseek(teeFd, (off_t) 4, SEEK_SET);
3570            uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3571            write(teeFd, &temp, sizeof(temp));
3572            lseek(teeFd, (off_t) 40, SEEK_SET);
3573            temp =  total * channelCount * sizeof(short);
3574            write(teeFd, &temp, sizeof(temp));
3575            close(teeFd);
3576            fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3577        } else {
3578            fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3579        }
3580    }
3581
3582    if (mAudioWatchdog != 0) {
3583        // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3584        AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3585        wdCopy.dump(fd);
3586    }
3587
3588    return NO_ERROR;
3589}
3590
3591uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3592{
3593    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3594}
3595
3596uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3597{
3598    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3599}
3600
3601void AudioFlinger::MixerThread::cacheParameters_l()
3602{
3603    PlaybackThread::cacheParameters_l();
3604
3605    // FIXME: Relaxed timing because of a certain device that can't meet latency
3606    // Should be reduced to 2x after the vendor fixes the driver issue
3607    // increase threshold again due to low power audio mode. The way this warning
3608    // threshold is calculated and its usefulness should be reconsidered anyway.
3609    maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3610}
3611
3612// ----------------------------------------------------------------------------
3613AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3614        AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3615    :   PlaybackThread(audioFlinger, output, id, device, DIRECT)
3616        // mLeftVolFloat, mRightVolFloat
3617{
3618}
3619
3620AudioFlinger::DirectOutputThread::~DirectOutputThread()
3621{
3622}
3623
3624AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3625    Vector< sp<Track> > *tracksToRemove
3626)
3627{
3628    sp<Track> trackToRemove;
3629
3630    mixer_state mixerStatus = MIXER_IDLE;
3631
3632    // find out which tracks need to be processed
3633    if (mActiveTracks.size() != 0) {
3634        sp<Track> t = mActiveTracks[0].promote();
3635        // The track died recently
3636        if (t == 0) return MIXER_IDLE;
3637
3638        Track* const track = t.get();
3639        audio_track_cblk_t* cblk = track->cblk();
3640
3641        // The first time a track is added we wait
3642        // for all its buffers to be filled before processing it
3643        uint32_t minFrames;
3644        if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3645            minFrames = mNormalFrameCount;
3646        } else {
3647            minFrames = 1;
3648        }
3649        if ((track->framesReady() >= minFrames) && track->isReady() &&
3650                !track->isPaused() && !track->isTerminated())
3651        {
3652            //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
3653
3654            if (track->mFillingUpStatus == Track::FS_FILLED) {
3655                track->mFillingUpStatus = Track::FS_ACTIVE;
3656                mLeftVolFloat = mRightVolFloat = 0;
3657                if (track->mState == TrackBase::RESUMING) {
3658                    track->mState = TrackBase::ACTIVE;
3659                }
3660            }
3661
3662            // compute volume for this track
3663            float left, right;
3664            if (track->isMuted() || mMasterMute || track->isPausing() ||
3665                mStreamTypes[track->streamType()].mute) {
3666                left = right = 0;
3667                if (track->isPausing()) {
3668                    track->setPaused();
3669                }
3670            } else {
3671                float typeVolume = mStreamTypes[track->streamType()].volume;
3672                float v = mMasterVolume * typeVolume;
3673                uint32_t vlr = cblk->getVolumeLR();
3674                float v_clamped = v * (vlr & 0xFFFF);
3675                if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3676                left = v_clamped/MAX_GAIN;
3677                v_clamped = v * (vlr >> 16);
3678                if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3679                right = v_clamped/MAX_GAIN;
3680            }
3681
3682            if (left != mLeftVolFloat || right != mRightVolFloat) {
3683                mLeftVolFloat = left;
3684                mRightVolFloat = right;
3685
3686                // Convert volumes from float to 8.24
3687                uint32_t vl = (uint32_t)(left * (1 << 24));
3688                uint32_t vr = (uint32_t)(right * (1 << 24));
3689
3690                // Delegate volume control to effect in track effect chain if needed
3691                // only one effect chain can be present on DirectOutputThread, so if
3692                // there is one, the track is connected to it
3693                if (!mEffectChains.isEmpty()) {
3694                    // Do not ramp volume if volume is controlled by effect
3695                    mEffectChains[0]->setVolume_l(&vl, &vr);
3696                    left = (float)vl / (1 << 24);
3697                    right = (float)vr / (1 << 24);
3698                }
3699                mOutput->stream->set_volume(mOutput->stream, left, right);
3700            }
3701
3702            // reset retry count
3703            track->mRetryCount = kMaxTrackRetriesDirect;
3704            mActiveTrack = t;
3705            mixerStatus = MIXER_TRACKS_READY;
3706        } else {
3707            // clear effect chain input buffer if an active track underruns to avoid sending
3708            // previous audio buffer again to effects
3709            if (!mEffectChains.isEmpty()) {
3710                mEffectChains[0]->clearInputBuffer();
3711            }
3712
3713            //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3714            if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3715                    track->isStopped() || track->isPaused()) {
3716                // We have consumed all the buffers of this track.
3717                // Remove it from the list of active tracks.
3718                // TODO: implement behavior for compressed audio
3719                size_t audioHALFrames =
3720                        (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3721                size_t framesWritten =
3722                        mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3723                if (track->presentationComplete(framesWritten, audioHALFrames)) {
3724                    if (track->isStopped()) {
3725                        track->reset();
3726                    }
3727                    trackToRemove = track;
3728                }
3729            } else {
3730                // No buffers for this track. Give it a few chances to
3731                // fill a buffer, then remove it from active list.
3732                if (--(track->mRetryCount) <= 0) {
3733                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3734                    trackToRemove = track;
3735                } else {
3736                    mixerStatus = MIXER_TRACKS_ENABLED;
3737                }
3738            }
3739        }
3740    }
3741
3742    // FIXME merge this with similar code for removing multiple tracks
3743    // remove all the tracks that need to be...
3744    if (CC_UNLIKELY(trackToRemove != 0)) {
3745        tracksToRemove->add(trackToRemove);
3746        mActiveTracks.remove(trackToRemove);
3747        if (!mEffectChains.isEmpty()) {
3748            ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
3749                    trackToRemove->sessionId());
3750            mEffectChains[0]->decActiveTrackCnt();
3751        }
3752        if (trackToRemove->isTerminated()) {
3753            removeTrack_l(trackToRemove);
3754        }
3755    }
3756
3757    return mixerStatus;
3758}
3759
3760void AudioFlinger::DirectOutputThread::threadLoop_mix()
3761{
3762    AudioBufferProvider::Buffer buffer;
3763    size_t frameCount = mFrameCount;
3764    int8_t *curBuf = (int8_t *)mMixBuffer;
3765    // output audio to hardware
3766    while (frameCount) {
3767        buffer.frameCount = frameCount;
3768        mActiveTrack->getNextBuffer(&buffer);
3769        if (CC_UNLIKELY(buffer.raw == NULL)) {
3770            memset(curBuf, 0, frameCount * mFrameSize);
3771            break;
3772        }
3773        memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3774        frameCount -= buffer.frameCount;
3775        curBuf += buffer.frameCount * mFrameSize;
3776        mActiveTrack->releaseBuffer(&buffer);
3777    }
3778    sleepTime = 0;
3779    standbyTime = systemTime() + standbyDelay;
3780    mActiveTrack.clear();
3781
3782}
3783
3784void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3785{
3786    if (sleepTime == 0) {
3787        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3788            sleepTime = activeSleepTime;
3789        } else {
3790            sleepTime = idleSleepTime;
3791        }
3792    } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3793        memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3794        sleepTime = 0;
3795    }
3796}
3797
3798// getTrackName_l() must be called with ThreadBase::mLock held
3799int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
3800{
3801    return 0;
3802}
3803
3804// deleteTrackName_l() must be called with ThreadBase::mLock held
3805void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3806{
3807}
3808
3809// checkForNewParameters_l() must be called with ThreadBase::mLock held
3810bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3811{
3812    bool reconfig = false;
3813
3814    while (!mNewParameters.isEmpty()) {
3815        status_t status = NO_ERROR;
3816        String8 keyValuePair = mNewParameters[0];
3817        AudioParameter param = AudioParameter(keyValuePair);
3818        int value;
3819
3820        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3821            // do not accept frame count changes if tracks are open as the track buffer
3822            // size depends on frame count and correct behavior would not be garantied
3823            // if frame count is changed after track creation
3824            if (!mTracks.isEmpty()) {
3825                status = INVALID_OPERATION;
3826            } else {
3827                reconfig = true;
3828            }
3829        }
3830        if (status == NO_ERROR) {
3831            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3832                                                    keyValuePair.string());
3833            if (!mStandby && status == INVALID_OPERATION) {
3834                mOutput->stream->common.standby(&mOutput->stream->common);
3835                mStandby = true;
3836                mBytesWritten = 0;
3837                status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3838                                                       keyValuePair.string());
3839            }
3840            if (status == NO_ERROR && reconfig) {
3841                readOutputParameters();
3842                sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3843            }
3844        }
3845
3846        mNewParameters.removeAt(0);
3847
3848        mParamStatus = status;
3849        mParamCond.signal();
3850        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3851        // already timed out waiting for the status and will never signal the condition.
3852        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3853    }
3854    return reconfig;
3855}
3856
3857uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3858{
3859    uint32_t time;
3860    if (audio_is_linear_pcm(mFormat)) {
3861        time = PlaybackThread::activeSleepTimeUs();
3862    } else {
3863        time = 10000;
3864    }
3865    return time;
3866}
3867
3868uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3869{
3870    uint32_t time;
3871    if (audio_is_linear_pcm(mFormat)) {
3872        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3873    } else {
3874        time = 10000;
3875    }
3876    return time;
3877}
3878
3879uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3880{
3881    uint32_t time;
3882    if (audio_is_linear_pcm(mFormat)) {
3883        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3884    } else {
3885        time = 10000;
3886    }
3887    return time;
3888}
3889
3890void AudioFlinger::DirectOutputThread::cacheParameters_l()
3891{
3892    PlaybackThread::cacheParameters_l();
3893
3894    // use shorter standby delay as on normal output to release
3895    // hardware resources as soon as possible
3896    standbyDelay = microseconds(activeSleepTime*2);
3897}
3898
3899// ----------------------------------------------------------------------------
3900
3901AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
3902        AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
3903    :   MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3904        mWaitTimeMs(UINT_MAX)
3905{
3906    addOutputTrack(mainThread);
3907}
3908
3909AudioFlinger::DuplicatingThread::~DuplicatingThread()
3910{
3911    for (size_t i = 0; i < mOutputTracks.size(); i++) {
3912        mOutputTracks[i]->destroy();
3913    }
3914}
3915
3916void AudioFlinger::DuplicatingThread::threadLoop_mix()
3917{
3918    // mix buffers...
3919    if (outputsReady(outputTracks)) {
3920        mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3921    } else {
3922        memset(mMixBuffer, 0, mixBufferSize);
3923    }
3924    sleepTime = 0;
3925    writeFrames = mNormalFrameCount;
3926    standbyTime = systemTime() + standbyDelay;
3927}
3928
3929void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3930{
3931    if (sleepTime == 0) {
3932        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3933            sleepTime = activeSleepTime;
3934        } else {
3935            sleepTime = idleSleepTime;
3936        }
3937    } else if (mBytesWritten != 0) {
3938        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3939            writeFrames = mNormalFrameCount;
3940            memset(mMixBuffer, 0, mixBufferSize);
3941        } else {
3942            // flush remaining overflow buffers in output tracks
3943            writeFrames = 0;
3944        }
3945        sleepTime = 0;
3946    }
3947}
3948
3949void AudioFlinger::DuplicatingThread::threadLoop_write()
3950{
3951    for (size_t i = 0; i < outputTracks.size(); i++) {
3952        outputTracks[i]->write(mMixBuffer, writeFrames);
3953    }
3954    mBytesWritten += mixBufferSize;
3955}
3956
3957void AudioFlinger::DuplicatingThread::threadLoop_standby()
3958{
3959    // DuplicatingThread implements standby by stopping all tracks
3960    for (size_t i = 0; i < outputTracks.size(); i++) {
3961        outputTracks[i]->stop();
3962    }
3963}
3964
3965void AudioFlinger::DuplicatingThread::saveOutputTracks()
3966{
3967    outputTracks = mOutputTracks;
3968}
3969
3970void AudioFlinger::DuplicatingThread::clearOutputTracks()
3971{
3972    outputTracks.clear();
3973}
3974
3975void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3976{
3977    Mutex::Autolock _l(mLock);
3978    // FIXME explain this formula
3979    int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
3980    OutputTrack *outputTrack = new OutputTrack(thread,
3981                                            this,
3982                                            mSampleRate,
3983                                            mFormat,
3984                                            mChannelMask,
3985                                            frameCount);
3986    if (outputTrack->cblk() != NULL) {
3987        thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
3988        mOutputTracks.add(outputTrack);
3989        ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
3990        updateWaitTime_l();
3991    }
3992}
3993
3994void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3995{
3996    Mutex::Autolock _l(mLock);
3997    for (size_t i = 0; i < mOutputTracks.size(); i++) {
3998        if (mOutputTracks[i]->thread() == thread) {
3999            mOutputTracks[i]->destroy();
4000            mOutputTracks.removeAt(i);
4001            updateWaitTime_l();
4002            return;
4003        }
4004    }
4005    ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4006}
4007
4008// caller must hold mLock
4009void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4010{
4011    mWaitTimeMs = UINT_MAX;
4012    for (size_t i = 0; i < mOutputTracks.size(); i++) {
4013        sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4014        if (strong != 0) {
4015            uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4016            if (waitTimeMs < mWaitTimeMs) {
4017                mWaitTimeMs = waitTimeMs;
4018            }
4019        }
4020    }
4021}
4022
4023
4024bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
4025{
4026    for (size_t i = 0; i < outputTracks.size(); i++) {
4027        sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4028        if (thread == 0) {
4029            ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
4030            return false;
4031        }
4032        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4033        // see note at standby() declaration
4034        if (playbackThread->standby() && !playbackThread->isSuspended()) {
4035            ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
4036            return false;
4037        }
4038    }
4039    return true;
4040}
4041
4042uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4043{
4044    return (mWaitTimeMs * 1000) / 2;
4045}
4046
4047void AudioFlinger::DuplicatingThread::cacheParameters_l()
4048{
4049    // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4050    updateWaitTime_l();
4051
4052    MixerThread::cacheParameters_l();
4053}
4054
4055// ----------------------------------------------------------------------------
4056
4057// TrackBase constructor must be called with AudioFlinger::mLock held
4058AudioFlinger::ThreadBase::TrackBase::TrackBase(
4059            ThreadBase *thread,
4060            const sp<Client>& client,
4061            uint32_t sampleRate,
4062            audio_format_t format,
4063            audio_channel_mask_t channelMask,
4064            int frameCount,
4065            const sp<IMemory>& sharedBuffer,
4066            int sessionId)
4067    :   RefBase(),
4068        mThread(thread),
4069        mClient(client),
4070        mCblk(NULL),
4071        // mBuffer
4072        // mBufferEnd
4073        mFrameCount(0),
4074        mState(IDLE),
4075        mSampleRate(sampleRate),
4076        mFormat(format),
4077        mStepServerFailed(false),
4078        mSessionId(sessionId)
4079        // mChannelCount
4080        // mChannelMask
4081{
4082    ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
4083
4084    // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
4085    size_t size = sizeof(audio_track_cblk_t);
4086    uint8_t channelCount = popcount(channelMask);
4087    size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4088    if (sharedBuffer == 0) {
4089        size += bufferSize;
4090    }
4091
4092    if (client != NULL) {
4093        mCblkMemory = client->heap()->allocate(size);
4094        if (mCblkMemory != 0) {
4095            mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
4096            if (mCblk != NULL) { // construct the shared structure in-place.
4097                new(mCblk) audio_track_cblk_t();
4098                // clear all buffers
4099                mCblk->frameCount = frameCount;
4100                mCblk->sampleRate = sampleRate;
4101// uncomment the following lines to quickly test 32-bit wraparound
4102//                mCblk->user = 0xffff0000;
4103//                mCblk->server = 0xffff0000;
4104//                mCblk->userBase = 0xffff0000;
4105//                mCblk->serverBase = 0xffff0000;
4106                mChannelCount = channelCount;
4107                mChannelMask = channelMask;
4108                if (sharedBuffer == 0) {
4109                    mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4110                    memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4111                    // Force underrun condition to avoid false underrun callback until first data is
4112                    // written to buffer (other flags are cleared)
4113                    mCblk->flags = CBLK_UNDERRUN_ON;
4114                } else {
4115                    mBuffer = sharedBuffer->pointer();
4116                }
4117                mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4118            }
4119        } else {
4120            ALOGE("not enough memory for AudioTrack size=%u", size);
4121            client->heap()->dump("AudioTrack");
4122            return;
4123        }
4124    } else {
4125        mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
4126        // construct the shared structure in-place.
4127        new(mCblk) audio_track_cblk_t();
4128        // clear all buffers
4129        mCblk->frameCount = frameCount;
4130        mCblk->sampleRate = sampleRate;
4131// uncomment the following lines to quickly test 32-bit wraparound
4132//        mCblk->user = 0xffff0000;
4133//        mCblk->server = 0xffff0000;
4134//        mCblk->userBase = 0xffff0000;
4135//        mCblk->serverBase = 0xffff0000;
4136        mChannelCount = channelCount;
4137        mChannelMask = channelMask;
4138        mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4139        memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4140        // Force underrun condition to avoid false underrun callback until first data is
4141        // written to buffer (other flags are cleared)
4142        mCblk->flags = CBLK_UNDERRUN_ON;
4143        mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4144    }
4145}
4146
4147AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4148{
4149    if (mCblk != NULL) {
4150        if (mClient == 0) {
4151            delete mCblk;
4152        } else {
4153            mCblk->~audio_track_cblk_t();   // destroy our shared-structure.
4154        }
4155    }
4156    mCblkMemory.clear();    // free the shared memory before releasing the heap it belongs to
4157    if (mClient != 0) {
4158        // Client destructor must run with AudioFlinger mutex locked
4159        Mutex::Autolock _l(mClient->audioFlinger()->mLock);
4160        // If the client's reference count drops to zero, the associated destructor
4161        // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4162        // relying on the automatic clear() at end of scope.
4163        mClient.clear();
4164    }
4165}
4166
4167// AudioBufferProvider interface
4168// getNextBuffer() = 0;
4169// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
4170void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4171{
4172    buffer->raw = NULL;
4173    mFrameCount = buffer->frameCount;
4174    // FIXME See note at getNextBuffer()
4175    (void) step();      // ignore return value of step()
4176    buffer->frameCount = 0;
4177}
4178
4179bool AudioFlinger::ThreadBase::TrackBase::step() {
4180    bool result;
4181    audio_track_cblk_t* cblk = this->cblk();
4182
4183    result = cblk->stepServer(mFrameCount);
4184    if (!result) {
4185        ALOGV("stepServer failed acquiring cblk mutex");
4186        mStepServerFailed = true;
4187    }
4188    return result;
4189}
4190
4191void AudioFlinger::ThreadBase::TrackBase::reset() {
4192    audio_track_cblk_t* cblk = this->cblk();
4193
4194    cblk->user = 0;
4195    cblk->server = 0;
4196    cblk->userBase = 0;
4197    cblk->serverBase = 0;
4198    mStepServerFailed = false;
4199    ALOGV("TrackBase::reset");
4200}
4201
4202int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4203    return (int)mCblk->sampleRate;
4204}
4205
4206void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4207    audio_track_cblk_t* cblk = this->cblk();
4208    size_t frameSize = cblk->frameSize;
4209    int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4210    int8_t *bufferEnd = bufferStart + frames * frameSize;
4211
4212    // Check validity of returned pointer in case the track control block would have been corrupted.
4213    ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4214            "TrackBase::getBuffer buffer out of range:\n"
4215                "    start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4216                "    server %u, serverBase %u, user %u, userBase %u, frameSize %d",
4217                bufferStart, bufferEnd, mBuffer, mBufferEnd,
4218                cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
4219
4220    return bufferStart;
4221}
4222
4223status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4224{
4225    mSyncEvents.add(event);
4226    return NO_ERROR;
4227}
4228
4229// ----------------------------------------------------------------------------
4230
4231// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4232AudioFlinger::PlaybackThread::Track::Track(
4233            PlaybackThread *thread,
4234            const sp<Client>& client,
4235            audio_stream_type_t streamType,
4236            uint32_t sampleRate,
4237            audio_format_t format,
4238            audio_channel_mask_t channelMask,
4239            int frameCount,
4240            const sp<IMemory>& sharedBuffer,
4241            int sessionId,
4242            IAudioFlinger::track_flags_t flags)
4243    :   TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
4244    mMute(false),
4245    mFillingUpStatus(FS_INVALID),
4246    // mRetryCount initialized later when needed
4247    mSharedBuffer(sharedBuffer),
4248    mStreamType(streamType),
4249    mName(-1),  // see note below
4250    mMainBuffer(thread->mixBuffer()),
4251    mAuxBuffer(NULL),
4252    mAuxEffectId(0), mHasVolumeController(false),
4253    mPresentationCompleteFrames(0),
4254    mFlags(flags),
4255    mFastIndex(-1),
4256    mUnderrunCount(0),
4257    mCachedVolume(1.0)
4258{
4259    if (mCblk != NULL) {
4260        // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4261        // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
4262        mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
4263        // to avoid leaking a track name, do not allocate one unless there is an mCblk
4264        mName = thread->getTrackName_l(channelMask);
4265        mCblk->mName = mName;
4266        if (mName < 0) {
4267            ALOGE("no more track names available");
4268            return;
4269        }
4270        // only allocate a fast track index if we were able to allocate a normal track name
4271        if (flags & IAudioFlinger::TRACK_FAST) {
4272            mCblk->flags |= CBLK_FAST;  // atomic op not needed yet
4273            ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4274            int i = __builtin_ctz(thread->mFastTrackAvailMask);
4275            ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
4276            // FIXME This is too eager.  We allocate a fast track index before the
4277            //       fast track becomes active.  Since fast tracks are a scarce resource,
4278            //       this means we are potentially denying other more important fast tracks from
4279            //       being created.  It would be better to allocate the index dynamically.
4280            mFastIndex = i;
4281            mCblk->mName = i;
4282            // Read the initial underruns because this field is never cleared by the fast mixer
4283            mObservedUnderruns = thread->getFastTrackUnderruns(i);
4284            thread->mFastTrackAvailMask &= ~(1 << i);
4285        }
4286    }
4287    ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
4288}
4289
4290AudioFlinger::PlaybackThread::Track::~Track()
4291{
4292    ALOGV("PlaybackThread::Track destructor");
4293    sp<ThreadBase> thread = mThread.promote();
4294    if (thread != 0) {
4295        Mutex::Autolock _l(thread->mLock);
4296        mState = TERMINATED;
4297    }
4298}
4299
4300void AudioFlinger::PlaybackThread::Track::destroy()
4301{
4302    // NOTE: destroyTrack_l() can remove a strong reference to this Track
4303    // by removing it from mTracks vector, so there is a risk that this Tracks's
4304    // destructor is called. As the destructor needs to lock mLock,
4305    // we must acquire a strong reference on this Track before locking mLock
4306    // here so that the destructor is called only when exiting this function.
4307    // On the other hand, as long as Track::destroy() is only called by
4308    // TrackHandle destructor, the TrackHandle still holds a strong ref on
4309    // this Track with its member mTrack.
4310    sp<Track> keep(this);
4311    { // scope for mLock
4312        sp<ThreadBase> thread = mThread.promote();
4313        if (thread != 0) {
4314            if (!isOutputTrack()) {
4315                if (mState == ACTIVE || mState == RESUMING) {
4316                    AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
4317
4318#ifdef ADD_BATTERY_DATA
4319                    // to track the speaker usage
4320                    addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
4321#endif
4322                }
4323                AudioSystem::releaseOutput(thread->id());
4324            }
4325            Mutex::Autolock _l(thread->mLock);
4326            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4327            playbackThread->destroyTrack_l(this);
4328        }
4329    }
4330}
4331
4332/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4333{
4334    result.append("   Name Client Type Fmt Chn mask   Session mFrCnt fCount S M F SRate  L dB  R dB  "
4335                  "  Server      User     Main buf    Aux Buf  Flags Underruns\n");
4336}
4337
4338void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4339{
4340    uint32_t vlr = mCblk->getVolumeLR();
4341    if (isFastTrack()) {
4342        sprintf(buffer, "   F %2d", mFastIndex);
4343    } else {
4344        sprintf(buffer, "   %4d", mName - AudioMixer::TRACK0);
4345    }
4346    track_state state = mState;
4347    char stateChar;
4348    switch (state) {
4349    case IDLE:
4350        stateChar = 'I';
4351        break;
4352    case TERMINATED:
4353        stateChar = 'T';
4354        break;
4355    case STOPPING_1:
4356        stateChar = 's';
4357        break;
4358    case STOPPING_2:
4359        stateChar = '5';
4360        break;
4361    case STOPPED:
4362        stateChar = 'S';
4363        break;
4364    case RESUMING:
4365        stateChar = 'R';
4366        break;
4367    case ACTIVE:
4368        stateChar = 'A';
4369        break;
4370    case PAUSING:
4371        stateChar = 'p';
4372        break;
4373    case PAUSED:
4374        stateChar = 'P';
4375        break;
4376    case FLUSHED:
4377        stateChar = 'F';
4378        break;
4379    default:
4380        stateChar = '?';
4381        break;
4382    }
4383    char nowInUnderrun;
4384    switch (mObservedUnderruns.mBitFields.mMostRecent) {
4385    case UNDERRUN_FULL:
4386        nowInUnderrun = ' ';
4387        break;
4388    case UNDERRUN_PARTIAL:
4389        nowInUnderrun = '<';
4390        break;
4391    case UNDERRUN_EMPTY:
4392        nowInUnderrun = '*';
4393        break;
4394    default:
4395        nowInUnderrun = '?';
4396        break;
4397    }
4398    snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g  "
4399            "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
4400            (mClient == 0) ? getpid_cached : mClient->pid(),
4401            mStreamType,
4402            mFormat,
4403            mChannelMask,
4404            mSessionId,
4405            mFrameCount,
4406            mCblk->frameCount,
4407            stateChar,
4408            mMute,
4409            mFillingUpStatus,
4410            mCblk->sampleRate,
4411            20.0 * log10((vlr & 0xFFFF) / 4096.0),
4412            20.0 * log10((vlr >> 16) / 4096.0),
4413            mCblk->server,
4414            mCblk->user,
4415            (int)mMainBuffer,
4416            (int)mAuxBuffer,
4417            mCblk->flags,
4418            mUnderrunCount,
4419            nowInUnderrun);
4420}
4421
4422// AudioBufferProvider interface
4423status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
4424        AudioBufferProvider::Buffer* buffer, int64_t pts)
4425{
4426    audio_track_cblk_t* cblk = this->cblk();
4427    uint32_t framesReady;
4428    uint32_t framesReq = buffer->frameCount;
4429
4430    // Check if last stepServer failed, try to step now
4431    if (mStepServerFailed) {
4432        // FIXME When called by fast mixer, this takes a mutex with tryLock().
4433        //       Since the fast mixer is higher priority than client callback thread,
4434        //       it does not result in priority inversion for client.
4435        //       But a non-blocking solution would be preferable to avoid
4436        //       fast mixer being unable to tryLock(), and
4437        //       to avoid the extra context switches if the client wakes up,
4438        //       discovers the mutex is locked, then has to wait for fast mixer to unlock.
4439        if (!step())  goto getNextBuffer_exit;
4440        ALOGV("stepServer recovered");
4441        mStepServerFailed = false;
4442    }
4443
4444    // FIXME Same as above
4445    framesReady = cblk->framesReady();
4446
4447    if (CC_LIKELY(framesReady)) {
4448        uint32_t s = cblk->server;
4449        uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4450
4451        bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4452        if (framesReq > framesReady) {
4453            framesReq = framesReady;
4454        }
4455        if (framesReq > bufferEnd - s) {
4456            framesReq = bufferEnd - s;
4457        }
4458
4459        buffer->raw = getBuffer(s, framesReq);
4460        buffer->frameCount = framesReq;
4461        return NO_ERROR;
4462    }
4463
4464getNextBuffer_exit:
4465    buffer->raw = NULL;
4466    buffer->frameCount = 0;
4467    ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4468    return NOT_ENOUGH_DATA;
4469}
4470
4471// Note that framesReady() takes a mutex on the control block using tryLock().
4472// This could result in priority inversion if framesReady() is called by the normal mixer,
4473// as the normal mixer thread runs at lower
4474// priority than the client's callback thread:  there is a short window within framesReady()
4475// during which the normal mixer could be preempted, and the client callback would block.
4476// Another problem can occur if framesReady() is called by the fast mixer:
4477// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4478// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4479size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
4480    return mCblk->framesReady();
4481}
4482
4483// Don't call for fast tracks; the framesReady() could result in priority inversion
4484bool AudioFlinger::PlaybackThread::Track::isReady() const {
4485    if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
4486
4487    if (framesReady() >= mCblk->frameCount ||
4488            (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4489        mFillingUpStatus = FS_FILLED;
4490        android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4491        return true;
4492    }
4493    return false;
4494}
4495
4496status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
4497                                                    int triggerSession)
4498{
4499    status_t status = NO_ERROR;
4500    ALOGV("start(%d), calling pid %d session %d",
4501            mName, IPCThreadState::self()->getCallingPid(), mSessionId);
4502
4503    sp<ThreadBase> thread = mThread.promote();
4504    if (thread != 0) {
4505        Mutex::Autolock _l(thread->mLock);
4506        track_state state = mState;
4507        // here the track could be either new, or restarted
4508        // in both cases "unstop" the track
4509        if (mState == PAUSED) {
4510            mState = TrackBase::RESUMING;
4511            ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
4512        } else {
4513            mState = TrackBase::ACTIVE;
4514            ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
4515        }
4516
4517        if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4518            thread->mLock.unlock();
4519            status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
4520            thread->mLock.lock();
4521
4522#ifdef ADD_BATTERY_DATA
4523            // to track the speaker usage
4524            if (status == NO_ERROR) {
4525                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4526            }
4527#endif
4528        }
4529        if (status == NO_ERROR) {
4530            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4531            playbackThread->addTrack_l(this);
4532        } else {
4533            mState = state;
4534            triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
4535        }
4536    } else {
4537        status = BAD_VALUE;
4538    }
4539    return status;
4540}
4541
4542void AudioFlinger::PlaybackThread::Track::stop()
4543{
4544    ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
4545    sp<ThreadBase> thread = mThread.promote();
4546    if (thread != 0) {
4547        Mutex::Autolock _l(thread->mLock);
4548        track_state state = mState;
4549        if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
4550            // If the track is not active (PAUSED and buffers full), flush buffers
4551            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4552            if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4553                reset();
4554                mState = STOPPED;
4555            } else if (!isFastTrack()) {
4556                mState = STOPPED;
4557            } else {
4558                // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4559                // and then to STOPPED and reset() when presentation is complete
4560                mState = STOPPING_1;
4561            }
4562            ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
4563        }
4564        if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4565            thread->mLock.unlock();
4566            AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
4567            thread->mLock.lock();
4568
4569#ifdef ADD_BATTERY_DATA
4570            // to track the speaker usage
4571            addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
4572#endif
4573        }
4574    }
4575}
4576
4577void AudioFlinger::PlaybackThread::Track::pause()
4578{
4579    ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
4580    sp<ThreadBase> thread = mThread.promote();
4581    if (thread != 0) {
4582        Mutex::Autolock _l(thread->mLock);
4583        if (mState == ACTIVE || mState == RESUMING) {
4584            mState = PAUSING;
4585            ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
4586            if (!isOutputTrack()) {
4587                thread->mLock.unlock();
4588                AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
4589                thread->mLock.lock();
4590
4591#ifdef ADD_BATTERY_DATA
4592                // to track the speaker usage
4593                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
4594#endif
4595            }
4596        }
4597    }
4598}
4599
4600void AudioFlinger::PlaybackThread::Track::flush()
4601{
4602    ALOGV("flush(%d)", mName);
4603    sp<ThreadBase> thread = mThread.promote();
4604    if (thread != 0) {
4605        Mutex::Autolock _l(thread->mLock);
4606        if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4607                mState != PAUSING) {
4608            return;
4609        }
4610        // No point remaining in PAUSED state after a flush => go to
4611        // FLUSHED state
4612        mState = FLUSHED;
4613        // do not reset the track if it is still in the process of being stopped or paused.
4614        // this will be done by prepareTracks_l() when the track is stopped.
4615        // prepareTracks_l() will see mState == FLUSHED, then
4616        // remove from active track list, reset(), and trigger presentation complete
4617        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4618        if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4619            reset();
4620        }
4621    }
4622}
4623
4624void AudioFlinger::PlaybackThread::Track::reset()
4625{
4626    // Do not reset twice to avoid discarding data written just after a flush and before
4627    // the audioflinger thread detects the track is stopped.
4628    if (!mResetDone) {
4629        TrackBase::reset();
4630        // Force underrun condition to avoid false underrun callback until first data is
4631        // written to buffer
4632        android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4633        android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
4634        mFillingUpStatus = FS_FILLING;
4635        mResetDone = true;
4636        if (mState == FLUSHED) {
4637            mState = IDLE;
4638        }
4639    }
4640}
4641
4642void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4643{
4644    mMute = muted;
4645}
4646
4647status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4648{
4649    status_t status = DEAD_OBJECT;
4650    sp<ThreadBase> thread = mThread.promote();
4651    if (thread != 0) {
4652        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4653        sp<AudioFlinger> af = mClient->audioFlinger();
4654
4655        Mutex::Autolock _l(af->mLock);
4656
4657        sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
4658
4659        if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
4660            Mutex::Autolock _dl(playbackThread->mLock);
4661            Mutex::Autolock _sl(srcThread->mLock);
4662            sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4663            if (chain == 0) {
4664                return INVALID_OPERATION;
4665            }
4666
4667            sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4668            if (effect == 0) {
4669                return INVALID_OPERATION;
4670            }
4671            srcThread->removeEffect_l(effect);
4672            playbackThread->addEffect_l(effect);
4673            // removeEffect_l() has stopped the effect if it was active so it must be restarted
4674            if (effect->state() == EffectModule::ACTIVE ||
4675                    effect->state() == EffectModule::STOPPING) {
4676                effect->start();
4677            }
4678
4679            sp<EffectChain> dstChain = effect->chain().promote();
4680            if (dstChain == 0) {
4681                srcThread->addEffect_l(effect);
4682                return INVALID_OPERATION;
4683            }
4684            AudioSystem::unregisterEffect(effect->id());
4685            AudioSystem::registerEffect(&effect->desc(),
4686                                        srcThread->id(),
4687                                        dstChain->strategy(),
4688                                        AUDIO_SESSION_OUTPUT_MIX,
4689                                        effect->id());
4690        }
4691        status = playbackThread->attachAuxEffect(this, EffectId);
4692    }
4693    return status;
4694}
4695
4696void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4697{
4698    mAuxEffectId = EffectId;
4699    mAuxBuffer = buffer;
4700}
4701
4702bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4703                                                         size_t audioHalFrames)
4704{
4705    // a track is considered presented when the total number of frames written to audio HAL
4706    // corresponds to the number of frames written when presentationComplete() is called for the
4707    // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4708    if (mPresentationCompleteFrames == 0) {
4709        mPresentationCompleteFrames = framesWritten + audioHalFrames;
4710        ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4711                  mPresentationCompleteFrames, audioHalFrames);
4712    }
4713    if (framesWritten >= mPresentationCompleteFrames) {
4714        ALOGV("presentationComplete() session %d complete: framesWritten %d",
4715                  mSessionId, framesWritten);
4716        triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
4717        return true;
4718    }
4719    return false;
4720}
4721
4722void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4723{
4724    for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4725        if (mSyncEvents[i]->type() == type) {
4726            mSyncEvents[i]->trigger();
4727            mSyncEvents.removeAt(i);
4728            i--;
4729        }
4730    }
4731}
4732
4733// implement VolumeBufferProvider interface
4734
4735uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4736{
4737    // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4738    ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4739    uint32_t vlr = mCblk->getVolumeLR();
4740    uint32_t vl = vlr & 0xFFFF;
4741    uint32_t vr = vlr >> 16;
4742    // track volumes come from shared memory, so can't be trusted and must be clamped
4743    if (vl > MAX_GAIN_INT) {
4744        vl = MAX_GAIN_INT;
4745    }
4746    if (vr > MAX_GAIN_INT) {
4747        vr = MAX_GAIN_INT;
4748    }
4749    // now apply the cached master volume and stream type volume;
4750    // this is trusted but lacks any synchronization or barrier so may be stale
4751    float v = mCachedVolume;
4752    vl *= v;
4753    vr *= v;
4754    // re-combine into U4.16
4755    vlr = (vr << 16) | (vl & 0xFFFF);
4756    // FIXME look at mute, pause, and stop flags
4757    return vlr;
4758}
4759
4760status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4761{
4762    if (mState == TERMINATED || mState == PAUSED ||
4763            ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4764                                      (mState == STOPPED)))) {
4765        ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4766              mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4767        event->cancel();
4768        return INVALID_OPERATION;
4769    }
4770    TrackBase::setSyncEvent(event);
4771    return NO_ERROR;
4772}
4773
4774// timed audio tracks
4775
4776sp<AudioFlinger::PlaybackThread::TimedTrack>
4777AudioFlinger::PlaybackThread::TimedTrack::create(
4778            PlaybackThread *thread,
4779            const sp<Client>& client,
4780            audio_stream_type_t streamType,
4781            uint32_t sampleRate,
4782            audio_format_t format,
4783            audio_channel_mask_t channelMask,
4784            int frameCount,
4785            const sp<IMemory>& sharedBuffer,
4786            int sessionId) {
4787    if (!client->reserveTimedTrack())
4788        return 0;
4789
4790    return new TimedTrack(
4791        thread, client, streamType, sampleRate, format, channelMask, frameCount,
4792        sharedBuffer, sessionId);
4793}
4794
4795AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
4796            PlaybackThread *thread,
4797            const sp<Client>& client,
4798            audio_stream_type_t streamType,
4799            uint32_t sampleRate,
4800            audio_format_t format,
4801            audio_channel_mask_t channelMask,
4802            int frameCount,
4803            const sp<IMemory>& sharedBuffer,
4804            int sessionId)
4805    : Track(thread, client, streamType, sampleRate, format, channelMask,
4806            frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
4807      mQueueHeadInFlight(false),
4808      mTrimQueueHeadOnRelease(false),
4809      mFramesPendingInQueue(0),
4810      mTimedSilenceBuffer(NULL),
4811      mTimedSilenceBufferSize(0),
4812      mTimedAudioOutputOnTime(false),
4813      mMediaTimeTransformValid(false)
4814{
4815    LocalClock lc;
4816    mLocalTimeFreq = lc.getLocalFreq();
4817
4818    mLocalTimeToSampleTransform.a_zero = 0;
4819    mLocalTimeToSampleTransform.b_zero = 0;
4820    mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4821    mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4822    LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4823                            &mLocalTimeToSampleTransform.a_to_b_denom);
4824
4825    mMediaTimeToSampleTransform.a_zero = 0;
4826    mMediaTimeToSampleTransform.b_zero = 0;
4827    mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4828    mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4829    LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4830                            &mMediaTimeToSampleTransform.a_to_b_denom);
4831}
4832
4833AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4834    mClient->releaseTimedTrack();
4835    delete [] mTimedSilenceBuffer;
4836}
4837
4838status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4839    size_t size, sp<IMemory>* buffer) {
4840
4841    Mutex::Autolock _l(mTimedBufferQueueLock);
4842
4843    trimTimedBufferQueue_l();
4844
4845    // lazily initialize the shared memory heap for timed buffers
4846    if (mTimedMemoryDealer == NULL) {
4847        const int kTimedBufferHeapSize = 512 << 10;
4848
4849        mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4850                                              "AudioFlingerTimed");
4851        if (mTimedMemoryDealer == NULL)
4852            return NO_MEMORY;
4853    }
4854
4855    sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4856    if (newBuffer == NULL) {
4857        newBuffer = mTimedMemoryDealer->allocate(size);
4858        if (newBuffer == NULL)
4859            return NO_MEMORY;
4860    }
4861
4862    *buffer = newBuffer;
4863    return NO_ERROR;
4864}
4865
4866// caller must hold mTimedBufferQueueLock
4867void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4868    int64_t mediaTimeNow;
4869    {
4870        Mutex::Autolock mttLock(mMediaTimeTransformLock);
4871        if (!mMediaTimeTransformValid)
4872            return;
4873
4874        int64_t targetTimeNow;
4875        status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4876            ? mCCHelper.getCommonTime(&targetTimeNow)
4877            : mCCHelper.getLocalTime(&targetTimeNow);
4878
4879        if (OK != res)
4880            return;
4881
4882        if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4883                                                    &mediaTimeNow)) {
4884            return;
4885        }
4886    }
4887
4888    size_t trimEnd;
4889    for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
4890        int64_t bufEnd;
4891
4892        if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4893            // We have a next buffer.  Just use its PTS as the PTS of the frame
4894            // following the last frame in this buffer.  If the stream is sparse
4895            // (ie, there are deliberate gaps left in the stream which should be
4896            // filled with silence by the TimedAudioTrack), then this can result
4897            // in one extra buffer being left un-trimmed when it could have
4898            // been.  In general, this is not typical, and we would rather
4899            // optimized away the TS calculation below for the more common case
4900            // where PTSes are contiguous.
4901            bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4902        } else {
4903            // We have no next buffer.  Compute the PTS of the frame following
4904            // the last frame in this buffer by computing the duration of of
4905            // this frame in media time units and adding it to the PTS of the
4906            // buffer.
4907            int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4908                               / mCblk->frameSize;
4909
4910            if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4911                                                                &bufEnd)) {
4912                ALOGE("Failed to convert frame count of %lld to media time"
4913                      " duration" " (scale factor %d/%u) in %s",
4914                      frameCount,
4915                      mMediaTimeToSampleTransform.a_to_b_numer,
4916                      mMediaTimeToSampleTransform.a_to_b_denom,
4917                      __PRETTY_FUNCTION__);
4918                break;
4919            }
4920            bufEnd += mTimedBufferQueue[trimEnd].pts();
4921        }
4922
4923        if (bufEnd > mediaTimeNow)
4924            break;
4925
4926        // Is the buffer we want to use in the middle of a mix operation right
4927        // now?  If so, don't actually trim it.  Just wait for the releaseBuffer
4928        // from the mixer which should be coming back shortly.
4929        if (!trimEnd && mQueueHeadInFlight) {
4930            mTrimQueueHeadOnRelease = true;
4931        }
4932    }
4933
4934    size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
4935    if (trimStart < trimEnd) {
4936        // Update the bookkeeping for framesReady()
4937        for (size_t i = trimStart; i < trimEnd; ++i) {
4938            updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4939        }
4940
4941        // Now actually remove the buffers from the queue.
4942        mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
4943    }
4944}
4945
4946void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4947        const char* logTag) {
4948    ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4949                "%s called (reason \"%s\"), but timed buffer queue has no"
4950                " elements to trim.", __FUNCTION__, logTag);
4951
4952    updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4953    mTimedBufferQueue.removeAt(0);
4954}
4955
4956void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4957        const TimedBuffer& buf,
4958        const char* logTag) {
4959    uint32_t bufBytes        = buf.buffer()->size();
4960    uint32_t consumedAlready = buf.position();
4961
4962    ALOG_ASSERT(consumedAlready <= bufBytes,
4963                "Bad bookkeeping while updating frames pending.  Timed buffer is"
4964                " only %u bytes long, but claims to have consumed %u"
4965                " bytes.  (update reason: \"%s\")",
4966                bufBytes, consumedAlready, logTag);
4967
4968    uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
4969    ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4970                "Bad bookkeeping while updating frames pending.  Should have at"
4971                " least %u queued frames, but we think we have only %u.  (update"
4972                " reason: \"%s\")",
4973                bufFrames, mFramesPendingInQueue, logTag);
4974
4975    mFramesPendingInQueue -= bufFrames;
4976}
4977
4978status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4979    const sp<IMemory>& buffer, int64_t pts) {
4980
4981    {
4982        Mutex::Autolock mttLock(mMediaTimeTransformLock);
4983        if (!mMediaTimeTransformValid)
4984            return INVALID_OPERATION;
4985    }
4986
4987    Mutex::Autolock _l(mTimedBufferQueueLock);
4988
4989    uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4990    mFramesPendingInQueue += bufFrames;
4991    mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4992
4993    return NO_ERROR;
4994}
4995
4996status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4997    const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4998
4999    ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5000           xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5001           target);
5002
5003    if (!(target == TimedAudioTrack::LOCAL_TIME ||
5004          target == TimedAudioTrack::COMMON_TIME)) {
5005        return BAD_VALUE;
5006    }
5007
5008    Mutex::Autolock lock(mMediaTimeTransformLock);
5009    mMediaTimeTransform = xform;
5010    mMediaTimeTransformTarget = target;
5011    mMediaTimeTransformValid = true;
5012
5013    return NO_ERROR;
5014}
5015
5016#define min(a, b) ((a) < (b) ? (a) : (b))
5017
5018// implementation of getNextBuffer for tracks whose buffers have timestamps
5019status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5020    AudioBufferProvider::Buffer* buffer, int64_t pts)
5021{
5022    if (pts == AudioBufferProvider::kInvalidPTS) {
5023        buffer->raw = NULL;
5024        buffer->frameCount = 0;
5025        mTimedAudioOutputOnTime = false;
5026        return INVALID_OPERATION;
5027    }
5028
5029    Mutex::Autolock _l(mTimedBufferQueueLock);
5030
5031    ALOG_ASSERT(!mQueueHeadInFlight,
5032                "getNextBuffer called without releaseBuffer!");
5033
5034    while (true) {
5035
5036        // if we have no timed buffers, then fail
5037        if (mTimedBufferQueue.isEmpty()) {
5038            buffer->raw = NULL;
5039            buffer->frameCount = 0;
5040            return NOT_ENOUGH_DATA;
5041        }
5042
5043        TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5044
5045        // calculate the PTS of the head of the timed buffer queue expressed in
5046        // local time
5047        int64_t headLocalPTS;
5048        {
5049            Mutex::Autolock mttLock(mMediaTimeTransformLock);
5050
5051            ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
5052
5053            if (mMediaTimeTransform.a_to_b_denom == 0) {
5054                // the transform represents a pause, so yield silence
5055                timedYieldSilence_l(buffer->frameCount, buffer);
5056                return NO_ERROR;
5057            }
5058
5059            int64_t transformedPTS;
5060            if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5061                                                        &transformedPTS)) {
5062                // the transform failed.  this shouldn't happen, but if it does
5063                // then just drop this buffer
5064                ALOGW("timedGetNextBuffer transform failed");
5065                buffer->raw = NULL;
5066                buffer->frameCount = 0;
5067                trimTimedBufferQueueHead_l("getNextBuffer; no transform");
5068                return NO_ERROR;
5069            }
5070
5071            if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5072                if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5073                                                          &headLocalPTS)) {
5074                    buffer->raw = NULL;
5075                    buffer->frameCount = 0;
5076                    return INVALID_OPERATION;
5077                }
5078            } else {
5079                headLocalPTS = transformedPTS;
5080            }
5081        }
5082
5083        // adjust the head buffer's PTS to reflect the portion of the head buffer
5084        // that has already been consumed
5085        int64_t effectivePTS = headLocalPTS +
5086                ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5087
5088        // Calculate the delta in samples between the head of the input buffer
5089        // queue and the start of the next output buffer that will be written.
5090        // If the transformation fails because of over or underflow, it means
5091        // that the sample's position in the output stream is so far out of
5092        // whack that it should just be dropped.
5093        int64_t sampleDelta;
5094        if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5095            ALOGV("*** head buffer is too far from PTS: dropped buffer");
5096            trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5097                                       " mix");
5098            continue;
5099        }
5100        if (!mLocalTimeToSampleTransform.doForwardTransform(
5101                (effectivePTS - pts) << 32, &sampleDelta)) {
5102            ALOGV("*** too late during sample rate transform: dropped buffer");
5103            trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
5104            continue;
5105        }
5106
5107        ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5108               " sampleDelta=[%d.%08x]",
5109               head.pts(), head.position(), pts,
5110               static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5111                   + (sampleDelta >> 32)),
5112               static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
5113
5114        // if the delta between the ideal placement for the next input sample and
5115        // the current output position is within this threshold, then we will
5116        // concatenate the next input samples to the previous output
5117        const int64_t kSampleContinuityThreshold =
5118                (static_cast<int64_t>(sampleRate()) << 32) / 250;
5119
5120        // if this is the first buffer of audio that we're emitting from this track
5121        // then it should be almost exactly on time.
5122        const int64_t kSampleStartupThreshold = 1LL << 32;
5123
5124        if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
5125           (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
5126            // the next input is close enough to being on time, so concatenate it
5127            // with the last output
5128            timedYieldSamples_l(buffer);
5129
5130            ALOGVV("*** on time: head.pos=%d frameCount=%u",
5131                    head.position(), buffer->frameCount);
5132            return NO_ERROR;
5133        }
5134
5135        // Looks like our output is not on time.  Reset our on timed status.
5136        // Next time we mix samples from our input queue, then should be within
5137        // the StartupThreshold.
5138        mTimedAudioOutputOnTime = false;
5139        if (sampleDelta > 0) {
5140            // the gap between the current output position and the proper start of
5141            // the next input sample is too big, so fill it with silence
5142            uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5143
5144            timedYieldSilence_l(framesUntilNextInput, buffer);
5145            ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5146            return NO_ERROR;
5147        } else {
5148            // the next input sample is late
5149            uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5150            size_t onTimeSamplePosition =
5151                    head.position() + lateFrames * mCblk->frameSize;
5152
5153            if (onTimeSamplePosition > head.buffer()->size()) {
5154                // all the remaining samples in the head are too late, so
5155                // drop it and move on
5156                ALOGV("*** too late: dropped buffer");
5157                trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
5158                continue;
5159            } else {
5160                // skip over the late samples
5161                head.setPosition(onTimeSamplePosition);
5162
5163                // yield the available samples
5164                timedYieldSamples_l(buffer);
5165
5166                ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5167                return NO_ERROR;
5168            }
5169        }
5170    }
5171}
5172
5173// Yield samples from the timed buffer queue head up to the given output
5174// buffer's capacity.
5175//
5176// Caller must hold mTimedBufferQueueLock
5177void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
5178    AudioBufferProvider::Buffer* buffer) {
5179
5180    const TimedBuffer& head = mTimedBufferQueue[0];
5181
5182    buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5183                   head.position());
5184
5185    uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5186                                 mCblk->frameSize);
5187    size_t framesRequested = buffer->frameCount;
5188    buffer->frameCount = min(framesLeftInHead, framesRequested);
5189
5190    mQueueHeadInFlight = true;
5191    mTimedAudioOutputOnTime = true;
5192}
5193
5194// Yield samples of silence up to the given output buffer's capacity
5195//
5196// Caller must hold mTimedBufferQueueLock
5197void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
5198    uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5199
5200    // lazily allocate a buffer filled with silence
5201    if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5202        delete [] mTimedSilenceBuffer;
5203        mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5204        mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5205        memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5206    }
5207
5208    buffer->raw = mTimedSilenceBuffer;
5209    size_t framesRequested = buffer->frameCount;
5210    buffer->frameCount = min(numFrames, framesRequested);
5211
5212    mTimedAudioOutputOnTime = false;
5213}
5214
5215// AudioBufferProvider interface
5216void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5217    AudioBufferProvider::Buffer* buffer) {
5218
5219    Mutex::Autolock _l(mTimedBufferQueueLock);
5220
5221    // If the buffer which was just released is part of the buffer at the head
5222    // of the queue, be sure to update the amt of the buffer which has been
5223    // consumed.  If the buffer being returned is not part of the head of the
5224    // queue, its either because the buffer is part of the silence buffer, or
5225    // because the head of the timed queue was trimmed after the mixer called
5226    // getNextBuffer but before the mixer called releaseBuffer.
5227    if (buffer->raw == mTimedSilenceBuffer) {
5228        ALOG_ASSERT(!mQueueHeadInFlight,
5229                    "Queue head in flight during release of silence buffer!");
5230        goto done;
5231    }
5232
5233    ALOG_ASSERT(mQueueHeadInFlight,
5234                "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5235                " head in flight.");
5236
5237    if (mTimedBufferQueue.size()) {
5238        TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5239
5240        void* start = head.buffer()->pointer();
5241        void* end   = reinterpret_cast<void*>(
5242                        reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5243                        + head.buffer()->size());
5244
5245        ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5246                    "released buffer not within the head of the timed buffer"
5247                    " queue; qHead = [%p, %p], released buffer = %p",
5248                    start, end, buffer->raw);
5249
5250        head.setPosition(head.position() +
5251                (buffer->frameCount * mCblk->frameSize));
5252        mQueueHeadInFlight = false;
5253
5254        ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5255                    "Bad bookkeeping during releaseBuffer!  Should have at"
5256                    " least %u queued frames, but we think we have only %u",
5257                    buffer->frameCount, mFramesPendingInQueue);
5258
5259        mFramesPendingInQueue -= buffer->frameCount;
5260
5261        if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5262            || mTrimQueueHeadOnRelease) {
5263            trimTimedBufferQueueHead_l("releaseBuffer");
5264            mTrimQueueHeadOnRelease = false;
5265        }
5266    } else {
5267        LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5268                  " buffers in the timed buffer queue");
5269    }
5270
5271done:
5272    buffer->raw = 0;
5273    buffer->frameCount = 0;
5274}
5275
5276size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
5277    Mutex::Autolock _l(mTimedBufferQueueLock);
5278    return mFramesPendingInQueue;
5279}
5280
5281AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5282        : mPTS(0), mPosition(0) {}
5283
5284AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5285    const sp<IMemory>& buffer, int64_t pts)
5286        : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5287
5288// ----------------------------------------------------------------------------
5289
5290// RecordTrack constructor must be called with AudioFlinger::mLock held
5291AudioFlinger::RecordThread::RecordTrack::RecordTrack(
5292            RecordThread *thread,
5293            const sp<Client>& client,
5294            uint32_t sampleRate,
5295            audio_format_t format,
5296            audio_channel_mask_t channelMask,
5297            int frameCount,
5298            int sessionId)
5299    :   TrackBase(thread, client, sampleRate, format,
5300                  channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
5301        mOverflow(false)
5302{
5303    if (mCblk != NULL) {
5304        ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5305        if (format == AUDIO_FORMAT_PCM_16_BIT) {
5306            mCblk->frameSize = mChannelCount * sizeof(int16_t);
5307        } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5308            mCblk->frameSize = mChannelCount * sizeof(int8_t);
5309        } else {
5310            mCblk->frameSize = sizeof(int8_t);
5311        }
5312    }
5313}
5314
5315AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5316{
5317    sp<ThreadBase> thread = mThread.promote();
5318    if (thread != 0) {
5319        AudioSystem::releaseInput(thread->id());
5320    }
5321}
5322
5323// AudioBufferProvider interface
5324status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
5325{
5326    audio_track_cblk_t* cblk = this->cblk();
5327    uint32_t framesAvail;
5328    uint32_t framesReq = buffer->frameCount;
5329
5330    // Check if last stepServer failed, try to step now
5331    if (mStepServerFailed) {
5332        if (!step()) goto getNextBuffer_exit;
5333        ALOGV("stepServer recovered");
5334        mStepServerFailed = false;
5335    }
5336
5337    framesAvail = cblk->framesAvailable_l();
5338
5339    if (CC_LIKELY(framesAvail)) {
5340        uint32_t s = cblk->server;
5341        uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5342
5343        if (framesReq > framesAvail) {
5344            framesReq = framesAvail;
5345        }
5346        if (framesReq > bufferEnd - s) {
5347            framesReq = bufferEnd - s;
5348        }
5349
5350        buffer->raw = getBuffer(s, framesReq);
5351        buffer->frameCount = framesReq;
5352        return NO_ERROR;
5353    }
5354
5355getNextBuffer_exit:
5356    buffer->raw = NULL;
5357    buffer->frameCount = 0;
5358    return NOT_ENOUGH_DATA;
5359}
5360
5361status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
5362                                                        int triggerSession)
5363{
5364    sp<ThreadBase> thread = mThread.promote();
5365    if (thread != 0) {
5366        RecordThread *recordThread = (RecordThread *)thread.get();
5367        return recordThread->start(this, event, triggerSession);
5368    } else {
5369        return BAD_VALUE;
5370    }
5371}
5372
5373void AudioFlinger::RecordThread::RecordTrack::stop()
5374{
5375    sp<ThreadBase> thread = mThread.promote();
5376    if (thread != 0) {
5377        RecordThread *recordThread = (RecordThread *)thread.get();
5378        recordThread->stop(this);
5379        TrackBase::reset();
5380        // Force overrun condition to avoid false overrun callback until first data is
5381        // read from buffer
5382        android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5383    }
5384}
5385
5386void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5387{
5388    snprintf(buffer, size, "   %05d %03u 0x%08x %05d   %04u %01d %05u  %08x %08x\n",
5389            (mClient == 0) ? getpid_cached : mClient->pid(),
5390            mFormat,
5391            mChannelMask,
5392            mSessionId,
5393            mFrameCount,
5394            mState,
5395            mCblk->sampleRate,
5396            mCblk->server,
5397            mCblk->user);
5398}
5399
5400
5401// ----------------------------------------------------------------------------
5402
5403AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
5404            PlaybackThread *playbackThread,
5405            DuplicatingThread *sourceThread,
5406            uint32_t sampleRate,
5407            audio_format_t format,
5408            audio_channel_mask_t channelMask,
5409            int frameCount)
5410    :   Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5411                NULL, 0, IAudioFlinger::TRACK_DEFAULT),
5412    mActive(false), mSourceThread(sourceThread)
5413{
5414
5415    if (mCblk != NULL) {
5416        mCblk->flags |= CBLK_DIRECTION_OUT;
5417        mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
5418        mOutBuffer.frameCount = 0;
5419        playbackThread->mTracks.add(this);
5420        ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
5421                "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5422                mCblk, mBuffer, mCblk->buffers,
5423                mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
5424    } else {
5425        ALOGW("Error creating output track on thread %p", playbackThread);
5426    }
5427}
5428
5429AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5430{
5431    clearBufferQueue();
5432}
5433
5434status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
5435                                                          int triggerSession)
5436{
5437    status_t status = Track::start(event, triggerSession);
5438    if (status != NO_ERROR) {
5439        return status;
5440    }
5441
5442    mActive = true;
5443    mRetryCount = 127;
5444    return status;
5445}
5446
5447void AudioFlinger::PlaybackThread::OutputTrack::stop()
5448{
5449    Track::stop();
5450    clearBufferQueue();
5451    mOutBuffer.frameCount = 0;
5452    mActive = false;
5453}
5454
5455bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5456{
5457    Buffer *pInBuffer;
5458    Buffer inBuffer;
5459    uint32_t channelCount = mChannelCount;
5460    bool outputBufferFull = false;
5461    inBuffer.frameCount = frames;
5462    inBuffer.i16 = data;
5463
5464    uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5465
5466    if (!mActive && frames != 0) {
5467        start();
5468        sp<ThreadBase> thread = mThread.promote();
5469        if (thread != 0) {
5470            MixerThread *mixerThread = (MixerThread *)thread.get();
5471            if (mCblk->frameCount > frames){
5472                if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5473                    uint32_t startFrames = (mCblk->frameCount - frames);
5474                    pInBuffer = new Buffer;
5475                    pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5476                    pInBuffer->frameCount = startFrames;
5477                    pInBuffer->i16 = pInBuffer->mBuffer;
5478                    memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5479                    mBufferQueue.add(pInBuffer);
5480                } else {
5481                    ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
5482                }
5483            }
5484        }
5485    }
5486
5487    while (waitTimeLeftMs) {
5488        // First write pending buffers, then new data
5489        if (mBufferQueue.size()) {
5490            pInBuffer = mBufferQueue.itemAt(0);
5491        } else {
5492            pInBuffer = &inBuffer;
5493        }
5494
5495        if (pInBuffer->frameCount == 0) {
5496            break;
5497        }
5498
5499        if (mOutBuffer.frameCount == 0) {
5500            mOutBuffer.frameCount = pInBuffer->frameCount;
5501            nsecs_t startTime = systemTime();
5502            if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
5503                ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
5504                outputBufferFull = true;
5505                break;
5506            }
5507            uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5508            if (waitTimeLeftMs >= waitTimeMs) {
5509                waitTimeLeftMs -= waitTimeMs;
5510            } else {
5511                waitTimeLeftMs = 0;
5512            }
5513        }
5514
5515        uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5516        memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5517        mCblk->stepUser(outFrames);
5518        pInBuffer->frameCount -= outFrames;
5519        pInBuffer->i16 += outFrames * channelCount;
5520        mOutBuffer.frameCount -= outFrames;
5521        mOutBuffer.i16 += outFrames * channelCount;
5522
5523        if (pInBuffer->frameCount == 0) {
5524            if (mBufferQueue.size()) {
5525                mBufferQueue.removeAt(0);
5526                delete [] pInBuffer->mBuffer;
5527                delete pInBuffer;
5528                ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
5529            } else {
5530                break;
5531            }
5532        }
5533    }
5534
5535    // If we could not write all frames, allocate a buffer and queue it for next time.
5536    if (inBuffer.frameCount) {
5537        sp<ThreadBase> thread = mThread.promote();
5538        if (thread != 0 && !thread->standby()) {
5539            if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5540                pInBuffer = new Buffer;
5541                pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5542                pInBuffer->frameCount = inBuffer.frameCount;
5543                pInBuffer->i16 = pInBuffer->mBuffer;
5544                memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5545                mBufferQueue.add(pInBuffer);
5546                ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
5547            } else {
5548                ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
5549            }
5550        }
5551    }
5552
5553    // Calling write() with a 0 length buffer, means that no more data will be written:
5554    // If no more buffers are pending, fill output track buffer to make sure it is started
5555    // by output mixer.
5556    if (frames == 0 && mBufferQueue.size() == 0) {
5557        if (mCblk->user < mCblk->frameCount) {
5558            frames = mCblk->frameCount - mCblk->user;
5559            pInBuffer = new Buffer;
5560            pInBuffer->mBuffer = new int16_t[frames * channelCount];
5561            pInBuffer->frameCount = frames;
5562            pInBuffer->i16 = pInBuffer->mBuffer;
5563            memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5564            mBufferQueue.add(pInBuffer);
5565        } else if (mActive) {
5566            stop();
5567        }
5568    }
5569
5570    return outputBufferFull;
5571}
5572
5573status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5574{
5575    int active;
5576    status_t result;
5577    audio_track_cblk_t* cblk = mCblk;
5578    uint32_t framesReq = buffer->frameCount;
5579
5580//    ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
5581    buffer->frameCount  = 0;
5582
5583    uint32_t framesAvail = cblk->framesAvailable();
5584
5585
5586    if (framesAvail == 0) {
5587        Mutex::Autolock _l(cblk->lock);
5588        goto start_loop_here;
5589        while (framesAvail == 0) {
5590            active = mActive;
5591            if (CC_UNLIKELY(!active)) {
5592                ALOGV("Not active and NO_MORE_BUFFERS");
5593                return NO_MORE_BUFFERS;
5594            }
5595            result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5596            if (result != NO_ERROR) {
5597                return NO_MORE_BUFFERS;
5598            }
5599            // read the server count again
5600        start_loop_here:
5601            framesAvail = cblk->framesAvailable_l();
5602        }
5603    }
5604
5605//    if (framesAvail < framesReq) {
5606//        return NO_MORE_BUFFERS;
5607//    }
5608
5609    if (framesReq > framesAvail) {
5610        framesReq = framesAvail;
5611    }
5612
5613    uint32_t u = cblk->user;
5614    uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5615
5616    if (framesReq > bufferEnd - u) {
5617        framesReq = bufferEnd - u;
5618    }
5619
5620    buffer->frameCount  = framesReq;
5621    buffer->raw         = (void *)cblk->buffer(u);
5622    return NO_ERROR;
5623}
5624
5625
5626void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5627{
5628    size_t size = mBufferQueue.size();
5629
5630    for (size_t i = 0; i < size; i++) {
5631        Buffer *pBuffer = mBufferQueue.itemAt(i);
5632        delete [] pBuffer->mBuffer;
5633        delete pBuffer;
5634    }
5635    mBufferQueue.clear();
5636}
5637
5638// ----------------------------------------------------------------------------
5639
5640AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5641    :   RefBase(),
5642        mAudioFlinger(audioFlinger),
5643        // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
5644        mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
5645        mPid(pid),
5646        mTimedTrackCount(0)
5647{
5648    // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5649}
5650
5651// Client destructor must be called with AudioFlinger::mLock held
5652AudioFlinger::Client::~Client()
5653{
5654    mAudioFlinger->removeClient_l(mPid);
5655}
5656
5657sp<MemoryDealer> AudioFlinger::Client::heap() const
5658{
5659    return mMemoryDealer;
5660}
5661
5662// Reserve one of the limited slots for a timed audio track associated
5663// with this client
5664bool AudioFlinger::Client::reserveTimedTrack()
5665{
5666    const int kMaxTimedTracksPerClient = 4;
5667
5668    Mutex::Autolock _l(mTimedTrackLock);
5669
5670    if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5671        ALOGW("can not create timed track - pid %d has exceeded the limit",
5672             mPid);
5673        return false;
5674    }
5675
5676    mTimedTrackCount++;
5677    return true;
5678}
5679
5680// Release a slot for a timed audio track
5681void AudioFlinger::Client::releaseTimedTrack()
5682{
5683    Mutex::Autolock _l(mTimedTrackLock);
5684    mTimedTrackCount--;
5685}
5686
5687// ----------------------------------------------------------------------------
5688
5689AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5690                                                     const sp<IAudioFlingerClient>& client,
5691                                                     pid_t pid)
5692    : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
5693{
5694}
5695
5696AudioFlinger::NotificationClient::~NotificationClient()
5697{
5698}
5699
5700void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5701{
5702    sp<NotificationClient> keep(this);
5703    mAudioFlinger->removeNotificationClient(mPid);
5704}
5705
5706// ----------------------------------------------------------------------------
5707
5708AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5709    : BnAudioTrack(),
5710      mTrack(track)
5711{
5712}
5713
5714AudioFlinger::TrackHandle::~TrackHandle() {
5715    // just stop the track on deletion, associated resources
5716    // will be freed from the main thread once all pending buffers have
5717    // been played. Unless it's not in the active track list, in which
5718    // case we free everything now...
5719    mTrack->destroy();
5720}
5721
5722sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5723    return mTrack->getCblk();
5724}
5725
5726status_t AudioFlinger::TrackHandle::start() {
5727    return mTrack->start();
5728}
5729
5730void AudioFlinger::TrackHandle::stop() {
5731    mTrack->stop();
5732}
5733
5734void AudioFlinger::TrackHandle::flush() {
5735    mTrack->flush();
5736}
5737
5738void AudioFlinger::TrackHandle::mute(bool e) {
5739    mTrack->mute(e);
5740}
5741
5742void AudioFlinger::TrackHandle::pause() {
5743    mTrack->pause();
5744}
5745
5746status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5747{
5748    return mTrack->attachAuxEffect(EffectId);
5749}
5750
5751status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5752                                                         sp<IMemory>* buffer) {
5753    if (!mTrack->isTimedTrack())
5754        return INVALID_OPERATION;
5755
5756    PlaybackThread::TimedTrack* tt =
5757            reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5758    return tt->allocateTimedBuffer(size, buffer);
5759}
5760
5761status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5762                                                     int64_t pts) {
5763    if (!mTrack->isTimedTrack())
5764        return INVALID_OPERATION;
5765
5766    PlaybackThread::TimedTrack* tt =
5767            reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5768    return tt->queueTimedBuffer(buffer, pts);
5769}
5770
5771status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5772    const LinearTransform& xform, int target) {
5773
5774    if (!mTrack->isTimedTrack())
5775        return INVALID_OPERATION;
5776
5777    PlaybackThread::TimedTrack* tt =
5778            reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5779    return tt->setMediaTimeTransform(
5780        xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5781}
5782
5783status_t AudioFlinger::TrackHandle::onTransact(
5784    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5785{
5786    return BnAudioTrack::onTransact(code, data, reply, flags);
5787}
5788
5789// ----------------------------------------------------------------------------
5790
5791sp<IAudioRecord> AudioFlinger::openRecord(
5792        pid_t pid,
5793        audio_io_handle_t input,
5794        uint32_t sampleRate,
5795        audio_format_t format,
5796        audio_channel_mask_t channelMask,
5797        int frameCount,
5798        IAudioFlinger::track_flags_t flags,
5799        pid_t tid,
5800        int *sessionId,
5801        status_t *status)
5802{
5803    sp<RecordThread::RecordTrack> recordTrack;
5804    sp<RecordHandle> recordHandle;
5805    sp<Client> client;
5806    status_t lStatus;
5807    RecordThread *thread;
5808    size_t inFrameCount;
5809    int lSessionId;
5810
5811    // check calling permissions
5812    if (!recordingAllowed()) {
5813        lStatus = PERMISSION_DENIED;
5814        goto Exit;
5815    }
5816
5817    // add client to list
5818    { // scope for mLock
5819        Mutex::Autolock _l(mLock);
5820        thread = checkRecordThread_l(input);
5821        if (thread == NULL) {
5822            lStatus = BAD_VALUE;
5823            goto Exit;
5824        }
5825
5826        client = registerPid_l(pid);
5827
5828        // If no audio session id is provided, create one here
5829        if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
5830            lSessionId = *sessionId;
5831        } else {
5832            lSessionId = nextUniqueId();
5833            if (sessionId != NULL) {
5834                *sessionId = lSessionId;
5835            }
5836        }
5837        // create new record track. The record track uses one track in mHardwareMixerThread by convention.
5838        recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5839                                                  frameCount, lSessionId, flags, tid, &lStatus);
5840    }
5841    if (lStatus != NO_ERROR) {
5842        // remove local strong reference to Client before deleting the RecordTrack so that the Client
5843        // destructor is called by the TrackBase destructor with mLock held
5844        client.clear();
5845        recordTrack.clear();
5846        goto Exit;
5847    }
5848
5849    // return to handle to client
5850    recordHandle = new RecordHandle(recordTrack);
5851    lStatus = NO_ERROR;
5852
5853Exit:
5854    if (status) {
5855        *status = lStatus;
5856    }
5857    return recordHandle;
5858}
5859
5860// ----------------------------------------------------------------------------
5861
5862AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5863    : BnAudioRecord(),
5864    mRecordTrack(recordTrack)
5865{
5866}
5867
5868AudioFlinger::RecordHandle::~RecordHandle() {
5869    stop_nonvirtual();
5870}
5871
5872sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5873    return mRecordTrack->getCblk();
5874}
5875
5876status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
5877    ALOGV("RecordHandle::start()");
5878    return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
5879}
5880
5881void AudioFlinger::RecordHandle::stop() {
5882    stop_nonvirtual();
5883}
5884
5885void AudioFlinger::RecordHandle::stop_nonvirtual() {
5886    ALOGV("RecordHandle::stop()");
5887    mRecordTrack->stop();
5888}
5889
5890status_t AudioFlinger::RecordHandle::onTransact(
5891    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5892{
5893    return BnAudioRecord::onTransact(code, data, reply, flags);
5894}
5895
5896// ----------------------------------------------------------------------------
5897
5898AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5899                                         AudioStreamIn *input,
5900                                         uint32_t sampleRate,
5901                                         audio_channel_mask_t channelMask,
5902                                         audio_io_handle_t id,
5903                                         uint32_t device) :
5904    ThreadBase(audioFlinger, id, device, RECORD),
5905    mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5906    // mRsmpInIndex and mInputBytes set by readInputParameters()
5907    mReqChannelCount(popcount(channelMask)),
5908    mReqSampleRate(sampleRate)
5909    // mBytesRead is only meaningful while active, and so is cleared in start()
5910    // (but might be better to also clear here for dump?)
5911{
5912    snprintf(mName, kNameLength, "AudioIn_%X", id);
5913
5914    readInputParameters();
5915}
5916
5917
5918AudioFlinger::RecordThread::~RecordThread()
5919{
5920    delete[] mRsmpInBuffer;
5921    delete mResampler;
5922    delete[] mRsmpOutBuffer;
5923}
5924
5925void AudioFlinger::RecordThread::onFirstRef()
5926{
5927    run(mName, PRIORITY_URGENT_AUDIO);
5928}
5929
5930status_t AudioFlinger::RecordThread::readyToRun()
5931{
5932    status_t status = initCheck();
5933    ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
5934    return status;
5935}
5936
5937bool AudioFlinger::RecordThread::threadLoop()
5938{
5939    AudioBufferProvider::Buffer buffer;
5940    sp<RecordTrack> activeTrack;
5941    Vector< sp<EffectChain> > effectChains;
5942
5943    nsecs_t lastWarning = 0;
5944
5945    acquireWakeLock();
5946
5947    // start recording
5948    while (!exitPending()) {
5949
5950        processConfigEvents();
5951
5952        { // scope for mLock
5953            Mutex::Autolock _l(mLock);
5954            checkForNewParameters_l();
5955            if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5956                if (!mStandby) {
5957                    mInput->stream->common.standby(&mInput->stream->common);
5958                    mStandby = true;
5959                }
5960
5961                if (exitPending()) break;
5962
5963                releaseWakeLock_l();
5964                ALOGV("RecordThread: loop stopping");
5965                // go to sleep
5966                mWaitWorkCV.wait(mLock);
5967                ALOGV("RecordThread: loop starting");
5968                acquireWakeLock_l();
5969                continue;
5970            }
5971            if (mActiveTrack != 0) {
5972                if (mActiveTrack->mState == TrackBase::PAUSING) {
5973                    if (!mStandby) {
5974                        mInput->stream->common.standby(&mInput->stream->common);
5975                        mStandby = true;
5976                    }
5977                    mActiveTrack.clear();
5978                    mStartStopCond.broadcast();
5979                } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5980                    if (mReqChannelCount != mActiveTrack->channelCount()) {
5981                        mActiveTrack.clear();
5982                        mStartStopCond.broadcast();
5983                    } else if (mBytesRead != 0) {
5984                        // record start succeeds only if first read from audio input
5985                        // succeeds
5986                        if (mBytesRead > 0) {
5987                            mActiveTrack->mState = TrackBase::ACTIVE;
5988                        } else {
5989                            mActiveTrack.clear();
5990                        }
5991                        mStartStopCond.broadcast();
5992                    }
5993                    mStandby = false;
5994                }
5995            }
5996            lockEffectChains_l(effectChains);
5997        }
5998
5999        if (mActiveTrack != 0) {
6000            if (mActiveTrack->mState != TrackBase::ACTIVE &&
6001                mActiveTrack->mState != TrackBase::RESUMING) {
6002                unlockEffectChains(effectChains);
6003                usleep(kRecordThreadSleepUs);
6004                continue;
6005            }
6006            for (size_t i = 0; i < effectChains.size(); i ++) {
6007                effectChains[i]->process_l();
6008            }
6009
6010            buffer.frameCount = mFrameCount;
6011            if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
6012                size_t framesOut = buffer.frameCount;
6013                if (mResampler == NULL) {
6014                    // no resampling
6015                    while (framesOut) {
6016                        size_t framesIn = mFrameCount - mRsmpInIndex;
6017                        if (framesIn) {
6018                            int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6019                            int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6020                            if (framesIn > framesOut)
6021                                framesIn = framesOut;
6022                            mRsmpInIndex += framesIn;
6023                            framesOut -= framesIn;
6024                            if ((int)mChannelCount == mReqChannelCount ||
6025                                mFormat != AUDIO_FORMAT_PCM_16_BIT) {
6026                                memcpy(dst, src, framesIn * mFrameSize);
6027                            } else {
6028                                int16_t *src16 = (int16_t *)src;
6029                                int16_t *dst16 = (int16_t *)dst;
6030                                if (mChannelCount == 1) {
6031                                    while (framesIn--) {
6032                                        *dst16++ = *src16;
6033                                        *dst16++ = *src16++;
6034                                    }
6035                                } else {
6036                                    while (framesIn--) {
6037                                        *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
6038                                        src16 += 2;
6039                                    }
6040                                }
6041                            }
6042                        }
6043                        if (framesOut && mFrameCount == mRsmpInIndex) {
6044                            if (framesOut == mFrameCount &&
6045                                ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
6046                                mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
6047                                framesOut = 0;
6048                            } else {
6049                                mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
6050                                mRsmpInIndex = 0;
6051                            }
6052                            if (mBytesRead < 0) {
6053                                ALOGE("Error reading audio input");
6054                                if (mActiveTrack->mState == TrackBase::ACTIVE) {
6055                                    // Force input into standby so that it tries to
6056                                    // recover at next read attempt
6057                                    mInput->stream->common.standby(&mInput->stream->common);
6058                                    usleep(kRecordThreadSleepUs);
6059                                }
6060                                mRsmpInIndex = mFrameCount;
6061                                framesOut = 0;
6062                                buffer.frameCount = 0;
6063                            }
6064                        }
6065                    }
6066                } else {
6067                    // resampling
6068
6069                    memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6070                    // alter output frame count as if we were expecting stereo samples
6071                    if (mChannelCount == 1 && mReqChannelCount == 1) {
6072                        framesOut >>= 1;
6073                    }
6074                    mResampler->resample(mRsmpOutBuffer, framesOut, this);
6075                    // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6076                    // are 32 bit aligned which should be always true.
6077                    if (mChannelCount == 2 && mReqChannelCount == 1) {
6078                        ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
6079                        // the resampler always outputs stereo samples: do post stereo to mono conversion
6080                        int16_t *src = (int16_t *)mRsmpOutBuffer;
6081                        int16_t *dst = buffer.i16;
6082                        while (framesOut--) {
6083                            *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6084                            src += 2;
6085                        }
6086                    } else {
6087                        ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
6088                    }
6089
6090                }
6091                if (mFramestoDrop == 0) {
6092                    mActiveTrack->releaseBuffer(&buffer);
6093                } else {
6094                    if (mFramestoDrop > 0) {
6095                        mFramestoDrop -= buffer.frameCount;
6096                        if (mFramestoDrop <= 0) {
6097                            clearSyncStartEvent();
6098                        }
6099                    } else {
6100                        mFramestoDrop += buffer.frameCount;
6101                        if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6102                                mSyncStartEvent->isCancelled()) {
6103                            ALOGW("Synced record %s, session %d, trigger session %d",
6104                                  (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6105                                  mActiveTrack->sessionId(),
6106                                  (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6107                            clearSyncStartEvent();
6108                        }
6109                    }
6110                }
6111                mActiveTrack->clearOverflow();
6112            }
6113            // client isn't retrieving buffers fast enough
6114            else {
6115                if (!mActiveTrack->setOverflow()) {
6116                    nsecs_t now = systemTime();
6117                    if ((now - lastWarning) > kWarningThrottleNs) {
6118                        ALOGW("RecordThread: buffer overflow");
6119                        lastWarning = now;
6120                    }
6121                }
6122                // Release the processor for a while before asking for a new buffer.
6123                // This will give the application more chance to read from the buffer and
6124                // clear the overflow.
6125                usleep(kRecordThreadSleepUs);
6126            }
6127        }
6128        // enable changes in effect chain
6129        unlockEffectChains(effectChains);
6130        effectChains.clear();
6131    }
6132
6133    if (!mStandby) {
6134        mInput->stream->common.standby(&mInput->stream->common);
6135    }
6136    mActiveTrack.clear();
6137
6138    mStartStopCond.broadcast();
6139
6140    releaseWakeLock();
6141
6142    ALOGV("RecordThread %p exiting", this);
6143    return false;
6144}
6145
6146
6147sp<AudioFlinger::RecordThread::RecordTrack>  AudioFlinger::RecordThread::createRecordTrack_l(
6148        const sp<AudioFlinger::Client>& client,
6149        uint32_t sampleRate,
6150        audio_format_t format,
6151        audio_channel_mask_t channelMask,
6152        int frameCount,
6153        int sessionId,
6154        IAudioFlinger::track_flags_t flags,
6155        pid_t tid,
6156        status_t *status)
6157{
6158    sp<RecordTrack> track;
6159    status_t lStatus;
6160
6161    lStatus = initCheck();
6162    if (lStatus != NO_ERROR) {
6163        ALOGE("Audio driver not initialized.");
6164        goto Exit;
6165    }
6166
6167    // FIXME use flags and tid similar to createTrack_l()
6168
6169    { // scope for mLock
6170        Mutex::Autolock _l(mLock);
6171
6172        track = new RecordTrack(this, client, sampleRate,
6173                      format, channelMask, frameCount, sessionId);
6174
6175        if (track->getCblk() == 0) {
6176            lStatus = NO_MEMORY;
6177            goto Exit;
6178        }
6179
6180        mTrack = track.get();
6181        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6182        bool suspend = audio_is_bluetooth_sco_device(
6183                (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
6184        setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6185        setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
6186    }
6187    lStatus = NO_ERROR;
6188
6189Exit:
6190    if (status) {
6191        *status = lStatus;
6192    }
6193    return track;
6194}
6195
6196status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6197                                           AudioSystem::sync_event_t event,
6198                                           int triggerSession)
6199{
6200    ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6201    sp<ThreadBase> strongMe = this;
6202    status_t status = NO_ERROR;
6203
6204    if (event == AudioSystem::SYNC_EVENT_NONE) {
6205        clearSyncStartEvent();
6206    } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6207        mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6208                                       triggerSession,
6209                                       recordTrack->sessionId(),
6210                                       syncStartEventCallback,
6211                                       this);
6212        // Sync event can be cancelled by the trigger session if the track is not in a
6213        // compatible state in which case we start record immediately
6214        if (mSyncStartEvent->isCancelled()) {
6215            clearSyncStartEvent();
6216        } else {
6217            // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6218            mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6219        }
6220    }
6221
6222    {
6223        AutoMutex lock(mLock);
6224        if (mActiveTrack != 0) {
6225            if (recordTrack != mActiveTrack.get()) {
6226                status = -EBUSY;
6227            } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6228                mActiveTrack->mState = TrackBase::ACTIVE;
6229            }
6230            return status;
6231        }
6232
6233        recordTrack->mState = TrackBase::IDLE;
6234        mActiveTrack = recordTrack;
6235        mLock.unlock();
6236        status_t status = AudioSystem::startInput(mId);
6237        mLock.lock();
6238        if (status != NO_ERROR) {
6239            mActiveTrack.clear();
6240            clearSyncStartEvent();
6241            return status;
6242        }
6243        mRsmpInIndex = mFrameCount;
6244        mBytesRead = 0;
6245        if (mResampler != NULL) {
6246            mResampler->reset();
6247        }
6248        mActiveTrack->mState = TrackBase::RESUMING;
6249        // signal thread to start
6250        ALOGV("Signal record thread");
6251        mWaitWorkCV.signal();
6252        // do not wait for mStartStopCond if exiting
6253        if (exitPending()) {
6254            mActiveTrack.clear();
6255            status = INVALID_OPERATION;
6256            goto startError;
6257        }
6258        mStartStopCond.wait(mLock);
6259        if (mActiveTrack == 0) {
6260            ALOGV("Record failed to start");
6261            status = BAD_VALUE;
6262            goto startError;
6263        }
6264        ALOGV("Record started OK");
6265        return status;
6266    }
6267startError:
6268    AudioSystem::stopInput(mId);
6269    clearSyncStartEvent();
6270    return status;
6271}
6272
6273void AudioFlinger::RecordThread::clearSyncStartEvent()
6274{
6275    if (mSyncStartEvent != 0) {
6276        mSyncStartEvent->cancel();
6277    }
6278    mSyncStartEvent.clear();
6279    mFramestoDrop = 0;
6280}
6281
6282void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6283{
6284    sp<SyncEvent> strongEvent = event.promote();
6285
6286    if (strongEvent != 0) {
6287        RecordThread *me = (RecordThread *)strongEvent->cookie();
6288        me->handleSyncStartEvent(strongEvent);
6289    }
6290}
6291
6292void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6293{
6294    if (event == mSyncStartEvent) {
6295        // TODO: use actual buffer filling status instead of 2 buffers when info is available
6296        // from audio HAL
6297        mFramestoDrop = mFrameCount * 2;
6298    }
6299}
6300
6301void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
6302    ALOGV("RecordThread::stop");
6303    sp<ThreadBase> strongMe = this;
6304    {
6305        AutoMutex lock(mLock);
6306        if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6307            mActiveTrack->mState = TrackBase::PAUSING;
6308            // do not wait for mStartStopCond if exiting
6309            if (exitPending()) {
6310                return;
6311            }
6312            mStartStopCond.wait(mLock);
6313            // if we have been restarted, recordTrack == mActiveTrack.get() here
6314            if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6315                mLock.unlock();
6316                AudioSystem::stopInput(mId);
6317                mLock.lock();
6318                ALOGV("Record stopped OK");
6319            }
6320        }
6321    }
6322}
6323
6324bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6325{
6326    return false;
6327}
6328
6329status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6330{
6331    if (!isValidSyncEvent(event)) {
6332        return BAD_VALUE;
6333    }
6334
6335    Mutex::Autolock _l(mLock);
6336
6337    if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6338        mTrack->setSyncEvent(event);
6339        return NO_ERROR;
6340    }
6341    return NAME_NOT_FOUND;
6342}
6343
6344status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6345{
6346    const size_t SIZE = 256;
6347    char buffer[SIZE];
6348    String8 result;
6349
6350    snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6351    result.append(buffer);
6352
6353    if (mActiveTrack != 0) {
6354        result.append("Active Track:\n");
6355        result.append("   Clien Fmt Chn mask   Session Buf  S SRate  Serv     User\n");
6356        mActiveTrack->dump(buffer, SIZE);
6357        result.append(buffer);
6358
6359        snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6360        result.append(buffer);
6361        snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6362        result.append(buffer);
6363        snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
6364        result.append(buffer);
6365        snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6366        result.append(buffer);
6367        snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6368        result.append(buffer);
6369
6370
6371    } else {
6372        result.append("No record client\n");
6373    }
6374    write(fd, result.string(), result.size());
6375
6376    dumpBase(fd, args);
6377    dumpEffectChains(fd, args);
6378
6379    return NO_ERROR;
6380}
6381
6382// AudioBufferProvider interface
6383status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
6384{
6385    size_t framesReq = buffer->frameCount;
6386    size_t framesReady = mFrameCount - mRsmpInIndex;
6387    int channelCount;
6388
6389    if (framesReady == 0) {
6390        mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
6391        if (mBytesRead < 0) {
6392            ALOGE("RecordThread::getNextBuffer() Error reading audio input");
6393            if (mActiveTrack->mState == TrackBase::ACTIVE) {
6394                // Force input into standby so that it tries to
6395                // recover at next read attempt
6396                mInput->stream->common.standby(&mInput->stream->common);
6397                usleep(kRecordThreadSleepUs);
6398            }
6399            buffer->raw = NULL;
6400            buffer->frameCount = 0;
6401            return NOT_ENOUGH_DATA;
6402        }
6403        mRsmpInIndex = 0;
6404        framesReady = mFrameCount;
6405    }
6406
6407    if (framesReq > framesReady) {
6408        framesReq = framesReady;
6409    }
6410
6411    if (mChannelCount == 1 && mReqChannelCount == 2) {
6412        channelCount = 1;
6413    } else {
6414        channelCount = 2;
6415    }
6416    buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6417    buffer->frameCount = framesReq;
6418    return NO_ERROR;
6419}
6420
6421// AudioBufferProvider interface
6422void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6423{
6424    mRsmpInIndex += buffer->frameCount;
6425    buffer->frameCount = 0;
6426}
6427
6428bool AudioFlinger::RecordThread::checkForNewParameters_l()
6429{
6430    bool reconfig = false;
6431
6432    while (!mNewParameters.isEmpty()) {
6433        status_t status = NO_ERROR;
6434        String8 keyValuePair = mNewParameters[0];
6435        AudioParameter param = AudioParameter(keyValuePair);
6436        int value;
6437        audio_format_t reqFormat = mFormat;
6438        int reqSamplingRate = mReqSampleRate;
6439        int reqChannelCount = mReqChannelCount;
6440
6441        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6442            reqSamplingRate = value;
6443            reconfig = true;
6444        }
6445        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6446            reqFormat = (audio_format_t) value;
6447            reconfig = true;
6448        }
6449        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6450            reqChannelCount = popcount(value);
6451            reconfig = true;
6452        }
6453        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6454            // do not accept frame count changes if tracks are open as the track buffer
6455            // size depends on frame count and correct behavior would not be guaranteed
6456            // if frame count is changed after track creation
6457            if (mActiveTrack != 0) {
6458                status = INVALID_OPERATION;
6459            } else {
6460                reconfig = true;
6461            }
6462        }
6463        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6464            // forward device change to effects that have requested to be
6465            // aware of attached audio device.
6466            for (size_t i = 0; i < mEffectChains.size(); i++) {
6467                mEffectChains[i]->setDevice_l(value);
6468            }
6469            // store input device and output device but do not forward output device to audio HAL.
6470            // Note that status is ignored by the caller for output device
6471            // (see AudioFlinger::setParameters()
6472            uint32_t /*audio_devices_t*/ newDevice = mDevice;
6473            if (value & AUDIO_DEVICE_OUT_ALL) {
6474                newDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6475                status = BAD_VALUE;
6476            } else {
6477                newDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
6478                // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6479                if (mTrack != NULL) {
6480                    bool suspend = audio_is_bluetooth_sco_device(
6481                            (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
6482                    setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6483                    setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6484                }
6485            }
6486            newDevice |= value;
6487            mDevice = (audio_devices_t) newDevice;    // since mDevice is read by other threads, only write to it once
6488        }
6489        if (status == NO_ERROR) {
6490            status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
6491            if (status == INVALID_OPERATION) {
6492                mInput->stream->common.standby(&mInput->stream->common);
6493                status = mInput->stream->common.set_parameters(&mInput->stream->common,
6494                        keyValuePair.string());
6495            }
6496            if (reconfig) {
6497                if (status == BAD_VALUE &&
6498                    reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6499                    reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6500                    ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
6501                    popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6502                    (reqChannelCount <= FCC_2)) {
6503                    status = NO_ERROR;
6504                }
6505                if (status == NO_ERROR) {
6506                    readInputParameters();
6507                    sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6508                }
6509            }
6510        }
6511
6512        mNewParameters.removeAt(0);
6513
6514        mParamStatus = status;
6515        mParamCond.signal();
6516        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6517        // already timed out waiting for the status and will never signal the condition.
6518        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
6519    }
6520    return reconfig;
6521}
6522
6523String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6524{
6525    char *s;
6526    String8 out_s8 = String8();
6527
6528    Mutex::Autolock _l(mLock);
6529    if (initCheck() != NO_ERROR) {
6530        return out_s8;
6531    }
6532
6533    s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6534    out_s8 = String8(s);
6535    free(s);
6536    return out_s8;
6537}
6538
6539void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6540    AudioSystem::OutputDescriptor desc;
6541    void *param2 = NULL;
6542
6543    switch (event) {
6544    case AudioSystem::INPUT_OPENED:
6545    case AudioSystem::INPUT_CONFIG_CHANGED:
6546        desc.channels = mChannelMask;
6547        desc.samplingRate = mSampleRate;
6548        desc.format = mFormat;
6549        desc.frameCount = mFrameCount;
6550        desc.latency = 0;
6551        param2 = &desc;
6552        break;
6553
6554    case AudioSystem::INPUT_CLOSED:
6555    default:
6556        break;
6557    }
6558    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6559}
6560
6561void AudioFlinger::RecordThread::readInputParameters()
6562{
6563    delete mRsmpInBuffer;
6564    // mRsmpInBuffer is always assigned a new[] below
6565    delete mRsmpOutBuffer;
6566    mRsmpOutBuffer = NULL;
6567    delete mResampler;
6568    mResampler = NULL;
6569
6570    mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6571    mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6572    mChannelCount = (uint16_t)popcount(mChannelMask);
6573    mFormat = mInput->stream->common.get_format(&mInput->stream->common);
6574    mFrameSize = audio_stream_frame_size(&mInput->stream->common);
6575    mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6576    mFrameCount = mInputBytes / mFrameSize;
6577    mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
6578    mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6579
6580    if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
6581    {
6582        int channelCount;
6583        // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6584        // stereo to mono post process as the resampler always outputs stereo.
6585        if (mChannelCount == 1 && mReqChannelCount == 2) {
6586            channelCount = 1;
6587        } else {
6588            channelCount = 2;
6589        }
6590        mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6591        mResampler->setSampleRate(mSampleRate);
6592        mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6593        mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6594
6595        // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6596        if (mChannelCount == 1 && mReqChannelCount == 1) {
6597            mFrameCount >>= 1;
6598        }
6599
6600    }
6601    mRsmpInIndex = mFrameCount;
6602}
6603
6604unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6605{
6606    Mutex::Autolock _l(mLock);
6607    if (initCheck() != NO_ERROR) {
6608        return 0;
6609    }
6610
6611    return mInput->stream->get_input_frames_lost(mInput->stream);
6612}
6613
6614uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6615{
6616    Mutex::Autolock _l(mLock);
6617    uint32_t result = 0;
6618    if (getEffectChain_l(sessionId) != 0) {
6619        result = EFFECT_SESSION;
6620    }
6621
6622    if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6623        result |= TRACK_SESSION;
6624    }
6625
6626    return result;
6627}
6628
6629AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6630{
6631    Mutex::Autolock _l(mLock);
6632    return mTrack;
6633}
6634
6635AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6636{
6637    Mutex::Autolock _l(mLock);
6638    AudioStreamIn *input = mInput;
6639    mInput = NULL;
6640    return input;
6641}
6642
6643// this method must always be called either with ThreadBase mLock held or inside the thread loop
6644audio_stream_t* AudioFlinger::RecordThread::stream() const
6645{
6646    if (mInput == NULL) {
6647        return NULL;
6648    }
6649    return &mInput->stream->common;
6650}
6651
6652
6653// ----------------------------------------------------------------------------
6654
6655audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6656{
6657    if (!settingsAllowed()) {
6658        return 0;
6659    }
6660    Mutex::Autolock _l(mLock);
6661    return loadHwModule_l(name);
6662}
6663
6664// loadHwModule_l() must be called with AudioFlinger::mLock held
6665audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6666{
6667    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6668        if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6669            ALOGW("loadHwModule() module %s already loaded", name);
6670            return mAudioHwDevs.keyAt(i);
6671        }
6672    }
6673
6674    audio_hw_device_t *dev;
6675
6676    int rc = load_audio_interface(name, &dev);
6677    if (rc) {
6678        ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6679        return 0;
6680    }
6681
6682    mHardwareStatus = AUDIO_HW_INIT;
6683    rc = dev->init_check(dev);
6684    mHardwareStatus = AUDIO_HW_IDLE;
6685    if (rc) {
6686        ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6687        return 0;
6688    }
6689
6690    if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6691        (NULL != dev->set_master_volume)) {
6692        AutoMutex lock(mHardwareLock);
6693        mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6694        dev->set_master_volume(dev, mMasterVolume);
6695        mHardwareStatus = AUDIO_HW_IDLE;
6696    }
6697
6698    audio_module_handle_t handle = nextUniqueId();
6699    mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6700
6701    ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
6702          name, dev->common.module->name, dev->common.module->id, handle);
6703
6704    return handle;
6705
6706}
6707
6708audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6709                                           audio_devices_t *pDevices,
6710                                           uint32_t *pSamplingRate,
6711                                           audio_format_t *pFormat,
6712                                           audio_channel_mask_t *pChannelMask,
6713                                           uint32_t *pLatencyMs,
6714                                           audio_output_flags_t flags)
6715{
6716    status_t status;
6717    PlaybackThread *thread = NULL;
6718    struct audio_config config = {
6719        sample_rate: pSamplingRate ? *pSamplingRate : 0,
6720        channel_mask: pChannelMask ? *pChannelMask : 0,
6721        format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6722    };
6723    audio_stream_out_t *outStream = NULL;
6724    audio_hw_device_t *outHwDev;
6725
6726    ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6727              module,
6728              (pDevices != NULL) ? (int)*pDevices : 0,
6729              config.sample_rate,
6730              config.format,
6731              config.channel_mask,
6732              flags);
6733
6734    if (pDevices == NULL || *pDevices == 0) {
6735        return 0;
6736    }
6737
6738    Mutex::Autolock _l(mLock);
6739
6740    outHwDev = findSuitableHwDev_l(module, *pDevices);
6741    if (outHwDev == NULL)
6742        return 0;
6743
6744    audio_io_handle_t id = nextUniqueId();
6745
6746    mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
6747
6748    status = outHwDev->open_output_stream(outHwDev,
6749                                          id,
6750                                          *pDevices,
6751                                          (audio_output_flags_t)flags,
6752                                          &config,
6753                                          &outStream);
6754
6755    mHardwareStatus = AUDIO_HW_IDLE;
6756    ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
6757            outStream,
6758            config.sample_rate,
6759            config.format,
6760            config.channel_mask,
6761            status);
6762
6763    if (status == NO_ERROR && outStream != NULL) {
6764        AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
6765
6766        if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
6767            (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6768            (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
6769            thread = new DirectOutputThread(this, output, id, *pDevices);
6770            ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
6771        } else {
6772            thread = new MixerThread(this, output, id, *pDevices);
6773            ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
6774        }
6775        mPlaybackThreads.add(id, thread);
6776
6777        if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6778        if (pFormat != NULL) *pFormat = config.format;
6779        if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
6780        if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
6781
6782        // notify client processes of the new output creation
6783        thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6784
6785        // the first primary output opened designates the primary hw device
6786        if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
6787            ALOGI("Using module %d has the primary audio interface", module);
6788            mPrimaryHardwareDev = outHwDev;
6789
6790            AutoMutex lock(mHardwareLock);
6791            mHardwareStatus = AUDIO_HW_SET_MODE;
6792            outHwDev->set_mode(outHwDev, mMode);
6793
6794            // Determine the level of master volume support the primary audio HAL has,
6795            // and set the initial master volume at the same time.
6796            float initialVolume = 1.0;
6797            mMasterVolumeSupportLvl = MVS_NONE;
6798
6799            mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6800            if ((NULL != outHwDev->get_master_volume) &&
6801                (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6802                mMasterVolumeSupportLvl = MVS_FULL;
6803            } else {
6804                mMasterVolumeSupportLvl = MVS_SETONLY;
6805                initialVolume = 1.0;
6806            }
6807
6808            mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6809            if ((NULL == outHwDev->set_master_volume) ||
6810                (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6811                mMasterVolumeSupportLvl = MVS_NONE;
6812            }
6813            // now that we have a primary device, initialize master volume on other devices
6814            for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6815                audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6816
6817                if ((dev != mPrimaryHardwareDev) &&
6818                    (NULL != dev->set_master_volume)) {
6819                    dev->set_master_volume(dev, initialVolume);
6820                }
6821            }
6822            mHardwareStatus = AUDIO_HW_IDLE;
6823            mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6824                                    ? initialVolume
6825                                    : 1.0;
6826            mMasterVolume   = initialVolume;
6827        }
6828        return id;
6829    }
6830
6831    return 0;
6832}
6833
6834audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6835        audio_io_handle_t output2)
6836{
6837    Mutex::Autolock _l(mLock);
6838    MixerThread *thread1 = checkMixerThread_l(output1);
6839    MixerThread *thread2 = checkMixerThread_l(output2);
6840
6841    if (thread1 == NULL || thread2 == NULL) {
6842        ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
6843        return 0;
6844    }
6845
6846    audio_io_handle_t id = nextUniqueId();
6847    DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6848    thread->addOutputTrack(thread2);
6849    mPlaybackThreads.add(id, thread);
6850    // notify client processes of the new output creation
6851    thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6852    return id;
6853}
6854
6855status_t AudioFlinger::closeOutput(audio_io_handle_t output)
6856{
6857    return closeOutput_nonvirtual(output);
6858}
6859
6860status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
6861{
6862    // keep strong reference on the playback thread so that
6863    // it is not destroyed while exit() is executed
6864    sp<PlaybackThread> thread;
6865    {
6866        Mutex::Autolock _l(mLock);
6867        thread = checkPlaybackThread_l(output);
6868        if (thread == NULL) {
6869            return BAD_VALUE;
6870        }
6871
6872        ALOGV("closeOutput() %d", output);
6873
6874        if (thread->type() == ThreadBase::MIXER) {
6875            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6876                if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
6877                    DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6878                    dupThread->removeOutputTrack((MixerThread *)thread.get());
6879                }
6880            }
6881        }
6882        audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
6883        mPlaybackThreads.removeItem(output);
6884    }
6885    thread->exit();
6886    // The thread entity (active unit of execution) is no longer running here,
6887    // but the ThreadBase container still exists.
6888
6889    if (thread->type() != ThreadBase::DUPLICATING) {
6890        AudioStreamOut *out = thread->clearOutput();
6891        ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
6892        // from now on thread->mOutput is NULL
6893        out->hwDev->close_output_stream(out->hwDev, out->stream);
6894        delete out;
6895    }
6896    return NO_ERROR;
6897}
6898
6899status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
6900{
6901    Mutex::Autolock _l(mLock);
6902    PlaybackThread *thread = checkPlaybackThread_l(output);
6903
6904    if (thread == NULL) {
6905        return BAD_VALUE;
6906    }
6907
6908    ALOGV("suspendOutput() %d", output);
6909    thread->suspend();
6910
6911    return NO_ERROR;
6912}
6913
6914status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
6915{
6916    Mutex::Autolock _l(mLock);
6917    PlaybackThread *thread = checkPlaybackThread_l(output);
6918
6919    if (thread == NULL) {
6920        return BAD_VALUE;
6921    }
6922
6923    ALOGV("restoreOutput() %d", output);
6924
6925    thread->restore();
6926
6927    return NO_ERROR;
6928}
6929
6930audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6931                                          audio_devices_t *pDevices,
6932                                          uint32_t *pSamplingRate,
6933                                          audio_format_t *pFormat,
6934                                          audio_channel_mask_t *pChannelMask)
6935{
6936    status_t status;
6937    RecordThread *thread = NULL;
6938    struct audio_config config = {
6939        sample_rate: pSamplingRate ? *pSamplingRate : 0,
6940        channel_mask: pChannelMask ? *pChannelMask : 0,
6941        format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6942    };
6943    uint32_t reqSamplingRate = config.sample_rate;
6944    audio_format_t reqFormat = config.format;
6945    audio_channel_mask_t reqChannels = config.channel_mask;
6946    audio_stream_in_t *inStream = NULL;
6947    audio_hw_device_t *inHwDev;
6948
6949    if (pDevices == NULL || *pDevices == 0) {
6950        return 0;
6951    }
6952
6953    Mutex::Autolock _l(mLock);
6954
6955    inHwDev = findSuitableHwDev_l(module, *pDevices);
6956    if (inHwDev == NULL)
6957        return 0;
6958
6959    audio_io_handle_t id = nextUniqueId();
6960
6961    status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
6962                                        &inStream);
6963    ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
6964            inStream,
6965            config.sample_rate,
6966            config.format,
6967            config.channel_mask,
6968            status);
6969
6970    // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6971    // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6972    // or stereo to mono conversions on 16 bit PCM inputs.
6973    if (status == BAD_VALUE &&
6974        reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6975        (config.sample_rate <= 2 * reqSamplingRate) &&
6976        (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
6977        ALOGV("openInput() reopening with proposed sampling rate and channel mask");
6978        inStream = NULL;
6979        status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
6980    }
6981
6982    if (status == NO_ERROR && inStream != NULL) {
6983        AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6984
6985        // Start record thread
6986        // RecorThread require both input and output device indication to forward to audio
6987        // pre processing modules
6988        uint32_t device = (*pDevices) | primaryOutputDevice_l();
6989        thread = new RecordThread(this,
6990                                  input,
6991                                  reqSamplingRate,
6992                                  reqChannels,
6993                                  id,
6994                                  device);
6995        mRecordThreads.add(id, thread);
6996        ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
6997        if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
6998        if (pFormat != NULL) *pFormat = config.format;
6999        if (pChannelMask != NULL) *pChannelMask = reqChannels;
7000
7001        input->stream->common.standby(&input->stream->common);
7002
7003        // notify client processes of the new input creation
7004        thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7005        return id;
7006    }
7007
7008    return 0;
7009}
7010
7011status_t AudioFlinger::closeInput(audio_io_handle_t input)
7012{
7013    return closeInput_nonvirtual(input);
7014}
7015
7016status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7017{
7018    // keep strong reference on the record thread so that
7019    // it is not destroyed while exit() is executed
7020    sp<RecordThread> thread;
7021    {
7022        Mutex::Autolock _l(mLock);
7023        thread = checkRecordThread_l(input);
7024        if (thread == 0) {
7025            return BAD_VALUE;
7026        }
7027
7028        ALOGV("closeInput() %d", input);
7029        audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
7030        mRecordThreads.removeItem(input);
7031    }
7032    thread->exit();
7033    // The thread entity (active unit of execution) is no longer running here,
7034    // but the ThreadBase container still exists.
7035
7036    AudioStreamIn *in = thread->clearInput();
7037    ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
7038    // from now on thread->mInput is NULL
7039    in->hwDev->close_input_stream(in->hwDev, in->stream);
7040    delete in;
7041
7042    return NO_ERROR;
7043}
7044
7045status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
7046{
7047    Mutex::Autolock _l(mLock);
7048    ALOGV("setStreamOutput() stream %d to output %d", stream, output);
7049
7050    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7051        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
7052        thread->invalidateTracks(stream);
7053    }
7054
7055    return NO_ERROR;
7056}
7057
7058
7059int AudioFlinger::newAudioSessionId()
7060{
7061    return nextUniqueId();
7062}
7063
7064void AudioFlinger::acquireAudioSessionId(int audioSession)
7065{
7066    Mutex::Autolock _l(mLock);
7067    pid_t caller = IPCThreadState::self()->getCallingPid();
7068    ALOGV("acquiring %d from %d", audioSession, caller);
7069    size_t num = mAudioSessionRefs.size();
7070    for (size_t i = 0; i< num; i++) {
7071        AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
7072        if (ref->mSessionid == audioSession && ref->mPid == caller) {
7073            ref->mCnt++;
7074            ALOGV(" incremented refcount to %d", ref->mCnt);
7075            return;
7076        }
7077    }
7078    mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7079    ALOGV(" added new entry for %d", audioSession);
7080}
7081
7082void AudioFlinger::releaseAudioSessionId(int audioSession)
7083{
7084    Mutex::Autolock _l(mLock);
7085    pid_t caller = IPCThreadState::self()->getCallingPid();
7086    ALOGV("releasing %d from %d", audioSession, caller);
7087    size_t num = mAudioSessionRefs.size();
7088    for (size_t i = 0; i< num; i++) {
7089        AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
7090        if (ref->mSessionid == audioSession && ref->mPid == caller) {
7091            ref->mCnt--;
7092            ALOGV(" decremented refcount to %d", ref->mCnt);
7093            if (ref->mCnt == 0) {
7094                mAudioSessionRefs.removeAt(i);
7095                delete ref;
7096                purgeStaleEffects_l();
7097            }
7098            return;
7099        }
7100    }
7101    ALOGW("session id %d not found for pid %d", audioSession, caller);
7102}
7103
7104void AudioFlinger::purgeStaleEffects_l() {
7105
7106    ALOGV("purging stale effects");
7107
7108    Vector< sp<EffectChain> > chains;
7109
7110    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7111        sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7112        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7113            sp<EffectChain> ec = t->mEffectChains[j];
7114            if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7115                chains.push(ec);
7116            }
7117        }
7118    }
7119    for (size_t i = 0; i < mRecordThreads.size(); i++) {
7120        sp<RecordThread> t = mRecordThreads.valueAt(i);
7121        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7122            sp<EffectChain> ec = t->mEffectChains[j];
7123            chains.push(ec);
7124        }
7125    }
7126
7127    for (size_t i = 0; i < chains.size(); i++) {
7128        sp<EffectChain> ec = chains[i];
7129        int sessionid = ec->sessionId();
7130        sp<ThreadBase> t = ec->mThread.promote();
7131        if (t == 0) {
7132            continue;
7133        }
7134        size_t numsessionrefs = mAudioSessionRefs.size();
7135        bool found = false;
7136        for (size_t k = 0; k < numsessionrefs; k++) {
7137            AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
7138            if (ref->mSessionid == sessionid) {
7139                ALOGV(" session %d still exists for %d with %d refs",
7140                    sessionid, ref->mPid, ref->mCnt);
7141                found = true;
7142                break;
7143            }
7144        }
7145        if (!found) {
7146            Mutex::Autolock _l (t->mLock);
7147            // remove all effects from the chain
7148            while (ec->mEffects.size()) {
7149                sp<EffectModule> effect = ec->mEffects[0];
7150                effect->unPin();
7151                t->removeEffect_l(effect);
7152                if (effect->purgeHandles()) {
7153                    t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
7154                }
7155                AudioSystem::unregisterEffect(effect->id());
7156            }
7157        }
7158    }
7159    return;
7160}
7161
7162// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
7163AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
7164{
7165    return mPlaybackThreads.valueFor(output).get();
7166}
7167
7168// checkMixerThread_l() must be called with AudioFlinger::mLock held
7169AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
7170{
7171    PlaybackThread *thread = checkPlaybackThread_l(output);
7172    return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
7173}
7174
7175// checkRecordThread_l() must be called with AudioFlinger::mLock held
7176AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
7177{
7178    return mRecordThreads.valueFor(input).get();
7179}
7180
7181uint32_t AudioFlinger::nextUniqueId()
7182{
7183    return android_atomic_inc(&mNextUniqueId);
7184}
7185
7186AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
7187{
7188    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7189        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
7190        AudioStreamOut *output = thread->getOutput();
7191        if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
7192            return thread;
7193        }
7194    }
7195    return NULL;
7196}
7197
7198uint32_t AudioFlinger::primaryOutputDevice_l() const
7199{
7200    PlaybackThread *thread = primaryPlaybackThread_l();
7201
7202    if (thread == NULL) {
7203        return 0;
7204    }
7205
7206    return thread->device();
7207}
7208
7209sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7210                                    int triggerSession,
7211                                    int listenerSession,
7212                                    sync_event_callback_t callBack,
7213                                    void *cookie)
7214{
7215    Mutex::Autolock _l(mLock);
7216
7217    sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7218    status_t playStatus = NAME_NOT_FOUND;
7219    status_t recStatus = NAME_NOT_FOUND;
7220    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7221        playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7222        if (playStatus == NO_ERROR) {
7223            return event;
7224        }
7225    }
7226    for (size_t i = 0; i < mRecordThreads.size(); i++) {
7227        recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7228        if (recStatus == NO_ERROR) {
7229            return event;
7230        }
7231    }
7232    if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7233        mPendingSyncEvents.add(event);
7234    } else {
7235        ALOGV("createSyncEvent() invalid event %d", event->type());
7236        event.clear();
7237    }
7238    return event;
7239}
7240
7241// ----------------------------------------------------------------------------
7242//  Effect management
7243// ----------------------------------------------------------------------------
7244
7245
7246status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
7247{
7248    Mutex::Autolock _l(mLock);
7249    return EffectQueryNumberEffects(numEffects);
7250}
7251
7252status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
7253{
7254    Mutex::Autolock _l(mLock);
7255    return EffectQueryEffect(index, descriptor);
7256}
7257
7258status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
7259        effect_descriptor_t *descriptor) const
7260{
7261    Mutex::Autolock _l(mLock);
7262    return EffectGetDescriptor(pUuid, descriptor);
7263}
7264
7265
7266sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7267        effect_descriptor_t *pDesc,
7268        const sp<IEffectClient>& effectClient,
7269        int32_t priority,
7270        audio_io_handle_t io,
7271        int sessionId,
7272        status_t *status,
7273        int *id,
7274        int *enabled)
7275{
7276    status_t lStatus = NO_ERROR;
7277    sp<EffectHandle> handle;
7278    effect_descriptor_t desc;
7279
7280    ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
7281            pid, effectClient.get(), priority, sessionId, io);
7282
7283    if (pDesc == NULL) {
7284        lStatus = BAD_VALUE;
7285        goto Exit;
7286    }
7287
7288    // check audio settings permission for global effects
7289    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
7290        lStatus = PERMISSION_DENIED;
7291        goto Exit;
7292    }
7293
7294    // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
7295    // that can only be created by audio policy manager (running in same process)
7296    if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
7297        lStatus = PERMISSION_DENIED;
7298        goto Exit;
7299    }
7300
7301    if (io == 0) {
7302        if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
7303            // output must be specified by AudioPolicyManager when using session
7304            // AUDIO_SESSION_OUTPUT_STAGE
7305            lStatus = BAD_VALUE;
7306            goto Exit;
7307        } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
7308            // if the output returned by getOutputForEffect() is removed before we lock the
7309            // mutex below, the call to checkPlaybackThread_l(io) below will detect it
7310            // and we will exit safely
7311            io = AudioSystem::getOutputForEffect(&desc);
7312        }
7313    }
7314
7315    {
7316        Mutex::Autolock _l(mLock);
7317
7318
7319        if (!EffectIsNullUuid(&pDesc->uuid)) {
7320            // if uuid is specified, request effect descriptor
7321            lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7322            if (lStatus < 0) {
7323                ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
7324                goto Exit;
7325            }
7326        } else {
7327            // if uuid is not specified, look for an available implementation
7328            // of the required type in effect factory
7329            if (EffectIsNullUuid(&pDesc->type)) {
7330                ALOGW("createEffect() no effect type");
7331                lStatus = BAD_VALUE;
7332                goto Exit;
7333            }
7334            uint32_t numEffects = 0;
7335            effect_descriptor_t d;
7336            d.flags = 0; // prevent compiler warning
7337            bool found = false;
7338
7339            lStatus = EffectQueryNumberEffects(&numEffects);
7340            if (lStatus < 0) {
7341                ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
7342                goto Exit;
7343            }
7344            for (uint32_t i = 0; i < numEffects; i++) {
7345                lStatus = EffectQueryEffect(i, &desc);
7346                if (lStatus < 0) {
7347                    ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
7348                    continue;
7349                }
7350                if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7351                    // If matching type found save effect descriptor. If the session is
7352                    // 0 and the effect is not auxiliary, continue enumeration in case
7353                    // an auxiliary version of this effect type is available
7354                    found = true;
7355                    memcpy(&d, &desc, sizeof(effect_descriptor_t));
7356                    if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
7357                            (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7358                        break;
7359                    }
7360                }
7361            }
7362            if (!found) {
7363                lStatus = BAD_VALUE;
7364                ALOGW("createEffect() effect not found");
7365                goto Exit;
7366            }
7367            // For same effect type, chose auxiliary version over insert version if
7368            // connect to output mix (Compliance to OpenSL ES)
7369            if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
7370                    (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7371                memcpy(&desc, &d, sizeof(effect_descriptor_t));
7372            }
7373        }
7374
7375        // Do not allow auxiliary effects on a session different from 0 (output mix)
7376        if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
7377             (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7378            lStatus = INVALID_OPERATION;
7379            goto Exit;
7380        }
7381
7382        // check recording permission for visualizer
7383        if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7384            !recordingAllowed()) {
7385            lStatus = PERMISSION_DENIED;
7386            goto Exit;
7387        }
7388
7389        // return effect descriptor
7390        memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7391
7392        // If output is not specified try to find a matching audio session ID in one of the
7393        // output threads.
7394        // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7395        // because of code checking output when entering the function.
7396        // Note: io is never 0 when creating an effect on an input
7397        if (io == 0) {
7398            // look for the thread where the specified audio session is present
7399            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7400                if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7401                    io = mPlaybackThreads.keyAt(i);
7402                    break;
7403                }
7404            }
7405            if (io == 0) {
7406                for (size_t i = 0; i < mRecordThreads.size(); i++) {
7407                    if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7408                        io = mRecordThreads.keyAt(i);
7409                        break;
7410                    }
7411                }
7412            }
7413            // If no output thread contains the requested session ID, default to
7414            // first output. The effect chain will be moved to the correct output
7415            // thread when a track with the same session ID is created
7416            if (io == 0 && mPlaybackThreads.size()) {
7417                io = mPlaybackThreads.keyAt(0);
7418            }
7419            ALOGV("createEffect() got io %d for effect %s", io, desc.name);
7420        }
7421        ThreadBase *thread = checkRecordThread_l(io);
7422        if (thread == NULL) {
7423            thread = checkPlaybackThread_l(io);
7424            if (thread == NULL) {
7425                ALOGE("createEffect() unknown output thread");
7426                lStatus = BAD_VALUE;
7427                goto Exit;
7428            }
7429        }
7430
7431        sp<Client> client = registerPid_l(pid);
7432
7433        // create effect on selected output thread
7434        handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7435                &desc, enabled, &lStatus);
7436        if (handle != 0 && id != NULL) {
7437            *id = handle->id();
7438        }
7439    }
7440
7441Exit:
7442    if (status != NULL) {
7443        *status = lStatus;
7444    }
7445    return handle;
7446}
7447
7448status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7449        audio_io_handle_t dstOutput)
7450{
7451    ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
7452            sessionId, srcOutput, dstOutput);
7453    Mutex::Autolock _l(mLock);
7454    if (srcOutput == dstOutput) {
7455        ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
7456        return NO_ERROR;
7457    }
7458    PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7459    if (srcThread == NULL) {
7460        ALOGW("moveEffects() bad srcOutput %d", srcOutput);
7461        return BAD_VALUE;
7462    }
7463    PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7464    if (dstThread == NULL) {
7465        ALOGW("moveEffects() bad dstOutput %d", dstOutput);
7466        return BAD_VALUE;
7467    }
7468
7469    Mutex::Autolock _dl(dstThread->mLock);
7470    Mutex::Autolock _sl(srcThread->mLock);
7471    moveEffectChain_l(sessionId, srcThread, dstThread, false);
7472
7473    return NO_ERROR;
7474}
7475
7476// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
7477status_t AudioFlinger::moveEffectChain_l(int sessionId,
7478                                   AudioFlinger::PlaybackThread *srcThread,
7479                                   AudioFlinger::PlaybackThread *dstThread,
7480                                   bool reRegister)
7481{
7482    ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
7483            sessionId, srcThread, dstThread);
7484
7485    sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
7486    if (chain == 0) {
7487        ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
7488                sessionId, srcThread);
7489        return INVALID_OPERATION;
7490    }
7491
7492    // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
7493    // so that a new chain is created with correct parameters when first effect is added. This is
7494    // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
7495    // removed.
7496    srcThread->removeEffectChain_l(chain);
7497
7498    // transfer all effects one by one so that new effect chain is created on new thread with
7499    // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
7500    audio_io_handle_t dstOutput = dstThread->id();
7501    sp<EffectChain> dstChain;
7502    uint32_t strategy = 0; // prevent compiler warning
7503    sp<EffectModule> effect = chain->getEffectFromId_l(0);
7504    while (effect != 0) {
7505        srcThread->removeEffect_l(effect);
7506        dstThread->addEffect_l(effect);
7507        // removeEffect_l() has stopped the effect if it was active so it must be restarted
7508        if (effect->state() == EffectModule::ACTIVE ||
7509                effect->state() == EffectModule::STOPPING) {
7510            effect->start();
7511        }
7512        // if the move request is not received from audio policy manager, the effect must be
7513        // re-registered with the new strategy and output
7514        if (dstChain == 0) {
7515            dstChain = effect->chain().promote();
7516            if (dstChain == 0) {
7517                ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
7518                srcThread->addEffect_l(effect);
7519                return NO_INIT;
7520            }
7521            strategy = dstChain->strategy();
7522        }
7523        if (reRegister) {
7524            AudioSystem::unregisterEffect(effect->id());
7525            AudioSystem::registerEffect(&effect->desc(),
7526                                        dstOutput,
7527                                        strategy,
7528                                        sessionId,
7529                                        effect->id());
7530        }
7531        effect = chain->getEffectFromId_l(0);
7532    }
7533
7534    return NO_ERROR;
7535}
7536
7537
7538// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
7539sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
7540        const sp<AudioFlinger::Client>& client,
7541        const sp<IEffectClient>& effectClient,
7542        int32_t priority,
7543        int sessionId,
7544        effect_descriptor_t *desc,
7545        int *enabled,
7546        status_t *status
7547        )
7548{
7549    sp<EffectModule> effect;
7550    sp<EffectHandle> handle;
7551    status_t lStatus;
7552    sp<EffectChain> chain;
7553    bool chainCreated = false;
7554    bool effectCreated = false;
7555    bool effectRegistered = false;
7556
7557    lStatus = initCheck();
7558    if (lStatus != NO_ERROR) {
7559        ALOGW("createEffect_l() Audio driver not initialized.");
7560        goto Exit;
7561    }
7562
7563    // Do not allow effects with session ID 0 on direct output or duplicating threads
7564    // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
7565    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
7566        ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
7567                desc->name, sessionId);
7568        lStatus = BAD_VALUE;
7569        goto Exit;
7570    }
7571    // Only Pre processor effects are allowed on input threads and only on input threads
7572    if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
7573        ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
7574                desc->name, desc->flags, mType);
7575        lStatus = BAD_VALUE;
7576        goto Exit;
7577    }
7578
7579    ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
7580
7581    { // scope for mLock
7582        Mutex::Autolock _l(mLock);
7583
7584        // check for existing effect chain with the requested audio session
7585        chain = getEffectChain_l(sessionId);
7586        if (chain == 0) {
7587            // create a new chain for this session
7588            ALOGV("createEffect_l() new effect chain for session %d", sessionId);
7589            chain = new EffectChain(this, sessionId);
7590            addEffectChain_l(chain);
7591            chain->setStrategy(getStrategyForSession_l(sessionId));
7592            chainCreated = true;
7593        } else {
7594            effect = chain->getEffectFromDesc_l(desc);
7595        }
7596
7597        ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
7598
7599        if (effect == 0) {
7600            int id = mAudioFlinger->nextUniqueId();
7601            // Check CPU and memory usage
7602            lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
7603            if (lStatus != NO_ERROR) {
7604                goto Exit;
7605            }
7606            effectRegistered = true;
7607            // create a new effect module if none present in the chain
7608            effect = new EffectModule(this, chain, desc, id, sessionId);
7609            lStatus = effect->status();
7610            if (lStatus != NO_ERROR) {
7611                goto Exit;
7612            }
7613            lStatus = chain->addEffect_l(effect);
7614            if (lStatus != NO_ERROR) {
7615                goto Exit;
7616            }
7617            effectCreated = true;
7618
7619            effect->setDevice(mDevice);
7620            effect->setMode(mAudioFlinger->getMode());
7621        }
7622        // create effect handle and connect it to effect module
7623        handle = new EffectHandle(effect, client, effectClient, priority);
7624        lStatus = effect->addHandle(handle.get());
7625        if (enabled != NULL) {
7626            *enabled = (int)effect->isEnabled();
7627        }
7628    }
7629
7630Exit:
7631    if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
7632        Mutex::Autolock _l(mLock);
7633        if (effectCreated) {
7634            chain->removeEffect_l(effect);
7635        }
7636        if (effectRegistered) {
7637            AudioSystem::unregisterEffect(effect->id());
7638        }
7639        if (chainCreated) {
7640            removeEffectChain_l(chain);
7641        }
7642        handle.clear();
7643    }
7644
7645    if (status != NULL) {
7646        *status = lStatus;
7647    }
7648    return handle;
7649}
7650
7651sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7652{
7653    Mutex::Autolock _l(mLock);
7654    return getEffect_l(sessionId, effectId);
7655}
7656
7657sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7658{
7659    sp<EffectChain> chain = getEffectChain_l(sessionId);
7660    return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
7661}
7662
7663// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7664// PlaybackThread::mLock held
7665status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
7666{
7667    // check for existing effect chain with the requested audio session
7668    int sessionId = effect->sessionId();
7669    sp<EffectChain> chain = getEffectChain_l(sessionId);
7670    bool chainCreated = false;
7671
7672    if (chain == 0) {
7673        // create a new chain for this session
7674        ALOGV("addEffect_l() new effect chain for session %d", sessionId);
7675        chain = new EffectChain(this, sessionId);
7676        addEffectChain_l(chain);
7677        chain->setStrategy(getStrategyForSession_l(sessionId));
7678        chainCreated = true;
7679    }
7680    ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
7681
7682    if (chain->getEffectFromId_l(effect->id()) != 0) {
7683        ALOGW("addEffect_l() %p effect %s already present in chain %p",
7684                this, effect->desc().name, chain.get());
7685        return BAD_VALUE;
7686    }
7687
7688    status_t status = chain->addEffect_l(effect);
7689    if (status != NO_ERROR) {
7690        if (chainCreated) {
7691            removeEffectChain_l(chain);
7692        }
7693        return status;
7694    }
7695
7696    effect->setDevice(mDevice);
7697    effect->setMode(mAudioFlinger->getMode());
7698    return NO_ERROR;
7699}
7700
7701void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
7702
7703    ALOGV("removeEffect_l() %p effect %p", this, effect.get());
7704    effect_descriptor_t desc = effect->desc();
7705    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7706        detachAuxEffect_l(effect->id());
7707    }
7708
7709    sp<EffectChain> chain = effect->chain().promote();
7710    if (chain != 0) {
7711        // remove effect chain if removing last effect
7712        if (chain->removeEffect_l(effect) == 0) {
7713            removeEffectChain_l(chain);
7714        }
7715    } else {
7716        ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
7717    }
7718}
7719
7720void AudioFlinger::ThreadBase::lockEffectChains_l(
7721        Vector< sp<AudioFlinger::EffectChain> >& effectChains)
7722{
7723    effectChains = mEffectChains;
7724    for (size_t i = 0; i < mEffectChains.size(); i++) {
7725        mEffectChains[i]->lock();
7726    }
7727}
7728
7729void AudioFlinger::ThreadBase::unlockEffectChains(
7730        const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
7731{
7732    for (size_t i = 0; i < effectChains.size(); i++) {
7733        effectChains[i]->unlock();
7734    }
7735}
7736
7737sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7738{
7739    Mutex::Autolock _l(mLock);
7740    return getEffectChain_l(sessionId);
7741}
7742
7743sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7744{
7745    size_t size = mEffectChains.size();
7746    for (size_t i = 0; i < size; i++) {
7747        if (mEffectChains[i]->sessionId() == sessionId) {
7748            return mEffectChains[i];
7749        }
7750    }
7751    return 0;
7752}
7753
7754void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
7755{
7756    Mutex::Autolock _l(mLock);
7757    size_t size = mEffectChains.size();
7758    for (size_t i = 0; i < size; i++) {
7759        mEffectChains[i]->setMode_l(mode);
7760    }
7761}
7762
7763void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
7764                                                    EffectHandle *handle,
7765                                                    bool unpinIfLast) {
7766
7767    Mutex::Autolock _l(mLock);
7768    ALOGV("disconnectEffect() %p effect %p", this, effect.get());
7769    // delete the effect module if removing last handle on it
7770    if (effect->removeHandle(handle) == 0) {
7771        if (!effect->isPinned() || unpinIfLast) {
7772            removeEffect_l(effect);
7773            AudioSystem::unregisterEffect(effect->id());
7774        }
7775    }
7776}
7777
7778status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7779{
7780    int session = chain->sessionId();
7781    int16_t *buffer = mMixBuffer;
7782    bool ownsBuffer = false;
7783
7784    ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
7785    if (session > 0) {
7786        // Only one effect chain can be present in direct output thread and it uses
7787        // the mix buffer as input
7788        if (mType != DIRECT) {
7789            size_t numSamples = mNormalFrameCount * mChannelCount;
7790            buffer = new int16_t[numSamples];
7791            memset(buffer, 0, numSamples * sizeof(int16_t));
7792            ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
7793            ownsBuffer = true;
7794        }
7795
7796        // Attach all tracks with same session ID to this chain.
7797        for (size_t i = 0; i < mTracks.size(); ++i) {
7798            sp<Track> track = mTracks[i];
7799            if (session == track->sessionId()) {
7800                ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
7801                track->setMainBuffer(buffer);
7802                chain->incTrackCnt();
7803            }
7804        }
7805
7806        // indicate all active tracks in the chain
7807        for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7808            sp<Track> track = mActiveTracks[i].promote();
7809            if (track == 0) continue;
7810            if (session == track->sessionId()) {
7811                ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
7812                chain->incActiveTrackCnt();
7813            }
7814        }
7815    }
7816
7817    chain->setInBuffer(buffer, ownsBuffer);
7818    chain->setOutBuffer(mMixBuffer);
7819    // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
7820    // chains list in order to be processed last as it contains output stage effects
7821    // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7822    // session AUDIO_SESSION_OUTPUT_STAGE to be processed
7823    // after track specific effects and before output stage
7824    // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7825    // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
7826    // Effect chain for other sessions are inserted at beginning of effect
7827    // chains list to be processed before output mix effects. Relative order between other
7828    // sessions is not important
7829    size_t size = mEffectChains.size();
7830    size_t i = 0;
7831    for (i = 0; i < size; i++) {
7832        if (mEffectChains[i]->sessionId() < session) break;
7833    }
7834    mEffectChains.insertAt(chain, i);
7835    checkSuspendOnAddEffectChain_l(chain);
7836
7837    return NO_ERROR;
7838}
7839
7840size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7841{
7842    int session = chain->sessionId();
7843
7844    ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
7845
7846    for (size_t i = 0; i < mEffectChains.size(); i++) {
7847        if (chain == mEffectChains[i]) {
7848            mEffectChains.removeAt(i);
7849            // detach all active tracks from the chain
7850            for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7851                sp<Track> track = mActiveTracks[i].promote();
7852                if (track == 0) continue;
7853                if (session == track->sessionId()) {
7854                    ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
7855                            chain.get(), session);
7856                    chain->decActiveTrackCnt();
7857                }
7858            }
7859
7860            // detach all tracks with same session ID from this chain
7861            for (size_t i = 0; i < mTracks.size(); ++i) {
7862                sp<Track> track = mTracks[i];
7863                if (session == track->sessionId()) {
7864                    track->setMainBuffer(mMixBuffer);
7865                    chain->decTrackCnt();
7866                }
7867            }
7868            break;
7869        }
7870    }
7871    return mEffectChains.size();
7872}
7873
7874status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7875        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
7876{
7877    Mutex::Autolock _l(mLock);
7878    return attachAuxEffect_l(track, EffectId);
7879}
7880
7881status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7882        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
7883{
7884    status_t status = NO_ERROR;
7885
7886    if (EffectId == 0) {
7887        track->setAuxBuffer(0, NULL);
7888    } else {
7889        // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7890        sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
7891        if (effect != 0) {
7892            if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7893                track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7894            } else {
7895                status = INVALID_OPERATION;
7896            }
7897        } else {
7898            status = BAD_VALUE;
7899        }
7900    }
7901    return status;
7902}
7903
7904void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7905{
7906    for (size_t i = 0; i < mTracks.size(); ++i) {
7907        sp<Track> track = mTracks[i];
7908        if (track->auxEffectId() == effectId) {
7909            attachAuxEffect_l(track, 0);
7910        }
7911    }
7912}
7913
7914status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7915{
7916    // only one chain per input thread
7917    if (mEffectChains.size() != 0) {
7918        return INVALID_OPERATION;
7919    }
7920    ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
7921
7922    chain->setInBuffer(NULL);
7923    chain->setOutBuffer(NULL);
7924
7925    checkSuspendOnAddEffectChain_l(chain);
7926
7927    mEffectChains.add(chain);
7928
7929    return NO_ERROR;
7930}
7931
7932size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7933{
7934    ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7935    ALOGW_IF(mEffectChains.size() != 1,
7936            "removeEffectChain_l() %p invalid chain size %d on thread %p",
7937            chain.get(), mEffectChains.size(), this);
7938    if (mEffectChains.size() == 1) {
7939        mEffectChains.removeAt(0);
7940    }
7941    return 0;
7942}
7943
7944// ----------------------------------------------------------------------------
7945//  EffectModule implementation
7946// ----------------------------------------------------------------------------
7947
7948#undef LOG_TAG
7949#define LOG_TAG "AudioFlinger::EffectModule"
7950
7951AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
7952                                        const wp<AudioFlinger::EffectChain>& chain,
7953                                        effect_descriptor_t *desc,
7954                                        int id,
7955                                        int sessionId)
7956    : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
7957      mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
7958      // mDescriptor is set below
7959      // mConfig is set by configure() and not used before then
7960      mEffectInterface(NULL),
7961      mStatus(NO_INIT), mState(IDLE),
7962      // mMaxDisableWaitCnt is set by configure() and not used before then
7963      // mDisableWaitCnt is set by process() and updateState() and not used before then
7964      mSuspended(false)
7965{
7966    ALOGV("Constructor %p", this);
7967    int lStatus;
7968    if (thread == NULL) {
7969        return;
7970    }
7971
7972    memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7973
7974    // create effect engine from effect factory
7975    mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
7976
7977    if (mStatus != NO_ERROR) {
7978        return;
7979    }
7980    lStatus = init();
7981    if (lStatus < 0) {
7982        mStatus = lStatus;
7983        goto Error;
7984    }
7985
7986    ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
7987    return;
7988Error:
7989    EffectRelease(mEffectInterface);
7990    mEffectInterface = NULL;
7991    ALOGV("Constructor Error %d", mStatus);
7992}
7993
7994AudioFlinger::EffectModule::~EffectModule()
7995{
7996    ALOGV("Destructor %p", this);
7997    if (mEffectInterface != NULL) {
7998        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7999                (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8000            sp<ThreadBase> thread = mThread.promote();
8001            if (thread != 0) {
8002                audio_stream_t *stream = thread->stream();
8003                if (stream != NULL) {
8004                    stream->remove_audio_effect(stream, mEffectInterface);
8005                }
8006            }
8007        }
8008        // release effect engine
8009        EffectRelease(mEffectInterface);
8010    }
8011}
8012
8013status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
8014{
8015    status_t status;
8016
8017    Mutex::Autolock _l(mLock);
8018    int priority = handle->priority();
8019    size_t size = mHandles.size();
8020    EffectHandle *controlHandle = NULL;
8021    size_t i;
8022    for (i = 0; i < size; i++) {
8023        EffectHandle *h = mHandles[i];
8024        if (h == NULL || h->destroyed_l()) continue;
8025        // first non destroyed handle is considered in control
8026        if (controlHandle == NULL)
8027            controlHandle = h;
8028        if (h->priority() <= priority) break;
8029    }
8030    // if inserted in first place, move effect control from previous owner to this handle
8031    if (i == 0) {
8032        bool enabled = false;
8033        if (controlHandle != NULL) {
8034            enabled = controlHandle->enabled();
8035            controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
8036        }
8037        handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
8038        status = NO_ERROR;
8039    } else {
8040        status = ALREADY_EXISTS;
8041    }
8042    ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
8043    mHandles.insertAt(handle, i);
8044    return status;
8045}
8046
8047size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
8048{
8049    Mutex::Autolock _l(mLock);
8050    size_t size = mHandles.size();
8051    size_t i;
8052    for (i = 0; i < size; i++) {
8053        if (mHandles[i] == handle) break;
8054    }
8055    if (i == size) {
8056        return size;
8057    }
8058    ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
8059
8060    mHandles.removeAt(i);
8061    // if removed from first place, move effect control from this handle to next in line
8062    if (i == 0) {
8063        EffectHandle *h = controlHandle_l();
8064        if (h != NULL) {
8065            h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
8066        }
8067    }
8068
8069    // Prevent calls to process() and other functions on effect interface from now on.
8070    // The effect engine will be released by the destructor when the last strong reference on
8071    // this object is released which can happen after next process is called.
8072    if (mHandles.size() == 0 && !mPinned) {
8073        mState = DESTROYED;
8074    }
8075
8076    return size;
8077}
8078
8079// must be called with EffectModule::mLock held
8080AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
8081{
8082    // the first valid handle in the list has control over the module
8083    for (size_t i = 0; i < mHandles.size(); i++) {
8084        EffectHandle *h = mHandles[i];
8085        if (h != NULL && !h->destroyed_l()) {
8086            return h;
8087        }
8088    }
8089
8090    return NULL;
8091}
8092
8093size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
8094{
8095    ALOGV("disconnect() %p handle %p", this, handle);
8096    // keep a strong reference on this EffectModule to avoid calling the
8097    // destructor before we exit
8098    sp<EffectModule> keep(this);
8099    {
8100        sp<ThreadBase> thread = mThread.promote();
8101        if (thread != 0) {
8102            thread->disconnectEffect(keep, handle, unpinIfLast);
8103        }
8104    }
8105    return mHandles.size();
8106}
8107
8108void AudioFlinger::EffectModule::updateState() {
8109    Mutex::Autolock _l(mLock);
8110
8111    switch (mState) {
8112    case RESTART:
8113        reset_l();
8114        // FALL THROUGH
8115
8116    case STARTING:
8117        // clear auxiliary effect input buffer for next accumulation
8118        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8119            memset(mConfig.inputCfg.buffer.raw,
8120                   0,
8121                   mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8122        }
8123        start_l();
8124        mState = ACTIVE;
8125        break;
8126    case STOPPING:
8127        stop_l();
8128        mDisableWaitCnt = mMaxDisableWaitCnt;
8129        mState = STOPPED;
8130        break;
8131    case STOPPED:
8132        // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8133        // turn off sequence.
8134        if (--mDisableWaitCnt == 0) {
8135            reset_l();
8136            mState = IDLE;
8137        }
8138        break;
8139    default: //IDLE , ACTIVE, DESTROYED
8140        break;
8141    }
8142}
8143
8144void AudioFlinger::EffectModule::process()
8145{
8146    Mutex::Autolock _l(mLock);
8147
8148    if (mState == DESTROYED || mEffectInterface == NULL ||
8149            mConfig.inputCfg.buffer.raw == NULL ||
8150            mConfig.outputCfg.buffer.raw == NULL) {
8151        return;
8152    }
8153
8154    if (isProcessEnabled()) {
8155        // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8156        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8157            ditherAndClamp(mConfig.inputCfg.buffer.s32,
8158                                        mConfig.inputCfg.buffer.s32,
8159                                        mConfig.inputCfg.buffer.frameCount/2);
8160        }
8161
8162        // do the actual processing in the effect engine
8163        int ret = (*mEffectInterface)->process(mEffectInterface,
8164                                               &mConfig.inputCfg.buffer,
8165                                               &mConfig.outputCfg.buffer);
8166
8167        // force transition to IDLE state when engine is ready
8168        if (mState == STOPPED && ret == -ENODATA) {
8169            mDisableWaitCnt = 1;
8170        }
8171
8172        // clear auxiliary effect input buffer for next accumulation
8173        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8174            memset(mConfig.inputCfg.buffer.raw, 0,
8175                   mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8176        }
8177    } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
8178                mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8179        // If an insert effect is idle and input buffer is different from output buffer,
8180        // accumulate input onto output
8181        sp<EffectChain> chain = mChain.promote();
8182        if (chain != 0 && chain->activeTrackCnt() != 0) {
8183            size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2;  //always stereo here
8184            int16_t *in = mConfig.inputCfg.buffer.s16;
8185            int16_t *out = mConfig.outputCfg.buffer.s16;
8186            for (size_t i = 0; i < frameCnt; i++) {
8187                out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
8188            }
8189        }
8190    }
8191}
8192
8193void AudioFlinger::EffectModule::reset_l()
8194{
8195    if (mEffectInterface == NULL) {
8196        return;
8197    }
8198    (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8199}
8200
8201status_t AudioFlinger::EffectModule::configure()
8202{
8203    if (mEffectInterface == NULL) {
8204        return NO_INIT;
8205    }
8206
8207    sp<ThreadBase> thread = mThread.promote();
8208    if (thread == 0) {
8209        return DEAD_OBJECT;
8210    }
8211
8212    // TODO: handle configuration of effects replacing track process
8213    audio_channel_mask_t channelMask = thread->channelMask();
8214
8215    if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8216        mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
8217    } else {
8218        mConfig.inputCfg.channels = channelMask;
8219    }
8220    mConfig.outputCfg.channels = channelMask;
8221    mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8222    mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8223    mConfig.inputCfg.samplingRate = thread->sampleRate();
8224    mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8225    mConfig.inputCfg.bufferProvider.cookie = NULL;
8226    mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8227    mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8228    mConfig.outputCfg.bufferProvider.cookie = NULL;
8229    mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8230    mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8231    mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8232    // Insert effect:
8233    // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
8234    // always overwrites output buffer: input buffer == output buffer
8235    // - in other sessions:
8236    //      last effect in the chain accumulates in output buffer: input buffer != output buffer
8237    //      other effect: overwrites output buffer: input buffer == output buffer
8238    // Auxiliary effect:
8239    //      accumulates in output buffer: input buffer != output buffer
8240    // Therefore: accumulate <=> input buffer != output buffer
8241    if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8242        mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8243    } else {
8244        mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8245    }
8246    mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8247    mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8248    mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8249    mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8250
8251    ALOGV("configure() %p thread %p buffer %p framecount %d",
8252            this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8253
8254    status_t cmdStatus;
8255    uint32_t size = sizeof(int);
8256    status_t status = (*mEffectInterface)->command(mEffectInterface,
8257                                                   EFFECT_CMD_SET_CONFIG,
8258                                                   sizeof(effect_config_t),
8259                                                   &mConfig,
8260                                                   &size,
8261                                                   &cmdStatus);
8262    if (status == 0) {
8263        status = cmdStatus;
8264    }
8265
8266    if (status == 0 &&
8267            (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8268        uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8269        effect_param_t *p = (effect_param_t *)buf32;
8270
8271        p->psize = sizeof(uint32_t);
8272        p->vsize = sizeof(uint32_t);
8273        size = sizeof(int);
8274        *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8275
8276        uint32_t latency = 0;
8277        PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8278        if (pbt != NULL) {
8279            latency = pbt->latency_l();
8280        }
8281
8282        *((int32_t *)p->data + 1)= latency;
8283        (*mEffectInterface)->command(mEffectInterface,
8284                                     EFFECT_CMD_SET_PARAM,
8285                                     sizeof(effect_param_t) + 8,
8286                                     &buf32,
8287                                     &size,
8288                                     &cmdStatus);
8289    }
8290
8291    mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8292            (1000 * mConfig.outputCfg.buffer.frameCount);
8293
8294    return status;
8295}
8296
8297status_t AudioFlinger::EffectModule::init()
8298{
8299    Mutex::Autolock _l(mLock);
8300    if (mEffectInterface == NULL) {
8301        return NO_INIT;
8302    }
8303    status_t cmdStatus;
8304    uint32_t size = sizeof(status_t);
8305    status_t status = (*mEffectInterface)->command(mEffectInterface,
8306                                                   EFFECT_CMD_INIT,
8307                                                   0,
8308                                                   NULL,
8309                                                   &size,
8310                                                   &cmdStatus);
8311    if (status == 0) {
8312        status = cmdStatus;
8313    }
8314    return status;
8315}
8316
8317status_t AudioFlinger::EffectModule::start()
8318{
8319    Mutex::Autolock _l(mLock);
8320    return start_l();
8321}
8322
8323status_t AudioFlinger::EffectModule::start_l()
8324{
8325    if (mEffectInterface == NULL) {
8326        return NO_INIT;
8327    }
8328    status_t cmdStatus;
8329    uint32_t size = sizeof(status_t);
8330    status_t status = (*mEffectInterface)->command(mEffectInterface,
8331                                                   EFFECT_CMD_ENABLE,
8332                                                   0,
8333                                                   NULL,
8334                                                   &size,
8335                                                   &cmdStatus);
8336    if (status == 0) {
8337        status = cmdStatus;
8338    }
8339    if (status == 0 &&
8340            ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8341             (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8342        sp<ThreadBase> thread = mThread.promote();
8343        if (thread != 0) {
8344            audio_stream_t *stream = thread->stream();
8345            if (stream != NULL) {
8346                stream->add_audio_effect(stream, mEffectInterface);
8347            }
8348        }
8349    }
8350    return status;
8351}
8352
8353status_t AudioFlinger::EffectModule::stop()
8354{
8355    Mutex::Autolock _l(mLock);
8356    return stop_l();
8357}
8358
8359status_t AudioFlinger::EffectModule::stop_l()
8360{
8361    if (mEffectInterface == NULL) {
8362        return NO_INIT;
8363    }
8364    status_t cmdStatus;
8365    uint32_t size = sizeof(status_t);
8366    status_t status = (*mEffectInterface)->command(mEffectInterface,
8367                                                   EFFECT_CMD_DISABLE,
8368                                                   0,
8369                                                   NULL,
8370                                                   &size,
8371                                                   &cmdStatus);
8372    if (status == 0) {
8373        status = cmdStatus;
8374    }
8375    if (status == 0 &&
8376            ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8377             (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8378        sp<ThreadBase> thread = mThread.promote();
8379        if (thread != 0) {
8380            audio_stream_t *stream = thread->stream();
8381            if (stream != NULL) {
8382                stream->remove_audio_effect(stream, mEffectInterface);
8383            }
8384        }
8385    }
8386    return status;
8387}
8388
8389status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8390                                             uint32_t cmdSize,
8391                                             void *pCmdData,
8392                                             uint32_t *replySize,
8393                                             void *pReplyData)
8394{
8395    Mutex::Autolock _l(mLock);
8396//    ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
8397
8398    if (mState == DESTROYED || mEffectInterface == NULL) {
8399        return NO_INIT;
8400    }
8401    status_t status = (*mEffectInterface)->command(mEffectInterface,
8402                                                   cmdCode,
8403                                                   cmdSize,
8404                                                   pCmdData,
8405                                                   replySize,
8406                                                   pReplyData);
8407    if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
8408        uint32_t size = (replySize == NULL) ? 0 : *replySize;
8409        for (size_t i = 1; i < mHandles.size(); i++) {
8410            EffectHandle *h = mHandles[i];
8411            if (h != NULL && !h->destroyed_l()) {
8412                h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8413            }
8414        }
8415    }
8416    return status;
8417}
8418
8419status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8420{
8421    Mutex::Autolock _l(mLock);
8422    return setEnabled_l(enabled);
8423}
8424
8425// must be called with EffectModule::mLock held
8426status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8427{
8428
8429    ALOGV("setEnabled %p enabled %d", this, enabled);
8430
8431    if (enabled != isEnabled()) {
8432        status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8433        if (enabled && status != NO_ERROR) {
8434            return status;
8435        }
8436
8437        switch (mState) {
8438        // going from disabled to enabled
8439        case IDLE:
8440            mState = STARTING;
8441            break;
8442        case STOPPED:
8443            mState = RESTART;
8444            break;
8445        case STOPPING:
8446            mState = ACTIVE;
8447            break;
8448
8449        // going from enabled to disabled
8450        case RESTART:
8451            mState = STOPPED;
8452            break;
8453        case STARTING:
8454            mState = IDLE;
8455            break;
8456        case ACTIVE:
8457            mState = STOPPING;
8458            break;
8459        case DESTROYED:
8460            return NO_ERROR; // simply ignore as we are being destroyed
8461        }
8462        for (size_t i = 1; i < mHandles.size(); i++) {
8463            EffectHandle *h = mHandles[i];
8464            if (h != NULL && !h->destroyed_l()) {
8465                h->setEnabled(enabled);
8466            }
8467        }
8468    }
8469    return NO_ERROR;
8470}
8471
8472bool AudioFlinger::EffectModule::isEnabled() const
8473{
8474    switch (mState) {
8475    case RESTART:
8476    case STARTING:
8477    case ACTIVE:
8478        return true;
8479    case IDLE:
8480    case STOPPING:
8481    case STOPPED:
8482    case DESTROYED:
8483    default:
8484        return false;
8485    }
8486}
8487
8488bool AudioFlinger::EffectModule::isProcessEnabled() const
8489{
8490    switch (mState) {
8491    case RESTART:
8492    case ACTIVE:
8493    case STOPPING:
8494    case STOPPED:
8495        return true;
8496    case IDLE:
8497    case STARTING:
8498    case DESTROYED:
8499    default:
8500        return false;
8501    }
8502}
8503
8504status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8505{
8506    Mutex::Autolock _l(mLock);
8507    status_t status = NO_ERROR;
8508
8509    // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8510    // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
8511    if (isProcessEnabled() &&
8512            ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8513            (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
8514        status_t cmdStatus;
8515        uint32_t volume[2];
8516        uint32_t *pVolume = NULL;
8517        uint32_t size = sizeof(volume);
8518        volume[0] = *left;
8519        volume[1] = *right;
8520        if (controller) {
8521            pVolume = volume;
8522        }
8523        status = (*mEffectInterface)->command(mEffectInterface,
8524                                              EFFECT_CMD_SET_VOLUME,
8525                                              size,
8526                                              volume,
8527                                              &size,
8528                                              pVolume);
8529        if (controller && status == NO_ERROR && size == sizeof(volume)) {
8530            *left = volume[0];
8531            *right = volume[1];
8532        }
8533    }
8534    return status;
8535}
8536
8537status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8538{
8539    Mutex::Autolock _l(mLock);
8540    status_t status = NO_ERROR;
8541    if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8542        // audio pre processing modules on RecordThread can receive both output and
8543        // input device indication in the same call
8544        uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8545        if (dev) {
8546            status_t cmdStatus;
8547            uint32_t size = sizeof(status_t);
8548
8549            status = (*mEffectInterface)->command(mEffectInterface,
8550                                                  EFFECT_CMD_SET_DEVICE,
8551                                                  sizeof(uint32_t),
8552                                                  &dev,
8553                                                  &size,
8554                                                  &cmdStatus);
8555            if (status == NO_ERROR) {
8556                status = cmdStatus;
8557            }
8558        }
8559        dev = device & AUDIO_DEVICE_IN_ALL;
8560        if (dev) {
8561            status_t cmdStatus;
8562            uint32_t size = sizeof(status_t);
8563
8564            status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8565                                                  EFFECT_CMD_SET_INPUT_DEVICE,
8566                                                  sizeof(uint32_t),
8567                                                  &dev,
8568                                                  &size,
8569                                                  &cmdStatus);
8570            if (status2 == NO_ERROR) {
8571                status2 = cmdStatus;
8572            }
8573            if (status == NO_ERROR) {
8574                status = status2;
8575            }
8576        }
8577    }
8578    return status;
8579}
8580
8581status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
8582{
8583    Mutex::Autolock _l(mLock);
8584    status_t status = NO_ERROR;
8585    if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
8586        status_t cmdStatus;
8587        uint32_t size = sizeof(status_t);
8588        status = (*mEffectInterface)->command(mEffectInterface,
8589                                              EFFECT_CMD_SET_AUDIO_MODE,
8590                                              sizeof(audio_mode_t),
8591                                              &mode,
8592                                              &size,
8593                                              &cmdStatus);
8594        if (status == NO_ERROR) {
8595            status = cmdStatus;
8596        }
8597    }
8598    return status;
8599}
8600
8601void AudioFlinger::EffectModule::setSuspended(bool suspended)
8602{
8603    Mutex::Autolock _l(mLock);
8604    mSuspended = suspended;
8605}
8606
8607bool AudioFlinger::EffectModule::suspended() const
8608{
8609    Mutex::Autolock _l(mLock);
8610    return mSuspended;
8611}
8612
8613bool AudioFlinger::EffectModule::purgeHandles()
8614{
8615    bool enabled = false;
8616    Mutex::Autolock _l(mLock);
8617    for (size_t i = 0; i < mHandles.size(); i++) {
8618        EffectHandle *handle = mHandles[i];
8619        if (handle != NULL && !handle->destroyed_l()) {
8620            handle->effect().clear();
8621            if (handle->hasControl()) {
8622                enabled = handle->enabled();
8623            }
8624        }
8625    }
8626    return enabled;
8627}
8628
8629status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8630{
8631    const size_t SIZE = 256;
8632    char buffer[SIZE];
8633    String8 result;
8634
8635    snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8636    result.append(buffer);
8637
8638    bool locked = tryLock(mLock);
8639    // failed to lock - AudioFlinger is probably deadlocked
8640    if (!locked) {
8641        result.append("\t\tCould not lock Fx mutex:\n");
8642    }
8643
8644    result.append("\t\tSession Status State Engine:\n");
8645    snprintf(buffer, SIZE, "\t\t%05d   %03d    %03d   0x%08x\n",
8646            mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8647    result.append(buffer);
8648
8649    result.append("\t\tDescriptor:\n");
8650    snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8651            mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8652            mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8653            mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8654    result.append(buffer);
8655    snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8656                mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8657                mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8658                mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8659    result.append(buffer);
8660    snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
8661            mDescriptor.apiVersion,
8662            mDescriptor.flags);
8663    result.append(buffer);
8664    snprintf(buffer, SIZE, "\t\t- name: %s\n",
8665            mDescriptor.name);
8666    result.append(buffer);
8667    snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8668            mDescriptor.implementor);
8669    result.append(buffer);
8670
8671    result.append("\t\t- Input configuration:\n");
8672    result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
8673    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
8674            (uint32_t)mConfig.inputCfg.buffer.raw,
8675            mConfig.inputCfg.buffer.frameCount,
8676            mConfig.inputCfg.samplingRate,
8677            mConfig.inputCfg.channels,
8678            mConfig.inputCfg.format);
8679    result.append(buffer);
8680
8681    result.append("\t\t- Output configuration:\n");
8682    result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
8683    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
8684            (uint32_t)mConfig.outputCfg.buffer.raw,
8685            mConfig.outputCfg.buffer.frameCount,
8686            mConfig.outputCfg.samplingRate,
8687            mConfig.outputCfg.channels,
8688            mConfig.outputCfg.format);
8689    result.append(buffer);
8690
8691    snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8692    result.append(buffer);
8693    result.append("\t\t\tPid   Priority Ctrl Locked client server\n");
8694    for (size_t i = 0; i < mHandles.size(); ++i) {
8695        EffectHandle *handle = mHandles[i];
8696        if (handle != NULL && !handle->destroyed_l()) {
8697            handle->dump(buffer, SIZE);
8698            result.append(buffer);
8699        }
8700    }
8701
8702    result.append("\n");
8703
8704    write(fd, result.string(), result.length());
8705
8706    if (locked) {
8707        mLock.unlock();
8708    }
8709
8710    return NO_ERROR;
8711}
8712
8713// ----------------------------------------------------------------------------
8714//  EffectHandle implementation
8715// ----------------------------------------------------------------------------
8716
8717#undef LOG_TAG
8718#define LOG_TAG "AudioFlinger::EffectHandle"
8719
8720AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8721                                        const sp<AudioFlinger::Client>& client,
8722                                        const sp<IEffectClient>& effectClient,
8723                                        int32_t priority)
8724    : BnEffect(),
8725    mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
8726    mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
8727{
8728    ALOGV("constructor %p", this);
8729
8730    if (client == 0) {
8731        return;
8732    }
8733    int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8734    mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8735    if (mCblkMemory != 0) {
8736        mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8737
8738        if (mCblk != NULL) {
8739            new(mCblk) effect_param_cblk_t();
8740            mBuffer = (uint8_t *)mCblk + bufOffset;
8741        }
8742    } else {
8743        ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
8744        return;
8745    }
8746}
8747
8748AudioFlinger::EffectHandle::~EffectHandle()
8749{
8750    ALOGV("Destructor %p", this);
8751
8752    if (mEffect == 0) {
8753        mDestroyed = true;
8754        return;
8755    }
8756    mEffect->lock();
8757    mDestroyed = true;
8758    mEffect->unlock();
8759    disconnect(false);
8760}
8761
8762status_t AudioFlinger::EffectHandle::enable()
8763{
8764    ALOGV("enable %p", this);
8765    if (!mHasControl) return INVALID_OPERATION;
8766    if (mEffect == 0) return DEAD_OBJECT;
8767
8768    if (mEnabled) {
8769        return NO_ERROR;
8770    }
8771
8772    mEnabled = true;
8773
8774    sp<ThreadBase> thread = mEffect->thread().promote();
8775    if (thread != 0) {
8776        thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8777    }
8778
8779    // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8780    if (mEffect->suspended()) {
8781        return NO_ERROR;
8782    }
8783
8784    status_t status = mEffect->setEnabled(true);
8785    if (status != NO_ERROR) {
8786        if (thread != 0) {
8787            thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8788        }
8789        mEnabled = false;
8790    }
8791    return status;
8792}
8793
8794status_t AudioFlinger::EffectHandle::disable()
8795{
8796    ALOGV("disable %p", this);
8797    if (!mHasControl) return INVALID_OPERATION;
8798    if (mEffect == 0) return DEAD_OBJECT;
8799
8800    if (!mEnabled) {
8801        return NO_ERROR;
8802    }
8803    mEnabled = false;
8804
8805    if (mEffect->suspended()) {
8806        return NO_ERROR;
8807    }
8808
8809    status_t status = mEffect->setEnabled(false);
8810
8811    sp<ThreadBase> thread = mEffect->thread().promote();
8812    if (thread != 0) {
8813        thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8814    }
8815
8816    return status;
8817}
8818
8819void AudioFlinger::EffectHandle::disconnect()
8820{
8821    disconnect(true);
8822}
8823
8824void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
8825{
8826    ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
8827    if (mEffect == 0) {
8828        return;
8829    }
8830    // restore suspended effects if the disconnected handle was enabled and the last one.
8831    if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
8832        sp<ThreadBase> thread = mEffect->thread().promote();
8833        if (thread != 0) {
8834            thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8835        }
8836    }
8837
8838    // release sp on module => module destructor can be called now
8839    mEffect.clear();
8840    if (mClient != 0) {
8841        if (mCblk != NULL) {
8842            // unlike ~TrackBase(), mCblk is never a local new, so don't delete
8843            mCblk->~effect_param_cblk_t();   // destroy our shared-structure.
8844        }
8845        mCblkMemory.clear();    // free the shared memory before releasing the heap it belongs to
8846        // Client destructor must run with AudioFlinger mutex locked
8847        Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8848        mClient.clear();
8849    }
8850}
8851
8852status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8853                                             uint32_t cmdSize,
8854                                             void *pCmdData,
8855                                             uint32_t *replySize,
8856                                             void *pReplyData)
8857{
8858//    ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
8859//              cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
8860
8861    // only get parameter command is permitted for applications not controlling the effect
8862    if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8863        return INVALID_OPERATION;
8864    }
8865    if (mEffect == 0) return DEAD_OBJECT;
8866    if (mClient == 0) return INVALID_OPERATION;
8867
8868    // handle commands that are not forwarded transparently to effect engine
8869    if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8870        // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8871        // no risk to block the whole media server process or mixer threads is we are stuck here
8872        Mutex::Autolock _l(mCblk->lock);
8873        if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8874            mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8875            mCblk->serverIndex = 0;
8876            mCblk->clientIndex = 0;
8877            return BAD_VALUE;
8878        }
8879        status_t status = NO_ERROR;
8880        while (mCblk->serverIndex < mCblk->clientIndex) {
8881            int reply;
8882            uint32_t rsize = sizeof(int);
8883            int *p = (int *)(mBuffer + mCblk->serverIndex);
8884            int size = *p++;
8885            if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
8886                ALOGW("command(): invalid parameter block size");
8887                break;
8888            }
8889            effect_param_t *param = (effect_param_t *)p;
8890            if (param->psize == 0 || param->vsize == 0) {
8891                ALOGW("command(): null parameter or value size");
8892                mCblk->serverIndex += size;
8893                continue;
8894            }
8895            uint32_t psize = sizeof(effect_param_t) +
8896                             ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8897                             param->vsize;
8898            status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8899                                            psize,
8900                                            p,
8901                                            &rsize,
8902                                            &reply);
8903            // stop at first error encountered
8904            if (ret != NO_ERROR) {
8905                status = ret;
8906                *(int *)pReplyData = reply;
8907                break;
8908            } else if (reply != NO_ERROR) {
8909                *(int *)pReplyData = reply;
8910                break;
8911            }
8912            mCblk->serverIndex += size;
8913        }
8914        mCblk->serverIndex = 0;
8915        mCblk->clientIndex = 0;
8916        return status;
8917    } else if (cmdCode == EFFECT_CMD_ENABLE) {
8918        *(int *)pReplyData = NO_ERROR;
8919        return enable();
8920    } else if (cmdCode == EFFECT_CMD_DISABLE) {
8921        *(int *)pReplyData = NO_ERROR;
8922        return disable();
8923    }
8924
8925    return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8926}
8927
8928void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
8929{
8930    ALOGV("setControl %p control %d", this, hasControl);
8931
8932    mHasControl = hasControl;
8933    mEnabled = enabled;
8934
8935    if (signal && mEffectClient != 0) {
8936        mEffectClient->controlStatusChanged(hasControl);
8937    }
8938}
8939
8940void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8941                                                 uint32_t cmdSize,
8942                                                 void *pCmdData,
8943                                                 uint32_t replySize,
8944                                                 void *pReplyData)
8945{
8946    if (mEffectClient != 0) {
8947        mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8948    }
8949}
8950
8951
8952
8953void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8954{
8955    if (mEffectClient != 0) {
8956        mEffectClient->enableStatusChanged(enabled);
8957    }
8958}
8959
8960status_t AudioFlinger::EffectHandle::onTransact(
8961    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8962{
8963    return BnEffect::onTransact(code, data, reply, flags);
8964}
8965
8966
8967void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8968{
8969    bool locked = mCblk != NULL && tryLock(mCblk->lock);
8970
8971    snprintf(buffer, size, "\t\t\t%05d %05d    %01u    %01u      %05u  %05u\n",
8972            (mClient == 0) ? getpid_cached : mClient->pid(),
8973            mPriority,
8974            mHasControl,
8975            !locked,
8976            mCblk ? mCblk->clientIndex : 0,
8977            mCblk ? mCblk->serverIndex : 0
8978            );
8979
8980    if (locked) {
8981        mCblk->lock.unlock();
8982    }
8983}
8984
8985#undef LOG_TAG
8986#define LOG_TAG "AudioFlinger::EffectChain"
8987
8988AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
8989                                        int sessionId)
8990    : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
8991      mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8992      mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
8993{
8994    mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
8995    if (thread == NULL) {
8996        return;
8997    }
8998    mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8999                                    thread->frameCount();
9000}
9001
9002AudioFlinger::EffectChain::~EffectChain()
9003{
9004    if (mOwnInBuffer) {
9005        delete mInBuffer;
9006    }
9007
9008}
9009
9010// getEffectFromDesc_l() must be called with ThreadBase::mLock held
9011sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
9012{
9013    size_t size = mEffects.size();
9014
9015    for (size_t i = 0; i < size; i++) {
9016        if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
9017            return mEffects[i];
9018        }
9019    }
9020    return 0;
9021}
9022
9023// getEffectFromId_l() must be called with ThreadBase::mLock held
9024sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
9025{
9026    size_t size = mEffects.size();
9027
9028    for (size_t i = 0; i < size; i++) {
9029        // by convention, return first effect if id provided is 0 (0 is never a valid id)
9030        if (id == 0 || mEffects[i]->id() == id) {
9031            return mEffects[i];
9032        }
9033    }
9034    return 0;
9035}
9036
9037// getEffectFromType_l() must be called with ThreadBase::mLock held
9038sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9039        const effect_uuid_t *type)
9040{
9041    size_t size = mEffects.size();
9042
9043    for (size_t i = 0; i < size; i++) {
9044        if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
9045            return mEffects[i];
9046        }
9047    }
9048    return 0;
9049}
9050
9051void AudioFlinger::EffectChain::clearInputBuffer()
9052{
9053    Mutex::Autolock _l(mLock);
9054    sp<ThreadBase> thread = mThread.promote();
9055    if (thread == 0) {
9056        ALOGW("clearInputBuffer(): cannot promote mixer thread");
9057        return;
9058    }
9059    clearInputBuffer_l(thread);
9060}
9061
9062// Must be called with EffectChain::mLock locked
9063void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9064{
9065    size_t numSamples = thread->frameCount() * thread->channelCount();
9066    memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9067
9068}
9069
9070// Must be called with EffectChain::mLock locked
9071void AudioFlinger::EffectChain::process_l()
9072{
9073    sp<ThreadBase> thread = mThread.promote();
9074    if (thread == 0) {
9075        ALOGW("process_l(): cannot promote mixer thread");
9076        return;
9077    }
9078    bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9079            (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
9080    // always process effects unless no more tracks are on the session and the effect tail
9081    // has been rendered
9082    bool doProcess = true;
9083    if (!isGlobalSession) {
9084        bool tracksOnSession = (trackCnt() != 0);
9085
9086        if (!tracksOnSession && mTailBufferCount == 0) {
9087            doProcess = false;
9088        }
9089
9090        if (activeTrackCnt() == 0) {
9091            // if no track is active and the effect tail has not been rendered,
9092            // the input buffer must be cleared here as the mixer process will not do it
9093            if (tracksOnSession || mTailBufferCount > 0) {
9094                clearInputBuffer_l(thread);
9095                if (mTailBufferCount > 0) {
9096                    mTailBufferCount--;
9097                }
9098            }
9099        }
9100    }
9101
9102    size_t size = mEffects.size();
9103    if (doProcess) {
9104        for (size_t i = 0; i < size; i++) {
9105            mEffects[i]->process();
9106        }
9107    }
9108    for (size_t i = 0; i < size; i++) {
9109        mEffects[i]->updateState();
9110    }
9111}
9112
9113// addEffect_l() must be called with PlaybackThread::mLock held
9114status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
9115{
9116    effect_descriptor_t desc = effect->desc();
9117    uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9118
9119    Mutex::Autolock _l(mLock);
9120    effect->setChain(this);
9121    sp<ThreadBase> thread = mThread.promote();
9122    if (thread == 0) {
9123        return NO_INIT;
9124    }
9125    effect->setThread(thread);
9126
9127    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9128        // Auxiliary effects are inserted at the beginning of mEffects vector as
9129        // they are processed first and accumulated in chain input buffer
9130        mEffects.insertAt(effect, 0);
9131
9132        // the input buffer for auxiliary effect contains mono samples in
9133        // 32 bit format. This is to avoid saturation in AudoMixer
9134        // accumulation stage. Saturation is done in EffectModule::process() before
9135        // calling the process in effect engine
9136        size_t numSamples = thread->frameCount();
9137        int32_t *buffer = new int32_t[numSamples];
9138        memset(buffer, 0, numSamples * sizeof(int32_t));
9139        effect->setInBuffer((int16_t *)buffer);
9140        // auxiliary effects output samples to chain input buffer for further processing
9141        // by insert effects
9142        effect->setOutBuffer(mInBuffer);
9143    } else {
9144        // Insert effects are inserted at the end of mEffects vector as they are processed
9145        //  after track and auxiliary effects.
9146        // Insert effect order as a function of indicated preference:
9147        //  if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9148        //  another effect is present
9149        //  else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9150        //  last effect claiming first position
9151        //  else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9152        //  first effect claiming last position
9153        //  else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9154        // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9155        // already present
9156
9157        size_t size = mEffects.size();
9158        size_t idx_insert = size;
9159        ssize_t idx_insert_first = -1;
9160        ssize_t idx_insert_last = -1;
9161
9162        for (size_t i = 0; i < size; i++) {
9163            effect_descriptor_t d = mEffects[i]->desc();
9164            uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9165            uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9166            if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9167                // check invalid effect chaining combinations
9168                if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9169                    iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
9170                    ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
9171                    return INVALID_OPERATION;
9172                }
9173                // remember position of first insert effect and by default
9174                // select this as insert position for new effect
9175                if (idx_insert == size) {
9176                    idx_insert = i;
9177                }
9178                // remember position of last insert effect claiming
9179                // first position
9180                if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9181                    idx_insert_first = i;
9182                }
9183                // remember position of first insert effect claiming
9184                // last position
9185                if (iPref == EFFECT_FLAG_INSERT_LAST &&
9186                    idx_insert_last == -1) {
9187                    idx_insert_last = i;
9188                }
9189            }
9190        }
9191
9192        // modify idx_insert from first position if needed
9193        if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9194            if (idx_insert_last != -1) {
9195                idx_insert = idx_insert_last;
9196            } else {
9197                idx_insert = size;
9198            }
9199        } else {
9200            if (idx_insert_first != -1) {
9201                idx_insert = idx_insert_first + 1;
9202            }
9203        }
9204
9205        // always read samples from chain input buffer
9206        effect->setInBuffer(mInBuffer);
9207
9208        // if last effect in the chain, output samples to chain
9209        // output buffer, otherwise to chain input buffer
9210        if (idx_insert == size) {
9211            if (idx_insert != 0) {
9212                mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9213                mEffects[idx_insert-1]->configure();
9214            }
9215            effect->setOutBuffer(mOutBuffer);
9216        } else {
9217            effect->setOutBuffer(mInBuffer);
9218        }
9219        mEffects.insertAt(effect, idx_insert);
9220
9221        ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
9222    }
9223    effect->configure();
9224    return NO_ERROR;
9225}
9226
9227// removeEffect_l() must be called with PlaybackThread::mLock held
9228size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
9229{
9230    Mutex::Autolock _l(mLock);
9231    size_t size = mEffects.size();
9232    uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9233
9234    for (size_t i = 0; i < size; i++) {
9235        if (effect == mEffects[i]) {
9236            // calling stop here will remove pre-processing effect from the audio HAL.
9237            // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9238            // the middle of a read from audio HAL
9239            if (mEffects[i]->state() == EffectModule::ACTIVE ||
9240                    mEffects[i]->state() == EffectModule::STOPPING) {
9241                mEffects[i]->stop();
9242            }
9243            if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9244                delete[] effect->inBuffer();
9245            } else {
9246                if (i == size - 1 && i != 0) {
9247                    mEffects[i - 1]->setOutBuffer(mOutBuffer);
9248                    mEffects[i - 1]->configure();
9249                }
9250            }
9251            mEffects.removeAt(i);
9252            ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
9253            break;
9254        }
9255    }
9256
9257    return mEffects.size();
9258}
9259
9260// setDevice_l() must be called with PlaybackThread::mLock held
9261void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
9262{
9263    size_t size = mEffects.size();
9264    for (size_t i = 0; i < size; i++) {
9265        mEffects[i]->setDevice(device);
9266    }
9267}
9268
9269// setMode_l() must be called with PlaybackThread::mLock held
9270void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
9271{
9272    size_t size = mEffects.size();
9273    for (size_t i = 0; i < size; i++) {
9274        mEffects[i]->setMode(mode);
9275    }
9276}
9277
9278// setVolume_l() must be called with PlaybackThread::mLock held
9279bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
9280{
9281    uint32_t newLeft = *left;
9282    uint32_t newRight = *right;
9283    bool hasControl = false;
9284    int ctrlIdx = -1;
9285    size_t size = mEffects.size();
9286
9287    // first update volume controller
9288    for (size_t i = size; i > 0; i--) {
9289        if (mEffects[i - 1]->isProcessEnabled() &&
9290            (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9291            ctrlIdx = i - 1;
9292            hasControl = true;
9293            break;
9294        }
9295    }
9296
9297    if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
9298        if (hasControl) {
9299            *left = mNewLeftVolume;
9300            *right = mNewRightVolume;
9301        }
9302        return hasControl;
9303    }
9304
9305    mVolumeCtrlIdx = ctrlIdx;
9306    mLeftVolume = newLeft;
9307    mRightVolume = newRight;
9308
9309    // second get volume update from volume controller
9310    if (ctrlIdx >= 0) {
9311        mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
9312        mNewLeftVolume = newLeft;
9313        mNewRightVolume = newRight;
9314    }
9315    // then indicate volume to all other effects in chain.
9316    // Pass altered volume to effects before volume controller
9317    // and requested volume to effects after controller
9318    uint32_t lVol = newLeft;
9319    uint32_t rVol = newRight;
9320
9321    for (size_t i = 0; i < size; i++) {
9322        if ((int)i == ctrlIdx) continue;
9323        // this also works for ctrlIdx == -1 when there is no volume controller
9324        if ((int)i > ctrlIdx) {
9325            lVol = *left;
9326            rVol = *right;
9327        }
9328        mEffects[i]->setVolume(&lVol, &rVol, false);
9329    }
9330    *left = newLeft;
9331    *right = newRight;
9332
9333    return hasControl;
9334}
9335
9336status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9337{
9338    const size_t SIZE = 256;
9339    char buffer[SIZE];
9340    String8 result;
9341
9342    snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9343    result.append(buffer);
9344
9345    bool locked = tryLock(mLock);
9346    // failed to lock - AudioFlinger is probably deadlocked
9347    if (!locked) {
9348        result.append("\tCould not lock mutex:\n");
9349    }
9350
9351    result.append("\tNum fx In buffer   Out buffer   Active tracks:\n");
9352    snprintf(buffer, SIZE, "\t%02d     0x%08x  0x%08x   %d\n",
9353            mEffects.size(),
9354            (uint32_t)mInBuffer,
9355            (uint32_t)mOutBuffer,
9356            mActiveTrackCnt);
9357    result.append(buffer);
9358    write(fd, result.string(), result.size());
9359
9360    for (size_t i = 0; i < mEffects.size(); ++i) {
9361        sp<EffectModule> effect = mEffects[i];
9362        if (effect != 0) {
9363            effect->dump(fd, args);
9364        }
9365    }
9366
9367    if (locked) {
9368        mLock.unlock();
9369    }
9370
9371    return NO_ERROR;
9372}
9373
9374// must be called with ThreadBase::mLock held
9375void AudioFlinger::EffectChain::setEffectSuspended_l(
9376        const effect_uuid_t *type, bool suspend)
9377{
9378    sp<SuspendedEffectDesc> desc;
9379    // use effect type UUID timelow as key as there is no real risk of identical
9380    // timeLow fields among effect type UUIDs.
9381    ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
9382    if (suspend) {
9383        if (index >= 0) {
9384            desc = mSuspendedEffects.valueAt(index);
9385        } else {
9386            desc = new SuspendedEffectDesc();
9387            memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9388            mSuspendedEffects.add(type->timeLow, desc);
9389            ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
9390        }
9391        if (desc->mRefCount++ == 0) {
9392            sp<EffectModule> effect = getEffectIfEnabled(type);
9393            if (effect != 0) {
9394                desc->mEffect = effect;
9395                effect->setSuspended(true);
9396                effect->setEnabled(false);
9397            }
9398        }
9399    } else {
9400        if (index < 0) {
9401            return;
9402        }
9403        desc = mSuspendedEffects.valueAt(index);
9404        if (desc->mRefCount <= 0) {
9405            ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
9406            desc->mRefCount = 1;
9407        }
9408        if (--desc->mRefCount == 0) {
9409            ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
9410            if (desc->mEffect != 0) {
9411                sp<EffectModule> effect = desc->mEffect.promote();
9412                if (effect != 0) {
9413                    effect->setSuspended(false);
9414                    effect->lock();
9415                    EffectHandle *handle = effect->controlHandle_l();
9416                    if (handle != NULL && !handle->destroyed_l()) {
9417                        effect->setEnabled_l(handle->enabled());
9418                    }
9419                    effect->unlock();
9420                }
9421                desc->mEffect.clear();
9422            }
9423            mSuspendedEffects.removeItemsAt(index);
9424        }
9425    }
9426}
9427
9428// must be called with ThreadBase::mLock held
9429void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9430{
9431    sp<SuspendedEffectDesc> desc;
9432
9433    ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9434    if (suspend) {
9435        if (index >= 0) {
9436            desc = mSuspendedEffects.valueAt(index);
9437        } else {
9438            desc = new SuspendedEffectDesc();
9439            mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
9440            ALOGV("setEffectSuspendedAll_l() add entry for 0");
9441        }
9442        if (desc->mRefCount++ == 0) {
9443            Vector< sp<EffectModule> > effects;
9444            getSuspendEligibleEffects(effects);
9445            for (size_t i = 0; i < effects.size(); i++) {
9446                setEffectSuspended_l(&effects[i]->desc().type, true);
9447            }
9448        }
9449    } else {
9450        if (index < 0) {
9451            return;
9452        }
9453        desc = mSuspendedEffects.valueAt(index);
9454        if (desc->mRefCount <= 0) {
9455            ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
9456            desc->mRefCount = 1;
9457        }
9458        if (--desc->mRefCount == 0) {
9459            Vector<const effect_uuid_t *> types;
9460            for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9461                if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9462                    continue;
9463                }
9464                types.add(&mSuspendedEffects.valueAt(i)->mType);
9465            }
9466            for (size_t i = 0; i < types.size(); i++) {
9467                setEffectSuspended_l(types[i], false);
9468            }
9469            ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
9470            mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9471        }
9472    }
9473}
9474
9475
9476// The volume effect is used for automated tests only
9477#ifndef OPENSL_ES_H_
9478static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9479                                            { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9480const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9481#endif //OPENSL_ES_H_
9482
9483bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9484{
9485    // auxiliary effects and visualizer are never suspended on output mix
9486    if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9487        (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
9488         (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9489         (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
9490        return false;
9491    }
9492    return true;
9493}
9494
9495void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
9496{
9497    effects.clear();
9498    for (size_t i = 0; i < mEffects.size(); i++) {
9499        if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9500            effects.add(mEffects[i]);
9501        }
9502    }
9503}
9504
9505sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9506                                                            const effect_uuid_t *type)
9507{
9508    sp<EffectModule> effect = getEffectFromType_l(type);
9509    return effect != 0 && effect->isEnabled() ? effect : 0;
9510}
9511
9512void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9513                                                            bool enabled)
9514{
9515    ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
9516    if (enabled) {
9517        if (index < 0) {
9518            // if the effect is not suspend check if all effects are suspended
9519            index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9520            if (index < 0) {
9521                return;
9522            }
9523            if (!isEffectEligibleForSuspend(effect->desc())) {
9524                return;
9525            }
9526            setEffectSuspended_l(&effect->desc().type, enabled);
9527            index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
9528            if (index < 0) {
9529                ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
9530                return;
9531            }
9532        }
9533        ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
9534            effect->desc().type.timeLow);
9535        sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9536        // if effect is requested to suspended but was not yet enabled, supend it now.
9537        if (desc->mEffect == 0) {
9538            desc->mEffect = effect;
9539            effect->setEnabled(false);
9540            effect->setSuspended(true);
9541        }
9542    } else {
9543        if (index < 0) {
9544            return;
9545        }
9546        ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
9547            effect->desc().type.timeLow);
9548        sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9549        desc->mEffect.clear();
9550        effect->setSuspended(false);
9551    }
9552}
9553
9554#undef LOG_TAG
9555#define LOG_TAG "AudioFlinger"
9556
9557// ----------------------------------------------------------------------------
9558
9559status_t AudioFlinger::onTransact(
9560        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9561{
9562    return BnAudioFlinger::onTransact(code, data, reply, flags);
9563}
9564
9565}; // namespace android
9566