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