AudioFlinger.cpp revision 9fbdee13d09447550dd22ae72c2dbabdce7f0a80
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      mQueueHeadInFlight(false),
3900      mTrimQueueHeadOnRelease(false),
3901      mTimedSilenceBuffer(NULL),
3902      mTimedSilenceBufferSize(0),
3903      mTimedAudioOutputOnTime(false),
3904      mMediaTimeTransformValid(false)
3905{
3906    LocalClock lc;
3907    mLocalTimeFreq = lc.getLocalFreq();
3908
3909    mLocalTimeToSampleTransform.a_zero = 0;
3910    mLocalTimeToSampleTransform.b_zero = 0;
3911    mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3912    mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3913    LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3914                            &mLocalTimeToSampleTransform.a_to_b_denom);
3915
3916    mMediaTimeToSampleTransform.a_zero = 0;
3917    mMediaTimeToSampleTransform.b_zero = 0;
3918    mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
3919    mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
3920    LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
3921                            &mMediaTimeToSampleTransform.a_to_b_denom);
3922}
3923
3924AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3925    mClient->releaseTimedTrack();
3926    delete [] mTimedSilenceBuffer;
3927}
3928
3929status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3930    size_t size, sp<IMemory>* buffer) {
3931
3932    Mutex::Autolock _l(mTimedBufferQueueLock);
3933
3934    trimTimedBufferQueue_l();
3935
3936    // lazily initialize the shared memory heap for timed buffers
3937    if (mTimedMemoryDealer == NULL) {
3938        const int kTimedBufferHeapSize = 512 << 10;
3939
3940        mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3941                                              "AudioFlingerTimed");
3942        if (mTimedMemoryDealer == NULL)
3943            return NO_MEMORY;
3944    }
3945
3946    sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3947    if (newBuffer == NULL) {
3948        newBuffer = mTimedMemoryDealer->allocate(size);
3949        if (newBuffer == NULL)
3950            return NO_MEMORY;
3951    }
3952
3953    *buffer = newBuffer;
3954    return NO_ERROR;
3955}
3956
3957// caller must hold mTimedBufferQueueLock
3958void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3959    int64_t mediaTimeNow;
3960    {
3961        Mutex::Autolock mttLock(mMediaTimeTransformLock);
3962        if (!mMediaTimeTransformValid)
3963            return;
3964
3965        int64_t targetTimeNow;
3966        status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3967            ? mCCHelper.getCommonTime(&targetTimeNow)
3968            : mCCHelper.getLocalTime(&targetTimeNow);
3969
3970        if (OK != res)
3971            return;
3972
3973        if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3974                                                    &mediaTimeNow)) {
3975            return;
3976        }
3977    }
3978
3979    size_t trimIndex;
3980    for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3981        int64_t frameCount = mTimedBufferQueue[trimIndex].buffer()->size()
3982                           / mCblk->frameSize;
3983        int64_t bufEnd;
3984
3985        if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
3986                                                            &bufEnd)) {
3987            ALOGE("Failed to convert frame count of %lld to media time duration"
3988                  " (scale factor %d/%u) in %s", frameCount,
3989                  mMediaTimeToSampleTransform.a_to_b_numer,
3990                  mMediaTimeToSampleTransform.a_to_b_denom,
3991                  __PRETTY_FUNCTION__);
3992            break;
3993        }
3994        bufEnd += mTimedBufferQueue[trimIndex].pts();
3995
3996        if (bufEnd > mediaTimeNow)
3997            break;
3998
3999        // Is the buffer we want to use in the middle of a mix operation right
4000        // now?  If so, don't actually trim it.  Just wait for the releaseBuffer
4001        // from the mixer which should be coming back shortly.
4002        if (!trimIndex && mQueueHeadInFlight) {
4003            mTrimQueueHeadOnRelease = true;
4004        }
4005    }
4006
4007    size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
4008    if (trimStart < trimIndex) {
4009        mTimedBufferQueue.removeItemsAt(trimStart, trimIndex);
4010    }
4011}
4012
4013status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4014    const sp<IMemory>& buffer, int64_t pts) {
4015
4016    {
4017        Mutex::Autolock mttLock(mMediaTimeTransformLock);
4018        if (!mMediaTimeTransformValid)
4019            return INVALID_OPERATION;
4020    }
4021
4022    Mutex::Autolock _l(mTimedBufferQueueLock);
4023
4024    mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4025
4026    return NO_ERROR;
4027}
4028
4029status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4030    const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4031
4032    ALOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
4033         xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4034         target);
4035
4036    if (!(target == TimedAudioTrack::LOCAL_TIME ||
4037          target == TimedAudioTrack::COMMON_TIME)) {
4038        return BAD_VALUE;
4039    }
4040
4041    Mutex::Autolock lock(mMediaTimeTransformLock);
4042    mMediaTimeTransform = xform;
4043    mMediaTimeTransformTarget = target;
4044    mMediaTimeTransformValid = true;
4045
4046    return NO_ERROR;
4047}
4048
4049#define min(a, b) ((a) < (b) ? (a) : (b))
4050
4051// implementation of getNextBuffer for tracks whose buffers have timestamps
4052status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4053    AudioBufferProvider::Buffer* buffer, int64_t pts)
4054{
4055    if (pts == AudioBufferProvider::kInvalidPTS) {
4056        buffer->raw = 0;
4057        buffer->frameCount = 0;
4058        return INVALID_OPERATION;
4059    }
4060
4061    Mutex::Autolock _l(mTimedBufferQueueLock);
4062
4063    ALOG_ASSERT(!mQueueHeadInFlight,
4064                "getNextBuffer called without releaseBuffer!");
4065
4066    while (true) {
4067
4068        // if we have no timed buffers, then fail
4069        if (mTimedBufferQueue.isEmpty()) {
4070            buffer->raw = 0;
4071            buffer->frameCount = 0;
4072            return NOT_ENOUGH_DATA;
4073        }
4074
4075        TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4076
4077        // calculate the PTS of the head of the timed buffer queue expressed in
4078        // local time
4079        int64_t headLocalPTS;
4080        {
4081            Mutex::Autolock mttLock(mMediaTimeTransformLock);
4082
4083            ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
4084
4085            if (mMediaTimeTransform.a_to_b_denom == 0) {
4086                // the transform represents a pause, so yield silence
4087                timedYieldSilence_l(buffer->frameCount, buffer);
4088                return NO_ERROR;
4089            }
4090
4091            int64_t transformedPTS;
4092            if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4093                                                        &transformedPTS)) {
4094                // the transform failed.  this shouldn't happen, but if it does
4095                // then just drop this buffer
4096                ALOGW("timedGetNextBuffer transform failed");
4097                buffer->raw = 0;
4098                buffer->frameCount = 0;
4099                mTimedBufferQueue.removeAt(0);
4100                return NO_ERROR;
4101            }
4102
4103            if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4104                if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4105                                                          &headLocalPTS)) {
4106                    buffer->raw = 0;
4107                    buffer->frameCount = 0;
4108                    return INVALID_OPERATION;
4109                }
4110            } else {
4111                headLocalPTS = transformedPTS;
4112            }
4113        }
4114
4115        // adjust the head buffer's PTS to reflect the portion of the head buffer
4116        // that has already been consumed
4117        int64_t effectivePTS = headLocalPTS +
4118                ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4119
4120        // Calculate the delta in samples between the head of the input buffer
4121        // queue and the start of the next output buffer that will be written.
4122        // If the transformation fails because of over or underflow, it means
4123        // that the sample's position in the output stream is so far out of
4124        // whack that it should just be dropped.
4125        int64_t sampleDelta;
4126        if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4127            ALOGV("*** head buffer is too far from PTS: dropped buffer");
4128            mTimedBufferQueue.removeAt(0);
4129            continue;
4130        }
4131        if (!mLocalTimeToSampleTransform.doForwardTransform(
4132                (effectivePTS - pts) << 32, &sampleDelta)) {
4133            ALOGV("*** too late during sample rate transform: dropped buffer");
4134            mTimedBufferQueue.removeAt(0);
4135            continue;
4136        }
4137
4138        ALOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
4139             __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
4140             static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
4141             static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
4142
4143        // if the delta between the ideal placement for the next input sample and
4144        // the current output position is within this threshold, then we will
4145        // concatenate the next input samples to the previous output
4146        const int64_t kSampleContinuityThreshold =
4147                (static_cast<int64_t>(sampleRate()) << 32) / 10;
4148
4149        // if this is the first buffer of audio that we're emitting from this track
4150        // then it should be almost exactly on time.
4151        const int64_t kSampleStartupThreshold = 1LL << 32;
4152
4153        if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
4154            (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
4155            // the next input is close enough to being on time, so concatenate it
4156            // with the last output
4157            timedYieldSamples_l(buffer);
4158
4159            ALOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4160            return NO_ERROR;
4161        } else if (sampleDelta > 0) {
4162            // the gap between the current output position and the proper start of
4163            // the next input sample is too big, so fill it with silence
4164            uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4165
4166            timedYieldSilence_l(framesUntilNextInput, buffer);
4167            ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4168            return NO_ERROR;
4169        } else {
4170            // the next input sample is late
4171            uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4172            size_t onTimeSamplePosition =
4173                    head.position() + lateFrames * mCblk->frameSize;
4174
4175            if (onTimeSamplePosition > head.buffer()->size()) {
4176                // all the remaining samples in the head are too late, so
4177                // drop it and move on
4178                ALOGV("*** too late: dropped buffer");
4179                mTimedBufferQueue.removeAt(0);
4180                continue;
4181            } else {
4182                // skip over the late samples
4183                head.setPosition(onTimeSamplePosition);
4184
4185                // yield the available samples
4186                timedYieldSamples_l(buffer);
4187
4188                ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4189                return NO_ERROR;
4190            }
4191        }
4192    }
4193}
4194
4195// Yield samples from the timed buffer queue head up to the given output
4196// buffer's capacity.
4197//
4198// Caller must hold mTimedBufferQueueLock
4199void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
4200    AudioBufferProvider::Buffer* buffer) {
4201
4202    const TimedBuffer& head = mTimedBufferQueue[0];
4203
4204    buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4205                   head.position());
4206
4207    uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4208                                 mCblk->frameSize);
4209    size_t framesRequested = buffer->frameCount;
4210    buffer->frameCount = min(framesLeftInHead, framesRequested);
4211
4212    mQueueHeadInFlight = true;
4213    mTimedAudioOutputOnTime = true;
4214}
4215
4216// Yield samples of silence up to the given output buffer's capacity
4217//
4218// Caller must hold mTimedBufferQueueLock
4219void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
4220    uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4221
4222    // lazily allocate a buffer filled with silence
4223    if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4224        delete [] mTimedSilenceBuffer;
4225        mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4226        mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4227        memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4228    }
4229
4230    buffer->raw = mTimedSilenceBuffer;
4231    size_t framesRequested = buffer->frameCount;
4232    buffer->frameCount = min(numFrames, framesRequested);
4233
4234    mTimedAudioOutputOnTime = false;
4235}
4236
4237// AudioBufferProvider interface
4238void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4239    AudioBufferProvider::Buffer* buffer) {
4240
4241    Mutex::Autolock _l(mTimedBufferQueueLock);
4242
4243    // If the buffer which was just released is part of the buffer at the head
4244    // of the queue, be sure to update the amt of the buffer which has been
4245    // consumed.  If the buffer being returned is not part of the head of the
4246    // queue, its either because the buffer is part of the silence buffer, or
4247    // because the head of the timed queue was trimmed after the mixer called
4248    // getNextBuffer but before the mixer called releaseBuffer.
4249    if (buffer->raw == mTimedSilenceBuffer) {
4250        ALOG_ASSERT(!mQueueHeadInFlight,
4251                    "Queue head in flight during release of silence buffer!");
4252        goto done;
4253    }
4254
4255    ALOG_ASSERT(mQueueHeadInFlight,
4256                "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
4257                " head in flight.");
4258
4259    if (mTimedBufferQueue.size()) {
4260        TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4261
4262        void* start = head.buffer()->pointer();
4263        void* end   = reinterpret_cast<void*>(
4264                        reinterpret_cast<uint8_t*>(head.buffer()->pointer())
4265                        + head.buffer()->size());
4266
4267        ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
4268                    "released buffer not within the head of the timed buffer"
4269                    " queue; qHead = [%p, %p], released buffer = %p",
4270                    start, end, buffer->raw);
4271
4272        head.setPosition(head.position() +
4273                (buffer->frameCount * mCblk->frameSize));
4274        mQueueHeadInFlight = false;
4275
4276        if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
4277            || mTrimQueueHeadOnRelease) {
4278            mTimedBufferQueue.removeAt(0);
4279            mTrimQueueHeadOnRelease = false;
4280        }
4281    } else {
4282        LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
4283                  " buffers in the timed buffer queue");
4284    }
4285
4286done:
4287    buffer->raw = 0;
4288    buffer->frameCount = 0;
4289}
4290
4291uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4292    Mutex::Autolock _l(mTimedBufferQueueLock);
4293
4294    uint32_t frames = 0;
4295    for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4296        const TimedBuffer& tb = mTimedBufferQueue[i];
4297        frames += (tb.buffer()->size() - tb.position())  / mCblk->frameSize;
4298    }
4299
4300    return frames;
4301}
4302
4303AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4304        : mPTS(0), mPosition(0) {}
4305
4306AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4307    const sp<IMemory>& buffer, int64_t pts)
4308        : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4309
4310// ----------------------------------------------------------------------------
4311
4312// RecordTrack constructor must be called with AudioFlinger::mLock held
4313AudioFlinger::RecordThread::RecordTrack::RecordTrack(
4314            RecordThread *thread,
4315            const sp<Client>& client,
4316            uint32_t sampleRate,
4317            audio_format_t format,
4318            uint32_t channelMask,
4319            int frameCount,
4320            int sessionId)
4321    :   TrackBase(thread, client, sampleRate, format,
4322                  channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
4323        mOverflow(false)
4324{
4325    if (mCblk != NULL) {
4326        ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4327        if (format == AUDIO_FORMAT_PCM_16_BIT) {
4328            mCblk->frameSize = mChannelCount * sizeof(int16_t);
4329        } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4330            mCblk->frameSize = mChannelCount * sizeof(int8_t);
4331        } else {
4332            mCblk->frameSize = sizeof(int8_t);
4333        }
4334    }
4335}
4336
4337AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4338{
4339    sp<ThreadBase> thread = mThread.promote();
4340    if (thread != 0) {
4341        AudioSystem::releaseInput(thread->id());
4342    }
4343}
4344
4345// AudioBufferProvider interface
4346status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
4347{
4348    audio_track_cblk_t* cblk = this->cblk();
4349    uint32_t framesAvail;
4350    uint32_t framesReq = buffer->frameCount;
4351
4352    // Check if last stepServer failed, try to step now
4353    if (mStepServerFailed) {
4354        if (!step()) goto getNextBuffer_exit;
4355        ALOGV("stepServer recovered");
4356        mStepServerFailed = false;
4357    }
4358
4359    framesAvail = cblk->framesAvailable_l();
4360
4361    if (CC_LIKELY(framesAvail)) {
4362        uint32_t s = cblk->server;
4363        uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4364
4365        if (framesReq > framesAvail) {
4366            framesReq = framesAvail;
4367        }
4368        if (framesReq > bufferEnd - s) {
4369            framesReq = bufferEnd - s;
4370        }
4371
4372        buffer->raw = getBuffer(s, framesReq);
4373        if (buffer->raw == NULL) goto getNextBuffer_exit;
4374
4375        buffer->frameCount = framesReq;
4376        return NO_ERROR;
4377    }
4378
4379getNextBuffer_exit:
4380    buffer->raw = NULL;
4381    buffer->frameCount = 0;
4382    return NOT_ENOUGH_DATA;
4383}
4384
4385status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid,
4386                                                        AudioSystem::sync_event_t event,
4387                                                        int triggerSession)
4388{
4389    sp<ThreadBase> thread = mThread.promote();
4390    if (thread != 0) {
4391        RecordThread *recordThread = (RecordThread *)thread.get();
4392        return recordThread->start(this, tid, event, triggerSession);
4393    } else {
4394        return BAD_VALUE;
4395    }
4396}
4397
4398void AudioFlinger::RecordThread::RecordTrack::stop()
4399{
4400    sp<ThreadBase> thread = mThread.promote();
4401    if (thread != 0) {
4402        RecordThread *recordThread = (RecordThread *)thread.get();
4403        recordThread->stop(this);
4404        TrackBase::reset();
4405        // Force overrun condition to avoid false overrun callback until first data is
4406        // read from buffer
4407        android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
4408    }
4409}
4410
4411void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4412{
4413    snprintf(buffer, size, "   %05d %03u 0x%08x %05d   %04u %01d %05u  %08x %08x\n",
4414            (mClient == 0) ? getpid_cached : mClient->pid(),
4415            mFormat,
4416            mChannelMask,
4417            mSessionId,
4418            mFrameCount,
4419            mState,
4420            mCblk->sampleRate,
4421            mCblk->server,
4422            mCblk->user);
4423}
4424
4425
4426// ----------------------------------------------------------------------------
4427
4428AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
4429            PlaybackThread *playbackThread,
4430            DuplicatingThread *sourceThread,
4431            uint32_t sampleRate,
4432            audio_format_t format,
4433            uint32_t channelMask,
4434            int frameCount)
4435    :   Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
4436                NULL, 0, IAudioFlinger::TRACK_DEFAULT),
4437    mActive(false), mSourceThread(sourceThread)
4438{
4439
4440    if (mCblk != NULL) {
4441        mCblk->flags |= CBLK_DIRECTION_OUT;
4442        mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
4443        mOutBuffer.frameCount = 0;
4444        playbackThread->mTracks.add(this);
4445        ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
4446                "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4447                mCblk, mBuffer, mCblk->buffers,
4448                mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
4449    } else {
4450        ALOGW("Error creating output track on thread %p", playbackThread);
4451    }
4452}
4453
4454AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4455{
4456    clearBufferQueue();
4457}
4458
4459status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid,
4460                                                          AudioSystem::sync_event_t event,
4461                                                          int triggerSession)
4462{
4463    status_t status = Track::start(tid, event, triggerSession);
4464    if (status != NO_ERROR) {
4465        return status;
4466    }
4467
4468    mActive = true;
4469    mRetryCount = 127;
4470    return status;
4471}
4472
4473void AudioFlinger::PlaybackThread::OutputTrack::stop()
4474{
4475    Track::stop();
4476    clearBufferQueue();
4477    mOutBuffer.frameCount = 0;
4478    mActive = false;
4479}
4480
4481bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4482{
4483    Buffer *pInBuffer;
4484    Buffer inBuffer;
4485    uint32_t channelCount = mChannelCount;
4486    bool outputBufferFull = false;
4487    inBuffer.frameCount = frames;
4488    inBuffer.i16 = data;
4489
4490    uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4491
4492    if (!mActive && frames != 0) {
4493        start(0);
4494        sp<ThreadBase> thread = mThread.promote();
4495        if (thread != 0) {
4496            MixerThread *mixerThread = (MixerThread *)thread.get();
4497            if (mCblk->frameCount > frames){
4498                if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4499                    uint32_t startFrames = (mCblk->frameCount - frames);
4500                    pInBuffer = new Buffer;
4501                    pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4502                    pInBuffer->frameCount = startFrames;
4503                    pInBuffer->i16 = pInBuffer->mBuffer;
4504                    memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4505                    mBufferQueue.add(pInBuffer);
4506                } else {
4507                    ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
4508                }
4509            }
4510        }
4511    }
4512
4513    while (waitTimeLeftMs) {
4514        // First write pending buffers, then new data
4515        if (mBufferQueue.size()) {
4516            pInBuffer = mBufferQueue.itemAt(0);
4517        } else {
4518            pInBuffer = &inBuffer;
4519        }
4520
4521        if (pInBuffer->frameCount == 0) {
4522            break;
4523        }
4524
4525        if (mOutBuffer.frameCount == 0) {
4526            mOutBuffer.frameCount = pInBuffer->frameCount;
4527            nsecs_t startTime = systemTime();
4528            if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
4529                ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
4530                outputBufferFull = true;
4531                break;
4532            }
4533            uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4534            if (waitTimeLeftMs >= waitTimeMs) {
4535                waitTimeLeftMs -= waitTimeMs;
4536            } else {
4537                waitTimeLeftMs = 0;
4538            }
4539        }
4540
4541        uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4542        memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4543        mCblk->stepUser(outFrames);
4544        pInBuffer->frameCount -= outFrames;
4545        pInBuffer->i16 += outFrames * channelCount;
4546        mOutBuffer.frameCount -= outFrames;
4547        mOutBuffer.i16 += outFrames * channelCount;
4548
4549        if (pInBuffer->frameCount == 0) {
4550            if (mBufferQueue.size()) {
4551                mBufferQueue.removeAt(0);
4552                delete [] pInBuffer->mBuffer;
4553                delete pInBuffer;
4554                ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
4555            } else {
4556                break;
4557            }
4558        }
4559    }
4560
4561    // If we could not write all frames, allocate a buffer and queue it for next time.
4562    if (inBuffer.frameCount) {
4563        sp<ThreadBase> thread = mThread.promote();
4564        if (thread != 0 && !thread->standby()) {
4565            if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4566                pInBuffer = new Buffer;
4567                pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4568                pInBuffer->frameCount = inBuffer.frameCount;
4569                pInBuffer->i16 = pInBuffer->mBuffer;
4570                memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4571                mBufferQueue.add(pInBuffer);
4572                ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
4573            } else {
4574                ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
4575            }
4576        }
4577    }
4578
4579    // Calling write() with a 0 length buffer, means that no more data will be written:
4580    // If no more buffers are pending, fill output track buffer to make sure it is started
4581    // by output mixer.
4582    if (frames == 0 && mBufferQueue.size() == 0) {
4583        if (mCblk->user < mCblk->frameCount) {
4584            frames = mCblk->frameCount - mCblk->user;
4585            pInBuffer = new Buffer;
4586            pInBuffer->mBuffer = new int16_t[frames * channelCount];
4587            pInBuffer->frameCount = frames;
4588            pInBuffer->i16 = pInBuffer->mBuffer;
4589            memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4590            mBufferQueue.add(pInBuffer);
4591        } else if (mActive) {
4592            stop();
4593        }
4594    }
4595
4596    return outputBufferFull;
4597}
4598
4599status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4600{
4601    int active;
4602    status_t result;
4603    audio_track_cblk_t* cblk = mCblk;
4604    uint32_t framesReq = buffer->frameCount;
4605
4606//    ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
4607    buffer->frameCount  = 0;
4608
4609    uint32_t framesAvail = cblk->framesAvailable();
4610
4611
4612    if (framesAvail == 0) {
4613        Mutex::Autolock _l(cblk->lock);
4614        goto start_loop_here;
4615        while (framesAvail == 0) {
4616            active = mActive;
4617            if (CC_UNLIKELY(!active)) {
4618                ALOGV("Not active and NO_MORE_BUFFERS");
4619                return NO_MORE_BUFFERS;
4620            }
4621            result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4622            if (result != NO_ERROR) {
4623                return NO_MORE_BUFFERS;
4624            }
4625            // read the server count again
4626        start_loop_here:
4627            framesAvail = cblk->framesAvailable_l();
4628        }
4629    }
4630
4631//    if (framesAvail < framesReq) {
4632//        return NO_MORE_BUFFERS;
4633//    }
4634
4635    if (framesReq > framesAvail) {
4636        framesReq = framesAvail;
4637    }
4638
4639    uint32_t u = cblk->user;
4640    uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4641
4642    if (framesReq > bufferEnd - u) {
4643        framesReq = bufferEnd - u;
4644    }
4645
4646    buffer->frameCount  = framesReq;
4647    buffer->raw         = (void *)cblk->buffer(u);
4648    return NO_ERROR;
4649}
4650
4651
4652void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4653{
4654    size_t size = mBufferQueue.size();
4655
4656    for (size_t i = 0; i < size; i++) {
4657        Buffer *pBuffer = mBufferQueue.itemAt(i);
4658        delete [] pBuffer->mBuffer;
4659        delete pBuffer;
4660    }
4661    mBufferQueue.clear();
4662}
4663
4664// ----------------------------------------------------------------------------
4665
4666AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4667    :   RefBase(),
4668        mAudioFlinger(audioFlinger),
4669        // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
4670        mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4671        mPid(pid),
4672        mTimedTrackCount(0)
4673{
4674    // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4675}
4676
4677// Client destructor must be called with AudioFlinger::mLock held
4678AudioFlinger::Client::~Client()
4679{
4680    mAudioFlinger->removeClient_l(mPid);
4681}
4682
4683sp<MemoryDealer> AudioFlinger::Client::heap() const
4684{
4685    return mMemoryDealer;
4686}
4687
4688// Reserve one of the limited slots for a timed audio track associated
4689// with this client
4690bool AudioFlinger::Client::reserveTimedTrack()
4691{
4692    const int kMaxTimedTracksPerClient = 4;
4693
4694    Mutex::Autolock _l(mTimedTrackLock);
4695
4696    if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4697        ALOGW("can not create timed track - pid %d has exceeded the limit",
4698             mPid);
4699        return false;
4700    }
4701
4702    mTimedTrackCount++;
4703    return true;
4704}
4705
4706// Release a slot for a timed audio track
4707void AudioFlinger::Client::releaseTimedTrack()
4708{
4709    Mutex::Autolock _l(mTimedTrackLock);
4710    mTimedTrackCount--;
4711}
4712
4713// ----------------------------------------------------------------------------
4714
4715AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4716                                                     const sp<IAudioFlingerClient>& client,
4717                                                     pid_t pid)
4718    : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
4719{
4720}
4721
4722AudioFlinger::NotificationClient::~NotificationClient()
4723{
4724}
4725
4726void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4727{
4728    sp<NotificationClient> keep(this);
4729    mAudioFlinger->removeNotificationClient(mPid);
4730}
4731
4732// ----------------------------------------------------------------------------
4733
4734AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4735    : BnAudioTrack(),
4736      mTrack(track)
4737{
4738}
4739
4740AudioFlinger::TrackHandle::~TrackHandle() {
4741    // just stop the track on deletion, associated resources
4742    // will be freed from the main thread once all pending buffers have
4743    // been played. Unless it's not in the active track list, in which
4744    // case we free everything now...
4745    mTrack->destroy();
4746}
4747
4748sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4749    return mTrack->getCblk();
4750}
4751
4752status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4753    return mTrack->start(tid);
4754}
4755
4756void AudioFlinger::TrackHandle::stop() {
4757    mTrack->stop();
4758}
4759
4760void AudioFlinger::TrackHandle::flush() {
4761    mTrack->flush();
4762}
4763
4764void AudioFlinger::TrackHandle::mute(bool e) {
4765    mTrack->mute(e);
4766}
4767
4768void AudioFlinger::TrackHandle::pause() {
4769    mTrack->pause();
4770}
4771
4772status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4773{
4774    return mTrack->attachAuxEffect(EffectId);
4775}
4776
4777status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4778                                                         sp<IMemory>* buffer) {
4779    if (!mTrack->isTimedTrack())
4780        return INVALID_OPERATION;
4781
4782    PlaybackThread::TimedTrack* tt =
4783            reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4784    return tt->allocateTimedBuffer(size, buffer);
4785}
4786
4787status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4788                                                     int64_t pts) {
4789    if (!mTrack->isTimedTrack())
4790        return INVALID_OPERATION;
4791
4792    PlaybackThread::TimedTrack* tt =
4793            reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4794    return tt->queueTimedBuffer(buffer, pts);
4795}
4796
4797status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4798    const LinearTransform& xform, int target) {
4799
4800    if (!mTrack->isTimedTrack())
4801        return INVALID_OPERATION;
4802
4803    PlaybackThread::TimedTrack* tt =
4804            reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4805    return tt->setMediaTimeTransform(
4806        xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4807}
4808
4809status_t AudioFlinger::TrackHandle::onTransact(
4810    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4811{
4812    return BnAudioTrack::onTransact(code, data, reply, flags);
4813}
4814
4815// ----------------------------------------------------------------------------
4816
4817sp<IAudioRecord> AudioFlinger::openRecord(
4818        pid_t pid,
4819        audio_io_handle_t input,
4820        uint32_t sampleRate,
4821        audio_format_t format,
4822        uint32_t channelMask,
4823        int frameCount,
4824        IAudioFlinger::track_flags_t flags,
4825        int *sessionId,
4826        status_t *status)
4827{
4828    sp<RecordThread::RecordTrack> recordTrack;
4829    sp<RecordHandle> recordHandle;
4830    sp<Client> client;
4831    status_t lStatus;
4832    RecordThread *thread;
4833    size_t inFrameCount;
4834    int lSessionId;
4835
4836    // check calling permissions
4837    if (!recordingAllowed()) {
4838        lStatus = PERMISSION_DENIED;
4839        goto Exit;
4840    }
4841
4842    // add client to list
4843    { // scope for mLock
4844        Mutex::Autolock _l(mLock);
4845        thread = checkRecordThread_l(input);
4846        if (thread == NULL) {
4847            lStatus = BAD_VALUE;
4848            goto Exit;
4849        }
4850
4851        client = registerPid_l(pid);
4852
4853        // If no audio session id is provided, create one here
4854        if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
4855            lSessionId = *sessionId;
4856        } else {
4857            lSessionId = nextUniqueId();
4858            if (sessionId != NULL) {
4859                *sessionId = lSessionId;
4860            }
4861        }
4862        // create new record track. The record track uses one track in mHardwareMixerThread by convention.
4863        recordTrack = thread->createRecordTrack_l(client,
4864                                                sampleRate,
4865                                                format,
4866                                                channelMask,
4867                                                frameCount,
4868                                                lSessionId,
4869                                                &lStatus);
4870    }
4871    if (lStatus != NO_ERROR) {
4872        // remove local strong reference to Client before deleting the RecordTrack so that the Client
4873        // destructor is called by the TrackBase destructor with mLock held
4874        client.clear();
4875        recordTrack.clear();
4876        goto Exit;
4877    }
4878
4879    // return to handle to client
4880    recordHandle = new RecordHandle(recordTrack);
4881    lStatus = NO_ERROR;
4882
4883Exit:
4884    if (status) {
4885        *status = lStatus;
4886    }
4887    return recordHandle;
4888}
4889
4890// ----------------------------------------------------------------------------
4891
4892AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4893    : BnAudioRecord(),
4894    mRecordTrack(recordTrack)
4895{
4896}
4897
4898AudioFlinger::RecordHandle::~RecordHandle() {
4899    stop();
4900}
4901
4902sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4903    return mRecordTrack->getCblk();
4904}
4905
4906status_t AudioFlinger::RecordHandle::start(pid_t tid, int event, int triggerSession) {
4907    ALOGV("RecordHandle::start()");
4908    return mRecordTrack->start(tid, (AudioSystem::sync_event_t)event, triggerSession);
4909}
4910
4911void AudioFlinger::RecordHandle::stop() {
4912    ALOGV("RecordHandle::stop()");
4913    mRecordTrack->stop();
4914}
4915
4916status_t AudioFlinger::RecordHandle::onTransact(
4917    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4918{
4919    return BnAudioRecord::onTransact(code, data, reply, flags);
4920}
4921
4922// ----------------------------------------------------------------------------
4923
4924AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4925                                         AudioStreamIn *input,
4926                                         uint32_t sampleRate,
4927                                         uint32_t channels,
4928                                         audio_io_handle_t id,
4929                                         uint32_t device) :
4930    ThreadBase(audioFlinger, id, device, RECORD),
4931    mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4932    // mRsmpInIndex and mInputBytes set by readInputParameters()
4933    mReqChannelCount(popcount(channels)),
4934    mReqSampleRate(sampleRate)
4935    // mBytesRead is only meaningful while active, and so is cleared in start()
4936    // (but might be better to also clear here for dump?)
4937{
4938    snprintf(mName, kNameLength, "AudioIn_%X", id);
4939
4940    readInputParameters();
4941}
4942
4943
4944AudioFlinger::RecordThread::~RecordThread()
4945{
4946    delete[] mRsmpInBuffer;
4947    delete mResampler;
4948    delete[] mRsmpOutBuffer;
4949}
4950
4951void AudioFlinger::RecordThread::onFirstRef()
4952{
4953    run(mName, PRIORITY_URGENT_AUDIO);
4954}
4955
4956status_t AudioFlinger::RecordThread::readyToRun()
4957{
4958    status_t status = initCheck();
4959    ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4960    return status;
4961}
4962
4963bool AudioFlinger::RecordThread::threadLoop()
4964{
4965    AudioBufferProvider::Buffer buffer;
4966    sp<RecordTrack> activeTrack;
4967    Vector< sp<EffectChain> > effectChains;
4968
4969    nsecs_t lastWarning = 0;
4970
4971    acquireWakeLock();
4972
4973    // start recording
4974    while (!exitPending()) {
4975
4976        processConfigEvents();
4977
4978        { // scope for mLock
4979            Mutex::Autolock _l(mLock);
4980            checkForNewParameters_l();
4981            if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4982                if (!mStandby) {
4983                    mInput->stream->common.standby(&mInput->stream->common);
4984                    mStandby = true;
4985                }
4986
4987                if (exitPending()) break;
4988
4989                releaseWakeLock_l();
4990                ALOGV("RecordThread: loop stopping");
4991                // go to sleep
4992                mWaitWorkCV.wait(mLock);
4993                ALOGV("RecordThread: loop starting");
4994                acquireWakeLock_l();
4995                continue;
4996            }
4997            if (mActiveTrack != 0) {
4998                if (mActiveTrack->mState == TrackBase::PAUSING) {
4999                    if (!mStandby) {
5000                        mInput->stream->common.standby(&mInput->stream->common);
5001                        mStandby = true;
5002                    }
5003                    mActiveTrack.clear();
5004                    mStartStopCond.broadcast();
5005                } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5006                    if (mReqChannelCount != mActiveTrack->channelCount()) {
5007                        mActiveTrack.clear();
5008                        mStartStopCond.broadcast();
5009                    } else if (mBytesRead != 0) {
5010                        // record start succeeds only if first read from audio input
5011                        // succeeds
5012                        if (mBytesRead > 0) {
5013                            mActiveTrack->mState = TrackBase::ACTIVE;
5014                        } else {
5015                            mActiveTrack.clear();
5016                        }
5017                        mStartStopCond.broadcast();
5018                    }
5019                    mStandby = false;
5020                }
5021            }
5022            lockEffectChains_l(effectChains);
5023        }
5024
5025        if (mActiveTrack != 0) {
5026            if (mActiveTrack->mState != TrackBase::ACTIVE &&
5027                mActiveTrack->mState != TrackBase::RESUMING) {
5028                unlockEffectChains(effectChains);
5029                usleep(kRecordThreadSleepUs);
5030                continue;
5031            }
5032            for (size_t i = 0; i < effectChains.size(); i ++) {
5033                effectChains[i]->process_l();
5034            }
5035
5036            buffer.frameCount = mFrameCount;
5037            if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
5038                size_t framesOut = buffer.frameCount;
5039                if (mResampler == NULL) {
5040                    // no resampling
5041                    while (framesOut) {
5042                        size_t framesIn = mFrameCount - mRsmpInIndex;
5043                        if (framesIn) {
5044                            int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5045                            int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5046                            if (framesIn > framesOut)
5047                                framesIn = framesOut;
5048                            mRsmpInIndex += framesIn;
5049                            framesOut -= framesIn;
5050                            if ((int)mChannelCount == mReqChannelCount ||
5051                                mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5052                                memcpy(dst, src, framesIn * mFrameSize);
5053                            } else {
5054                                int16_t *src16 = (int16_t *)src;
5055                                int16_t *dst16 = (int16_t *)dst;
5056                                if (mChannelCount == 1) {
5057                                    while (framesIn--) {
5058                                        *dst16++ = *src16;
5059                                        *dst16++ = *src16++;
5060                                    }
5061                                } else {
5062                                    while (framesIn--) {
5063                                        *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5064                                        src16 += 2;
5065                                    }
5066                                }
5067                            }
5068                        }
5069                        if (framesOut && mFrameCount == mRsmpInIndex) {
5070                            if (framesOut == mFrameCount &&
5071                                ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
5072                                mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
5073                                framesOut = 0;
5074                            } else {
5075                                mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
5076                                mRsmpInIndex = 0;
5077                            }
5078                            if (mBytesRead < 0) {
5079                                ALOGE("Error reading audio input");
5080                                if (mActiveTrack->mState == TrackBase::ACTIVE) {
5081                                    // Force input into standby so that it tries to
5082                                    // recover at next read attempt
5083                                    mInput->stream->common.standby(&mInput->stream->common);
5084                                    usleep(kRecordThreadSleepUs);
5085                                }
5086                                mRsmpInIndex = mFrameCount;
5087                                framesOut = 0;
5088                                buffer.frameCount = 0;
5089                            }
5090                        }
5091                    }
5092                } else {
5093                    // resampling
5094
5095                    memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5096                    // alter output frame count as if we were expecting stereo samples
5097                    if (mChannelCount == 1 && mReqChannelCount == 1) {
5098                        framesOut >>= 1;
5099                    }
5100                    mResampler->resample(mRsmpOutBuffer, framesOut, this);
5101                    // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5102                    // are 32 bit aligned which should be always true.
5103                    if (mChannelCount == 2 && mReqChannelCount == 1) {
5104                        ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
5105                        // the resampler always outputs stereo samples: do post stereo to mono conversion
5106                        int16_t *src = (int16_t *)mRsmpOutBuffer;
5107                        int16_t *dst = buffer.i16;
5108                        while (framesOut--) {
5109                            *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5110                            src += 2;
5111                        }
5112                    } else {
5113                        ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
5114                    }
5115
5116                }
5117                if (mFramestoDrop == 0) {
5118                    mActiveTrack->releaseBuffer(&buffer);
5119                } else {
5120                    if (mFramestoDrop > 0) {
5121                        mFramestoDrop -= buffer.frameCount;
5122                        if (mFramestoDrop < 0) {
5123                            mFramestoDrop = 0;
5124                        }
5125                    }
5126                }
5127                mActiveTrack->overflow();
5128            }
5129            // client isn't retrieving buffers fast enough
5130            else {
5131                if (!mActiveTrack->setOverflow()) {
5132                    nsecs_t now = systemTime();
5133                    if ((now - lastWarning) > kWarningThrottleNs) {
5134                        ALOGW("RecordThread: buffer overflow");
5135                        lastWarning = now;
5136                    }
5137                }
5138                // Release the processor for a while before asking for a new buffer.
5139                // This will give the application more chance to read from the buffer and
5140                // clear the overflow.
5141                usleep(kRecordThreadSleepUs);
5142            }
5143        }
5144        // enable changes in effect chain
5145        unlockEffectChains(effectChains);
5146        effectChains.clear();
5147    }
5148
5149    if (!mStandby) {
5150        mInput->stream->common.standby(&mInput->stream->common);
5151    }
5152    mActiveTrack.clear();
5153
5154    mStartStopCond.broadcast();
5155
5156    releaseWakeLock();
5157
5158    ALOGV("RecordThread %p exiting", this);
5159    return false;
5160}
5161
5162
5163sp<AudioFlinger::RecordThread::RecordTrack>  AudioFlinger::RecordThread::createRecordTrack_l(
5164        const sp<AudioFlinger::Client>& client,
5165        uint32_t sampleRate,
5166        audio_format_t format,
5167        int channelMask,
5168        int frameCount,
5169        int sessionId,
5170        status_t *status)
5171{
5172    sp<RecordTrack> track;
5173    status_t lStatus;
5174
5175    lStatus = initCheck();
5176    if (lStatus != NO_ERROR) {
5177        ALOGE("Audio driver not initialized.");
5178        goto Exit;
5179    }
5180
5181    { // scope for mLock
5182        Mutex::Autolock _l(mLock);
5183
5184        track = new RecordTrack(this, client, sampleRate,
5185                      format, channelMask, frameCount, sessionId);
5186
5187        if (track->getCblk() == 0) {
5188            lStatus = NO_MEMORY;
5189            goto Exit;
5190        }
5191
5192        mTrack = track.get();
5193        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5194        bool suspend = audio_is_bluetooth_sco_device(
5195                (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
5196        setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5197        setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
5198    }
5199    lStatus = NO_ERROR;
5200
5201Exit:
5202    if (status) {
5203        *status = lStatus;
5204    }
5205    return track;
5206}
5207
5208status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5209                                           pid_t tid, AudioSystem::sync_event_t event,
5210                                           int triggerSession)
5211{
5212    ALOGV("RecordThread::start tid=%d,  event %d, triggerSession %d", tid, event, triggerSession);
5213    sp<ThreadBase> strongMe = this;
5214    status_t status = NO_ERROR;
5215
5216    if (event == AudioSystem::SYNC_EVENT_NONE) {
5217        mSyncStartEvent.clear();
5218        mFramestoDrop = 0;
5219    } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5220        mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5221                                       triggerSession,
5222                                       recordTrack->sessionId(),
5223                                       syncStartEventCallback,
5224                                       this);
5225        mFramestoDrop = -1;
5226    }
5227
5228    {
5229        AutoMutex lock(mLock);
5230        if (mActiveTrack != 0) {
5231            if (recordTrack != mActiveTrack.get()) {
5232                status = -EBUSY;
5233            } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5234                mActiveTrack->mState = TrackBase::ACTIVE;
5235            }
5236            return status;
5237        }
5238
5239        recordTrack->mState = TrackBase::IDLE;
5240        mActiveTrack = recordTrack;
5241        mLock.unlock();
5242        status_t status = AudioSystem::startInput(mId);
5243        mLock.lock();
5244        if (status != NO_ERROR) {
5245            mActiveTrack.clear();
5246            clearSyncStartEvent();
5247            return status;
5248        }
5249        mRsmpInIndex = mFrameCount;
5250        mBytesRead = 0;
5251        if (mResampler != NULL) {
5252            mResampler->reset();
5253        }
5254        mActiveTrack->mState = TrackBase::RESUMING;
5255        // signal thread to start
5256        ALOGV("Signal record thread");
5257        mWaitWorkCV.signal();
5258        // do not wait for mStartStopCond if exiting
5259        if (exitPending()) {
5260            mActiveTrack.clear();
5261            status = INVALID_OPERATION;
5262            goto startError;
5263        }
5264        mStartStopCond.wait(mLock);
5265        if (mActiveTrack == 0) {
5266            ALOGV("Record failed to start");
5267            status = BAD_VALUE;
5268            goto startError;
5269        }
5270        ALOGV("Record started OK");
5271        return status;
5272    }
5273startError:
5274    AudioSystem::stopInput(mId);
5275    clearSyncStartEvent();
5276    return status;
5277}
5278
5279void AudioFlinger::RecordThread::clearSyncStartEvent()
5280{
5281    if (mSyncStartEvent != 0) {
5282        mSyncStartEvent->cancel();
5283    }
5284    mSyncStartEvent.clear();
5285}
5286
5287void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5288{
5289    sp<SyncEvent> strongEvent = event.promote();
5290
5291    if (strongEvent != 0) {
5292        RecordThread *me = (RecordThread *)strongEvent->cookie();
5293        me->handleSyncStartEvent(strongEvent);
5294    }
5295}
5296
5297void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
5298{
5299    ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
5300              mActiveTrack.get(),
5301              mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
5302              event->listenerSession());
5303
5304    if (mActiveTrack != 0 &&
5305            event == mSyncStartEvent) {
5306        // TODO: use actual buffer filling status instead of 2 buffers when info is available
5307        // from audio HAL
5308        mFramestoDrop = mFrameCount * 2;
5309        mSyncStartEvent.clear();
5310    }
5311}
5312
5313void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
5314    ALOGV("RecordThread::stop");
5315    sp<ThreadBase> strongMe = this;
5316    {
5317        AutoMutex lock(mLock);
5318        if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5319            mActiveTrack->mState = TrackBase::PAUSING;
5320            // do not wait for mStartStopCond if exiting
5321            if (exitPending()) {
5322                return;
5323            }
5324            mStartStopCond.wait(mLock);
5325            // if we have been restarted, recordTrack == mActiveTrack.get() here
5326            if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5327                mLock.unlock();
5328                AudioSystem::stopInput(mId);
5329                mLock.lock();
5330                ALOGV("Record stopped OK");
5331            }
5332        }
5333    }
5334}
5335
5336bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
5337{
5338    return false;
5339}
5340
5341status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
5342{
5343    if (!isValidSyncEvent(event)) {
5344        return BAD_VALUE;
5345    }
5346
5347    Mutex::Autolock _l(mLock);
5348
5349    if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
5350        mTrack->setSyncEvent(event);
5351        return NO_ERROR;
5352    }
5353    return NAME_NOT_FOUND;
5354}
5355
5356status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5357{
5358    const size_t SIZE = 256;
5359    char buffer[SIZE];
5360    String8 result;
5361
5362    snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5363    result.append(buffer);
5364
5365    if (mActiveTrack != 0) {
5366        result.append("Active Track:\n");
5367        result.append("   Clien Fmt Chn mask   Session Buf  S SRate  Serv     User\n");
5368        mActiveTrack->dump(buffer, SIZE);
5369        result.append(buffer);
5370
5371        snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5372        result.append(buffer);
5373        snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5374        result.append(buffer);
5375        snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
5376        result.append(buffer);
5377        snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5378        result.append(buffer);
5379        snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5380        result.append(buffer);
5381
5382
5383    } else {
5384        result.append("No record client\n");
5385    }
5386    write(fd, result.string(), result.size());
5387
5388    dumpBase(fd, args);
5389    dumpEffectChains(fd, args);
5390
5391    return NO_ERROR;
5392}
5393
5394// AudioBufferProvider interface
5395status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
5396{
5397    size_t framesReq = buffer->frameCount;
5398    size_t framesReady = mFrameCount - mRsmpInIndex;
5399    int channelCount;
5400
5401    if (framesReady == 0) {
5402        mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
5403        if (mBytesRead < 0) {
5404            ALOGE("RecordThread::getNextBuffer() Error reading audio input");
5405            if (mActiveTrack->mState == TrackBase::ACTIVE) {
5406                // Force input into standby so that it tries to
5407                // recover at next read attempt
5408                mInput->stream->common.standby(&mInput->stream->common);
5409                usleep(kRecordThreadSleepUs);
5410            }
5411            buffer->raw = NULL;
5412            buffer->frameCount = 0;
5413            return NOT_ENOUGH_DATA;
5414        }
5415        mRsmpInIndex = 0;
5416        framesReady = mFrameCount;
5417    }
5418
5419    if (framesReq > framesReady) {
5420        framesReq = framesReady;
5421    }
5422
5423    if (mChannelCount == 1 && mReqChannelCount == 2) {
5424        channelCount = 1;
5425    } else {
5426        channelCount = 2;
5427    }
5428    buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5429    buffer->frameCount = framesReq;
5430    return NO_ERROR;
5431}
5432
5433// AudioBufferProvider interface
5434void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5435{
5436    mRsmpInIndex += buffer->frameCount;
5437    buffer->frameCount = 0;
5438}
5439
5440bool AudioFlinger::RecordThread::checkForNewParameters_l()
5441{
5442    bool reconfig = false;
5443
5444    while (!mNewParameters.isEmpty()) {
5445        status_t status = NO_ERROR;
5446        String8 keyValuePair = mNewParameters[0];
5447        AudioParameter param = AudioParameter(keyValuePair);
5448        int value;
5449        audio_format_t reqFormat = mFormat;
5450        int reqSamplingRate = mReqSampleRate;
5451        int reqChannelCount = mReqChannelCount;
5452
5453        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5454            reqSamplingRate = value;
5455            reconfig = true;
5456        }
5457        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5458            reqFormat = (audio_format_t) value;
5459            reconfig = true;
5460        }
5461        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5462            reqChannelCount = popcount(value);
5463            reconfig = true;
5464        }
5465        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5466            // do not accept frame count changes if tracks are open as the track buffer
5467            // size depends on frame count and correct behavior would not be guaranteed
5468            // if frame count is changed after track creation
5469            if (mActiveTrack != 0) {
5470                status = INVALID_OPERATION;
5471            } else {
5472                reconfig = true;
5473            }
5474        }
5475        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5476            // forward device change to effects that have requested to be
5477            // aware of attached audio device.
5478            for (size_t i = 0; i < mEffectChains.size(); i++) {
5479                mEffectChains[i]->setDevice_l(value);
5480            }
5481            // store input device and output device but do not forward output device to audio HAL.
5482            // Note that status is ignored by the caller for output device
5483            // (see AudioFlinger::setParameters()
5484            if (value & AUDIO_DEVICE_OUT_ALL) {
5485                mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5486                status = BAD_VALUE;
5487            } else {
5488                mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
5489                // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5490                if (mTrack != NULL) {
5491                    bool suspend = audio_is_bluetooth_sco_device(
5492                            (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
5493                    setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5494                    setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5495                }
5496            }
5497            mDevice |= (uint32_t)value;
5498        }
5499        if (status == NO_ERROR) {
5500            status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
5501            if (status == INVALID_OPERATION) {
5502                mInput->stream->common.standby(&mInput->stream->common);
5503                status = mInput->stream->common.set_parameters(&mInput->stream->common,
5504                        keyValuePair.string());
5505            }
5506            if (reconfig) {
5507                if (status == BAD_VALUE &&
5508                    reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5509                    reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
5510                    ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
5511                    popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
5512                    (reqChannelCount <= FCC_2)) {
5513                    status = NO_ERROR;
5514                }
5515                if (status == NO_ERROR) {
5516                    readInputParameters();
5517                    sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5518                }
5519            }
5520        }
5521
5522        mNewParameters.removeAt(0);
5523
5524        mParamStatus = status;
5525        mParamCond.signal();
5526        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5527        // already timed out waiting for the status and will never signal the condition.
5528        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5529    }
5530    return reconfig;
5531}
5532
5533String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5534{
5535    char *s;
5536    String8 out_s8 = String8();
5537
5538    Mutex::Autolock _l(mLock);
5539    if (initCheck() != NO_ERROR) {
5540        return out_s8;
5541    }
5542
5543    s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5544    out_s8 = String8(s);
5545    free(s);
5546    return out_s8;
5547}
5548
5549void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5550    AudioSystem::OutputDescriptor desc;
5551    void *param2 = NULL;
5552
5553    switch (event) {
5554    case AudioSystem::INPUT_OPENED:
5555    case AudioSystem::INPUT_CONFIG_CHANGED:
5556        desc.channels = mChannelMask;
5557        desc.samplingRate = mSampleRate;
5558        desc.format = mFormat;
5559        desc.frameCount = mFrameCount;
5560        desc.latency = 0;
5561        param2 = &desc;
5562        break;
5563
5564    case AudioSystem::INPUT_CLOSED:
5565    default:
5566        break;
5567    }
5568    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5569}
5570
5571void AudioFlinger::RecordThread::readInputParameters()
5572{
5573    delete mRsmpInBuffer;
5574    // mRsmpInBuffer is always assigned a new[] below
5575    delete mRsmpOutBuffer;
5576    mRsmpOutBuffer = NULL;
5577    delete mResampler;
5578    mResampler = NULL;
5579
5580    mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5581    mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5582    mChannelCount = (uint16_t)popcount(mChannelMask);
5583    mFormat = mInput->stream->common.get_format(&mInput->stream->common);
5584    mFrameSize = audio_stream_frame_size(&mInput->stream->common);
5585    mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5586    mFrameCount = mInputBytes / mFrameSize;
5587    mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5588
5589    if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
5590    {
5591        int channelCount;
5592        // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5593        // stereo to mono post process as the resampler always outputs stereo.
5594        if (mChannelCount == 1 && mReqChannelCount == 2) {
5595            channelCount = 1;
5596        } else {
5597            channelCount = 2;
5598        }
5599        mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5600        mResampler->setSampleRate(mSampleRate);
5601        mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5602        mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5603
5604        // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5605        if (mChannelCount == 1 && mReqChannelCount == 1) {
5606            mFrameCount >>= 1;
5607        }
5608
5609    }
5610    mRsmpInIndex = mFrameCount;
5611}
5612
5613unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5614{
5615    Mutex::Autolock _l(mLock);
5616    if (initCheck() != NO_ERROR) {
5617        return 0;
5618    }
5619
5620    return mInput->stream->get_input_frames_lost(mInput->stream);
5621}
5622
5623uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5624{
5625    Mutex::Autolock _l(mLock);
5626    uint32_t result = 0;
5627    if (getEffectChain_l(sessionId) != 0) {
5628        result = EFFECT_SESSION;
5629    }
5630
5631    if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5632        result |= TRACK_SESSION;
5633    }
5634
5635    return result;
5636}
5637
5638AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5639{
5640    Mutex::Autolock _l(mLock);
5641    return mTrack;
5642}
5643
5644AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
5645{
5646    Mutex::Autolock _l(mLock);
5647    return mInput;
5648}
5649
5650AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5651{
5652    Mutex::Autolock _l(mLock);
5653    AudioStreamIn *input = mInput;
5654    mInput = NULL;
5655    return input;
5656}
5657
5658// this method must always be called either with ThreadBase mLock held or inside the thread loop
5659audio_stream_t* AudioFlinger::RecordThread::stream() const
5660{
5661    if (mInput == NULL) {
5662        return NULL;
5663    }
5664    return &mInput->stream->common;
5665}
5666
5667
5668// ----------------------------------------------------------------------------
5669
5670audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
5671{
5672    if (!settingsAllowed()) {
5673        return 0;
5674    }
5675    Mutex::Autolock _l(mLock);
5676    return loadHwModule_l(name);
5677}
5678
5679// loadHwModule_l() must be called with AudioFlinger::mLock held
5680audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
5681{
5682    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
5683        if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
5684            ALOGW("loadHwModule() module %s already loaded", name);
5685            return mAudioHwDevs.keyAt(i);
5686        }
5687    }
5688
5689    const hw_module_t *mod;
5690    audio_hw_device_t *dev;
5691
5692    int rc = load_audio_interface(name, &mod, &dev);
5693    if (rc) {
5694        ALOGI("loadHwModule() error %d loading module %s ", rc, name);
5695        return 0;
5696    }
5697
5698    mHardwareStatus = AUDIO_HW_INIT;
5699    rc = dev->init_check(dev);
5700    mHardwareStatus = AUDIO_HW_IDLE;
5701    if (rc) {
5702        ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
5703        return 0;
5704    }
5705
5706    if ((mMasterVolumeSupportLvl != MVS_NONE) &&
5707        (NULL != dev->set_master_volume)) {
5708        AutoMutex lock(mHardwareLock);
5709        mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
5710        dev->set_master_volume(dev, mMasterVolume);
5711        mHardwareStatus = AUDIO_HW_IDLE;
5712    }
5713
5714    audio_module_handle_t handle = nextUniqueId();
5715    mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
5716
5717    ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
5718          name, mod->name, mod->id, handle);
5719
5720    return handle;
5721
5722}
5723
5724audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
5725                                           audio_devices_t *pDevices,
5726                                           uint32_t *pSamplingRate,
5727                                           audio_format_t *pFormat,
5728                                           audio_channel_mask_t *pChannelMask,
5729                                           uint32_t *pLatencyMs,
5730                                           audio_policy_output_flags_t flags)
5731{
5732    status_t status;
5733    PlaybackThread *thread = NULL;
5734    uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5735    audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
5736    audio_channel_mask_t channelMask = pChannelMask ? *pChannelMask : 0;
5737    uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
5738    audio_stream_out_t *outStream;
5739    audio_hw_device_t *outHwDev;
5740
5741    ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
5742              module,
5743              (pDevices != NULL) ? (int)*pDevices : 0,
5744              samplingRate,
5745              format,
5746              channelMask,
5747              flags);
5748
5749    if (pDevices == NULL || *pDevices == 0) {
5750        return 0;
5751    }
5752
5753    Mutex::Autolock _l(mLock);
5754
5755    outHwDev = findSuitableHwDev_l(module, *pDevices);
5756    if (outHwDev == NULL)
5757        return 0;
5758
5759    mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
5760    status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
5761                                          &channelMask, &samplingRate, &outStream);
5762    mHardwareStatus = AUDIO_HW_IDLE;
5763    ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
5764            outStream,
5765            samplingRate,
5766            format,
5767            channelMask,
5768            status);
5769
5770    if (outStream != NULL) {
5771        AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
5772        audio_io_handle_t id = nextUniqueId();
5773
5774        if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5775            (format != AUDIO_FORMAT_PCM_16_BIT) ||
5776            (channelMask != AUDIO_CHANNEL_OUT_STEREO)) {
5777            thread = new DirectOutputThread(this, output, id, *pDevices);
5778            ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
5779        } else {
5780            thread = new MixerThread(this, output, id, *pDevices);
5781            ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
5782        }
5783        mPlaybackThreads.add(id, thread);
5784
5785        if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5786        if (pFormat != NULL) *pFormat = format;
5787        if (pChannelMask != NULL) *pChannelMask = channelMask;
5788        if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
5789
5790        // notify client processes of the new output creation
5791        thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5792
5793        // the first primary output opened designates the primary hw device
5794        if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_POLICY_OUTPUT_FLAG_PRIMARY)) {
5795            ALOGI("Using module %d has the primary audio interface", module);
5796            mPrimaryHardwareDev = outHwDev;
5797
5798            AutoMutex lock(mHardwareLock);
5799            mHardwareStatus = AUDIO_HW_SET_MODE;
5800            outHwDev->set_mode(outHwDev, mMode);
5801
5802            // Determine the level of master volume support the primary audio HAL has,
5803            // and set the initial master volume at the same time.
5804            float initialVolume = 1.0;
5805            mMasterVolumeSupportLvl = MVS_NONE;
5806
5807            mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
5808            if ((NULL != outHwDev->get_master_volume) &&
5809                (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
5810                mMasterVolumeSupportLvl = MVS_FULL;
5811            } else {
5812                mMasterVolumeSupportLvl = MVS_SETONLY;
5813                initialVolume = 1.0;
5814            }
5815
5816            mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
5817            if ((NULL == outHwDev->set_master_volume) ||
5818                (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
5819                mMasterVolumeSupportLvl = MVS_NONE;
5820            }
5821            // now that we have a primary device, initialize master volume on other devices
5822            for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
5823                audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
5824
5825                if ((dev != mPrimaryHardwareDev) &&
5826                    (NULL != dev->set_master_volume)) {
5827                    dev->set_master_volume(dev, initialVolume);
5828                }
5829            }
5830            mHardwareStatus = AUDIO_HW_IDLE;
5831            mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
5832                                    ? initialVolume
5833                                    : 1.0;
5834            mMasterVolume   = initialVolume;
5835        }
5836        return id;
5837    }
5838
5839    return 0;
5840}
5841
5842audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5843        audio_io_handle_t output2)
5844{
5845    Mutex::Autolock _l(mLock);
5846    MixerThread *thread1 = checkMixerThread_l(output1);
5847    MixerThread *thread2 = checkMixerThread_l(output2);
5848
5849    if (thread1 == NULL || thread2 == NULL) {
5850        ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
5851        return 0;
5852    }
5853
5854    audio_io_handle_t id = nextUniqueId();
5855    DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5856    thread->addOutputTrack(thread2);
5857    mPlaybackThreads.add(id, thread);
5858    // notify client processes of the new output creation
5859    thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5860    return id;
5861}
5862
5863status_t AudioFlinger::closeOutput(audio_io_handle_t output)
5864{
5865    // keep strong reference on the playback thread so that
5866    // it is not destroyed while exit() is executed
5867    sp<PlaybackThread> thread;
5868    {
5869        Mutex::Autolock _l(mLock);
5870        thread = checkPlaybackThread_l(output);
5871        if (thread == NULL) {
5872            return BAD_VALUE;
5873        }
5874
5875        ALOGV("closeOutput() %d", output);
5876
5877        if (thread->type() == ThreadBase::MIXER) {
5878            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5879                if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
5880                    DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5881                    dupThread->removeOutputTrack((MixerThread *)thread.get());
5882                }
5883            }
5884        }
5885        audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
5886        mPlaybackThreads.removeItem(output);
5887    }
5888    thread->exit();
5889    // The thread entity (active unit of execution) is no longer running here,
5890    // but the ThreadBase container still exists.
5891
5892    if (thread->type() != ThreadBase::DUPLICATING) {
5893        AudioStreamOut *out = thread->clearOutput();
5894        ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
5895        // from now on thread->mOutput is NULL
5896        out->hwDev->close_output_stream(out->hwDev, out->stream);
5897        delete out;
5898    }
5899    return NO_ERROR;
5900}
5901
5902status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
5903{
5904    Mutex::Autolock _l(mLock);
5905    PlaybackThread *thread = checkPlaybackThread_l(output);
5906
5907    if (thread == NULL) {
5908        return BAD_VALUE;
5909    }
5910
5911    ALOGV("suspendOutput() %d", output);
5912    thread->suspend();
5913
5914    return NO_ERROR;
5915}
5916
5917status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
5918{
5919    Mutex::Autolock _l(mLock);
5920    PlaybackThread *thread = checkPlaybackThread_l(output);
5921
5922    if (thread == NULL) {
5923        return BAD_VALUE;
5924    }
5925
5926    ALOGV("restoreOutput() %d", output);
5927
5928    thread->restore();
5929
5930    return NO_ERROR;
5931}
5932
5933audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
5934                                          audio_devices_t *pDevices,
5935                                          uint32_t *pSamplingRate,
5936                                          audio_format_t *pFormat,
5937                                          uint32_t *pChannelMask)
5938{
5939    status_t status;
5940    RecordThread *thread = NULL;
5941    uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5942    audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
5943    audio_channel_mask_t channelMask = pChannelMask ? *pChannelMask : 0;
5944    uint32_t reqSamplingRate = samplingRate;
5945    audio_format_t reqFormat = format;
5946    audio_channel_mask_t reqChannels = channelMask;
5947    audio_stream_in_t *inStream;
5948    audio_hw_device_t *inHwDev;
5949
5950    if (pDevices == NULL || *pDevices == 0) {
5951        return 0;
5952    }
5953
5954    Mutex::Autolock _l(mLock);
5955
5956    inHwDev = findSuitableHwDev_l(module, *pDevices);
5957    if (inHwDev == NULL)
5958        return 0;
5959
5960    status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
5961                                        &channelMask, &samplingRate,
5962                                        (audio_in_acoustics_t)0,
5963                                        &inStream);
5964    ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
5965            inStream,
5966            samplingRate,
5967            format,
5968            channelMask,
5969            status);
5970
5971    // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5972    // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5973    // or stereo to mono conversions on 16 bit PCM inputs.
5974    if (inStream == NULL && status == BAD_VALUE &&
5975        reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
5976        (samplingRate <= 2 * reqSamplingRate) &&
5977        (popcount(channelMask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
5978        ALOGV("openInput() reopening with proposed sampling rate and channels");
5979        status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
5980                                            &channelMask, &samplingRate,
5981                                            (audio_in_acoustics_t)0,
5982                                            &inStream);
5983    }
5984
5985    if (inStream != NULL) {
5986        AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5987
5988        audio_io_handle_t id = nextUniqueId();
5989        // Start record thread
5990        // RecorThread require both input and output device indication to forward to audio
5991        // pre processing modules
5992        uint32_t device = (*pDevices) | primaryOutputDevice_l();
5993        thread = new RecordThread(this,
5994                                  input,
5995                                  reqSamplingRate,
5996                                  reqChannels,
5997                                  id,
5998                                  device);
5999        mRecordThreads.add(id, thread);
6000        ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
6001        if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
6002        if (pFormat != NULL) *pFormat = format;
6003        if (pChannelMask != NULL) *pChannelMask = reqChannels;
6004
6005        input->stream->common.standby(&input->stream->common);
6006
6007        // notify client processes of the new input creation
6008        thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6009        return id;
6010    }
6011
6012    return 0;
6013}
6014
6015status_t AudioFlinger::closeInput(audio_io_handle_t input)
6016{
6017    // keep strong reference on the record thread so that
6018    // it is not destroyed while exit() is executed
6019    sp<RecordThread> thread;
6020    {
6021        Mutex::Autolock _l(mLock);
6022        thread = checkRecordThread_l(input);
6023        if (thread == NULL) {
6024            return BAD_VALUE;
6025        }
6026
6027        ALOGV("closeInput() %d", input);
6028        audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
6029        mRecordThreads.removeItem(input);
6030    }
6031    thread->exit();
6032    // The thread entity (active unit of execution) is no longer running here,
6033    // but the ThreadBase container still exists.
6034
6035    AudioStreamIn *in = thread->clearInput();
6036    ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
6037    // from now on thread->mInput is NULL
6038    in->hwDev->close_input_stream(in->hwDev, in->stream);
6039    delete in;
6040
6041    return NO_ERROR;
6042}
6043
6044status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
6045{
6046    Mutex::Autolock _l(mLock);
6047    MixerThread *dstThread = checkMixerThread_l(output);
6048    if (dstThread == NULL) {
6049        ALOGW("setStreamOutput() bad output id %d", output);
6050        return BAD_VALUE;
6051    }
6052
6053    ALOGV("setStreamOutput() stream %d to output %d", stream, output);
6054    audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6055
6056    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6057        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
6058        if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
6059            MixerThread *srcThread = (MixerThread *)thread;
6060            srcThread->invalidateTracks(stream);
6061        }
6062    }
6063
6064    return NO_ERROR;
6065}
6066
6067
6068int AudioFlinger::newAudioSessionId()
6069{
6070    return nextUniqueId();
6071}
6072
6073void AudioFlinger::acquireAudioSessionId(int audioSession)
6074{
6075    Mutex::Autolock _l(mLock);
6076    pid_t caller = IPCThreadState::self()->getCallingPid();
6077    ALOGV("acquiring %d from %d", audioSession, caller);
6078    size_t num = mAudioSessionRefs.size();
6079    for (size_t i = 0; i< num; i++) {
6080        AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
6081        if (ref->mSessionid == audioSession && ref->mPid == caller) {
6082            ref->mCnt++;
6083            ALOGV(" incremented refcount to %d", ref->mCnt);
6084            return;
6085        }
6086    }
6087    mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6088    ALOGV(" added new entry for %d", audioSession);
6089}
6090
6091void AudioFlinger::releaseAudioSessionId(int audioSession)
6092{
6093    Mutex::Autolock _l(mLock);
6094    pid_t caller = IPCThreadState::self()->getCallingPid();
6095    ALOGV("releasing %d from %d", audioSession, caller);
6096    size_t num = mAudioSessionRefs.size();
6097    for (size_t i = 0; i< num; i++) {
6098        AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
6099        if (ref->mSessionid == audioSession && ref->mPid == caller) {
6100            ref->mCnt--;
6101            ALOGV(" decremented refcount to %d", ref->mCnt);
6102            if (ref->mCnt == 0) {
6103                mAudioSessionRefs.removeAt(i);
6104                delete ref;
6105                purgeStaleEffects_l();
6106            }
6107            return;
6108        }
6109    }
6110    ALOGW("session id %d not found for pid %d", audioSession, caller);
6111}
6112
6113void AudioFlinger::purgeStaleEffects_l() {
6114
6115    ALOGV("purging stale effects");
6116
6117    Vector< sp<EffectChain> > chains;
6118
6119    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6120        sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6121        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6122            sp<EffectChain> ec = t->mEffectChains[j];
6123            if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6124                chains.push(ec);
6125            }
6126        }
6127    }
6128    for (size_t i = 0; i < mRecordThreads.size(); i++) {
6129        sp<RecordThread> t = mRecordThreads.valueAt(i);
6130        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6131            sp<EffectChain> ec = t->mEffectChains[j];
6132            chains.push(ec);
6133        }
6134    }
6135
6136    for (size_t i = 0; i < chains.size(); i++) {
6137        sp<EffectChain> ec = chains[i];
6138        int sessionid = ec->sessionId();
6139        sp<ThreadBase> t = ec->mThread.promote();
6140        if (t == 0) {
6141            continue;
6142        }
6143        size_t numsessionrefs = mAudioSessionRefs.size();
6144        bool found = false;
6145        for (size_t k = 0; k < numsessionrefs; k++) {
6146            AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
6147            if (ref->mSessionid == sessionid) {
6148                ALOGV(" session %d still exists for %d with %d refs",
6149                    sessionid, ref->mPid, ref->mCnt);
6150                found = true;
6151                break;
6152            }
6153        }
6154        if (!found) {
6155            // remove all effects from the chain
6156            while (ec->mEffects.size()) {
6157                sp<EffectModule> effect = ec->mEffects[0];
6158                effect->unPin();
6159                Mutex::Autolock _l (t->mLock);
6160                t->removeEffect_l(effect);
6161                for (size_t j = 0; j < effect->mHandles.size(); j++) {
6162                    sp<EffectHandle> handle = effect->mHandles[j].promote();
6163                    if (handle != 0) {
6164                        handle->mEffect.clear();
6165                        if (handle->mHasControl && handle->mEnabled) {
6166                            t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6167                        }
6168                    }
6169                }
6170                AudioSystem::unregisterEffect(effect->id());
6171            }
6172        }
6173    }
6174    return;
6175}
6176
6177// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
6178AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
6179{
6180    return mPlaybackThreads.valueFor(output).get();
6181}
6182
6183// checkMixerThread_l() must be called with AudioFlinger::mLock held
6184AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
6185{
6186    PlaybackThread *thread = checkPlaybackThread_l(output);
6187    return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
6188}
6189
6190// checkRecordThread_l() must be called with AudioFlinger::mLock held
6191AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
6192{
6193    return mRecordThreads.valueFor(input).get();
6194}
6195
6196uint32_t AudioFlinger::nextUniqueId()
6197{
6198    return android_atomic_inc(&mNextUniqueId);
6199}
6200
6201AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
6202{
6203    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6204        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
6205        AudioStreamOut *output = thread->getOutput();
6206        if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
6207            return thread;
6208        }
6209    }
6210    return NULL;
6211}
6212
6213uint32_t AudioFlinger::primaryOutputDevice_l() const
6214{
6215    PlaybackThread *thread = primaryPlaybackThread_l();
6216
6217    if (thread == NULL) {
6218        return 0;
6219    }
6220
6221    return thread->device();
6222}
6223
6224sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
6225                                    int triggerSession,
6226                                    int listenerSession,
6227                                    sync_event_callback_t callBack,
6228                                    void *cookie)
6229{
6230    Mutex::Autolock _l(mLock);
6231
6232    sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
6233    status_t playStatus = NAME_NOT_FOUND;
6234    status_t recStatus = NAME_NOT_FOUND;
6235    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6236        playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
6237        if (playStatus == NO_ERROR) {
6238            return event;
6239        }
6240    }
6241    for (size_t i = 0; i < mRecordThreads.size(); i++) {
6242        recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
6243        if (recStatus == NO_ERROR) {
6244            return event;
6245        }
6246    }
6247    if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
6248        mPendingSyncEvents.add(event);
6249    } else {
6250        ALOGV("createSyncEvent() invalid event %d", event->type());
6251        event.clear();
6252    }
6253    return event;
6254}
6255
6256// ----------------------------------------------------------------------------
6257//  Effect management
6258// ----------------------------------------------------------------------------
6259
6260
6261status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
6262{
6263    Mutex::Autolock _l(mLock);
6264    return EffectQueryNumberEffects(numEffects);
6265}
6266
6267status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
6268{
6269    Mutex::Autolock _l(mLock);
6270    return EffectQueryEffect(index, descriptor);
6271}
6272
6273status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
6274        effect_descriptor_t *descriptor) const
6275{
6276    Mutex::Autolock _l(mLock);
6277    return EffectGetDescriptor(pUuid, descriptor);
6278}
6279
6280
6281sp<IEffect> AudioFlinger::createEffect(pid_t pid,
6282        effect_descriptor_t *pDesc,
6283        const sp<IEffectClient>& effectClient,
6284        int32_t priority,
6285        audio_io_handle_t io,
6286        int sessionId,
6287        status_t *status,
6288        int *id,
6289        int *enabled)
6290{
6291    status_t lStatus = NO_ERROR;
6292    sp<EffectHandle> handle;
6293    effect_descriptor_t desc;
6294
6295    ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
6296            pid, effectClient.get(), priority, sessionId, io);
6297
6298    if (pDesc == NULL) {
6299        lStatus = BAD_VALUE;
6300        goto Exit;
6301    }
6302
6303    // check audio settings permission for global effects
6304    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
6305        lStatus = PERMISSION_DENIED;
6306        goto Exit;
6307    }
6308
6309    // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
6310    // that can only be created by audio policy manager (running in same process)
6311    if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
6312        lStatus = PERMISSION_DENIED;
6313        goto Exit;
6314    }
6315
6316    if (io == 0) {
6317        if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
6318            // output must be specified by AudioPolicyManager when using session
6319            // AUDIO_SESSION_OUTPUT_STAGE
6320            lStatus = BAD_VALUE;
6321            goto Exit;
6322        } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
6323            // if the output returned by getOutputForEffect() is removed before we lock the
6324            // mutex below, the call to checkPlaybackThread_l(io) below will detect it
6325            // and we will exit safely
6326            io = AudioSystem::getOutputForEffect(&desc);
6327        }
6328    }
6329
6330    {
6331        Mutex::Autolock _l(mLock);
6332
6333
6334        if (!EffectIsNullUuid(&pDesc->uuid)) {
6335            // if uuid is specified, request effect descriptor
6336            lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
6337            if (lStatus < 0) {
6338                ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
6339                goto Exit;
6340            }
6341        } else {
6342            // if uuid is not specified, look for an available implementation
6343            // of the required type in effect factory
6344            if (EffectIsNullUuid(&pDesc->type)) {
6345                ALOGW("createEffect() no effect type");
6346                lStatus = BAD_VALUE;
6347                goto Exit;
6348            }
6349            uint32_t numEffects = 0;
6350            effect_descriptor_t d;
6351            d.flags = 0; // prevent compiler warning
6352            bool found = false;
6353
6354            lStatus = EffectQueryNumberEffects(&numEffects);
6355            if (lStatus < 0) {
6356                ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
6357                goto Exit;
6358            }
6359            for (uint32_t i = 0; i < numEffects; i++) {
6360                lStatus = EffectQueryEffect(i, &desc);
6361                if (lStatus < 0) {
6362                    ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
6363                    continue;
6364                }
6365                if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
6366                    // If matching type found save effect descriptor. If the session is
6367                    // 0 and the effect is not auxiliary, continue enumeration in case
6368                    // an auxiliary version of this effect type is available
6369                    found = true;
6370                    memcpy(&d, &desc, sizeof(effect_descriptor_t));
6371                    if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
6372                            (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6373                        break;
6374                    }
6375                }
6376            }
6377            if (!found) {
6378                lStatus = BAD_VALUE;
6379                ALOGW("createEffect() effect not found");
6380                goto Exit;
6381            }
6382            // For same effect type, chose auxiliary version over insert version if
6383            // connect to output mix (Compliance to OpenSL ES)
6384            if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
6385                    (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6386                memcpy(&desc, &d, sizeof(effect_descriptor_t));
6387            }
6388        }
6389
6390        // Do not allow auxiliary effects on a session different from 0 (output mix)
6391        if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
6392             (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6393            lStatus = INVALID_OPERATION;
6394            goto Exit;
6395        }
6396
6397        // check recording permission for visualizer
6398        if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6399            !recordingAllowed()) {
6400            lStatus = PERMISSION_DENIED;
6401            goto Exit;
6402        }
6403
6404        // return effect descriptor
6405        memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6406
6407        // If output is not specified try to find a matching audio session ID in one of the
6408        // output threads.
6409        // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6410        // because of code checking output when entering the function.
6411        // Note: io is never 0 when creating an effect on an input
6412        if (io == 0) {
6413            // look for the thread where the specified audio session is present
6414            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6415                if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6416                    io = mPlaybackThreads.keyAt(i);
6417                    break;
6418                }
6419            }
6420            if (io == 0) {
6421                for (size_t i = 0; i < mRecordThreads.size(); i++) {
6422                    if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6423                        io = mRecordThreads.keyAt(i);
6424                        break;
6425                    }
6426                }
6427            }
6428            // If no output thread contains the requested session ID, default to
6429            // first output. The effect chain will be moved to the correct output
6430            // thread when a track with the same session ID is created
6431            if (io == 0 && mPlaybackThreads.size()) {
6432                io = mPlaybackThreads.keyAt(0);
6433            }
6434            ALOGV("createEffect() got io %d for effect %s", io, desc.name);
6435        }
6436        ThreadBase *thread = checkRecordThread_l(io);
6437        if (thread == NULL) {
6438            thread = checkPlaybackThread_l(io);
6439            if (thread == NULL) {
6440                ALOGE("createEffect() unknown output thread");
6441                lStatus = BAD_VALUE;
6442                goto Exit;
6443            }
6444        }
6445
6446        sp<Client> client = registerPid_l(pid);
6447
6448        // create effect on selected output thread
6449        handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6450                &desc, enabled, &lStatus);
6451        if (handle != 0 && id != NULL) {
6452            *id = handle->id();
6453        }
6454    }
6455
6456Exit:
6457    if (status != NULL) {
6458        *status = lStatus;
6459    }
6460    return handle;
6461}
6462
6463status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6464        audio_io_handle_t dstOutput)
6465{
6466    ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
6467            sessionId, srcOutput, dstOutput);
6468    Mutex::Autolock _l(mLock);
6469    if (srcOutput == dstOutput) {
6470        ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
6471        return NO_ERROR;
6472    }
6473    PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6474    if (srcThread == NULL) {
6475        ALOGW("moveEffects() bad srcOutput %d", srcOutput);
6476        return BAD_VALUE;
6477    }
6478    PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6479    if (dstThread == NULL) {
6480        ALOGW("moveEffects() bad dstOutput %d", dstOutput);
6481        return BAD_VALUE;
6482    }
6483
6484    Mutex::Autolock _dl(dstThread->mLock);
6485    Mutex::Autolock _sl(srcThread->mLock);
6486    moveEffectChain_l(sessionId, srcThread, dstThread, false);
6487
6488    return NO_ERROR;
6489}
6490
6491// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
6492status_t AudioFlinger::moveEffectChain_l(int sessionId,
6493                                   AudioFlinger::PlaybackThread *srcThread,
6494                                   AudioFlinger::PlaybackThread *dstThread,
6495                                   bool reRegister)
6496{
6497    ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
6498            sessionId, srcThread, dstThread);
6499
6500    sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
6501    if (chain == 0) {
6502        ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
6503                sessionId, srcThread);
6504        return INVALID_OPERATION;
6505    }
6506
6507    // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
6508    // so that a new chain is created with correct parameters when first effect is added. This is
6509    // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
6510    // removed.
6511    srcThread->removeEffectChain_l(chain);
6512
6513    // transfer all effects one by one so that new effect chain is created on new thread with
6514    // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
6515    audio_io_handle_t dstOutput = dstThread->id();
6516    sp<EffectChain> dstChain;
6517    uint32_t strategy = 0; // prevent compiler warning
6518    sp<EffectModule> effect = chain->getEffectFromId_l(0);
6519    while (effect != 0) {
6520        srcThread->removeEffect_l(effect);
6521        dstThread->addEffect_l(effect);
6522        // removeEffect_l() has stopped the effect if it was active so it must be restarted
6523        if (effect->state() == EffectModule::ACTIVE ||
6524                effect->state() == EffectModule::STOPPING) {
6525            effect->start();
6526        }
6527        // if the move request is not received from audio policy manager, the effect must be
6528        // re-registered with the new strategy and output
6529        if (dstChain == 0) {
6530            dstChain = effect->chain().promote();
6531            if (dstChain == 0) {
6532                ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
6533                srcThread->addEffect_l(effect);
6534                return NO_INIT;
6535            }
6536            strategy = dstChain->strategy();
6537        }
6538        if (reRegister) {
6539            AudioSystem::unregisterEffect(effect->id());
6540            AudioSystem::registerEffect(&effect->desc(),
6541                                        dstOutput,
6542                                        strategy,
6543                                        sessionId,
6544                                        effect->id());
6545        }
6546        effect = chain->getEffectFromId_l(0);
6547    }
6548
6549    return NO_ERROR;
6550}
6551
6552
6553// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
6554sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
6555        const sp<AudioFlinger::Client>& client,
6556        const sp<IEffectClient>& effectClient,
6557        int32_t priority,
6558        int sessionId,
6559        effect_descriptor_t *desc,
6560        int *enabled,
6561        status_t *status
6562        )
6563{
6564    sp<EffectModule> effect;
6565    sp<EffectHandle> handle;
6566    status_t lStatus;
6567    sp<EffectChain> chain;
6568    bool chainCreated = false;
6569    bool effectCreated = false;
6570    bool effectRegistered = false;
6571
6572    lStatus = initCheck();
6573    if (lStatus != NO_ERROR) {
6574        ALOGW("createEffect_l() Audio driver not initialized.");
6575        goto Exit;
6576    }
6577
6578    // Do not allow effects with session ID 0 on direct output or duplicating threads
6579    // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
6580    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
6581        ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
6582                desc->name, sessionId);
6583        lStatus = BAD_VALUE;
6584        goto Exit;
6585    }
6586    // Only Pre processor effects are allowed on input threads and only on input threads
6587    if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
6588        ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
6589                desc->name, desc->flags, mType);
6590        lStatus = BAD_VALUE;
6591        goto Exit;
6592    }
6593
6594    ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
6595
6596    { // scope for mLock
6597        Mutex::Autolock _l(mLock);
6598
6599        // check for existing effect chain with the requested audio session
6600        chain = getEffectChain_l(sessionId);
6601        if (chain == 0) {
6602            // create a new chain for this session
6603            ALOGV("createEffect_l() new effect chain for session %d", sessionId);
6604            chain = new EffectChain(this, sessionId);
6605            addEffectChain_l(chain);
6606            chain->setStrategy(getStrategyForSession_l(sessionId));
6607            chainCreated = true;
6608        } else {
6609            effect = chain->getEffectFromDesc_l(desc);
6610        }
6611
6612        ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
6613
6614        if (effect == 0) {
6615            int id = mAudioFlinger->nextUniqueId();
6616            // Check CPU and memory usage
6617            lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
6618            if (lStatus != NO_ERROR) {
6619                goto Exit;
6620            }
6621            effectRegistered = true;
6622            // create a new effect module if none present in the chain
6623            effect = new EffectModule(this, chain, desc, id, sessionId);
6624            lStatus = effect->status();
6625            if (lStatus != NO_ERROR) {
6626                goto Exit;
6627            }
6628            lStatus = chain->addEffect_l(effect);
6629            if (lStatus != NO_ERROR) {
6630                goto Exit;
6631            }
6632            effectCreated = true;
6633
6634            effect->setDevice(mDevice);
6635            effect->setMode(mAudioFlinger->getMode());
6636        }
6637        // create effect handle and connect it to effect module
6638        handle = new EffectHandle(effect, client, effectClient, priority);
6639        lStatus = effect->addHandle(handle);
6640        if (enabled != NULL) {
6641            *enabled = (int)effect->isEnabled();
6642        }
6643    }
6644
6645Exit:
6646    if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
6647        Mutex::Autolock _l(mLock);
6648        if (effectCreated) {
6649            chain->removeEffect_l(effect);
6650        }
6651        if (effectRegistered) {
6652            AudioSystem::unregisterEffect(effect->id());
6653        }
6654        if (chainCreated) {
6655            removeEffectChain_l(chain);
6656        }
6657        handle.clear();
6658    }
6659
6660    if (status != NULL) {
6661        *status = lStatus;
6662    }
6663    return handle;
6664}
6665
6666sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6667{
6668    sp<EffectChain> chain = getEffectChain_l(sessionId);
6669    return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
6670}
6671
6672// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6673// PlaybackThread::mLock held
6674status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
6675{
6676    // check for existing effect chain with the requested audio session
6677    int sessionId = effect->sessionId();
6678    sp<EffectChain> chain = getEffectChain_l(sessionId);
6679    bool chainCreated = false;
6680
6681    if (chain == 0) {
6682        // create a new chain for this session
6683        ALOGV("addEffect_l() new effect chain for session %d", sessionId);
6684        chain = new EffectChain(this, sessionId);
6685        addEffectChain_l(chain);
6686        chain->setStrategy(getStrategyForSession_l(sessionId));
6687        chainCreated = true;
6688    }
6689    ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
6690
6691    if (chain->getEffectFromId_l(effect->id()) != 0) {
6692        ALOGW("addEffect_l() %p effect %s already present in chain %p",
6693                this, effect->desc().name, chain.get());
6694        return BAD_VALUE;
6695    }
6696
6697    status_t status = chain->addEffect_l(effect);
6698    if (status != NO_ERROR) {
6699        if (chainCreated) {
6700            removeEffectChain_l(chain);
6701        }
6702        return status;
6703    }
6704
6705    effect->setDevice(mDevice);
6706    effect->setMode(mAudioFlinger->getMode());
6707    return NO_ERROR;
6708}
6709
6710void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
6711
6712    ALOGV("removeEffect_l() %p effect %p", this, effect.get());
6713    effect_descriptor_t desc = effect->desc();
6714    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6715        detachAuxEffect_l(effect->id());
6716    }
6717
6718    sp<EffectChain> chain = effect->chain().promote();
6719    if (chain != 0) {
6720        // remove effect chain if removing last effect
6721        if (chain->removeEffect_l(effect) == 0) {
6722            removeEffectChain_l(chain);
6723        }
6724    } else {
6725        ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
6726    }
6727}
6728
6729void AudioFlinger::ThreadBase::lockEffectChains_l(
6730        Vector< sp<AudioFlinger::EffectChain> >& effectChains)
6731{
6732    effectChains = mEffectChains;
6733    for (size_t i = 0; i < mEffectChains.size(); i++) {
6734        mEffectChains[i]->lock();
6735    }
6736}
6737
6738void AudioFlinger::ThreadBase::unlockEffectChains(
6739        const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
6740{
6741    for (size_t i = 0; i < effectChains.size(); i++) {
6742        effectChains[i]->unlock();
6743    }
6744}
6745
6746sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6747{
6748    Mutex::Autolock _l(mLock);
6749    return getEffectChain_l(sessionId);
6750}
6751
6752sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6753{
6754    size_t size = mEffectChains.size();
6755    for (size_t i = 0; i < size; i++) {
6756        if (mEffectChains[i]->sessionId() == sessionId) {
6757            return mEffectChains[i];
6758        }
6759    }
6760    return 0;
6761}
6762
6763void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
6764{
6765    Mutex::Autolock _l(mLock);
6766    size_t size = mEffectChains.size();
6767    for (size_t i = 0; i < size; i++) {
6768        mEffectChains[i]->setMode_l(mode);
6769    }
6770}
6771
6772void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
6773                                                    const wp<EffectHandle>& handle,
6774                                                    bool unpinIfLast) {
6775
6776    Mutex::Autolock _l(mLock);
6777    ALOGV("disconnectEffect() %p effect %p", this, effect.get());
6778    // delete the effect module if removing last handle on it
6779    if (effect->removeHandle(handle) == 0) {
6780        if (!effect->isPinned() || unpinIfLast) {
6781            removeEffect_l(effect);
6782            AudioSystem::unregisterEffect(effect->id());
6783        }
6784    }
6785}
6786
6787status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6788{
6789    int session = chain->sessionId();
6790    int16_t *buffer = mMixBuffer;
6791    bool ownsBuffer = false;
6792
6793    ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
6794    if (session > 0) {
6795        // Only one effect chain can be present in direct output thread and it uses
6796        // the mix buffer as input
6797        if (mType != DIRECT) {
6798            size_t numSamples = mFrameCount * mChannelCount;
6799            buffer = new int16_t[numSamples];
6800            memset(buffer, 0, numSamples * sizeof(int16_t));
6801            ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
6802            ownsBuffer = true;
6803        }
6804
6805        // Attach all tracks with same session ID to this chain.
6806        for (size_t i = 0; i < mTracks.size(); ++i) {
6807            sp<Track> track = mTracks[i];
6808            if (session == track->sessionId()) {
6809                ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
6810                track->setMainBuffer(buffer);
6811                chain->incTrackCnt();
6812            }
6813        }
6814
6815        // indicate all active tracks in the chain
6816        for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6817            sp<Track> track = mActiveTracks[i].promote();
6818            if (track == 0) continue;
6819            if (session == track->sessionId()) {
6820                ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
6821                chain->incActiveTrackCnt();
6822            }
6823        }
6824    }
6825
6826    chain->setInBuffer(buffer, ownsBuffer);
6827    chain->setOutBuffer(mMixBuffer);
6828    // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
6829    // chains list in order to be processed last as it contains output stage effects
6830    // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6831    // session AUDIO_SESSION_OUTPUT_STAGE to be processed
6832    // after track specific effects and before output stage
6833    // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6834    // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
6835    // Effect chain for other sessions are inserted at beginning of effect
6836    // chains list to be processed before output mix effects. Relative order between other
6837    // sessions is not important
6838    size_t size = mEffectChains.size();
6839    size_t i = 0;
6840    for (i = 0; i < size; i++) {
6841        if (mEffectChains[i]->sessionId() < session) break;
6842    }
6843    mEffectChains.insertAt(chain, i);
6844    checkSuspendOnAddEffectChain_l(chain);
6845
6846    return NO_ERROR;
6847}
6848
6849size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6850{
6851    int session = chain->sessionId();
6852
6853    ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
6854
6855    for (size_t i = 0; i < mEffectChains.size(); i++) {
6856        if (chain == mEffectChains[i]) {
6857            mEffectChains.removeAt(i);
6858            // detach all active tracks from the chain
6859            for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6860                sp<Track> track = mActiveTracks[i].promote();
6861                if (track == 0) continue;
6862                if (session == track->sessionId()) {
6863                    ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
6864                            chain.get(), session);
6865                    chain->decActiveTrackCnt();
6866                }
6867            }
6868
6869            // detach all tracks with same session ID from this chain
6870            for (size_t i = 0; i < mTracks.size(); ++i) {
6871                sp<Track> track = mTracks[i];
6872                if (session == track->sessionId()) {
6873                    track->setMainBuffer(mMixBuffer);
6874                    chain->decTrackCnt();
6875                }
6876            }
6877            break;
6878        }
6879    }
6880    return mEffectChains.size();
6881}
6882
6883status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6884        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
6885{
6886    Mutex::Autolock _l(mLock);
6887    return attachAuxEffect_l(track, EffectId);
6888}
6889
6890status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6891        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
6892{
6893    status_t status = NO_ERROR;
6894
6895    if (EffectId == 0) {
6896        track->setAuxBuffer(0, NULL);
6897    } else {
6898        // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6899        sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
6900        if (effect != 0) {
6901            if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6902                track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6903            } else {
6904                status = INVALID_OPERATION;
6905            }
6906        } else {
6907            status = BAD_VALUE;
6908        }
6909    }
6910    return status;
6911}
6912
6913void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6914{
6915    for (size_t i = 0; i < mTracks.size(); ++i) {
6916        sp<Track> track = mTracks[i];
6917        if (track->auxEffectId() == effectId) {
6918            attachAuxEffect_l(track, 0);
6919        }
6920    }
6921}
6922
6923status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6924{
6925    // only one chain per input thread
6926    if (mEffectChains.size() != 0) {
6927        return INVALID_OPERATION;
6928    }
6929    ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
6930
6931    chain->setInBuffer(NULL);
6932    chain->setOutBuffer(NULL);
6933
6934    checkSuspendOnAddEffectChain_l(chain);
6935
6936    mEffectChains.add(chain);
6937
6938    return NO_ERROR;
6939}
6940
6941size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6942{
6943    ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6944    ALOGW_IF(mEffectChains.size() != 1,
6945            "removeEffectChain_l() %p invalid chain size %d on thread %p",
6946            chain.get(), mEffectChains.size(), this);
6947    if (mEffectChains.size() == 1) {
6948        mEffectChains.removeAt(0);
6949    }
6950    return 0;
6951}
6952
6953// ----------------------------------------------------------------------------
6954//  EffectModule implementation
6955// ----------------------------------------------------------------------------
6956
6957#undef LOG_TAG
6958#define LOG_TAG "AudioFlinger::EffectModule"
6959
6960AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
6961                                        const wp<AudioFlinger::EffectChain>& chain,
6962                                        effect_descriptor_t *desc,
6963                                        int id,
6964                                        int sessionId)
6965    : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
6966      mStatus(NO_INIT), mState(IDLE), mSuspended(false)
6967{
6968    ALOGV("Constructor %p", this);
6969    int lStatus;
6970    if (thread == NULL) {
6971        return;
6972    }
6973
6974    memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6975
6976    // create effect engine from effect factory
6977    mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
6978
6979    if (mStatus != NO_ERROR) {
6980        return;
6981    }
6982    lStatus = init();
6983    if (lStatus < 0) {
6984        mStatus = lStatus;
6985        goto Error;
6986    }
6987
6988    if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6989        mPinned = true;
6990    }
6991    ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
6992    return;
6993Error:
6994    EffectRelease(mEffectInterface);
6995    mEffectInterface = NULL;
6996    ALOGV("Constructor Error %d", mStatus);
6997}
6998
6999AudioFlinger::EffectModule::~EffectModule()
7000{
7001    ALOGV("Destructor %p", this);
7002    if (mEffectInterface != NULL) {
7003        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7004                (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7005            sp<ThreadBase> thread = mThread.promote();
7006            if (thread != 0) {
7007                audio_stream_t *stream = thread->stream();
7008                if (stream != NULL) {
7009                    stream->remove_audio_effect(stream, mEffectInterface);
7010                }
7011            }
7012        }
7013        // release effect engine
7014        EffectRelease(mEffectInterface);
7015    }
7016}
7017
7018status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
7019{
7020    status_t status;
7021
7022    Mutex::Autolock _l(mLock);
7023    int priority = handle->priority();
7024    size_t size = mHandles.size();
7025    sp<EffectHandle> h;
7026    size_t i;
7027    for (i = 0; i < size; i++) {
7028        h = mHandles[i].promote();
7029        if (h == 0) continue;
7030        if (h->priority() <= priority) break;
7031    }
7032    // if inserted in first place, move effect control from previous owner to this handle
7033    if (i == 0) {
7034        bool enabled = false;
7035        if (h != 0) {
7036            enabled = h->enabled();
7037            h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
7038        }
7039        handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
7040        status = NO_ERROR;
7041    } else {
7042        status = ALREADY_EXISTS;
7043    }
7044    ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
7045    mHandles.insertAt(handle, i);
7046    return status;
7047}
7048
7049size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7050{
7051    Mutex::Autolock _l(mLock);
7052    size_t size = mHandles.size();
7053    size_t i;
7054    for (i = 0; i < size; i++) {
7055        if (mHandles[i] == handle) break;
7056    }
7057    if (i == size) {
7058        return size;
7059    }
7060    ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
7061
7062    bool enabled = false;
7063    EffectHandle *hdl = handle.unsafe_get();
7064    if (hdl != NULL) {
7065        ALOGV("removeHandle() unsafe_get OK");
7066        enabled = hdl->enabled();
7067    }
7068    mHandles.removeAt(i);
7069    size = mHandles.size();
7070    // if removed from first place, move effect control from this handle to next in line
7071    if (i == 0 && size != 0) {
7072        sp<EffectHandle> h = mHandles[0].promote();
7073        if (h != 0) {
7074            h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
7075        }
7076    }
7077
7078    // Prevent calls to process() and other functions on effect interface from now on.
7079    // The effect engine will be released by the destructor when the last strong reference on
7080    // this object is released which can happen after next process is called.
7081    if (size == 0 && !mPinned) {
7082        mState = DESTROYED;
7083    }
7084
7085    return size;
7086}
7087
7088sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7089{
7090    Mutex::Autolock _l(mLock);
7091    return mHandles.size() != 0 ? mHandles[0].promote() : 0;
7092}
7093
7094void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
7095{
7096    ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
7097    // keep a strong reference on this EffectModule to avoid calling the
7098    // destructor before we exit
7099    sp<EffectModule> keep(this);
7100    {
7101        sp<ThreadBase> thread = mThread.promote();
7102        if (thread != 0) {
7103            thread->disconnectEffect(keep, handle, unpinIfLast);
7104        }
7105    }
7106}
7107
7108void AudioFlinger::EffectModule::updateState() {
7109    Mutex::Autolock _l(mLock);
7110
7111    switch (mState) {
7112    case RESTART:
7113        reset_l();
7114        // FALL THROUGH
7115
7116    case STARTING:
7117        // clear auxiliary effect input buffer for next accumulation
7118        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7119            memset(mConfig.inputCfg.buffer.raw,
7120                   0,
7121                   mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7122        }
7123        start_l();
7124        mState = ACTIVE;
7125        break;
7126    case STOPPING:
7127        stop_l();
7128        mDisableWaitCnt = mMaxDisableWaitCnt;
7129        mState = STOPPED;
7130        break;
7131    case STOPPED:
7132        // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7133        // turn off sequence.
7134        if (--mDisableWaitCnt == 0) {
7135            reset_l();
7136            mState = IDLE;
7137        }
7138        break;
7139    default: //IDLE , ACTIVE, DESTROYED
7140        break;
7141    }
7142}
7143
7144void AudioFlinger::EffectModule::process()
7145{
7146    Mutex::Autolock _l(mLock);
7147
7148    if (mState == DESTROYED || mEffectInterface == NULL ||
7149            mConfig.inputCfg.buffer.raw == NULL ||
7150            mConfig.outputCfg.buffer.raw == NULL) {
7151        return;
7152    }
7153
7154    if (isProcessEnabled()) {
7155        // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7156        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7157            ditherAndClamp(mConfig.inputCfg.buffer.s32,
7158                                        mConfig.inputCfg.buffer.s32,
7159                                        mConfig.inputCfg.buffer.frameCount/2);
7160        }
7161
7162        // do the actual processing in the effect engine
7163        int ret = (*mEffectInterface)->process(mEffectInterface,
7164                                               &mConfig.inputCfg.buffer,
7165                                               &mConfig.outputCfg.buffer);
7166
7167        // force transition to IDLE state when engine is ready
7168        if (mState == STOPPED && ret == -ENODATA) {
7169            mDisableWaitCnt = 1;
7170        }
7171
7172        // clear auxiliary effect input buffer for next accumulation
7173        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7174            memset(mConfig.inputCfg.buffer.raw, 0,
7175                   mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7176        }
7177    } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
7178                mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7179        // If an insert effect is idle and input buffer is different from output buffer,
7180        // accumulate input onto output
7181        sp<EffectChain> chain = mChain.promote();
7182        if (chain != 0 && chain->activeTrackCnt() != 0) {
7183            size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2;  //always stereo here
7184            int16_t *in = mConfig.inputCfg.buffer.s16;
7185            int16_t *out = mConfig.outputCfg.buffer.s16;
7186            for (size_t i = 0; i < frameCnt; i++) {
7187                out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
7188            }
7189        }
7190    }
7191}
7192
7193void AudioFlinger::EffectModule::reset_l()
7194{
7195    if (mEffectInterface == NULL) {
7196        return;
7197    }
7198    (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
7199}
7200
7201status_t AudioFlinger::EffectModule::configure()
7202{
7203    uint32_t channels;
7204    if (mEffectInterface == NULL) {
7205        return NO_INIT;
7206    }
7207
7208    sp<ThreadBase> thread = mThread.promote();
7209    if (thread == 0) {
7210        return DEAD_OBJECT;
7211    }
7212
7213    // TODO: handle configuration of effects replacing track process
7214    if (thread->channelCount() == 1) {
7215        channels = AUDIO_CHANNEL_OUT_MONO;
7216    } else {
7217        channels = AUDIO_CHANNEL_OUT_STEREO;
7218    }
7219
7220    if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7221        mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
7222    } else {
7223        mConfig.inputCfg.channels = channels;
7224    }
7225    mConfig.outputCfg.channels = channels;
7226    mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7227    mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7228    mConfig.inputCfg.samplingRate = thread->sampleRate();
7229    mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
7230    mConfig.inputCfg.bufferProvider.cookie = NULL;
7231    mConfig.inputCfg.bufferProvider.getBuffer = NULL;
7232    mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
7233    mConfig.outputCfg.bufferProvider.cookie = NULL;
7234    mConfig.outputCfg.bufferProvider.getBuffer = NULL;
7235    mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
7236    mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
7237    // Insert effect:
7238    // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
7239    // always overwrites output buffer: input buffer == output buffer
7240    // - in other sessions:
7241    //      last effect in the chain accumulates in output buffer: input buffer != output buffer
7242    //      other effect: overwrites output buffer: input buffer == output buffer
7243    // Auxiliary effect:
7244    //      accumulates in output buffer: input buffer != output buffer
7245    // Therefore: accumulate <=> input buffer != output buffer
7246    if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7247        mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
7248    } else {
7249        mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
7250    }
7251    mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
7252    mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
7253    mConfig.inputCfg.buffer.frameCount = thread->frameCount();
7254    mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
7255
7256    ALOGV("configure() %p thread %p buffer %p framecount %d",
7257            this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
7258
7259    status_t cmdStatus;
7260    uint32_t size = sizeof(int);
7261    status_t status = (*mEffectInterface)->command(mEffectInterface,
7262                                                   EFFECT_CMD_SET_CONFIG,
7263                                                   sizeof(effect_config_t),
7264                                                   &mConfig,
7265                                                   &size,
7266                                                   &cmdStatus);
7267    if (status == 0) {
7268        status = cmdStatus;
7269    }
7270
7271    mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
7272            (1000 * mConfig.outputCfg.buffer.frameCount);
7273
7274    return status;
7275}
7276
7277status_t AudioFlinger::EffectModule::init()
7278{
7279    Mutex::Autolock _l(mLock);
7280    if (mEffectInterface == NULL) {
7281        return NO_INIT;
7282    }
7283    status_t cmdStatus;
7284    uint32_t size = sizeof(status_t);
7285    status_t status = (*mEffectInterface)->command(mEffectInterface,
7286                                                   EFFECT_CMD_INIT,
7287                                                   0,
7288                                                   NULL,
7289                                                   &size,
7290                                                   &cmdStatus);
7291    if (status == 0) {
7292        status = cmdStatus;
7293    }
7294    return status;
7295}
7296
7297status_t AudioFlinger::EffectModule::start()
7298{
7299    Mutex::Autolock _l(mLock);
7300    return start_l();
7301}
7302
7303status_t AudioFlinger::EffectModule::start_l()
7304{
7305    if (mEffectInterface == NULL) {
7306        return NO_INIT;
7307    }
7308    status_t cmdStatus;
7309    uint32_t size = sizeof(status_t);
7310    status_t status = (*mEffectInterface)->command(mEffectInterface,
7311                                                   EFFECT_CMD_ENABLE,
7312                                                   0,
7313                                                   NULL,
7314                                                   &size,
7315                                                   &cmdStatus);
7316    if (status == 0) {
7317        status = cmdStatus;
7318    }
7319    if (status == 0 &&
7320            ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7321             (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7322        sp<ThreadBase> thread = mThread.promote();
7323        if (thread != 0) {
7324            audio_stream_t *stream = thread->stream();
7325            if (stream != NULL) {
7326                stream->add_audio_effect(stream, mEffectInterface);
7327            }
7328        }
7329    }
7330    return status;
7331}
7332
7333status_t AudioFlinger::EffectModule::stop()
7334{
7335    Mutex::Autolock _l(mLock);
7336    return stop_l();
7337}
7338
7339status_t AudioFlinger::EffectModule::stop_l()
7340{
7341    if (mEffectInterface == NULL) {
7342        return NO_INIT;
7343    }
7344    status_t cmdStatus;
7345    uint32_t size = sizeof(status_t);
7346    status_t status = (*mEffectInterface)->command(mEffectInterface,
7347                                                   EFFECT_CMD_DISABLE,
7348                                                   0,
7349                                                   NULL,
7350                                                   &size,
7351                                                   &cmdStatus);
7352    if (status == 0) {
7353        status = cmdStatus;
7354    }
7355    if (status == 0 &&
7356            ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7357             (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7358        sp<ThreadBase> thread = mThread.promote();
7359        if (thread != 0) {
7360            audio_stream_t *stream = thread->stream();
7361            if (stream != NULL) {
7362                stream->remove_audio_effect(stream, mEffectInterface);
7363            }
7364        }
7365    }
7366    return status;
7367}
7368
7369status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7370                                             uint32_t cmdSize,
7371                                             void *pCmdData,
7372                                             uint32_t *replySize,
7373                                             void *pReplyData)
7374{
7375    Mutex::Autolock _l(mLock);
7376//    ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
7377
7378    if (mState == DESTROYED || mEffectInterface == NULL) {
7379        return NO_INIT;
7380    }
7381    status_t status = (*mEffectInterface)->command(mEffectInterface,
7382                                                   cmdCode,
7383                                                   cmdSize,
7384                                                   pCmdData,
7385                                                   replySize,
7386                                                   pReplyData);
7387    if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
7388        uint32_t size = (replySize == NULL) ? 0 : *replySize;
7389        for (size_t i = 1; i < mHandles.size(); i++) {
7390            sp<EffectHandle> h = mHandles[i].promote();
7391            if (h != 0) {
7392                h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7393            }
7394        }
7395    }
7396    return status;
7397}
7398
7399status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7400{
7401
7402    Mutex::Autolock _l(mLock);
7403    ALOGV("setEnabled %p enabled %d", this, enabled);
7404
7405    if (enabled != isEnabled()) {
7406        status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7407        if (enabled && status != NO_ERROR) {
7408            return status;
7409        }
7410
7411        switch (mState) {
7412        // going from disabled to enabled
7413        case IDLE:
7414            mState = STARTING;
7415            break;
7416        case STOPPED:
7417            mState = RESTART;
7418            break;
7419        case STOPPING:
7420            mState = ACTIVE;
7421            break;
7422
7423        // going from enabled to disabled
7424        case RESTART:
7425            mState = STOPPED;
7426            break;
7427        case STARTING:
7428            mState = IDLE;
7429            break;
7430        case ACTIVE:
7431            mState = STOPPING;
7432            break;
7433        case DESTROYED:
7434            return NO_ERROR; // simply ignore as we are being destroyed
7435        }
7436        for (size_t i = 1; i < mHandles.size(); i++) {
7437            sp<EffectHandle> h = mHandles[i].promote();
7438            if (h != 0) {
7439                h->setEnabled(enabled);
7440            }
7441        }
7442    }
7443    return NO_ERROR;
7444}
7445
7446bool AudioFlinger::EffectModule::isEnabled() const
7447{
7448    switch (mState) {
7449    case RESTART:
7450    case STARTING:
7451    case ACTIVE:
7452        return true;
7453    case IDLE:
7454    case STOPPING:
7455    case STOPPED:
7456    case DESTROYED:
7457    default:
7458        return false;
7459    }
7460}
7461
7462bool AudioFlinger::EffectModule::isProcessEnabled() const
7463{
7464    switch (mState) {
7465    case RESTART:
7466    case ACTIVE:
7467    case STOPPING:
7468    case STOPPED:
7469        return true;
7470    case IDLE:
7471    case STARTING:
7472    case DESTROYED:
7473    default:
7474        return false;
7475    }
7476}
7477
7478status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7479{
7480    Mutex::Autolock _l(mLock);
7481    status_t status = NO_ERROR;
7482
7483    // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7484    // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
7485    if (isProcessEnabled() &&
7486            ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7487            (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
7488        status_t cmdStatus;
7489        uint32_t volume[2];
7490        uint32_t *pVolume = NULL;
7491        uint32_t size = sizeof(volume);
7492        volume[0] = *left;
7493        volume[1] = *right;
7494        if (controller) {
7495            pVolume = volume;
7496        }
7497        status = (*mEffectInterface)->command(mEffectInterface,
7498                                              EFFECT_CMD_SET_VOLUME,
7499                                              size,
7500                                              volume,
7501                                              &size,
7502                                              pVolume);
7503        if (controller && status == NO_ERROR && size == sizeof(volume)) {
7504            *left = volume[0];
7505            *right = volume[1];
7506        }
7507    }
7508    return status;
7509}
7510
7511status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7512{
7513    Mutex::Autolock _l(mLock);
7514    status_t status = NO_ERROR;
7515    if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7516        // audio pre processing modules on RecordThread can receive both output and
7517        // input device indication in the same call
7518        uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7519        if (dev) {
7520            status_t cmdStatus;
7521            uint32_t size = sizeof(status_t);
7522
7523            status = (*mEffectInterface)->command(mEffectInterface,
7524                                                  EFFECT_CMD_SET_DEVICE,
7525                                                  sizeof(uint32_t),
7526                                                  &dev,
7527                                                  &size,
7528                                                  &cmdStatus);
7529            if (status == NO_ERROR) {
7530                status = cmdStatus;
7531            }
7532        }
7533        dev = device & AUDIO_DEVICE_IN_ALL;
7534        if (dev) {
7535            status_t cmdStatus;
7536            uint32_t size = sizeof(status_t);
7537
7538            status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7539                                                  EFFECT_CMD_SET_INPUT_DEVICE,
7540                                                  sizeof(uint32_t),
7541                                                  &dev,
7542                                                  &size,
7543                                                  &cmdStatus);
7544            if (status2 == NO_ERROR) {
7545                status2 = cmdStatus;
7546            }
7547            if (status == NO_ERROR) {
7548                status = status2;
7549            }
7550        }
7551    }
7552    return status;
7553}
7554
7555status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
7556{
7557    Mutex::Autolock _l(mLock);
7558    status_t status = NO_ERROR;
7559    if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
7560        status_t cmdStatus;
7561        uint32_t size = sizeof(status_t);
7562        status = (*mEffectInterface)->command(mEffectInterface,
7563                                              EFFECT_CMD_SET_AUDIO_MODE,
7564                                              sizeof(audio_mode_t),
7565                                              &mode,
7566                                              &size,
7567                                              &cmdStatus);
7568        if (status == NO_ERROR) {
7569            status = cmdStatus;
7570        }
7571    }
7572    return status;
7573}
7574
7575void AudioFlinger::EffectModule::setSuspended(bool suspended)
7576{
7577    Mutex::Autolock _l(mLock);
7578    mSuspended = suspended;
7579}
7580
7581bool AudioFlinger::EffectModule::suspended() const
7582{
7583    Mutex::Autolock _l(mLock);
7584    return mSuspended;
7585}
7586
7587status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7588{
7589    const size_t SIZE = 256;
7590    char buffer[SIZE];
7591    String8 result;
7592
7593    snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7594    result.append(buffer);
7595
7596    bool locked = tryLock(mLock);
7597    // failed to lock - AudioFlinger is probably deadlocked
7598    if (!locked) {
7599        result.append("\t\tCould not lock Fx mutex:\n");
7600    }
7601
7602    result.append("\t\tSession Status State Engine:\n");
7603    snprintf(buffer, SIZE, "\t\t%05d   %03d    %03d   0x%08x\n",
7604            mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7605    result.append(buffer);
7606
7607    result.append("\t\tDescriptor:\n");
7608    snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7609            mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7610            mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7611            mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7612    result.append(buffer);
7613    snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7614                mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7615                mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7616                mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7617    result.append(buffer);
7618    snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
7619            mDescriptor.apiVersion,
7620            mDescriptor.flags);
7621    result.append(buffer);
7622    snprintf(buffer, SIZE, "\t\t- name: %s\n",
7623            mDescriptor.name);
7624    result.append(buffer);
7625    snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7626            mDescriptor.implementor);
7627    result.append(buffer);
7628
7629    result.append("\t\t- Input configuration:\n");
7630    result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
7631    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
7632            (uint32_t)mConfig.inputCfg.buffer.raw,
7633            mConfig.inputCfg.buffer.frameCount,
7634            mConfig.inputCfg.samplingRate,
7635            mConfig.inputCfg.channels,
7636            mConfig.inputCfg.format);
7637    result.append(buffer);
7638
7639    result.append("\t\t- Output configuration:\n");
7640    result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
7641    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
7642            (uint32_t)mConfig.outputCfg.buffer.raw,
7643            mConfig.outputCfg.buffer.frameCount,
7644            mConfig.outputCfg.samplingRate,
7645            mConfig.outputCfg.channels,
7646            mConfig.outputCfg.format);
7647    result.append(buffer);
7648
7649    snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7650    result.append(buffer);
7651    result.append("\t\t\tPid   Priority Ctrl Locked client server\n");
7652    for (size_t i = 0; i < mHandles.size(); ++i) {
7653        sp<EffectHandle> handle = mHandles[i].promote();
7654        if (handle != 0) {
7655            handle->dump(buffer, SIZE);
7656            result.append(buffer);
7657        }
7658    }
7659
7660    result.append("\n");
7661
7662    write(fd, result.string(), result.length());
7663
7664    if (locked) {
7665        mLock.unlock();
7666    }
7667
7668    return NO_ERROR;
7669}
7670
7671// ----------------------------------------------------------------------------
7672//  EffectHandle implementation
7673// ----------------------------------------------------------------------------
7674
7675#undef LOG_TAG
7676#define LOG_TAG "AudioFlinger::EffectHandle"
7677
7678AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7679                                        const sp<AudioFlinger::Client>& client,
7680                                        const sp<IEffectClient>& effectClient,
7681                                        int32_t priority)
7682    : BnEffect(),
7683    mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
7684    mPriority(priority), mHasControl(false), mEnabled(false)
7685{
7686    ALOGV("constructor %p", this);
7687
7688    if (client == 0) {
7689        return;
7690    }
7691    int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7692    mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7693    if (mCblkMemory != 0) {
7694        mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7695
7696        if (mCblk != NULL) {
7697            new(mCblk) effect_param_cblk_t();
7698            mBuffer = (uint8_t *)mCblk + bufOffset;
7699        }
7700    } else {
7701        ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
7702        return;
7703    }
7704}
7705
7706AudioFlinger::EffectHandle::~EffectHandle()
7707{
7708    ALOGV("Destructor %p", this);
7709    disconnect(false);
7710    ALOGV("Destructor DONE %p", this);
7711}
7712
7713status_t AudioFlinger::EffectHandle::enable()
7714{
7715    ALOGV("enable %p", this);
7716    if (!mHasControl) return INVALID_OPERATION;
7717    if (mEffect == 0) return DEAD_OBJECT;
7718
7719    if (mEnabled) {
7720        return NO_ERROR;
7721    }
7722
7723    mEnabled = true;
7724
7725    sp<ThreadBase> thread = mEffect->thread().promote();
7726    if (thread != 0) {
7727        thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7728    }
7729
7730    // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7731    if (mEffect->suspended()) {
7732        return NO_ERROR;
7733    }
7734
7735    status_t status = mEffect->setEnabled(true);
7736    if (status != NO_ERROR) {
7737        if (thread != 0) {
7738            thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7739        }
7740        mEnabled = false;
7741    }
7742    return status;
7743}
7744
7745status_t AudioFlinger::EffectHandle::disable()
7746{
7747    ALOGV("disable %p", this);
7748    if (!mHasControl) return INVALID_OPERATION;
7749    if (mEffect == 0) return DEAD_OBJECT;
7750
7751    if (!mEnabled) {
7752        return NO_ERROR;
7753    }
7754    mEnabled = false;
7755
7756    if (mEffect->suspended()) {
7757        return NO_ERROR;
7758    }
7759
7760    status_t status = mEffect->setEnabled(false);
7761
7762    sp<ThreadBase> thread = mEffect->thread().promote();
7763    if (thread != 0) {
7764        thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7765    }
7766
7767    return status;
7768}
7769
7770void AudioFlinger::EffectHandle::disconnect()
7771{
7772    disconnect(true);
7773}
7774
7775void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
7776{
7777    ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
7778    if (mEffect == 0) {
7779        return;
7780    }
7781    mEffect->disconnect(this, unpinIfLast);
7782
7783    if (mHasControl && mEnabled) {
7784        sp<ThreadBase> thread = mEffect->thread().promote();
7785        if (thread != 0) {
7786            thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7787        }
7788    }
7789
7790    // release sp on module => module destructor can be called now
7791    mEffect.clear();
7792    if (mClient != 0) {
7793        if (mCblk != NULL) {
7794            // unlike ~TrackBase(), mCblk is never a local new, so don't delete
7795            mCblk->~effect_param_cblk_t();   // destroy our shared-structure.
7796        }
7797        mCblkMemory.clear();    // free the shared memory before releasing the heap it belongs to
7798        // Client destructor must run with AudioFlinger mutex locked
7799        Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7800        mClient.clear();
7801    }
7802}
7803
7804status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7805                                             uint32_t cmdSize,
7806                                             void *pCmdData,
7807                                             uint32_t *replySize,
7808                                             void *pReplyData)
7809{
7810//    ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
7811//              cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
7812
7813    // only get parameter command is permitted for applications not controlling the effect
7814    if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7815        return INVALID_OPERATION;
7816    }
7817    if (mEffect == 0) return DEAD_OBJECT;
7818    if (mClient == 0) return INVALID_OPERATION;
7819
7820    // handle commands that are not forwarded transparently to effect engine
7821    if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7822        // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7823        // no risk to block the whole media server process or mixer threads is we are stuck here
7824        Mutex::Autolock _l(mCblk->lock);
7825        if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7826            mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7827            mCblk->serverIndex = 0;
7828            mCblk->clientIndex = 0;
7829            return BAD_VALUE;
7830        }
7831        status_t status = NO_ERROR;
7832        while (mCblk->serverIndex < mCblk->clientIndex) {
7833            int reply;
7834            uint32_t rsize = sizeof(int);
7835            int *p = (int *)(mBuffer + mCblk->serverIndex);
7836            int size = *p++;
7837            if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
7838                ALOGW("command(): invalid parameter block size");
7839                break;
7840            }
7841            effect_param_t *param = (effect_param_t *)p;
7842            if (param->psize == 0 || param->vsize == 0) {
7843                ALOGW("command(): null parameter or value size");
7844                mCblk->serverIndex += size;
7845                continue;
7846            }
7847            uint32_t psize = sizeof(effect_param_t) +
7848                             ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7849                             param->vsize;
7850            status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7851                                            psize,
7852                                            p,
7853                                            &rsize,
7854                                            &reply);
7855            // stop at first error encountered
7856            if (ret != NO_ERROR) {
7857                status = ret;
7858                *(int *)pReplyData = reply;
7859                break;
7860            } else if (reply != NO_ERROR) {
7861                *(int *)pReplyData = reply;
7862                break;
7863            }
7864            mCblk->serverIndex += size;
7865        }
7866        mCblk->serverIndex = 0;
7867        mCblk->clientIndex = 0;
7868        return status;
7869    } else if (cmdCode == EFFECT_CMD_ENABLE) {
7870        *(int *)pReplyData = NO_ERROR;
7871        return enable();
7872    } else if (cmdCode == EFFECT_CMD_DISABLE) {
7873        *(int *)pReplyData = NO_ERROR;
7874        return disable();
7875    }
7876
7877    return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7878}
7879
7880void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
7881{
7882    ALOGV("setControl %p control %d", this, hasControl);
7883
7884    mHasControl = hasControl;
7885    mEnabled = enabled;
7886
7887    if (signal && mEffectClient != 0) {
7888        mEffectClient->controlStatusChanged(hasControl);
7889    }
7890}
7891
7892void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7893                                                 uint32_t cmdSize,
7894                                                 void *pCmdData,
7895                                                 uint32_t replySize,
7896                                                 void *pReplyData)
7897{
7898    if (mEffectClient != 0) {
7899        mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7900    }
7901}
7902
7903
7904
7905void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7906{
7907    if (mEffectClient != 0) {
7908        mEffectClient->enableStatusChanged(enabled);
7909    }
7910}
7911
7912status_t AudioFlinger::EffectHandle::onTransact(
7913    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7914{
7915    return BnEffect::onTransact(code, data, reply, flags);
7916}
7917
7918
7919void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7920{
7921    bool locked = mCblk != NULL && tryLock(mCblk->lock);
7922
7923    snprintf(buffer, size, "\t\t\t%05d %05d    %01u    %01u      %05u  %05u\n",
7924            (mClient == 0) ? getpid_cached : mClient->pid(),
7925            mPriority,
7926            mHasControl,
7927            !locked,
7928            mCblk ? mCblk->clientIndex : 0,
7929            mCblk ? mCblk->serverIndex : 0
7930            );
7931
7932    if (locked) {
7933        mCblk->lock.unlock();
7934    }
7935}
7936
7937#undef LOG_TAG
7938#define LOG_TAG "AudioFlinger::EffectChain"
7939
7940AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
7941                                        int sessionId)
7942    : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
7943      mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7944      mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
7945{
7946    mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
7947    if (thread == NULL) {
7948        return;
7949    }
7950    mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7951                                    thread->frameCount();
7952}
7953
7954AudioFlinger::EffectChain::~EffectChain()
7955{
7956    if (mOwnInBuffer) {
7957        delete mInBuffer;
7958    }
7959
7960}
7961
7962// getEffectFromDesc_l() must be called with ThreadBase::mLock held
7963sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
7964{
7965    size_t size = mEffects.size();
7966
7967    for (size_t i = 0; i < size; i++) {
7968        if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7969            return mEffects[i];
7970        }
7971    }
7972    return 0;
7973}
7974
7975// getEffectFromId_l() must be called with ThreadBase::mLock held
7976sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
7977{
7978    size_t size = mEffects.size();
7979
7980    for (size_t i = 0; i < size; i++) {
7981        // by convention, return first effect if id provided is 0 (0 is never a valid id)
7982        if (id == 0 || mEffects[i]->id() == id) {
7983            return mEffects[i];
7984        }
7985    }
7986    return 0;
7987}
7988
7989// getEffectFromType_l() must be called with ThreadBase::mLock held
7990sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7991        const effect_uuid_t *type)
7992{
7993    size_t size = mEffects.size();
7994
7995    for (size_t i = 0; i < size; i++) {
7996        if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7997            return mEffects[i];
7998        }
7999    }
8000    return 0;
8001}
8002
8003// Must be called with EffectChain::mLock locked
8004void AudioFlinger::EffectChain::process_l()
8005{
8006    sp<ThreadBase> thread = mThread.promote();
8007    if (thread == 0) {
8008        ALOGW("process_l(): cannot promote mixer thread");
8009        return;
8010    }
8011    bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8012            (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
8013    // always process effects unless no more tracks are on the session and the effect tail
8014    // has been rendered
8015    bool doProcess = true;
8016    if (!isGlobalSession) {
8017        bool tracksOnSession = (trackCnt() != 0);
8018
8019        if (!tracksOnSession && mTailBufferCount == 0) {
8020            doProcess = false;
8021        }
8022
8023        if (activeTrackCnt() == 0) {
8024            // if no track is active and the effect tail has not been rendered,
8025            // the input buffer must be cleared here as the mixer process will not do it
8026            if (tracksOnSession || mTailBufferCount > 0) {
8027                size_t numSamples = thread->frameCount() * thread->channelCount();
8028                memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8029                if (mTailBufferCount > 0) {
8030                    mTailBufferCount--;
8031                }
8032            }
8033        }
8034    }
8035
8036    size_t size = mEffects.size();
8037    if (doProcess) {
8038        for (size_t i = 0; i < size; i++) {
8039            mEffects[i]->process();
8040        }
8041    }
8042    for (size_t i = 0; i < size; i++) {
8043        mEffects[i]->updateState();
8044    }
8045}
8046
8047// addEffect_l() must be called with PlaybackThread::mLock held
8048status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
8049{
8050    effect_descriptor_t desc = effect->desc();
8051    uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
8052
8053    Mutex::Autolock _l(mLock);
8054    effect->setChain(this);
8055    sp<ThreadBase> thread = mThread.promote();
8056    if (thread == 0) {
8057        return NO_INIT;
8058    }
8059    effect->setThread(thread);
8060
8061    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8062        // Auxiliary effects are inserted at the beginning of mEffects vector as
8063        // they are processed first and accumulated in chain input buffer
8064        mEffects.insertAt(effect, 0);
8065
8066        // the input buffer for auxiliary effect contains mono samples in
8067        // 32 bit format. This is to avoid saturation in AudoMixer
8068        // accumulation stage. Saturation is done in EffectModule::process() before
8069        // calling the process in effect engine
8070        size_t numSamples = thread->frameCount();
8071        int32_t *buffer = new int32_t[numSamples];
8072        memset(buffer, 0, numSamples * sizeof(int32_t));
8073        effect->setInBuffer((int16_t *)buffer);
8074        // auxiliary effects output samples to chain input buffer for further processing
8075        // by insert effects
8076        effect->setOutBuffer(mInBuffer);
8077    } else {
8078        // Insert effects are inserted at the end of mEffects vector as they are processed
8079        //  after track and auxiliary effects.
8080        // Insert effect order as a function of indicated preference:
8081        //  if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8082        //  another effect is present
8083        //  else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8084        //  last effect claiming first position
8085        //  else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8086        //  first effect claiming last position
8087        //  else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8088        // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8089        // already present
8090
8091        size_t size = mEffects.size();
8092        size_t idx_insert = size;
8093        ssize_t idx_insert_first = -1;
8094        ssize_t idx_insert_last = -1;
8095
8096        for (size_t i = 0; i < size; i++) {
8097            effect_descriptor_t d = mEffects[i]->desc();
8098            uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8099            uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8100            if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8101                // check invalid effect chaining combinations
8102                if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8103                    iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
8104                    ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
8105                    return INVALID_OPERATION;
8106                }
8107                // remember position of first insert effect and by default
8108                // select this as insert position for new effect
8109                if (idx_insert == size) {
8110                    idx_insert = i;
8111                }
8112                // remember position of last insert effect claiming
8113                // first position
8114                if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8115                    idx_insert_first = i;
8116                }
8117                // remember position of first insert effect claiming
8118                // last position
8119                if (iPref == EFFECT_FLAG_INSERT_LAST &&
8120                    idx_insert_last == -1) {
8121                    idx_insert_last = i;
8122                }
8123            }
8124        }
8125
8126        // modify idx_insert from first position if needed
8127        if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8128            if (idx_insert_last != -1) {
8129                idx_insert = idx_insert_last;
8130            } else {
8131                idx_insert = size;
8132            }
8133        } else {
8134            if (idx_insert_first != -1) {
8135                idx_insert = idx_insert_first + 1;
8136            }
8137        }
8138
8139        // always read samples from chain input buffer
8140        effect->setInBuffer(mInBuffer);
8141
8142        // if last effect in the chain, output samples to chain
8143        // output buffer, otherwise to chain input buffer
8144        if (idx_insert == size) {
8145            if (idx_insert != 0) {
8146                mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8147                mEffects[idx_insert-1]->configure();
8148            }
8149            effect->setOutBuffer(mOutBuffer);
8150        } else {
8151            effect->setOutBuffer(mInBuffer);
8152        }
8153        mEffects.insertAt(effect, idx_insert);
8154
8155        ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
8156    }
8157    effect->configure();
8158    return NO_ERROR;
8159}
8160
8161// removeEffect_l() must be called with PlaybackThread::mLock held
8162size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
8163{
8164    Mutex::Autolock _l(mLock);
8165    size_t size = mEffects.size();
8166    uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8167
8168    for (size_t i = 0; i < size; i++) {
8169        if (effect == mEffects[i]) {
8170            // calling stop here will remove pre-processing effect from the audio HAL.
8171            // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8172            // the middle of a read from audio HAL
8173            if (mEffects[i]->state() == EffectModule::ACTIVE ||
8174                    mEffects[i]->state() == EffectModule::STOPPING) {
8175                mEffects[i]->stop();
8176            }
8177            if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8178                delete[] effect->inBuffer();
8179            } else {
8180                if (i == size - 1 && i != 0) {
8181                    mEffects[i - 1]->setOutBuffer(mOutBuffer);
8182                    mEffects[i - 1]->configure();
8183                }
8184            }
8185            mEffects.removeAt(i);
8186            ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
8187            break;
8188        }
8189    }
8190
8191    return mEffects.size();
8192}
8193
8194// setDevice_l() must be called with PlaybackThread::mLock held
8195void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
8196{
8197    size_t size = mEffects.size();
8198    for (size_t i = 0; i < size; i++) {
8199        mEffects[i]->setDevice(device);
8200    }
8201}
8202
8203// setMode_l() must be called with PlaybackThread::mLock held
8204void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
8205{
8206    size_t size = mEffects.size();
8207    for (size_t i = 0; i < size; i++) {
8208        mEffects[i]->setMode(mode);
8209    }
8210}
8211
8212// setVolume_l() must be called with PlaybackThread::mLock held
8213bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
8214{
8215    uint32_t newLeft = *left;
8216    uint32_t newRight = *right;
8217    bool hasControl = false;
8218    int ctrlIdx = -1;
8219    size_t size = mEffects.size();
8220
8221    // first update volume controller
8222    for (size_t i = size; i > 0; i--) {
8223        if (mEffects[i - 1]->isProcessEnabled() &&
8224            (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
8225            ctrlIdx = i - 1;
8226            hasControl = true;
8227            break;
8228        }
8229    }
8230
8231    if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
8232        if (hasControl) {
8233            *left = mNewLeftVolume;
8234            *right = mNewRightVolume;
8235        }
8236        return hasControl;
8237    }
8238
8239    mVolumeCtrlIdx = ctrlIdx;
8240    mLeftVolume = newLeft;
8241    mRightVolume = newRight;
8242
8243    // second get volume update from volume controller
8244    if (ctrlIdx >= 0) {
8245        mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
8246        mNewLeftVolume = newLeft;
8247        mNewRightVolume = newRight;
8248    }
8249    // then indicate volume to all other effects in chain.
8250    // Pass altered volume to effects before volume controller
8251    // and requested volume to effects after controller
8252    uint32_t lVol = newLeft;
8253    uint32_t rVol = newRight;
8254
8255    for (size_t i = 0; i < size; i++) {
8256        if ((int)i == ctrlIdx) continue;
8257        // this also works for ctrlIdx == -1 when there is no volume controller
8258        if ((int)i > ctrlIdx) {
8259            lVol = *left;
8260            rVol = *right;
8261        }
8262        mEffects[i]->setVolume(&lVol, &rVol, false);
8263    }
8264    *left = newLeft;
8265    *right = newRight;
8266
8267    return hasControl;
8268}
8269
8270status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
8271{
8272    const size_t SIZE = 256;
8273    char buffer[SIZE];
8274    String8 result;
8275
8276    snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
8277    result.append(buffer);
8278
8279    bool locked = tryLock(mLock);
8280    // failed to lock - AudioFlinger is probably deadlocked
8281    if (!locked) {
8282        result.append("\tCould not lock mutex:\n");
8283    }
8284
8285    result.append("\tNum fx In buffer   Out buffer   Active tracks:\n");
8286    snprintf(buffer, SIZE, "\t%02d     0x%08x  0x%08x   %d\n",
8287            mEffects.size(),
8288            (uint32_t)mInBuffer,
8289            (uint32_t)mOutBuffer,
8290            mActiveTrackCnt);
8291    result.append(buffer);
8292    write(fd, result.string(), result.size());
8293
8294    for (size_t i = 0; i < mEffects.size(); ++i) {
8295        sp<EffectModule> effect = mEffects[i];
8296        if (effect != 0) {
8297            effect->dump(fd, args);
8298        }
8299    }
8300
8301    if (locked) {
8302        mLock.unlock();
8303    }
8304
8305    return NO_ERROR;
8306}
8307
8308// must be called with ThreadBase::mLock held
8309void AudioFlinger::EffectChain::setEffectSuspended_l(
8310        const effect_uuid_t *type, bool suspend)
8311{
8312    sp<SuspendedEffectDesc> desc;
8313    // use effect type UUID timelow as key as there is no real risk of identical
8314    // timeLow fields among effect type UUIDs.
8315    ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
8316    if (suspend) {
8317        if (index >= 0) {
8318            desc = mSuspendedEffects.valueAt(index);
8319        } else {
8320            desc = new SuspendedEffectDesc();
8321            memcpy(&desc->mType, type, sizeof(effect_uuid_t));
8322            mSuspendedEffects.add(type->timeLow, desc);
8323            ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
8324        }
8325        if (desc->mRefCount++ == 0) {
8326            sp<EffectModule> effect = getEffectIfEnabled(type);
8327            if (effect != 0) {
8328                desc->mEffect = effect;
8329                effect->setSuspended(true);
8330                effect->setEnabled(false);
8331            }
8332        }
8333    } else {
8334        if (index < 0) {
8335            return;
8336        }
8337        desc = mSuspendedEffects.valueAt(index);
8338        if (desc->mRefCount <= 0) {
8339            ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
8340            desc->mRefCount = 1;
8341        }
8342        if (--desc->mRefCount == 0) {
8343            ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
8344            if (desc->mEffect != 0) {
8345                sp<EffectModule> effect = desc->mEffect.promote();
8346                if (effect != 0) {
8347                    effect->setSuspended(false);
8348                    sp<EffectHandle> handle = effect->controlHandle();
8349                    if (handle != 0) {
8350                        effect->setEnabled(handle->enabled());
8351                    }
8352                }
8353                desc->mEffect.clear();
8354            }
8355            mSuspendedEffects.removeItemsAt(index);
8356        }
8357    }
8358}
8359
8360// must be called with ThreadBase::mLock held
8361void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
8362{
8363    sp<SuspendedEffectDesc> desc;
8364
8365    ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8366    if (suspend) {
8367        if (index >= 0) {
8368            desc = mSuspendedEffects.valueAt(index);
8369        } else {
8370            desc = new SuspendedEffectDesc();
8371            mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
8372            ALOGV("setEffectSuspendedAll_l() add entry for 0");
8373        }
8374        if (desc->mRefCount++ == 0) {
8375            Vector< sp<EffectModule> > effects;
8376            getSuspendEligibleEffects(effects);
8377            for (size_t i = 0; i < effects.size(); i++) {
8378                setEffectSuspended_l(&effects[i]->desc().type, true);
8379            }
8380        }
8381    } else {
8382        if (index < 0) {
8383            return;
8384        }
8385        desc = mSuspendedEffects.valueAt(index);
8386        if (desc->mRefCount <= 0) {
8387            ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
8388            desc->mRefCount = 1;
8389        }
8390        if (--desc->mRefCount == 0) {
8391            Vector<const effect_uuid_t *> types;
8392            for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8393                if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8394                    continue;
8395                }
8396                types.add(&mSuspendedEffects.valueAt(i)->mType);
8397            }
8398            for (size_t i = 0; i < types.size(); i++) {
8399                setEffectSuspended_l(types[i], false);
8400            }
8401            ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
8402            mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8403        }
8404    }
8405}
8406
8407
8408// The volume effect is used for automated tests only
8409#ifndef OPENSL_ES_H_
8410static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8411                                            { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8412const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8413#endif //OPENSL_ES_H_
8414
8415bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8416{
8417    // auxiliary effects and visualizer are never suspended on output mix
8418    if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8419        (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
8420         (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8421         (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
8422        return false;
8423    }
8424    return true;
8425}
8426
8427void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
8428{
8429    effects.clear();
8430    for (size_t i = 0; i < mEffects.size(); i++) {
8431        if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8432            effects.add(mEffects[i]);
8433        }
8434    }
8435}
8436
8437sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8438                                                            const effect_uuid_t *type)
8439{
8440    sp<EffectModule> effect = getEffectFromType_l(type);
8441    return effect != 0 && effect->isEnabled() ? effect : 0;
8442}
8443
8444void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8445                                                            bool enabled)
8446{
8447    ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
8448    if (enabled) {
8449        if (index < 0) {
8450            // if the effect is not suspend check if all effects are suspended
8451            index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8452            if (index < 0) {
8453                return;
8454            }
8455            if (!isEffectEligibleForSuspend(effect->desc())) {
8456                return;
8457            }
8458            setEffectSuspended_l(&effect->desc().type, enabled);
8459            index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
8460            if (index < 0) {
8461                ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
8462                return;
8463            }
8464        }
8465        ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
8466            effect->desc().type.timeLow);
8467        sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8468        // if effect is requested to suspended but was not yet enabled, supend it now.
8469        if (desc->mEffect == 0) {
8470            desc->mEffect = effect;
8471            effect->setEnabled(false);
8472            effect->setSuspended(true);
8473        }
8474    } else {
8475        if (index < 0) {
8476            return;
8477        }
8478        ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
8479            effect->desc().type.timeLow);
8480        sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8481        desc->mEffect.clear();
8482        effect->setSuspended(false);
8483    }
8484}
8485
8486#undef LOG_TAG
8487#define LOG_TAG "AudioFlinger"
8488
8489// ----------------------------------------------------------------------------
8490
8491status_t AudioFlinger::onTransact(
8492        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8493{
8494    return BnAudioFlinger::onTransact(code, data, reply, flags);
8495}
8496
8497}; // namespace android
8498