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