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