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