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