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