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