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