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