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