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