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