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