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