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