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