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