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