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