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