AudioFlinger.cpp revision 300a2ee9327c05fbf9d3a5fd595b558097c7c5e8
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->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->isTerminated() || track->isStopped() || track->isPaused()) {
2994                // We have consumed all the buffers of this track.
2995                // Remove it from the list of active tracks.
2996                // TODO: use actual buffer filling status instead of latency when available from
2997                // audio HAL
2998                size_t audioHALFrames =
2999                        (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3000                size_t framesWritten =
3001                        mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3002                if (track->presentationComplete(framesWritten, audioHALFrames)) {
3003                    tracksToRemove->add(track);
3004                }
3005            } else {
3006                // No buffers for this track. Give it a few chances to
3007                // fill a buffer, then remove it from active list.
3008                if (--(track->mRetryCount) <= 0) {
3009                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
3010                    tracksToRemove->add(track);
3011                    // indicate to client process that the track was disabled because of underrun
3012                    android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
3013                // If one track is not ready, mark the mixer also not ready if:
3014                //  - the mixer was ready during previous round OR
3015                //  - no other track is ready
3016                } else if (mMixerStatus == MIXER_TRACKS_READY ||
3017                                mixerStatus != MIXER_TRACKS_READY) {
3018                    mixerStatus = MIXER_TRACKS_ENABLED;
3019                }
3020            }
3021            mAudioMixer->disable(name);
3022        }
3023
3024        }   // local variable scope to avoid goto warning
3025track_is_ready: ;
3026
3027    }
3028
3029    // FIXME Here is where we would push the new FastMixer state if necessary
3030
3031    // remove all the tracks that need to be...
3032    count = tracksToRemove->size();
3033    if (CC_UNLIKELY(count)) {
3034        for (size_t i=0 ; i<count ; i++) {
3035            const sp<Track>& track = tracksToRemove->itemAt(i);
3036            mActiveTracks.remove(track);
3037            if (track->mainBuffer() != mMixBuffer) {
3038                chain = getEffectChain_l(track->sessionId());
3039                if (chain != 0) {
3040                    ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
3041                    chain->decActiveTrackCnt();
3042                }
3043            }
3044            if (track->isTerminated()) {
3045                removeTrack_l(track);
3046            }
3047        }
3048    }
3049
3050    // mix buffer must be cleared if all tracks are connected to an
3051    // effect chain as in this case the mixer will not write to
3052    // mix buffer and track effects will accumulate into it
3053    if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3054        // FIXME as a performance optimization, should remember previous zero status
3055        memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3056    }
3057
3058    // if any fast tracks, then status is ready
3059    if (fastTracks > 0) {
3060        mixerStatus = MIXER_TRACKS_READY;
3061    }
3062    return mixerStatus;
3063}
3064
3065/*
3066The derived values that are cached:
3067 - mixBufferSize from frame count * frame size
3068 - activeSleepTime from activeSleepTimeUs()
3069 - idleSleepTime from idleSleepTimeUs()
3070 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3071 - maxPeriod from frame count and sample rate (MIXER only)
3072
3073The parameters that affect these derived values are:
3074 - frame count
3075 - frame size
3076 - sample rate
3077 - device type: A2DP or not
3078 - device latency
3079 - format: PCM or not
3080 - active sleep time
3081 - idle sleep time
3082*/
3083
3084void AudioFlinger::PlaybackThread::cacheParameters_l()
3085{
3086    mixBufferSize = mNormalFrameCount * mFrameSize;
3087    activeSleepTime = activeSleepTimeUs();
3088    idleSleepTime = idleSleepTimeUs();
3089}
3090
3091void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
3092{
3093    ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
3094            this,  streamType, mTracks.size());
3095    Mutex::Autolock _l(mLock);
3096
3097    size_t size = mTracks.size();
3098    for (size_t i = 0; i < size; i++) {
3099        sp<Track> t = mTracks[i];
3100        if (t->streamType() == streamType) {
3101            android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
3102            t->mCblk->cv.signal();
3103        }
3104    }
3105}
3106
3107// getTrackName_l() must be called with ThreadBase::mLock held
3108int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
3109{
3110    return mAudioMixer->getTrackName(channelMask);
3111}
3112
3113// deleteTrackName_l() must be called with ThreadBase::mLock held
3114void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3115{
3116    ALOGV("remove track (%d) and delete from mixer", name);
3117    mAudioMixer->deleteTrackName(name);
3118}
3119
3120// checkForNewParameters_l() must be called with ThreadBase::mLock held
3121bool AudioFlinger::MixerThread::checkForNewParameters_l()
3122{
3123    // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3124    FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3125    bool reconfig = false;
3126
3127    while (!mNewParameters.isEmpty()) {
3128
3129        if (mFastMixer != NULL) {
3130            FastMixerStateQueue *sq = mFastMixer->sq();
3131            FastMixerState *state = sq->begin();
3132            if (!(state->mCommand & FastMixerState::IDLE)) {
3133                previousCommand = state->mCommand;
3134                state->mCommand = FastMixerState::HOT_IDLE;
3135                sq->end();
3136                sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3137            } else {
3138                sq->end(false /*didModify*/);
3139            }
3140        }
3141
3142        status_t status = NO_ERROR;
3143        String8 keyValuePair = mNewParameters[0];
3144        AudioParameter param = AudioParameter(keyValuePair);
3145        int value;
3146
3147        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3148            reconfig = true;
3149        }
3150        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3151            if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3152                status = BAD_VALUE;
3153            } else {
3154                reconfig = true;
3155            }
3156        }
3157        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3158            if (value != AUDIO_CHANNEL_OUT_STEREO) {
3159                status = BAD_VALUE;
3160            } else {
3161                reconfig = true;
3162            }
3163        }
3164        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3165            // do not accept frame count changes if tracks are open as the track buffer
3166            // size depends on frame count and correct behavior would not be guaranteed
3167            // if frame count is changed after track creation
3168            if (!mTracks.isEmpty()) {
3169                status = INVALID_OPERATION;
3170            } else {
3171                reconfig = true;
3172            }
3173        }
3174        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3175#ifdef ADD_BATTERY_DATA
3176            // when changing the audio output device, call addBatteryData to notify
3177            // the change
3178            if ((int)mDevice != value) {
3179                uint32_t params = 0;
3180                // check whether speaker is on
3181                if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3182                    params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3183                }
3184
3185                int deviceWithoutSpeaker
3186                    = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3187                // check if any other device (except speaker) is on
3188                if (value & deviceWithoutSpeaker ) {
3189                    params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3190                }
3191
3192                if (params != 0) {
3193                    addBatteryData(params);
3194                }
3195            }
3196#endif
3197
3198            // forward device change to effects that have requested to be
3199            // aware of attached audio device.
3200            mDevice = (uint32_t)value;
3201            for (size_t i = 0; i < mEffectChains.size(); i++) {
3202                mEffectChains[i]->setDevice_l(mDevice);
3203            }
3204        }
3205
3206        if (status == NO_ERROR) {
3207            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3208                                                    keyValuePair.string());
3209            if (!mStandby && status == INVALID_OPERATION) {
3210                mOutput->stream->common.standby(&mOutput->stream->common);
3211                mStandby = true;
3212                mBytesWritten = 0;
3213                status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3214                                                       keyValuePair.string());
3215            }
3216            if (status == NO_ERROR && reconfig) {
3217                delete mAudioMixer;
3218                // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3219                mAudioMixer = NULL;
3220                readOutputParameters();
3221                mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3222                for (size_t i = 0; i < mTracks.size() ; i++) {
3223                    int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
3224                    if (name < 0) break;
3225                    mTracks[i]->mName = name;
3226                    // limit track sample rate to 2 x new output sample rate
3227                    if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3228                        mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3229                    }
3230                }
3231                sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3232            }
3233        }
3234
3235        mNewParameters.removeAt(0);
3236
3237        mParamStatus = status;
3238        mParamCond.signal();
3239        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3240        // already timed out waiting for the status and will never signal the condition.
3241        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3242    }
3243
3244    if (!(previousCommand & FastMixerState::IDLE)) {
3245        ALOG_ASSERT(mFastMixer != NULL);
3246        FastMixerStateQueue *sq = mFastMixer->sq();
3247        FastMixerState *state = sq->begin();
3248        ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3249        state->mCommand = previousCommand;
3250        sq->end();
3251        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3252    }
3253
3254    return reconfig;
3255}
3256
3257status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3258{
3259    const size_t SIZE = 256;
3260    char buffer[SIZE];
3261    String8 result;
3262
3263    PlaybackThread::dumpInternals(fd, args);
3264
3265    snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3266    result.append(buffer);
3267    write(fd, result.string(), result.size());
3268
3269    // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3270    FastMixerDumpState copy = mFastMixerDumpState;
3271    copy.dump(fd);
3272
3273    return NO_ERROR;
3274}
3275
3276uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3277{
3278    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3279}
3280
3281uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3282{
3283    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3284}
3285
3286void AudioFlinger::MixerThread::cacheParameters_l()
3287{
3288    PlaybackThread::cacheParameters_l();
3289
3290    // FIXME: Relaxed timing because of a certain device that can't meet latency
3291    // Should be reduced to 2x after the vendor fixes the driver issue
3292    // increase threshold again due to low power audio mode. The way this warning
3293    // threshold is calculated and its usefulness should be reconsidered anyway.
3294    maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3295}
3296
3297// ----------------------------------------------------------------------------
3298AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3299        AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3300    :   PlaybackThread(audioFlinger, output, id, device, DIRECT)
3301        // mLeftVolFloat, mRightVolFloat
3302        // mLeftVolShort, mRightVolShort
3303{
3304}
3305
3306AudioFlinger::DirectOutputThread::~DirectOutputThread()
3307{
3308}
3309
3310AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3311    Vector< sp<Track> > *tracksToRemove
3312)
3313{
3314    sp<Track> trackToRemove;
3315
3316    mixer_state mixerStatus = MIXER_IDLE;
3317
3318    // find out which tracks need to be processed
3319    if (mActiveTracks.size() != 0) {
3320        sp<Track> t = mActiveTracks[0].promote();
3321        // The track died recently
3322        if (t == 0) return MIXER_IDLE;
3323
3324        Track* const track = t.get();
3325        audio_track_cblk_t* cblk = track->cblk();
3326
3327        // The first time a track is added we wait
3328        // for all its buffers to be filled before processing it
3329        if (cblk->framesReady() && track->isReady() &&
3330                !track->isPaused() && !track->isTerminated())
3331        {
3332            //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
3333
3334            if (track->mFillingUpStatus == Track::FS_FILLED) {
3335                track->mFillingUpStatus = Track::FS_ACTIVE;
3336                mLeftVolFloat = mRightVolFloat = 0;
3337                mLeftVolShort = mRightVolShort = 0;
3338                if (track->mState == TrackBase::RESUMING) {
3339                    track->mState = TrackBase::ACTIVE;
3340                    rampVolume = true;
3341                }
3342            } else if (cblk->server != 0) {
3343                // If the track is stopped before the first frame was mixed,
3344                // do not apply ramp
3345                rampVolume = true;
3346            }
3347            // compute volume for this track
3348            float left, right;
3349            if (track->isMuted() || mMasterMute || track->isPausing() ||
3350                mStreamTypes[track->streamType()].mute) {
3351                left = right = 0;
3352                if (track->isPausing()) {
3353                    track->setPaused();
3354                }
3355            } else {
3356                float typeVolume = mStreamTypes[track->streamType()].volume;
3357                float v = mMasterVolume * typeVolume;
3358                uint32_t vlr = cblk->getVolumeLR();
3359                float v_clamped = v * (vlr & 0xFFFF);
3360                if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3361                left = v_clamped/MAX_GAIN;
3362                v_clamped = v * (vlr >> 16);
3363                if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3364                right = v_clamped/MAX_GAIN;
3365            }
3366
3367            if (left != mLeftVolFloat || right != mRightVolFloat) {
3368                mLeftVolFloat = left;
3369                mRightVolFloat = right;
3370
3371                // If audio HAL implements volume control,
3372                // force software volume to nominal value
3373                if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
3374                    left = 1.0f;
3375                    right = 1.0f;
3376                }
3377
3378                // Convert volumes from float to 8.24
3379                uint32_t vl = (uint32_t)(left * (1 << 24));
3380                uint32_t vr = (uint32_t)(right * (1 << 24));
3381
3382                // Delegate volume control to effect in track effect chain if needed
3383                // only one effect chain can be present on DirectOutputThread, so if
3384                // there is one, the track is connected to it
3385                if (!mEffectChains.isEmpty()) {
3386                    // Do not ramp volume if volume is controlled by effect
3387                    if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
3388                        rampVolume = false;
3389                    }
3390                }
3391
3392                // Convert volumes from 8.24 to 4.12 format
3393                uint32_t v_clamped = (vl + (1 << 11)) >> 12;
3394                if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3395                leftVol = (uint16_t)v_clamped;
3396                v_clamped = (vr + (1 << 11)) >> 12;
3397                if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3398                rightVol = (uint16_t)v_clamped;
3399            } else {
3400                leftVol = mLeftVolShort;
3401                rightVol = mRightVolShort;
3402                rampVolume = false;
3403            }
3404
3405            // reset retry count
3406            track->mRetryCount = kMaxTrackRetriesDirect;
3407            mActiveTrack = t;
3408            mixerStatus = MIXER_TRACKS_READY;
3409        } else {
3410            //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3411            if (track->isStopped()) {
3412                track->reset();
3413            }
3414            if (track->isTerminated() || track->isStopped() || track->isPaused()) {
3415                // We have consumed all the buffers of this track.
3416                // Remove it from the list of active tracks.
3417                // TODO: implement behavior for compressed audio
3418                size_t audioHALFrames =
3419                        (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3420                size_t framesWritten =
3421                        mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3422                if (track->presentationComplete(framesWritten, audioHALFrames)) {
3423                    trackToRemove = track;
3424                }
3425            } else {
3426                // No buffers for this track. Give it a few chances to
3427                // fill a buffer, then remove it from active list.
3428                if (--(track->mRetryCount) <= 0) {
3429                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3430                    trackToRemove = track;
3431                } else {
3432                    mixerStatus = MIXER_TRACKS_ENABLED;
3433                }
3434            }
3435        }
3436    }
3437
3438    // FIXME merge this with similar code for removing multiple tracks
3439    // remove all the tracks that need to be...
3440    if (CC_UNLIKELY(trackToRemove != 0)) {
3441        tracksToRemove->add(trackToRemove);
3442        mActiveTracks.remove(trackToRemove);
3443        if (!mEffectChains.isEmpty()) {
3444            ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
3445                    trackToRemove->sessionId());
3446            mEffectChains[0]->decActiveTrackCnt();
3447        }
3448        if (trackToRemove->isTerminated()) {
3449            removeTrack_l(trackToRemove);
3450        }
3451    }
3452
3453    return mixerStatus;
3454}
3455
3456void AudioFlinger::DirectOutputThread::threadLoop_mix()
3457{
3458    AudioBufferProvider::Buffer buffer;
3459    size_t frameCount = mFrameCount;
3460    int8_t *curBuf = (int8_t *)mMixBuffer;
3461    // output audio to hardware
3462    while (frameCount) {
3463        buffer.frameCount = frameCount;
3464        mActiveTrack->getNextBuffer(&buffer);
3465        if (CC_UNLIKELY(buffer.raw == NULL)) {
3466            memset(curBuf, 0, frameCount * mFrameSize);
3467            break;
3468        }
3469        memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3470        frameCount -= buffer.frameCount;
3471        curBuf += buffer.frameCount * mFrameSize;
3472        mActiveTrack->releaseBuffer(&buffer);
3473    }
3474    sleepTime = 0;
3475    standbyTime = systemTime() + standbyDelay;
3476    mActiveTrack.clear();
3477
3478    // apply volume
3479
3480    // Do not apply volume on compressed audio
3481    if (!audio_is_linear_pcm(mFormat)) {
3482        return;
3483    }
3484
3485    // convert to signed 16 bit before volume calculation
3486    if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3487        size_t count = mFrameCount * mChannelCount;
3488        uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3489        int16_t *dst = mMixBuffer + count-1;
3490        while (count--) {
3491            *dst-- = (int16_t)(*src--^0x80) << 8;
3492        }
3493    }
3494
3495    frameCount = mFrameCount;
3496    int16_t *out = mMixBuffer;
3497    if (rampVolume) {
3498        if (mChannelCount == 1) {
3499            int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3500            int32_t vlInc = d / (int32_t)frameCount;
3501            int32_t vl = ((int32_t)mLeftVolShort << 16);
3502            do {
3503                out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3504                out++;
3505                vl += vlInc;
3506            } while (--frameCount);
3507
3508        } else {
3509            int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3510            int32_t vlInc = d / (int32_t)frameCount;
3511            d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3512            int32_t vrInc = d / (int32_t)frameCount;
3513            int32_t vl = ((int32_t)mLeftVolShort << 16);
3514            int32_t vr = ((int32_t)mRightVolShort << 16);
3515            do {
3516                out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3517                out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3518                out += 2;
3519                vl += vlInc;
3520                vr += vrInc;
3521            } while (--frameCount);
3522        }
3523    } else {
3524        if (mChannelCount == 1) {
3525            do {
3526                out[0] = clamp16(mul(out[0], leftVol) >> 12);
3527                out++;
3528            } while (--frameCount);
3529        } else {
3530            do {
3531                out[0] = clamp16(mul(out[0], leftVol) >> 12);
3532                out[1] = clamp16(mul(out[1], rightVol) >> 12);
3533                out += 2;
3534            } while (--frameCount);
3535        }
3536    }
3537
3538    // convert back to unsigned 8 bit after volume calculation
3539    if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3540        size_t count = mFrameCount * mChannelCount;
3541        int16_t *src = mMixBuffer;
3542        uint8_t *dst = (uint8_t *)mMixBuffer;
3543        while (count--) {
3544            *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3545        }
3546    }
3547
3548    mLeftVolShort = leftVol;
3549    mRightVolShort = rightVol;
3550}
3551
3552void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3553{
3554    if (sleepTime == 0) {
3555        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3556            sleepTime = activeSleepTime;
3557        } else {
3558            sleepTime = idleSleepTime;
3559        }
3560    } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3561        memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3562        sleepTime = 0;
3563    }
3564}
3565
3566// getTrackName_l() must be called with ThreadBase::mLock held
3567int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
3568{
3569    return 0;
3570}
3571
3572// deleteTrackName_l() must be called with ThreadBase::mLock held
3573void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3574{
3575}
3576
3577// checkForNewParameters_l() must be called with ThreadBase::mLock held
3578bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3579{
3580    bool reconfig = false;
3581
3582    while (!mNewParameters.isEmpty()) {
3583        status_t status = NO_ERROR;
3584        String8 keyValuePair = mNewParameters[0];
3585        AudioParameter param = AudioParameter(keyValuePair);
3586        int value;
3587
3588        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3589            // do not accept frame count changes if tracks are open as the track buffer
3590            // size depends on frame count and correct behavior would not be garantied
3591            // if frame count is changed after track creation
3592            if (!mTracks.isEmpty()) {
3593                status = INVALID_OPERATION;
3594            } else {
3595                reconfig = true;
3596            }
3597        }
3598        if (status == NO_ERROR) {
3599            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3600                                                    keyValuePair.string());
3601            if (!mStandby && status == INVALID_OPERATION) {
3602                mOutput->stream->common.standby(&mOutput->stream->common);
3603                mStandby = true;
3604                mBytesWritten = 0;
3605                status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3606                                                       keyValuePair.string());
3607            }
3608            if (status == NO_ERROR && reconfig) {
3609                readOutputParameters();
3610                sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3611            }
3612        }
3613
3614        mNewParameters.removeAt(0);
3615
3616        mParamStatus = status;
3617        mParamCond.signal();
3618        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3619        // already timed out waiting for the status and will never signal the condition.
3620        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3621    }
3622    return reconfig;
3623}
3624
3625uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3626{
3627    uint32_t time;
3628    if (audio_is_linear_pcm(mFormat)) {
3629        time = PlaybackThread::activeSleepTimeUs();
3630    } else {
3631        time = 10000;
3632    }
3633    return time;
3634}
3635
3636uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3637{
3638    uint32_t time;
3639    if (audio_is_linear_pcm(mFormat)) {
3640        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3641    } else {
3642        time = 10000;
3643    }
3644    return time;
3645}
3646
3647uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3648{
3649    uint32_t time;
3650    if (audio_is_linear_pcm(mFormat)) {
3651        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3652    } else {
3653        time = 10000;
3654    }
3655    return time;
3656}
3657
3658void AudioFlinger::DirectOutputThread::cacheParameters_l()
3659{
3660    PlaybackThread::cacheParameters_l();
3661
3662    // use shorter standby delay as on normal output to release
3663    // hardware resources as soon as possible
3664    standbyDelay = microseconds(activeSleepTime*2);
3665}
3666
3667// ----------------------------------------------------------------------------
3668
3669AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
3670        AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
3671    :   MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3672        mWaitTimeMs(UINT_MAX)
3673{
3674    addOutputTrack(mainThread);
3675}
3676
3677AudioFlinger::DuplicatingThread::~DuplicatingThread()
3678{
3679    for (size_t i = 0; i < mOutputTracks.size(); i++) {
3680        mOutputTracks[i]->destroy();
3681    }
3682}
3683
3684void AudioFlinger::DuplicatingThread::threadLoop_mix()
3685{
3686    // mix buffers...
3687    if (outputsReady(outputTracks)) {
3688        mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3689    } else {
3690        memset(mMixBuffer, 0, mixBufferSize);
3691    }
3692    sleepTime = 0;
3693    writeFrames = mNormalFrameCount;
3694}
3695
3696void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3697{
3698    if (sleepTime == 0) {
3699        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3700            sleepTime = activeSleepTime;
3701        } else {
3702            sleepTime = idleSleepTime;
3703        }
3704    } else if (mBytesWritten != 0) {
3705        // flush remaining overflow buffers in output tracks
3706        for (size_t i = 0; i < outputTracks.size(); i++) {
3707            if (outputTracks[i]->isActive()) {
3708                sleepTime = 0;
3709                writeFrames = 0;
3710                memset(mMixBuffer, 0, mixBufferSize);
3711                break;
3712            }
3713        }
3714    }
3715}
3716
3717void AudioFlinger::DuplicatingThread::threadLoop_write()
3718{
3719    standbyTime = systemTime() + standbyDelay;
3720    for (size_t i = 0; i < outputTracks.size(); i++) {
3721        outputTracks[i]->write(mMixBuffer, writeFrames);
3722    }
3723    mBytesWritten += mixBufferSize;
3724}
3725
3726void AudioFlinger::DuplicatingThread::threadLoop_standby()
3727{
3728    // DuplicatingThread implements standby by stopping all tracks
3729    for (size_t i = 0; i < outputTracks.size(); i++) {
3730        outputTracks[i]->stop();
3731    }
3732}
3733
3734void AudioFlinger::DuplicatingThread::saveOutputTracks()
3735{
3736    outputTracks = mOutputTracks;
3737}
3738
3739void AudioFlinger::DuplicatingThread::clearOutputTracks()
3740{
3741    outputTracks.clear();
3742}
3743
3744void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3745{
3746    Mutex::Autolock _l(mLock);
3747    // FIXME explain this formula
3748    int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
3749    OutputTrack *outputTrack = new OutputTrack(thread,
3750                                            this,
3751                                            mSampleRate,
3752                                            mFormat,
3753                                            mChannelMask,
3754                                            frameCount);
3755    if (outputTrack->cblk() != NULL) {
3756        thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
3757        mOutputTracks.add(outputTrack);
3758        ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
3759        updateWaitTime_l();
3760    }
3761}
3762
3763void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3764{
3765    Mutex::Autolock _l(mLock);
3766    for (size_t i = 0; i < mOutputTracks.size(); i++) {
3767        if (mOutputTracks[i]->thread() == thread) {
3768            mOutputTracks[i]->destroy();
3769            mOutputTracks.removeAt(i);
3770            updateWaitTime_l();
3771            return;
3772        }
3773    }
3774    ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
3775}
3776
3777// caller must hold mLock
3778void AudioFlinger::DuplicatingThread::updateWaitTime_l()
3779{
3780    mWaitTimeMs = UINT_MAX;
3781    for (size_t i = 0; i < mOutputTracks.size(); i++) {
3782        sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3783        if (strong != 0) {
3784            uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3785            if (waitTimeMs < mWaitTimeMs) {
3786                mWaitTimeMs = waitTimeMs;
3787            }
3788        }
3789    }
3790}
3791
3792
3793bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
3794{
3795    for (size_t i = 0; i < outputTracks.size(); i++) {
3796        sp<ThreadBase> thread = outputTracks[i]->thread().promote();
3797        if (thread == 0) {
3798            ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3799            return false;
3800        }
3801        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3802        if (playbackThread->standby() && !playbackThread->isSuspended()) {
3803            ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
3804            return false;
3805        }
3806    }
3807    return true;
3808}
3809
3810uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
3811{
3812    return (mWaitTimeMs * 1000) / 2;
3813}
3814
3815void AudioFlinger::DuplicatingThread::cacheParameters_l()
3816{
3817    // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3818    updateWaitTime_l();
3819
3820    MixerThread::cacheParameters_l();
3821}
3822
3823// ----------------------------------------------------------------------------
3824
3825// TrackBase constructor must be called with AudioFlinger::mLock held
3826AudioFlinger::ThreadBase::TrackBase::TrackBase(
3827            ThreadBase *thread,
3828            const sp<Client>& client,
3829            uint32_t sampleRate,
3830            audio_format_t format,
3831            uint32_t channelMask,
3832            int frameCount,
3833            const sp<IMemory>& sharedBuffer,
3834            int sessionId)
3835    :   RefBase(),
3836        mThread(thread),
3837        mClient(client),
3838        mCblk(NULL),
3839        // mBuffer
3840        // mBufferEnd
3841        mFrameCount(0),
3842        mState(IDLE),
3843        mSampleRate(sampleRate),
3844        mFormat(format),
3845        mStepServerFailed(false),
3846        mSessionId(sessionId)
3847        // mChannelCount
3848        // mChannelMask
3849{
3850    ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
3851
3852    // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
3853    size_t size = sizeof(audio_track_cblk_t);
3854    uint8_t channelCount = popcount(channelMask);
3855    size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3856    if (sharedBuffer == 0) {
3857        size += bufferSize;
3858    }
3859
3860    if (client != NULL) {
3861        mCblkMemory = client->heap()->allocate(size);
3862        if (mCblkMemory != 0) {
3863            mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3864            if (mCblk != NULL) { // construct the shared structure in-place.
3865                new(mCblk) audio_track_cblk_t();
3866                // clear all buffers
3867                mCblk->frameCount = frameCount;
3868                mCblk->sampleRate = sampleRate;
3869// uncomment the following lines to quickly test 32-bit wraparound
3870//                mCblk->user = 0xffff0000;
3871//                mCblk->server = 0xffff0000;
3872//                mCblk->userBase = 0xffff0000;
3873//                mCblk->serverBase = 0xffff0000;
3874                mChannelCount = channelCount;
3875                mChannelMask = channelMask;
3876                if (sharedBuffer == 0) {
3877                    mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3878                    memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3879                    // Force underrun condition to avoid false underrun callback until first data is
3880                    // written to buffer (other flags are cleared)
3881                    mCblk->flags = CBLK_UNDERRUN_ON;
3882                } else {
3883                    mBuffer = sharedBuffer->pointer();
3884                }
3885                mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3886            }
3887        } else {
3888            ALOGE("not enough memory for AudioTrack size=%u", size);
3889            client->heap()->dump("AudioTrack");
3890            return;
3891        }
3892    } else {
3893        mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3894        // construct the shared structure in-place.
3895        new(mCblk) audio_track_cblk_t();
3896        // clear all buffers
3897        mCblk->frameCount = frameCount;
3898        mCblk->sampleRate = sampleRate;
3899// uncomment the following lines to quickly test 32-bit wraparound
3900//        mCblk->user = 0xffff0000;
3901//        mCblk->server = 0xffff0000;
3902//        mCblk->userBase = 0xffff0000;
3903//        mCblk->serverBase = 0xffff0000;
3904        mChannelCount = channelCount;
3905        mChannelMask = channelMask;
3906        mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3907        memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3908        // Force underrun condition to avoid false underrun callback until first data is
3909        // written to buffer (other flags are cleared)
3910        mCblk->flags = CBLK_UNDERRUN_ON;
3911        mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3912    }
3913}
3914
3915AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3916{
3917    if (mCblk != NULL) {
3918        if (mClient == 0) {
3919            delete mCblk;
3920        } else {
3921            mCblk->~audio_track_cblk_t();   // destroy our shared-structure.
3922        }
3923    }
3924    mCblkMemory.clear();    // free the shared memory before releasing the heap it belongs to
3925    if (mClient != 0) {
3926        // Client destructor must run with AudioFlinger mutex locked
3927        Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3928        // If the client's reference count drops to zero, the associated destructor
3929        // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3930        // relying on the automatic clear() at end of scope.
3931        mClient.clear();
3932    }
3933}
3934
3935// AudioBufferProvider interface
3936// getNextBuffer() = 0;
3937// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
3938void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3939{
3940    buffer->raw = NULL;
3941    mFrameCount = buffer->frameCount;
3942    (void) step();      // ignore return value of step()
3943    buffer->frameCount = 0;
3944}
3945
3946bool AudioFlinger::ThreadBase::TrackBase::step() {
3947    bool result;
3948    audio_track_cblk_t* cblk = this->cblk();
3949
3950    result = cblk->stepServer(mFrameCount);
3951    if (!result) {
3952        ALOGV("stepServer failed acquiring cblk mutex");
3953        mStepServerFailed = true;
3954    }
3955    return result;
3956}
3957
3958void AudioFlinger::ThreadBase::TrackBase::reset() {
3959    audio_track_cblk_t* cblk = this->cblk();
3960
3961    cblk->user = 0;
3962    cblk->server = 0;
3963    cblk->userBase = 0;
3964    cblk->serverBase = 0;
3965    mStepServerFailed = false;
3966    ALOGV("TrackBase::reset");
3967}
3968
3969int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3970    return (int)mCblk->sampleRate;
3971}
3972
3973void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3974    audio_track_cblk_t* cblk = this->cblk();
3975    size_t frameSize = cblk->frameSize;
3976    int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3977    int8_t *bufferEnd = bufferStart + frames * frameSize;
3978
3979    // Check validity of returned pointer in case the track control block would have been corrupted.
3980    ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
3981            "TrackBase::getBuffer buffer out of range:\n"
3982                "    start: %p, end %p , mBuffer %p mBufferEnd %p\n"
3983                "    server %u, serverBase %u, user %u, userBase %u, frameSize %d",
3984                bufferStart, bufferEnd, mBuffer, mBufferEnd,
3985                cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
3986
3987    return bufferStart;
3988}
3989
3990status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
3991{
3992    mSyncEvents.add(event);
3993    return NO_ERROR;
3994}
3995
3996// ----------------------------------------------------------------------------
3997
3998// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3999AudioFlinger::PlaybackThread::Track::Track(
4000            PlaybackThread *thread,
4001            const sp<Client>& client,
4002            audio_stream_type_t streamType,
4003            uint32_t sampleRate,
4004            audio_format_t format,
4005            uint32_t channelMask,
4006            int frameCount,
4007            const sp<IMemory>& sharedBuffer,
4008            int sessionId,
4009            IAudioFlinger::track_flags_t flags)
4010    :   TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
4011    mMute(false),
4012    mFillingUpStatus(FS_INVALID),
4013    // mRetryCount initialized later when needed
4014    mSharedBuffer(sharedBuffer),
4015    mStreamType(streamType),
4016    mName(-1),  // see note below
4017    mMainBuffer(thread->mixBuffer()),
4018    mAuxBuffer(NULL),
4019    mAuxEffectId(0), mHasVolumeController(false),
4020    mPresentationCompleteFrames(0),
4021    mFlags(flags),
4022    mFastIndex(-1),
4023    mCachedVolume(1.0)
4024{
4025    if (mCblk != NULL) {
4026        // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4027        // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
4028        mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
4029        if (flags & IAudioFlinger::TRACK_FAST) {
4030            mCblk->flags |= CBLK_FAST;  // atomic op not needed yet
4031            ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4032            int i = __builtin_ctz(thread->mFastTrackAvailMask);
4033            ALOG_ASSERT(0 < i && i < FastMixerState::kMaxFastTracks);
4034            mFastIndex = i;
4035            thread->mFastTrackAvailMask &= ~(1 << i);
4036            // Although we've allocated an index, we can't mutate or push a new fast track state
4037            // here, because that data structure can only be changed within the normal mixer
4038            // threadLoop().  So instead, make a note to mutate and push later.
4039            thread->mFastTrackNewArray[i] = this;
4040            thread->mFastTrackNewMask |= 1 << i;
4041        }
4042        // to avoid leaking a track name, do not allocate one unless there is an mCblk
4043        mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
4044        if (mName < 0) {
4045            ALOGE("no more track names available");
4046        }
4047    }
4048    ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
4049}
4050
4051AudioFlinger::PlaybackThread::Track::~Track()
4052{
4053    ALOGV("PlaybackThread::Track destructor");
4054    sp<ThreadBase> thread = mThread.promote();
4055    if (thread != 0) {
4056        Mutex::Autolock _l(thread->mLock);
4057        mState = TERMINATED;
4058    }
4059}
4060
4061void AudioFlinger::PlaybackThread::Track::destroy()
4062{
4063    // NOTE: destroyTrack_l() can remove a strong reference to this Track
4064    // by removing it from mTracks vector, so there is a risk that this Tracks's
4065    // destructor is called. As the destructor needs to lock mLock,
4066    // we must acquire a strong reference on this Track before locking mLock
4067    // here so that the destructor is called only when exiting this function.
4068    // On the other hand, as long as Track::destroy() is only called by
4069    // TrackHandle destructor, the TrackHandle still holds a strong ref on
4070    // this Track with its member mTrack.
4071    sp<Track> keep(this);
4072    { // scope for mLock
4073        sp<ThreadBase> thread = mThread.promote();
4074        if (thread != 0) {
4075            if (!isOutputTrack()) {
4076                if (mState == ACTIVE || mState == RESUMING) {
4077                    AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
4078
4079#ifdef ADD_BATTERY_DATA
4080                    // to track the speaker usage
4081                    addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
4082#endif
4083                }
4084                AudioSystem::releaseOutput(thread->id());
4085            }
4086            Mutex::Autolock _l(thread->mLock);
4087            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4088            playbackThread->destroyTrack_l(this);
4089        }
4090    }
4091}
4092
4093void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4094{
4095    uint32_t vlr = mCblk->getVolumeLR();
4096    if (isFastTrack()) {
4097        strcpy(buffer, "   fast");
4098    } else {
4099        sprintf(buffer, "   %4d", mName - AudioMixer::TRACK0);
4100    }
4101    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",
4102            (mClient == 0) ? getpid_cached : mClient->pid(),
4103            mStreamType,
4104            mFormat,
4105            mChannelMask,
4106            mSessionId,
4107            mFrameCount,
4108            mState,
4109            mMute,
4110            mFillingUpStatus,
4111            mCblk->sampleRate,
4112            20.0 * log10((vlr & 0xFFFF) / 4096.0),
4113            20.0 * log10((vlr >> 16) / 4096.0),
4114            mCblk->server,
4115            mCblk->user,
4116            (int)mMainBuffer,
4117            (int)mAuxBuffer);
4118}
4119
4120// AudioBufferProvider interface
4121status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
4122        AudioBufferProvider::Buffer* buffer, int64_t pts)
4123{
4124    audio_track_cblk_t* cblk = this->cblk();
4125    uint32_t framesReady;
4126    uint32_t framesReq = buffer->frameCount;
4127
4128    // Check if last stepServer failed, try to step now
4129    if (mStepServerFailed) {
4130        if (!step())  goto getNextBuffer_exit;
4131        ALOGV("stepServer recovered");
4132        mStepServerFailed = false;
4133    }
4134
4135    framesReady = cblk->framesReady();
4136
4137    if (CC_LIKELY(framesReady)) {
4138        uint32_t s = cblk->server;
4139        uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4140
4141        bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4142        if (framesReq > framesReady) {
4143            framesReq = framesReady;
4144        }
4145        if (framesReq > bufferEnd - s) {
4146            framesReq = bufferEnd - s;
4147        }
4148
4149        buffer->raw = getBuffer(s, framesReq);
4150        if (buffer->raw == NULL) goto getNextBuffer_exit;
4151
4152        buffer->frameCount = framesReq;
4153        return NO_ERROR;
4154    }
4155
4156getNextBuffer_exit:
4157    buffer->raw = NULL;
4158    buffer->frameCount = 0;
4159    ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4160    return NOT_ENOUGH_DATA;
4161}
4162
4163uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const {
4164    return mCblk->framesReady();
4165}
4166
4167bool AudioFlinger::PlaybackThread::Track::isReady() const {
4168    if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
4169
4170    if (framesReady() >= mCblk->frameCount ||
4171            (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4172        mFillingUpStatus = FS_FILLED;
4173        android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4174        return true;
4175    }
4176    return false;
4177}
4178
4179status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
4180                                                    int triggerSession)
4181{
4182    status_t status = NO_ERROR;
4183    ALOGV("start(%d), calling pid %d session %d",
4184            mName, IPCThreadState::self()->getCallingPid(), mSessionId);
4185
4186    sp<ThreadBase> thread = mThread.promote();
4187    if (thread != 0) {
4188        Mutex::Autolock _l(thread->mLock);
4189        track_state state = mState;
4190        // here the track could be either new, or restarted
4191        // in both cases "unstop" the track
4192        if (mState == PAUSED) {
4193            mState = TrackBase::RESUMING;
4194            ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
4195        } else {
4196            mState = TrackBase::ACTIVE;
4197            ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
4198        }
4199
4200        if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4201            thread->mLock.unlock();
4202            status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
4203            thread->mLock.lock();
4204
4205#ifdef ADD_BATTERY_DATA
4206            // to track the speaker usage
4207            if (status == NO_ERROR) {
4208                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4209            }
4210#endif
4211        }
4212        if (status == NO_ERROR) {
4213            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4214            playbackThread->addTrack_l(this);
4215        } else {
4216            mState = state;
4217        }
4218    } else {
4219        status = BAD_VALUE;
4220    }
4221    return status;
4222}
4223
4224void AudioFlinger::PlaybackThread::Track::stop()
4225{
4226    ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
4227    sp<ThreadBase> thread = mThread.promote();
4228    if (thread != 0) {
4229        Mutex::Autolock _l(thread->mLock);
4230        track_state state = mState;
4231        if (mState > STOPPED) {
4232            mState = STOPPED;
4233            // If the track is not active (PAUSED and buffers full), flush buffers
4234            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4235            if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4236                reset();
4237            }
4238            ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
4239        }
4240        if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4241            thread->mLock.unlock();
4242            AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
4243            thread->mLock.lock();
4244
4245#ifdef ADD_BATTERY_DATA
4246            // to track the speaker usage
4247            addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
4248#endif
4249        }
4250    }
4251}
4252
4253void AudioFlinger::PlaybackThread::Track::pause()
4254{
4255    ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
4256    sp<ThreadBase> thread = mThread.promote();
4257    if (thread != 0) {
4258        Mutex::Autolock _l(thread->mLock);
4259        if (mState == ACTIVE || mState == RESUMING) {
4260            mState = PAUSING;
4261            ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
4262            if (!isOutputTrack()) {
4263                thread->mLock.unlock();
4264                AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
4265                thread->mLock.lock();
4266
4267#ifdef ADD_BATTERY_DATA
4268                // to track the speaker usage
4269                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
4270#endif
4271            }
4272        }
4273    }
4274}
4275
4276void AudioFlinger::PlaybackThread::Track::flush()
4277{
4278    ALOGV("flush(%d)", mName);
4279    sp<ThreadBase> thread = mThread.promote();
4280    if (thread != 0) {
4281        Mutex::Autolock _l(thread->mLock);
4282        if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
4283            return;
4284        }
4285        // No point remaining in PAUSED state after a flush => go to
4286        // STOPPED state
4287        mState = STOPPED;
4288
4289        // do not reset the track if it is still in the process of being stopped or paused.
4290        // this will be done by prepareTracks_l() when the track is stopped.
4291        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4292        if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4293            reset();
4294        }
4295    }
4296}
4297
4298void AudioFlinger::PlaybackThread::Track::reset()
4299{
4300    // Do not reset twice to avoid discarding data written just after a flush and before
4301    // the audioflinger thread detects the track is stopped.
4302    if (!mResetDone) {
4303        TrackBase::reset();
4304        // Force underrun condition to avoid false underrun callback until first data is
4305        // written to buffer
4306        android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4307        android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
4308        mFillingUpStatus = FS_FILLING;
4309        mResetDone = true;
4310        mPresentationCompleteFrames = 0;
4311    }
4312}
4313
4314void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4315{
4316    mMute = muted;
4317}
4318
4319status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4320{
4321    status_t status = DEAD_OBJECT;
4322    sp<ThreadBase> thread = mThread.promote();
4323    if (thread != 0) {
4324        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4325        status = playbackThread->attachAuxEffect(this, EffectId);
4326    }
4327    return status;
4328}
4329
4330void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4331{
4332    mAuxEffectId = EffectId;
4333    mAuxBuffer = buffer;
4334}
4335
4336bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4337                                                         size_t audioHalFrames)
4338{
4339    // a track is considered presented when the total number of frames written to audio HAL
4340    // corresponds to the number of frames written when presentationComplete() is called for the
4341    // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4342    if (mPresentationCompleteFrames == 0) {
4343        mPresentationCompleteFrames = framesWritten + audioHalFrames;
4344        ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4345                  mPresentationCompleteFrames, audioHalFrames);
4346    }
4347    if (framesWritten >= mPresentationCompleteFrames) {
4348        ALOGV("presentationComplete() session %d complete: framesWritten %d",
4349                  mSessionId, framesWritten);
4350        triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
4351        mPresentationCompleteFrames = 0;
4352        return true;
4353    }
4354    return false;
4355}
4356
4357void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4358{
4359    for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4360        if (mSyncEvents[i]->type() == type) {
4361            mSyncEvents[i]->trigger();
4362            mSyncEvents.removeAt(i);
4363            i--;
4364        }
4365    }
4366}
4367
4368// implement VolumeBufferProvider interface
4369
4370uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4371{
4372    // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4373    ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4374    uint32_t vlr = mCblk->getVolumeLR();
4375    uint32_t vl = vlr & 0xFFFF;
4376    uint32_t vr = vlr >> 16;
4377    // track volumes come from shared memory, so can't be trusted and must be clamped
4378    if (vl > MAX_GAIN_INT) {
4379        vl = MAX_GAIN_INT;
4380    }
4381    if (vr > MAX_GAIN_INT) {
4382        vr = MAX_GAIN_INT;
4383    }
4384    // now apply the cached master volume and stream type volume;
4385    // this is trusted but lacks any synchronization or barrier so may be stale
4386    float v = mCachedVolume;
4387    vl *= v;
4388    vr *= v;
4389    // re-combine into U4.16
4390    vlr = (vr << 16) | (vl & 0xFFFF);
4391    // FIXME look at mute, pause, and stop flags
4392    return vlr;
4393}
4394
4395// timed audio tracks
4396
4397sp<AudioFlinger::PlaybackThread::TimedTrack>
4398AudioFlinger::PlaybackThread::TimedTrack::create(
4399            PlaybackThread *thread,
4400            const sp<Client>& client,
4401            audio_stream_type_t streamType,
4402            uint32_t sampleRate,
4403            audio_format_t format,
4404            uint32_t channelMask,
4405            int frameCount,
4406            const sp<IMemory>& sharedBuffer,
4407            int sessionId) {
4408    if (!client->reserveTimedTrack())
4409        return NULL;
4410
4411    return new TimedTrack(
4412        thread, client, streamType, sampleRate, format, channelMask, frameCount,
4413        sharedBuffer, sessionId);
4414}
4415
4416AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
4417            PlaybackThread *thread,
4418            const sp<Client>& client,
4419            audio_stream_type_t streamType,
4420            uint32_t sampleRate,
4421            audio_format_t format,
4422            uint32_t channelMask,
4423            int frameCount,
4424            const sp<IMemory>& sharedBuffer,
4425            int sessionId)
4426    : Track(thread, client, streamType, sampleRate, format, channelMask,
4427            frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
4428      mQueueHeadInFlight(false),
4429      mTrimQueueHeadOnRelease(false),
4430      mFramesPendingInQueue(0),
4431      mTimedSilenceBuffer(NULL),
4432      mTimedSilenceBufferSize(0),
4433      mTimedAudioOutputOnTime(false),
4434      mMediaTimeTransformValid(false)
4435{
4436    LocalClock lc;
4437    mLocalTimeFreq = lc.getLocalFreq();
4438
4439    mLocalTimeToSampleTransform.a_zero = 0;
4440    mLocalTimeToSampleTransform.b_zero = 0;
4441    mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4442    mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4443    LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4444                            &mLocalTimeToSampleTransform.a_to_b_denom);
4445
4446    mMediaTimeToSampleTransform.a_zero = 0;
4447    mMediaTimeToSampleTransform.b_zero = 0;
4448    mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4449    mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4450    LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4451                            &mMediaTimeToSampleTransform.a_to_b_denom);
4452}
4453
4454AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4455    mClient->releaseTimedTrack();
4456    delete [] mTimedSilenceBuffer;
4457}
4458
4459status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4460    size_t size, sp<IMemory>* buffer) {
4461
4462    Mutex::Autolock _l(mTimedBufferQueueLock);
4463
4464    trimTimedBufferQueue_l();
4465
4466    // lazily initialize the shared memory heap for timed buffers
4467    if (mTimedMemoryDealer == NULL) {
4468        const int kTimedBufferHeapSize = 512 << 10;
4469
4470        mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4471                                              "AudioFlingerTimed");
4472        if (mTimedMemoryDealer == NULL)
4473            return NO_MEMORY;
4474    }
4475
4476    sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4477    if (newBuffer == NULL) {
4478        newBuffer = mTimedMemoryDealer->allocate(size);
4479        if (newBuffer == NULL)
4480            return NO_MEMORY;
4481    }
4482
4483    *buffer = newBuffer;
4484    return NO_ERROR;
4485}
4486
4487// caller must hold mTimedBufferQueueLock
4488void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4489    int64_t mediaTimeNow;
4490    {
4491        Mutex::Autolock mttLock(mMediaTimeTransformLock);
4492        if (!mMediaTimeTransformValid)
4493            return;
4494
4495        int64_t targetTimeNow;
4496        status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4497            ? mCCHelper.getCommonTime(&targetTimeNow)
4498            : mCCHelper.getLocalTime(&targetTimeNow);
4499
4500        if (OK != res)
4501            return;
4502
4503        if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4504                                                    &mediaTimeNow)) {
4505            return;
4506        }
4507    }
4508
4509    size_t trimEnd;
4510    for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
4511        int64_t bufEnd;
4512
4513        if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4514            // We have a next buffer.  Just use its PTS as the PTS of the frame
4515            // following the last frame in this buffer.  If the stream is sparse
4516            // (ie, there are deliberate gaps left in the stream which should be
4517            // filled with silence by the TimedAudioTrack), then this can result
4518            // in one extra buffer being left un-trimmed when it could have
4519            // been.  In general, this is not typical, and we would rather
4520            // optimized away the TS calculation below for the more common case
4521            // where PTSes are contiguous.
4522            bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4523        } else {
4524            // We have no next buffer.  Compute the PTS of the frame following
4525            // the last frame in this buffer by computing the duration of of
4526            // this frame in media time units and adding it to the PTS of the
4527            // buffer.
4528            int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4529                               / mCblk->frameSize;
4530
4531            if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4532                                                                &bufEnd)) {
4533                ALOGE("Failed to convert frame count of %lld to media time"
4534                      " duration" " (scale factor %d/%u) in %s",
4535                      frameCount,
4536                      mMediaTimeToSampleTransform.a_to_b_numer,
4537                      mMediaTimeToSampleTransform.a_to_b_denom,
4538                      __PRETTY_FUNCTION__);
4539                break;
4540            }
4541            bufEnd += mTimedBufferQueue[trimEnd].pts();
4542        }
4543
4544        if (bufEnd > mediaTimeNow)
4545            break;
4546
4547        // Is the buffer we want to use in the middle of a mix operation right
4548        // now?  If so, don't actually trim it.  Just wait for the releaseBuffer
4549        // from the mixer which should be coming back shortly.
4550        if (!trimEnd && mQueueHeadInFlight) {
4551            mTrimQueueHeadOnRelease = true;
4552        }
4553    }
4554
4555    size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
4556    if (trimStart < trimEnd) {
4557        // Update the bookkeeping for framesReady()
4558        for (size_t i = trimStart; i < trimEnd; ++i) {
4559            updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4560        }
4561
4562        // Now actually remove the buffers from the queue.
4563        mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
4564    }
4565}
4566
4567void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4568        const char* logTag) {
4569    ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4570                "%s called (reason \"%s\"), but timed buffer queue has no"
4571                " elements to trim.", __FUNCTION__, logTag);
4572
4573    updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4574    mTimedBufferQueue.removeAt(0);
4575}
4576
4577void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4578        const TimedBuffer& buf,
4579        const char* logTag) {
4580    uint32_t bufBytes        = buf.buffer()->size();
4581    uint32_t consumedAlready = buf.position();
4582
4583    ALOG_ASSERT(consumedAlready <= bufBytes,
4584                "Bad bookkeeping while updating frames pending.  Timed buffer is"
4585                " only %u bytes long, but claims to have consumed %u"
4586                " bytes.  (update reason: \"%s\")",
4587                bufBytes, consumedAlready, logTag);
4588
4589    uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
4590    ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4591                "Bad bookkeeping while updating frames pending.  Should have at"
4592                " least %u queued frames, but we think we have only %u.  (update"
4593                " reason: \"%s\")",
4594                bufFrames, mFramesPendingInQueue, logTag);
4595
4596    mFramesPendingInQueue -= bufFrames;
4597}
4598
4599status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4600    const sp<IMemory>& buffer, int64_t pts) {
4601
4602    {
4603        Mutex::Autolock mttLock(mMediaTimeTransformLock);
4604        if (!mMediaTimeTransformValid)
4605            return INVALID_OPERATION;
4606    }
4607
4608    Mutex::Autolock _l(mTimedBufferQueueLock);
4609
4610    uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4611    mFramesPendingInQueue += bufFrames;
4612    mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4613
4614    return NO_ERROR;
4615}
4616
4617status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4618    const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4619
4620    ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4621           xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4622           target);
4623
4624    if (!(target == TimedAudioTrack::LOCAL_TIME ||
4625          target == TimedAudioTrack::COMMON_TIME)) {
4626        return BAD_VALUE;
4627    }
4628
4629    Mutex::Autolock lock(mMediaTimeTransformLock);
4630    mMediaTimeTransform = xform;
4631    mMediaTimeTransformTarget = target;
4632    mMediaTimeTransformValid = true;
4633
4634    return NO_ERROR;
4635}
4636
4637#define min(a, b) ((a) < (b) ? (a) : (b))
4638
4639// implementation of getNextBuffer for tracks whose buffers have timestamps
4640status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4641    AudioBufferProvider::Buffer* buffer, int64_t pts)
4642{
4643    if (pts == AudioBufferProvider::kInvalidPTS) {
4644        buffer->raw = 0;
4645        buffer->frameCount = 0;
4646        mTimedAudioOutputOnTime = false;
4647        return INVALID_OPERATION;
4648    }
4649
4650    Mutex::Autolock _l(mTimedBufferQueueLock);
4651
4652    ALOG_ASSERT(!mQueueHeadInFlight,
4653                "getNextBuffer called without releaseBuffer!");
4654
4655    while (true) {
4656
4657        // if we have no timed buffers, then fail
4658        if (mTimedBufferQueue.isEmpty()) {
4659            buffer->raw = 0;
4660            buffer->frameCount = 0;
4661            return NOT_ENOUGH_DATA;
4662        }
4663
4664        TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4665
4666        // calculate the PTS of the head of the timed buffer queue expressed in
4667        // local time
4668        int64_t headLocalPTS;
4669        {
4670            Mutex::Autolock mttLock(mMediaTimeTransformLock);
4671
4672            ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
4673
4674            if (mMediaTimeTransform.a_to_b_denom == 0) {
4675                // the transform represents a pause, so yield silence
4676                timedYieldSilence_l(buffer->frameCount, buffer);
4677                return NO_ERROR;
4678            }
4679
4680            int64_t transformedPTS;
4681            if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4682                                                        &transformedPTS)) {
4683                // the transform failed.  this shouldn't happen, but if it does
4684                // then just drop this buffer
4685                ALOGW("timedGetNextBuffer transform failed");
4686                buffer->raw = 0;
4687                buffer->frameCount = 0;
4688                trimTimedBufferQueueHead_l("getNextBuffer; no transform");
4689                return NO_ERROR;
4690            }
4691
4692            if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4693                if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4694                                                          &headLocalPTS)) {
4695                    buffer->raw = 0;
4696                    buffer->frameCount = 0;
4697                    return INVALID_OPERATION;
4698                }
4699            } else {
4700                headLocalPTS = transformedPTS;
4701            }
4702        }
4703
4704        // adjust the head buffer's PTS to reflect the portion of the head buffer
4705        // that has already been consumed
4706        int64_t effectivePTS = headLocalPTS +
4707                ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4708
4709        // Calculate the delta in samples between the head of the input buffer
4710        // queue and the start of the next output buffer that will be written.
4711        // If the transformation fails because of over or underflow, it means
4712        // that the sample's position in the output stream is so far out of
4713        // whack that it should just be dropped.
4714        int64_t sampleDelta;
4715        if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4716            ALOGV("*** head buffer is too far from PTS: dropped buffer");
4717            trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
4718                                       " mix");
4719            continue;
4720        }
4721        if (!mLocalTimeToSampleTransform.doForwardTransform(
4722                (effectivePTS - pts) << 32, &sampleDelta)) {
4723            ALOGV("*** too late during sample rate transform: dropped buffer");
4724            trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
4725            continue;
4726        }
4727
4728        ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
4729               " sampleDelta=[%d.%08x]",
4730               head.pts(), head.position(), pts,
4731               static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
4732                   + (sampleDelta >> 32)),
4733               static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
4734
4735        // if the delta between the ideal placement for the next input sample and
4736        // the current output position is within this threshold, then we will
4737        // concatenate the next input samples to the previous output
4738        const int64_t kSampleContinuityThreshold =
4739                (static_cast<int64_t>(sampleRate()) << 32) / 250;
4740
4741        // if this is the first buffer of audio that we're emitting from this track
4742        // then it should be almost exactly on time.
4743        const int64_t kSampleStartupThreshold = 1LL << 32;
4744
4745        if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
4746           (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
4747            // the next input is close enough to being on time, so concatenate it
4748            // with the last output
4749            timedYieldSamples_l(buffer);
4750
4751            ALOGVV("*** on time: head.pos=%d frameCount=%u",
4752                    head.position(), buffer->frameCount);
4753            return NO_ERROR;
4754        }
4755
4756        // Looks like our output is not on time.  Reset our on timed status.
4757        // Next time we mix samples from our input queue, then should be within
4758        // the StartupThreshold.
4759        mTimedAudioOutputOnTime = false;
4760        if (sampleDelta > 0) {
4761            // the gap between the current output position and the proper start of
4762            // the next input sample is too big, so fill it with silence
4763            uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4764
4765            timedYieldSilence_l(framesUntilNextInput, buffer);
4766            ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4767            return NO_ERROR;
4768        } else {
4769            // the next input sample is late
4770            uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4771            size_t onTimeSamplePosition =
4772                    head.position() + lateFrames * mCblk->frameSize;
4773
4774            if (onTimeSamplePosition > head.buffer()->size()) {
4775                // all the remaining samples in the head are too late, so
4776                // drop it and move on
4777                ALOGV("*** too late: dropped buffer");
4778                trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
4779                continue;
4780            } else {
4781                // skip over the late samples
4782                head.setPosition(onTimeSamplePosition);
4783
4784                // yield the available samples
4785                timedYieldSamples_l(buffer);
4786
4787                ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4788                return NO_ERROR;
4789            }
4790        }
4791    }
4792}
4793
4794// Yield samples from the timed buffer queue head up to the given output
4795// buffer's capacity.
4796//
4797// Caller must hold mTimedBufferQueueLock
4798void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
4799    AudioBufferProvider::Buffer* buffer) {
4800
4801    const TimedBuffer& head = mTimedBufferQueue[0];
4802
4803    buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4804                   head.position());
4805
4806    uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4807                                 mCblk->frameSize);
4808    size_t framesRequested = buffer->frameCount;
4809    buffer->frameCount = min(framesLeftInHead, framesRequested);
4810
4811    mQueueHeadInFlight = true;
4812    mTimedAudioOutputOnTime = true;
4813}
4814
4815// Yield samples of silence up to the given output buffer's capacity
4816//
4817// Caller must hold mTimedBufferQueueLock
4818void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
4819    uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4820
4821    // lazily allocate a buffer filled with silence
4822    if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4823        delete [] mTimedSilenceBuffer;
4824        mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4825        mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4826        memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4827    }
4828
4829    buffer->raw = mTimedSilenceBuffer;
4830    size_t framesRequested = buffer->frameCount;
4831    buffer->frameCount = min(numFrames, framesRequested);
4832
4833    mTimedAudioOutputOnTime = false;
4834}
4835
4836// AudioBufferProvider interface
4837void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4838    AudioBufferProvider::Buffer* buffer) {
4839
4840    Mutex::Autolock _l(mTimedBufferQueueLock);
4841
4842    // If the buffer which was just released is part of the buffer at the head
4843    // of the queue, be sure to update the amt of the buffer which has been
4844    // consumed.  If the buffer being returned is not part of the head of the
4845    // queue, its either because the buffer is part of the silence buffer, or
4846    // because the head of the timed queue was trimmed after the mixer called
4847    // getNextBuffer but before the mixer called releaseBuffer.
4848    if (buffer->raw == mTimedSilenceBuffer) {
4849        ALOG_ASSERT(!mQueueHeadInFlight,
4850                    "Queue head in flight during release of silence buffer!");
4851        goto done;
4852    }
4853
4854    ALOG_ASSERT(mQueueHeadInFlight,
4855                "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
4856                " head in flight.");
4857
4858    if (mTimedBufferQueue.size()) {
4859        TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4860
4861        void* start = head.buffer()->pointer();
4862        void* end   = reinterpret_cast<void*>(
4863                        reinterpret_cast<uint8_t*>(head.buffer()->pointer())
4864                        + head.buffer()->size());
4865
4866        ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
4867                    "released buffer not within the head of the timed buffer"
4868                    " queue; qHead = [%p, %p], released buffer = %p",
4869                    start, end, buffer->raw);
4870
4871        head.setPosition(head.position() +
4872                (buffer->frameCount * mCblk->frameSize));
4873        mQueueHeadInFlight = false;
4874
4875        ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
4876                    "Bad bookkeeping during releaseBuffer!  Should have at"
4877                    " least %u queued frames, but we think we have only %u",
4878                    buffer->frameCount, mFramesPendingInQueue);
4879
4880        mFramesPendingInQueue -= buffer->frameCount;
4881
4882        if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
4883            || mTrimQueueHeadOnRelease) {
4884            trimTimedBufferQueueHead_l("releaseBuffer");
4885            mTrimQueueHeadOnRelease = false;
4886        }
4887    } else {
4888        LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
4889                  " buffers in the timed buffer queue");
4890    }
4891
4892done:
4893    buffer->raw = 0;
4894    buffer->frameCount = 0;
4895}
4896
4897uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4898    Mutex::Autolock _l(mTimedBufferQueueLock);
4899    return mFramesPendingInQueue;
4900}
4901
4902AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4903        : mPTS(0), mPosition(0) {}
4904
4905AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4906    const sp<IMemory>& buffer, int64_t pts)
4907        : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4908
4909// ----------------------------------------------------------------------------
4910
4911// RecordTrack constructor must be called with AudioFlinger::mLock held
4912AudioFlinger::RecordThread::RecordTrack::RecordTrack(
4913            RecordThread *thread,
4914            const sp<Client>& client,
4915            uint32_t sampleRate,
4916            audio_format_t format,
4917            uint32_t channelMask,
4918            int frameCount,
4919            int sessionId)
4920    :   TrackBase(thread, client, sampleRate, format,
4921                  channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
4922        mOverflow(false)
4923{
4924    if (mCblk != NULL) {
4925        ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4926        if (format == AUDIO_FORMAT_PCM_16_BIT) {
4927            mCblk->frameSize = mChannelCount * sizeof(int16_t);
4928        } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4929            mCblk->frameSize = mChannelCount * sizeof(int8_t);
4930        } else {
4931            mCblk->frameSize = sizeof(int8_t);
4932        }
4933    }
4934}
4935
4936AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4937{
4938    sp<ThreadBase> thread = mThread.promote();
4939    if (thread != 0) {
4940        AudioSystem::releaseInput(thread->id());
4941    }
4942}
4943
4944// AudioBufferProvider interface
4945status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
4946{
4947    audio_track_cblk_t* cblk = this->cblk();
4948    uint32_t framesAvail;
4949    uint32_t framesReq = buffer->frameCount;
4950
4951    // Check if last stepServer failed, try to step now
4952    if (mStepServerFailed) {
4953        if (!step()) goto getNextBuffer_exit;
4954        ALOGV("stepServer recovered");
4955        mStepServerFailed = false;
4956    }
4957
4958    framesAvail = cblk->framesAvailable_l();
4959
4960    if (CC_LIKELY(framesAvail)) {
4961        uint32_t s = cblk->server;
4962        uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4963
4964        if (framesReq > framesAvail) {
4965            framesReq = framesAvail;
4966        }
4967        if (framesReq > bufferEnd - s) {
4968            framesReq = bufferEnd - s;
4969        }
4970
4971        buffer->raw = getBuffer(s, framesReq);
4972        if (buffer->raw == NULL) goto getNextBuffer_exit;
4973
4974        buffer->frameCount = framesReq;
4975        return NO_ERROR;
4976    }
4977
4978getNextBuffer_exit:
4979    buffer->raw = NULL;
4980    buffer->frameCount = 0;
4981    return NOT_ENOUGH_DATA;
4982}
4983
4984status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
4985                                                        int triggerSession)
4986{
4987    sp<ThreadBase> thread = mThread.promote();
4988    if (thread != 0) {
4989        RecordThread *recordThread = (RecordThread *)thread.get();
4990        return recordThread->start(this, event, triggerSession);
4991    } else {
4992        return BAD_VALUE;
4993    }
4994}
4995
4996void AudioFlinger::RecordThread::RecordTrack::stop()
4997{
4998    sp<ThreadBase> thread = mThread.promote();
4999    if (thread != 0) {
5000        RecordThread *recordThread = (RecordThread *)thread.get();
5001        recordThread->stop(this);
5002        TrackBase::reset();
5003        // Force overrun condition to avoid false overrun callback until first data is
5004        // read from buffer
5005        android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5006    }
5007}
5008
5009void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5010{
5011    snprintf(buffer, size, "   %05d %03u 0x%08x %05d   %04u %01d %05u  %08x %08x\n",
5012            (mClient == 0) ? getpid_cached : mClient->pid(),
5013            mFormat,
5014            mChannelMask,
5015            mSessionId,
5016            mFrameCount,
5017            mState,
5018            mCblk->sampleRate,
5019            mCblk->server,
5020            mCblk->user);
5021}
5022
5023
5024// ----------------------------------------------------------------------------
5025
5026AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
5027            PlaybackThread *playbackThread,
5028            DuplicatingThread *sourceThread,
5029            uint32_t sampleRate,
5030            audio_format_t format,
5031            uint32_t channelMask,
5032            int frameCount)
5033    :   Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5034                NULL, 0, IAudioFlinger::TRACK_DEFAULT),
5035    mActive(false), mSourceThread(sourceThread)
5036{
5037
5038    if (mCblk != NULL) {
5039        mCblk->flags |= CBLK_DIRECTION_OUT;
5040        mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
5041        mOutBuffer.frameCount = 0;
5042        playbackThread->mTracks.add(this);
5043        ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
5044                "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5045                mCblk, mBuffer, mCblk->buffers,
5046                mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
5047    } else {
5048        ALOGW("Error creating output track on thread %p", playbackThread);
5049    }
5050}
5051
5052AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5053{
5054    clearBufferQueue();
5055}
5056
5057status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
5058                                                          int triggerSession)
5059{
5060    status_t status = Track::start(event, triggerSession);
5061    if (status != NO_ERROR) {
5062        return status;
5063    }
5064
5065    mActive = true;
5066    mRetryCount = 127;
5067    return status;
5068}
5069
5070void AudioFlinger::PlaybackThread::OutputTrack::stop()
5071{
5072    Track::stop();
5073    clearBufferQueue();
5074    mOutBuffer.frameCount = 0;
5075    mActive = false;
5076}
5077
5078bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5079{
5080    Buffer *pInBuffer;
5081    Buffer inBuffer;
5082    uint32_t channelCount = mChannelCount;
5083    bool outputBufferFull = false;
5084    inBuffer.frameCount = frames;
5085    inBuffer.i16 = data;
5086
5087    uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5088
5089    if (!mActive && frames != 0) {
5090        start();
5091        sp<ThreadBase> thread = mThread.promote();
5092        if (thread != 0) {
5093            MixerThread *mixerThread = (MixerThread *)thread.get();
5094            if (mCblk->frameCount > frames){
5095                if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5096                    uint32_t startFrames = (mCblk->frameCount - frames);
5097                    pInBuffer = new Buffer;
5098                    pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5099                    pInBuffer->frameCount = startFrames;
5100                    pInBuffer->i16 = pInBuffer->mBuffer;
5101                    memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5102                    mBufferQueue.add(pInBuffer);
5103                } else {
5104                    ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
5105                }
5106            }
5107        }
5108    }
5109
5110    while (waitTimeLeftMs) {
5111        // First write pending buffers, then new data
5112        if (mBufferQueue.size()) {
5113            pInBuffer = mBufferQueue.itemAt(0);
5114        } else {
5115            pInBuffer = &inBuffer;
5116        }
5117
5118        if (pInBuffer->frameCount == 0) {
5119            break;
5120        }
5121
5122        if (mOutBuffer.frameCount == 0) {
5123            mOutBuffer.frameCount = pInBuffer->frameCount;
5124            nsecs_t startTime = systemTime();
5125            if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
5126                ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
5127                outputBufferFull = true;
5128                break;
5129            }
5130            uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5131            if (waitTimeLeftMs >= waitTimeMs) {
5132                waitTimeLeftMs -= waitTimeMs;
5133            } else {
5134                waitTimeLeftMs = 0;
5135            }
5136        }
5137
5138        uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5139        memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5140        mCblk->stepUser(outFrames);
5141        pInBuffer->frameCount -= outFrames;
5142        pInBuffer->i16 += outFrames * channelCount;
5143        mOutBuffer.frameCount -= outFrames;
5144        mOutBuffer.i16 += outFrames * channelCount;
5145
5146        if (pInBuffer->frameCount == 0) {
5147            if (mBufferQueue.size()) {
5148                mBufferQueue.removeAt(0);
5149                delete [] pInBuffer->mBuffer;
5150                delete pInBuffer;
5151                ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
5152            } else {
5153                break;
5154            }
5155        }
5156    }
5157
5158    // If we could not write all frames, allocate a buffer and queue it for next time.
5159    if (inBuffer.frameCount) {
5160        sp<ThreadBase> thread = mThread.promote();
5161        if (thread != 0 && !thread->standby()) {
5162            if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5163                pInBuffer = new Buffer;
5164                pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5165                pInBuffer->frameCount = inBuffer.frameCount;
5166                pInBuffer->i16 = pInBuffer->mBuffer;
5167                memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5168                mBufferQueue.add(pInBuffer);
5169                ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
5170            } else {
5171                ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
5172            }
5173        }
5174    }
5175
5176    // Calling write() with a 0 length buffer, means that no more data will be written:
5177    // If no more buffers are pending, fill output track buffer to make sure it is started
5178    // by output mixer.
5179    if (frames == 0 && mBufferQueue.size() == 0) {
5180        if (mCblk->user < mCblk->frameCount) {
5181            frames = mCblk->frameCount - mCblk->user;
5182            pInBuffer = new Buffer;
5183            pInBuffer->mBuffer = new int16_t[frames * channelCount];
5184            pInBuffer->frameCount = frames;
5185            pInBuffer->i16 = pInBuffer->mBuffer;
5186            memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5187            mBufferQueue.add(pInBuffer);
5188        } else if (mActive) {
5189            stop();
5190        }
5191    }
5192
5193    return outputBufferFull;
5194}
5195
5196status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5197{
5198    int active;
5199    status_t result;
5200    audio_track_cblk_t* cblk = mCblk;
5201    uint32_t framesReq = buffer->frameCount;
5202
5203//    ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
5204    buffer->frameCount  = 0;
5205
5206    uint32_t framesAvail = cblk->framesAvailable();
5207
5208
5209    if (framesAvail == 0) {
5210        Mutex::Autolock _l(cblk->lock);
5211        goto start_loop_here;
5212        while (framesAvail == 0) {
5213            active = mActive;
5214            if (CC_UNLIKELY(!active)) {
5215                ALOGV("Not active and NO_MORE_BUFFERS");
5216                return NO_MORE_BUFFERS;
5217            }
5218            result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5219            if (result != NO_ERROR) {
5220                return NO_MORE_BUFFERS;
5221            }
5222            // read the server count again
5223        start_loop_here:
5224            framesAvail = cblk->framesAvailable_l();
5225        }
5226    }
5227
5228//    if (framesAvail < framesReq) {
5229//        return NO_MORE_BUFFERS;
5230//    }
5231
5232    if (framesReq > framesAvail) {
5233        framesReq = framesAvail;
5234    }
5235
5236    uint32_t u = cblk->user;
5237    uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5238
5239    if (framesReq > bufferEnd - u) {
5240        framesReq = bufferEnd - u;
5241    }
5242
5243    buffer->frameCount  = framesReq;
5244    buffer->raw         = (void *)cblk->buffer(u);
5245    return NO_ERROR;
5246}
5247
5248
5249void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5250{
5251    size_t size = mBufferQueue.size();
5252
5253    for (size_t i = 0; i < size; i++) {
5254        Buffer *pBuffer = mBufferQueue.itemAt(i);
5255        delete [] pBuffer->mBuffer;
5256        delete pBuffer;
5257    }
5258    mBufferQueue.clear();
5259}
5260
5261// ----------------------------------------------------------------------------
5262
5263AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5264    :   RefBase(),
5265        mAudioFlinger(audioFlinger),
5266        // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
5267        mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
5268        mPid(pid),
5269        mTimedTrackCount(0)
5270{
5271    // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5272}
5273
5274// Client destructor must be called with AudioFlinger::mLock held
5275AudioFlinger::Client::~Client()
5276{
5277    mAudioFlinger->removeClient_l(mPid);
5278}
5279
5280sp<MemoryDealer> AudioFlinger::Client::heap() const
5281{
5282    return mMemoryDealer;
5283}
5284
5285// Reserve one of the limited slots for a timed audio track associated
5286// with this client
5287bool AudioFlinger::Client::reserveTimedTrack()
5288{
5289    const int kMaxTimedTracksPerClient = 4;
5290
5291    Mutex::Autolock _l(mTimedTrackLock);
5292
5293    if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5294        ALOGW("can not create timed track - pid %d has exceeded the limit",
5295             mPid);
5296        return false;
5297    }
5298
5299    mTimedTrackCount++;
5300    return true;
5301}
5302
5303// Release a slot for a timed audio track
5304void AudioFlinger::Client::releaseTimedTrack()
5305{
5306    Mutex::Autolock _l(mTimedTrackLock);
5307    mTimedTrackCount--;
5308}
5309
5310// ----------------------------------------------------------------------------
5311
5312AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5313                                                     const sp<IAudioFlingerClient>& client,
5314                                                     pid_t pid)
5315    : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
5316{
5317}
5318
5319AudioFlinger::NotificationClient::~NotificationClient()
5320{
5321}
5322
5323void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5324{
5325    sp<NotificationClient> keep(this);
5326    mAudioFlinger->removeNotificationClient(mPid);
5327}
5328
5329// ----------------------------------------------------------------------------
5330
5331AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5332    : BnAudioTrack(),
5333      mTrack(track)
5334{
5335}
5336
5337AudioFlinger::TrackHandle::~TrackHandle() {
5338    // just stop the track on deletion, associated resources
5339    // will be freed from the main thread once all pending buffers have
5340    // been played. Unless it's not in the active track list, in which
5341    // case we free everything now...
5342    mTrack->destroy();
5343}
5344
5345sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5346    return mTrack->getCblk();
5347}
5348
5349status_t AudioFlinger::TrackHandle::start() {
5350    return mTrack->start();
5351}
5352
5353void AudioFlinger::TrackHandle::stop() {
5354    mTrack->stop();
5355}
5356
5357void AudioFlinger::TrackHandle::flush() {
5358    mTrack->flush();
5359}
5360
5361void AudioFlinger::TrackHandle::mute(bool e) {
5362    mTrack->mute(e);
5363}
5364
5365void AudioFlinger::TrackHandle::pause() {
5366    mTrack->pause();
5367}
5368
5369status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5370{
5371    return mTrack->attachAuxEffect(EffectId);
5372}
5373
5374status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5375                                                         sp<IMemory>* buffer) {
5376    if (!mTrack->isTimedTrack())
5377        return INVALID_OPERATION;
5378
5379    PlaybackThread::TimedTrack* tt =
5380            reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5381    return tt->allocateTimedBuffer(size, buffer);
5382}
5383
5384status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5385                                                     int64_t pts) {
5386    if (!mTrack->isTimedTrack())
5387        return INVALID_OPERATION;
5388
5389    PlaybackThread::TimedTrack* tt =
5390            reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5391    return tt->queueTimedBuffer(buffer, pts);
5392}
5393
5394status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5395    const LinearTransform& xform, int target) {
5396
5397    if (!mTrack->isTimedTrack())
5398        return INVALID_OPERATION;
5399
5400    PlaybackThread::TimedTrack* tt =
5401            reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5402    return tt->setMediaTimeTransform(
5403        xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5404}
5405
5406status_t AudioFlinger::TrackHandle::onTransact(
5407    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5408{
5409    return BnAudioTrack::onTransact(code, data, reply, flags);
5410}
5411
5412// ----------------------------------------------------------------------------
5413
5414sp<IAudioRecord> AudioFlinger::openRecord(
5415        pid_t pid,
5416        audio_io_handle_t input,
5417        uint32_t sampleRate,
5418        audio_format_t format,
5419        uint32_t channelMask,
5420        int frameCount,
5421        IAudioFlinger::track_flags_t flags,
5422        int *sessionId,
5423        status_t *status)
5424{
5425    sp<RecordThread::RecordTrack> recordTrack;
5426    sp<RecordHandle> recordHandle;
5427    sp<Client> client;
5428    status_t lStatus;
5429    RecordThread *thread;
5430    size_t inFrameCount;
5431    int lSessionId;
5432
5433    // check calling permissions
5434    if (!recordingAllowed()) {
5435        lStatus = PERMISSION_DENIED;
5436        goto Exit;
5437    }
5438
5439    // add client to list
5440    { // scope for mLock
5441        Mutex::Autolock _l(mLock);
5442        thread = checkRecordThread_l(input);
5443        if (thread == NULL) {
5444            lStatus = BAD_VALUE;
5445            goto Exit;
5446        }
5447
5448        client = registerPid_l(pid);
5449
5450        // If no audio session id is provided, create one here
5451        if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
5452            lSessionId = *sessionId;
5453        } else {
5454            lSessionId = nextUniqueId();
5455            if (sessionId != NULL) {
5456                *sessionId = lSessionId;
5457            }
5458        }
5459        // create new record track. The record track uses one track in mHardwareMixerThread by convention.
5460        recordTrack = thread->createRecordTrack_l(client,
5461                                                sampleRate,
5462                                                format,
5463                                                channelMask,
5464                                                frameCount,
5465                                                lSessionId,
5466                                                &lStatus);
5467    }
5468    if (lStatus != NO_ERROR) {
5469        // remove local strong reference to Client before deleting the RecordTrack so that the Client
5470        // destructor is called by the TrackBase destructor with mLock held
5471        client.clear();
5472        recordTrack.clear();
5473        goto Exit;
5474    }
5475
5476    // return to handle to client
5477    recordHandle = new RecordHandle(recordTrack);
5478    lStatus = NO_ERROR;
5479
5480Exit:
5481    if (status) {
5482        *status = lStatus;
5483    }
5484    return recordHandle;
5485}
5486
5487// ----------------------------------------------------------------------------
5488
5489AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5490    : BnAudioRecord(),
5491    mRecordTrack(recordTrack)
5492{
5493}
5494
5495AudioFlinger::RecordHandle::~RecordHandle() {
5496    stop();
5497}
5498
5499sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5500    return mRecordTrack->getCblk();
5501}
5502
5503status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
5504    ALOGV("RecordHandle::start()");
5505    return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
5506}
5507
5508void AudioFlinger::RecordHandle::stop() {
5509    ALOGV("RecordHandle::stop()");
5510    mRecordTrack->stop();
5511}
5512
5513status_t AudioFlinger::RecordHandle::onTransact(
5514    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5515{
5516    return BnAudioRecord::onTransact(code, data, reply, flags);
5517}
5518
5519// ----------------------------------------------------------------------------
5520
5521AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5522                                         AudioStreamIn *input,
5523                                         uint32_t sampleRate,
5524                                         uint32_t channels,
5525                                         audio_io_handle_t id,
5526                                         uint32_t device) :
5527    ThreadBase(audioFlinger, id, device, RECORD),
5528    mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5529    // mRsmpInIndex and mInputBytes set by readInputParameters()
5530    mReqChannelCount(popcount(channels)),
5531    mReqSampleRate(sampleRate)
5532    // mBytesRead is only meaningful while active, and so is cleared in start()
5533    // (but might be better to also clear here for dump?)
5534{
5535    snprintf(mName, kNameLength, "AudioIn_%X", id);
5536
5537    readInputParameters();
5538}
5539
5540
5541AudioFlinger::RecordThread::~RecordThread()
5542{
5543    delete[] mRsmpInBuffer;
5544    delete mResampler;
5545    delete[] mRsmpOutBuffer;
5546}
5547
5548void AudioFlinger::RecordThread::onFirstRef()
5549{
5550    run(mName, PRIORITY_URGENT_AUDIO);
5551}
5552
5553status_t AudioFlinger::RecordThread::readyToRun()
5554{
5555    status_t status = initCheck();
5556    ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
5557    return status;
5558}
5559
5560bool AudioFlinger::RecordThread::threadLoop()
5561{
5562    AudioBufferProvider::Buffer buffer;
5563    sp<RecordTrack> activeTrack;
5564    Vector< sp<EffectChain> > effectChains;
5565
5566    nsecs_t lastWarning = 0;
5567
5568    acquireWakeLock();
5569
5570    // start recording
5571    while (!exitPending()) {
5572
5573        processConfigEvents();
5574
5575        { // scope for mLock
5576            Mutex::Autolock _l(mLock);
5577            checkForNewParameters_l();
5578            if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5579                if (!mStandby) {
5580                    mInput->stream->common.standby(&mInput->stream->common);
5581                    mStandby = true;
5582                }
5583
5584                if (exitPending()) break;
5585
5586                releaseWakeLock_l();
5587                ALOGV("RecordThread: loop stopping");
5588                // go to sleep
5589                mWaitWorkCV.wait(mLock);
5590                ALOGV("RecordThread: loop starting");
5591                acquireWakeLock_l();
5592                continue;
5593            }
5594            if (mActiveTrack != 0) {
5595                if (mActiveTrack->mState == TrackBase::PAUSING) {
5596                    if (!mStandby) {
5597                        mInput->stream->common.standby(&mInput->stream->common);
5598                        mStandby = true;
5599                    }
5600                    mActiveTrack.clear();
5601                    mStartStopCond.broadcast();
5602                } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5603                    if (mReqChannelCount != mActiveTrack->channelCount()) {
5604                        mActiveTrack.clear();
5605                        mStartStopCond.broadcast();
5606                    } else if (mBytesRead != 0) {
5607                        // record start succeeds only if first read from audio input
5608                        // succeeds
5609                        if (mBytesRead > 0) {
5610                            mActiveTrack->mState = TrackBase::ACTIVE;
5611                        } else {
5612                            mActiveTrack.clear();
5613                        }
5614                        mStartStopCond.broadcast();
5615                    }
5616                    mStandby = false;
5617                }
5618            }
5619            lockEffectChains_l(effectChains);
5620        }
5621
5622        if (mActiveTrack != 0) {
5623            if (mActiveTrack->mState != TrackBase::ACTIVE &&
5624                mActiveTrack->mState != TrackBase::RESUMING) {
5625                unlockEffectChains(effectChains);
5626                usleep(kRecordThreadSleepUs);
5627                continue;
5628            }
5629            for (size_t i = 0; i < effectChains.size(); i ++) {
5630                effectChains[i]->process_l();
5631            }
5632
5633            buffer.frameCount = mFrameCount;
5634            if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
5635                size_t framesOut = buffer.frameCount;
5636                if (mResampler == NULL) {
5637                    // no resampling
5638                    while (framesOut) {
5639                        size_t framesIn = mFrameCount - mRsmpInIndex;
5640                        if (framesIn) {
5641                            int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5642                            int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5643                            if (framesIn > framesOut)
5644                                framesIn = framesOut;
5645                            mRsmpInIndex += framesIn;
5646                            framesOut -= framesIn;
5647                            if ((int)mChannelCount == mReqChannelCount ||
5648                                mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5649                                memcpy(dst, src, framesIn * mFrameSize);
5650                            } else {
5651                                int16_t *src16 = (int16_t *)src;
5652                                int16_t *dst16 = (int16_t *)dst;
5653                                if (mChannelCount == 1) {
5654                                    while (framesIn--) {
5655                                        *dst16++ = *src16;
5656                                        *dst16++ = *src16++;
5657                                    }
5658                                } else {
5659                                    while (framesIn--) {
5660                                        *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5661                                        src16 += 2;
5662                                    }
5663                                }
5664                            }
5665                        }
5666                        if (framesOut && mFrameCount == mRsmpInIndex) {
5667                            if (framesOut == mFrameCount &&
5668                                ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
5669                                mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
5670                                framesOut = 0;
5671                            } else {
5672                                mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
5673                                mRsmpInIndex = 0;
5674                            }
5675                            if (mBytesRead < 0) {
5676                                ALOGE("Error reading audio input");
5677                                if (mActiveTrack->mState == TrackBase::ACTIVE) {
5678                                    // Force input into standby so that it tries to
5679                                    // recover at next read attempt
5680                                    mInput->stream->common.standby(&mInput->stream->common);
5681                                    usleep(kRecordThreadSleepUs);
5682                                }
5683                                mRsmpInIndex = mFrameCount;
5684                                framesOut = 0;
5685                                buffer.frameCount = 0;
5686                            }
5687                        }
5688                    }
5689                } else {
5690                    // resampling
5691
5692                    memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5693                    // alter output frame count as if we were expecting stereo samples
5694                    if (mChannelCount == 1 && mReqChannelCount == 1) {
5695                        framesOut >>= 1;
5696                    }
5697                    mResampler->resample(mRsmpOutBuffer, framesOut, this);
5698                    // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5699                    // are 32 bit aligned which should be always true.
5700                    if (mChannelCount == 2 && mReqChannelCount == 1) {
5701                        ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
5702                        // the resampler always outputs stereo samples: do post stereo to mono conversion
5703                        int16_t *src = (int16_t *)mRsmpOutBuffer;
5704                        int16_t *dst = buffer.i16;
5705                        while (framesOut--) {
5706                            *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5707                            src += 2;
5708                        }
5709                    } else {
5710                        ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
5711                    }
5712
5713                }
5714                if (mFramestoDrop == 0) {
5715                    mActiveTrack->releaseBuffer(&buffer);
5716                } else {
5717                    if (mFramestoDrop > 0) {
5718                        mFramestoDrop -= buffer.frameCount;
5719                        if (mFramestoDrop < 0) {
5720                            mFramestoDrop = 0;
5721                        }
5722                    }
5723                }
5724                mActiveTrack->overflow();
5725            }
5726            // client isn't retrieving buffers fast enough
5727            else {
5728                if (!mActiveTrack->setOverflow()) {
5729                    nsecs_t now = systemTime();
5730                    if ((now - lastWarning) > kWarningThrottleNs) {
5731                        ALOGW("RecordThread: buffer overflow");
5732                        lastWarning = now;
5733                    }
5734                }
5735                // Release the processor for a while before asking for a new buffer.
5736                // This will give the application more chance to read from the buffer and
5737                // clear the overflow.
5738                usleep(kRecordThreadSleepUs);
5739            }
5740        }
5741        // enable changes in effect chain
5742        unlockEffectChains(effectChains);
5743        effectChains.clear();
5744    }
5745
5746    if (!mStandby) {
5747        mInput->stream->common.standby(&mInput->stream->common);
5748    }
5749    mActiveTrack.clear();
5750
5751    mStartStopCond.broadcast();
5752
5753    releaseWakeLock();
5754
5755    ALOGV("RecordThread %p exiting", this);
5756    return false;
5757}
5758
5759
5760sp<AudioFlinger::RecordThread::RecordTrack>  AudioFlinger::RecordThread::createRecordTrack_l(
5761        const sp<AudioFlinger::Client>& client,
5762        uint32_t sampleRate,
5763        audio_format_t format,
5764        int channelMask,
5765        int frameCount,
5766        int sessionId,
5767        status_t *status)
5768{
5769    sp<RecordTrack> track;
5770    status_t lStatus;
5771
5772    lStatus = initCheck();
5773    if (lStatus != NO_ERROR) {
5774        ALOGE("Audio driver not initialized.");
5775        goto Exit;
5776    }
5777
5778    { // scope for mLock
5779        Mutex::Autolock _l(mLock);
5780
5781        track = new RecordTrack(this, client, sampleRate,
5782                      format, channelMask, frameCount, sessionId);
5783
5784        if (track->getCblk() == 0) {
5785            lStatus = NO_MEMORY;
5786            goto Exit;
5787        }
5788
5789        mTrack = track.get();
5790        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5791        bool suspend = audio_is_bluetooth_sco_device(
5792                (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
5793        setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5794        setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
5795    }
5796    lStatus = NO_ERROR;
5797
5798Exit:
5799    if (status) {
5800        *status = lStatus;
5801    }
5802    return track;
5803}
5804
5805status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5806                                           AudioSystem::sync_event_t event,
5807                                           int triggerSession)
5808{
5809    ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5810    sp<ThreadBase> strongMe = this;
5811    status_t status = NO_ERROR;
5812
5813    if (event == AudioSystem::SYNC_EVENT_NONE) {
5814        mSyncStartEvent.clear();
5815        mFramestoDrop = 0;
5816    } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5817        mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5818                                       triggerSession,
5819                                       recordTrack->sessionId(),
5820                                       syncStartEventCallback,
5821                                       this);
5822        mFramestoDrop = -1;
5823    }
5824
5825    {
5826        AutoMutex lock(mLock);
5827        if (mActiveTrack != 0) {
5828            if (recordTrack != mActiveTrack.get()) {
5829                status = -EBUSY;
5830            } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5831                mActiveTrack->mState = TrackBase::ACTIVE;
5832            }
5833            return status;
5834        }
5835
5836        recordTrack->mState = TrackBase::IDLE;
5837        mActiveTrack = recordTrack;
5838        mLock.unlock();
5839        status_t status = AudioSystem::startInput(mId);
5840        mLock.lock();
5841        if (status != NO_ERROR) {
5842            mActiveTrack.clear();
5843            clearSyncStartEvent();
5844            return status;
5845        }
5846        mRsmpInIndex = mFrameCount;
5847        mBytesRead = 0;
5848        if (mResampler != NULL) {
5849            mResampler->reset();
5850        }
5851        mActiveTrack->mState = TrackBase::RESUMING;
5852        // signal thread to start
5853        ALOGV("Signal record thread");
5854        mWaitWorkCV.signal();
5855        // do not wait for mStartStopCond if exiting
5856        if (exitPending()) {
5857            mActiveTrack.clear();
5858            status = INVALID_OPERATION;
5859            goto startError;
5860        }
5861        mStartStopCond.wait(mLock);
5862        if (mActiveTrack == 0) {
5863            ALOGV("Record failed to start");
5864            status = BAD_VALUE;
5865            goto startError;
5866        }
5867        ALOGV("Record started OK");
5868        return status;
5869    }
5870startError:
5871    AudioSystem::stopInput(mId);
5872    clearSyncStartEvent();
5873    return status;
5874}
5875
5876void AudioFlinger::RecordThread::clearSyncStartEvent()
5877{
5878    if (mSyncStartEvent != 0) {
5879        mSyncStartEvent->cancel();
5880    }
5881    mSyncStartEvent.clear();
5882}
5883
5884void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5885{
5886    sp<SyncEvent> strongEvent = event.promote();
5887
5888    if (strongEvent != 0) {
5889        RecordThread *me = (RecordThread *)strongEvent->cookie();
5890        me->handleSyncStartEvent(strongEvent);
5891    }
5892}
5893
5894void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
5895{
5896    ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
5897              mActiveTrack.get(),
5898              mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
5899              event->listenerSession());
5900
5901    if (mActiveTrack != 0 &&
5902            event == mSyncStartEvent) {
5903        // TODO: use actual buffer filling status instead of 2 buffers when info is available
5904        // from audio HAL
5905        mFramestoDrop = mFrameCount * 2;
5906        mSyncStartEvent.clear();
5907    }
5908}
5909
5910void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
5911    ALOGV("RecordThread::stop");
5912    sp<ThreadBase> strongMe = this;
5913    {
5914        AutoMutex lock(mLock);
5915        if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5916            mActiveTrack->mState = TrackBase::PAUSING;
5917            // do not wait for mStartStopCond if exiting
5918            if (exitPending()) {
5919                return;
5920            }
5921            mStartStopCond.wait(mLock);
5922            // if we have been restarted, recordTrack == mActiveTrack.get() here
5923            if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5924                mLock.unlock();
5925                AudioSystem::stopInput(mId);
5926                mLock.lock();
5927                ALOGV("Record stopped OK");
5928            }
5929        }
5930    }
5931}
5932
5933bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
5934{
5935    return false;
5936}
5937
5938status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
5939{
5940    if (!isValidSyncEvent(event)) {
5941        return BAD_VALUE;
5942    }
5943
5944    Mutex::Autolock _l(mLock);
5945
5946    if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
5947        mTrack->setSyncEvent(event);
5948        return NO_ERROR;
5949    }
5950    return NAME_NOT_FOUND;
5951}
5952
5953status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5954{
5955    const size_t SIZE = 256;
5956    char buffer[SIZE];
5957    String8 result;
5958
5959    snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5960    result.append(buffer);
5961
5962    if (mActiveTrack != 0) {
5963        result.append("Active Track:\n");
5964        result.append("   Clien Fmt Chn mask   Session Buf  S SRate  Serv     User\n");
5965        mActiveTrack->dump(buffer, SIZE);
5966        result.append(buffer);
5967
5968        snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5969        result.append(buffer);
5970        snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5971        result.append(buffer);
5972        snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
5973        result.append(buffer);
5974        snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5975        result.append(buffer);
5976        snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5977        result.append(buffer);
5978
5979
5980    } else {
5981        result.append("No record client\n");
5982    }
5983    write(fd, result.string(), result.size());
5984
5985    dumpBase(fd, args);
5986    dumpEffectChains(fd, args);
5987
5988    return NO_ERROR;
5989}
5990
5991// AudioBufferProvider interface
5992status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
5993{
5994    size_t framesReq = buffer->frameCount;
5995    size_t framesReady = mFrameCount - mRsmpInIndex;
5996    int channelCount;
5997
5998    if (framesReady == 0) {
5999        mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
6000        if (mBytesRead < 0) {
6001            ALOGE("RecordThread::getNextBuffer() Error reading audio input");
6002            if (mActiveTrack->mState == TrackBase::ACTIVE) {
6003                // Force input into standby so that it tries to
6004                // recover at next read attempt
6005                mInput->stream->common.standby(&mInput->stream->common);
6006                usleep(kRecordThreadSleepUs);
6007            }
6008            buffer->raw = NULL;
6009            buffer->frameCount = 0;
6010            return NOT_ENOUGH_DATA;
6011        }
6012        mRsmpInIndex = 0;
6013        framesReady = mFrameCount;
6014    }
6015
6016    if (framesReq > framesReady) {
6017        framesReq = framesReady;
6018    }
6019
6020    if (mChannelCount == 1 && mReqChannelCount == 2) {
6021        channelCount = 1;
6022    } else {
6023        channelCount = 2;
6024    }
6025    buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6026    buffer->frameCount = framesReq;
6027    return NO_ERROR;
6028}
6029
6030// AudioBufferProvider interface
6031void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6032{
6033    mRsmpInIndex += buffer->frameCount;
6034    buffer->frameCount = 0;
6035}
6036
6037bool AudioFlinger::RecordThread::checkForNewParameters_l()
6038{
6039    bool reconfig = false;
6040
6041    while (!mNewParameters.isEmpty()) {
6042        status_t status = NO_ERROR;
6043        String8 keyValuePair = mNewParameters[0];
6044        AudioParameter param = AudioParameter(keyValuePair);
6045        int value;
6046        audio_format_t reqFormat = mFormat;
6047        int reqSamplingRate = mReqSampleRate;
6048        int reqChannelCount = mReqChannelCount;
6049
6050        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6051            reqSamplingRate = value;
6052            reconfig = true;
6053        }
6054        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6055            reqFormat = (audio_format_t) value;
6056            reconfig = true;
6057        }
6058        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6059            reqChannelCount = popcount(value);
6060            reconfig = true;
6061        }
6062        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6063            // do not accept frame count changes if tracks are open as the track buffer
6064            // size depends on frame count and correct behavior would not be guaranteed
6065            // if frame count is changed after track creation
6066            if (mActiveTrack != 0) {
6067                status = INVALID_OPERATION;
6068            } else {
6069                reconfig = true;
6070            }
6071        }
6072        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6073            // forward device change to effects that have requested to be
6074            // aware of attached audio device.
6075            for (size_t i = 0; i < mEffectChains.size(); i++) {
6076                mEffectChains[i]->setDevice_l(value);
6077            }
6078            // store input device and output device but do not forward output device to audio HAL.
6079            // Note that status is ignored by the caller for output device
6080            // (see AudioFlinger::setParameters()
6081            if (value & AUDIO_DEVICE_OUT_ALL) {
6082                mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6083                status = BAD_VALUE;
6084            } else {
6085                mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
6086                // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6087                if (mTrack != NULL) {
6088                    bool suspend = audio_is_bluetooth_sco_device(
6089                            (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
6090                    setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6091                    setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6092                }
6093            }
6094            mDevice |= (uint32_t)value;
6095        }
6096        if (status == NO_ERROR) {
6097            status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
6098            if (status == INVALID_OPERATION) {
6099                mInput->stream->common.standby(&mInput->stream->common);
6100                status = mInput->stream->common.set_parameters(&mInput->stream->common,
6101                        keyValuePair.string());
6102            }
6103            if (reconfig) {
6104                if (status == BAD_VALUE &&
6105                    reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6106                    reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6107                    ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
6108                    popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6109                    (reqChannelCount <= FCC_2)) {
6110                    status = NO_ERROR;
6111                }
6112                if (status == NO_ERROR) {
6113                    readInputParameters();
6114                    sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6115                }
6116            }
6117        }
6118
6119        mNewParameters.removeAt(0);
6120
6121        mParamStatus = status;
6122        mParamCond.signal();
6123        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6124        // already timed out waiting for the status and will never signal the condition.
6125        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
6126    }
6127    return reconfig;
6128}
6129
6130String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6131{
6132    char *s;
6133    String8 out_s8 = String8();
6134
6135    Mutex::Autolock _l(mLock);
6136    if (initCheck() != NO_ERROR) {
6137        return out_s8;
6138    }
6139
6140    s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6141    out_s8 = String8(s);
6142    free(s);
6143    return out_s8;
6144}
6145
6146void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6147    AudioSystem::OutputDescriptor desc;
6148    void *param2 = NULL;
6149
6150    switch (event) {
6151    case AudioSystem::INPUT_OPENED:
6152    case AudioSystem::INPUT_CONFIG_CHANGED:
6153        desc.channels = mChannelMask;
6154        desc.samplingRate = mSampleRate;
6155        desc.format = mFormat;
6156        desc.frameCount = mFrameCount;
6157        desc.latency = 0;
6158        param2 = &desc;
6159        break;
6160
6161    case AudioSystem::INPUT_CLOSED:
6162    default:
6163        break;
6164    }
6165    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6166}
6167
6168void AudioFlinger::RecordThread::readInputParameters()
6169{
6170    delete mRsmpInBuffer;
6171    // mRsmpInBuffer is always assigned a new[] below
6172    delete mRsmpOutBuffer;
6173    mRsmpOutBuffer = NULL;
6174    delete mResampler;
6175    mResampler = NULL;
6176
6177    mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6178    mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6179    mChannelCount = (uint16_t)popcount(mChannelMask);
6180    mFormat = mInput->stream->common.get_format(&mInput->stream->common);
6181    mFrameSize = audio_stream_frame_size(&mInput->stream->common);
6182    mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6183    mFrameCount = mInputBytes / mFrameSize;
6184    mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
6185    mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6186
6187    if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
6188    {
6189        int channelCount;
6190        // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6191        // stereo to mono post process as the resampler always outputs stereo.
6192        if (mChannelCount == 1 && mReqChannelCount == 2) {
6193            channelCount = 1;
6194        } else {
6195            channelCount = 2;
6196        }
6197        mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6198        mResampler->setSampleRate(mSampleRate);
6199        mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6200        mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6201
6202        // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6203        if (mChannelCount == 1 && mReqChannelCount == 1) {
6204            mFrameCount >>= 1;
6205        }
6206
6207    }
6208    mRsmpInIndex = mFrameCount;
6209}
6210
6211unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6212{
6213    Mutex::Autolock _l(mLock);
6214    if (initCheck() != NO_ERROR) {
6215        return 0;
6216    }
6217
6218    return mInput->stream->get_input_frames_lost(mInput->stream);
6219}
6220
6221uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6222{
6223    Mutex::Autolock _l(mLock);
6224    uint32_t result = 0;
6225    if (getEffectChain_l(sessionId) != 0) {
6226        result = EFFECT_SESSION;
6227    }
6228
6229    if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6230        result |= TRACK_SESSION;
6231    }
6232
6233    return result;
6234}
6235
6236AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6237{
6238    Mutex::Autolock _l(mLock);
6239    return mTrack;
6240}
6241
6242AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
6243{
6244    Mutex::Autolock _l(mLock);
6245    return mInput;
6246}
6247
6248AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6249{
6250    Mutex::Autolock _l(mLock);
6251    AudioStreamIn *input = mInput;
6252    mInput = NULL;
6253    return input;
6254}
6255
6256// this method must always be called either with ThreadBase mLock held or inside the thread loop
6257audio_stream_t* AudioFlinger::RecordThread::stream() const
6258{
6259    if (mInput == NULL) {
6260        return NULL;
6261    }
6262    return &mInput->stream->common;
6263}
6264
6265
6266// ----------------------------------------------------------------------------
6267
6268audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6269{
6270    if (!settingsAllowed()) {
6271        return 0;
6272    }
6273    Mutex::Autolock _l(mLock);
6274    return loadHwModule_l(name);
6275}
6276
6277// loadHwModule_l() must be called with AudioFlinger::mLock held
6278audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6279{
6280    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6281        if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6282            ALOGW("loadHwModule() module %s already loaded", name);
6283            return mAudioHwDevs.keyAt(i);
6284        }
6285    }
6286
6287    audio_hw_device_t *dev;
6288
6289    int rc = load_audio_interface(name, &dev);
6290    if (rc) {
6291        ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6292        return 0;
6293    }
6294
6295    mHardwareStatus = AUDIO_HW_INIT;
6296    rc = dev->init_check(dev);
6297    mHardwareStatus = AUDIO_HW_IDLE;
6298    if (rc) {
6299        ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6300        return 0;
6301    }
6302
6303    if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6304        (NULL != dev->set_master_volume)) {
6305        AutoMutex lock(mHardwareLock);
6306        mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6307        dev->set_master_volume(dev, mMasterVolume);
6308        mHardwareStatus = AUDIO_HW_IDLE;
6309    }
6310
6311    audio_module_handle_t handle = nextUniqueId();
6312    mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6313
6314    ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
6315          name, dev->common.module->name, dev->common.module->id, handle);
6316
6317    return handle;
6318
6319}
6320
6321audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6322                                           audio_devices_t *pDevices,
6323                                           uint32_t *pSamplingRate,
6324                                           audio_format_t *pFormat,
6325                                           audio_channel_mask_t *pChannelMask,
6326                                           uint32_t *pLatencyMs,
6327                                           audio_output_flags_t flags)
6328{
6329    status_t status;
6330    PlaybackThread *thread = NULL;
6331    struct audio_config config = {
6332        sample_rate: pSamplingRate ? *pSamplingRate : 0,
6333        channel_mask: pChannelMask ? *pChannelMask : 0,
6334        format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6335    };
6336    audio_stream_out_t *outStream = NULL;
6337    audio_hw_device_t *outHwDev;
6338
6339    ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6340              module,
6341              (pDevices != NULL) ? (int)*pDevices : 0,
6342              config.sample_rate,
6343              config.format,
6344              config.channel_mask,
6345              flags);
6346
6347    if (pDevices == NULL || *pDevices == 0) {
6348        return 0;
6349    }
6350
6351    Mutex::Autolock _l(mLock);
6352
6353    outHwDev = findSuitableHwDev_l(module, *pDevices);
6354    if (outHwDev == NULL)
6355        return 0;
6356
6357    audio_io_handle_t id = nextUniqueId();
6358
6359    mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
6360
6361    status = outHwDev->open_output_stream(outHwDev,
6362                                          id,
6363                                          *pDevices,
6364                                          (audio_output_flags_t)flags,
6365                                          &config,
6366                                          &outStream);
6367
6368    mHardwareStatus = AUDIO_HW_IDLE;
6369    ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
6370            outStream,
6371            config.sample_rate,
6372            config.format,
6373            config.channel_mask,
6374            status);
6375
6376    if (status == NO_ERROR && outStream != NULL) {
6377        AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
6378
6379        if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
6380            (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6381            (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
6382            thread = new DirectOutputThread(this, output, id, *pDevices);
6383            ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
6384        } else {
6385            thread = new MixerThread(this, output, id, *pDevices);
6386            ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
6387        }
6388        mPlaybackThreads.add(id, thread);
6389
6390        if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6391        if (pFormat != NULL) *pFormat = config.format;
6392        if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
6393        if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
6394
6395        // notify client processes of the new output creation
6396        thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6397
6398        // the first primary output opened designates the primary hw device
6399        if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
6400            ALOGI("Using module %d has the primary audio interface", module);
6401            mPrimaryHardwareDev = outHwDev;
6402
6403            AutoMutex lock(mHardwareLock);
6404            mHardwareStatus = AUDIO_HW_SET_MODE;
6405            outHwDev->set_mode(outHwDev, mMode);
6406
6407            // Determine the level of master volume support the primary audio HAL has,
6408            // and set the initial master volume at the same time.
6409            float initialVolume = 1.0;
6410            mMasterVolumeSupportLvl = MVS_NONE;
6411
6412            mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6413            if ((NULL != outHwDev->get_master_volume) &&
6414                (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6415                mMasterVolumeSupportLvl = MVS_FULL;
6416            } else {
6417                mMasterVolumeSupportLvl = MVS_SETONLY;
6418                initialVolume = 1.0;
6419            }
6420
6421            mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6422            if ((NULL == outHwDev->set_master_volume) ||
6423                (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6424                mMasterVolumeSupportLvl = MVS_NONE;
6425            }
6426            // now that we have a primary device, initialize master volume on other devices
6427            for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6428                audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6429
6430                if ((dev != mPrimaryHardwareDev) &&
6431                    (NULL != dev->set_master_volume)) {
6432                    dev->set_master_volume(dev, initialVolume);
6433                }
6434            }
6435            mHardwareStatus = AUDIO_HW_IDLE;
6436            mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6437                                    ? initialVolume
6438                                    : 1.0;
6439            mMasterVolume   = initialVolume;
6440        }
6441        return id;
6442    }
6443
6444    return 0;
6445}
6446
6447audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6448        audio_io_handle_t output2)
6449{
6450    Mutex::Autolock _l(mLock);
6451    MixerThread *thread1 = checkMixerThread_l(output1);
6452    MixerThread *thread2 = checkMixerThread_l(output2);
6453
6454    if (thread1 == NULL || thread2 == NULL) {
6455        ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
6456        return 0;
6457    }
6458
6459    audio_io_handle_t id = nextUniqueId();
6460    DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6461    thread->addOutputTrack(thread2);
6462    mPlaybackThreads.add(id, thread);
6463    // notify client processes of the new output creation
6464    thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6465    return id;
6466}
6467
6468status_t AudioFlinger::closeOutput(audio_io_handle_t output)
6469{
6470    // keep strong reference on the playback thread so that
6471    // it is not destroyed while exit() is executed
6472    sp<PlaybackThread> thread;
6473    {
6474        Mutex::Autolock _l(mLock);
6475        thread = checkPlaybackThread_l(output);
6476        if (thread == NULL) {
6477            return BAD_VALUE;
6478        }
6479
6480        ALOGV("closeOutput() %d", output);
6481
6482        if (thread->type() == ThreadBase::MIXER) {
6483            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6484                if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
6485                    DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6486                    dupThread->removeOutputTrack((MixerThread *)thread.get());
6487                }
6488            }
6489        }
6490        audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
6491        mPlaybackThreads.removeItem(output);
6492    }
6493    thread->exit();
6494    // The thread entity (active unit of execution) is no longer running here,
6495    // but the ThreadBase container still exists.
6496
6497    if (thread->type() != ThreadBase::DUPLICATING) {
6498        AudioStreamOut *out = thread->clearOutput();
6499        ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
6500        // from now on thread->mOutput is NULL
6501        out->hwDev->close_output_stream(out->hwDev, out->stream);
6502        delete out;
6503    }
6504    return NO_ERROR;
6505}
6506
6507status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
6508{
6509    Mutex::Autolock _l(mLock);
6510    PlaybackThread *thread = checkPlaybackThread_l(output);
6511
6512    if (thread == NULL) {
6513        return BAD_VALUE;
6514    }
6515
6516    ALOGV("suspendOutput() %d", output);
6517    thread->suspend();
6518
6519    return NO_ERROR;
6520}
6521
6522status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
6523{
6524    Mutex::Autolock _l(mLock);
6525    PlaybackThread *thread = checkPlaybackThread_l(output);
6526
6527    if (thread == NULL) {
6528        return BAD_VALUE;
6529    }
6530
6531    ALOGV("restoreOutput() %d", output);
6532
6533    thread->restore();
6534
6535    return NO_ERROR;
6536}
6537
6538audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6539                                          audio_devices_t *pDevices,
6540                                          uint32_t *pSamplingRate,
6541                                          audio_format_t *pFormat,
6542                                          uint32_t *pChannelMask)
6543{
6544    status_t status;
6545    RecordThread *thread = NULL;
6546    struct audio_config config = {
6547        sample_rate: pSamplingRate ? *pSamplingRate : 0,
6548        channel_mask: pChannelMask ? *pChannelMask : 0,
6549        format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6550    };
6551    uint32_t reqSamplingRate = config.sample_rate;
6552    audio_format_t reqFormat = config.format;
6553    audio_channel_mask_t reqChannels = config.channel_mask;
6554    audio_stream_in_t *inStream = NULL;
6555    audio_hw_device_t *inHwDev;
6556
6557    if (pDevices == NULL || *pDevices == 0) {
6558        return 0;
6559    }
6560
6561    Mutex::Autolock _l(mLock);
6562
6563    inHwDev = findSuitableHwDev_l(module, *pDevices);
6564    if (inHwDev == NULL)
6565        return 0;
6566
6567    audio_io_handle_t id = nextUniqueId();
6568
6569    status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
6570                                        &inStream);
6571    ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
6572            inStream,
6573            config.sample_rate,
6574            config.format,
6575            config.channel_mask,
6576            status);
6577
6578    // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6579    // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6580    // or stereo to mono conversions on 16 bit PCM inputs.
6581    if (status == BAD_VALUE &&
6582        reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6583        (config.sample_rate <= 2 * reqSamplingRate) &&
6584        (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
6585        ALOGV("openInput() reopening with proposed sampling rate and channels");
6586        inStream = NULL;
6587        status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
6588    }
6589
6590    if (status == NO_ERROR && inStream != NULL) {
6591        AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6592
6593        // Start record thread
6594        // RecorThread require both input and output device indication to forward to audio
6595        // pre processing modules
6596        uint32_t device = (*pDevices) | primaryOutputDevice_l();
6597        thread = new RecordThread(this,
6598                                  input,
6599                                  reqSamplingRate,
6600                                  reqChannels,
6601                                  id,
6602                                  device);
6603        mRecordThreads.add(id, thread);
6604        ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
6605        if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
6606        if (pFormat != NULL) *pFormat = config.format;
6607        if (pChannelMask != NULL) *pChannelMask = reqChannels;
6608
6609        input->stream->common.standby(&input->stream->common);
6610
6611        // notify client processes of the new input creation
6612        thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6613        return id;
6614    }
6615
6616    return 0;
6617}
6618
6619status_t AudioFlinger::closeInput(audio_io_handle_t input)
6620{
6621    // keep strong reference on the record thread so that
6622    // it is not destroyed while exit() is executed
6623    sp<RecordThread> thread;
6624    {
6625        Mutex::Autolock _l(mLock);
6626        thread = checkRecordThread_l(input);
6627        if (thread == NULL) {
6628            return BAD_VALUE;
6629        }
6630
6631        ALOGV("closeInput() %d", input);
6632        audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
6633        mRecordThreads.removeItem(input);
6634    }
6635    thread->exit();
6636    // The thread entity (active unit of execution) is no longer running here,
6637    // but the ThreadBase container still exists.
6638
6639    AudioStreamIn *in = thread->clearInput();
6640    ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
6641    // from now on thread->mInput is NULL
6642    in->hwDev->close_input_stream(in->hwDev, in->stream);
6643    delete in;
6644
6645    return NO_ERROR;
6646}
6647
6648status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
6649{
6650    Mutex::Autolock _l(mLock);
6651    MixerThread *dstThread = checkMixerThread_l(output);
6652    if (dstThread == NULL) {
6653        ALOGW("setStreamOutput() bad output id %d", output);
6654        return BAD_VALUE;
6655    }
6656
6657    ALOGV("setStreamOutput() stream %d to output %d", stream, output);
6658    audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6659
6660    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6661        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
6662        if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
6663            MixerThread *srcThread = (MixerThread *)thread;
6664            srcThread->invalidateTracks(stream);
6665        }
6666    }
6667
6668    return NO_ERROR;
6669}
6670
6671
6672int AudioFlinger::newAudioSessionId()
6673{
6674    return nextUniqueId();
6675}
6676
6677void AudioFlinger::acquireAudioSessionId(int audioSession)
6678{
6679    Mutex::Autolock _l(mLock);
6680    pid_t caller = IPCThreadState::self()->getCallingPid();
6681    ALOGV("acquiring %d from %d", audioSession, caller);
6682    size_t num = mAudioSessionRefs.size();
6683    for (size_t i = 0; i< num; i++) {
6684        AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
6685        if (ref->mSessionid == audioSession && ref->mPid == caller) {
6686            ref->mCnt++;
6687            ALOGV(" incremented refcount to %d", ref->mCnt);
6688            return;
6689        }
6690    }
6691    mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6692    ALOGV(" added new entry for %d", audioSession);
6693}
6694
6695void AudioFlinger::releaseAudioSessionId(int audioSession)
6696{
6697    Mutex::Autolock _l(mLock);
6698    pid_t caller = IPCThreadState::self()->getCallingPid();
6699    ALOGV("releasing %d from %d", audioSession, caller);
6700    size_t num = mAudioSessionRefs.size();
6701    for (size_t i = 0; i< num; i++) {
6702        AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
6703        if (ref->mSessionid == audioSession && ref->mPid == caller) {
6704            ref->mCnt--;
6705            ALOGV(" decremented refcount to %d", ref->mCnt);
6706            if (ref->mCnt == 0) {
6707                mAudioSessionRefs.removeAt(i);
6708                delete ref;
6709                purgeStaleEffects_l();
6710            }
6711            return;
6712        }
6713    }
6714    ALOGW("session id %d not found for pid %d", audioSession, caller);
6715}
6716
6717void AudioFlinger::purgeStaleEffects_l() {
6718
6719    ALOGV("purging stale effects");
6720
6721    Vector< sp<EffectChain> > chains;
6722
6723    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6724        sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6725        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6726            sp<EffectChain> ec = t->mEffectChains[j];
6727            if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6728                chains.push(ec);
6729            }
6730        }
6731    }
6732    for (size_t i = 0; i < mRecordThreads.size(); i++) {
6733        sp<RecordThread> t = mRecordThreads.valueAt(i);
6734        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6735            sp<EffectChain> ec = t->mEffectChains[j];
6736            chains.push(ec);
6737        }
6738    }
6739
6740    for (size_t i = 0; i < chains.size(); i++) {
6741        sp<EffectChain> ec = chains[i];
6742        int sessionid = ec->sessionId();
6743        sp<ThreadBase> t = ec->mThread.promote();
6744        if (t == 0) {
6745            continue;
6746        }
6747        size_t numsessionrefs = mAudioSessionRefs.size();
6748        bool found = false;
6749        for (size_t k = 0; k < numsessionrefs; k++) {
6750            AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
6751            if (ref->mSessionid == sessionid) {
6752                ALOGV(" session %d still exists for %d with %d refs",
6753                    sessionid, ref->mPid, ref->mCnt);
6754                found = true;
6755                break;
6756            }
6757        }
6758        if (!found) {
6759            // remove all effects from the chain
6760            while (ec->mEffects.size()) {
6761                sp<EffectModule> effect = ec->mEffects[0];
6762                effect->unPin();
6763                Mutex::Autolock _l (t->mLock);
6764                t->removeEffect_l(effect);
6765                for (size_t j = 0; j < effect->mHandles.size(); j++) {
6766                    sp<EffectHandle> handle = effect->mHandles[j].promote();
6767                    if (handle != 0) {
6768                        handle->mEffect.clear();
6769                        if (handle->mHasControl && handle->mEnabled) {
6770                            t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6771                        }
6772                    }
6773                }
6774                AudioSystem::unregisterEffect(effect->id());
6775            }
6776        }
6777    }
6778    return;
6779}
6780
6781// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
6782AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
6783{
6784    return mPlaybackThreads.valueFor(output).get();
6785}
6786
6787// checkMixerThread_l() must be called with AudioFlinger::mLock held
6788AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
6789{
6790    PlaybackThread *thread = checkPlaybackThread_l(output);
6791    return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
6792}
6793
6794// checkRecordThread_l() must be called with AudioFlinger::mLock held
6795AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
6796{
6797    return mRecordThreads.valueFor(input).get();
6798}
6799
6800uint32_t AudioFlinger::nextUniqueId()
6801{
6802    return android_atomic_inc(&mNextUniqueId);
6803}
6804
6805AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
6806{
6807    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6808        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
6809        AudioStreamOut *output = thread->getOutput();
6810        if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
6811            return thread;
6812        }
6813    }
6814    return NULL;
6815}
6816
6817uint32_t AudioFlinger::primaryOutputDevice_l() const
6818{
6819    PlaybackThread *thread = primaryPlaybackThread_l();
6820
6821    if (thread == NULL) {
6822        return 0;
6823    }
6824
6825    return thread->device();
6826}
6827
6828sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
6829                                    int triggerSession,
6830                                    int listenerSession,
6831                                    sync_event_callback_t callBack,
6832                                    void *cookie)
6833{
6834    Mutex::Autolock _l(mLock);
6835
6836    sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
6837    status_t playStatus = NAME_NOT_FOUND;
6838    status_t recStatus = NAME_NOT_FOUND;
6839    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6840        playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
6841        if (playStatus == NO_ERROR) {
6842            return event;
6843        }
6844    }
6845    for (size_t i = 0; i < mRecordThreads.size(); i++) {
6846        recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
6847        if (recStatus == NO_ERROR) {
6848            return event;
6849        }
6850    }
6851    if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
6852        mPendingSyncEvents.add(event);
6853    } else {
6854        ALOGV("createSyncEvent() invalid event %d", event->type());
6855        event.clear();
6856    }
6857    return event;
6858}
6859
6860// ----------------------------------------------------------------------------
6861//  Effect management
6862// ----------------------------------------------------------------------------
6863
6864
6865status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
6866{
6867    Mutex::Autolock _l(mLock);
6868    return EffectQueryNumberEffects(numEffects);
6869}
6870
6871status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
6872{
6873    Mutex::Autolock _l(mLock);
6874    return EffectQueryEffect(index, descriptor);
6875}
6876
6877status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
6878        effect_descriptor_t *descriptor) const
6879{
6880    Mutex::Autolock _l(mLock);
6881    return EffectGetDescriptor(pUuid, descriptor);
6882}
6883
6884
6885sp<IEffect> AudioFlinger::createEffect(pid_t pid,
6886        effect_descriptor_t *pDesc,
6887        const sp<IEffectClient>& effectClient,
6888        int32_t priority,
6889        audio_io_handle_t io,
6890        int sessionId,
6891        status_t *status,
6892        int *id,
6893        int *enabled)
6894{
6895    status_t lStatus = NO_ERROR;
6896    sp<EffectHandle> handle;
6897    effect_descriptor_t desc;
6898
6899    ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
6900            pid, effectClient.get(), priority, sessionId, io);
6901
6902    if (pDesc == NULL) {
6903        lStatus = BAD_VALUE;
6904        goto Exit;
6905    }
6906
6907    // check audio settings permission for global effects
6908    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
6909        lStatus = PERMISSION_DENIED;
6910        goto Exit;
6911    }
6912
6913    // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
6914    // that can only be created by audio policy manager (running in same process)
6915    if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
6916        lStatus = PERMISSION_DENIED;
6917        goto Exit;
6918    }
6919
6920    if (io == 0) {
6921        if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
6922            // output must be specified by AudioPolicyManager when using session
6923            // AUDIO_SESSION_OUTPUT_STAGE
6924            lStatus = BAD_VALUE;
6925            goto Exit;
6926        } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
6927            // if the output returned by getOutputForEffect() is removed before we lock the
6928            // mutex below, the call to checkPlaybackThread_l(io) below will detect it
6929            // and we will exit safely
6930            io = AudioSystem::getOutputForEffect(&desc);
6931        }
6932    }
6933
6934    {
6935        Mutex::Autolock _l(mLock);
6936
6937
6938        if (!EffectIsNullUuid(&pDesc->uuid)) {
6939            // if uuid is specified, request effect descriptor
6940            lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
6941            if (lStatus < 0) {
6942                ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
6943                goto Exit;
6944            }
6945        } else {
6946            // if uuid is not specified, look for an available implementation
6947            // of the required type in effect factory
6948            if (EffectIsNullUuid(&pDesc->type)) {
6949                ALOGW("createEffect() no effect type");
6950                lStatus = BAD_VALUE;
6951                goto Exit;
6952            }
6953            uint32_t numEffects = 0;
6954            effect_descriptor_t d;
6955            d.flags = 0; // prevent compiler warning
6956            bool found = false;
6957
6958            lStatus = EffectQueryNumberEffects(&numEffects);
6959            if (lStatus < 0) {
6960                ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
6961                goto Exit;
6962            }
6963            for (uint32_t i = 0; i < numEffects; i++) {
6964                lStatus = EffectQueryEffect(i, &desc);
6965                if (lStatus < 0) {
6966                    ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
6967                    continue;
6968                }
6969                if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
6970                    // If matching type found save effect descriptor. If the session is
6971                    // 0 and the effect is not auxiliary, continue enumeration in case
6972                    // an auxiliary version of this effect type is available
6973                    found = true;
6974                    memcpy(&d, &desc, sizeof(effect_descriptor_t));
6975                    if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
6976                            (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6977                        break;
6978                    }
6979                }
6980            }
6981            if (!found) {
6982                lStatus = BAD_VALUE;
6983                ALOGW("createEffect() effect not found");
6984                goto Exit;
6985            }
6986            // For same effect type, chose auxiliary version over insert version if
6987            // connect to output mix (Compliance to OpenSL ES)
6988            if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
6989                    (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6990                memcpy(&desc, &d, sizeof(effect_descriptor_t));
6991            }
6992        }
6993
6994        // Do not allow auxiliary effects on a session different from 0 (output mix)
6995        if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
6996             (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6997            lStatus = INVALID_OPERATION;
6998            goto Exit;
6999        }
7000
7001        // check recording permission for visualizer
7002        if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7003            !recordingAllowed()) {
7004            lStatus = PERMISSION_DENIED;
7005            goto Exit;
7006        }
7007
7008        // return effect descriptor
7009        memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7010
7011        // If output is not specified try to find a matching audio session ID in one of the
7012        // output threads.
7013        // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7014        // because of code checking output when entering the function.
7015        // Note: io is never 0 when creating an effect on an input
7016        if (io == 0) {
7017            // look for the thread where the specified audio session is present
7018            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7019                if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7020                    io = mPlaybackThreads.keyAt(i);
7021                    break;
7022                }
7023            }
7024            if (io == 0) {
7025                for (size_t i = 0; i < mRecordThreads.size(); i++) {
7026                    if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7027                        io = mRecordThreads.keyAt(i);
7028                        break;
7029                    }
7030                }
7031            }
7032            // If no output thread contains the requested session ID, default to
7033            // first output. The effect chain will be moved to the correct output
7034            // thread when a track with the same session ID is created
7035            if (io == 0 && mPlaybackThreads.size()) {
7036                io = mPlaybackThreads.keyAt(0);
7037            }
7038            ALOGV("createEffect() got io %d for effect %s", io, desc.name);
7039        }
7040        ThreadBase *thread = checkRecordThread_l(io);
7041        if (thread == NULL) {
7042            thread = checkPlaybackThread_l(io);
7043            if (thread == NULL) {
7044                ALOGE("createEffect() unknown output thread");
7045                lStatus = BAD_VALUE;
7046                goto Exit;
7047            }
7048        }
7049
7050        sp<Client> client = registerPid_l(pid);
7051
7052        // create effect on selected output thread
7053        handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7054                &desc, enabled, &lStatus);
7055        if (handle != 0 && id != NULL) {
7056            *id = handle->id();
7057        }
7058    }
7059
7060Exit:
7061    if (status != NULL) {
7062        *status = lStatus;
7063    }
7064    return handle;
7065}
7066
7067status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7068        audio_io_handle_t dstOutput)
7069{
7070    ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
7071            sessionId, srcOutput, dstOutput);
7072    Mutex::Autolock _l(mLock);
7073    if (srcOutput == dstOutput) {
7074        ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
7075        return NO_ERROR;
7076    }
7077    PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7078    if (srcThread == NULL) {
7079        ALOGW("moveEffects() bad srcOutput %d", srcOutput);
7080        return BAD_VALUE;
7081    }
7082    PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7083    if (dstThread == NULL) {
7084        ALOGW("moveEffects() bad dstOutput %d", dstOutput);
7085        return BAD_VALUE;
7086    }
7087
7088    Mutex::Autolock _dl(dstThread->mLock);
7089    Mutex::Autolock _sl(srcThread->mLock);
7090    moveEffectChain_l(sessionId, srcThread, dstThread, false);
7091
7092    return NO_ERROR;
7093}
7094
7095// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
7096status_t AudioFlinger::moveEffectChain_l(int sessionId,
7097                                   AudioFlinger::PlaybackThread *srcThread,
7098                                   AudioFlinger::PlaybackThread *dstThread,
7099                                   bool reRegister)
7100{
7101    ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
7102            sessionId, srcThread, dstThread);
7103
7104    sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
7105    if (chain == 0) {
7106        ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
7107                sessionId, srcThread);
7108        return INVALID_OPERATION;
7109    }
7110
7111    // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
7112    // so that a new chain is created with correct parameters when first effect is added. This is
7113    // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
7114    // removed.
7115    srcThread->removeEffectChain_l(chain);
7116
7117    // transfer all effects one by one so that new effect chain is created on new thread with
7118    // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
7119    audio_io_handle_t dstOutput = dstThread->id();
7120    sp<EffectChain> dstChain;
7121    uint32_t strategy = 0; // prevent compiler warning
7122    sp<EffectModule> effect = chain->getEffectFromId_l(0);
7123    while (effect != 0) {
7124        srcThread->removeEffect_l(effect);
7125        dstThread->addEffect_l(effect);
7126        // removeEffect_l() has stopped the effect if it was active so it must be restarted
7127        if (effect->state() == EffectModule::ACTIVE ||
7128                effect->state() == EffectModule::STOPPING) {
7129            effect->start();
7130        }
7131        // if the move request is not received from audio policy manager, the effect must be
7132        // re-registered with the new strategy and output
7133        if (dstChain == 0) {
7134            dstChain = effect->chain().promote();
7135            if (dstChain == 0) {
7136                ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
7137                srcThread->addEffect_l(effect);
7138                return NO_INIT;
7139            }
7140            strategy = dstChain->strategy();
7141        }
7142        if (reRegister) {
7143            AudioSystem::unregisterEffect(effect->id());
7144            AudioSystem::registerEffect(&effect->desc(),
7145                                        dstOutput,
7146                                        strategy,
7147                                        sessionId,
7148                                        effect->id());
7149        }
7150        effect = chain->getEffectFromId_l(0);
7151    }
7152
7153    return NO_ERROR;
7154}
7155
7156
7157// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
7158sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
7159        const sp<AudioFlinger::Client>& client,
7160        const sp<IEffectClient>& effectClient,
7161        int32_t priority,
7162        int sessionId,
7163        effect_descriptor_t *desc,
7164        int *enabled,
7165        status_t *status
7166        )
7167{
7168    sp<EffectModule> effect;
7169    sp<EffectHandle> handle;
7170    status_t lStatus;
7171    sp<EffectChain> chain;
7172    bool chainCreated = false;
7173    bool effectCreated = false;
7174    bool effectRegistered = false;
7175
7176    lStatus = initCheck();
7177    if (lStatus != NO_ERROR) {
7178        ALOGW("createEffect_l() Audio driver not initialized.");
7179        goto Exit;
7180    }
7181
7182    // Do not allow effects with session ID 0 on direct output or duplicating threads
7183    // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
7184    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
7185        ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
7186                desc->name, sessionId);
7187        lStatus = BAD_VALUE;
7188        goto Exit;
7189    }
7190    // Only Pre processor effects are allowed on input threads and only on input threads
7191    if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
7192        ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
7193                desc->name, desc->flags, mType);
7194        lStatus = BAD_VALUE;
7195        goto Exit;
7196    }
7197
7198    ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
7199
7200    { // scope for mLock
7201        Mutex::Autolock _l(mLock);
7202
7203        // check for existing effect chain with the requested audio session
7204        chain = getEffectChain_l(sessionId);
7205        if (chain == 0) {
7206            // create a new chain for this session
7207            ALOGV("createEffect_l() new effect chain for session %d", sessionId);
7208            chain = new EffectChain(this, sessionId);
7209            addEffectChain_l(chain);
7210            chain->setStrategy(getStrategyForSession_l(sessionId));
7211            chainCreated = true;
7212        } else {
7213            effect = chain->getEffectFromDesc_l(desc);
7214        }
7215
7216        ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
7217
7218        if (effect == 0) {
7219            int id = mAudioFlinger->nextUniqueId();
7220            // Check CPU and memory usage
7221            lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
7222            if (lStatus != NO_ERROR) {
7223                goto Exit;
7224            }
7225            effectRegistered = true;
7226            // create a new effect module if none present in the chain
7227            effect = new EffectModule(this, chain, desc, id, sessionId);
7228            lStatus = effect->status();
7229            if (lStatus != NO_ERROR) {
7230                goto Exit;
7231            }
7232            lStatus = chain->addEffect_l(effect);
7233            if (lStatus != NO_ERROR) {
7234                goto Exit;
7235            }
7236            effectCreated = true;
7237
7238            effect->setDevice(mDevice);
7239            effect->setMode(mAudioFlinger->getMode());
7240        }
7241        // create effect handle and connect it to effect module
7242        handle = new EffectHandle(effect, client, effectClient, priority);
7243        lStatus = effect->addHandle(handle);
7244        if (enabled != NULL) {
7245            *enabled = (int)effect->isEnabled();
7246        }
7247    }
7248
7249Exit:
7250    if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
7251        Mutex::Autolock _l(mLock);
7252        if (effectCreated) {
7253            chain->removeEffect_l(effect);
7254        }
7255        if (effectRegistered) {
7256            AudioSystem::unregisterEffect(effect->id());
7257        }
7258        if (chainCreated) {
7259            removeEffectChain_l(chain);
7260        }
7261        handle.clear();
7262    }
7263
7264    if (status != NULL) {
7265        *status = lStatus;
7266    }
7267    return handle;
7268}
7269
7270sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7271{
7272    sp<EffectChain> chain = getEffectChain_l(sessionId);
7273    return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
7274}
7275
7276// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7277// PlaybackThread::mLock held
7278status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
7279{
7280    // check for existing effect chain with the requested audio session
7281    int sessionId = effect->sessionId();
7282    sp<EffectChain> chain = getEffectChain_l(sessionId);
7283    bool chainCreated = false;
7284
7285    if (chain == 0) {
7286        // create a new chain for this session
7287        ALOGV("addEffect_l() new effect chain for session %d", sessionId);
7288        chain = new EffectChain(this, sessionId);
7289        addEffectChain_l(chain);
7290        chain->setStrategy(getStrategyForSession_l(sessionId));
7291        chainCreated = true;
7292    }
7293    ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
7294
7295    if (chain->getEffectFromId_l(effect->id()) != 0) {
7296        ALOGW("addEffect_l() %p effect %s already present in chain %p",
7297                this, effect->desc().name, chain.get());
7298        return BAD_VALUE;
7299    }
7300
7301    status_t status = chain->addEffect_l(effect);
7302    if (status != NO_ERROR) {
7303        if (chainCreated) {
7304            removeEffectChain_l(chain);
7305        }
7306        return status;
7307    }
7308
7309    effect->setDevice(mDevice);
7310    effect->setMode(mAudioFlinger->getMode());
7311    return NO_ERROR;
7312}
7313
7314void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
7315
7316    ALOGV("removeEffect_l() %p effect %p", this, effect.get());
7317    effect_descriptor_t desc = effect->desc();
7318    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7319        detachAuxEffect_l(effect->id());
7320    }
7321
7322    sp<EffectChain> chain = effect->chain().promote();
7323    if (chain != 0) {
7324        // remove effect chain if removing last effect
7325        if (chain->removeEffect_l(effect) == 0) {
7326            removeEffectChain_l(chain);
7327        }
7328    } else {
7329        ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
7330    }
7331}
7332
7333void AudioFlinger::ThreadBase::lockEffectChains_l(
7334        Vector< sp<AudioFlinger::EffectChain> >& effectChains)
7335{
7336    effectChains = mEffectChains;
7337    for (size_t i = 0; i < mEffectChains.size(); i++) {
7338        mEffectChains[i]->lock();
7339    }
7340}
7341
7342void AudioFlinger::ThreadBase::unlockEffectChains(
7343        const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
7344{
7345    for (size_t i = 0; i < effectChains.size(); i++) {
7346        effectChains[i]->unlock();
7347    }
7348}
7349
7350sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7351{
7352    Mutex::Autolock _l(mLock);
7353    return getEffectChain_l(sessionId);
7354}
7355
7356sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7357{
7358    size_t size = mEffectChains.size();
7359    for (size_t i = 0; i < size; i++) {
7360        if (mEffectChains[i]->sessionId() == sessionId) {
7361            return mEffectChains[i];
7362        }
7363    }
7364    return 0;
7365}
7366
7367void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
7368{
7369    Mutex::Autolock _l(mLock);
7370    size_t size = mEffectChains.size();
7371    for (size_t i = 0; i < size; i++) {
7372        mEffectChains[i]->setMode_l(mode);
7373    }
7374}
7375
7376void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
7377                                                    const wp<EffectHandle>& handle,
7378                                                    bool unpinIfLast) {
7379
7380    Mutex::Autolock _l(mLock);
7381    ALOGV("disconnectEffect() %p effect %p", this, effect.get());
7382    // delete the effect module if removing last handle on it
7383    if (effect->removeHandle(handle) == 0) {
7384        if (!effect->isPinned() || unpinIfLast) {
7385            removeEffect_l(effect);
7386            AudioSystem::unregisterEffect(effect->id());
7387        }
7388    }
7389}
7390
7391status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7392{
7393    int session = chain->sessionId();
7394    int16_t *buffer = mMixBuffer;
7395    bool ownsBuffer = false;
7396
7397    ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
7398    if (session > 0) {
7399        // Only one effect chain can be present in direct output thread and it uses
7400        // the mix buffer as input
7401        if (mType != DIRECT) {
7402            size_t numSamples = mNormalFrameCount * mChannelCount;
7403            buffer = new int16_t[numSamples];
7404            memset(buffer, 0, numSamples * sizeof(int16_t));
7405            ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
7406            ownsBuffer = true;
7407        }
7408
7409        // Attach all tracks with same session ID to this chain.
7410        for (size_t i = 0; i < mTracks.size(); ++i) {
7411            sp<Track> track = mTracks[i];
7412            if (session == track->sessionId()) {
7413                ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
7414                track->setMainBuffer(buffer);
7415                chain->incTrackCnt();
7416            }
7417        }
7418
7419        // indicate all active tracks in the chain
7420        for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7421            sp<Track> track = mActiveTracks[i].promote();
7422            if (track == 0) continue;
7423            if (session == track->sessionId()) {
7424                ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
7425                chain->incActiveTrackCnt();
7426            }
7427        }
7428    }
7429
7430    chain->setInBuffer(buffer, ownsBuffer);
7431    chain->setOutBuffer(mMixBuffer);
7432    // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
7433    // chains list in order to be processed last as it contains output stage effects
7434    // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7435    // session AUDIO_SESSION_OUTPUT_STAGE to be processed
7436    // after track specific effects and before output stage
7437    // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7438    // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
7439    // Effect chain for other sessions are inserted at beginning of effect
7440    // chains list to be processed before output mix effects. Relative order between other
7441    // sessions is not important
7442    size_t size = mEffectChains.size();
7443    size_t i = 0;
7444    for (i = 0; i < size; i++) {
7445        if (mEffectChains[i]->sessionId() < session) break;
7446    }
7447    mEffectChains.insertAt(chain, i);
7448    checkSuspendOnAddEffectChain_l(chain);
7449
7450    return NO_ERROR;
7451}
7452
7453size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7454{
7455    int session = chain->sessionId();
7456
7457    ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
7458
7459    for (size_t i = 0; i < mEffectChains.size(); i++) {
7460        if (chain == mEffectChains[i]) {
7461            mEffectChains.removeAt(i);
7462            // detach all active tracks from the chain
7463            for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7464                sp<Track> track = mActiveTracks[i].promote();
7465                if (track == 0) continue;
7466                if (session == track->sessionId()) {
7467                    ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
7468                            chain.get(), session);
7469                    chain->decActiveTrackCnt();
7470                }
7471            }
7472
7473            // detach all tracks with same session ID from this chain
7474            for (size_t i = 0; i < mTracks.size(); ++i) {
7475                sp<Track> track = mTracks[i];
7476                if (session == track->sessionId()) {
7477                    track->setMainBuffer(mMixBuffer);
7478                    chain->decTrackCnt();
7479                }
7480            }
7481            break;
7482        }
7483    }
7484    return mEffectChains.size();
7485}
7486
7487status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7488        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
7489{
7490    Mutex::Autolock _l(mLock);
7491    return attachAuxEffect_l(track, EffectId);
7492}
7493
7494status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7495        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
7496{
7497    status_t status = NO_ERROR;
7498
7499    if (EffectId == 0) {
7500        track->setAuxBuffer(0, NULL);
7501    } else {
7502        // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7503        sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
7504        if (effect != 0) {
7505            if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7506                track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7507            } else {
7508                status = INVALID_OPERATION;
7509            }
7510        } else {
7511            status = BAD_VALUE;
7512        }
7513    }
7514    return status;
7515}
7516
7517void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7518{
7519    for (size_t i = 0; i < mTracks.size(); ++i) {
7520        sp<Track> track = mTracks[i];
7521        if (track->auxEffectId() == effectId) {
7522            attachAuxEffect_l(track, 0);
7523        }
7524    }
7525}
7526
7527status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7528{
7529    // only one chain per input thread
7530    if (mEffectChains.size() != 0) {
7531        return INVALID_OPERATION;
7532    }
7533    ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
7534
7535    chain->setInBuffer(NULL);
7536    chain->setOutBuffer(NULL);
7537
7538    checkSuspendOnAddEffectChain_l(chain);
7539
7540    mEffectChains.add(chain);
7541
7542    return NO_ERROR;
7543}
7544
7545size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7546{
7547    ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7548    ALOGW_IF(mEffectChains.size() != 1,
7549            "removeEffectChain_l() %p invalid chain size %d on thread %p",
7550            chain.get(), mEffectChains.size(), this);
7551    if (mEffectChains.size() == 1) {
7552        mEffectChains.removeAt(0);
7553    }
7554    return 0;
7555}
7556
7557// ----------------------------------------------------------------------------
7558//  EffectModule implementation
7559// ----------------------------------------------------------------------------
7560
7561#undef LOG_TAG
7562#define LOG_TAG "AudioFlinger::EffectModule"
7563
7564AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
7565                                        const wp<AudioFlinger::EffectChain>& chain,
7566                                        effect_descriptor_t *desc,
7567                                        int id,
7568                                        int sessionId)
7569    : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
7570      mStatus(NO_INIT), mState(IDLE), mSuspended(false)
7571{
7572    ALOGV("Constructor %p", this);
7573    int lStatus;
7574    if (thread == NULL) {
7575        return;
7576    }
7577
7578    memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7579
7580    // create effect engine from effect factory
7581    mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
7582
7583    if (mStatus != NO_ERROR) {
7584        return;
7585    }
7586    lStatus = init();
7587    if (lStatus < 0) {
7588        mStatus = lStatus;
7589        goto Error;
7590    }
7591
7592    if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7593        mPinned = true;
7594    }
7595    ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
7596    return;
7597Error:
7598    EffectRelease(mEffectInterface);
7599    mEffectInterface = NULL;
7600    ALOGV("Constructor Error %d", mStatus);
7601}
7602
7603AudioFlinger::EffectModule::~EffectModule()
7604{
7605    ALOGV("Destructor %p", this);
7606    if (mEffectInterface != NULL) {
7607        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7608                (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7609            sp<ThreadBase> thread = mThread.promote();
7610            if (thread != 0) {
7611                audio_stream_t *stream = thread->stream();
7612                if (stream != NULL) {
7613                    stream->remove_audio_effect(stream, mEffectInterface);
7614                }
7615            }
7616        }
7617        // release effect engine
7618        EffectRelease(mEffectInterface);
7619    }
7620}
7621
7622status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
7623{
7624    status_t status;
7625
7626    Mutex::Autolock _l(mLock);
7627    int priority = handle->priority();
7628    size_t size = mHandles.size();
7629    sp<EffectHandle> h;
7630    size_t i;
7631    for (i = 0; i < size; i++) {
7632        h = mHandles[i].promote();
7633        if (h == 0) continue;
7634        if (h->priority() <= priority) break;
7635    }
7636    // if inserted in first place, move effect control from previous owner to this handle
7637    if (i == 0) {
7638        bool enabled = false;
7639        if (h != 0) {
7640            enabled = h->enabled();
7641            h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
7642        }
7643        handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
7644        status = NO_ERROR;
7645    } else {
7646        status = ALREADY_EXISTS;
7647    }
7648    ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
7649    mHandles.insertAt(handle, i);
7650    return status;
7651}
7652
7653size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7654{
7655    Mutex::Autolock _l(mLock);
7656    size_t size = mHandles.size();
7657    size_t i;
7658    for (i = 0; i < size; i++) {
7659        if (mHandles[i] == handle) break;
7660    }
7661    if (i == size) {
7662        return size;
7663    }
7664    ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
7665
7666    bool enabled = false;
7667    EffectHandle *hdl = handle.unsafe_get();
7668    if (hdl != NULL) {
7669        ALOGV("removeHandle() unsafe_get OK");
7670        enabled = hdl->enabled();
7671    }
7672    mHandles.removeAt(i);
7673    size = mHandles.size();
7674    // if removed from first place, move effect control from this handle to next in line
7675    if (i == 0 && size != 0) {
7676        sp<EffectHandle> h = mHandles[0].promote();
7677        if (h != 0) {
7678            h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
7679        }
7680    }
7681
7682    // Prevent calls to process() and other functions on effect interface from now on.
7683    // The effect engine will be released by the destructor when the last strong reference on
7684    // this object is released which can happen after next process is called.
7685    if (size == 0 && !mPinned) {
7686        mState = DESTROYED;
7687    }
7688
7689    return size;
7690}
7691
7692sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7693{
7694    Mutex::Autolock _l(mLock);
7695    return mHandles.size() != 0 ? mHandles[0].promote() : 0;
7696}
7697
7698void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
7699{
7700    ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
7701    // keep a strong reference on this EffectModule to avoid calling the
7702    // destructor before we exit
7703    sp<EffectModule> keep(this);
7704    {
7705        sp<ThreadBase> thread = mThread.promote();
7706        if (thread != 0) {
7707            thread->disconnectEffect(keep, handle, unpinIfLast);
7708        }
7709    }
7710}
7711
7712void AudioFlinger::EffectModule::updateState() {
7713    Mutex::Autolock _l(mLock);
7714
7715    switch (mState) {
7716    case RESTART:
7717        reset_l();
7718        // FALL THROUGH
7719
7720    case STARTING:
7721        // clear auxiliary effect input buffer for next accumulation
7722        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7723            memset(mConfig.inputCfg.buffer.raw,
7724                   0,
7725                   mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7726        }
7727        start_l();
7728        mState = ACTIVE;
7729        break;
7730    case STOPPING:
7731        stop_l();
7732        mDisableWaitCnt = mMaxDisableWaitCnt;
7733        mState = STOPPED;
7734        break;
7735    case STOPPED:
7736        // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7737        // turn off sequence.
7738        if (--mDisableWaitCnt == 0) {
7739            reset_l();
7740            mState = IDLE;
7741        }
7742        break;
7743    default: //IDLE , ACTIVE, DESTROYED
7744        break;
7745    }
7746}
7747
7748void AudioFlinger::EffectModule::process()
7749{
7750    Mutex::Autolock _l(mLock);
7751
7752    if (mState == DESTROYED || mEffectInterface == NULL ||
7753            mConfig.inputCfg.buffer.raw == NULL ||
7754            mConfig.outputCfg.buffer.raw == NULL) {
7755        return;
7756    }
7757
7758    if (isProcessEnabled()) {
7759        // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7760        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7761            ditherAndClamp(mConfig.inputCfg.buffer.s32,
7762                                        mConfig.inputCfg.buffer.s32,
7763                                        mConfig.inputCfg.buffer.frameCount/2);
7764        }
7765
7766        // do the actual processing in the effect engine
7767        int ret = (*mEffectInterface)->process(mEffectInterface,
7768                                               &mConfig.inputCfg.buffer,
7769                                               &mConfig.outputCfg.buffer);
7770
7771        // force transition to IDLE state when engine is ready
7772        if (mState == STOPPED && ret == -ENODATA) {
7773            mDisableWaitCnt = 1;
7774        }
7775
7776        // clear auxiliary effect input buffer for next accumulation
7777        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7778            memset(mConfig.inputCfg.buffer.raw, 0,
7779                   mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7780        }
7781    } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
7782                mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7783        // If an insert effect is idle and input buffer is different from output buffer,
7784        // accumulate input onto output
7785        sp<EffectChain> chain = mChain.promote();
7786        if (chain != 0 && chain->activeTrackCnt() != 0) {
7787            size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2;  //always stereo here
7788            int16_t *in = mConfig.inputCfg.buffer.s16;
7789            int16_t *out = mConfig.outputCfg.buffer.s16;
7790            for (size_t i = 0; i < frameCnt; i++) {
7791                out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
7792            }
7793        }
7794    }
7795}
7796
7797void AudioFlinger::EffectModule::reset_l()
7798{
7799    if (mEffectInterface == NULL) {
7800        return;
7801    }
7802    (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
7803}
7804
7805status_t AudioFlinger::EffectModule::configure()
7806{
7807    uint32_t channels;
7808    if (mEffectInterface == NULL) {
7809        return NO_INIT;
7810    }
7811
7812    sp<ThreadBase> thread = mThread.promote();
7813    if (thread == 0) {
7814        return DEAD_OBJECT;
7815    }
7816
7817    // TODO: handle configuration of effects replacing track process
7818    if (thread->channelCount() == 1) {
7819        channels = AUDIO_CHANNEL_OUT_MONO;
7820    } else {
7821        channels = AUDIO_CHANNEL_OUT_STEREO;
7822    }
7823
7824    if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7825        mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
7826    } else {
7827        mConfig.inputCfg.channels = channels;
7828    }
7829    mConfig.outputCfg.channels = channels;
7830    mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7831    mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7832    mConfig.inputCfg.samplingRate = thread->sampleRate();
7833    mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
7834    mConfig.inputCfg.bufferProvider.cookie = NULL;
7835    mConfig.inputCfg.bufferProvider.getBuffer = NULL;
7836    mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
7837    mConfig.outputCfg.bufferProvider.cookie = NULL;
7838    mConfig.outputCfg.bufferProvider.getBuffer = NULL;
7839    mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
7840    mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
7841    // Insert effect:
7842    // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
7843    // always overwrites output buffer: input buffer == output buffer
7844    // - in other sessions:
7845    //      last effect in the chain accumulates in output buffer: input buffer != output buffer
7846    //      other effect: overwrites output buffer: input buffer == output buffer
7847    // Auxiliary effect:
7848    //      accumulates in output buffer: input buffer != output buffer
7849    // Therefore: accumulate <=> input buffer != output buffer
7850    if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7851        mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
7852    } else {
7853        mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
7854    }
7855    mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
7856    mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
7857    mConfig.inputCfg.buffer.frameCount = thread->frameCount();
7858    mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
7859
7860    ALOGV("configure() %p thread %p buffer %p framecount %d",
7861            this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
7862
7863    status_t cmdStatus;
7864    uint32_t size = sizeof(int);
7865    status_t status = (*mEffectInterface)->command(mEffectInterface,
7866                                                   EFFECT_CMD_SET_CONFIG,
7867                                                   sizeof(effect_config_t),
7868                                                   &mConfig,
7869                                                   &size,
7870                                                   &cmdStatus);
7871    if (status == 0) {
7872        status = cmdStatus;
7873    }
7874
7875    mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
7876            (1000 * mConfig.outputCfg.buffer.frameCount);
7877
7878    return status;
7879}
7880
7881status_t AudioFlinger::EffectModule::init()
7882{
7883    Mutex::Autolock _l(mLock);
7884    if (mEffectInterface == NULL) {
7885        return NO_INIT;
7886    }
7887    status_t cmdStatus;
7888    uint32_t size = sizeof(status_t);
7889    status_t status = (*mEffectInterface)->command(mEffectInterface,
7890                                                   EFFECT_CMD_INIT,
7891                                                   0,
7892                                                   NULL,
7893                                                   &size,
7894                                                   &cmdStatus);
7895    if (status == 0) {
7896        status = cmdStatus;
7897    }
7898    return status;
7899}
7900
7901status_t AudioFlinger::EffectModule::start()
7902{
7903    Mutex::Autolock _l(mLock);
7904    return start_l();
7905}
7906
7907status_t AudioFlinger::EffectModule::start_l()
7908{
7909    if (mEffectInterface == NULL) {
7910        return NO_INIT;
7911    }
7912    status_t cmdStatus;
7913    uint32_t size = sizeof(status_t);
7914    status_t status = (*mEffectInterface)->command(mEffectInterface,
7915                                                   EFFECT_CMD_ENABLE,
7916                                                   0,
7917                                                   NULL,
7918                                                   &size,
7919                                                   &cmdStatus);
7920    if (status == 0) {
7921        status = cmdStatus;
7922    }
7923    if (status == 0 &&
7924            ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7925             (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7926        sp<ThreadBase> thread = mThread.promote();
7927        if (thread != 0) {
7928            audio_stream_t *stream = thread->stream();
7929            if (stream != NULL) {
7930                stream->add_audio_effect(stream, mEffectInterface);
7931            }
7932        }
7933    }
7934    return status;
7935}
7936
7937status_t AudioFlinger::EffectModule::stop()
7938{
7939    Mutex::Autolock _l(mLock);
7940    return stop_l();
7941}
7942
7943status_t AudioFlinger::EffectModule::stop_l()
7944{
7945    if (mEffectInterface == NULL) {
7946        return NO_INIT;
7947    }
7948    status_t cmdStatus;
7949    uint32_t size = sizeof(status_t);
7950    status_t status = (*mEffectInterface)->command(mEffectInterface,
7951                                                   EFFECT_CMD_DISABLE,
7952                                                   0,
7953                                                   NULL,
7954                                                   &size,
7955                                                   &cmdStatus);
7956    if (status == 0) {
7957        status = cmdStatus;
7958    }
7959    if (status == 0 &&
7960            ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7961             (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7962        sp<ThreadBase> thread = mThread.promote();
7963        if (thread != 0) {
7964            audio_stream_t *stream = thread->stream();
7965            if (stream != NULL) {
7966                stream->remove_audio_effect(stream, mEffectInterface);
7967            }
7968        }
7969    }
7970    return status;
7971}
7972
7973status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7974                                             uint32_t cmdSize,
7975                                             void *pCmdData,
7976                                             uint32_t *replySize,
7977                                             void *pReplyData)
7978{
7979    Mutex::Autolock _l(mLock);
7980//    ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
7981
7982    if (mState == DESTROYED || mEffectInterface == NULL) {
7983        return NO_INIT;
7984    }
7985    status_t status = (*mEffectInterface)->command(mEffectInterface,
7986                                                   cmdCode,
7987                                                   cmdSize,
7988                                                   pCmdData,
7989                                                   replySize,
7990                                                   pReplyData);
7991    if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
7992        uint32_t size = (replySize == NULL) ? 0 : *replySize;
7993        for (size_t i = 1; i < mHandles.size(); i++) {
7994            sp<EffectHandle> h = mHandles[i].promote();
7995            if (h != 0) {
7996                h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7997            }
7998        }
7999    }
8000    return status;
8001}
8002
8003status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8004{
8005
8006    Mutex::Autolock _l(mLock);
8007    ALOGV("setEnabled %p enabled %d", this, enabled);
8008
8009    if (enabled != isEnabled()) {
8010        status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8011        if (enabled && status != NO_ERROR) {
8012            return status;
8013        }
8014
8015        switch (mState) {
8016        // going from disabled to enabled
8017        case IDLE:
8018            mState = STARTING;
8019            break;
8020        case STOPPED:
8021            mState = RESTART;
8022            break;
8023        case STOPPING:
8024            mState = ACTIVE;
8025            break;
8026
8027        // going from enabled to disabled
8028        case RESTART:
8029            mState = STOPPED;
8030            break;
8031        case STARTING:
8032            mState = IDLE;
8033            break;
8034        case ACTIVE:
8035            mState = STOPPING;
8036            break;
8037        case DESTROYED:
8038            return NO_ERROR; // simply ignore as we are being destroyed
8039        }
8040        for (size_t i = 1; i < mHandles.size(); i++) {
8041            sp<EffectHandle> h = mHandles[i].promote();
8042            if (h != 0) {
8043                h->setEnabled(enabled);
8044            }
8045        }
8046    }
8047    return NO_ERROR;
8048}
8049
8050bool AudioFlinger::EffectModule::isEnabled() const
8051{
8052    switch (mState) {
8053    case RESTART:
8054    case STARTING:
8055    case ACTIVE:
8056        return true;
8057    case IDLE:
8058    case STOPPING:
8059    case STOPPED:
8060    case DESTROYED:
8061    default:
8062        return false;
8063    }
8064}
8065
8066bool AudioFlinger::EffectModule::isProcessEnabled() const
8067{
8068    switch (mState) {
8069    case RESTART:
8070    case ACTIVE:
8071    case STOPPING:
8072    case STOPPED:
8073        return true;
8074    case IDLE:
8075    case STARTING:
8076    case DESTROYED:
8077    default:
8078        return false;
8079    }
8080}
8081
8082status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8083{
8084    Mutex::Autolock _l(mLock);
8085    status_t status = NO_ERROR;
8086
8087    // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8088    // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
8089    if (isProcessEnabled() &&
8090            ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8091            (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
8092        status_t cmdStatus;
8093        uint32_t volume[2];
8094        uint32_t *pVolume = NULL;
8095        uint32_t size = sizeof(volume);
8096        volume[0] = *left;
8097        volume[1] = *right;
8098        if (controller) {
8099            pVolume = volume;
8100        }
8101        status = (*mEffectInterface)->command(mEffectInterface,
8102                                              EFFECT_CMD_SET_VOLUME,
8103                                              size,
8104                                              volume,
8105                                              &size,
8106                                              pVolume);
8107        if (controller && status == NO_ERROR && size == sizeof(volume)) {
8108            *left = volume[0];
8109            *right = volume[1];
8110        }
8111    }
8112    return status;
8113}
8114
8115status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8116{
8117    Mutex::Autolock _l(mLock);
8118    status_t status = NO_ERROR;
8119    if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8120        // audio pre processing modules on RecordThread can receive both output and
8121        // input device indication in the same call
8122        uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8123        if (dev) {
8124            status_t cmdStatus;
8125            uint32_t size = sizeof(status_t);
8126
8127            status = (*mEffectInterface)->command(mEffectInterface,
8128                                                  EFFECT_CMD_SET_DEVICE,
8129                                                  sizeof(uint32_t),
8130                                                  &dev,
8131                                                  &size,
8132                                                  &cmdStatus);
8133            if (status == NO_ERROR) {
8134                status = cmdStatus;
8135            }
8136        }
8137        dev = device & AUDIO_DEVICE_IN_ALL;
8138        if (dev) {
8139            status_t cmdStatus;
8140            uint32_t size = sizeof(status_t);
8141
8142            status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8143                                                  EFFECT_CMD_SET_INPUT_DEVICE,
8144                                                  sizeof(uint32_t),
8145                                                  &dev,
8146                                                  &size,
8147                                                  &cmdStatus);
8148            if (status2 == NO_ERROR) {
8149                status2 = cmdStatus;
8150            }
8151            if (status == NO_ERROR) {
8152                status = status2;
8153            }
8154        }
8155    }
8156    return status;
8157}
8158
8159status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
8160{
8161    Mutex::Autolock _l(mLock);
8162    status_t status = NO_ERROR;
8163    if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
8164        status_t cmdStatus;
8165        uint32_t size = sizeof(status_t);
8166        status = (*mEffectInterface)->command(mEffectInterface,
8167                                              EFFECT_CMD_SET_AUDIO_MODE,
8168                                              sizeof(audio_mode_t),
8169                                              &mode,
8170                                              &size,
8171                                              &cmdStatus);
8172        if (status == NO_ERROR) {
8173            status = cmdStatus;
8174        }
8175    }
8176    return status;
8177}
8178
8179void AudioFlinger::EffectModule::setSuspended(bool suspended)
8180{
8181    Mutex::Autolock _l(mLock);
8182    mSuspended = suspended;
8183}
8184
8185bool AudioFlinger::EffectModule::suspended() const
8186{
8187    Mutex::Autolock _l(mLock);
8188    return mSuspended;
8189}
8190
8191status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8192{
8193    const size_t SIZE = 256;
8194    char buffer[SIZE];
8195    String8 result;
8196
8197    snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8198    result.append(buffer);
8199
8200    bool locked = tryLock(mLock);
8201    // failed to lock - AudioFlinger is probably deadlocked
8202    if (!locked) {
8203        result.append("\t\tCould not lock Fx mutex:\n");
8204    }
8205
8206    result.append("\t\tSession Status State Engine:\n");
8207    snprintf(buffer, SIZE, "\t\t%05d   %03d    %03d   0x%08x\n",
8208            mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8209    result.append(buffer);
8210
8211    result.append("\t\tDescriptor:\n");
8212    snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8213            mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8214            mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8215            mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8216    result.append(buffer);
8217    snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8218                mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8219                mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8220                mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8221    result.append(buffer);
8222    snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
8223            mDescriptor.apiVersion,
8224            mDescriptor.flags);
8225    result.append(buffer);
8226    snprintf(buffer, SIZE, "\t\t- name: %s\n",
8227            mDescriptor.name);
8228    result.append(buffer);
8229    snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8230            mDescriptor.implementor);
8231    result.append(buffer);
8232
8233    result.append("\t\t- Input configuration:\n");
8234    result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
8235    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
8236            (uint32_t)mConfig.inputCfg.buffer.raw,
8237            mConfig.inputCfg.buffer.frameCount,
8238            mConfig.inputCfg.samplingRate,
8239            mConfig.inputCfg.channels,
8240            mConfig.inputCfg.format);
8241    result.append(buffer);
8242
8243    result.append("\t\t- Output configuration:\n");
8244    result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
8245    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
8246            (uint32_t)mConfig.outputCfg.buffer.raw,
8247            mConfig.outputCfg.buffer.frameCount,
8248            mConfig.outputCfg.samplingRate,
8249            mConfig.outputCfg.channels,
8250            mConfig.outputCfg.format);
8251    result.append(buffer);
8252
8253    snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8254    result.append(buffer);
8255    result.append("\t\t\tPid   Priority Ctrl Locked client server\n");
8256    for (size_t i = 0; i < mHandles.size(); ++i) {
8257        sp<EffectHandle> handle = mHandles[i].promote();
8258        if (handle != 0) {
8259            handle->dump(buffer, SIZE);
8260            result.append(buffer);
8261        }
8262    }
8263
8264    result.append("\n");
8265
8266    write(fd, result.string(), result.length());
8267
8268    if (locked) {
8269        mLock.unlock();
8270    }
8271
8272    return NO_ERROR;
8273}
8274
8275// ----------------------------------------------------------------------------
8276//  EffectHandle implementation
8277// ----------------------------------------------------------------------------
8278
8279#undef LOG_TAG
8280#define LOG_TAG "AudioFlinger::EffectHandle"
8281
8282AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8283                                        const sp<AudioFlinger::Client>& client,
8284                                        const sp<IEffectClient>& effectClient,
8285                                        int32_t priority)
8286    : BnEffect(),
8287    mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
8288    mPriority(priority), mHasControl(false), mEnabled(false)
8289{
8290    ALOGV("constructor %p", this);
8291
8292    if (client == 0) {
8293        return;
8294    }
8295    int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8296    mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8297    if (mCblkMemory != 0) {
8298        mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8299
8300        if (mCblk != NULL) {
8301            new(mCblk) effect_param_cblk_t();
8302            mBuffer = (uint8_t *)mCblk + bufOffset;
8303        }
8304    } else {
8305        ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
8306        return;
8307    }
8308}
8309
8310AudioFlinger::EffectHandle::~EffectHandle()
8311{
8312    ALOGV("Destructor %p", this);
8313    disconnect(false);
8314    ALOGV("Destructor DONE %p", this);
8315}
8316
8317status_t AudioFlinger::EffectHandle::enable()
8318{
8319    ALOGV("enable %p", this);
8320    if (!mHasControl) return INVALID_OPERATION;
8321    if (mEffect == 0) return DEAD_OBJECT;
8322
8323    if (mEnabled) {
8324        return NO_ERROR;
8325    }
8326
8327    mEnabled = true;
8328
8329    sp<ThreadBase> thread = mEffect->thread().promote();
8330    if (thread != 0) {
8331        thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8332    }
8333
8334    // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8335    if (mEffect->suspended()) {
8336        return NO_ERROR;
8337    }
8338
8339    status_t status = mEffect->setEnabled(true);
8340    if (status != NO_ERROR) {
8341        if (thread != 0) {
8342            thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8343        }
8344        mEnabled = false;
8345    }
8346    return status;
8347}
8348
8349status_t AudioFlinger::EffectHandle::disable()
8350{
8351    ALOGV("disable %p", this);
8352    if (!mHasControl) return INVALID_OPERATION;
8353    if (mEffect == 0) return DEAD_OBJECT;
8354
8355    if (!mEnabled) {
8356        return NO_ERROR;
8357    }
8358    mEnabled = false;
8359
8360    if (mEffect->suspended()) {
8361        return NO_ERROR;
8362    }
8363
8364    status_t status = mEffect->setEnabled(false);
8365
8366    sp<ThreadBase> thread = mEffect->thread().promote();
8367    if (thread != 0) {
8368        thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8369    }
8370
8371    return status;
8372}
8373
8374void AudioFlinger::EffectHandle::disconnect()
8375{
8376    disconnect(true);
8377}
8378
8379void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
8380{
8381    ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
8382    if (mEffect == 0) {
8383        return;
8384    }
8385    mEffect->disconnect(this, unpinIfLast);
8386
8387    if (mHasControl && mEnabled) {
8388        sp<ThreadBase> thread = mEffect->thread().promote();
8389        if (thread != 0) {
8390            thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8391        }
8392    }
8393
8394    // release sp on module => module destructor can be called now
8395    mEffect.clear();
8396    if (mClient != 0) {
8397        if (mCblk != NULL) {
8398            // unlike ~TrackBase(), mCblk is never a local new, so don't delete
8399            mCblk->~effect_param_cblk_t();   // destroy our shared-structure.
8400        }
8401        mCblkMemory.clear();    // free the shared memory before releasing the heap it belongs to
8402        // Client destructor must run with AudioFlinger mutex locked
8403        Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8404        mClient.clear();
8405    }
8406}
8407
8408status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8409                                             uint32_t cmdSize,
8410                                             void *pCmdData,
8411                                             uint32_t *replySize,
8412                                             void *pReplyData)
8413{
8414//    ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
8415//              cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
8416
8417    // only get parameter command is permitted for applications not controlling the effect
8418    if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8419        return INVALID_OPERATION;
8420    }
8421    if (mEffect == 0) return DEAD_OBJECT;
8422    if (mClient == 0) return INVALID_OPERATION;
8423
8424    // handle commands that are not forwarded transparently to effect engine
8425    if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8426        // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8427        // no risk to block the whole media server process or mixer threads is we are stuck here
8428        Mutex::Autolock _l(mCblk->lock);
8429        if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8430            mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8431            mCblk->serverIndex = 0;
8432            mCblk->clientIndex = 0;
8433            return BAD_VALUE;
8434        }
8435        status_t status = NO_ERROR;
8436        while (mCblk->serverIndex < mCblk->clientIndex) {
8437            int reply;
8438            uint32_t rsize = sizeof(int);
8439            int *p = (int *)(mBuffer + mCblk->serverIndex);
8440            int size = *p++;
8441            if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
8442                ALOGW("command(): invalid parameter block size");
8443                break;
8444            }
8445            effect_param_t *param = (effect_param_t *)p;
8446            if (param->psize == 0 || param->vsize == 0) {
8447                ALOGW("command(): null parameter or value size");
8448                mCblk->serverIndex += size;
8449                continue;
8450            }
8451            uint32_t psize = sizeof(effect_param_t) +
8452                             ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8453                             param->vsize;
8454            status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8455                                            psize,
8456                                            p,
8457                                            &rsize,
8458                                            &reply);
8459            // stop at first error encountered
8460            if (ret != NO_ERROR) {
8461                status = ret;
8462                *(int *)pReplyData = reply;
8463                break;
8464            } else if (reply != NO_ERROR) {
8465                *(int *)pReplyData = reply;
8466                break;
8467            }
8468            mCblk->serverIndex += size;
8469        }
8470        mCblk->serverIndex = 0;
8471        mCblk->clientIndex = 0;
8472        return status;
8473    } else if (cmdCode == EFFECT_CMD_ENABLE) {
8474        *(int *)pReplyData = NO_ERROR;
8475        return enable();
8476    } else if (cmdCode == EFFECT_CMD_DISABLE) {
8477        *(int *)pReplyData = NO_ERROR;
8478        return disable();
8479    }
8480
8481    return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8482}
8483
8484void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
8485{
8486    ALOGV("setControl %p control %d", this, hasControl);
8487
8488    mHasControl = hasControl;
8489    mEnabled = enabled;
8490
8491    if (signal && mEffectClient != 0) {
8492        mEffectClient->controlStatusChanged(hasControl);
8493    }
8494}
8495
8496void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8497                                                 uint32_t cmdSize,
8498                                                 void *pCmdData,
8499                                                 uint32_t replySize,
8500                                                 void *pReplyData)
8501{
8502    if (mEffectClient != 0) {
8503        mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8504    }
8505}
8506
8507
8508
8509void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8510{
8511    if (mEffectClient != 0) {
8512        mEffectClient->enableStatusChanged(enabled);
8513    }
8514}
8515
8516status_t AudioFlinger::EffectHandle::onTransact(
8517    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8518{
8519    return BnEffect::onTransact(code, data, reply, flags);
8520}
8521
8522
8523void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8524{
8525    bool locked = mCblk != NULL && tryLock(mCblk->lock);
8526
8527    snprintf(buffer, size, "\t\t\t%05d %05d    %01u    %01u      %05u  %05u\n",
8528            (mClient == 0) ? getpid_cached : mClient->pid(),
8529            mPriority,
8530            mHasControl,
8531            !locked,
8532            mCblk ? mCblk->clientIndex : 0,
8533            mCblk ? mCblk->serverIndex : 0
8534            );
8535
8536    if (locked) {
8537        mCblk->lock.unlock();
8538    }
8539}
8540
8541#undef LOG_TAG
8542#define LOG_TAG "AudioFlinger::EffectChain"
8543
8544AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
8545                                        int sessionId)
8546    : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
8547      mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8548      mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
8549{
8550    mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
8551    if (thread == NULL) {
8552        return;
8553    }
8554    mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8555                                    thread->frameCount();
8556}
8557
8558AudioFlinger::EffectChain::~EffectChain()
8559{
8560    if (mOwnInBuffer) {
8561        delete mInBuffer;
8562    }
8563
8564}
8565
8566// getEffectFromDesc_l() must be called with ThreadBase::mLock held
8567sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
8568{
8569    size_t size = mEffects.size();
8570
8571    for (size_t i = 0; i < size; i++) {
8572        if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
8573            return mEffects[i];
8574        }
8575    }
8576    return 0;
8577}
8578
8579// getEffectFromId_l() must be called with ThreadBase::mLock held
8580sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
8581{
8582    size_t size = mEffects.size();
8583
8584    for (size_t i = 0; i < size; i++) {
8585        // by convention, return first effect if id provided is 0 (0 is never a valid id)
8586        if (id == 0 || mEffects[i]->id() == id) {
8587            return mEffects[i];
8588        }
8589    }
8590    return 0;
8591}
8592
8593// getEffectFromType_l() must be called with ThreadBase::mLock held
8594sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8595        const effect_uuid_t *type)
8596{
8597    size_t size = mEffects.size();
8598
8599    for (size_t i = 0; i < size; i++) {
8600        if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
8601            return mEffects[i];
8602        }
8603    }
8604    return 0;
8605}
8606
8607// Must be called with EffectChain::mLock locked
8608void AudioFlinger::EffectChain::process_l()
8609{
8610    sp<ThreadBase> thread = mThread.promote();
8611    if (thread == 0) {
8612        ALOGW("process_l(): cannot promote mixer thread");
8613        return;
8614    }
8615    bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8616            (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
8617    // always process effects unless no more tracks are on the session and the effect tail
8618    // has been rendered
8619    bool doProcess = true;
8620    if (!isGlobalSession) {
8621        bool tracksOnSession = (trackCnt() != 0);
8622
8623        if (!tracksOnSession && mTailBufferCount == 0) {
8624            doProcess = false;
8625        }
8626
8627        if (activeTrackCnt() == 0) {
8628            // if no track is active and the effect tail has not been rendered,
8629            // the input buffer must be cleared here as the mixer process will not do it
8630            if (tracksOnSession || mTailBufferCount > 0) {
8631                size_t numSamples = thread->frameCount() * thread->channelCount();
8632                memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8633                if (mTailBufferCount > 0) {
8634                    mTailBufferCount--;
8635                }
8636            }
8637        }
8638    }
8639
8640    size_t size = mEffects.size();
8641    if (doProcess) {
8642        for (size_t i = 0; i < size; i++) {
8643            mEffects[i]->process();
8644        }
8645    }
8646    for (size_t i = 0; i < size; i++) {
8647        mEffects[i]->updateState();
8648    }
8649}
8650
8651// addEffect_l() must be called with PlaybackThread::mLock held
8652status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
8653{
8654    effect_descriptor_t desc = effect->desc();
8655    uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
8656
8657    Mutex::Autolock _l(mLock);
8658    effect->setChain(this);
8659    sp<ThreadBase> thread = mThread.promote();
8660    if (thread == 0) {
8661        return NO_INIT;
8662    }
8663    effect->setThread(thread);
8664
8665    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8666        // Auxiliary effects are inserted at the beginning of mEffects vector as
8667        // they are processed first and accumulated in chain input buffer
8668        mEffects.insertAt(effect, 0);
8669
8670        // the input buffer for auxiliary effect contains mono samples in
8671        // 32 bit format. This is to avoid saturation in AudoMixer
8672        // accumulation stage. Saturation is done in EffectModule::process() before
8673        // calling the process in effect engine
8674        size_t numSamples = thread->frameCount();
8675        int32_t *buffer = new int32_t[numSamples];
8676        memset(buffer, 0, numSamples * sizeof(int32_t));
8677        effect->setInBuffer((int16_t *)buffer);
8678        // auxiliary effects output samples to chain input buffer for further processing
8679        // by insert effects
8680        effect->setOutBuffer(mInBuffer);
8681    } else {
8682        // Insert effects are inserted at the end of mEffects vector as they are processed
8683        //  after track and auxiliary effects.
8684        // Insert effect order as a function of indicated preference:
8685        //  if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8686        //  another effect is present
8687        //  else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8688        //  last effect claiming first position
8689        //  else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8690        //  first effect claiming last position
8691        //  else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8692        // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8693        // already present
8694
8695        size_t size = mEffects.size();
8696        size_t idx_insert = size;
8697        ssize_t idx_insert_first = -1;
8698        ssize_t idx_insert_last = -1;
8699
8700        for (size_t i = 0; i < size; i++) {
8701            effect_descriptor_t d = mEffects[i]->desc();
8702            uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8703            uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8704            if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8705                // check invalid effect chaining combinations
8706                if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8707                    iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
8708                    ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
8709                    return INVALID_OPERATION;
8710                }
8711                // remember position of first insert effect and by default
8712                // select this as insert position for new effect
8713                if (idx_insert == size) {
8714                    idx_insert = i;
8715                }
8716                // remember position of last insert effect claiming
8717                // first position
8718                if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8719                    idx_insert_first = i;
8720                }
8721                // remember position of first insert effect claiming
8722                // last position
8723                if (iPref == EFFECT_FLAG_INSERT_LAST &&
8724                    idx_insert_last == -1) {
8725                    idx_insert_last = i;
8726                }
8727            }
8728        }
8729
8730        // modify idx_insert from first position if needed
8731        if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8732            if (idx_insert_last != -1) {
8733                idx_insert = idx_insert_last;
8734            } else {
8735                idx_insert = size;
8736            }
8737        } else {
8738            if (idx_insert_first != -1) {
8739                idx_insert = idx_insert_first + 1;
8740            }
8741        }
8742
8743        // always read samples from chain input buffer
8744        effect->setInBuffer(mInBuffer);
8745
8746        // if last effect in the chain, output samples to chain
8747        // output buffer, otherwise to chain input buffer
8748        if (idx_insert == size) {
8749            if (idx_insert != 0) {
8750                mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8751                mEffects[idx_insert-1]->configure();
8752            }
8753            effect->setOutBuffer(mOutBuffer);
8754        } else {
8755            effect->setOutBuffer(mInBuffer);
8756        }
8757        mEffects.insertAt(effect, idx_insert);
8758
8759        ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
8760    }
8761    effect->configure();
8762    return NO_ERROR;
8763}
8764
8765// removeEffect_l() must be called with PlaybackThread::mLock held
8766size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
8767{
8768    Mutex::Autolock _l(mLock);
8769    size_t size = mEffects.size();
8770    uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8771
8772    for (size_t i = 0; i < size; i++) {
8773        if (effect == mEffects[i]) {
8774            // calling stop here will remove pre-processing effect from the audio HAL.
8775            // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8776            // the middle of a read from audio HAL
8777            if (mEffects[i]->state() == EffectModule::ACTIVE ||
8778                    mEffects[i]->state() == EffectModule::STOPPING) {
8779                mEffects[i]->stop();
8780            }
8781            if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8782                delete[] effect->inBuffer();
8783            } else {
8784                if (i == size - 1 && i != 0) {
8785                    mEffects[i - 1]->setOutBuffer(mOutBuffer);
8786                    mEffects[i - 1]->configure();
8787                }
8788            }
8789            mEffects.removeAt(i);
8790            ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
8791            break;
8792        }
8793    }
8794
8795    return mEffects.size();
8796}
8797
8798// setDevice_l() must be called with PlaybackThread::mLock held
8799void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
8800{
8801    size_t size = mEffects.size();
8802    for (size_t i = 0; i < size; i++) {
8803        mEffects[i]->setDevice(device);
8804    }
8805}
8806
8807// setMode_l() must be called with PlaybackThread::mLock held
8808void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
8809{
8810    size_t size = mEffects.size();
8811    for (size_t i = 0; i < size; i++) {
8812        mEffects[i]->setMode(mode);
8813    }
8814}
8815
8816// setVolume_l() must be called with PlaybackThread::mLock held
8817bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
8818{
8819    uint32_t newLeft = *left;
8820    uint32_t newRight = *right;
8821    bool hasControl = false;
8822    int ctrlIdx = -1;
8823    size_t size = mEffects.size();
8824
8825    // first update volume controller
8826    for (size_t i = size; i > 0; i--) {
8827        if (mEffects[i - 1]->isProcessEnabled() &&
8828            (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
8829            ctrlIdx = i - 1;
8830            hasControl = true;
8831            break;
8832        }
8833    }
8834
8835    if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
8836        if (hasControl) {
8837            *left = mNewLeftVolume;
8838            *right = mNewRightVolume;
8839        }
8840        return hasControl;
8841    }
8842
8843    mVolumeCtrlIdx = ctrlIdx;
8844    mLeftVolume = newLeft;
8845    mRightVolume = newRight;
8846
8847    // second get volume update from volume controller
8848    if (ctrlIdx >= 0) {
8849        mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
8850        mNewLeftVolume = newLeft;
8851        mNewRightVolume = newRight;
8852    }
8853    // then indicate volume to all other effects in chain.
8854    // Pass altered volume to effects before volume controller
8855    // and requested volume to effects after controller
8856    uint32_t lVol = newLeft;
8857    uint32_t rVol = newRight;
8858
8859    for (size_t i = 0; i < size; i++) {
8860        if ((int)i == ctrlIdx) continue;
8861        // this also works for ctrlIdx == -1 when there is no volume controller
8862        if ((int)i > ctrlIdx) {
8863            lVol = *left;
8864            rVol = *right;
8865        }
8866        mEffects[i]->setVolume(&lVol, &rVol, false);
8867    }
8868    *left = newLeft;
8869    *right = newRight;
8870
8871    return hasControl;
8872}
8873
8874status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
8875{
8876    const size_t SIZE = 256;
8877    char buffer[SIZE];
8878    String8 result;
8879
8880    snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
8881    result.append(buffer);
8882
8883    bool locked = tryLock(mLock);
8884    // failed to lock - AudioFlinger is probably deadlocked
8885    if (!locked) {
8886        result.append("\tCould not lock mutex:\n");
8887    }
8888
8889    result.append("\tNum fx In buffer   Out buffer   Active tracks:\n");
8890    snprintf(buffer, SIZE, "\t%02d     0x%08x  0x%08x   %d\n",
8891            mEffects.size(),
8892            (uint32_t)mInBuffer,
8893            (uint32_t)mOutBuffer,
8894            mActiveTrackCnt);
8895    result.append(buffer);
8896    write(fd, result.string(), result.size());
8897
8898    for (size_t i = 0; i < mEffects.size(); ++i) {
8899        sp<EffectModule> effect = mEffects[i];
8900        if (effect != 0) {
8901            effect->dump(fd, args);
8902        }
8903    }
8904
8905    if (locked) {
8906        mLock.unlock();
8907    }
8908
8909    return NO_ERROR;
8910}
8911
8912// must be called with ThreadBase::mLock held
8913void AudioFlinger::EffectChain::setEffectSuspended_l(
8914        const effect_uuid_t *type, bool suspend)
8915{
8916    sp<SuspendedEffectDesc> desc;
8917    // use effect type UUID timelow as key as there is no real risk of identical
8918    // timeLow fields among effect type UUIDs.
8919    ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
8920    if (suspend) {
8921        if (index >= 0) {
8922            desc = mSuspendedEffects.valueAt(index);
8923        } else {
8924            desc = new SuspendedEffectDesc();
8925            memcpy(&desc->mType, type, sizeof(effect_uuid_t));
8926            mSuspendedEffects.add(type->timeLow, desc);
8927            ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
8928        }
8929        if (desc->mRefCount++ == 0) {
8930            sp<EffectModule> effect = getEffectIfEnabled(type);
8931            if (effect != 0) {
8932                desc->mEffect = effect;
8933                effect->setSuspended(true);
8934                effect->setEnabled(false);
8935            }
8936        }
8937    } else {
8938        if (index < 0) {
8939            return;
8940        }
8941        desc = mSuspendedEffects.valueAt(index);
8942        if (desc->mRefCount <= 0) {
8943            ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
8944            desc->mRefCount = 1;
8945        }
8946        if (--desc->mRefCount == 0) {
8947            ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
8948            if (desc->mEffect != 0) {
8949                sp<EffectModule> effect = desc->mEffect.promote();
8950                if (effect != 0) {
8951                    effect->setSuspended(false);
8952                    sp<EffectHandle> handle = effect->controlHandle();
8953                    if (handle != 0) {
8954                        effect->setEnabled(handle->enabled());
8955                    }
8956                }
8957                desc->mEffect.clear();
8958            }
8959            mSuspendedEffects.removeItemsAt(index);
8960        }
8961    }
8962}
8963
8964// must be called with ThreadBase::mLock held
8965void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
8966{
8967    sp<SuspendedEffectDesc> desc;
8968
8969    ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8970    if (suspend) {
8971        if (index >= 0) {
8972            desc = mSuspendedEffects.valueAt(index);
8973        } else {
8974            desc = new SuspendedEffectDesc();
8975            mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
8976            ALOGV("setEffectSuspendedAll_l() add entry for 0");
8977        }
8978        if (desc->mRefCount++ == 0) {
8979            Vector< sp<EffectModule> > effects;
8980            getSuspendEligibleEffects(effects);
8981            for (size_t i = 0; i < effects.size(); i++) {
8982                setEffectSuspended_l(&effects[i]->desc().type, true);
8983            }
8984        }
8985    } else {
8986        if (index < 0) {
8987            return;
8988        }
8989        desc = mSuspendedEffects.valueAt(index);
8990        if (desc->mRefCount <= 0) {
8991            ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
8992            desc->mRefCount = 1;
8993        }
8994        if (--desc->mRefCount == 0) {
8995            Vector<const effect_uuid_t *> types;
8996            for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8997                if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8998                    continue;
8999                }
9000                types.add(&mSuspendedEffects.valueAt(i)->mType);
9001            }
9002            for (size_t i = 0; i < types.size(); i++) {
9003                setEffectSuspended_l(types[i], false);
9004            }
9005            ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
9006            mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9007        }
9008    }
9009}
9010
9011
9012// The volume effect is used for automated tests only
9013#ifndef OPENSL_ES_H_
9014static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9015                                            { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9016const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9017#endif //OPENSL_ES_H_
9018
9019bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9020{
9021    // auxiliary effects and visualizer are never suspended on output mix
9022    if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9023        (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
9024         (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9025         (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
9026        return false;
9027    }
9028    return true;
9029}
9030
9031void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
9032{
9033    effects.clear();
9034    for (size_t i = 0; i < mEffects.size(); i++) {
9035        if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9036            effects.add(mEffects[i]);
9037        }
9038    }
9039}
9040
9041sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9042                                                            const effect_uuid_t *type)
9043{
9044    sp<EffectModule> effect = getEffectFromType_l(type);
9045    return effect != 0 && effect->isEnabled() ? effect : 0;
9046}
9047
9048void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9049                                                            bool enabled)
9050{
9051    ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
9052    if (enabled) {
9053        if (index < 0) {
9054            // if the effect is not suspend check if all effects are suspended
9055            index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9056            if (index < 0) {
9057                return;
9058            }
9059            if (!isEffectEligibleForSuspend(effect->desc())) {
9060                return;
9061            }
9062            setEffectSuspended_l(&effect->desc().type, enabled);
9063            index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
9064            if (index < 0) {
9065                ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
9066                return;
9067            }
9068        }
9069        ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
9070            effect->desc().type.timeLow);
9071        sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9072        // if effect is requested to suspended but was not yet enabled, supend it now.
9073        if (desc->mEffect == 0) {
9074            desc->mEffect = effect;
9075            effect->setEnabled(false);
9076            effect->setSuspended(true);
9077        }
9078    } else {
9079        if (index < 0) {
9080            return;
9081        }
9082        ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
9083            effect->desc().type.timeLow);
9084        sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9085        desc->mEffect.clear();
9086        effect->setSuspended(false);
9087    }
9088}
9089
9090#undef LOG_TAG
9091#define LOG_TAG "AudioFlinger"
9092
9093// ----------------------------------------------------------------------------
9094
9095status_t AudioFlinger::onTransact(
9096        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9097{
9098    return BnAudioFlinger::onTransact(code, data, reply, flags);
9099}
9100
9101}; // namespace android
9102