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