AudioFlinger.cpp revision d4513b09123deebf8023b73a82d2d46d35806cea
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, 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
2077if (mType == DUPLICATING) {
2078#if 0   // see earlier FIXME
2079            // Now that this is a field instead of local variable,
2080            // clear it so it is empty the first time through the loop,
2081            // and later an assignment could combine the clear with the loop below
2082            outputTracks.clear();
2083#endif
2084            for (size_t i = 0; i < mOutputTracks.size(); i++) {
2085                outputTracks.add(mOutputTracks[i]);
2086            }
2087}
2088
2089            // put audio hardware into standby after short delay
2090            if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2091                        mSuspended > 0)) {
2092                if (!mStandby) {
2093
2094                    threadLoop_standby();
2095
2096                    mStandby = true;
2097                    mBytesWritten = 0;
2098                }
2099
2100                if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2101                    // we're about to wait, flush the binder command buffer
2102                    IPCThreadState::self()->flushCommands();
2103
2104if (mType == DUPLICATING) {
2105                    outputTracks.clear();
2106}
2107
2108                    if (exitPending()) break;
2109
2110                    releaseWakeLock_l();
2111                    // wait until we have something to do...
2112                    ALOGV("Thread %p type %d TID %d going to sleep", this, mType, gettid());
2113                    mWaitWorkCV.wait(mLock);
2114                    ALOGV("Thread %p type %d TID %d waking up", this, mType, gettid());
2115                    acquireWakeLock_l();
2116
2117if (mType == MIXER || mType == DUPLICATING) {
2118                    mPrevMixerStatus = MIXER_IDLE;
2119}
2120
2121                    checkSilentMode_l();
2122
2123if (mType == MIXER || mType == DUPLICATING) {
2124                    standbyTime = systemTime() + mStandbyTimeInNsecs;
2125}
2126
2127if (mType == DIRECT) {
2128                    standbyTime = systemTime() + standbyDelay;
2129}
2130
2131                    sleepTime = idleSleepTime;
2132
2133if (mType == MIXER) {
2134                    sleepTimeShift = 0;
2135}
2136
2137                    continue;
2138                }
2139            }
2140
2141            mixerStatus = prepareTracks_l(&tracksToRemove);
2142            // see FIXME in AudioFlinger.h
2143            if (mixerStatus == MIXER_CONTINUE) {
2144                continue;
2145            }
2146
2147            // prevent any changes in effect chain list and in each effect chain
2148            // during mixing and effect process as the audio buffers could be deleted
2149            // or modified if an effect is created or deleted
2150            lockEffectChains_l(effectChains);
2151        }
2152
2153if (mType == DIRECT) {
2154        // For DirectOutputThread, this test is equivalent to "activeTrack != 0"
2155}
2156
2157        if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2158            threadLoop_mix();
2159        } else {
2160            threadLoop_sleepTime();
2161        }
2162
2163        if (mSuspended > 0) {
2164            sleepTime = suspendSleepTimeUs();
2165        }
2166
2167        // only process effects if we're going to write
2168        if (sleepTime == 0) {
2169            for (size_t i = 0; i < effectChains.size(); i ++) {
2170                effectChains[i]->process_l();
2171            }
2172        }
2173
2174        // enable changes in effect chain
2175        unlockEffectChains(effectChains);
2176
2177        // sleepTime == 0 means we must write to audio hardware
2178        if (sleepTime == 0) {
2179
2180            threadLoop_write();
2181
2182if (mType == MIXER) {
2183            // write blocked detection
2184            nsecs_t now = systemTime();
2185            nsecs_t delta = now - mLastWriteTime;
2186            if (!mStandby && delta > maxPeriod) {
2187                mNumDelayedWrites++;
2188                if ((now - lastWarning) > kWarningThrottleNs) {
2189                    ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2190                            ns2ms(delta), mNumDelayedWrites, this);
2191                    lastWarning = now;
2192                }
2193                // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2194                // a different threshold. Or completely removed for what it is worth anyway...
2195                if (mStandby) {
2196                    longStandbyExit = true;
2197                }
2198            }
2199}
2200
2201            mStandby = false;
2202        } else {
2203            usleep(sleepTime);
2204        }
2205
2206        // finally let go of removed track(s), without the lock held
2207        // since we can't guarantee the destructors won't acquire that
2208        // same lock.
2209        tracksToRemove.clear();
2210
2211// FIXME merge these
2212if (mType == DIRECT) {
2213        activeTrack.clear();
2214}
2215if (mType == DUPLICATING) {
2216        outputTracks.clear();
2217}
2218
2219        // Effect chains will be actually deleted here if they were removed from
2220        // mEffectChains list during mixing or effects processing
2221        effectChains.clear();
2222
2223        // FIXME Note that the above .clear() is no longer necessary since effectChains
2224        // is now local to this block, but will keep it for now (at least until merge done).
2225    }
2226
2227if (mType == MIXER || mType == DIRECT) {
2228    // put output stream into standby mode
2229    if (!mStandby) {
2230        mOutput->stream->common.standby(&mOutput->stream->common);
2231    }
2232}
2233if (mType == DUPLICATING) {
2234    // for DuplicatingThread, standby mode is handled by the outputTracks
2235}
2236
2237    releaseWakeLock();
2238
2239    ALOGV("Thread %p type %d exiting", this, mType);
2240    return false;
2241}
2242
2243// shared by MIXER and DIRECT, overridden by DUPLICATING
2244void AudioFlinger::PlaybackThread::threadLoop_write()
2245{
2246    // FIXME rewrite to reduce number of system calls
2247    mLastWriteTime = systemTime();
2248    mInWrite = true;
2249    mBytesWritten += mixBufferSize;
2250    int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2251    if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2252    mNumWrites++;
2253    mInWrite = false;
2254}
2255
2256// shared by MIXER and DIRECT, overridden by DUPLICATING
2257void AudioFlinger::PlaybackThread::threadLoop_standby()
2258{
2259    ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2260    mOutput->stream->common.standby(&mOutput->stream->common);
2261}
2262
2263void AudioFlinger::MixerThread::threadLoop_mix()
2264{
2265    // obtain the presentation timestamp of the next output buffer
2266    int64_t pts;
2267    status_t status = INVALID_OPERATION;
2268
2269    if (NULL != mOutput->stream->get_next_write_timestamp) {
2270        status = mOutput->stream->get_next_write_timestamp(
2271                mOutput->stream, &pts);
2272    }
2273
2274    if (status != NO_ERROR) {
2275        pts = AudioBufferProvider::kInvalidPTS;
2276    }
2277
2278    // mix buffers...
2279    mAudioMixer->process(pts);
2280    // increase sleep time progressively when application underrun condition clears.
2281    // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2282    // that a steady state of alternating ready/not ready conditions keeps the sleep time
2283    // such that we would underrun the audio HAL.
2284    if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2285        sleepTimeShift--;
2286    }
2287    sleepTime = 0;
2288    standbyTime = systemTime() + mStandbyTimeInNsecs;
2289    //TODO: delay standby when effects have a tail
2290}
2291
2292void AudioFlinger::MixerThread::threadLoop_sleepTime()
2293{
2294    // If no tracks are ready, sleep once for the duration of an output
2295    // buffer size, then write 0s to the output
2296    if (sleepTime == 0) {
2297        if (mixerStatus == MIXER_TRACKS_ENABLED) {
2298            sleepTime = activeSleepTime >> sleepTimeShift;
2299            if (sleepTime < kMinThreadSleepTimeUs) {
2300                sleepTime = kMinThreadSleepTimeUs;
2301            }
2302            // reduce sleep time in case of consecutive application underruns to avoid
2303            // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2304            // duration we would end up writing less data than needed by the audio HAL if
2305            // the condition persists.
2306            if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2307                sleepTimeShift++;
2308            }
2309        } else {
2310            sleepTime = idleSleepTime;
2311        }
2312    } else if (mBytesWritten != 0 ||
2313               (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2314        memset (mMixBuffer, 0, mixBufferSize);
2315        sleepTime = 0;
2316        ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
2317    }
2318    // TODO add standby time extension fct of effect tail
2319}
2320
2321// prepareTracks_l() must be called with ThreadBase::mLock held
2322AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2323        Vector< sp<Track> > *tracksToRemove)
2324{
2325
2326    mixer_state mixerStatus = MIXER_IDLE;
2327    // find out which tracks need to be processed
2328    size_t count = mActiveTracks.size();
2329    size_t mixedTracks = 0;
2330    size_t tracksWithEffect = 0;
2331
2332    float masterVolume = mMasterVolume;
2333    bool  masterMute = mMasterMute;
2334
2335    if (masterMute) {
2336        masterVolume = 0;
2337    }
2338    // Delegate master volume control to effect in output mix effect chain if needed
2339    sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2340    if (chain != 0) {
2341        uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2342        chain->setVolume_l(&v, &v);
2343        masterVolume = (float)((v + (1 << 23)) >> 24);
2344        chain.clear();
2345    }
2346
2347    for (size_t i=0 ; i<count ; i++) {
2348        sp<Track> t = mActiveTracks[i].promote();
2349        if (t == 0) continue;
2350
2351        // this const just means the local variable doesn't change
2352        Track* const track = t.get();
2353        audio_track_cblk_t* cblk = track->cblk();
2354
2355        // The first time a track is added we wait
2356        // for all its buffers to be filled before processing it
2357        int name = track->name();
2358        // make sure that we have enough frames to mix one full buffer.
2359        // enforce this condition only once to enable draining the buffer in case the client
2360        // app does not call stop() and relies on underrun to stop:
2361        // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
2362        // during last round
2363        uint32_t minFrames = 1;
2364        if (!track->isStopped() && !track->isPausing() &&
2365                (mPrevMixerStatus == MIXER_TRACKS_READY)) {
2366            if (t->sampleRate() == (int)mSampleRate) {
2367                minFrames = mFrameCount;
2368            } else {
2369                // +1 for rounding and +1 for additional sample needed for interpolation
2370                minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2371                // add frames already consumed but not yet released by the resampler
2372                // because cblk->framesReady() will  include these frames
2373                minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2374                // the minimum track buffer size is normally twice the number of frames necessary
2375                // to fill one buffer and the resampler should not leave more than one buffer worth
2376                // of unreleased frames after each pass, but just in case...
2377                ALOG_ASSERT(minFrames <= cblk->frameCount);
2378            }
2379        }
2380        if ((track->framesReady() >= minFrames) && track->isReady() &&
2381                !track->isPaused() && !track->isTerminated())
2382        {
2383            //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
2384
2385            mixedTracks++;
2386
2387            // track->mainBuffer() != mMixBuffer means there is an effect chain
2388            // connected to the track
2389            chain.clear();
2390            if (track->mainBuffer() != mMixBuffer) {
2391                chain = getEffectChain_l(track->sessionId());
2392                // Delegate volume control to effect in track effect chain if needed
2393                if (chain != 0) {
2394                    tracksWithEffect++;
2395                } else {
2396                    ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
2397                            name, track->sessionId());
2398                }
2399            }
2400
2401
2402            int param = AudioMixer::VOLUME;
2403            if (track->mFillingUpStatus == Track::FS_FILLED) {
2404                // no ramp for the first volume setting
2405                track->mFillingUpStatus = Track::FS_ACTIVE;
2406                if (track->mState == TrackBase::RESUMING) {
2407                    track->mState = TrackBase::ACTIVE;
2408                    param = AudioMixer::RAMP_VOLUME;
2409                }
2410                mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
2411            } else if (cblk->server != 0) {
2412                // If the track is stopped before the first frame was mixed,
2413                // do not apply ramp
2414                param = AudioMixer::RAMP_VOLUME;
2415            }
2416
2417            // compute volume for this track
2418            uint32_t vl, vr, va;
2419            if (track->isMuted() || track->isPausing() ||
2420                mStreamTypes[track->streamType()].mute) {
2421                vl = vr = va = 0;
2422                if (track->isPausing()) {
2423                    track->setPaused();
2424                }
2425            } else {
2426
2427                // read original volumes with volume control
2428                float typeVolume = mStreamTypes[track->streamType()].volume;
2429                float v = masterVolume * typeVolume;
2430                uint32_t vlr = cblk->getVolumeLR();
2431                vl = vlr & 0xFFFF;
2432                vr = vlr >> 16;
2433                // track volumes come from shared memory, so can't be trusted and must be clamped
2434                if (vl > MAX_GAIN_INT) {
2435                    ALOGV("Track left volume out of range: %04X", vl);
2436                    vl = MAX_GAIN_INT;
2437                }
2438                if (vr > MAX_GAIN_INT) {
2439                    ALOGV("Track right volume out of range: %04X", vr);
2440                    vr = MAX_GAIN_INT;
2441                }
2442                // now apply the master volume and stream type volume
2443                vl = (uint32_t)(v * vl) << 12;
2444                vr = (uint32_t)(v * vr) << 12;
2445                // assuming master volume and stream type volume each go up to 1.0,
2446                // vl and vr are now in 8.24 format
2447
2448                uint16_t sendLevel = cblk->getSendLevel_U4_12();
2449                // send level comes from shared memory and so may be corrupt
2450                if (sendLevel > MAX_GAIN_INT) {
2451                    ALOGV("Track send level out of range: %04X", sendLevel);
2452                    sendLevel = MAX_GAIN_INT;
2453                }
2454                va = (uint32_t)(v * sendLevel);
2455            }
2456            // Delegate volume control to effect in track effect chain if needed
2457            if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2458                // Do not ramp volume if volume is controlled by effect
2459                param = AudioMixer::VOLUME;
2460                track->mHasVolumeController = true;
2461            } else {
2462                // force no volume ramp when volume controller was just disabled or removed
2463                // from effect chain to avoid volume spike
2464                if (track->mHasVolumeController) {
2465                    param = AudioMixer::VOLUME;
2466                }
2467                track->mHasVolumeController = false;
2468            }
2469
2470            // Convert volumes from 8.24 to 4.12 format
2471            // This additional clamping is needed in case chain->setVolume_l() overshot
2472            vl = (vl + (1 << 11)) >> 12;
2473            if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2474            vr = (vr + (1 << 11)) >> 12;
2475            if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
2476
2477            if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;   // va is uint32_t, so no need to check for -
2478
2479            // XXX: these things DON'T need to be done each time
2480            mAudioMixer->setBufferProvider(name, track);
2481            mAudioMixer->enable(name);
2482
2483            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2484            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2485            mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
2486            mAudioMixer->setParameter(
2487                name,
2488                AudioMixer::TRACK,
2489                AudioMixer::FORMAT, (void *)track->format());
2490            mAudioMixer->setParameter(
2491                name,
2492                AudioMixer::TRACK,
2493                AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
2494            mAudioMixer->setParameter(
2495                name,
2496                AudioMixer::RESAMPLE,
2497                AudioMixer::SAMPLE_RATE,
2498                (void *)(cblk->sampleRate));
2499            mAudioMixer->setParameter(
2500                name,
2501                AudioMixer::TRACK,
2502                AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2503            mAudioMixer->setParameter(
2504                name,
2505                AudioMixer::TRACK,
2506                AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2507
2508            // reset retry count
2509            track->mRetryCount = kMaxTrackRetries;
2510            // If one track is ready, set the mixer ready if:
2511            //  - the mixer was not ready during previous round OR
2512            //  - no other track is not ready
2513            if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2514                    mixerStatus != MIXER_TRACKS_ENABLED) {
2515                mixerStatus = MIXER_TRACKS_READY;
2516            }
2517        } else {
2518            //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
2519            if (track->isStopped()) {
2520                track->reset();
2521            }
2522            if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2523                // We have consumed all the buffers of this track.
2524                // Remove it from the list of active tracks.
2525                tracksToRemove->add(track);
2526            } else {
2527                // No buffers for this track. Give it a few chances to
2528                // fill a buffer, then remove it from active list.
2529                if (--(track->mRetryCount) <= 0) {
2530                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
2531                    tracksToRemove->add(track);
2532                    // indicate to client process that the track was disabled because of underrun
2533                    android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
2534                // If one track is not ready, mark the mixer also not ready if:
2535                //  - the mixer was ready during previous round OR
2536                //  - no other track is ready
2537                } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2538                                mixerStatus != MIXER_TRACKS_READY) {
2539                    mixerStatus = MIXER_TRACKS_ENABLED;
2540                }
2541            }
2542            mAudioMixer->disable(name);
2543        }
2544    }
2545
2546    // remove all the tracks that need to be...
2547    count = tracksToRemove->size();
2548    if (CC_UNLIKELY(count)) {
2549        for (size_t i=0 ; i<count ; i++) {
2550            const sp<Track>& track = tracksToRemove->itemAt(i);
2551            mActiveTracks.remove(track);
2552            if (track->mainBuffer() != mMixBuffer) {
2553                chain = getEffectChain_l(track->sessionId());
2554                if (chain != 0) {
2555                    ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
2556                    chain->decActiveTrackCnt();
2557                }
2558            }
2559            if (track->isTerminated()) {
2560                removeTrack_l(track);
2561            }
2562        }
2563    }
2564
2565    // mix buffer must be cleared if all tracks are connected to an
2566    // effect chain as in this case the mixer will not write to
2567    // mix buffer and track effects will accumulate into it
2568    if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2569        memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2570    }
2571
2572    mPrevMixerStatus = mixerStatus;
2573    return mixerStatus;
2574}
2575
2576void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
2577{
2578    ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
2579            this,  streamType, mTracks.size());
2580    Mutex::Autolock _l(mLock);
2581
2582    size_t size = mTracks.size();
2583    for (size_t i = 0; i < size; i++) {
2584        sp<Track> t = mTracks[i];
2585        if (t->streamType() == streamType) {
2586            android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
2587            t->mCblk->cv.signal();
2588        }
2589    }
2590}
2591
2592void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
2593{
2594    ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
2595            this,  streamType, valid);
2596    Mutex::Autolock _l(mLock);
2597
2598    mStreamTypes[streamType].valid = valid;
2599}
2600
2601// getTrackName_l() must be called with ThreadBase::mLock held
2602int AudioFlinger::MixerThread::getTrackName_l()
2603{
2604    return mAudioMixer->getTrackName();
2605}
2606
2607// deleteTrackName_l() must be called with ThreadBase::mLock held
2608void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2609{
2610    ALOGV("remove track (%d) and delete from mixer", name);
2611    mAudioMixer->deleteTrackName(name);
2612}
2613
2614// checkForNewParameters_l() must be called with ThreadBase::mLock held
2615bool AudioFlinger::MixerThread::checkForNewParameters_l()
2616{
2617    bool reconfig = false;
2618
2619    while (!mNewParameters.isEmpty()) {
2620        status_t status = NO_ERROR;
2621        String8 keyValuePair = mNewParameters[0];
2622        AudioParameter param = AudioParameter(keyValuePair);
2623        int value;
2624
2625        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2626            reconfig = true;
2627        }
2628        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
2629            if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
2630                status = BAD_VALUE;
2631            } else {
2632                reconfig = true;
2633            }
2634        }
2635        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
2636            if (value != AUDIO_CHANNEL_OUT_STEREO) {
2637                status = BAD_VALUE;
2638            } else {
2639                reconfig = true;
2640            }
2641        }
2642        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2643            // do not accept frame count changes if tracks are open as the track buffer
2644            // size depends on frame count and correct behavior would not be guaranteed
2645            // if frame count is changed after track creation
2646            if (!mTracks.isEmpty()) {
2647                status = INVALID_OPERATION;
2648            } else {
2649                reconfig = true;
2650            }
2651        }
2652        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
2653            // when changing the audio output device, call addBatteryData to notify
2654            // the change
2655            if ((int)mDevice != value) {
2656                uint32_t params = 0;
2657                // check whether speaker is on
2658                if (value & AUDIO_DEVICE_OUT_SPEAKER) {
2659                    params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2660                }
2661
2662                int deviceWithoutSpeaker
2663                    = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
2664                // check if any other device (except speaker) is on
2665                if (value & deviceWithoutSpeaker ) {
2666                    params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2667                }
2668
2669                if (params != 0) {
2670                    addBatteryData(params);
2671                }
2672            }
2673
2674            // forward device change to effects that have requested to be
2675            // aware of attached audio device.
2676            mDevice = (uint32_t)value;
2677            for (size_t i = 0; i < mEffectChains.size(); i++) {
2678                mEffectChains[i]->setDevice_l(mDevice);
2679            }
2680        }
2681
2682        if (status == NO_ERROR) {
2683            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
2684                                                    keyValuePair.string());
2685            if (!mStandby && status == INVALID_OPERATION) {
2686               mOutput->stream->common.standby(&mOutput->stream->common);
2687               mStandby = true;
2688               mBytesWritten = 0;
2689               status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
2690                                                       keyValuePair.string());
2691            }
2692            if (status == NO_ERROR && reconfig) {
2693                delete mAudioMixer;
2694                // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2695                mAudioMixer = NULL;
2696                readOutputParameters();
2697                mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2698                for (size_t i = 0; i < mTracks.size() ; i++) {
2699                    int name = getTrackName_l();
2700                    if (name < 0) break;
2701                    mTracks[i]->mName = name;
2702                    // limit track sample rate to 2 x new output sample rate
2703                    if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2704                        mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2705                    }
2706                }
2707                sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2708            }
2709        }
2710
2711        mNewParameters.removeAt(0);
2712
2713        mParamStatus = status;
2714        mParamCond.signal();
2715        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2716        // already timed out waiting for the status and will never signal the condition.
2717        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
2718    }
2719    return reconfig;
2720}
2721
2722status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2723{
2724    const size_t SIZE = 256;
2725    char buffer[SIZE];
2726    String8 result;
2727
2728    PlaybackThread::dumpInternals(fd, args);
2729
2730    snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2731    result.append(buffer);
2732    write(fd, result.string(), result.size());
2733    return NO_ERROR;
2734}
2735
2736uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2737{
2738    return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
2739}
2740
2741uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2742{
2743    return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2744}
2745
2746// ----------------------------------------------------------------------------
2747AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2748        AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
2749    :   PlaybackThread(audioFlinger, output, id, device, DIRECT)
2750        // mLeftVolFloat, mRightVolFloat
2751        // mLeftVolShort, mRightVolShort
2752{
2753}
2754
2755AudioFlinger::DirectOutputThread::~DirectOutputThread()
2756{
2757}
2758
2759void AudioFlinger::DirectOutputThread::applyVolume()
2760{
2761    // Do not apply volume on compressed audio
2762    if (!audio_is_linear_pcm(mFormat)) {
2763        return;
2764    }
2765
2766    // convert to signed 16 bit before volume calculation
2767    if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
2768        size_t count = mFrameCount * mChannelCount;
2769        uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2770        int16_t *dst = mMixBuffer + count-1;
2771        while(count--) {
2772            *dst-- = (int16_t)(*src--^0x80) << 8;
2773        }
2774    }
2775
2776    size_t frameCount = mFrameCount;
2777    int16_t *out = mMixBuffer;
2778    if (rampVolume) {
2779        if (mChannelCount == 1) {
2780            int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2781            int32_t vlInc = d / (int32_t)frameCount;
2782            int32_t vl = ((int32_t)mLeftVolShort << 16);
2783            do {
2784                out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2785                out++;
2786                vl += vlInc;
2787            } while (--frameCount);
2788
2789        } else {
2790            int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2791            int32_t vlInc = d / (int32_t)frameCount;
2792            d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2793            int32_t vrInc = d / (int32_t)frameCount;
2794            int32_t vl = ((int32_t)mLeftVolShort << 16);
2795            int32_t vr = ((int32_t)mRightVolShort << 16);
2796            do {
2797                out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2798                out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2799                out += 2;
2800                vl += vlInc;
2801                vr += vrInc;
2802            } while (--frameCount);
2803        }
2804    } else {
2805        if (mChannelCount == 1) {
2806            do {
2807                out[0] = clamp16(mul(out[0], leftVol) >> 12);
2808                out++;
2809            } while (--frameCount);
2810        } else {
2811            do {
2812                out[0] = clamp16(mul(out[0], leftVol) >> 12);
2813                out[1] = clamp16(mul(out[1], rightVol) >> 12);
2814                out += 2;
2815            } while (--frameCount);
2816        }
2817    }
2818
2819    // convert back to unsigned 8 bit after volume calculation
2820    if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
2821        size_t count = mFrameCount * mChannelCount;
2822        int16_t *src = mMixBuffer;
2823        uint8_t *dst = (uint8_t *)mMixBuffer;
2824        while(count--) {
2825            *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2826        }
2827    }
2828
2829    mLeftVolShort = leftVol;
2830    mRightVolShort = rightVol;
2831}
2832
2833AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
2834    Vector< sp<Track> > *tracksToRemove
2835)
2836{
2837    sp<Track> trackToRemove;
2838
2839    // FIXME Temporarily renamed to avoid confusion with the member "mixerStatus"
2840    mixer_state mixerStatus_ = MIXER_IDLE;
2841
2842    // find out which tracks need to be processed
2843    if (mActiveTracks.size() != 0) {
2844        sp<Track> t = mActiveTracks[0].promote();
2845        // see FIXME in AudioFlinger.h, return MIXER_IDLE might also work
2846        if (t == 0) return MIXER_CONTINUE;
2847        //if (t == 0) continue;
2848
2849        Track* const track = t.get();
2850        audio_track_cblk_t* cblk = track->cblk();
2851
2852        // The first time a track is added we wait
2853        // for all its buffers to be filled before processing it
2854        if (cblk->framesReady() && track->isReady() &&
2855                !track->isPaused() && !track->isTerminated())
2856        {
2857            //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2858
2859            if (track->mFillingUpStatus == Track::FS_FILLED) {
2860                track->mFillingUpStatus = Track::FS_ACTIVE;
2861                mLeftVolFloat = mRightVolFloat = 0;
2862                mLeftVolShort = mRightVolShort = 0;
2863                if (track->mState == TrackBase::RESUMING) {
2864                    track->mState = TrackBase::ACTIVE;
2865                    rampVolume = true;
2866                }
2867            } else if (cblk->server != 0) {
2868                // If the track is stopped before the first frame was mixed,
2869                // do not apply ramp
2870                rampVolume = true;
2871            }
2872            // compute volume for this track
2873            float left, right;
2874            if (track->isMuted() || mMasterMute || track->isPausing() ||
2875                mStreamTypes[track->streamType()].mute) {
2876                left = right = 0;
2877                if (track->isPausing()) {
2878                    track->setPaused();
2879                }
2880            } else {
2881                float typeVolume = mStreamTypes[track->streamType()].volume;
2882                float v = mMasterVolume * typeVolume;
2883                uint32_t vlr = cblk->getVolumeLR();
2884                float v_clamped = v * (vlr & 0xFFFF);
2885                if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2886                left = v_clamped/MAX_GAIN;
2887                v_clamped = v * (vlr >> 16);
2888                if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2889                right = v_clamped/MAX_GAIN;
2890            }
2891
2892            if (left != mLeftVolFloat || right != mRightVolFloat) {
2893                mLeftVolFloat = left;
2894                mRightVolFloat = right;
2895
2896                // If audio HAL implements volume control,
2897                // force software volume to nominal value
2898                if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
2899                    left = 1.0f;
2900                    right = 1.0f;
2901                }
2902
2903                // Convert volumes from float to 8.24
2904                uint32_t vl = (uint32_t)(left * (1 << 24));
2905                uint32_t vr = (uint32_t)(right * (1 << 24));
2906
2907                // Delegate volume control to effect in track effect chain if needed
2908                // only one effect chain can be present on DirectOutputThread, so if
2909                // there is one, the track is connected to it
2910                if (!mEffectChains.isEmpty()) {
2911                    // Do not ramp volume if volume is controlled by effect
2912                    if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
2913                        rampVolume = false;
2914                    }
2915                }
2916
2917                // Convert volumes from 8.24 to 4.12 format
2918                uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2919                if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2920                leftVol = (uint16_t)v_clamped;
2921                v_clamped = (vr + (1 << 11)) >> 12;
2922                if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2923                rightVol = (uint16_t)v_clamped;
2924            } else {
2925                leftVol = mLeftVolShort;
2926                rightVol = mRightVolShort;
2927                rampVolume = false;
2928            }
2929
2930            // reset retry count
2931            track->mRetryCount = kMaxTrackRetriesDirect;
2932            activeTrack = t;
2933            mixerStatus_ = MIXER_TRACKS_READY;
2934        } else {
2935            //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2936            if (track->isStopped()) {
2937                track->reset();
2938            }
2939            if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2940                // We have consumed all the buffers of this track.
2941                // Remove it from the list of active tracks.
2942                trackToRemove = track;
2943            } else {
2944                // No buffers for this track. Give it a few chances to
2945                // fill a buffer, then remove it from active list.
2946                if (--(track->mRetryCount) <= 0) {
2947                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2948                    trackToRemove = track;
2949                } else {
2950                    mixerStatus_ = MIXER_TRACKS_ENABLED;
2951                }
2952            }
2953        }
2954    }
2955
2956    // FIXME merge this with similar code for removing multiple tracks
2957    // remove all the tracks that need to be...
2958    if (CC_UNLIKELY(trackToRemove != 0)) {
2959        tracksToRemove->add(trackToRemove);
2960        mActiveTracks.remove(trackToRemove);
2961        if (!mEffectChains.isEmpty()) {
2962            ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2963                    trackToRemove->sessionId());
2964            mEffectChains[0]->decActiveTrackCnt();
2965        }
2966        if (trackToRemove->isTerminated()) {
2967            removeTrack_l(trackToRemove);
2968        }
2969    }
2970
2971    return mixerStatus_;
2972}
2973
2974void AudioFlinger::DirectOutputThread::threadLoop_mix()
2975{
2976    AudioBufferProvider::Buffer buffer;
2977    size_t frameCount = mFrameCount;
2978    int8_t *curBuf = (int8_t *)mMixBuffer;
2979    // output audio to hardware
2980    while (frameCount) {
2981        buffer.frameCount = frameCount;
2982        activeTrack->getNextBuffer(&buffer);
2983        if (CC_UNLIKELY(buffer.raw == NULL)) {
2984            memset(curBuf, 0, frameCount * mFrameSize);
2985            break;
2986        }
2987        memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2988        frameCount -= buffer.frameCount;
2989        curBuf += buffer.frameCount * mFrameSize;
2990        activeTrack->releaseBuffer(&buffer);
2991    }
2992    sleepTime = 0;
2993    standbyTime = systemTime() + standbyDelay;
2994    applyVolume();
2995}
2996
2997void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
2998{
2999    if (sleepTime == 0) {
3000        if (mixerStatus == MIXER_TRACKS_ENABLED) {
3001            sleepTime = activeSleepTime;
3002        } else {
3003            sleepTime = idleSleepTime;
3004        }
3005    } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3006        memset (mMixBuffer, 0, mFrameCount * mFrameSize);
3007        sleepTime = 0;
3008    }
3009}
3010
3011// getTrackName_l() must be called with ThreadBase::mLock held
3012int AudioFlinger::DirectOutputThread::getTrackName_l()
3013{
3014    return 0;
3015}
3016
3017// deleteTrackName_l() must be called with ThreadBase::mLock held
3018void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3019{
3020}
3021
3022// checkForNewParameters_l() must be called with ThreadBase::mLock held
3023bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3024{
3025    bool reconfig = false;
3026
3027    while (!mNewParameters.isEmpty()) {
3028        status_t status = NO_ERROR;
3029        String8 keyValuePair = mNewParameters[0];
3030        AudioParameter param = AudioParameter(keyValuePair);
3031        int value;
3032
3033        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3034            // do not accept frame count changes if tracks are open as the track buffer
3035            // size depends on frame count and correct behavior would not be garantied
3036            // if frame count is changed after track creation
3037            if (!mTracks.isEmpty()) {
3038                status = INVALID_OPERATION;
3039            } else {
3040                reconfig = true;
3041            }
3042        }
3043        if (status == NO_ERROR) {
3044            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3045                                                    keyValuePair.string());
3046            if (!mStandby && status == INVALID_OPERATION) {
3047               mOutput->stream->common.standby(&mOutput->stream->common);
3048               mStandby = true;
3049               mBytesWritten = 0;
3050               status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3051                                                       keyValuePair.string());
3052            }
3053            if (status == NO_ERROR && reconfig) {
3054                readOutputParameters();
3055                sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3056            }
3057        }
3058
3059        mNewParameters.removeAt(0);
3060
3061        mParamStatus = status;
3062        mParamCond.signal();
3063        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3064        // already timed out waiting for the status and will never signal the condition.
3065        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3066    }
3067    return reconfig;
3068}
3069
3070uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
3071{
3072    uint32_t time;
3073    if (audio_is_linear_pcm(mFormat)) {
3074        time = PlaybackThread::activeSleepTimeUs();
3075    } else {
3076        time = 10000;
3077    }
3078    return time;
3079}
3080
3081uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
3082{
3083    uint32_t time;
3084    if (audio_is_linear_pcm(mFormat)) {
3085        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3086    } else {
3087        time = 10000;
3088    }
3089    return time;
3090}
3091
3092uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
3093{
3094    uint32_t time;
3095    if (audio_is_linear_pcm(mFormat)) {
3096        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3097    } else {
3098        time = 10000;
3099    }
3100    return time;
3101}
3102
3103
3104// ----------------------------------------------------------------------------
3105
3106AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
3107        AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
3108    :   MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3109        mWaitTimeMs(UINT_MAX)
3110{
3111    addOutputTrack(mainThread);
3112}
3113
3114AudioFlinger::DuplicatingThread::~DuplicatingThread()
3115{
3116    for (size_t i = 0; i < mOutputTracks.size(); i++) {
3117        mOutputTracks[i]->destroy();
3118    }
3119}
3120
3121void AudioFlinger::DuplicatingThread::threadLoop_mix()
3122{
3123    // mix buffers...
3124    if (outputsReady(outputTracks)) {
3125        mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3126    } else {
3127        memset(mMixBuffer, 0, mixBufferSize);
3128    }
3129    sleepTime = 0;
3130    writeFrames = mFrameCount;
3131}
3132
3133void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3134{
3135    if (sleepTime == 0) {
3136        if (mixerStatus == MIXER_TRACKS_ENABLED) {
3137            sleepTime = activeSleepTime;
3138        } else {
3139            sleepTime = idleSleepTime;
3140        }
3141    } else if (mBytesWritten != 0) {
3142        // flush remaining overflow buffers in output tracks
3143        for (size_t i = 0; i < outputTracks.size(); i++) {
3144            if (outputTracks[i]->isActive()) {
3145                sleepTime = 0;
3146                writeFrames = 0;
3147                memset(mMixBuffer, 0, mixBufferSize);
3148                break;
3149            }
3150        }
3151    }
3152}
3153
3154void AudioFlinger::DuplicatingThread::threadLoop_write()
3155{
3156    standbyTime = systemTime() + mStandbyTimeInNsecs;
3157    for (size_t i = 0; i < outputTracks.size(); i++) {
3158        outputTracks[i]->write(mMixBuffer, writeFrames);
3159    }
3160    mBytesWritten += mixBufferSize;
3161}
3162
3163void AudioFlinger::DuplicatingThread::threadLoop_standby()
3164{
3165    // DuplicatingThread implements standby by stopping all tracks
3166    for (size_t i = 0; i < outputTracks.size(); i++) {
3167        outputTracks[i]->stop();
3168    }
3169}
3170
3171void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3172{
3173    Mutex::Autolock _l(mLock);
3174    // FIXME explain this formula
3175    int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3176    OutputTrack *outputTrack = new OutputTrack(thread,
3177                                            this,
3178                                            mSampleRate,
3179                                            mFormat,
3180                                            mChannelMask,
3181                                            frameCount);
3182    if (outputTrack->cblk() != NULL) {
3183        thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
3184        mOutputTracks.add(outputTrack);
3185        ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
3186        updateWaitTime_l();
3187    }
3188}
3189
3190void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3191{
3192    Mutex::Autolock _l(mLock);
3193    for (size_t i = 0; i < mOutputTracks.size(); i++) {
3194        if (mOutputTracks[i]->thread() == thread) {
3195            mOutputTracks[i]->destroy();
3196            mOutputTracks.removeAt(i);
3197            updateWaitTime_l();
3198            return;
3199        }
3200    }
3201    ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
3202}
3203
3204// caller must hold mLock
3205void AudioFlinger::DuplicatingThread::updateWaitTime_l()
3206{
3207    mWaitTimeMs = UINT_MAX;
3208    for (size_t i = 0; i < mOutputTracks.size(); i++) {
3209        sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3210        if (strong != 0) {
3211            uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3212            if (waitTimeMs < mWaitTimeMs) {
3213                mWaitTimeMs = waitTimeMs;
3214            }
3215        }
3216    }
3217}
3218
3219
3220bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
3221{
3222    for (size_t i = 0; i < outputTracks.size(); i++) {
3223        sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3224        if (thread == 0) {
3225            ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3226            return false;
3227        }
3228        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3229        if (playbackThread->standby() && !playbackThread->isSuspended()) {
3230            ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
3231            return false;
3232        }
3233    }
3234    return true;
3235}
3236
3237uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3238{
3239    return (mWaitTimeMs * 1000) / 2;
3240}
3241
3242// ----------------------------------------------------------------------------
3243
3244// TrackBase constructor must be called with AudioFlinger::mLock held
3245AudioFlinger::ThreadBase::TrackBase::TrackBase(
3246            ThreadBase *thread,
3247            const sp<Client>& client,
3248            uint32_t sampleRate,
3249            audio_format_t format,
3250            uint32_t channelMask,
3251            int frameCount,
3252            const sp<IMemory>& sharedBuffer,
3253            int sessionId)
3254    :   RefBase(),
3255        mThread(thread),
3256        mClient(client),
3257        mCblk(NULL),
3258        // mBuffer
3259        // mBufferEnd
3260        mFrameCount(0),
3261        mState(IDLE),
3262        mFormat(format),
3263        mStepServerFailed(false),
3264        mSessionId(sessionId)
3265        // mChannelCount
3266        // mChannelMask
3267{
3268    ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
3269
3270    // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
3271   size_t size = sizeof(audio_track_cblk_t);
3272   uint8_t channelCount = popcount(channelMask);
3273   size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3274   if (sharedBuffer == 0) {
3275       size += bufferSize;
3276   }
3277
3278   if (client != NULL) {
3279        mCblkMemory = client->heap()->allocate(size);
3280        if (mCblkMemory != 0) {
3281            mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3282            if (mCblk != NULL) { // construct the shared structure in-place.
3283                new(mCblk) audio_track_cblk_t();
3284                // clear all buffers
3285                mCblk->frameCount = frameCount;
3286                mCblk->sampleRate = sampleRate;
3287                mChannelCount = channelCount;
3288                mChannelMask = channelMask;
3289                if (sharedBuffer == 0) {
3290                    mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3291                    memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3292                    // Force underrun condition to avoid false underrun callback until first data is
3293                    // written to buffer (other flags are cleared)
3294                    mCblk->flags = CBLK_UNDERRUN_ON;
3295                } else {
3296                    mBuffer = sharedBuffer->pointer();
3297                }
3298                mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3299            }
3300        } else {
3301            ALOGE("not enough memory for AudioTrack size=%u", size);
3302            client->heap()->dump("AudioTrack");
3303            return;
3304        }
3305   } else {
3306       mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3307           // construct the shared structure in-place.
3308           new(mCblk) audio_track_cblk_t();
3309           // clear all buffers
3310           mCblk->frameCount = frameCount;
3311           mCblk->sampleRate = sampleRate;
3312           mChannelCount = channelCount;
3313           mChannelMask = channelMask;
3314           mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3315           memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3316           // Force underrun condition to avoid false underrun callback until first data is
3317           // written to buffer (other flags are cleared)
3318           mCblk->flags = CBLK_UNDERRUN_ON;
3319           mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3320   }
3321}
3322
3323AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3324{
3325    if (mCblk != NULL) {
3326        if (mClient == 0) {
3327            delete mCblk;
3328        } else {
3329            mCblk->~audio_track_cblk_t();   // destroy our shared-structure.
3330        }
3331    }
3332    mCblkMemory.clear();    // free the shared memory before releasing the heap it belongs to
3333    if (mClient != 0) {
3334        // Client destructor must run with AudioFlinger mutex locked
3335        Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3336        // If the client's reference count drops to zero, the associated destructor
3337        // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3338        // relying on the automatic clear() at end of scope.
3339        mClient.clear();
3340    }
3341}
3342
3343// AudioBufferProvider interface
3344// getNextBuffer() = 0;
3345// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
3346void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3347{
3348    buffer->raw = NULL;
3349    mFrameCount = buffer->frameCount;
3350    (void) step();      // ignore return value of step()
3351    buffer->frameCount = 0;
3352}
3353
3354bool AudioFlinger::ThreadBase::TrackBase::step() {
3355    bool result;
3356    audio_track_cblk_t* cblk = this->cblk();
3357
3358    result = cblk->stepServer(mFrameCount);
3359    if (!result) {
3360        ALOGV("stepServer failed acquiring cblk mutex");
3361        mStepServerFailed = true;
3362    }
3363    return result;
3364}
3365
3366void AudioFlinger::ThreadBase::TrackBase::reset() {
3367    audio_track_cblk_t* cblk = this->cblk();
3368
3369    cblk->user = 0;
3370    cblk->server = 0;
3371    cblk->userBase = 0;
3372    cblk->serverBase = 0;
3373    mStepServerFailed = false;
3374    ALOGV("TrackBase::reset");
3375}
3376
3377int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3378    return (int)mCblk->sampleRate;
3379}
3380
3381void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3382    audio_track_cblk_t* cblk = this->cblk();
3383    size_t frameSize = cblk->frameSize;
3384    int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3385    int8_t *bufferEnd = bufferStart + frames * frameSize;
3386
3387    // Check validity of returned pointer in case the track control block would have been corrupted.
3388    if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3389        ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
3390        ALOGE("TrackBase::getBuffer buffer out of range:\n    start: %p, end %p , mBuffer %p mBufferEnd %p\n    \
3391                server %d, serverBase %d, user %d, userBase %d",
3392                bufferStart, bufferEnd, mBuffer, mBufferEnd,
3393                cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
3394        return NULL;
3395    }
3396
3397    return bufferStart;
3398}
3399
3400// ----------------------------------------------------------------------------
3401
3402// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3403AudioFlinger::PlaybackThread::Track::Track(
3404            PlaybackThread *thread,
3405            const sp<Client>& client,
3406            audio_stream_type_t streamType,
3407            uint32_t sampleRate,
3408            audio_format_t format,
3409            uint32_t channelMask,
3410            int frameCount,
3411            const sp<IMemory>& sharedBuffer,
3412            int sessionId)
3413    :   TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
3414    mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3415    mAuxEffectId(0), mHasVolumeController(false)
3416{
3417    if (mCblk != NULL) {
3418        if (thread != NULL) {
3419            mName = thread->getTrackName_l();
3420            mMainBuffer = thread->mixBuffer();
3421        }
3422        ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
3423        if (mName < 0) {
3424            ALOGE("no more track names available");
3425        }
3426        mStreamType = streamType;
3427        // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3428        // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
3429        mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
3430    }
3431}
3432
3433AudioFlinger::PlaybackThread::Track::~Track()
3434{
3435    ALOGV("PlaybackThread::Track destructor");
3436    sp<ThreadBase> thread = mThread.promote();
3437    if (thread != 0) {
3438        Mutex::Autolock _l(thread->mLock);
3439        mState = TERMINATED;
3440    }
3441}
3442
3443void AudioFlinger::PlaybackThread::Track::destroy()
3444{
3445    // NOTE: destroyTrack_l() can remove a strong reference to this Track
3446    // by removing it from mTracks vector, so there is a risk that this Tracks's
3447    // destructor is called. As the destructor needs to lock mLock,
3448    // we must acquire a strong reference on this Track before locking mLock
3449    // here so that the destructor is called only when exiting this function.
3450    // On the other hand, as long as Track::destroy() is only called by
3451    // TrackHandle destructor, the TrackHandle still holds a strong ref on
3452    // this Track with its member mTrack.
3453    sp<Track> keep(this);
3454    { // scope for mLock
3455        sp<ThreadBase> thread = mThread.promote();
3456        if (thread != 0) {
3457            if (!isOutputTrack()) {
3458                if (mState == ACTIVE || mState == RESUMING) {
3459                    AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
3460
3461                    // to track the speaker usage
3462                    addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
3463                }
3464                AudioSystem::releaseOutput(thread->id());
3465            }
3466            Mutex::Autolock _l(thread->mLock);
3467            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3468            playbackThread->destroyTrack_l(this);
3469        }
3470    }
3471}
3472
3473void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3474{
3475    uint32_t vlr = mCblk->getVolumeLR();
3476    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",
3477            mName - AudioMixer::TRACK0,
3478            (mClient == 0) ? getpid_cached : mClient->pid(),
3479            mStreamType,
3480            mFormat,
3481            mChannelMask,
3482            mSessionId,
3483            mFrameCount,
3484            mState,
3485            mMute,
3486            mFillingUpStatus,
3487            mCblk->sampleRate,
3488            vlr & 0xFFFF,
3489            vlr >> 16,
3490            mCblk->server,
3491            mCblk->user,
3492            (int)mMainBuffer,
3493            (int)mAuxBuffer);
3494}
3495
3496// AudioBufferProvider interface
3497status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
3498    AudioBufferProvider::Buffer* buffer, int64_t pts)
3499{
3500     audio_track_cblk_t* cblk = this->cblk();
3501     uint32_t framesReady;
3502     uint32_t framesReq = buffer->frameCount;
3503
3504     // Check if last stepServer failed, try to step now
3505     if (mStepServerFailed) {
3506         if (!step())  goto getNextBuffer_exit;
3507         ALOGV("stepServer recovered");
3508         mStepServerFailed = false;
3509     }
3510
3511     framesReady = cblk->framesReady();
3512
3513     if (CC_LIKELY(framesReady)) {
3514        uint32_t s = cblk->server;
3515        uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3516
3517        bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3518        if (framesReq > framesReady) {
3519            framesReq = framesReady;
3520        }
3521        if (s + framesReq > bufferEnd) {
3522            framesReq = bufferEnd - s;
3523        }
3524
3525         buffer->raw = getBuffer(s, framesReq);
3526         if (buffer->raw == NULL) goto getNextBuffer_exit;
3527
3528         buffer->frameCount = framesReq;
3529        return NO_ERROR;
3530     }
3531
3532getNextBuffer_exit:
3533     buffer->raw = NULL;
3534     buffer->frameCount = 0;
3535     ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3536     return NOT_ENOUGH_DATA;
3537}
3538
3539uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const{
3540    return mCblk->framesReady();
3541}
3542
3543bool AudioFlinger::PlaybackThread::Track::isReady() const {
3544    if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
3545
3546    if (framesReady() >= mCblk->frameCount ||
3547            (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3548        mFillingUpStatus = FS_FILLED;
3549        android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3550        return true;
3551    }
3552    return false;
3553}
3554
3555status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid)
3556{
3557    status_t status = NO_ERROR;
3558    ALOGV("start(%d), calling pid %d session %d tid %d",
3559            mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
3560    sp<ThreadBase> thread = mThread.promote();
3561    if (thread != 0) {
3562        Mutex::Autolock _l(thread->mLock);
3563        track_state state = mState;
3564        // here the track could be either new, or restarted
3565        // in both cases "unstop" the track
3566        if (mState == PAUSED) {
3567            mState = TrackBase::RESUMING;
3568            ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3569        } else {
3570            mState = TrackBase::ACTIVE;
3571            ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
3572        }
3573
3574        if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3575            thread->mLock.unlock();
3576            status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
3577            thread->mLock.lock();
3578
3579            // to track the speaker usage
3580            if (status == NO_ERROR) {
3581                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3582            }
3583        }
3584        if (status == NO_ERROR) {
3585            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3586            playbackThread->addTrack_l(this);
3587        } else {
3588            mState = state;
3589        }
3590    } else {
3591        status = BAD_VALUE;
3592    }
3593    return status;
3594}
3595
3596void AudioFlinger::PlaybackThread::Track::stop()
3597{
3598    ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
3599    sp<ThreadBase> thread = mThread.promote();
3600    if (thread != 0) {
3601        Mutex::Autolock _l(thread->mLock);
3602        track_state state = mState;
3603        if (mState > STOPPED) {
3604            mState = STOPPED;
3605            // If the track is not active (PAUSED and buffers full), flush buffers
3606            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3607            if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3608                reset();
3609            }
3610            ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
3611        }
3612        if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3613            thread->mLock.unlock();
3614            AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
3615            thread->mLock.lock();
3616
3617            // to track the speaker usage
3618            addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
3619        }
3620    }
3621}
3622
3623void AudioFlinger::PlaybackThread::Track::pause()
3624{
3625    ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
3626    sp<ThreadBase> thread = mThread.promote();
3627    if (thread != 0) {
3628        Mutex::Autolock _l(thread->mLock);
3629        if (mState == ACTIVE || mState == RESUMING) {
3630            mState = PAUSING;
3631            ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
3632            if (!isOutputTrack()) {
3633                thread->mLock.unlock();
3634                AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
3635                thread->mLock.lock();
3636
3637                // to track the speaker usage
3638                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
3639            }
3640        }
3641    }
3642}
3643
3644void AudioFlinger::PlaybackThread::Track::flush()
3645{
3646    ALOGV("flush(%d)", mName);
3647    sp<ThreadBase> thread = mThread.promote();
3648    if (thread != 0) {
3649        Mutex::Autolock _l(thread->mLock);
3650        if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3651            return;
3652        }
3653        // No point remaining in PAUSED state after a flush => go to
3654        // STOPPED state
3655        mState = STOPPED;
3656
3657        // do not reset the track if it is still in the process of being stopped or paused.
3658        // this will be done by prepareTracks_l() when the track is stopped.
3659        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3660        if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3661            reset();
3662        }
3663    }
3664}
3665
3666void AudioFlinger::PlaybackThread::Track::reset()
3667{
3668    // Do not reset twice to avoid discarding data written just after a flush and before
3669    // the audioflinger thread detects the track is stopped.
3670    if (!mResetDone) {
3671        TrackBase::reset();
3672        // Force underrun condition to avoid false underrun callback until first data is
3673        // written to buffer
3674        android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3675        android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
3676        mFillingUpStatus = FS_FILLING;
3677        mResetDone = true;
3678    }
3679}
3680
3681void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3682{
3683    mMute = muted;
3684}
3685
3686status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3687{
3688    status_t status = DEAD_OBJECT;
3689    sp<ThreadBase> thread = mThread.promote();
3690    if (thread != 0) {
3691       PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3692       status = playbackThread->attachAuxEffect(this, EffectId);
3693    }
3694    return status;
3695}
3696
3697void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3698{
3699    mAuxEffectId = EffectId;
3700    mAuxBuffer = buffer;
3701}
3702
3703// timed audio tracks
3704
3705sp<AudioFlinger::PlaybackThread::TimedTrack>
3706AudioFlinger::PlaybackThread::TimedTrack::create(
3707            PlaybackThread *thread,
3708            const sp<Client>& client,
3709            audio_stream_type_t streamType,
3710            uint32_t sampleRate,
3711            audio_format_t format,
3712            uint32_t channelMask,
3713            int frameCount,
3714            const sp<IMemory>& sharedBuffer,
3715            int sessionId) {
3716    if (!client->reserveTimedTrack())
3717        return NULL;
3718
3719    sp<TimedTrack> track = new TimedTrack(
3720        thread, client, streamType, sampleRate, format, channelMask, frameCount,
3721        sharedBuffer, sessionId);
3722
3723    if (track == NULL) {
3724        client->releaseTimedTrack();
3725        return NULL;
3726    }
3727
3728    return track;
3729}
3730
3731AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
3732            PlaybackThread *thread,
3733            const sp<Client>& client,
3734            audio_stream_type_t streamType,
3735            uint32_t sampleRate,
3736            audio_format_t format,
3737            uint32_t channelMask,
3738            int frameCount,
3739            const sp<IMemory>& sharedBuffer,
3740            int sessionId)
3741    : Track(thread, client, streamType, sampleRate, format, channelMask,
3742            frameCount, sharedBuffer, sessionId),
3743      mTimedSilenceBuffer(NULL),
3744      mTimedSilenceBufferSize(0),
3745      mTimedAudioOutputOnTime(false),
3746      mMediaTimeTransformValid(false)
3747{
3748    LocalClock lc;
3749    mLocalTimeFreq = lc.getLocalFreq();
3750
3751    mLocalTimeToSampleTransform.a_zero = 0;
3752    mLocalTimeToSampleTransform.b_zero = 0;
3753    mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3754    mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3755    LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3756                            &mLocalTimeToSampleTransform.a_to_b_denom);
3757}
3758
3759AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3760    mClient->releaseTimedTrack();
3761    delete [] mTimedSilenceBuffer;
3762}
3763
3764status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3765    size_t size, sp<IMemory>* buffer) {
3766
3767    Mutex::Autolock _l(mTimedBufferQueueLock);
3768
3769    trimTimedBufferQueue_l();
3770
3771    // lazily initialize the shared memory heap for timed buffers
3772    if (mTimedMemoryDealer == NULL) {
3773        const int kTimedBufferHeapSize = 512 << 10;
3774
3775        mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3776                                              "AudioFlingerTimed");
3777        if (mTimedMemoryDealer == NULL)
3778            return NO_MEMORY;
3779    }
3780
3781    sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3782    if (newBuffer == NULL) {
3783        newBuffer = mTimedMemoryDealer->allocate(size);
3784        if (newBuffer == NULL)
3785            return NO_MEMORY;
3786    }
3787
3788    *buffer = newBuffer;
3789    return NO_ERROR;
3790}
3791
3792// caller must hold mTimedBufferQueueLock
3793void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3794    int64_t mediaTimeNow;
3795    {
3796        Mutex::Autolock mttLock(mMediaTimeTransformLock);
3797        if (!mMediaTimeTransformValid)
3798            return;
3799
3800        int64_t targetTimeNow;
3801        status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3802            ? mCCHelper.getCommonTime(&targetTimeNow)
3803            : mCCHelper.getLocalTime(&targetTimeNow);
3804
3805        if (OK != res)
3806            return;
3807
3808        if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3809                                                    &mediaTimeNow)) {
3810            return;
3811        }
3812    }
3813
3814    size_t trimIndex;
3815    for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3816        if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3817            break;
3818    }
3819
3820    if (trimIndex) {
3821        mTimedBufferQueue.removeItemsAt(0, trimIndex);
3822    }
3823}
3824
3825status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3826    const sp<IMemory>& buffer, int64_t pts) {
3827
3828    {
3829        Mutex::Autolock mttLock(mMediaTimeTransformLock);
3830        if (!mMediaTimeTransformValid)
3831            return INVALID_OPERATION;
3832    }
3833
3834    Mutex::Autolock _l(mTimedBufferQueueLock);
3835
3836    mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3837
3838    return NO_ERROR;
3839}
3840
3841status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3842    const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3843
3844    ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
3845         xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
3846         target);
3847
3848    if (!(target == TimedAudioTrack::LOCAL_TIME ||
3849          target == TimedAudioTrack::COMMON_TIME)) {
3850        return BAD_VALUE;
3851    }
3852
3853    Mutex::Autolock lock(mMediaTimeTransformLock);
3854    mMediaTimeTransform = xform;
3855    mMediaTimeTransformTarget = target;
3856    mMediaTimeTransformValid = true;
3857
3858    return NO_ERROR;
3859}
3860
3861#define min(a, b) ((a) < (b) ? (a) : (b))
3862
3863// implementation of getNextBuffer for tracks whose buffers have timestamps
3864status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
3865    AudioBufferProvider::Buffer* buffer, int64_t pts)
3866{
3867    if (pts == AudioBufferProvider::kInvalidPTS) {
3868        buffer->raw = 0;
3869        buffer->frameCount = 0;
3870        return INVALID_OPERATION;
3871    }
3872
3873    Mutex::Autolock _l(mTimedBufferQueueLock);
3874
3875    while (true) {
3876
3877        // if we have no timed buffers, then fail
3878        if (mTimedBufferQueue.isEmpty()) {
3879            buffer->raw = 0;
3880            buffer->frameCount = 0;
3881            return NOT_ENOUGH_DATA;
3882        }
3883
3884        TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
3885
3886        // calculate the PTS of the head of the timed buffer queue expressed in
3887        // local time
3888        int64_t headLocalPTS;
3889        {
3890            Mutex::Autolock mttLock(mMediaTimeTransformLock);
3891
3892            assert(mMediaTimeTransformValid);
3893
3894            if (mMediaTimeTransform.a_to_b_denom == 0) {
3895                // the transform represents a pause, so yield silence
3896                timedYieldSilence(buffer->frameCount, buffer);
3897                return NO_ERROR;
3898            }
3899
3900            int64_t transformedPTS;
3901            if (!mMediaTimeTransform.doForwardTransform(head.pts(),
3902                                                        &transformedPTS)) {
3903                // the transform failed.  this shouldn't happen, but if it does
3904                // then just drop this buffer
3905                ALOGW("timedGetNextBuffer transform failed");
3906                buffer->raw = 0;
3907                buffer->frameCount = 0;
3908                mTimedBufferQueue.removeAt(0);
3909                return NO_ERROR;
3910            }
3911
3912            if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
3913                if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
3914                                                          &headLocalPTS)) {
3915                    buffer->raw = 0;
3916                    buffer->frameCount = 0;
3917                    return INVALID_OPERATION;
3918                }
3919            } else {
3920                headLocalPTS = transformedPTS;
3921            }
3922        }
3923
3924        // adjust the head buffer's PTS to reflect the portion of the head buffer
3925        // that has already been consumed
3926        int64_t effectivePTS = headLocalPTS +
3927                ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
3928
3929        // Calculate the delta in samples between the head of the input buffer
3930        // queue and the start of the next output buffer that will be written.
3931        // If the transformation fails because of over or underflow, it means
3932        // that the sample's position in the output stream is so far out of
3933        // whack that it should just be dropped.
3934        int64_t sampleDelta;
3935        if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
3936            ALOGV("*** head buffer is too far from PTS: dropped buffer");
3937            mTimedBufferQueue.removeAt(0);
3938            continue;
3939        }
3940        if (!mLocalTimeToSampleTransform.doForwardTransform(
3941                (effectivePTS - pts) << 32, &sampleDelta)) {
3942            ALOGV("*** too late during sample rate transform: dropped buffer");
3943            mTimedBufferQueue.removeAt(0);
3944            continue;
3945        }
3946
3947        ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
3948             __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
3949             static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
3950             static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
3951
3952        // if the delta between the ideal placement for the next input sample and
3953        // the current output position is within this threshold, then we will
3954        // concatenate the next input samples to the previous output
3955        const int64_t kSampleContinuityThreshold =
3956                (static_cast<int64_t>(sampleRate()) << 32) / 10;
3957
3958        // if this is the first buffer of audio that we're emitting from this track
3959        // then it should be almost exactly on time.
3960        const int64_t kSampleStartupThreshold = 1LL << 32;
3961
3962        if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
3963            (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
3964            // the next input is close enough to being on time, so concatenate it
3965            // with the last output
3966            timedYieldSamples(buffer);
3967
3968            ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
3969            return NO_ERROR;
3970        } else if (sampleDelta > 0) {
3971            // the gap between the current output position and the proper start of
3972            // the next input sample is too big, so fill it with silence
3973            uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
3974
3975            timedYieldSilence(framesUntilNextInput, buffer);
3976            ALOGV("*** silence: frameCount=%u", buffer->frameCount);
3977            return NO_ERROR;
3978        } else {
3979            // the next input sample is late
3980            uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
3981            size_t onTimeSamplePosition =
3982                    head.position() + lateFrames * mCblk->frameSize;
3983
3984            if (onTimeSamplePosition > head.buffer()->size()) {
3985                // all the remaining samples in the head are too late, so
3986                // drop it and move on
3987                ALOGV("*** too late: dropped buffer");
3988                mTimedBufferQueue.removeAt(0);
3989                continue;
3990            } else {
3991                // skip over the late samples
3992                head.setPosition(onTimeSamplePosition);
3993
3994                // yield the available samples
3995                timedYieldSamples(buffer);
3996
3997                ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
3998                return NO_ERROR;
3999            }
4000        }
4001    }
4002}
4003
4004// Yield samples from the timed buffer queue head up to the given output
4005// buffer's capacity.
4006//
4007// Caller must hold mTimedBufferQueueLock
4008void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4009    AudioBufferProvider::Buffer* buffer) {
4010
4011    const TimedBuffer& head = mTimedBufferQueue[0];
4012
4013    buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4014                   head.position());
4015
4016    uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4017                                 mCblk->frameSize);
4018    size_t framesRequested = buffer->frameCount;
4019    buffer->frameCount = min(framesLeftInHead, framesRequested);
4020
4021    mTimedAudioOutputOnTime = true;
4022}
4023
4024// Yield samples of silence up to the given output buffer's capacity
4025//
4026// Caller must hold mTimedBufferQueueLock
4027void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4028    uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4029
4030    // lazily allocate a buffer filled with silence
4031    if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4032        delete [] mTimedSilenceBuffer;
4033        mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4034        mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4035        memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4036    }
4037
4038    buffer->raw = mTimedSilenceBuffer;
4039    size_t framesRequested = buffer->frameCount;
4040    buffer->frameCount = min(numFrames, framesRequested);
4041
4042    mTimedAudioOutputOnTime = false;
4043}
4044
4045// AudioBufferProvider interface
4046void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4047    AudioBufferProvider::Buffer* buffer) {
4048
4049    Mutex::Autolock _l(mTimedBufferQueueLock);
4050
4051    // If the buffer which was just released is part of the buffer at the head
4052    // of the queue, be sure to update the amt of the buffer which has been
4053    // consumed.  If the buffer being returned is not part of the head of the
4054    // queue, its either because the buffer is part of the silence buffer, or
4055    // because the head of the timed queue was trimmed after the mixer called
4056    // getNextBuffer but before the mixer called releaseBuffer.
4057    if ((buffer->raw != mTimedSilenceBuffer) && mTimedBufferQueue.size()) {
4058        TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4059
4060        void* start = head.buffer()->pointer();
4061        void* end   = (char *) head.buffer()->pointer() + head.buffer()->size();
4062
4063        if ((buffer->raw >= start) && (buffer->raw <= end)) {
4064            head.setPosition(head.position() +
4065                    (buffer->frameCount * mCblk->frameSize));
4066            if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4067                mTimedBufferQueue.removeAt(0);
4068            }
4069        }
4070    }
4071
4072    buffer->raw = 0;
4073    buffer->frameCount = 0;
4074}
4075
4076uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4077    Mutex::Autolock _l(mTimedBufferQueueLock);
4078
4079    uint32_t frames = 0;
4080    for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4081        const TimedBuffer& tb = mTimedBufferQueue[i];
4082        frames += (tb.buffer()->size() - tb.position())  / mCblk->frameSize;
4083    }
4084
4085    return frames;
4086}
4087
4088AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4089        : mPTS(0), mPosition(0) {}
4090
4091AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4092    const sp<IMemory>& buffer, int64_t pts)
4093        : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4094
4095// ----------------------------------------------------------------------------
4096
4097// RecordTrack constructor must be called with AudioFlinger::mLock held
4098AudioFlinger::RecordThread::RecordTrack::RecordTrack(
4099            RecordThread *thread,
4100            const sp<Client>& client,
4101            uint32_t sampleRate,
4102            audio_format_t format,
4103            uint32_t channelMask,
4104            int frameCount,
4105            int sessionId)
4106    :   TrackBase(thread, client, sampleRate, format,
4107                  channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
4108        mOverflow(false)
4109{
4110    if (mCblk != NULL) {
4111       ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4112       if (format == AUDIO_FORMAT_PCM_16_BIT) {
4113           mCblk->frameSize = mChannelCount * sizeof(int16_t);
4114       } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4115           mCblk->frameSize = mChannelCount * sizeof(int8_t);
4116       } else {
4117           mCblk->frameSize = sizeof(int8_t);
4118       }
4119    }
4120}
4121
4122AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4123{
4124    sp<ThreadBase> thread = mThread.promote();
4125    if (thread != 0) {
4126        AudioSystem::releaseInput(thread->id());
4127    }
4128}
4129
4130// AudioBufferProvider interface
4131status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
4132{
4133    audio_track_cblk_t* cblk = this->cblk();
4134    uint32_t framesAvail;
4135    uint32_t framesReq = buffer->frameCount;
4136
4137     // Check if last stepServer failed, try to step now
4138    if (mStepServerFailed) {
4139        if (!step()) goto getNextBuffer_exit;
4140        ALOGV("stepServer recovered");
4141        mStepServerFailed = false;
4142    }
4143
4144    framesAvail = cblk->framesAvailable_l();
4145
4146    if (CC_LIKELY(framesAvail)) {
4147        uint32_t s = cblk->server;
4148        uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4149
4150        if (framesReq > framesAvail) {
4151            framesReq = framesAvail;
4152        }
4153        if (s + framesReq > bufferEnd) {
4154            framesReq = bufferEnd - s;
4155        }
4156
4157        buffer->raw = getBuffer(s, framesReq);
4158        if (buffer->raw == NULL) goto getNextBuffer_exit;
4159
4160        buffer->frameCount = framesReq;
4161        return NO_ERROR;
4162    }
4163
4164getNextBuffer_exit:
4165    buffer->raw = NULL;
4166    buffer->frameCount = 0;
4167    return NOT_ENOUGH_DATA;
4168}
4169
4170status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid)
4171{
4172    sp<ThreadBase> thread = mThread.promote();
4173    if (thread != 0) {
4174        RecordThread *recordThread = (RecordThread *)thread.get();
4175        return recordThread->start(this, tid);
4176    } else {
4177        return BAD_VALUE;
4178    }
4179}
4180
4181void AudioFlinger::RecordThread::RecordTrack::stop()
4182{
4183    sp<ThreadBase> thread = mThread.promote();
4184    if (thread != 0) {
4185        RecordThread *recordThread = (RecordThread *)thread.get();
4186        recordThread->stop(this);
4187        TrackBase::reset();
4188        // Force overerrun condition to avoid false overrun callback until first data is
4189        // read from buffer
4190        android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
4191    }
4192}
4193
4194void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4195{
4196    snprintf(buffer, size, "   %05d %03u 0x%08x %05d   %04u %01d %05u  %08x %08x\n",
4197            (mClient == 0) ? getpid_cached : mClient->pid(),
4198            mFormat,
4199            mChannelMask,
4200            mSessionId,
4201            mFrameCount,
4202            mState,
4203            mCblk->sampleRate,
4204            mCblk->server,
4205            mCblk->user);
4206}
4207
4208
4209// ----------------------------------------------------------------------------
4210
4211AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
4212            PlaybackThread *playbackThread,
4213            DuplicatingThread *sourceThread,
4214            uint32_t sampleRate,
4215            audio_format_t format,
4216            uint32_t channelMask,
4217            int frameCount)
4218    :   Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
4219    mActive(false), mSourceThread(sourceThread)
4220{
4221
4222    if (mCblk != NULL) {
4223        mCblk->flags |= CBLK_DIRECTION_OUT;
4224        mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
4225        mOutBuffer.frameCount = 0;
4226        playbackThread->mTracks.add(this);
4227        ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
4228                "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4229                mCblk, mBuffer, mCblk->buffers,
4230                mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
4231    } else {
4232        ALOGW("Error creating output track on thread %p", playbackThread);
4233    }
4234}
4235
4236AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4237{
4238    clearBufferQueue();
4239}
4240
4241status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid)
4242{
4243    status_t status = Track::start(tid);
4244    if (status != NO_ERROR) {
4245        return status;
4246    }
4247
4248    mActive = true;
4249    mRetryCount = 127;
4250    return status;
4251}
4252
4253void AudioFlinger::PlaybackThread::OutputTrack::stop()
4254{
4255    Track::stop();
4256    clearBufferQueue();
4257    mOutBuffer.frameCount = 0;
4258    mActive = false;
4259}
4260
4261bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4262{
4263    Buffer *pInBuffer;
4264    Buffer inBuffer;
4265    uint32_t channelCount = mChannelCount;
4266    bool outputBufferFull = false;
4267    inBuffer.frameCount = frames;
4268    inBuffer.i16 = data;
4269
4270    uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4271
4272    if (!mActive && frames != 0) {
4273        start(0);
4274        sp<ThreadBase> thread = mThread.promote();
4275        if (thread != 0) {
4276            MixerThread *mixerThread = (MixerThread *)thread.get();
4277            if (mCblk->frameCount > frames){
4278                if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4279                    uint32_t startFrames = (mCblk->frameCount - frames);
4280                    pInBuffer = new Buffer;
4281                    pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4282                    pInBuffer->frameCount = startFrames;
4283                    pInBuffer->i16 = pInBuffer->mBuffer;
4284                    memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4285                    mBufferQueue.add(pInBuffer);
4286                } else {
4287                    ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
4288                }
4289            }
4290        }
4291    }
4292
4293    while (waitTimeLeftMs) {
4294        // First write pending buffers, then new data
4295        if (mBufferQueue.size()) {
4296            pInBuffer = mBufferQueue.itemAt(0);
4297        } else {
4298            pInBuffer = &inBuffer;
4299        }
4300
4301        if (pInBuffer->frameCount == 0) {
4302            break;
4303        }
4304
4305        if (mOutBuffer.frameCount == 0) {
4306            mOutBuffer.frameCount = pInBuffer->frameCount;
4307            nsecs_t startTime = systemTime();
4308            if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
4309                ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
4310                outputBufferFull = true;
4311                break;
4312            }
4313            uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4314            if (waitTimeLeftMs >= waitTimeMs) {
4315                waitTimeLeftMs -= waitTimeMs;
4316            } else {
4317                waitTimeLeftMs = 0;
4318            }
4319        }
4320
4321        uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4322        memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4323        mCblk->stepUser(outFrames);
4324        pInBuffer->frameCount -= outFrames;
4325        pInBuffer->i16 += outFrames * channelCount;
4326        mOutBuffer.frameCount -= outFrames;
4327        mOutBuffer.i16 += outFrames * channelCount;
4328
4329        if (pInBuffer->frameCount == 0) {
4330            if (mBufferQueue.size()) {
4331                mBufferQueue.removeAt(0);
4332                delete [] pInBuffer->mBuffer;
4333                delete pInBuffer;
4334                ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
4335            } else {
4336                break;
4337            }
4338        }
4339    }
4340
4341    // If we could not write all frames, allocate a buffer and queue it for next time.
4342    if (inBuffer.frameCount) {
4343        sp<ThreadBase> thread = mThread.promote();
4344        if (thread != 0 && !thread->standby()) {
4345            if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4346                pInBuffer = new Buffer;
4347                pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4348                pInBuffer->frameCount = inBuffer.frameCount;
4349                pInBuffer->i16 = pInBuffer->mBuffer;
4350                memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4351                mBufferQueue.add(pInBuffer);
4352                ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
4353            } else {
4354                ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
4355            }
4356        }
4357    }
4358
4359    // Calling write() with a 0 length buffer, means that no more data will be written:
4360    // If no more buffers are pending, fill output track buffer to make sure it is started
4361    // by output mixer.
4362    if (frames == 0 && mBufferQueue.size() == 0) {
4363        if (mCblk->user < mCblk->frameCount) {
4364            frames = mCblk->frameCount - mCblk->user;
4365            pInBuffer = new Buffer;
4366            pInBuffer->mBuffer = new int16_t[frames * channelCount];
4367            pInBuffer->frameCount = frames;
4368            pInBuffer->i16 = pInBuffer->mBuffer;
4369            memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4370            mBufferQueue.add(pInBuffer);
4371        } else if (mActive) {
4372            stop();
4373        }
4374    }
4375
4376    return outputBufferFull;
4377}
4378
4379status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4380{
4381    int active;
4382    status_t result;
4383    audio_track_cblk_t* cblk = mCblk;
4384    uint32_t framesReq = buffer->frameCount;
4385
4386//    ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
4387    buffer->frameCount  = 0;
4388
4389    uint32_t framesAvail = cblk->framesAvailable();
4390
4391
4392    if (framesAvail == 0) {
4393        Mutex::Autolock _l(cblk->lock);
4394        goto start_loop_here;
4395        while (framesAvail == 0) {
4396            active = mActive;
4397            if (CC_UNLIKELY(!active)) {
4398                ALOGV("Not active and NO_MORE_BUFFERS");
4399                return NO_MORE_BUFFERS;
4400            }
4401            result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4402            if (result != NO_ERROR) {
4403                return NO_MORE_BUFFERS;
4404            }
4405            // read the server count again
4406        start_loop_here:
4407            framesAvail = cblk->framesAvailable_l();
4408        }
4409    }
4410
4411//    if (framesAvail < framesReq) {
4412//        return NO_MORE_BUFFERS;
4413//    }
4414
4415    if (framesReq > framesAvail) {
4416        framesReq = framesAvail;
4417    }
4418
4419    uint32_t u = cblk->user;
4420    uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4421
4422    if (u + framesReq > bufferEnd) {
4423        framesReq = bufferEnd - u;
4424    }
4425
4426    buffer->frameCount  = framesReq;
4427    buffer->raw         = (void *)cblk->buffer(u);
4428    return NO_ERROR;
4429}
4430
4431
4432void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4433{
4434    size_t size = mBufferQueue.size();
4435
4436    for (size_t i = 0; i < size; i++) {
4437        Buffer *pBuffer = mBufferQueue.itemAt(i);
4438        delete [] pBuffer->mBuffer;
4439        delete pBuffer;
4440    }
4441    mBufferQueue.clear();
4442}
4443
4444// ----------------------------------------------------------------------------
4445
4446AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4447    :   RefBase(),
4448        mAudioFlinger(audioFlinger),
4449        // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
4450        mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4451        mPid(pid),
4452        mTimedTrackCount(0)
4453{
4454    // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4455}
4456
4457// Client destructor must be called with AudioFlinger::mLock held
4458AudioFlinger::Client::~Client()
4459{
4460    mAudioFlinger->removeClient_l(mPid);
4461}
4462
4463sp<MemoryDealer> AudioFlinger::Client::heap() const
4464{
4465    return mMemoryDealer;
4466}
4467
4468// Reserve one of the limited slots for a timed audio track associated
4469// with this client
4470bool AudioFlinger::Client::reserveTimedTrack()
4471{
4472    const int kMaxTimedTracksPerClient = 4;
4473
4474    Mutex::Autolock _l(mTimedTrackLock);
4475
4476    if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4477        ALOGW("can not create timed track - pid %d has exceeded the limit",
4478             mPid);
4479        return false;
4480    }
4481
4482    mTimedTrackCount++;
4483    return true;
4484}
4485
4486// Release a slot for a timed audio track
4487void AudioFlinger::Client::releaseTimedTrack()
4488{
4489    Mutex::Autolock _l(mTimedTrackLock);
4490    mTimedTrackCount--;
4491}
4492
4493// ----------------------------------------------------------------------------
4494
4495AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4496                                                     const sp<IAudioFlingerClient>& client,
4497                                                     pid_t pid)
4498    : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
4499{
4500}
4501
4502AudioFlinger::NotificationClient::~NotificationClient()
4503{
4504}
4505
4506void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4507{
4508    sp<NotificationClient> keep(this);
4509    mAudioFlinger->removeNotificationClient(mPid);
4510}
4511
4512// ----------------------------------------------------------------------------
4513
4514AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4515    : BnAudioTrack(),
4516      mTrack(track)
4517{
4518}
4519
4520AudioFlinger::TrackHandle::~TrackHandle() {
4521    // just stop the track on deletion, associated resources
4522    // will be freed from the main thread once all pending buffers have
4523    // been played. Unless it's not in the active track list, in which
4524    // case we free everything now...
4525    mTrack->destroy();
4526}
4527
4528sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4529    return mTrack->getCblk();
4530}
4531
4532status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4533    return mTrack->start(tid);
4534}
4535
4536void AudioFlinger::TrackHandle::stop() {
4537    mTrack->stop();
4538}
4539
4540void AudioFlinger::TrackHandle::flush() {
4541    mTrack->flush();
4542}
4543
4544void AudioFlinger::TrackHandle::mute(bool e) {
4545    mTrack->mute(e);
4546}
4547
4548void AudioFlinger::TrackHandle::pause() {
4549    mTrack->pause();
4550}
4551
4552status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4553{
4554    return mTrack->attachAuxEffect(EffectId);
4555}
4556
4557status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4558                                                         sp<IMemory>* buffer) {
4559    if (!mTrack->isTimedTrack())
4560        return INVALID_OPERATION;
4561
4562    PlaybackThread::TimedTrack* tt =
4563            reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4564    return tt->allocateTimedBuffer(size, buffer);
4565}
4566
4567status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4568                                                     int64_t pts) {
4569    if (!mTrack->isTimedTrack())
4570        return INVALID_OPERATION;
4571
4572    PlaybackThread::TimedTrack* tt =
4573            reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4574    return tt->queueTimedBuffer(buffer, pts);
4575}
4576
4577status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4578    const LinearTransform& xform, int target) {
4579
4580    if (!mTrack->isTimedTrack())
4581        return INVALID_OPERATION;
4582
4583    PlaybackThread::TimedTrack* tt =
4584            reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4585    return tt->setMediaTimeTransform(
4586        xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4587}
4588
4589status_t AudioFlinger::TrackHandle::onTransact(
4590    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4591{
4592    return BnAudioTrack::onTransact(code, data, reply, flags);
4593}
4594
4595// ----------------------------------------------------------------------------
4596
4597sp<IAudioRecord> AudioFlinger::openRecord(
4598        pid_t pid,
4599        audio_io_handle_t input,
4600        uint32_t sampleRate,
4601        audio_format_t format,
4602        uint32_t channelMask,
4603        int frameCount,
4604        // FIXME dead, remove from IAudioFlinger
4605        uint32_t flags,
4606        int *sessionId,
4607        status_t *status)
4608{
4609    sp<RecordThread::RecordTrack> recordTrack;
4610    sp<RecordHandle> recordHandle;
4611    sp<Client> client;
4612    status_t lStatus;
4613    RecordThread *thread;
4614    size_t inFrameCount;
4615    int lSessionId;
4616
4617    // check calling permissions
4618    if (!recordingAllowed()) {
4619        lStatus = PERMISSION_DENIED;
4620        goto Exit;
4621    }
4622
4623    // add client to list
4624    { // scope for mLock
4625        Mutex::Autolock _l(mLock);
4626        thread = checkRecordThread_l(input);
4627        if (thread == NULL) {
4628            lStatus = BAD_VALUE;
4629            goto Exit;
4630        }
4631
4632        client = registerPid_l(pid);
4633
4634        // If no audio session id is provided, create one here
4635        if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
4636            lSessionId = *sessionId;
4637        } else {
4638            lSessionId = nextUniqueId();
4639            if (sessionId != NULL) {
4640                *sessionId = lSessionId;
4641            }
4642        }
4643        // create new record track. The record track uses one track in mHardwareMixerThread by convention.
4644        recordTrack = thread->createRecordTrack_l(client,
4645                                                sampleRate,
4646                                                format,
4647                                                channelMask,
4648                                                frameCount,
4649                                                lSessionId,
4650                                                &lStatus);
4651    }
4652    if (lStatus != NO_ERROR) {
4653        // remove local strong reference to Client before deleting the RecordTrack so that the Client
4654        // destructor is called by the TrackBase destructor with mLock held
4655        client.clear();
4656        recordTrack.clear();
4657        goto Exit;
4658    }
4659
4660    // return to handle to client
4661    recordHandle = new RecordHandle(recordTrack);
4662    lStatus = NO_ERROR;
4663
4664Exit:
4665    if (status) {
4666        *status = lStatus;
4667    }
4668    return recordHandle;
4669}
4670
4671// ----------------------------------------------------------------------------
4672
4673AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4674    : BnAudioRecord(),
4675    mRecordTrack(recordTrack)
4676{
4677}
4678
4679AudioFlinger::RecordHandle::~RecordHandle() {
4680    stop();
4681}
4682
4683sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4684    return mRecordTrack->getCblk();
4685}
4686
4687status_t AudioFlinger::RecordHandle::start(pid_t tid) {
4688    ALOGV("RecordHandle::start()");
4689    return mRecordTrack->start(tid);
4690}
4691
4692void AudioFlinger::RecordHandle::stop() {
4693    ALOGV("RecordHandle::stop()");
4694    mRecordTrack->stop();
4695}
4696
4697status_t AudioFlinger::RecordHandle::onTransact(
4698    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4699{
4700    return BnAudioRecord::onTransact(code, data, reply, flags);
4701}
4702
4703// ----------------------------------------------------------------------------
4704
4705AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4706                                         AudioStreamIn *input,
4707                                         uint32_t sampleRate,
4708                                         uint32_t channels,
4709                                         audio_io_handle_t id,
4710                                         uint32_t device) :
4711    ThreadBase(audioFlinger, id, device, RECORD),
4712    mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4713    // mRsmpInIndex and mInputBytes set by readInputParameters()
4714    mReqChannelCount(popcount(channels)),
4715    mReqSampleRate(sampleRate)
4716    // mBytesRead is only meaningful while active, and so is cleared in start()
4717    // (but might be better to also clear here for dump?)
4718{
4719    snprintf(mName, kNameLength, "AudioIn_%X", id);
4720
4721    readInputParameters();
4722}
4723
4724
4725AudioFlinger::RecordThread::~RecordThread()
4726{
4727    delete[] mRsmpInBuffer;
4728    delete mResampler;
4729    delete[] mRsmpOutBuffer;
4730}
4731
4732void AudioFlinger::RecordThread::onFirstRef()
4733{
4734    run(mName, PRIORITY_URGENT_AUDIO);
4735}
4736
4737status_t AudioFlinger::RecordThread::readyToRun()
4738{
4739    status_t status = initCheck();
4740    ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4741    return status;
4742}
4743
4744bool AudioFlinger::RecordThread::threadLoop()
4745{
4746    AudioBufferProvider::Buffer buffer;
4747    sp<RecordTrack> activeTrack;
4748    Vector< sp<EffectChain> > effectChains;
4749
4750    nsecs_t lastWarning = 0;
4751
4752    acquireWakeLock();
4753
4754    // start recording
4755    while (!exitPending()) {
4756
4757        processConfigEvents();
4758
4759        { // scope for mLock
4760            Mutex::Autolock _l(mLock);
4761            checkForNewParameters_l();
4762            if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4763                if (!mStandby) {
4764                    mInput->stream->common.standby(&mInput->stream->common);
4765                    mStandby = true;
4766                }
4767
4768                if (exitPending()) break;
4769
4770                releaseWakeLock_l();
4771                ALOGV("RecordThread: loop stopping");
4772                // go to sleep
4773                mWaitWorkCV.wait(mLock);
4774                ALOGV("RecordThread: loop starting");
4775                acquireWakeLock_l();
4776                continue;
4777            }
4778            if (mActiveTrack != 0) {
4779                if (mActiveTrack->mState == TrackBase::PAUSING) {
4780                    if (!mStandby) {
4781                        mInput->stream->common.standby(&mInput->stream->common);
4782                        mStandby = true;
4783                    }
4784                    mActiveTrack.clear();
4785                    mStartStopCond.broadcast();
4786                } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4787                    if (mReqChannelCount != mActiveTrack->channelCount()) {
4788                        mActiveTrack.clear();
4789                        mStartStopCond.broadcast();
4790                    } else if (mBytesRead != 0) {
4791                        // record start succeeds only if first read from audio input
4792                        // succeeds
4793                        if (mBytesRead > 0) {
4794                            mActiveTrack->mState = TrackBase::ACTIVE;
4795                        } else {
4796                            mActiveTrack.clear();
4797                        }
4798                        mStartStopCond.broadcast();
4799                    }
4800                    mStandby = false;
4801                }
4802            }
4803            lockEffectChains_l(effectChains);
4804        }
4805
4806        if (mActiveTrack != 0) {
4807            if (mActiveTrack->mState != TrackBase::ACTIVE &&
4808                mActiveTrack->mState != TrackBase::RESUMING) {
4809                unlockEffectChains(effectChains);
4810                usleep(kRecordThreadSleepUs);
4811                continue;
4812            }
4813            for (size_t i = 0; i < effectChains.size(); i ++) {
4814                effectChains[i]->process_l();
4815            }
4816
4817            buffer.frameCount = mFrameCount;
4818            if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4819                size_t framesOut = buffer.frameCount;
4820                if (mResampler == NULL) {
4821                    // no resampling
4822                    while (framesOut) {
4823                        size_t framesIn = mFrameCount - mRsmpInIndex;
4824                        if (framesIn) {
4825                            int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4826                            int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4827                            if (framesIn > framesOut)
4828                                framesIn = framesOut;
4829                            mRsmpInIndex += framesIn;
4830                            framesOut -= framesIn;
4831                            if ((int)mChannelCount == mReqChannelCount ||
4832                                mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4833                                memcpy(dst, src, framesIn * mFrameSize);
4834                            } else {
4835                                int16_t *src16 = (int16_t *)src;
4836                                int16_t *dst16 = (int16_t *)dst;
4837                                if (mChannelCount == 1) {
4838                                    while (framesIn--) {
4839                                        *dst16++ = *src16;
4840                                        *dst16++ = *src16++;
4841                                    }
4842                                } else {
4843                                    while (framesIn--) {
4844                                        *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4845                                        src16 += 2;
4846                                    }
4847                                }
4848                            }
4849                        }
4850                        if (framesOut && mFrameCount == mRsmpInIndex) {
4851                            if (framesOut == mFrameCount &&
4852                                ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
4853                                mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
4854                                framesOut = 0;
4855                            } else {
4856                                mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
4857                                mRsmpInIndex = 0;
4858                            }
4859                            if (mBytesRead < 0) {
4860                                ALOGE("Error reading audio input");
4861                                if (mActiveTrack->mState == TrackBase::ACTIVE) {
4862                                    // Force input into standby so that it tries to
4863                                    // recover at next read attempt
4864                                    mInput->stream->common.standby(&mInput->stream->common);
4865                                    usleep(kRecordThreadSleepUs);
4866                                }
4867                                mRsmpInIndex = mFrameCount;
4868                                framesOut = 0;
4869                                buffer.frameCount = 0;
4870                            }
4871                        }
4872                    }
4873                } else {
4874                    // resampling
4875
4876                    memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4877                    // alter output frame count as if we were expecting stereo samples
4878                    if (mChannelCount == 1 && mReqChannelCount == 1) {
4879                        framesOut >>= 1;
4880                    }
4881                    mResampler->resample(mRsmpOutBuffer, framesOut, this);
4882                    // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4883                    // are 32 bit aligned which should be always true.
4884                    if (mChannelCount == 2 && mReqChannelCount == 1) {
4885                        ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4886                        // the resampler always outputs stereo samples: do post stereo to mono conversion
4887                        int16_t *src = (int16_t *)mRsmpOutBuffer;
4888                        int16_t *dst = buffer.i16;
4889                        while (framesOut--) {
4890                            *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4891                            src += 2;
4892                        }
4893                    } else {
4894                        ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4895                    }
4896
4897                }
4898                mActiveTrack->releaseBuffer(&buffer);
4899                mActiveTrack->overflow();
4900            }
4901            // client isn't retrieving buffers fast enough
4902            else {
4903                if (!mActiveTrack->setOverflow()) {
4904                    nsecs_t now = systemTime();
4905                    if ((now - lastWarning) > kWarningThrottleNs) {
4906                        ALOGW("RecordThread: buffer overflow");
4907                        lastWarning = now;
4908                    }
4909                }
4910                // Release the processor for a while before asking for a new buffer.
4911                // This will give the application more chance to read from the buffer and
4912                // clear the overflow.
4913                usleep(kRecordThreadSleepUs);
4914            }
4915        }
4916        // enable changes in effect chain
4917        unlockEffectChains(effectChains);
4918        effectChains.clear();
4919    }
4920
4921    if (!mStandby) {
4922        mInput->stream->common.standby(&mInput->stream->common);
4923    }
4924    mActiveTrack.clear();
4925
4926    mStartStopCond.broadcast();
4927
4928    releaseWakeLock();
4929
4930    ALOGV("RecordThread %p exiting", this);
4931    return false;
4932}
4933
4934
4935sp<AudioFlinger::RecordThread::RecordTrack>  AudioFlinger::RecordThread::createRecordTrack_l(
4936        const sp<AudioFlinger::Client>& client,
4937        uint32_t sampleRate,
4938        audio_format_t format,
4939        int channelMask,
4940        int frameCount,
4941        int sessionId,
4942        status_t *status)
4943{
4944    sp<RecordTrack> track;
4945    status_t lStatus;
4946
4947    lStatus = initCheck();
4948    if (lStatus != NO_ERROR) {
4949        ALOGE("Audio driver not initialized.");
4950        goto Exit;
4951    }
4952
4953    { // scope for mLock
4954        Mutex::Autolock _l(mLock);
4955
4956        track = new RecordTrack(this, client, sampleRate,
4957                      format, channelMask, frameCount, sessionId);
4958
4959        if (track->getCblk() == 0) {
4960            lStatus = NO_MEMORY;
4961            goto Exit;
4962        }
4963
4964        mTrack = track.get();
4965        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4966        bool suspend = audio_is_bluetooth_sco_device(
4967                (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
4968        setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4969        setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
4970    }
4971    lStatus = NO_ERROR;
4972
4973Exit:
4974    if (status) {
4975        *status = lStatus;
4976    }
4977    return track;
4978}
4979
4980status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, pid_t tid)
4981{
4982    ALOGV("RecordThread::start tid=%d", tid);
4983    sp <ThreadBase> strongMe = this;
4984    status_t status = NO_ERROR;
4985    {
4986        AutoMutex lock(mLock);
4987        if (mActiveTrack != 0) {
4988            if (recordTrack != mActiveTrack.get()) {
4989                status = -EBUSY;
4990            } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4991                mActiveTrack->mState = TrackBase::ACTIVE;
4992            }
4993            return status;
4994        }
4995
4996        recordTrack->mState = TrackBase::IDLE;
4997        mActiveTrack = recordTrack;
4998        mLock.unlock();
4999        status_t status = AudioSystem::startInput(mId);
5000        mLock.lock();
5001        if (status != NO_ERROR) {
5002            mActiveTrack.clear();
5003            return status;
5004        }
5005        mRsmpInIndex = mFrameCount;
5006        mBytesRead = 0;
5007        if (mResampler != NULL) {
5008            mResampler->reset();
5009        }
5010        mActiveTrack->mState = TrackBase::RESUMING;
5011        // signal thread to start
5012        ALOGV("Signal record thread");
5013        mWaitWorkCV.signal();
5014        // do not wait for mStartStopCond if exiting
5015        if (exitPending()) {
5016            mActiveTrack.clear();
5017            status = INVALID_OPERATION;
5018            goto startError;
5019        }
5020        mStartStopCond.wait(mLock);
5021        if (mActiveTrack == 0) {
5022            ALOGV("Record failed to start");
5023            status = BAD_VALUE;
5024            goto startError;
5025        }
5026        ALOGV("Record started OK");
5027        return status;
5028    }
5029startError:
5030    AudioSystem::stopInput(mId);
5031    return status;
5032}
5033
5034void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
5035    ALOGV("RecordThread::stop");
5036    sp <ThreadBase> strongMe = this;
5037    {
5038        AutoMutex lock(mLock);
5039        if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5040            mActiveTrack->mState = TrackBase::PAUSING;
5041            // do not wait for mStartStopCond if exiting
5042            if (exitPending()) {
5043                return;
5044            }
5045            mStartStopCond.wait(mLock);
5046            // if we have been restarted, recordTrack == mActiveTrack.get() here
5047            if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5048                mLock.unlock();
5049                AudioSystem::stopInput(mId);
5050                mLock.lock();
5051                ALOGV("Record stopped OK");
5052            }
5053        }
5054    }
5055}
5056
5057status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5058{
5059    const size_t SIZE = 256;
5060    char buffer[SIZE];
5061    String8 result;
5062
5063    snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5064    result.append(buffer);
5065
5066    if (mActiveTrack != 0) {
5067        result.append("Active Track:\n");
5068        result.append("   Clien Fmt Chn mask   Session Buf  S SRate  Serv     User\n");
5069        mActiveTrack->dump(buffer, SIZE);
5070        result.append(buffer);
5071
5072        snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5073        result.append(buffer);
5074        snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5075        result.append(buffer);
5076        snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
5077        result.append(buffer);
5078        snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5079        result.append(buffer);
5080        snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5081        result.append(buffer);
5082
5083
5084    } else {
5085        result.append("No record client\n");
5086    }
5087    write(fd, result.string(), result.size());
5088
5089    dumpBase(fd, args);
5090    dumpEffectChains(fd, args);
5091
5092    return NO_ERROR;
5093}
5094
5095// AudioBufferProvider interface
5096status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
5097{
5098    size_t framesReq = buffer->frameCount;
5099    size_t framesReady = mFrameCount - mRsmpInIndex;
5100    int channelCount;
5101
5102    if (framesReady == 0) {
5103        mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
5104        if (mBytesRead < 0) {
5105            ALOGE("RecordThread::getNextBuffer() Error reading audio input");
5106            if (mActiveTrack->mState == TrackBase::ACTIVE) {
5107                // Force input into standby so that it tries to
5108                // recover at next read attempt
5109                mInput->stream->common.standby(&mInput->stream->common);
5110                usleep(kRecordThreadSleepUs);
5111            }
5112            buffer->raw = NULL;
5113            buffer->frameCount = 0;
5114            return NOT_ENOUGH_DATA;
5115        }
5116        mRsmpInIndex = 0;
5117        framesReady = mFrameCount;
5118    }
5119
5120    if (framesReq > framesReady) {
5121        framesReq = framesReady;
5122    }
5123
5124    if (mChannelCount == 1 && mReqChannelCount == 2) {
5125        channelCount = 1;
5126    } else {
5127        channelCount = 2;
5128    }
5129    buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5130    buffer->frameCount = framesReq;
5131    return NO_ERROR;
5132}
5133
5134// AudioBufferProvider interface
5135void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5136{
5137    mRsmpInIndex += buffer->frameCount;
5138    buffer->frameCount = 0;
5139}
5140
5141bool AudioFlinger::RecordThread::checkForNewParameters_l()
5142{
5143    bool reconfig = false;
5144
5145    while (!mNewParameters.isEmpty()) {
5146        status_t status = NO_ERROR;
5147        String8 keyValuePair = mNewParameters[0];
5148        AudioParameter param = AudioParameter(keyValuePair);
5149        int value;
5150        audio_format_t reqFormat = mFormat;
5151        int reqSamplingRate = mReqSampleRate;
5152        int reqChannelCount = mReqChannelCount;
5153
5154        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5155            reqSamplingRate = value;
5156            reconfig = true;
5157        }
5158        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5159            reqFormat = (audio_format_t) value;
5160            reconfig = true;
5161        }
5162        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5163            reqChannelCount = popcount(value);
5164            reconfig = true;
5165        }
5166        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5167            // do not accept frame count changes if tracks are open as the track buffer
5168            // size depends on frame count and correct behavior would not be guaranteed
5169            // if frame count is changed after track creation
5170            if (mActiveTrack != 0) {
5171                status = INVALID_OPERATION;
5172            } else {
5173                reconfig = true;
5174            }
5175        }
5176        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5177            // forward device change to effects that have requested to be
5178            // aware of attached audio device.
5179            for (size_t i = 0; i < mEffectChains.size(); i++) {
5180                mEffectChains[i]->setDevice_l(value);
5181            }
5182            // store input device and output device but do not forward output device to audio HAL.
5183            // Note that status is ignored by the caller for output device
5184            // (see AudioFlinger::setParameters()
5185            if (value & AUDIO_DEVICE_OUT_ALL) {
5186                mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5187                status = BAD_VALUE;
5188            } else {
5189                mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
5190                // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5191                if (mTrack != NULL) {
5192                    bool suspend = audio_is_bluetooth_sco_device(
5193                            (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
5194                    setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5195                    setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5196                }
5197            }
5198            mDevice |= (uint32_t)value;
5199        }
5200        if (status == NO_ERROR) {
5201            status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
5202            if (status == INVALID_OPERATION) {
5203               mInput->stream->common.standby(&mInput->stream->common);
5204               status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
5205            }
5206            if (reconfig) {
5207                if (status == BAD_VALUE &&
5208                    reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5209                    reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
5210                    ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
5211                    (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
5212                    (reqChannelCount < 3)) {
5213                    status = NO_ERROR;
5214                }
5215                if (status == NO_ERROR) {
5216                    readInputParameters();
5217                    sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5218                }
5219            }
5220        }
5221
5222        mNewParameters.removeAt(0);
5223
5224        mParamStatus = status;
5225        mParamCond.signal();
5226        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5227        // already timed out waiting for the status and will never signal the condition.
5228        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5229    }
5230    return reconfig;
5231}
5232
5233String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5234{
5235    char *s;
5236    String8 out_s8 = String8();
5237
5238    Mutex::Autolock _l(mLock);
5239    if (initCheck() != NO_ERROR) {
5240        return out_s8;
5241    }
5242
5243    s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5244    out_s8 = String8(s);
5245    free(s);
5246    return out_s8;
5247}
5248
5249void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5250    AudioSystem::OutputDescriptor desc;
5251    void *param2 = NULL;
5252
5253    switch (event) {
5254    case AudioSystem::INPUT_OPENED:
5255    case AudioSystem::INPUT_CONFIG_CHANGED:
5256        desc.channels = mChannelMask;
5257        desc.samplingRate = mSampleRate;
5258        desc.format = mFormat;
5259        desc.frameCount = mFrameCount;
5260        desc.latency = 0;
5261        param2 = &desc;
5262        break;
5263
5264    case AudioSystem::INPUT_CLOSED:
5265    default:
5266        break;
5267    }
5268    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5269}
5270
5271void AudioFlinger::RecordThread::readInputParameters()
5272{
5273    delete mRsmpInBuffer;
5274    // mRsmpInBuffer is always assigned a new[] below
5275    delete mRsmpOutBuffer;
5276    mRsmpOutBuffer = NULL;
5277    delete mResampler;
5278    mResampler = NULL;
5279
5280    mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5281    mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5282    mChannelCount = (uint16_t)popcount(mChannelMask);
5283    mFormat = mInput->stream->common.get_format(&mInput->stream->common);
5284    mFrameSize = audio_stream_frame_size(&mInput->stream->common);
5285    mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5286    mFrameCount = mInputBytes / mFrameSize;
5287    mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5288
5289    if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
5290    {
5291        int channelCount;
5292         // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5293         // stereo to mono post process as the resampler always outputs stereo.
5294        if (mChannelCount == 1 && mReqChannelCount == 2) {
5295            channelCount = 1;
5296        } else {
5297            channelCount = 2;
5298        }
5299        mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5300        mResampler->setSampleRate(mSampleRate);
5301        mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5302        mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5303
5304        // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5305        if (mChannelCount == 1 && mReqChannelCount == 1) {
5306            mFrameCount >>= 1;
5307        }
5308
5309    }
5310    mRsmpInIndex = mFrameCount;
5311}
5312
5313unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5314{
5315    Mutex::Autolock _l(mLock);
5316    if (initCheck() != NO_ERROR) {
5317        return 0;
5318    }
5319
5320    return mInput->stream->get_input_frames_lost(mInput->stream);
5321}
5322
5323uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5324{
5325    Mutex::Autolock _l(mLock);
5326    uint32_t result = 0;
5327    if (getEffectChain_l(sessionId) != 0) {
5328        result = EFFECT_SESSION;
5329    }
5330
5331    if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5332        result |= TRACK_SESSION;
5333    }
5334
5335    return result;
5336}
5337
5338AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5339{
5340    Mutex::Autolock _l(mLock);
5341    return mTrack;
5342}
5343
5344AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
5345{
5346    Mutex::Autolock _l(mLock);
5347    return mInput;
5348}
5349
5350AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5351{
5352    Mutex::Autolock _l(mLock);
5353    AudioStreamIn *input = mInput;
5354    mInput = NULL;
5355    return input;
5356}
5357
5358// this method must always be called either with ThreadBase mLock held or inside the thread loop
5359audio_stream_t* AudioFlinger::RecordThread::stream()
5360{
5361    if (mInput == NULL) {
5362        return NULL;
5363    }
5364    return &mInput->stream->common;
5365}
5366
5367
5368// ----------------------------------------------------------------------------
5369
5370audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
5371                                uint32_t *pSamplingRate,
5372                                audio_format_t *pFormat,
5373                                uint32_t *pChannels,
5374                                uint32_t *pLatencyMs,
5375                                uint32_t flags)
5376{
5377    status_t status;
5378    PlaybackThread *thread = NULL;
5379    uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5380    audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
5381    uint32_t channels = pChannels ? *pChannels : 0;
5382    uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
5383    audio_stream_out_t *outStream;
5384    audio_hw_device_t *outHwDev;
5385
5386    ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
5387            pDevices ? *pDevices : 0,
5388            samplingRate,
5389            format,
5390            channels,
5391            flags);
5392
5393    if (pDevices == NULL || *pDevices == 0) {
5394        return 0;
5395    }
5396
5397    Mutex::Autolock _l(mLock);
5398
5399    outHwDev = findSuitableHwDev_l(*pDevices);
5400    if (outHwDev == NULL)
5401        return 0;
5402
5403    mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
5404    status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
5405                                          &channels, &samplingRate, &outStream);
5406    mHardwareStatus = AUDIO_HW_IDLE;
5407    ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
5408            outStream,
5409            samplingRate,
5410            format,
5411            channels,
5412            status);
5413
5414    if (outStream != NULL) {
5415        AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
5416        audio_io_handle_t id = nextUniqueId();
5417
5418        if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5419            (format != AUDIO_FORMAT_PCM_16_BIT) ||
5420            (channels != AUDIO_CHANNEL_OUT_STEREO)) {
5421            thread = new DirectOutputThread(this, output, id, *pDevices);
5422            ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
5423        } else {
5424            thread = new MixerThread(this, output, id, *pDevices);
5425            ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
5426        }
5427        mPlaybackThreads.add(id, thread);
5428
5429        if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5430        if (pFormat != NULL) *pFormat = format;
5431        if (pChannels != NULL) *pChannels = channels;
5432        if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
5433
5434        // notify client processes of the new output creation
5435        thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5436        return id;
5437    }
5438
5439    return 0;
5440}
5441
5442audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5443        audio_io_handle_t output2)
5444{
5445    Mutex::Autolock _l(mLock);
5446    MixerThread *thread1 = checkMixerThread_l(output1);
5447    MixerThread *thread2 = checkMixerThread_l(output2);
5448
5449    if (thread1 == NULL || thread2 == NULL) {
5450        ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
5451        return 0;
5452    }
5453
5454    audio_io_handle_t id = nextUniqueId();
5455    DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5456    thread->addOutputTrack(thread2);
5457    mPlaybackThreads.add(id, thread);
5458    // notify client processes of the new output creation
5459    thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5460    return id;
5461}
5462
5463status_t AudioFlinger::closeOutput(audio_io_handle_t output)
5464{
5465    // keep strong reference on the playback thread so that
5466    // it is not destroyed while exit() is executed
5467    sp <PlaybackThread> thread;
5468    {
5469        Mutex::Autolock _l(mLock);
5470        thread = checkPlaybackThread_l(output);
5471        if (thread == NULL) {
5472            return BAD_VALUE;
5473        }
5474
5475        ALOGV("closeOutput() %d", output);
5476
5477        if (thread->type() == ThreadBase::MIXER) {
5478            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5479                if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
5480                    DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5481                    dupThread->removeOutputTrack((MixerThread *)thread.get());
5482                }
5483            }
5484        }
5485        audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
5486        mPlaybackThreads.removeItem(output);
5487    }
5488    thread->exit();
5489    // The thread entity (active unit of execution) is no longer running here,
5490    // but the ThreadBase container still exists.
5491
5492    if (thread->type() != ThreadBase::DUPLICATING) {
5493        AudioStreamOut *out = thread->clearOutput();
5494        assert(out != NULL);
5495        // from now on thread->mOutput is NULL
5496        out->hwDev->close_output_stream(out->hwDev, out->stream);
5497        delete out;
5498    }
5499    return NO_ERROR;
5500}
5501
5502status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
5503{
5504    Mutex::Autolock _l(mLock);
5505    PlaybackThread *thread = checkPlaybackThread_l(output);
5506
5507    if (thread == NULL) {
5508        return BAD_VALUE;
5509    }
5510
5511    ALOGV("suspendOutput() %d", output);
5512    thread->suspend();
5513
5514    return NO_ERROR;
5515}
5516
5517status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
5518{
5519    Mutex::Autolock _l(mLock);
5520    PlaybackThread *thread = checkPlaybackThread_l(output);
5521
5522    if (thread == NULL) {
5523        return BAD_VALUE;
5524    }
5525
5526    ALOGV("restoreOutput() %d", output);
5527
5528    thread->restore();
5529
5530    return NO_ERROR;
5531}
5532
5533audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
5534                                uint32_t *pSamplingRate,
5535                                audio_format_t *pFormat,
5536                                uint32_t *pChannels,
5537                                audio_in_acoustics_t acoustics)
5538{
5539    status_t status;
5540    RecordThread *thread = NULL;
5541    uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5542    audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
5543    uint32_t channels = pChannels ? *pChannels : 0;
5544    uint32_t reqSamplingRate = samplingRate;
5545    audio_format_t reqFormat = format;
5546    uint32_t reqChannels = channels;
5547    audio_stream_in_t *inStream;
5548    audio_hw_device_t *inHwDev;
5549
5550    if (pDevices == NULL || *pDevices == 0) {
5551        return 0;
5552    }
5553
5554    Mutex::Autolock _l(mLock);
5555
5556    inHwDev = findSuitableHwDev_l(*pDevices);
5557    if (inHwDev == NULL)
5558        return 0;
5559
5560    status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
5561                                        &channels, &samplingRate,
5562                                        acoustics,
5563                                        &inStream);
5564    ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
5565            inStream,
5566            samplingRate,
5567            format,
5568            channels,
5569            acoustics,
5570            status);
5571
5572    // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5573    // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5574    // or stereo to mono conversions on 16 bit PCM inputs.
5575    if (inStream == NULL && status == BAD_VALUE &&
5576        reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
5577        (samplingRate <= 2 * reqSamplingRate) &&
5578        (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
5579        ALOGV("openInput() reopening with proposed sampling rate and channels");
5580        status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
5581                                            &channels, &samplingRate,
5582                                            acoustics,
5583                                            &inStream);
5584    }
5585
5586    if (inStream != NULL) {
5587        AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5588
5589        audio_io_handle_t id = nextUniqueId();
5590        // Start record thread
5591        // RecorThread require both input and output device indication to forward to audio
5592        // pre processing modules
5593        uint32_t device = (*pDevices) | primaryOutputDevice_l();
5594        thread = new RecordThread(this,
5595                                  input,
5596                                  reqSamplingRate,
5597                                  reqChannels,
5598                                  id,
5599                                  device);
5600        mRecordThreads.add(id, thread);
5601        ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
5602        if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5603        if (pFormat != NULL) *pFormat = format;
5604        if (pChannels != NULL) *pChannels = reqChannels;
5605
5606        input->stream->common.standby(&input->stream->common);
5607
5608        // notify client processes of the new input creation
5609        thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5610        return id;
5611    }
5612
5613    return 0;
5614}
5615
5616status_t AudioFlinger::closeInput(audio_io_handle_t input)
5617{
5618    // keep strong reference on the record thread so that
5619    // it is not destroyed while exit() is executed
5620    sp <RecordThread> thread;
5621    {
5622        Mutex::Autolock _l(mLock);
5623        thread = checkRecordThread_l(input);
5624        if (thread == NULL) {
5625            return BAD_VALUE;
5626        }
5627
5628        ALOGV("closeInput() %d", input);
5629        audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
5630        mRecordThreads.removeItem(input);
5631    }
5632    thread->exit();
5633    // The thread entity (active unit of execution) is no longer running here,
5634    // but the ThreadBase container still exists.
5635
5636    AudioStreamIn *in = thread->clearInput();
5637    assert(in != NULL);
5638    // from now on thread->mInput is NULL
5639    in->hwDev->close_input_stream(in->hwDev, in->stream);
5640    delete in;
5641
5642    return NO_ERROR;
5643}
5644
5645status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
5646{
5647    Mutex::Autolock _l(mLock);
5648    MixerThread *dstThread = checkMixerThread_l(output);
5649    if (dstThread == NULL) {
5650        ALOGW("setStreamOutput() bad output id %d", output);
5651        return BAD_VALUE;
5652    }
5653
5654    ALOGV("setStreamOutput() stream %d to output %d", stream, output);
5655    audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5656
5657    dstThread->setStreamValid(stream, true);
5658
5659    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5660        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5661        if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
5662            MixerThread *srcThread = (MixerThread *)thread;
5663            srcThread->setStreamValid(stream, false);
5664            srcThread->invalidateTracks(stream);
5665        }
5666    }
5667
5668    return NO_ERROR;
5669}
5670
5671
5672int AudioFlinger::newAudioSessionId()
5673{
5674    return nextUniqueId();
5675}
5676
5677void AudioFlinger::acquireAudioSessionId(int audioSession)
5678{
5679    Mutex::Autolock _l(mLock);
5680    pid_t caller = IPCThreadState::self()->getCallingPid();
5681    ALOGV("acquiring %d from %d", audioSession, caller);
5682    size_t num = mAudioSessionRefs.size();
5683    for (size_t i = 0; i< num; i++) {
5684        AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5685        if (ref->mSessionid == audioSession && ref->mPid == caller) {
5686            ref->mCnt++;
5687            ALOGV(" incremented refcount to %d", ref->mCnt);
5688            return;
5689        }
5690    }
5691    mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5692    ALOGV(" added new entry for %d", audioSession);
5693}
5694
5695void AudioFlinger::releaseAudioSessionId(int audioSession)
5696{
5697    Mutex::Autolock _l(mLock);
5698    pid_t caller = IPCThreadState::self()->getCallingPid();
5699    ALOGV("releasing %d from %d", audioSession, caller);
5700    size_t num = mAudioSessionRefs.size();
5701    for (size_t i = 0; i< num; i++) {
5702        AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5703        if (ref->mSessionid == audioSession && ref->mPid == caller) {
5704            ref->mCnt--;
5705            ALOGV(" decremented refcount to %d", ref->mCnt);
5706            if (ref->mCnt == 0) {
5707                mAudioSessionRefs.removeAt(i);
5708                delete ref;
5709                purgeStaleEffects_l();
5710            }
5711            return;
5712        }
5713    }
5714    ALOGW("session id %d not found for pid %d", audioSession, caller);
5715}
5716
5717void AudioFlinger::purgeStaleEffects_l() {
5718
5719    ALOGV("purging stale effects");
5720
5721    Vector< sp<EffectChain> > chains;
5722
5723    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5724        sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5725        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5726            sp<EffectChain> ec = t->mEffectChains[j];
5727            if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5728                chains.push(ec);
5729            }
5730        }
5731    }
5732    for (size_t i = 0; i < mRecordThreads.size(); i++) {
5733        sp<RecordThread> t = mRecordThreads.valueAt(i);
5734        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5735            sp<EffectChain> ec = t->mEffectChains[j];
5736            chains.push(ec);
5737        }
5738    }
5739
5740    for (size_t i = 0; i < chains.size(); i++) {
5741        sp<EffectChain> ec = chains[i];
5742        int sessionid = ec->sessionId();
5743        sp<ThreadBase> t = ec->mThread.promote();
5744        if (t == 0) {
5745            continue;
5746        }
5747        size_t numsessionrefs = mAudioSessionRefs.size();
5748        bool found = false;
5749        for (size_t k = 0; k < numsessionrefs; k++) {
5750            AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5751            if (ref->mSessionid == sessionid) {
5752                ALOGV(" session %d still exists for %d with %d refs",
5753                     sessionid, ref->mPid, ref->mCnt);
5754                found = true;
5755                break;
5756            }
5757        }
5758        if (!found) {
5759            // remove all effects from the chain
5760            while (ec->mEffects.size()) {
5761                sp<EffectModule> effect = ec->mEffects[0];
5762                effect->unPin();
5763                Mutex::Autolock _l (t->mLock);
5764                t->removeEffect_l(effect);
5765                for (size_t j = 0; j < effect->mHandles.size(); j++) {
5766                    sp<EffectHandle> handle = effect->mHandles[j].promote();
5767                    if (handle != 0) {
5768                        handle->mEffect.clear();
5769                        if (handle->mHasControl && handle->mEnabled) {
5770                            t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5771                        }
5772                    }
5773                }
5774                AudioSystem::unregisterEffect(effect->id());
5775            }
5776        }
5777    }
5778    return;
5779}
5780
5781// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5782AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
5783{
5784    return mPlaybackThreads.valueFor(output).get();
5785}
5786
5787// checkMixerThread_l() must be called with AudioFlinger::mLock held
5788AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
5789{
5790    PlaybackThread *thread = checkPlaybackThread_l(output);
5791    return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
5792}
5793
5794// checkRecordThread_l() must be called with AudioFlinger::mLock held
5795AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
5796{
5797    return mRecordThreads.valueFor(input).get();
5798}
5799
5800uint32_t AudioFlinger::nextUniqueId()
5801{
5802    return android_atomic_inc(&mNextUniqueId);
5803}
5804
5805AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
5806{
5807    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5808        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5809        AudioStreamOut *output = thread->getOutput();
5810        if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
5811            return thread;
5812        }
5813    }
5814    return NULL;
5815}
5816
5817uint32_t AudioFlinger::primaryOutputDevice_l() const
5818{
5819    PlaybackThread *thread = primaryPlaybackThread_l();
5820
5821    if (thread == NULL) {
5822        return 0;
5823    }
5824
5825    return thread->device();
5826}
5827
5828
5829// ----------------------------------------------------------------------------
5830//  Effect management
5831// ----------------------------------------------------------------------------
5832
5833
5834status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
5835{
5836    Mutex::Autolock _l(mLock);
5837    return EffectQueryNumberEffects(numEffects);
5838}
5839
5840status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
5841{
5842    Mutex::Autolock _l(mLock);
5843    return EffectQueryEffect(index, descriptor);
5844}
5845
5846status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
5847        effect_descriptor_t *descriptor) const
5848{
5849    Mutex::Autolock _l(mLock);
5850    return EffectGetDescriptor(pUuid, descriptor);
5851}
5852
5853
5854sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5855        effect_descriptor_t *pDesc,
5856        const sp<IEffectClient>& effectClient,
5857        int32_t priority,
5858        audio_io_handle_t io,
5859        int sessionId,
5860        status_t *status,
5861        int *id,
5862        int *enabled)
5863{
5864    status_t lStatus = NO_ERROR;
5865    sp<EffectHandle> handle;
5866    effect_descriptor_t desc;
5867
5868    ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
5869            pid, effectClient.get(), priority, sessionId, io);
5870
5871    if (pDesc == NULL) {
5872        lStatus = BAD_VALUE;
5873        goto Exit;
5874    }
5875
5876    // check audio settings permission for global effects
5877    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
5878        lStatus = PERMISSION_DENIED;
5879        goto Exit;
5880    }
5881
5882    // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
5883    // that can only be created by audio policy manager (running in same process)
5884    if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
5885        lStatus = PERMISSION_DENIED;
5886        goto Exit;
5887    }
5888
5889    if (io == 0) {
5890        if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
5891            // output must be specified by AudioPolicyManager when using session
5892            // AUDIO_SESSION_OUTPUT_STAGE
5893            lStatus = BAD_VALUE;
5894            goto Exit;
5895        } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
5896            // if the output returned by getOutputForEffect() is removed before we lock the
5897            // mutex below, the call to checkPlaybackThread_l(io) below will detect it
5898            // and we will exit safely
5899            io = AudioSystem::getOutputForEffect(&desc);
5900        }
5901    }
5902
5903    {
5904        Mutex::Autolock _l(mLock);
5905
5906
5907        if (!EffectIsNullUuid(&pDesc->uuid)) {
5908            // if uuid is specified, request effect descriptor
5909            lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5910            if (lStatus < 0) {
5911                ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5912                goto Exit;
5913            }
5914        } else {
5915            // if uuid is not specified, look for an available implementation
5916            // of the required type in effect factory
5917            if (EffectIsNullUuid(&pDesc->type)) {
5918                ALOGW("createEffect() no effect type");
5919                lStatus = BAD_VALUE;
5920                goto Exit;
5921            }
5922            uint32_t numEffects = 0;
5923            effect_descriptor_t d;
5924            d.flags = 0; // prevent compiler warning
5925            bool found = false;
5926
5927            lStatus = EffectQueryNumberEffects(&numEffects);
5928            if (lStatus < 0) {
5929                ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5930                goto Exit;
5931            }
5932            for (uint32_t i = 0; i < numEffects; i++) {
5933                lStatus = EffectQueryEffect(i, &desc);
5934                if (lStatus < 0) {
5935                    ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
5936                    continue;
5937                }
5938                if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5939                    // If matching type found save effect descriptor. If the session is
5940                    // 0 and the effect is not auxiliary, continue enumeration in case
5941                    // an auxiliary version of this effect type is available
5942                    found = true;
5943                    memcpy(&d, &desc, sizeof(effect_descriptor_t));
5944                    if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
5945                            (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5946                        break;
5947                    }
5948                }
5949            }
5950            if (!found) {
5951                lStatus = BAD_VALUE;
5952                ALOGW("createEffect() effect not found");
5953                goto Exit;
5954            }
5955            // For same effect type, chose auxiliary version over insert version if
5956            // connect to output mix (Compliance to OpenSL ES)
5957            if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
5958                    (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5959                memcpy(&desc, &d, sizeof(effect_descriptor_t));
5960            }
5961        }
5962
5963        // Do not allow auxiliary effects on a session different from 0 (output mix)
5964        if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
5965             (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5966            lStatus = INVALID_OPERATION;
5967            goto Exit;
5968        }
5969
5970        // check recording permission for visualizer
5971        if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5972            !recordingAllowed()) {
5973            lStatus = PERMISSION_DENIED;
5974            goto Exit;
5975        }
5976
5977        // return effect descriptor
5978        memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5979
5980        // If output is not specified try to find a matching audio session ID in one of the
5981        // output threads.
5982        // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5983        // because of code checking output when entering the function.
5984        // Note: io is never 0 when creating an effect on an input
5985        if (io == 0) {
5986             // look for the thread where the specified audio session is present
5987            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5988                if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5989                    io = mPlaybackThreads.keyAt(i);
5990                    break;
5991                }
5992            }
5993            if (io == 0) {
5994               for (size_t i = 0; i < mRecordThreads.size(); i++) {
5995                   if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5996                       io = mRecordThreads.keyAt(i);
5997                       break;
5998                   }
5999               }
6000            }
6001            // If no output thread contains the requested session ID, default to
6002            // first output. The effect chain will be moved to the correct output
6003            // thread when a track with the same session ID is created
6004            if (io == 0 && mPlaybackThreads.size()) {
6005                io = mPlaybackThreads.keyAt(0);
6006            }
6007            ALOGV("createEffect() got io %d for effect %s", io, desc.name);
6008        }
6009        ThreadBase *thread = checkRecordThread_l(io);
6010        if (thread == NULL) {
6011            thread = checkPlaybackThread_l(io);
6012            if (thread == NULL) {
6013                ALOGE("createEffect() unknown output thread");
6014                lStatus = BAD_VALUE;
6015                goto Exit;
6016            }
6017        }
6018
6019        sp<Client> client = registerPid_l(pid);
6020
6021        // create effect on selected output thread
6022        handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6023                &desc, enabled, &lStatus);
6024        if (handle != 0 && id != NULL) {
6025            *id = handle->id();
6026        }
6027    }
6028
6029Exit:
6030    if(status) {
6031        *status = lStatus;
6032    }
6033    return handle;
6034}
6035
6036status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6037        audio_io_handle_t dstOutput)
6038{
6039    ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
6040            sessionId, srcOutput, dstOutput);
6041    Mutex::Autolock _l(mLock);
6042    if (srcOutput == dstOutput) {
6043        ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
6044        return NO_ERROR;
6045    }
6046    PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6047    if (srcThread == NULL) {
6048        ALOGW("moveEffects() bad srcOutput %d", srcOutput);
6049        return BAD_VALUE;
6050    }
6051    PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6052    if (dstThread == NULL) {
6053        ALOGW("moveEffects() bad dstOutput %d", dstOutput);
6054        return BAD_VALUE;
6055    }
6056
6057    Mutex::Autolock _dl(dstThread->mLock);
6058    Mutex::Autolock _sl(srcThread->mLock);
6059    moveEffectChain_l(sessionId, srcThread, dstThread, false);
6060
6061    return NO_ERROR;
6062}
6063
6064// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
6065status_t AudioFlinger::moveEffectChain_l(int sessionId,
6066                                   AudioFlinger::PlaybackThread *srcThread,
6067                                   AudioFlinger::PlaybackThread *dstThread,
6068                                   bool reRegister)
6069{
6070    ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
6071            sessionId, srcThread, dstThread);
6072
6073    sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
6074    if (chain == 0) {
6075        ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
6076                sessionId, srcThread);
6077        return INVALID_OPERATION;
6078    }
6079
6080    // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
6081    // so that a new chain is created with correct parameters when first effect is added. This is
6082    // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
6083    // removed.
6084    srcThread->removeEffectChain_l(chain);
6085
6086    // transfer all effects one by one so that new effect chain is created on new thread with
6087    // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
6088    audio_io_handle_t dstOutput = dstThread->id();
6089    sp<EffectChain> dstChain;
6090    uint32_t strategy = 0; // prevent compiler warning
6091    sp<EffectModule> effect = chain->getEffectFromId_l(0);
6092    while (effect != 0) {
6093        srcThread->removeEffect_l(effect);
6094        dstThread->addEffect_l(effect);
6095        // removeEffect_l() has stopped the effect if it was active so it must be restarted
6096        if (effect->state() == EffectModule::ACTIVE ||
6097                effect->state() == EffectModule::STOPPING) {
6098            effect->start();
6099        }
6100        // if the move request is not received from audio policy manager, the effect must be
6101        // re-registered with the new strategy and output
6102        if (dstChain == 0) {
6103            dstChain = effect->chain().promote();
6104            if (dstChain == 0) {
6105                ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
6106                srcThread->addEffect_l(effect);
6107                return NO_INIT;
6108            }
6109            strategy = dstChain->strategy();
6110        }
6111        if (reRegister) {
6112            AudioSystem::unregisterEffect(effect->id());
6113            AudioSystem::registerEffect(&effect->desc(),
6114                                        dstOutput,
6115                                        strategy,
6116                                        sessionId,
6117                                        effect->id());
6118        }
6119        effect = chain->getEffectFromId_l(0);
6120    }
6121
6122    return NO_ERROR;
6123}
6124
6125
6126// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
6127sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
6128        const sp<AudioFlinger::Client>& client,
6129        const sp<IEffectClient>& effectClient,
6130        int32_t priority,
6131        int sessionId,
6132        effect_descriptor_t *desc,
6133        int *enabled,
6134        status_t *status
6135        )
6136{
6137    sp<EffectModule> effect;
6138    sp<EffectHandle> handle;
6139    status_t lStatus;
6140    sp<EffectChain> chain;
6141    bool chainCreated = false;
6142    bool effectCreated = false;
6143    bool effectRegistered = false;
6144
6145    lStatus = initCheck();
6146    if (lStatus != NO_ERROR) {
6147        ALOGW("createEffect_l() Audio driver not initialized.");
6148        goto Exit;
6149    }
6150
6151    // Do not allow effects with session ID 0 on direct output or duplicating threads
6152    // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
6153    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
6154        ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
6155                desc->name, sessionId);
6156        lStatus = BAD_VALUE;
6157        goto Exit;
6158    }
6159    // Only Pre processor effects are allowed on input threads and only on input threads
6160    if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
6161        ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
6162                desc->name, desc->flags, mType);
6163        lStatus = BAD_VALUE;
6164        goto Exit;
6165    }
6166
6167    ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
6168
6169    { // scope for mLock
6170        Mutex::Autolock _l(mLock);
6171
6172        // check for existing effect chain with the requested audio session
6173        chain = getEffectChain_l(sessionId);
6174        if (chain == 0) {
6175            // create a new chain for this session
6176            ALOGV("createEffect_l() new effect chain for session %d", sessionId);
6177            chain = new EffectChain(this, sessionId);
6178            addEffectChain_l(chain);
6179            chain->setStrategy(getStrategyForSession_l(sessionId));
6180            chainCreated = true;
6181        } else {
6182            effect = chain->getEffectFromDesc_l(desc);
6183        }
6184
6185        ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
6186
6187        if (effect == 0) {
6188            int id = mAudioFlinger->nextUniqueId();
6189            // Check CPU and memory usage
6190            lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
6191            if (lStatus != NO_ERROR) {
6192                goto Exit;
6193            }
6194            effectRegistered = true;
6195            // create a new effect module if none present in the chain
6196            effect = new EffectModule(this, chain, desc, id, sessionId);
6197            lStatus = effect->status();
6198            if (lStatus != NO_ERROR) {
6199                goto Exit;
6200            }
6201            lStatus = chain->addEffect_l(effect);
6202            if (lStatus != NO_ERROR) {
6203                goto Exit;
6204            }
6205            effectCreated = true;
6206
6207            effect->setDevice(mDevice);
6208            effect->setMode(mAudioFlinger->getMode());
6209        }
6210        // create effect handle and connect it to effect module
6211        handle = new EffectHandle(effect, client, effectClient, priority);
6212        lStatus = effect->addHandle(handle);
6213        if (enabled != NULL) {
6214            *enabled = (int)effect->isEnabled();
6215        }
6216    }
6217
6218Exit:
6219    if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
6220        Mutex::Autolock _l(mLock);
6221        if (effectCreated) {
6222            chain->removeEffect_l(effect);
6223        }
6224        if (effectRegistered) {
6225            AudioSystem::unregisterEffect(effect->id());
6226        }
6227        if (chainCreated) {
6228            removeEffectChain_l(chain);
6229        }
6230        handle.clear();
6231    }
6232
6233    if(status) {
6234        *status = lStatus;
6235    }
6236    return handle;
6237}
6238
6239sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6240{
6241    sp<EffectChain> chain = getEffectChain_l(sessionId);
6242    return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
6243}
6244
6245// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6246// PlaybackThread::mLock held
6247status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
6248{
6249    // check for existing effect chain with the requested audio session
6250    int sessionId = effect->sessionId();
6251    sp<EffectChain> chain = getEffectChain_l(sessionId);
6252    bool chainCreated = false;
6253
6254    if (chain == 0) {
6255        // create a new chain for this session
6256        ALOGV("addEffect_l() new effect chain for session %d", sessionId);
6257        chain = new EffectChain(this, sessionId);
6258        addEffectChain_l(chain);
6259        chain->setStrategy(getStrategyForSession_l(sessionId));
6260        chainCreated = true;
6261    }
6262    ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
6263
6264    if (chain->getEffectFromId_l(effect->id()) != 0) {
6265        ALOGW("addEffect_l() %p effect %s already present in chain %p",
6266                this, effect->desc().name, chain.get());
6267        return BAD_VALUE;
6268    }
6269
6270    status_t status = chain->addEffect_l(effect);
6271    if (status != NO_ERROR) {
6272        if (chainCreated) {
6273            removeEffectChain_l(chain);
6274        }
6275        return status;
6276    }
6277
6278    effect->setDevice(mDevice);
6279    effect->setMode(mAudioFlinger->getMode());
6280    return NO_ERROR;
6281}
6282
6283void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
6284
6285    ALOGV("removeEffect_l() %p effect %p", this, effect.get());
6286    effect_descriptor_t desc = effect->desc();
6287    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6288        detachAuxEffect_l(effect->id());
6289    }
6290
6291    sp<EffectChain> chain = effect->chain().promote();
6292    if (chain != 0) {
6293        // remove effect chain if removing last effect
6294        if (chain->removeEffect_l(effect) == 0) {
6295            removeEffectChain_l(chain);
6296        }
6297    } else {
6298        ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
6299    }
6300}
6301
6302void AudioFlinger::ThreadBase::lockEffectChains_l(
6303        Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6304{
6305    effectChains = mEffectChains;
6306    for (size_t i = 0; i < mEffectChains.size(); i++) {
6307        mEffectChains[i]->lock();
6308    }
6309}
6310
6311void AudioFlinger::ThreadBase::unlockEffectChains(
6312        const Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6313{
6314    for (size_t i = 0; i < effectChains.size(); i++) {
6315        effectChains[i]->unlock();
6316    }
6317}
6318
6319sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6320{
6321    Mutex::Autolock _l(mLock);
6322    return getEffectChain_l(sessionId);
6323}
6324
6325sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6326{
6327    size_t size = mEffectChains.size();
6328    for (size_t i = 0; i < size; i++) {
6329        if (mEffectChains[i]->sessionId() == sessionId) {
6330            return mEffectChains[i];
6331        }
6332    }
6333    return 0;
6334}
6335
6336void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
6337{
6338    Mutex::Autolock _l(mLock);
6339    size_t size = mEffectChains.size();
6340    for (size_t i = 0; i < size; i++) {
6341        mEffectChains[i]->setMode_l(mode);
6342    }
6343}
6344
6345void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
6346                                                    const wp<EffectHandle>& handle,
6347                                                    bool unpinIfLast) {
6348
6349    Mutex::Autolock _l(mLock);
6350    ALOGV("disconnectEffect() %p effect %p", this, effect.get());
6351    // delete the effect module if removing last handle on it
6352    if (effect->removeHandle(handle) == 0) {
6353        if (!effect->isPinned() || unpinIfLast) {
6354            removeEffect_l(effect);
6355            AudioSystem::unregisterEffect(effect->id());
6356        }
6357    }
6358}
6359
6360status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6361{
6362    int session = chain->sessionId();
6363    int16_t *buffer = mMixBuffer;
6364    bool ownsBuffer = false;
6365
6366    ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
6367    if (session > 0) {
6368        // Only one effect chain can be present in direct output thread and it uses
6369        // the mix buffer as input
6370        if (mType != DIRECT) {
6371            size_t numSamples = mFrameCount * mChannelCount;
6372            buffer = new int16_t[numSamples];
6373            memset(buffer, 0, numSamples * sizeof(int16_t));
6374            ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
6375            ownsBuffer = true;
6376        }
6377
6378        // Attach all tracks with same session ID to this chain.
6379        for (size_t i = 0; i < mTracks.size(); ++i) {
6380            sp<Track> track = mTracks[i];
6381            if (session == track->sessionId()) {
6382                ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
6383                track->setMainBuffer(buffer);
6384                chain->incTrackCnt();
6385            }
6386        }
6387
6388        // indicate all active tracks in the chain
6389        for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6390            sp<Track> track = mActiveTracks[i].promote();
6391            if (track == 0) continue;
6392            if (session == track->sessionId()) {
6393                ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
6394                chain->incActiveTrackCnt();
6395            }
6396        }
6397    }
6398
6399    chain->setInBuffer(buffer, ownsBuffer);
6400    chain->setOutBuffer(mMixBuffer);
6401    // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
6402    // chains list in order to be processed last as it contains output stage effects
6403    // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6404    // session AUDIO_SESSION_OUTPUT_STAGE to be processed
6405    // after track specific effects and before output stage
6406    // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6407    // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
6408    // Effect chain for other sessions are inserted at beginning of effect
6409    // chains list to be processed before output mix effects. Relative order between other
6410    // sessions is not important
6411    size_t size = mEffectChains.size();
6412    size_t i = 0;
6413    for (i = 0; i < size; i++) {
6414        if (mEffectChains[i]->sessionId() < session) break;
6415    }
6416    mEffectChains.insertAt(chain, i);
6417    checkSuspendOnAddEffectChain_l(chain);
6418
6419    return NO_ERROR;
6420}
6421
6422size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6423{
6424    int session = chain->sessionId();
6425
6426    ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
6427
6428    for (size_t i = 0; i < mEffectChains.size(); i++) {
6429        if (chain == mEffectChains[i]) {
6430            mEffectChains.removeAt(i);
6431            // detach all active tracks from the chain
6432            for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6433                sp<Track> track = mActiveTracks[i].promote();
6434                if (track == 0) continue;
6435                if (session == track->sessionId()) {
6436                    ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
6437                            chain.get(), session);
6438                    chain->decActiveTrackCnt();
6439                }
6440            }
6441
6442            // detach all tracks with same session ID from this chain
6443            for (size_t i = 0; i < mTracks.size(); ++i) {
6444                sp<Track> track = mTracks[i];
6445                if (session == track->sessionId()) {
6446                    track->setMainBuffer(mMixBuffer);
6447                    chain->decTrackCnt();
6448                }
6449            }
6450            break;
6451        }
6452    }
6453    return mEffectChains.size();
6454}
6455
6456status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6457        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
6458{
6459    Mutex::Autolock _l(mLock);
6460    return attachAuxEffect_l(track, EffectId);
6461}
6462
6463status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6464        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
6465{
6466    status_t status = NO_ERROR;
6467
6468    if (EffectId == 0) {
6469        track->setAuxBuffer(0, NULL);
6470    } else {
6471        // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6472        sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
6473        if (effect != 0) {
6474            if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6475                track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6476            } else {
6477                status = INVALID_OPERATION;
6478            }
6479        } else {
6480            status = BAD_VALUE;
6481        }
6482    }
6483    return status;
6484}
6485
6486void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6487{
6488     for (size_t i = 0; i < mTracks.size(); ++i) {
6489        sp<Track> track = mTracks[i];
6490        if (track->auxEffectId() == effectId) {
6491            attachAuxEffect_l(track, 0);
6492        }
6493    }
6494}
6495
6496status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6497{
6498    // only one chain per input thread
6499    if (mEffectChains.size() != 0) {
6500        return INVALID_OPERATION;
6501    }
6502    ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
6503
6504    chain->setInBuffer(NULL);
6505    chain->setOutBuffer(NULL);
6506
6507    checkSuspendOnAddEffectChain_l(chain);
6508
6509    mEffectChains.add(chain);
6510
6511    return NO_ERROR;
6512}
6513
6514size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6515{
6516    ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6517    ALOGW_IF(mEffectChains.size() != 1,
6518            "removeEffectChain_l() %p invalid chain size %d on thread %p",
6519            chain.get(), mEffectChains.size(), this);
6520    if (mEffectChains.size() == 1) {
6521        mEffectChains.removeAt(0);
6522    }
6523    return 0;
6524}
6525
6526// ----------------------------------------------------------------------------
6527//  EffectModule implementation
6528// ----------------------------------------------------------------------------
6529
6530#undef LOG_TAG
6531#define LOG_TAG "AudioFlinger::EffectModule"
6532
6533AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
6534                                        const wp<AudioFlinger::EffectChain>& chain,
6535                                        effect_descriptor_t *desc,
6536                                        int id,
6537                                        int sessionId)
6538    : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
6539      mStatus(NO_INIT), mState(IDLE), mSuspended(false)
6540{
6541    ALOGV("Constructor %p", this);
6542    int lStatus;
6543    if (thread == NULL) {
6544        return;
6545    }
6546
6547    memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6548
6549    // create effect engine from effect factory
6550    mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
6551
6552    if (mStatus != NO_ERROR) {
6553        return;
6554    }
6555    lStatus = init();
6556    if (lStatus < 0) {
6557        mStatus = lStatus;
6558        goto Error;
6559    }
6560
6561    if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6562        mPinned = true;
6563    }
6564    ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
6565    return;
6566Error:
6567    EffectRelease(mEffectInterface);
6568    mEffectInterface = NULL;
6569    ALOGV("Constructor Error %d", mStatus);
6570}
6571
6572AudioFlinger::EffectModule::~EffectModule()
6573{
6574    ALOGV("Destructor %p", this);
6575    if (mEffectInterface != NULL) {
6576        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6577                (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6578            sp<ThreadBase> thread = mThread.promote();
6579            if (thread != 0) {
6580                audio_stream_t *stream = thread->stream();
6581                if (stream != NULL) {
6582                    stream->remove_audio_effect(stream, mEffectInterface);
6583                }
6584            }
6585        }
6586        // release effect engine
6587        EffectRelease(mEffectInterface);
6588    }
6589}
6590
6591status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
6592{
6593    status_t status;
6594
6595    Mutex::Autolock _l(mLock);
6596    int priority = handle->priority();
6597    size_t size = mHandles.size();
6598    sp<EffectHandle> h;
6599    size_t i;
6600    for (i = 0; i < size; i++) {
6601        h = mHandles[i].promote();
6602        if (h == 0) continue;
6603        if (h->priority() <= priority) break;
6604    }
6605    // if inserted in first place, move effect control from previous owner to this handle
6606    if (i == 0) {
6607        bool enabled = false;
6608        if (h != 0) {
6609            enabled = h->enabled();
6610            h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
6611        }
6612        handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
6613        status = NO_ERROR;
6614    } else {
6615        status = ALREADY_EXISTS;
6616    }
6617    ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
6618    mHandles.insertAt(handle, i);
6619    return status;
6620}
6621
6622size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6623{
6624    Mutex::Autolock _l(mLock);
6625    size_t size = mHandles.size();
6626    size_t i;
6627    for (i = 0; i < size; i++) {
6628        if (mHandles[i] == handle) break;
6629    }
6630    if (i == size) {
6631        return size;
6632    }
6633    ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
6634
6635    bool enabled = false;
6636    EffectHandle *hdl = handle.unsafe_get();
6637    if (hdl != NULL) {
6638        ALOGV("removeHandle() unsafe_get OK");
6639        enabled = hdl->enabled();
6640    }
6641    mHandles.removeAt(i);
6642    size = mHandles.size();
6643    // if removed from first place, move effect control from this handle to next in line
6644    if (i == 0 && size != 0) {
6645        sp<EffectHandle> h = mHandles[0].promote();
6646        if (h != 0) {
6647            h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
6648        }
6649    }
6650
6651    // Prevent calls to process() and other functions on effect interface from now on.
6652    // The effect engine will be released by the destructor when the last strong reference on
6653    // this object is released which can happen after next process is called.
6654    if (size == 0 && !mPinned) {
6655        mState = DESTROYED;
6656    }
6657
6658    return size;
6659}
6660
6661sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6662{
6663    Mutex::Autolock _l(mLock);
6664    return mHandles.size() != 0 ? mHandles[0].promote() : 0;
6665}
6666
6667void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
6668{
6669    ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
6670    // keep a strong reference on this EffectModule to avoid calling the
6671    // destructor before we exit
6672    sp<EffectModule> keep(this);
6673    {
6674        sp<ThreadBase> thread = mThread.promote();
6675        if (thread != 0) {
6676            thread->disconnectEffect(keep, handle, unpinIfLast);
6677        }
6678    }
6679}
6680
6681void AudioFlinger::EffectModule::updateState() {
6682    Mutex::Autolock _l(mLock);
6683
6684    switch (mState) {
6685    case RESTART:
6686        reset_l();
6687        // FALL THROUGH
6688
6689    case STARTING:
6690        // clear auxiliary effect input buffer for next accumulation
6691        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6692            memset(mConfig.inputCfg.buffer.raw,
6693                   0,
6694                   mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6695        }
6696        start_l();
6697        mState = ACTIVE;
6698        break;
6699    case STOPPING:
6700        stop_l();
6701        mDisableWaitCnt = mMaxDisableWaitCnt;
6702        mState = STOPPED;
6703        break;
6704    case STOPPED:
6705        // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6706        // turn off sequence.
6707        if (--mDisableWaitCnt == 0) {
6708            reset_l();
6709            mState = IDLE;
6710        }
6711        break;
6712    default: //IDLE , ACTIVE, DESTROYED
6713        break;
6714    }
6715}
6716
6717void AudioFlinger::EffectModule::process()
6718{
6719    Mutex::Autolock _l(mLock);
6720
6721    if (mState == DESTROYED || mEffectInterface == NULL ||
6722            mConfig.inputCfg.buffer.raw == NULL ||
6723            mConfig.outputCfg.buffer.raw == NULL) {
6724        return;
6725    }
6726
6727    if (isProcessEnabled()) {
6728        // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6729        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6730            ditherAndClamp(mConfig.inputCfg.buffer.s32,
6731                                        mConfig.inputCfg.buffer.s32,
6732                                        mConfig.inputCfg.buffer.frameCount/2);
6733        }
6734
6735        // do the actual processing in the effect engine
6736        int ret = (*mEffectInterface)->process(mEffectInterface,
6737                                               &mConfig.inputCfg.buffer,
6738                                               &mConfig.outputCfg.buffer);
6739
6740        // force transition to IDLE state when engine is ready
6741        if (mState == STOPPED && ret == -ENODATA) {
6742            mDisableWaitCnt = 1;
6743        }
6744
6745        // clear auxiliary effect input buffer for next accumulation
6746        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6747            memset(mConfig.inputCfg.buffer.raw, 0,
6748                   mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6749        }
6750    } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
6751                mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6752        // If an insert effect is idle and input buffer is different from output buffer,
6753        // accumulate input onto output
6754        sp<EffectChain> chain = mChain.promote();
6755        if (chain != 0 && chain->activeTrackCnt() != 0) {
6756            size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2;  //always stereo here
6757            int16_t *in = mConfig.inputCfg.buffer.s16;
6758            int16_t *out = mConfig.outputCfg.buffer.s16;
6759            for (size_t i = 0; i < frameCnt; i++) {
6760                out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
6761            }
6762        }
6763    }
6764}
6765
6766void AudioFlinger::EffectModule::reset_l()
6767{
6768    if (mEffectInterface == NULL) {
6769        return;
6770    }
6771    (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6772}
6773
6774status_t AudioFlinger::EffectModule::configure()
6775{
6776    uint32_t channels;
6777    if (mEffectInterface == NULL) {
6778        return NO_INIT;
6779    }
6780
6781    sp<ThreadBase> thread = mThread.promote();
6782    if (thread == 0) {
6783        return DEAD_OBJECT;
6784    }
6785
6786    // TODO: handle configuration of effects replacing track process
6787    if (thread->channelCount() == 1) {
6788        channels = AUDIO_CHANNEL_OUT_MONO;
6789    } else {
6790        channels = AUDIO_CHANNEL_OUT_STEREO;
6791    }
6792
6793    if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6794        mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
6795    } else {
6796        mConfig.inputCfg.channels = channels;
6797    }
6798    mConfig.outputCfg.channels = channels;
6799    mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6800    mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6801    mConfig.inputCfg.samplingRate = thread->sampleRate();
6802    mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6803    mConfig.inputCfg.bufferProvider.cookie = NULL;
6804    mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6805    mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6806    mConfig.outputCfg.bufferProvider.cookie = NULL;
6807    mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6808    mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6809    mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6810    // Insert effect:
6811    // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
6812    // always overwrites output buffer: input buffer == output buffer
6813    // - in other sessions:
6814    //      last effect in the chain accumulates in output buffer: input buffer != output buffer
6815    //      other effect: overwrites output buffer: input buffer == output buffer
6816    // Auxiliary effect:
6817    //      accumulates in output buffer: input buffer != output buffer
6818    // Therefore: accumulate <=> input buffer != output buffer
6819    if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6820        mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6821    } else {
6822        mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6823    }
6824    mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6825    mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6826    mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6827    mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6828
6829    ALOGV("configure() %p thread %p buffer %p framecount %d",
6830            this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6831
6832    status_t cmdStatus;
6833    uint32_t size = sizeof(int);
6834    status_t status = (*mEffectInterface)->command(mEffectInterface,
6835                                                   EFFECT_CMD_SET_CONFIG,
6836                                                   sizeof(effect_config_t),
6837                                                   &mConfig,
6838                                                   &size,
6839                                                   &cmdStatus);
6840    if (status == 0) {
6841        status = cmdStatus;
6842    }
6843
6844    mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6845            (1000 * mConfig.outputCfg.buffer.frameCount);
6846
6847    return status;
6848}
6849
6850status_t AudioFlinger::EffectModule::init()
6851{
6852    Mutex::Autolock _l(mLock);
6853    if (mEffectInterface == NULL) {
6854        return NO_INIT;
6855    }
6856    status_t cmdStatus;
6857    uint32_t size = sizeof(status_t);
6858    status_t status = (*mEffectInterface)->command(mEffectInterface,
6859                                                   EFFECT_CMD_INIT,
6860                                                   0,
6861                                                   NULL,
6862                                                   &size,
6863                                                   &cmdStatus);
6864    if (status == 0) {
6865        status = cmdStatus;
6866    }
6867    return status;
6868}
6869
6870status_t AudioFlinger::EffectModule::start()
6871{
6872    Mutex::Autolock _l(mLock);
6873    return start_l();
6874}
6875
6876status_t AudioFlinger::EffectModule::start_l()
6877{
6878    if (mEffectInterface == NULL) {
6879        return NO_INIT;
6880    }
6881    status_t cmdStatus;
6882    uint32_t size = sizeof(status_t);
6883    status_t status = (*mEffectInterface)->command(mEffectInterface,
6884                                                   EFFECT_CMD_ENABLE,
6885                                                   0,
6886                                                   NULL,
6887                                                   &size,
6888                                                   &cmdStatus);
6889    if (status == 0) {
6890        status = cmdStatus;
6891    }
6892    if (status == 0 &&
6893            ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6894             (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6895        sp<ThreadBase> thread = mThread.promote();
6896        if (thread != 0) {
6897            audio_stream_t *stream = thread->stream();
6898            if (stream != NULL) {
6899                stream->add_audio_effect(stream, mEffectInterface);
6900            }
6901        }
6902    }
6903    return status;
6904}
6905
6906status_t AudioFlinger::EffectModule::stop()
6907{
6908    Mutex::Autolock _l(mLock);
6909    return stop_l();
6910}
6911
6912status_t AudioFlinger::EffectModule::stop_l()
6913{
6914    if (mEffectInterface == NULL) {
6915        return NO_INIT;
6916    }
6917    status_t cmdStatus;
6918    uint32_t size = sizeof(status_t);
6919    status_t status = (*mEffectInterface)->command(mEffectInterface,
6920                                                   EFFECT_CMD_DISABLE,
6921                                                   0,
6922                                                   NULL,
6923                                                   &size,
6924                                                   &cmdStatus);
6925    if (status == 0) {
6926        status = cmdStatus;
6927    }
6928    if (status == 0 &&
6929            ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6930             (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6931        sp<ThreadBase> thread = mThread.promote();
6932        if (thread != 0) {
6933            audio_stream_t *stream = thread->stream();
6934            if (stream != NULL) {
6935                stream->remove_audio_effect(stream, mEffectInterface);
6936            }
6937        }
6938    }
6939    return status;
6940}
6941
6942status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6943                                             uint32_t cmdSize,
6944                                             void *pCmdData,
6945                                             uint32_t *replySize,
6946                                             void *pReplyData)
6947{
6948    Mutex::Autolock _l(mLock);
6949//    ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
6950
6951    if (mState == DESTROYED || mEffectInterface == NULL) {
6952        return NO_INIT;
6953    }
6954    status_t status = (*mEffectInterface)->command(mEffectInterface,
6955                                                   cmdCode,
6956                                                   cmdSize,
6957                                                   pCmdData,
6958                                                   replySize,
6959                                                   pReplyData);
6960    if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
6961        uint32_t size = (replySize == NULL) ? 0 : *replySize;
6962        for (size_t i = 1; i < mHandles.size(); i++) {
6963            sp<EffectHandle> h = mHandles[i].promote();
6964            if (h != 0) {
6965                h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6966            }
6967        }
6968    }
6969    return status;
6970}
6971
6972status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6973{
6974
6975    Mutex::Autolock _l(mLock);
6976    ALOGV("setEnabled %p enabled %d", this, enabled);
6977
6978    if (enabled != isEnabled()) {
6979        status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6980        if (enabled && status != NO_ERROR) {
6981            return status;
6982        }
6983
6984        switch (mState) {
6985        // going from disabled to enabled
6986        case IDLE:
6987            mState = STARTING;
6988            break;
6989        case STOPPED:
6990            mState = RESTART;
6991            break;
6992        case STOPPING:
6993            mState = ACTIVE;
6994            break;
6995
6996        // going from enabled to disabled
6997        case RESTART:
6998            mState = STOPPED;
6999            break;
7000        case STARTING:
7001            mState = IDLE;
7002            break;
7003        case ACTIVE:
7004            mState = STOPPING;
7005            break;
7006        case DESTROYED:
7007            return NO_ERROR; // simply ignore as we are being destroyed
7008        }
7009        for (size_t i = 1; i < mHandles.size(); i++) {
7010            sp<EffectHandle> h = mHandles[i].promote();
7011            if (h != 0) {
7012                h->setEnabled(enabled);
7013            }
7014        }
7015    }
7016    return NO_ERROR;
7017}
7018
7019bool AudioFlinger::EffectModule::isEnabled() const
7020{
7021    switch (mState) {
7022    case RESTART:
7023    case STARTING:
7024    case ACTIVE:
7025        return true;
7026    case IDLE:
7027    case STOPPING:
7028    case STOPPED:
7029    case DESTROYED:
7030    default:
7031        return false;
7032    }
7033}
7034
7035bool AudioFlinger::EffectModule::isProcessEnabled() const
7036{
7037    switch (mState) {
7038    case RESTART:
7039    case ACTIVE:
7040    case STOPPING:
7041    case STOPPED:
7042        return true;
7043    case IDLE:
7044    case STARTING:
7045    case DESTROYED:
7046    default:
7047        return false;
7048    }
7049}
7050
7051status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7052{
7053    Mutex::Autolock _l(mLock);
7054    status_t status = NO_ERROR;
7055
7056    // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7057    // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
7058    if (isProcessEnabled() &&
7059            ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7060            (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
7061        status_t cmdStatus;
7062        uint32_t volume[2];
7063        uint32_t *pVolume = NULL;
7064        uint32_t size = sizeof(volume);
7065        volume[0] = *left;
7066        volume[1] = *right;
7067        if (controller) {
7068            pVolume = volume;
7069        }
7070        status = (*mEffectInterface)->command(mEffectInterface,
7071                                              EFFECT_CMD_SET_VOLUME,
7072                                              size,
7073                                              volume,
7074                                              &size,
7075                                              pVolume);
7076        if (controller && status == NO_ERROR && size == sizeof(volume)) {
7077            *left = volume[0];
7078            *right = volume[1];
7079        }
7080    }
7081    return status;
7082}
7083
7084status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7085{
7086    Mutex::Autolock _l(mLock);
7087    status_t status = NO_ERROR;
7088    if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7089        // audio pre processing modules on RecordThread can receive both output and
7090        // input device indication in the same call
7091        uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7092        if (dev) {
7093            status_t cmdStatus;
7094            uint32_t size = sizeof(status_t);
7095
7096            status = (*mEffectInterface)->command(mEffectInterface,
7097                                                  EFFECT_CMD_SET_DEVICE,
7098                                                  sizeof(uint32_t),
7099                                                  &dev,
7100                                                  &size,
7101                                                  &cmdStatus);
7102            if (status == NO_ERROR) {
7103                status = cmdStatus;
7104            }
7105        }
7106        dev = device & AUDIO_DEVICE_IN_ALL;
7107        if (dev) {
7108            status_t cmdStatus;
7109            uint32_t size = sizeof(status_t);
7110
7111            status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7112                                                  EFFECT_CMD_SET_INPUT_DEVICE,
7113                                                  sizeof(uint32_t),
7114                                                  &dev,
7115                                                  &size,
7116                                                  &cmdStatus);
7117            if (status2 == NO_ERROR) {
7118                status2 = cmdStatus;
7119            }
7120            if (status == NO_ERROR) {
7121                status = status2;
7122            }
7123        }
7124    }
7125    return status;
7126}
7127
7128status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
7129{
7130    Mutex::Autolock _l(mLock);
7131    status_t status = NO_ERROR;
7132    if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
7133        status_t cmdStatus;
7134        uint32_t size = sizeof(status_t);
7135        status = (*mEffectInterface)->command(mEffectInterface,
7136                                              EFFECT_CMD_SET_AUDIO_MODE,
7137                                              sizeof(audio_mode_t),
7138                                              &mode,
7139                                              &size,
7140                                              &cmdStatus);
7141        if (status == NO_ERROR) {
7142            status = cmdStatus;
7143        }
7144    }
7145    return status;
7146}
7147
7148void AudioFlinger::EffectModule::setSuspended(bool suspended)
7149{
7150    Mutex::Autolock _l(mLock);
7151    mSuspended = suspended;
7152}
7153
7154bool AudioFlinger::EffectModule::suspended() const
7155{
7156    Mutex::Autolock _l(mLock);
7157    return mSuspended;
7158}
7159
7160status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7161{
7162    const size_t SIZE = 256;
7163    char buffer[SIZE];
7164    String8 result;
7165
7166    snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7167    result.append(buffer);
7168
7169    bool locked = tryLock(mLock);
7170    // failed to lock - AudioFlinger is probably deadlocked
7171    if (!locked) {
7172        result.append("\t\tCould not lock Fx mutex:\n");
7173    }
7174
7175    result.append("\t\tSession Status State Engine:\n");
7176    snprintf(buffer, SIZE, "\t\t%05d   %03d    %03d   0x%08x\n",
7177            mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7178    result.append(buffer);
7179
7180    result.append("\t\tDescriptor:\n");
7181    snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7182            mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7183            mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7184            mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7185    result.append(buffer);
7186    snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7187                mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7188                mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7189                mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7190    result.append(buffer);
7191    snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
7192            mDescriptor.apiVersion,
7193            mDescriptor.flags);
7194    result.append(buffer);
7195    snprintf(buffer, SIZE, "\t\t- name: %s\n",
7196            mDescriptor.name);
7197    result.append(buffer);
7198    snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7199            mDescriptor.implementor);
7200    result.append(buffer);
7201
7202    result.append("\t\t- Input configuration:\n");
7203    result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
7204    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
7205            (uint32_t)mConfig.inputCfg.buffer.raw,
7206            mConfig.inputCfg.buffer.frameCount,
7207            mConfig.inputCfg.samplingRate,
7208            mConfig.inputCfg.channels,
7209            mConfig.inputCfg.format);
7210    result.append(buffer);
7211
7212    result.append("\t\t- Output configuration:\n");
7213    result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
7214    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
7215            (uint32_t)mConfig.outputCfg.buffer.raw,
7216            mConfig.outputCfg.buffer.frameCount,
7217            mConfig.outputCfg.samplingRate,
7218            mConfig.outputCfg.channels,
7219            mConfig.outputCfg.format);
7220    result.append(buffer);
7221
7222    snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7223    result.append(buffer);
7224    result.append("\t\t\tPid   Priority Ctrl Locked client server\n");
7225    for (size_t i = 0; i < mHandles.size(); ++i) {
7226        sp<EffectHandle> handle = mHandles[i].promote();
7227        if (handle != 0) {
7228            handle->dump(buffer, SIZE);
7229            result.append(buffer);
7230        }
7231    }
7232
7233    result.append("\n");
7234
7235    write(fd, result.string(), result.length());
7236
7237    if (locked) {
7238        mLock.unlock();
7239    }
7240
7241    return NO_ERROR;
7242}
7243
7244// ----------------------------------------------------------------------------
7245//  EffectHandle implementation
7246// ----------------------------------------------------------------------------
7247
7248#undef LOG_TAG
7249#define LOG_TAG "AudioFlinger::EffectHandle"
7250
7251AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7252                                        const sp<AudioFlinger::Client>& client,
7253                                        const sp<IEffectClient>& effectClient,
7254                                        int32_t priority)
7255    : BnEffect(),
7256    mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
7257    mPriority(priority), mHasControl(false), mEnabled(false)
7258{
7259    ALOGV("constructor %p", this);
7260
7261    if (client == 0) {
7262        return;
7263    }
7264    int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7265    mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7266    if (mCblkMemory != 0) {
7267        mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7268
7269        if (mCblk != NULL) {
7270            new(mCblk) effect_param_cblk_t();
7271            mBuffer = (uint8_t *)mCblk + bufOffset;
7272         }
7273    } else {
7274        ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
7275        return;
7276    }
7277}
7278
7279AudioFlinger::EffectHandle::~EffectHandle()
7280{
7281    ALOGV("Destructor %p", this);
7282    disconnect(false);
7283    ALOGV("Destructor DONE %p", this);
7284}
7285
7286status_t AudioFlinger::EffectHandle::enable()
7287{
7288    ALOGV("enable %p", this);
7289    if (!mHasControl) return INVALID_OPERATION;
7290    if (mEffect == 0) return DEAD_OBJECT;
7291
7292    if (mEnabled) {
7293        return NO_ERROR;
7294    }
7295
7296    mEnabled = true;
7297
7298    sp<ThreadBase> thread = mEffect->thread().promote();
7299    if (thread != 0) {
7300        thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7301    }
7302
7303    // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7304    if (mEffect->suspended()) {
7305        return NO_ERROR;
7306    }
7307
7308    status_t status = mEffect->setEnabled(true);
7309    if (status != NO_ERROR) {
7310        if (thread != 0) {
7311            thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7312        }
7313        mEnabled = false;
7314    }
7315    return status;
7316}
7317
7318status_t AudioFlinger::EffectHandle::disable()
7319{
7320    ALOGV("disable %p", this);
7321    if (!mHasControl) return INVALID_OPERATION;
7322    if (mEffect == 0) return DEAD_OBJECT;
7323
7324    if (!mEnabled) {
7325        return NO_ERROR;
7326    }
7327    mEnabled = false;
7328
7329    if (mEffect->suspended()) {
7330        return NO_ERROR;
7331    }
7332
7333    status_t status = mEffect->setEnabled(false);
7334
7335    sp<ThreadBase> thread = mEffect->thread().promote();
7336    if (thread != 0) {
7337        thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7338    }
7339
7340    return status;
7341}
7342
7343void AudioFlinger::EffectHandle::disconnect()
7344{
7345    disconnect(true);
7346}
7347
7348void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
7349{
7350    ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
7351    if (mEffect == 0) {
7352        return;
7353    }
7354    mEffect->disconnect(this, unpinIfLast);
7355
7356    if (mHasControl && mEnabled) {
7357        sp<ThreadBase> thread = mEffect->thread().promote();
7358        if (thread != 0) {
7359            thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7360        }
7361    }
7362
7363    // release sp on module => module destructor can be called now
7364    mEffect.clear();
7365    if (mClient != 0) {
7366        if (mCblk != NULL) {
7367            // unlike ~TrackBase(), mCblk is never a local new, so don't delete
7368            mCblk->~effect_param_cblk_t();   // destroy our shared-structure.
7369        }
7370        mCblkMemory.clear();    // free the shared memory before releasing the heap it belongs to
7371        // Client destructor must run with AudioFlinger mutex locked
7372        Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7373        mClient.clear();
7374    }
7375}
7376
7377status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7378                                             uint32_t cmdSize,
7379                                             void *pCmdData,
7380                                             uint32_t *replySize,
7381                                             void *pReplyData)
7382{
7383//    ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
7384//              cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
7385
7386    // only get parameter command is permitted for applications not controlling the effect
7387    if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7388        return INVALID_OPERATION;
7389    }
7390    if (mEffect == 0) return DEAD_OBJECT;
7391    if (mClient == 0) return INVALID_OPERATION;
7392
7393    // handle commands that are not forwarded transparently to effect engine
7394    if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7395        // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7396        // no risk to block the whole media server process or mixer threads is we are stuck here
7397        Mutex::Autolock _l(mCblk->lock);
7398        if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7399            mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7400            mCblk->serverIndex = 0;
7401            mCblk->clientIndex = 0;
7402            return BAD_VALUE;
7403        }
7404        status_t status = NO_ERROR;
7405        while (mCblk->serverIndex < mCblk->clientIndex) {
7406            int reply;
7407            uint32_t rsize = sizeof(int);
7408            int *p = (int *)(mBuffer + mCblk->serverIndex);
7409            int size = *p++;
7410            if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
7411                ALOGW("command(): invalid parameter block size");
7412                break;
7413            }
7414            effect_param_t *param = (effect_param_t *)p;
7415            if (param->psize == 0 || param->vsize == 0) {
7416                ALOGW("command(): null parameter or value size");
7417                mCblk->serverIndex += size;
7418                continue;
7419            }
7420            uint32_t psize = sizeof(effect_param_t) +
7421                             ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7422                             param->vsize;
7423            status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7424                                            psize,
7425                                            p,
7426                                            &rsize,
7427                                            &reply);
7428            // stop at first error encountered
7429            if (ret != NO_ERROR) {
7430                status = ret;
7431                *(int *)pReplyData = reply;
7432                break;
7433            } else if (reply != NO_ERROR) {
7434                *(int *)pReplyData = reply;
7435                break;
7436            }
7437            mCblk->serverIndex += size;
7438        }
7439        mCblk->serverIndex = 0;
7440        mCblk->clientIndex = 0;
7441        return status;
7442    } else if (cmdCode == EFFECT_CMD_ENABLE) {
7443        *(int *)pReplyData = NO_ERROR;
7444        return enable();
7445    } else if (cmdCode == EFFECT_CMD_DISABLE) {
7446        *(int *)pReplyData = NO_ERROR;
7447        return disable();
7448    }
7449
7450    return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7451}
7452
7453void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
7454{
7455    ALOGV("setControl %p control %d", this, hasControl);
7456
7457    mHasControl = hasControl;
7458    mEnabled = enabled;
7459
7460    if (signal && mEffectClient != 0) {
7461        mEffectClient->controlStatusChanged(hasControl);
7462    }
7463}
7464
7465void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7466                                                 uint32_t cmdSize,
7467                                                 void *pCmdData,
7468                                                 uint32_t replySize,
7469                                                 void *pReplyData)
7470{
7471    if (mEffectClient != 0) {
7472        mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7473    }
7474}
7475
7476
7477
7478void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7479{
7480    if (mEffectClient != 0) {
7481        mEffectClient->enableStatusChanged(enabled);
7482    }
7483}
7484
7485status_t AudioFlinger::EffectHandle::onTransact(
7486    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7487{
7488    return BnEffect::onTransact(code, data, reply, flags);
7489}
7490
7491
7492void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7493{
7494    bool locked = mCblk != NULL && tryLock(mCblk->lock);
7495
7496    snprintf(buffer, size, "\t\t\t%05d %05d    %01u    %01u      %05u  %05u\n",
7497            (mClient == 0) ? getpid_cached : mClient->pid(),
7498            mPriority,
7499            mHasControl,
7500            !locked,
7501            mCblk ? mCblk->clientIndex : 0,
7502            mCblk ? mCblk->serverIndex : 0
7503            );
7504
7505    if (locked) {
7506        mCblk->lock.unlock();
7507    }
7508}
7509
7510#undef LOG_TAG
7511#define LOG_TAG "AudioFlinger::EffectChain"
7512
7513AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
7514                                        int sessionId)
7515    : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
7516      mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7517      mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
7518{
7519    mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
7520    if (thread == NULL) {
7521        return;
7522    }
7523    mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7524                                    thread->frameCount();
7525}
7526
7527AudioFlinger::EffectChain::~EffectChain()
7528{
7529    if (mOwnInBuffer) {
7530        delete mInBuffer;
7531    }
7532
7533}
7534
7535// getEffectFromDesc_l() must be called with ThreadBase::mLock held
7536sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
7537{
7538    size_t size = mEffects.size();
7539
7540    for (size_t i = 0; i < size; i++) {
7541        if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7542            return mEffects[i];
7543        }
7544    }
7545    return 0;
7546}
7547
7548// getEffectFromId_l() must be called with ThreadBase::mLock held
7549sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
7550{
7551    size_t size = mEffects.size();
7552
7553    for (size_t i = 0; i < size; i++) {
7554        // by convention, return first effect if id provided is 0 (0 is never a valid id)
7555        if (id == 0 || mEffects[i]->id() == id) {
7556            return mEffects[i];
7557        }
7558    }
7559    return 0;
7560}
7561
7562// getEffectFromType_l() must be called with ThreadBase::mLock held
7563sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7564        const effect_uuid_t *type)
7565{
7566    size_t size = mEffects.size();
7567
7568    for (size_t i = 0; i < size; i++) {
7569        if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7570            return mEffects[i];
7571        }
7572    }
7573    return 0;
7574}
7575
7576// Must be called with EffectChain::mLock locked
7577void AudioFlinger::EffectChain::process_l()
7578{
7579    sp<ThreadBase> thread = mThread.promote();
7580    if (thread == 0) {
7581        ALOGW("process_l(): cannot promote mixer thread");
7582        return;
7583    }
7584    bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7585            (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
7586    // always process effects unless no more tracks are on the session and the effect tail
7587    // has been rendered
7588    bool doProcess = true;
7589    if (!isGlobalSession) {
7590        bool tracksOnSession = (trackCnt() != 0);
7591
7592        if (!tracksOnSession && mTailBufferCount == 0) {
7593            doProcess = false;
7594        }
7595
7596        if (activeTrackCnt() == 0) {
7597            // if no track is active and the effect tail has not been rendered,
7598            // the input buffer must be cleared here as the mixer process will not do it
7599            if (tracksOnSession || mTailBufferCount > 0) {
7600                size_t numSamples = thread->frameCount() * thread->channelCount();
7601                memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7602                if (mTailBufferCount > 0) {
7603                    mTailBufferCount--;
7604                }
7605            }
7606        }
7607    }
7608
7609    size_t size = mEffects.size();
7610    if (doProcess) {
7611        for (size_t i = 0; i < size; i++) {
7612            mEffects[i]->process();
7613        }
7614    }
7615    for (size_t i = 0; i < size; i++) {
7616        mEffects[i]->updateState();
7617    }
7618}
7619
7620// addEffect_l() must be called with PlaybackThread::mLock held
7621status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
7622{
7623    effect_descriptor_t desc = effect->desc();
7624    uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7625
7626    Mutex::Autolock _l(mLock);
7627    effect->setChain(this);
7628    sp<ThreadBase> thread = mThread.promote();
7629    if (thread == 0) {
7630        return NO_INIT;
7631    }
7632    effect->setThread(thread);
7633
7634    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7635        // Auxiliary effects are inserted at the beginning of mEffects vector as
7636        // they are processed first and accumulated in chain input buffer
7637        mEffects.insertAt(effect, 0);
7638
7639        // the input buffer for auxiliary effect contains mono samples in
7640        // 32 bit format. This is to avoid saturation in AudoMixer
7641        // accumulation stage. Saturation is done in EffectModule::process() before
7642        // calling the process in effect engine
7643        size_t numSamples = thread->frameCount();
7644        int32_t *buffer = new int32_t[numSamples];
7645        memset(buffer, 0, numSamples * sizeof(int32_t));
7646        effect->setInBuffer((int16_t *)buffer);
7647        // auxiliary effects output samples to chain input buffer for further processing
7648        // by insert effects
7649        effect->setOutBuffer(mInBuffer);
7650    } else {
7651        // Insert effects are inserted at the end of mEffects vector as they are processed
7652        //  after track and auxiliary effects.
7653        // Insert effect order as a function of indicated preference:
7654        //  if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7655        //  another effect is present
7656        //  else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7657        //  last effect claiming first position
7658        //  else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7659        //  first effect claiming last position
7660        //  else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7661        // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7662        // already present
7663
7664        size_t size = mEffects.size();
7665        size_t idx_insert = size;
7666        ssize_t idx_insert_first = -1;
7667        ssize_t idx_insert_last = -1;
7668
7669        for (size_t i = 0; i < size; i++) {
7670            effect_descriptor_t d = mEffects[i]->desc();
7671            uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7672            uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7673            if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7674                // check invalid effect chaining combinations
7675                if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7676                    iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
7677                    ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
7678                    return INVALID_OPERATION;
7679                }
7680                // remember position of first insert effect and by default
7681                // select this as insert position for new effect
7682                if (idx_insert == size) {
7683                    idx_insert = i;
7684                }
7685                // remember position of last insert effect claiming
7686                // first position
7687                if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7688                    idx_insert_first = i;
7689                }
7690                // remember position of first insert effect claiming
7691                // last position
7692                if (iPref == EFFECT_FLAG_INSERT_LAST &&
7693                    idx_insert_last == -1) {
7694                    idx_insert_last = i;
7695                }
7696            }
7697        }
7698
7699        // modify idx_insert from first position if needed
7700        if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7701            if (idx_insert_last != -1) {
7702                idx_insert = idx_insert_last;
7703            } else {
7704                idx_insert = size;
7705            }
7706        } else {
7707            if (idx_insert_first != -1) {
7708                idx_insert = idx_insert_first + 1;
7709            }
7710        }
7711
7712        // always read samples from chain input buffer
7713        effect->setInBuffer(mInBuffer);
7714
7715        // if last effect in the chain, output samples to chain
7716        // output buffer, otherwise to chain input buffer
7717        if (idx_insert == size) {
7718            if (idx_insert != 0) {
7719                mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7720                mEffects[idx_insert-1]->configure();
7721            }
7722            effect->setOutBuffer(mOutBuffer);
7723        } else {
7724            effect->setOutBuffer(mInBuffer);
7725        }
7726        mEffects.insertAt(effect, idx_insert);
7727
7728        ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
7729    }
7730    effect->configure();
7731    return NO_ERROR;
7732}
7733
7734// removeEffect_l() must be called with PlaybackThread::mLock held
7735size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
7736{
7737    Mutex::Autolock _l(mLock);
7738    size_t size = mEffects.size();
7739    uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7740
7741    for (size_t i = 0; i < size; i++) {
7742        if (effect == mEffects[i]) {
7743            // calling stop here will remove pre-processing effect from the audio HAL.
7744            // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7745            // the middle of a read from audio HAL
7746            if (mEffects[i]->state() == EffectModule::ACTIVE ||
7747                    mEffects[i]->state() == EffectModule::STOPPING) {
7748                mEffects[i]->stop();
7749            }
7750            if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7751                delete[] effect->inBuffer();
7752            } else {
7753                if (i == size - 1 && i != 0) {
7754                    mEffects[i - 1]->setOutBuffer(mOutBuffer);
7755                    mEffects[i - 1]->configure();
7756                }
7757            }
7758            mEffects.removeAt(i);
7759            ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
7760            break;
7761        }
7762    }
7763
7764    return mEffects.size();
7765}
7766
7767// setDevice_l() must be called with PlaybackThread::mLock held
7768void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
7769{
7770    size_t size = mEffects.size();
7771    for (size_t i = 0; i < size; i++) {
7772        mEffects[i]->setDevice(device);
7773    }
7774}
7775
7776// setMode_l() must be called with PlaybackThread::mLock held
7777void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
7778{
7779    size_t size = mEffects.size();
7780    for (size_t i = 0; i < size; i++) {
7781        mEffects[i]->setMode(mode);
7782    }
7783}
7784
7785// setVolume_l() must be called with PlaybackThread::mLock held
7786bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
7787{
7788    uint32_t newLeft = *left;
7789    uint32_t newRight = *right;
7790    bool hasControl = false;
7791    int ctrlIdx = -1;
7792    size_t size = mEffects.size();
7793
7794    // first update volume controller
7795    for (size_t i = size; i > 0; i--) {
7796        if (mEffects[i - 1]->isProcessEnabled() &&
7797            (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7798            ctrlIdx = i - 1;
7799            hasControl = true;
7800            break;
7801        }
7802    }
7803
7804    if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
7805        if (hasControl) {
7806            *left = mNewLeftVolume;
7807            *right = mNewRightVolume;
7808        }
7809        return hasControl;
7810    }
7811
7812    mVolumeCtrlIdx = ctrlIdx;
7813    mLeftVolume = newLeft;
7814    mRightVolume = newRight;
7815
7816    // second get volume update from volume controller
7817    if (ctrlIdx >= 0) {
7818        mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
7819        mNewLeftVolume = newLeft;
7820        mNewRightVolume = newRight;
7821    }
7822    // then indicate volume to all other effects in chain.
7823    // Pass altered volume to effects before volume controller
7824    // and requested volume to effects after controller
7825    uint32_t lVol = newLeft;
7826    uint32_t rVol = newRight;
7827
7828    for (size_t i = 0; i < size; i++) {
7829        if ((int)i == ctrlIdx) continue;
7830        // this also works for ctrlIdx == -1 when there is no volume controller
7831        if ((int)i > ctrlIdx) {
7832            lVol = *left;
7833            rVol = *right;
7834        }
7835        mEffects[i]->setVolume(&lVol, &rVol, false);
7836    }
7837    *left = newLeft;
7838    *right = newRight;
7839
7840    return hasControl;
7841}
7842
7843status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7844{
7845    const size_t SIZE = 256;
7846    char buffer[SIZE];
7847    String8 result;
7848
7849    snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7850    result.append(buffer);
7851
7852    bool locked = tryLock(mLock);
7853    // failed to lock - AudioFlinger is probably deadlocked
7854    if (!locked) {
7855        result.append("\tCould not lock mutex:\n");
7856    }
7857
7858    result.append("\tNum fx In buffer   Out buffer   Active tracks:\n");
7859    snprintf(buffer, SIZE, "\t%02d     0x%08x  0x%08x   %d\n",
7860            mEffects.size(),
7861            (uint32_t)mInBuffer,
7862            (uint32_t)mOutBuffer,
7863            mActiveTrackCnt);
7864    result.append(buffer);
7865    write(fd, result.string(), result.size());
7866
7867    for (size_t i = 0; i < mEffects.size(); ++i) {
7868        sp<EffectModule> effect = mEffects[i];
7869        if (effect != 0) {
7870            effect->dump(fd, args);
7871        }
7872    }
7873
7874    if (locked) {
7875        mLock.unlock();
7876    }
7877
7878    return NO_ERROR;
7879}
7880
7881// must be called with ThreadBase::mLock held
7882void AudioFlinger::EffectChain::setEffectSuspended_l(
7883        const effect_uuid_t *type, bool suspend)
7884{
7885    sp<SuspendedEffectDesc> desc;
7886    // use effect type UUID timelow as key as there is no real risk of identical
7887    // timeLow fields among effect type UUIDs.
7888    ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
7889    if (suspend) {
7890        if (index >= 0) {
7891            desc = mSuspendedEffects.valueAt(index);
7892        } else {
7893            desc = new SuspendedEffectDesc();
7894            memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7895            mSuspendedEffects.add(type->timeLow, desc);
7896            ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
7897        }
7898        if (desc->mRefCount++ == 0) {
7899            sp<EffectModule> effect = getEffectIfEnabled(type);
7900            if (effect != 0) {
7901                desc->mEffect = effect;
7902                effect->setSuspended(true);
7903                effect->setEnabled(false);
7904            }
7905        }
7906    } else {
7907        if (index < 0) {
7908            return;
7909        }
7910        desc = mSuspendedEffects.valueAt(index);
7911        if (desc->mRefCount <= 0) {
7912            ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7913            desc->mRefCount = 1;
7914        }
7915        if (--desc->mRefCount == 0) {
7916            ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7917            if (desc->mEffect != 0) {
7918                sp<EffectModule> effect = desc->mEffect.promote();
7919                if (effect != 0) {
7920                    effect->setSuspended(false);
7921                    sp<EffectHandle> handle = effect->controlHandle();
7922                    if (handle != 0) {
7923                        effect->setEnabled(handle->enabled());
7924                    }
7925                }
7926                desc->mEffect.clear();
7927            }
7928            mSuspendedEffects.removeItemsAt(index);
7929        }
7930    }
7931}
7932
7933// must be called with ThreadBase::mLock held
7934void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7935{
7936    sp<SuspendedEffectDesc> desc;
7937
7938    ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7939    if (suspend) {
7940        if (index >= 0) {
7941            desc = mSuspendedEffects.valueAt(index);
7942        } else {
7943            desc = new SuspendedEffectDesc();
7944            mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
7945            ALOGV("setEffectSuspendedAll_l() add entry for 0");
7946        }
7947        if (desc->mRefCount++ == 0) {
7948            Vector< sp<EffectModule> > effects;
7949            getSuspendEligibleEffects(effects);
7950            for (size_t i = 0; i < effects.size(); i++) {
7951                setEffectSuspended_l(&effects[i]->desc().type, true);
7952            }
7953        }
7954    } else {
7955        if (index < 0) {
7956            return;
7957        }
7958        desc = mSuspendedEffects.valueAt(index);
7959        if (desc->mRefCount <= 0) {
7960            ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7961            desc->mRefCount = 1;
7962        }
7963        if (--desc->mRefCount == 0) {
7964            Vector<const effect_uuid_t *> types;
7965            for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7966                if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7967                    continue;
7968                }
7969                types.add(&mSuspendedEffects.valueAt(i)->mType);
7970            }
7971            for (size_t i = 0; i < types.size(); i++) {
7972                setEffectSuspended_l(types[i], false);
7973            }
7974            ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7975            mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7976        }
7977    }
7978}
7979
7980
7981// The volume effect is used for automated tests only
7982#ifndef OPENSL_ES_H_
7983static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7984                                            { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7985const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7986#endif //OPENSL_ES_H_
7987
7988bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7989{
7990    // auxiliary effects and visualizer are never suspended on output mix
7991    if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7992        (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
7993         (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7994         (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
7995        return false;
7996    }
7997    return true;
7998}
7999
8000void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
8001{
8002    effects.clear();
8003    for (size_t i = 0; i < mEffects.size(); i++) {
8004        if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8005            effects.add(mEffects[i]);
8006        }
8007    }
8008}
8009
8010sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8011                                                            const effect_uuid_t *type)
8012{
8013    sp<EffectModule> effect = getEffectFromType_l(type);
8014    return effect != 0 && effect->isEnabled() ? effect : 0;
8015}
8016
8017void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8018                                                            bool enabled)
8019{
8020    ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
8021    if (enabled) {
8022        if (index < 0) {
8023            // if the effect is not suspend check if all effects are suspended
8024            index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8025            if (index < 0) {
8026                return;
8027            }
8028            if (!isEffectEligibleForSuspend(effect->desc())) {
8029                return;
8030            }
8031            setEffectSuspended_l(&effect->desc().type, enabled);
8032            index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
8033            if (index < 0) {
8034                ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
8035                return;
8036            }
8037        }
8038        ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
8039             effect->desc().type.timeLow);
8040        sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8041        // if effect is requested to suspended but was not yet enabled, supend it now.
8042        if (desc->mEffect == 0) {
8043            desc->mEffect = effect;
8044            effect->setEnabled(false);
8045            effect->setSuspended(true);
8046        }
8047    } else {
8048        if (index < 0) {
8049            return;
8050        }
8051        ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
8052             effect->desc().type.timeLow);
8053        sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8054        desc->mEffect.clear();
8055        effect->setSuspended(false);
8056    }
8057}
8058
8059#undef LOG_TAG
8060#define LOG_TAG "AudioFlinger"
8061
8062// ----------------------------------------------------------------------------
8063
8064status_t AudioFlinger::onTransact(
8065        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8066{
8067    return BnAudioFlinger::onTransact(code, data, reply, flags);
8068}
8069
8070}; // namespace android
8071