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