1 /* AudioHardwareALSA.cpp
3 ** Copyright 2008 Wind River Systems
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
9 ** http://www.apache.org/licenses/LICENSE-2.0
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.
21 #include <sys/types.h>
27 #define LOG_TAG "AudioHardwareALSA"
28 #include <utils/Log.h>
29 #include <utils/String8.h>
31 #include <cutils/properties.h>
32 #include <media/AudioRecord.h>
33 #include <hardware/power.h>
35 #include <alsa/asoundlib.h>
36 #include "AudioHardwareALSA.h"
38 #define SND_MIXER_VOL_RANGE_MIN (0)
39 #define SND_MIXER_VOL_RANGE_MAX (1000)
43 extern int ffs(int i);
46 // Make sure this prototype is consistent with what's in
47 // external/libasound/alsa-lib-1.0.16/src/pcm/pcm_null.c!
49 extern int snd_pcm_null_open(snd_pcm_t **pcmp,
51 snd_pcm_stream_t stream,
55 // Function for dlsym() to look up for creating a new AudioHardwareInterface.
57 android::AudioHardwareInterface *createAudioHardware(void)
59 return new android::AudioHardwareALSA();
67 // ----------------------------------------------------------------------------
69 static const char _nullALSADeviceName[] = "NULL_Device";
71 static void ALSAErrorHandler(const char *file,
83 l = snprintf(buf, BUFSIZ, "%s:%i:(%s) ", file, line, function);
84 vsnprintf(buf + l, BUFSIZ - l, fmt, arg);
86 LOG(LOG_ERROR, "ALSALib", buf);
90 // ----------------------------------------------------------------------------
92 struct alsa_properties_t {
94 const char *propDefault;
97 static const alsa_properties_t masterPlaybackProp = {
98 "alsa.mixer.playback.master", "PCM"
101 static const alsa_properties_t masterCaptureProp = {
102 "alsa.mixer.capture.master", "Capture"
105 /* The following table(s) need to match in order of the route bits
107 static const char *deviceSuffix[] = {
108 /* ROUTE_EARPIECE */ "_Earpiece",
109 /* ROUTE_SPEAKER */ "_Speaker",
110 /* ROUTE_BLUETOOTH */ "_Bluetooth",
111 /* ROUTE_HEADSET */ "_Headset",
114 static const int deviceSuffixLen = (sizeof(deviceSuffix) / sizeof(char *));
116 static const alsa_properties_t
117 mixerMasterProp[SND_PCM_STREAM_LAST+1] =
119 { "alsa.mixer.playback.master", "PCM" },
120 { "alsa.mixer.capture.master", "Capture" }
123 static const alsa_properties_t
124 mixerProp[SND_PCM_STREAM_LAST+1][ALSAMixer::MIXER_LAST+1] =
127 {"alsa.mixer.playback.earpiece", "Earpiece"},
128 {"alsa.mixer.playback.speaker", "Speaker"},
129 {"alsa.mixer.playback.bluetooth", "Bluetooth"},
130 {"alsa.mixer.playback.headset", "Headphone"}
133 {"alsa.mixer.capture.earpiece", "Capture"},
134 {"alsa.mixer.capture.speaker", ""},
135 {"alsa.mixer.capture.bluetooth", "Bluetooth Capture"},
136 {"alsa.mixer.capture.headset", "Capture"}
140 // ----------------------------------------------------------------------------
142 AudioHardwareALSA::AudioHardwareALSA() :
146 snd_lib_error_set_handler(&ALSAErrorHandler);
147 mMixer = new ALSAMixer;
150 AudioHardwareALSA::~AudioHardwareALSA()
152 if (mOutput) delete mOutput;
153 if (mInput) delete mInput;
154 if (mMixer) delete mMixer;
157 status_t AudioHardwareALSA::initCheck()
159 if (mMixer && mMixer->isValid())
165 status_t AudioHardwareALSA::standby()
168 return mOutput->standby();
173 status_t AudioHardwareALSA::setVoiceVolume(float volume)
175 // The voice volume is used by the VOICE_CALL audio stream.
177 return mMixer->setVolume(ALSAMixer::MIXER_EARPIECE, volume);
179 return INVALID_OPERATION;
182 status_t AudioHardwareALSA::setMasterVolume(float volume)
185 return mMixer->setMasterVolume(volume);
187 return INVALID_OPERATION;
190 AudioStreamOut *AudioHardwareALSA::openOutputStream(int format,
194 AutoMutex lock(mLock);
196 // only one output stream allowed
200 AudioStreamOutALSA *out = new AudioStreamOutALSA(this);
202 if (out->set(format, channelCount, sampleRate) == NO_ERROR) {
204 // Some information is expected to be available immediately after
205 // the device is open.
206 uint32_t routes = mRoutes[mMode];
207 mOutput->setDevice(mMode, routes);
215 AudioStreamIn *AudioHardwareALSA::openInputStream(int format,
219 AutoMutex lock(mLock);
221 // only one input stream allowed
225 AudioStreamInALSA *in = new AudioStreamInALSA(this);
227 if (in->set(format, channelCount, sampleRate) == NO_ERROR) {
229 // Now, actually open the device. Only 1 route used
230 mInput->setDevice(0, 0);
237 status_t AudioHardwareALSA::doRouting()
241 AutoMutex lock(mLock);
244 routes = mRoutes[mMode];
245 return mOutput->setDevice(mMode, routes);
250 status_t AudioHardwareALSA::setMicMute(bool state)
252 ALSAMixer::mixer_types mixer_type =
253 static_cast<ALSAMixer::mixer_types>(ffs(AudioSystem::ROUTE_EARPIECE) - 1);
256 return mMixer->setCaptureMuteState(mixer_type, state);
261 status_t AudioHardwareALSA::getMicMute(bool *state)
263 ALSAMixer::mixer_types mixer_type =
264 static_cast<ALSAMixer::mixer_types>(ffs(AudioSystem::ROUTE_EARPIECE) - 1);
267 return mMixer->getCaptureMuteState(mixer_type, state);
272 status_t AudioHardwareALSA::dump(int fd, const Vector<String16>& args)
277 // ----------------------------------------------------------------------------
279 ALSAStreamOps::ALSAStreamOps() :
286 if (snd_pcm_hw_params_malloc(&mHardwareParams) < 0) {
287 LOG_ALWAYS_FATAL("Failed to allocate ALSA hardware parameters!");
290 if (snd_pcm_sw_params_malloc(&mSoftwareParams) < 0) {
291 LOG_ALWAYS_FATAL("Failed to allocate ALSA software parameters!");
295 ALSAStreamOps::~ALSAStreamOps()
297 AutoMutex lock(mLock);
302 snd_pcm_hw_params_free(mHardwareParams);
305 snd_pcm_sw_params_free(mSoftwareParams);
308 status_t ALSAStreamOps::set(int format,
313 mDefaults->channels = channels;
316 mDefaults->sampleRate = rate;
319 case AudioSystem::DEFAULT: // format == 0
322 case AudioSystem::PCM_16_BIT:
323 mDefaults->format = SND_PCM_FORMAT_S16_LE;
326 case AudioSystem::PCM_8_BIT:
327 mDefaults->format = SND_PCM_FORMAT_S8;
331 LOGE("Unknown PCM format %i. Forcing default", format);
338 uint32_t ALSAStreamOps::sampleRate() const
346 return snd_pcm_hw_params_get_rate(mHardwareParams, &rate, 0) < 0
347 ? 0 : static_cast<uint32_t>(rate);
350 status_t ALSAStreamOps::sampleRate(uint32_t rate)
353 unsigned int requestedRate;
359 stream = streamName();
360 requestedRate = rate;
361 err = snd_pcm_hw_params_set_rate_near(mHandle,
367 LOGE("Unable to set %s sample rate to %u: %s",
368 stream, rate, snd_strerror(err));
371 if (requestedRate != rate) {
372 // Some devices have a fixed sample rate, and can not be changed.
373 // This may cause resampling problems; i.e. PCM playback will be too
375 LOGW("Requested rate (%u HZ) does not match actual rate (%u HZ)",
376 rate, requestedRate);
378 LOGD("Set %s sample rate to %u HZ", stream, requestedRate);
384 // Return the number of bytes (not frames)
386 size_t ALSAStreamOps::bufferSize() const
388 snd_pcm_uframes_t periodSize;
394 err = snd_pcm_hw_params_get_period_size(mHardwareParams,
400 return static_cast<size_t>(snd_pcm_frames_to_bytes(mHandle, periodSize));
403 int ALSAStreamOps::format() const
405 snd_pcm_format_t ALSAFormat;
406 int pcmFormatBitWidth;
407 int audioSystemFormat;
412 if (snd_pcm_hw_params_get_format(mHardwareParams, &ALSAFormat) < 0) {
416 pcmFormatBitWidth = snd_pcm_format_physical_width(ALSAFormat);
417 audioSystemFormat = AudioSystem::DEFAULT;
418 switch(pcmFormatBitWidth)
421 audioSystemFormat = AudioSystem::PCM_8_BIT;
425 audioSystemFormat = AudioSystem::PCM_16_BIT;
429 LOG_FATAL("Unknown AudioSystem bit width %i!", pcmFormatBitWidth);
432 return audioSystemFormat;
435 int ALSAStreamOps::channelCount() const
443 err = snd_pcm_hw_params_get_channels(mHardwareParams, &val);
445 LOGE("Unable to get device channel count: %s",
453 status_t ALSAStreamOps::channelCount(int channels)
460 err = snd_pcm_hw_params_set_channels(mHandle, mHardwareParams, channels);
462 LOGE("Unable to set channel count to %i: %s",
463 channels, snd_strerror(err));
467 LOGD("Using %i %s for %s.",
468 channels, channels == 1 ? "channel" : "channels", streamName());
473 status_t ALSAStreamOps::open(int mode, int device)
475 const char *stream = streamName();
476 const char *devName = deviceName(mode, device);
480 // The PCM stream is opened in blocking mode, per ALSA defaults. The
481 // AudioFlinger seems to assume blocking mode too, so asynchronous mode
482 // should not be used.
483 if ((err = snd_pcm_open(&mHandle, devName, mDefaults->direction, 0)) < 0) {
485 // Try without the mode.
486 devName = deviceName(AudioSystem::MODE_INVALID, device);
488 err = snd_pcm_open(&mHandle, devName, mDefaults->direction, 0);
491 // Try without mode or device.
492 devName = deviceName(AudioSystem::MODE_INVALID, -1);
494 err = snd_pcm_open(&mHandle, devName, mDefaults->direction, 0);
497 err = snd_pcm_open(&mHandle, "hw:00,0", mDefaults->direction, 0);
500 LOGE("Unable to open fallback %s device: %s",
501 stream, snd_strerror(err));
503 // Last resort is the NULL device (i.e. the bit bucket).
504 err = snd_pcm_null_open(&mHandle, _nullALSADeviceName,
505 mDefaults->direction, 0);
507 LOG_FATAL("Unable to open NULL ALSA device: %s",
510 LOGD("Opened NULL %s device.", streamName());
520 LOGI("Initialized ALSA %s device %s", stream, devName);
524 void ALSAStreamOps::close()
526 snd_pcm_t *handle = mHandle;
530 snd_pcm_close(handle);
536 status_t ALSAStreamOps::setSoftwareParams()
543 // Get the current software parameters
544 err = snd_pcm_sw_params_current(mHandle, mSoftwareParams);
546 LOGE("Unable to get software parameters: %s", snd_strerror(err));
550 snd_pcm_uframes_t bufferSize = 0;
551 snd_pcm_uframes_t periodSize = 0;
552 snd_pcm_uframes_t startThreshold;
554 // Configure ALSA to start the transfer when the buffer is almost full.
555 snd_pcm_get_params(mHandle, &bufferSize, &periodSize);
557 if (mDefaults->direction == SND_PCM_STREAM_PLAYBACK) {
558 // For playback, configure ALSA to start the transfer when the
559 // buffer is almost full.
560 startThreshold = (bufferSize / periodSize) * periodSize;
562 // For recording, configure ALSA to start the transfer on the
567 err = snd_pcm_sw_params_set_start_threshold(mHandle,
571 LOGE("Unable to set start threshold to %lu frames: %s",
572 startThreshold, snd_strerror(err));
576 // Stop the transfer when the buffer is full.
577 err = snd_pcm_sw_params_set_stop_threshold(mHandle,
581 LOGE("Unable to set stop threshold to %lu frames: %s",
582 bufferSize, snd_strerror(err));
586 // Allow the transfer to start when at least periodSize samples can be
588 err = snd_pcm_sw_params_set_avail_min(mHandle,
592 LOGE("Unable to configure available minimum to %lu: %s",
593 periodSize, snd_strerror(err));
597 // Commit the software parameters back to the device.
598 err = snd_pcm_sw_params(mHandle, mSoftwareParams);
600 LOGE("Unable to configure software parameters: %s",
608 status_t ALSAStreamOps::setPCMFormat(snd_pcm_format_t format)
610 const char *formatDesc;
611 const char *formatName;
615 // snd_pcm_format_description() and snd_pcm_format_name() do not perform
616 // proper bounds checking.
617 validFormat = (static_cast<int>(format) > SND_PCM_FORMAT_UNKNOWN) &&
618 (static_cast<int>(format) <= SND_PCM_FORMAT_LAST);
619 formatDesc = validFormat ?
620 snd_pcm_format_description(format) : "Invalid Format";
621 formatName = validFormat ?
622 snd_pcm_format_name(format) : "UNKNOWN";
624 err = snd_pcm_hw_params_set_format(mHandle, mHardwareParams, format);
626 LOGE("Unable to configure PCM format %s (%s): %s",
627 formatName, formatDesc, snd_strerror(err));
631 LOGD("Set %s PCM format to %s (%s)", streamName(), formatName, formatDesc);
635 status_t ALSAStreamOps::setHardwareResample(bool resample)
639 err = snd_pcm_hw_params_set_rate_resample(mHandle,
641 static_cast<int>(resample));
643 LOGE("Unable to %s hardware resampling: %s",
644 resample ? "enable" : "disable",
651 const char *ALSAStreamOps::streamName()
653 // Don't use snd_pcm_stream(mHandle), as the PCM stream may not be
654 // opened yet. In such case, snd_pcm_stream() will abort().
655 return snd_pcm_stream_name(mDefaults->direction);
659 // Set playback or capture PCM device. It's possible to support audio output
660 // or input from multiple devices by using the ALSA plugins, but this is
661 // not supported for simplicity.
663 // The AudioHardwareALSA API does not allow one to set the input routing.
665 // If the "routes" value does not map to a valid device, the default playback
668 status_t ALSAStreamOps::setDevice(int mode, uint32_t device)
670 // Close off previously opened device.
671 // It would be nice to determine if the underlying device actually
672 // changes, but we might be manipulating mixer settings (see asound.conf).
676 const char *stream = streamName();
678 status_t status = open (mode, device);
681 if (status != NO_ERROR)
684 err = snd_pcm_hw_params_any(mHandle, mHardwareParams);
686 LOGE("Unable to configure hardware: %s", snd_strerror(err));
690 // Set the interleaved read and write format.
691 err = snd_pcm_hw_params_set_access(mHandle, mHardwareParams,
692 SND_PCM_ACCESS_RW_INTERLEAVED);
694 LOGE("Unable to configure PCM read/write format: %s",
699 status = setPCMFormat(mDefaults->format);
702 // Some devices do not have the default two channels. Force an error to
703 // prevent AudioMixer from crashing and taking the whole system down.
705 // Note that some devices will return an -EINVAL if the channel count
706 // is queried before it has been set. i.e. calling channelCount()
707 // before channelCount(channels) may return -EINVAL.
709 status = channelCount(mDefaults->channels);
710 if (status != NO_ERROR)
713 // Don't check for failure; some devices do not support the default
715 sampleRate(mDefaults->sampleRate);
717 // Disable hardware resampling.
718 status = setHardwareResample(false);
719 if (status != NO_ERROR)
722 unsigned int bufferTime;
723 unsigned int periodTime;
725 // Set the buffer time.
726 bufferTime = mDefaults->bufferTime;
727 err = snd_pcm_hw_params_set_buffer_time_near(mHandle,
732 LOGE("Unable to set buffer time to %u usec: %s",
733 bufferTime, snd_strerror(err));
737 // Set the period time (i.e. the number of frames)
738 periodTime = mDefaults->periodTime;
739 err = snd_pcm_hw_params_set_period_time_near(mHandle,
744 LOGE("Unable to set period time to %u usec: %s",
745 periodTime, snd_strerror(err));
749 // Commit the hardware parameters back to the device.
750 err = snd_pcm_hw_params(mHandle, mHardwareParams);
752 LOGE("Unable to set hardware parameters: %s", snd_strerror(err));
756 status = setSoftwareParams();
761 // ----------------------------------------------------------------------------
763 AudioStreamOutALSA::AudioStreamOutALSA(AudioHardwareALSA *parent) :
767 static StreamDefaults _defaults =
769 deviceName : "AndroidPlayback",
770 direction : SND_PCM_STREAM_PLAYBACK,
771 format : SND_PCM_FORMAT_S16_LE, // AudioSystem::PCM_16_BIT
774 bufferTime : 500000, // Ring buffer length in usec, 1/2 second
775 periodTime : 100000, // Period time in usec
778 setStreamDefaults(&_defaults);
781 AudioStreamOutALSA::~AudioStreamOutALSA()
784 mParent->mOutput = NULL;
787 int AudioStreamOutALSA::channelCount() const
791 c = ALSAStreamOps::channelCount();
793 // AudioMixer will seg fault if it doesn't have two channels.
795 "AudioMixer expects two channels, but only %i found!", c);
799 status_t AudioStreamOutALSA::setVolume(float volume)
801 if (! mParent->mMixer || mDevice < 0)
804 ALSAMixer::mixer_types mixer_type = static_cast<ALSAMixer::mixer_types>(mDevice);
806 return mParent->mMixer->setVolume (mixer_type, volume);
809 ssize_t AudioStreamOutALSA::write(const void *buffer, size_t bytes)
814 AutoMutex lock(mLock);
820 acquire_wake_lock (PARTIAL_WAKE_LOCK, "AudioLock");
821 ALSAStreamOps::setDevice(mMode, mDevice);
825 n = snd_pcm_writei(mHandle,
827 snd_pcm_bytes_to_frames(mHandle, bytes));
828 if (n < 0 && mHandle) {
829 // snd_pcm_recover() will return 0 if successful in recovering from
830 // an error, or -errno if the error was unrecoverable.
831 n = snd_pcm_recover(mHandle, n, 0);
834 return static_cast<ssize_t>(n);
837 status_t AudioStreamOutALSA::dump(int fd, const Vector<String16>& args)
842 status_t AudioStreamOutALSA::setDevice(int mode, uint32_t newDevice)
847 // Output to only one device. The new device is the first selected bit
848 // in newDevice (per IAudioFlinger::ROUTE_*).
850 // It's possible to not output to any device (i.e. newDevice is 0).
852 dev = newDevice ? (ffs(static_cast<int>(newDevice)) - 1) : -1;
854 AutoMutex lock(mLock);
856 return ALSAStreamOps::setDevice(mode, dev);
859 const char *AudioStreamOutALSA::deviceName(int mode, int device)
861 static char devString[PROPERTY_VALUE_MAX];
864 strcpy (devString, mDefaults->deviceName);
866 if (device >= 0 && device < deviceSuffixLen) {
867 strcat (devString, deviceSuffix[device]);
873 case AudioSystem::MODE_NORMAL:
874 strcat (devString, "_normal");
876 case AudioSystem::MODE_RINGTONE:
877 strcat (devString, "_ringtone");
879 case AudioSystem::MODE_IN_CALL:
880 strcat (devString, "_incall");
887 status_t AudioStreamOutALSA::standby()
889 AutoMutex lock(mLock);
892 snd_pcm_drain (mHandle);
895 release_wake_lock ("AudioLock");
902 bool AudioStreamOutALSA::isStandby()
907 // ----------------------------------------------------------------------------
909 AudioStreamInALSA::AudioStreamInALSA(AudioHardwareALSA *parent) :
912 static StreamDefaults _defaults =
914 deviceName : "AndroidRecord",
915 direction : SND_PCM_STREAM_CAPTURE,
916 format : SND_PCM_FORMAT_S16_LE, // AudioSystem::PCM_16_BIT
918 sampleRate : AudioRecord::DEFAULT_SAMPLE_RATE,
919 bufferTime : 500000, // Ring buffer length in usec, 1/2 second
920 periodTime : 100000, // Period time in usec
923 setStreamDefaults(&_defaults);
926 AudioStreamInALSA::~AudioStreamInALSA()
928 mParent->mInput = NULL;
931 status_t AudioStreamInALSA::setGain(float gain)
934 return mParent->mMixer->setMasterGain (gain);
939 ssize_t AudioStreamInALSA::read(void *buffer, ssize_t bytes)
944 AutoMutex lock(mLock);
946 n = snd_pcm_readi(mHandle,
948 snd_pcm_bytes_to_frames(mHandle, bytes));
949 if (n < 0 && mHandle) {
950 n = snd_pcm_recover(mHandle, n, 0);
953 return static_cast<ssize_t>(n);
956 status_t AudioStreamInALSA::dump(int fd, const Vector<String16>& args)
961 status_t AudioStreamInALSA::setDevice(int mode, uint32_t newDevice)
963 AutoMutex lock(mLock);
965 // The AudioHardwareALSA API does not allow one to set the input routing.
966 // Only one input device (the microphone) is currently supported.
968 return ALSAStreamOps::setDevice(mode, AudioRecord::MIC_INPUT);
971 const char *AudioStreamInALSA::deviceName(int mode, int device)
973 static char devString[PROPERTY_VALUE_MAX];
975 strcpy (devString, mDefaults->deviceName);
976 strcat (devString, "_Microphone");
981 // ----------------------------------------------------------------------------
983 struct ALSAMixer::mixer_info_t {
985 elem(0), min(0), max(100), mute(false)
988 snd_mixer_elem_t *elem;
993 char name[PROPERTY_VALUE_MAX];
996 static int initMixer (snd_mixer_t **mixer, const char *name)
1000 if ((err = snd_mixer_open(mixer, 0)) < 0) {
1001 LOGE("Unable to open mixer: %s", snd_strerror(err));
1005 if ((err = snd_mixer_attach(*mixer, name)) < 0) {
1006 LOGE("Unable to attach mixer to device %s: %s",
1007 name, snd_strerror(err));
1009 if ((err = snd_mixer_attach(*mixer, "hw:00")) < 0) {
1010 LOGE("Unable to attach mixer to device default: %s",
1013 snd_mixer_close (*mixer);
1019 if ((err = snd_mixer_selem_register(*mixer, NULL, NULL)) < 0) {
1020 LOGE("Unable to register mixer elements: %s", snd_strerror(err));
1021 snd_mixer_close (*mixer);
1026 // Get the mixer controls from the kernel
1027 if ((err = snd_mixer_load(*mixer)) < 0) {
1028 LOGE("Unable to load mixer elements: %s", snd_strerror(err));
1029 snd_mixer_close (*mixer);
1037 typedef int (*hasVolume_t)(snd_mixer_elem_t*);
1039 static hasVolume_t hasVolume[] =
1041 snd_mixer_selem_has_playback_volume,
1042 snd_mixer_selem_has_capture_volume
1045 typedef int (*getVolumeRange_t)(snd_mixer_elem_t*, long int*, long int*);
1047 static getVolumeRange_t getVolumeRange[] =
1049 snd_mixer_selem_get_playback_volume_range,
1050 snd_mixer_selem_get_capture_volume_range
1053 typedef int (*setVolume_t)(snd_mixer_elem_t*, long int);
1055 static setVolume_t setVol[] =
1057 snd_mixer_selem_set_playback_volume_all,
1058 snd_mixer_selem_set_capture_volume_all
1061 ALSAMixer::ALSAMixer()
1065 initMixer (&mMixer[SND_PCM_STREAM_PLAYBACK], "AndroidPlayback");
1066 initMixer (&mMixer[SND_PCM_STREAM_CAPTURE], "AndroidRecord");
1068 snd_mixer_selem_id_t *sid;
1069 snd_mixer_selem_id_alloca(&sid);
1071 for (int i = 0; i <= SND_PCM_STREAM_LAST; i++) {
1073 mMaster[i] = new mixer_info_t;
1075 property_get (mixerMasterProp[i].propName,
1077 mixerMasterProp[i].propDefault);
1079 for (snd_mixer_elem_t *elem = snd_mixer_first_elem(mMixer[i]);
1081 elem = snd_mixer_elem_next(elem)) {
1083 if (!snd_mixer_selem_is_active(elem))
1086 snd_mixer_selem_get_id(elem, sid);
1088 // Find PCM playback volume control element.
1089 const char *elementName = snd_mixer_selem_id_get_name(sid);
1091 if (mMaster[i]->elem == NULL &&
1092 strcmp(elementName, mMaster[i]->name) == 0 &&
1093 hasVolume[i] (elem)) {
1095 mMaster[i]->elem = elem;
1096 getVolumeRange[i] (elem, &mMaster[i]->min, &mMaster[i]->max);
1097 mMaster[i]->volume = mMaster[i]->max;
1098 setVol[i] (elem, mMaster[i]->volume);
1099 if (i == SND_PCM_STREAM_PLAYBACK &&
1100 snd_mixer_selem_has_playback_switch (elem))
1101 snd_mixer_selem_set_playback_switch_all (elem, 1);
1106 for (int j = 0; j <= MIXER_LAST; j++) {
1108 mInfo[i][j] = new mixer_info_t;
1110 property_get (mixerProp[i][j].propName,
1112 mixerProp[i][j].propDefault);
1114 for (snd_mixer_elem_t *elem = snd_mixer_first_elem(mMixer[i]);
1116 elem = snd_mixer_elem_next(elem)) {
1118 if (!snd_mixer_selem_is_active(elem))
1121 snd_mixer_selem_get_id(elem, sid);
1123 // Find PCM playback volume control element.
1124 const char *elementName = snd_mixer_selem_id_get_name(sid);
1126 if (mInfo[i][j]->elem == NULL &&
1127 strcmp(elementName, mInfo[i][j]->name) == 0 &&
1128 hasVolume[i] (elem)) {
1130 mInfo[i][j]->elem = elem;
1131 getVolumeRange[i] (elem, &mInfo[i][j]->min, &mInfo[i][j]->max);
1132 mInfo[i][j]->volume = mInfo[i][j]->max;
1133 setVol[i] (elem, mInfo[i][j]->volume);
1134 if (i == SND_PCM_STREAM_PLAYBACK &&
1135 snd_mixer_selem_has_playback_switch (elem))
1136 snd_mixer_selem_set_playback_switch_all (elem, 1);
1142 LOGD("mixer initialized.");
1145 ALSAMixer::~ALSAMixer()
1147 for (int i = 0; i <= SND_PCM_STREAM_LAST; i++) {
1148 if (mMixer[i]) snd_mixer_close (mMixer[i]);
1149 if (mMaster[i]) delete mMaster[i];
1150 for (int j = 0; j <= MIXER_LAST; j++) {
1151 if (mInfo[i][j]) delete mInfo[i][j];
1154 LOGD("mixer destroyed.");
1157 status_t ALSAMixer::setMasterVolume(float volume)
1159 mixer_info_t *info = mMaster[SND_PCM_STREAM_PLAYBACK];
1160 if (!info || !info->elem) return INVALID_OPERATION;
1162 long minVol = info->min;
1163 long maxVol = info->max;
1165 // Make sure volume is between bounds.
1166 long vol = minVol + volume * (maxVol - minVol);
1167 if (vol > maxVol) vol = maxVol;
1168 if (vol < minVol) vol = minVol;
1171 snd_mixer_selem_set_playback_volume_all (info->elem, vol);
1176 status_t ALSAMixer::setMasterGain(float gain)
1178 mixer_info_t *info = mMaster[SND_PCM_STREAM_CAPTURE];
1179 if (!info || !info->elem) return INVALID_OPERATION;
1181 long minVol = info->min;
1182 long maxVol = info->max;
1184 // Make sure volume is between bounds.
1185 long vol = minVol + gain * (maxVol - minVol);
1186 if (vol > maxVol) vol = maxVol;
1187 if (vol < minVol) vol = minVol;
1190 snd_mixer_selem_set_capture_volume_all (info->elem, vol);
1195 status_t ALSAMixer::setVolume(mixer_types mixer, float volume)
1197 mixer_info_t *info = mInfo[mixer][SND_PCM_STREAM_PLAYBACK];
1198 if (!info || !info->elem) return INVALID_OPERATION;
1200 long minVol = info->min;
1201 long maxVol = info->max;
1203 // Make sure volume is between bounds.
1204 long vol = minVol + volume * (maxVol - minVol);
1205 if (vol > maxVol) vol = maxVol;
1206 if (vol < minVol) vol = minVol;
1209 snd_mixer_selem_set_playback_volume_all (info->elem, vol);
1214 status_t ALSAMixer::setGain(mixer_types mixer, float gain)
1216 mixer_info_t *info = mInfo[mixer][SND_PCM_STREAM_CAPTURE];
1217 if (!info || !info->elem) return INVALID_OPERATION;
1219 long minVol = info->min;
1220 long maxVol = info->max;
1222 // Make sure volume is between bounds.
1223 long vol = minVol + gain * (maxVol - minVol);
1224 if (vol > maxVol) vol = maxVol;
1225 if (vol < minVol) vol = minVol;
1228 snd_mixer_selem_set_capture_volume_all (info->elem, vol);
1233 status_t ALSAMixer::setCaptureMuteState(mixer_types mixer, bool state)
1235 mixer_info_t *info = mInfo[mixer][SND_PCM_STREAM_CAPTURE];
1236 if (!info || !info->elem) return INVALID_OPERATION;
1238 if (info->mute == state) return NO_ERROR;
1240 if (snd_mixer_selem_has_capture_switch (info->elem)) {
1242 int err = snd_mixer_selem_set_capture_switch_all (info->elem, static_cast<int>(!state));
1244 LOGE("Unable to %s capture mixer switch %s",
1245 state ? "enable" : "disable", info->name);
1246 return INVALID_OPERATION;
1254 status_t ALSAMixer::getCaptureMuteState(mixer_types mixer, bool *state)
1256 mixer_info_t *info = mInfo[mixer][SND_PCM_STREAM_CAPTURE];
1257 if (!info || !info->elem) return INVALID_OPERATION;
1259 if (! state) return BAD_VALUE;
1261 *state = info->mute;
1266 status_t ALSAMixer::setPlaybackMuteState(mixer_types mixer, bool state)
1268 mixer_info_t *info = mInfo[mixer][SND_PCM_STREAM_PLAYBACK];
1269 if (!info || !info->elem) return INVALID_OPERATION;
1271 if (snd_mixer_selem_has_playback_switch (info->elem)) {
1273 int err = snd_mixer_selem_set_playback_switch_all (info->elem, static_cast<int>(!state));
1275 LOGE("Unable to %s playback mixer switch %s",
1276 state ? "enable" : "disable", info->name);
1277 return INVALID_OPERATION;
1285 status_t ALSAMixer::getPlaybackMuteState(mixer_types mixer, bool *state)
1287 mixer_info_t *info = mInfo[SND_PCM_STREAM_PLAYBACK][mixer];
1288 if (!info || !info->elem) return INVALID_OPERATION;
1290 if (! state) return BAD_VALUE;
1292 *state = info->mute;
1297 // ----------------------------------------------------------------------------
1299 }; // namespace android