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