1 /* AudioHardwareALSA.cpp
3 ** Copyright 2008-2009 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_legacy/power.h>
35 #include <alsa/asoundlib.h>
36 #include "AudioHardwareALSA.h"
38 #ifndef ALSA_DEFAULT_SAMPLE_RATE
39 #define ALSA_DEFAULT_SAMPLE_RATE 44100 // in Hz
42 #define SND_MIXER_VOL_RANGE_MIN (0)
43 #define SND_MIXER_VOL_RANGE_MAX (100)
45 #define ALSA_NAME_MAX 128
47 #define ALSA_STRCAT(x,y) \
48 if (strlen(x) + strlen(y) < ALSA_NAME_MAX) \
53 extern int ffs(int i);
56 // Make sure this prototype is consistent with what's in
57 // external/libasound/alsa-lib-1.0.16/src/pcm/pcm_null.c!
59 extern int snd_pcm_null_open(snd_pcm_t **pcmp,
61 snd_pcm_stream_t stream,
65 // Function for dlsym() to look up for creating a new AudioHardwareInterface.
67 android::AudioHardwareInterface *createAudioHardware(void) {
68 return new android::AudioHardwareALSA();
75 typedef AudioSystem::audio_routes audio_routes;
77 #define ROUTE_ALL AudioSystem::ROUTE_ALL
78 #define ROUTE_EARPIECE AudioSystem::ROUTE_EARPIECE
79 #define ROUTE_SPEAKER AudioSystem::ROUTE_SPEAKER
80 #define ROUTE_BLUETOOTH_SCO AudioSystem::ROUTE_BLUETOOTH_SCO
81 #define ROUTE_HEADSET AudioSystem::ROUTE_HEADSET
82 #define ROUTE_BLUETOOTH_A2DP AudioSystem::ROUTE_BLUETOOTH_A2DP
84 // ----------------------------------------------------------------------------
86 static const int DEFAULT_SAMPLE_RATE = ALSA_DEFAULT_SAMPLE_RATE;
88 static const char _nullALSADeviceName[] = "NULL_Device";
90 static void ALSAErrorHandler(const char *file,
102 l = snprintf(buf, BUFSIZ, "%s:%i:(%s) ", file, line, function);
103 vsnprintf(buf + l, BUFSIZ - l, fmt, arg);
104 buf[BUFSIZ-1] = '\0';
105 LOG(LOG_ERROR, "ALSALib", buf);
109 // ----------------------------------------------------------------------------
111 /* The following table(s) need to match in order of the route bits
113 static const char *deviceSuffix[] = {
114 /* ROUTE_EARPIECE */ "_Earpiece",
115 /* ROUTE_SPEAKER */ "_Speaker",
116 /* ROUTE_BLUETOOTH_SCO */ "_Bluetooth",
117 /* ROUTE_HEADSET */ "_Headset",
118 /* ROUTE_BLUETOOTH_A2DP */ "_Bluetooth-A2DP",
121 static const int deviceSuffixLen = (sizeof(deviceSuffix) / sizeof(char *));
125 struct alsa_properties_t
127 const audio_routes routes;
128 const char *propName;
129 const char *propDefault;
133 static alsa_properties_t masterPlaybackProp = {
134 ROUTE_ALL, "alsa.mixer.playback.master", "PCM", NULL
137 static alsa_properties_t masterCaptureProp = {
138 ROUTE_ALL, "alsa.mixer.capture.master", "Capture", NULL
141 static alsa_properties_t
142 mixerMasterProp[SND_PCM_STREAM_LAST+1] = {
143 { ROUTE_ALL, "alsa.mixer.playback.master", "PCM", NULL},
144 { ROUTE_ALL, "alsa.mixer.capture.master", "Capture", NULL}
147 static alsa_properties_t
148 mixerProp[][SND_PCM_STREAM_LAST+1] = {
150 {ROUTE_EARPIECE, "alsa.mixer.playback.earpiece", "Earpiece", NULL},
151 {ROUTE_EARPIECE, "alsa.mixer.capture.earpiece", "Capture", NULL}
154 {ROUTE_SPEAKER, "alsa.mixer.playback.speaker", "Speaker", NULL},
155 {ROUTE_SPEAKER, "alsa.mixer.capture.speaker", "", NULL}
158 {ROUTE_BLUETOOTH_SCO, "alsa.mixer.playback.bluetooth.sco", "Bluetooth", NULL},
159 {ROUTE_BLUETOOTH_SCO, "alsa.mixer.capture.bluetooth.sco", "Bluetooth Capture", NULL}
162 {ROUTE_HEADSET, "alsa.mixer.playback.headset", "Headphone", NULL},
163 {ROUTE_HEADSET, "alsa.mixer.capture.headset", "Capture", NULL}
166 {ROUTE_BLUETOOTH_A2DP, "alsa.mixer.playback.bluetooth.a2dp", "Bluetooth A2DP", NULL},
167 {ROUTE_BLUETOOTH_A2DP, "alsa.mixer.capture.bluetooth.a2dp", "Bluetooth A2DP Capture", NULL}
170 {static_cast<audio_routes>(0), NULL, NULL, NULL},
171 {static_cast<audio_routes>(0), NULL, NULL, NULL}
175 // ----------------------------------------------------------------------------
177 AudioHardwareALSA::AudioHardwareALSA() :
181 snd_lib_error_set_handler(&ALSAErrorHandler);
182 mMixer = new ALSAMixer;
185 AudioHardwareALSA::~AudioHardwareALSA()
187 if (mOutput) delete mOutput;
188 if (mInput) delete mInput;
189 if (mMixer) delete mMixer;
192 status_t AudioHardwareALSA::initCheck()
194 if (mMixer && mMixer->isValid())
200 status_t AudioHardwareALSA::standby()
203 return mOutput->standby();
208 status_t AudioHardwareALSA::setVoiceVolume(float volume)
210 // The voice volume is used by the VOICE_CALL audio stream.
212 return mMixer->setVolume(ROUTE_EARPIECE, volume);
214 return INVALID_OPERATION;
217 status_t AudioHardwareALSA::setMasterVolume(float volume)
220 return mMixer->setMasterVolume(volume);
222 return INVALID_OPERATION;
226 AudioHardwareALSA::openOutputStream(int format,
231 AutoMutex lock(mLock);
233 // only one output stream allowed
235 *status = ALREADY_EXISTS;
239 AudioStreamOutALSA *out = new AudioStreamOutALSA(this);
241 *status = out->set(format, channelCount, sampleRate);
243 if (*status == NO_ERROR) {
245 // Some information is expected to be available immediately after
246 // the device is open.
247 uint32_t routes = mRoutes[mMode];
248 mOutput->setDevice(mMode, routes);
258 AudioHardwareALSA::openInputStream(int format,
262 AudioSystem::audio_in_acoustics acoustics)
264 AutoMutex lock(mLock);
266 // only one input stream allowed
268 *status = ALREADY_EXISTS;
272 AudioStreamInALSA *in = new AudioStreamInALSA(this);
274 *status = in->set(format, channelCount, sampleRate);
275 if (*status == NO_ERROR) {
277 // Some information is expected to be available immediately after
278 // the device is open.
279 uint32_t routes = mRoutes[mMode];
280 mInput->setDevice(mMode, routes); return mInput;
288 status_t AudioHardwareALSA::doRouting()
292 AutoMutex lock(mLock);
295 routes = mRoutes[mMode];
296 return mOutput->setDevice(mMode, routes);
301 status_t AudioHardwareALSA::setMicMute(bool state)
304 return mMixer->setCaptureMuteState(ROUTE_EARPIECE, state);
309 status_t AudioHardwareALSA::getMicMute(bool *state)
312 return mMixer->getCaptureMuteState(ROUTE_EARPIECE, state);
317 status_t AudioHardwareALSA::dump(int fd, const Vector<String16>& args)
322 // ----------------------------------------------------------------------------
324 ALSAStreamOps::ALSAStreamOps() :
331 if (snd_pcm_hw_params_malloc(&mHardwareParams) < 0) {
332 LOG_ALWAYS_FATAL("Failed to allocate ALSA hardware parameters!");
335 if (snd_pcm_sw_params_malloc(&mSoftwareParams) < 0) {
336 LOG_ALWAYS_FATAL("Failed to allocate ALSA software parameters!");
340 ALSAStreamOps::~ALSAStreamOps()
342 AutoMutex lock(mLock);
347 snd_pcm_hw_params_free(mHardwareParams);
350 snd_pcm_sw_params_free(mSoftwareParams);
353 status_t ALSAStreamOps::set(int format,
358 mDefaults->channels = channels;
361 mDefaults->sampleRate = rate;
365 case AudioSystem::DEFAULT:
368 case AudioSystem::PCM_16_BIT:
369 mDefaults->format = SND_PCM_FORMAT_S16_LE;
372 case AudioSystem::PCM_8_BIT:
373 mDefaults->format = SND_PCM_FORMAT_S8;
377 LOGE("Unknown PCM format %i. Forcing default", format);
384 uint32_t ALSAStreamOps::sampleRate() const
392 return snd_pcm_hw_params_get_rate(mHardwareParams, &rate, 0) < 0
393 ? 0 : static_cast<uint32_t>(rate);
396 status_t ALSAStreamOps::sampleRate(uint32_t rate)
399 unsigned int requestedRate;
405 stream = streamName();
406 requestedRate = rate;
407 err = snd_pcm_hw_params_set_rate_near(mHandle,
413 LOGE("Unable to set %s sample rate to %u: %s",
414 stream, rate, snd_strerror(err));
417 if (requestedRate != rate) {
418 // Some devices have a fixed sample rate, and can not be changed.
419 // This may cause resampling problems; i.e. PCM playback will be too
421 LOGW("Requested rate (%u HZ) does not match actual rate (%u HZ)",
422 rate, requestedRate);
425 LOGD("Set %s sample rate to %u HZ", stream, requestedRate);
431 // Return the number of bytes (not frames)
433 size_t ALSAStreamOps::bufferSize() const
440 snd_pcm_uframes_t bufferSize = 0;
441 snd_pcm_uframes_t periodSize = 0;
443 err = snd_pcm_get_params(mHandle, &bufferSize, &periodSize);
448 return static_cast<size_t>(snd_pcm_frames_to_bytes(mHandle, bufferSize));
451 int ALSAStreamOps::format() const
453 snd_pcm_format_t ALSAFormat;
454 int pcmFormatBitWidth;
455 int audioSystemFormat;
460 if (snd_pcm_hw_params_get_format(mHardwareParams, &ALSAFormat) < 0) {
464 pcmFormatBitWidth = snd_pcm_format_physical_width(ALSAFormat);
465 audioSystemFormat = AudioSystem::DEFAULT;
466 switch(pcmFormatBitWidth) {
468 audioSystemFormat = AudioSystem::PCM_8_BIT;
472 audioSystemFormat = AudioSystem::PCM_16_BIT;
476 LOG_FATAL("Unknown AudioSystem bit width %i!", pcmFormatBitWidth);
479 return audioSystemFormat;
482 int ALSAStreamOps::channelCount() const
490 err = snd_pcm_hw_params_get_channels(mHardwareParams, &val);
492 LOGE("Unable to get device channel count: %s",
500 status_t ALSAStreamOps::channelCount(int channels) {
506 err = snd_pcm_hw_params_set_channels(mHandle, mHardwareParams, channels);
508 LOGE("Unable to set channel count to %i: %s",
509 channels, snd_strerror(err));
513 LOGD("Using %i %s for %s.",
514 channels, channels == 1 ? "channel" : "channels", streamName());
519 status_t ALSAStreamOps::open(int mode, uint32_t device)
521 const char *stream = streamName();
522 const char *devName = deviceName(mode, device);
527 // The PCM stream is opened in blocking mode, per ALSA defaults. The
528 // AudioFlinger seems to assume blocking mode too, so asynchronous mode
529 // should not be used.
530 err = snd_pcm_open(&mHandle, devName, mDefaults->direction, 0);
533 // See if there is a less specific name we can try.
534 // Note: We are changing the contents of a const char * here.
535 char *tail = strrchr(devName, '_');
541 // None of the Android defined audio devices exist. Open a generic one.
543 err = snd_pcm_open(&mHandle, devName, mDefaults->direction, 0);
545 // Last resort is the NULL device (i.e. the bit bucket).
546 devName = _nullALSADeviceName;
547 err = snd_pcm_open(&mHandle, devName, mDefaults->direction, 0);
554 LOGI("Initialized ALSA %s device %s", stream, devName);
558 void ALSAStreamOps::close()
560 snd_pcm_t *handle = mHandle;
564 snd_pcm_close(handle);
570 status_t ALSAStreamOps::setSoftwareParams()
577 // Get the current software parameters
578 err = snd_pcm_sw_params_current(mHandle, mSoftwareParams);
580 LOGE("Unable to get software parameters: %s", snd_strerror(err));
584 snd_pcm_uframes_t bufferSize = 0;
585 snd_pcm_uframes_t periodSize = 0;
586 snd_pcm_uframes_t startThreshold;
588 // Configure ALSA to start the transfer when the buffer is almost full.
589 snd_pcm_get_params(mHandle, &bufferSize, &periodSize);
591 if (mDefaults->direction == SND_PCM_STREAM_PLAYBACK) {
592 // For playback, configure ALSA to start the transfer when the
593 // buffer is almost full.
594 startThreshold = (bufferSize / periodSize) * periodSize;
597 // For recording, configure ALSA to start the transfer on the
602 err = snd_pcm_sw_params_set_start_threshold(mHandle,
606 LOGE("Unable to set start threshold to %lu frames: %s",
607 startThreshold, snd_strerror(err));
611 // Stop the transfer when the buffer is full.
612 err = snd_pcm_sw_params_set_stop_threshold(mHandle,
616 LOGE("Unable to set stop threshold to %lu frames: %s",
617 bufferSize, snd_strerror(err));
621 // Allow the transfer to start when at least periodSize samples can be
623 err = snd_pcm_sw_params_set_avail_min(mHandle,
627 LOGE("Unable to configure available minimum to %lu: %s",
628 periodSize, snd_strerror(err));
632 // Commit the software parameters back to the device.
633 err = snd_pcm_sw_params(mHandle, mSoftwareParams);
635 LOGE("Unable to configure software parameters: %s",
643 status_t ALSAStreamOps::setPCMFormat(snd_pcm_format_t format)
645 const char *formatDesc;
646 const char *formatName;
650 // snd_pcm_format_description() and snd_pcm_format_name() do not perform
651 // proper bounds checking.
652 validFormat = (static_cast<int>(format) > SND_PCM_FORMAT_UNKNOWN) &&
653 (static_cast<int>(format) <= SND_PCM_FORMAT_LAST);
654 formatDesc = validFormat ?
655 snd_pcm_format_description(format) : "Invalid Format";
656 formatName = validFormat ?
657 snd_pcm_format_name(format) : "UNKNOWN";
659 err = snd_pcm_hw_params_set_format(mHandle, mHardwareParams, format);
661 LOGE("Unable to configure PCM format %s (%s): %s",
662 formatName, formatDesc, snd_strerror(err));
666 LOGD("Set %s PCM format to %s (%s)", streamName(), formatName, formatDesc);
670 status_t ALSAStreamOps::setHardwareResample(bool resample)
674 err = snd_pcm_hw_params_set_rate_resample(mHandle,
676 static_cast<int>(resample));
678 LOGE("Unable to %s hardware resampling: %s",
679 resample ? "enable" : "disable",
686 const char *ALSAStreamOps::streamName()
688 // Don't use snd_pcm_stream(mHandle), as the PCM stream may not be
689 // opened yet. In such case, snd_pcm_stream() will abort().
690 return snd_pcm_stream_name(mDefaults->direction);
694 // Set playback or capture PCM device. It's possible to support audio output
695 // or input from multiple devices by using the ALSA plugins, but this is
696 // not supported for simplicity.
698 // The AudioHardwareALSA API does not allow one to set the input routing.
700 // If the "routes" value does not map to a valid device, the default playback
703 status_t ALSAStreamOps::setDevice(int mode, uint32_t device)
705 // Close off previously opened device.
706 // It would be nice to determine if the underlying device actually
707 // changes, but we might be manipulating mixer settings (see asound.conf).
711 const char *stream = streamName();
713 status_t status = open (mode, device);
716 if (status != NO_ERROR)
719 err = snd_pcm_hw_params_any(mHandle, mHardwareParams);
721 LOGE("Unable to configure hardware: %s", snd_strerror(err));
725 status = setPCMFormat(mDefaults->format);
727 // Set the interleaved read and write format.
728 err = snd_pcm_hw_params_set_access(mHandle, mHardwareParams,
729 SND_PCM_ACCESS_RW_INTERLEAVED);
731 LOGE("Unable to configure PCM read/write format: %s",
737 // Some devices do not have the default two channels. Force an error to
738 // prevent AudioMixer from crashing and taking the whole system down.
740 // Note that some devices will return an -EINVAL if the channel count
741 // is queried before it has been set. i.e. calling channelCount()
742 // before channelCount(channels) may return -EINVAL.
744 status = channelCount(mDefaults->channels);
745 if (status != NO_ERROR)
748 // Don't check for failure; some devices do not support the default
750 sampleRate(mDefaults->sampleRate);
752 // Disable hardware resampling.
753 status = setHardwareResample(false);
754 if (status != NO_ERROR)
757 snd_pcm_uframes_t bufferSize = mDefaults->bufferSize;
758 unsigned int latency = mDefaults->latency;
760 // Make sure we have at least the size we originally wanted
761 err = snd_pcm_hw_params_set_buffer_size(mHandle, mHardwareParams, bufferSize);
763 LOGE("Unable to set buffer size to %d: %s",
764 (int)bufferSize, snd_strerror(err));
768 // Setup buffers for latency
769 err = snd_pcm_hw_params_set_buffer_time_near (mHandle, mHardwareParams,
772 /* That didn't work, set the period instead */
773 unsigned int periodTime = latency / 4;
774 err = snd_pcm_hw_params_set_period_time_near (mHandle, mHardwareParams,
777 LOGE("Unable to set the period time for latency: %s", snd_strerror(err));
780 snd_pcm_uframes_t periodSize;
781 err = snd_pcm_hw_params_get_period_size (mHardwareParams, &periodSize, NULL);
783 LOGE("Unable to get the period size for latency: %s", snd_strerror(err));
786 bufferSize = periodSize * 4;
787 if (bufferSize < mDefaults->bufferSize)
788 bufferSize = mDefaults->bufferSize;
789 err = snd_pcm_hw_params_set_buffer_size_near (mHandle, mHardwareParams, &bufferSize);
791 LOGE("Unable to set the buffer size for latency: %s", snd_strerror(err));
795 // OK, we got buffer time near what we expect. See what that did for bufferSize.
796 err = snd_pcm_hw_params_get_buffer_size (mHardwareParams, &bufferSize);
798 LOGE("Unable to get the buffer size for latency: %s", snd_strerror(err));
801 // Does set_buffer_time_near change the passed value? It should.
802 err = snd_pcm_hw_params_get_buffer_time (mHardwareParams, &latency, NULL);
804 LOGE("Unable to get the buffer time for latency: %s", snd_strerror(err));
807 unsigned int periodTime = latency / 4;
808 err = snd_pcm_hw_params_set_period_time_near (mHandle, mHardwareParams,
811 LOGE("Unable to set the period time for latency: %s", snd_strerror(err));
816 LOGD("Buffer size: %d", (int)bufferSize);
817 LOGD("Latency: %d", (int)latency);
819 mDefaults->bufferSize = bufferSize;
820 mDefaults->latency = latency;
822 // Commit the hardware parameters back to the device.
823 err = snd_pcm_hw_params(mHandle, mHardwareParams);
825 LOGE("Unable to set hardware parameters: %s", snd_strerror(err));
829 status = setSoftwareParams();
834 const char *ALSAStreamOps::deviceName(int mode, uint32_t device)
836 static char devString[ALSA_NAME_MAX];
840 strcpy (devString, mDefaults->devicePrefix);
842 for (dev=0; device; dev++)
843 if (device & (1 << dev)) {
844 /* Don't go past the end of our list */
845 if (dev >= deviceSuffixLen)
847 ALSA_STRCAT (devString, deviceSuffix[dev]);
848 device &= ~(1 << dev);
854 case AudioSystem::MODE_NORMAL:
855 ALSA_STRCAT (devString, "_normal");
857 case AudioSystem::MODE_RINGTONE:
858 ALSA_STRCAT (devString, "_ringtone");
860 case AudioSystem::MODE_IN_CALL:
861 ALSA_STRCAT (devString, "_incall");
868 // ----------------------------------------------------------------------------
870 AudioStreamOutALSA::AudioStreamOutALSA(AudioHardwareALSA *parent) :
874 static StreamDefaults _defaults = {
875 devicePrefix : "AndroidPlayback",
876 direction : SND_PCM_STREAM_PLAYBACK,
877 format : SND_PCM_FORMAT_S16_LE, // AudioSystem::PCM_16_BIT
879 sampleRate : DEFAULT_SAMPLE_RATE,
880 latency : 250000, // Desired Delay in usec
881 bufferSize : 16384, // Desired Number of samples
884 setStreamDefaults(&_defaults);
887 AudioStreamOutALSA::~AudioStreamOutALSA()
890 mParent->mOutput = NULL;
893 int AudioStreamOutALSA::channelCount() const
895 int c = ALSAStreamOps::channelCount();
897 // AudioMixer will seg fault if it doesn't have two channels.
899 "AudioMixer expects two channels, but only %i found!", c);
903 status_t AudioStreamOutALSA::setVolume(float volume)
905 if (! mParent->mMixer || ! mDevice)
908 return mParent->mMixer->setVolume (mDevice, volume);
911 ssize_t AudioStreamOutALSA::write(const void *buffer, size_t bytes)
916 AutoMutex lock(mLock);
922 acquire_wake_lock (PARTIAL_WAKE_LOCK, "AudioLock");
923 ALSAStreamOps::setDevice(mMode, mDevice);
927 n = snd_pcm_writei(mHandle,
929 snd_pcm_bytes_to_frames(mHandle, bytes));
930 if (n < 0 && mHandle) {
931 // snd_pcm_recover() will return 0 if successful in recovering from
932 // an error, or -errno if the error was unrecoverable.
933 n = snd_pcm_recover(mHandle, n, 0);
936 return static_cast<ssize_t>(n);
939 status_t AudioStreamOutALSA::dump(int fd, const Vector<String16>& args)
944 status_t AudioStreamOutALSA::setDevice(int mode, uint32_t newDevice)
946 AutoMutex lock(mLock);
948 return ALSAStreamOps::setDevice(mode, newDevice);
951 status_t AudioStreamOutALSA::standby()
953 AutoMutex lock(mLock);
956 snd_pcm_drain (mHandle);
959 release_wake_lock ("AudioLock");
966 bool AudioStreamOutALSA::isStandby()
971 #define USEC_TO_MSEC(x) ((x + 999) / 1000)
973 uint32_t AudioStreamOutALSA::latency() const
975 // Android wants latency in milliseconds.
976 return USEC_TO_MSEC (mDefaults->latency);
979 // ----------------------------------------------------------------------------
981 AudioStreamInALSA::AudioStreamInALSA(AudioHardwareALSA *parent) :
984 static StreamDefaults _defaults = {
985 devicePrefix : "AndroidRecord",
986 direction : SND_PCM_STREAM_CAPTURE,
987 format : SND_PCM_FORMAT_S16_LE, // AudioSystem::PCM_16_BIT
989 sampleRate : AudioRecord::DEFAULT_SAMPLE_RATE,
990 latency : 250000, // Desired Delay in usec
991 bufferSize : 16384, // Desired Number of samples
994 setStreamDefaults(&_defaults);
997 AudioStreamInALSA::~AudioStreamInALSA()
999 mParent->mInput = NULL;
1002 status_t AudioStreamInALSA::setGain(float gain)
1004 if (mParent->mMixer)
1005 return mParent->mMixer->setMasterGain (gain);
1010 ssize_t AudioStreamInALSA::read(void *buffer, ssize_t bytes)
1012 snd_pcm_sframes_t n;
1015 AutoMutex lock(mLock);
1017 n = snd_pcm_readi(mHandle,
1019 snd_pcm_bytes_to_frames(mHandle, bytes));
1020 if (n < 0 && mHandle) {
1021 n = snd_pcm_recover(mHandle, n, 0);
1024 return static_cast<ssize_t>(n);
1027 status_t AudioStreamInALSA::dump(int fd, const Vector<String16>& args)
1032 status_t AudioStreamInALSA::setDevice(int mode, uint32_t newDevice)
1034 AutoMutex lock(mLock);
1036 return ALSAStreamOps::setDevice(mode, newDevice);
1039 status_t AudioStreamInALSA::standby()
1041 AutoMutex lock(mLock);
1046 // ----------------------------------------------------------------------------
1052 min(SND_MIXER_VOL_RANGE_MIN),
1053 max(SND_MIXER_VOL_RANGE_MAX),
1058 snd_mixer_elem_t *elem;
1063 char name[ALSA_NAME_MAX];
1066 static int initMixer (snd_mixer_t **mixer, const char *name)
1070 if ((err = snd_mixer_open(mixer, 0)) < 0) {
1071 LOGE("Unable to open mixer: %s", snd_strerror(err));
1075 if ((err = snd_mixer_attach(*mixer, name)) < 0) {
1076 LOGE("Unable to attach mixer to device %s: %s",
1077 name, snd_strerror(err));
1079 if ((err = snd_mixer_attach(*mixer, "hw:00")) < 0) {
1080 LOGE("Unable to attach mixer to device default: %s",
1083 snd_mixer_close (*mixer);
1089 if ((err = snd_mixer_selem_register(*mixer, NULL, NULL)) < 0) {
1090 LOGE("Unable to register mixer elements: %s", snd_strerror(err));
1091 snd_mixer_close (*mixer);
1096 // Get the mixer controls from the kernel
1097 if ((err = snd_mixer_load(*mixer)) < 0) {
1098 LOGE("Unable to load mixer elements: %s", snd_strerror(err));
1099 snd_mixer_close (*mixer);
1107 typedef int (*hasVolume_t)(snd_mixer_elem_t*);
1109 static const hasVolume_t hasVolume[] = {
1110 snd_mixer_selem_has_playback_volume,
1111 snd_mixer_selem_has_capture_volume
1114 typedef int (*getVolumeRange_t)(snd_mixer_elem_t*, long int*, long int*);
1116 static const getVolumeRange_t getVolumeRange[] = {
1117 snd_mixer_selem_get_playback_volume_range,
1118 snd_mixer_selem_get_capture_volume_range
1121 typedef int (*setVolume_t)(snd_mixer_elem_t*, long int);
1123 static const setVolume_t setVol[] = {
1124 snd_mixer_selem_set_playback_volume_all,
1125 snd_mixer_selem_set_capture_volume_all
1128 ALSAMixer::ALSAMixer()
1132 initMixer (&mMixer[SND_PCM_STREAM_PLAYBACK], "AndroidPlayback");
1133 initMixer (&mMixer[SND_PCM_STREAM_CAPTURE], "AndroidRecord");
1135 snd_mixer_selem_id_t *sid;
1136 snd_mixer_selem_id_alloca(&sid);
1138 for (int i = 0; i <= SND_PCM_STREAM_LAST; i++) {
1140 mixer_info_t *info = mixerMasterProp[i].mInfo = new mixer_info_t;
1142 property_get (mixerMasterProp[i].propName,
1144 mixerMasterProp[i].propDefault);
1146 for (snd_mixer_elem_t *elem = snd_mixer_first_elem(mMixer[i]);
1148 elem = snd_mixer_elem_next(elem)) {
1150 if (!snd_mixer_selem_is_active(elem))
1153 snd_mixer_selem_get_id(elem, sid);
1155 // Find PCM playback volume control element.
1156 const char *elementName = snd_mixer_selem_id_get_name(sid);
1158 if (hasVolume[i] (elem))
1159 LOGD ("Mixer: element name: '%s'", elementName);
1161 if (info->elem == NULL &&
1162 strcmp(elementName, info->name) == 0 &&
1163 hasVolume[i] (elem)) {
1166 getVolumeRange[i] (elem, &info->min, &info->max);
1167 info->volume = info->max;
1168 setVol[i] (elem, info->volume);
1169 if (i == SND_PCM_STREAM_PLAYBACK &&
1170 snd_mixer_selem_has_playback_switch (elem))
1171 snd_mixer_selem_set_playback_switch_all (elem, 1);
1176 LOGD ("Mixer: master '%s' %s.", info->name, info->elem ? "found" : "not found");
1178 for (int j = 0; mixerProp[j][i].routes; j++) {
1180 mixer_info_t *info = mixerProp[j][i].mInfo = new mixer_info_t;
1182 property_get (mixerProp[j][i].propName,
1184 mixerProp[j][i].propDefault);
1186 for (snd_mixer_elem_t *elem = snd_mixer_first_elem(mMixer[i]);
1188 elem = snd_mixer_elem_next(elem)) {
1190 if (!snd_mixer_selem_is_active(elem))
1193 snd_mixer_selem_get_id(elem, sid);
1195 // Find PCM playback volume control element.
1196 const char *elementName = snd_mixer_selem_id_get_name(sid);
1198 if (info->elem == NULL &&
1199 strcmp(elementName, info->name) == 0 &&
1200 hasVolume[i] (elem)) {
1203 getVolumeRange[i] (elem, &info->min, &info->max);
1204 info->volume = info->max;
1205 setVol[i] (elem, info->volume);
1206 if (i == SND_PCM_STREAM_PLAYBACK &&
1207 snd_mixer_selem_has_playback_switch (elem))
1208 snd_mixer_selem_set_playback_switch_all (elem, 1);
1212 LOGD ("Mixer: route '%s' %s.", info->name, info->elem ? "found" : "not found");
1215 LOGD("mixer initialized.");
1218 ALSAMixer::~ALSAMixer()
1220 for (int i = 0; i <= SND_PCM_STREAM_LAST; i++) {
1221 if (mMixer[i]) snd_mixer_close (mMixer[i]);
1222 if (mixerMasterProp[i].mInfo) {
1223 delete mixerMasterProp[i].mInfo;
1224 mixerMasterProp[i].mInfo = NULL;
1226 for (int j = 0; mixerProp[j][i].routes; j++) {
1227 if (mixerProp[j][i].mInfo) {
1228 delete mixerProp[j][i].mInfo;
1229 mixerProp[j][i].mInfo = NULL;
1233 LOGD("mixer destroyed.");
1236 status_t ALSAMixer::setMasterVolume(float volume)
1238 mixer_info_t *info = mixerMasterProp[SND_PCM_STREAM_PLAYBACK].mInfo;
1239 if (!info || !info->elem) return INVALID_OPERATION;
1241 long minVol = info->min;
1242 long maxVol = info->max;
1244 // Make sure volume is between bounds.
1245 long vol = minVol + volume * (maxVol - minVol);
1246 if (vol > maxVol) vol = maxVol;
1247 if (vol < minVol) vol = minVol;
1250 snd_mixer_selem_set_playback_volume_all (info->elem, vol);
1255 status_t ALSAMixer::setMasterGain(float gain)
1257 mixer_info_t *info = mixerMasterProp[SND_PCM_STREAM_CAPTURE].mInfo;
1258 if (!info || !info->elem) return INVALID_OPERATION;
1260 long minVol = info->min;
1261 long maxVol = info->max;
1263 // Make sure volume is between bounds.
1264 long vol = minVol + gain * (maxVol - minVol);
1265 if (vol > maxVol) vol = maxVol;
1266 if (vol < minVol) vol = minVol;
1269 snd_mixer_selem_set_capture_volume_all (info->elem, vol);
1274 status_t ALSAMixer::setVolume(uint32_t device, float volume)
1276 for (int j = 0; mixerProp[j][SND_PCM_STREAM_PLAYBACK].routes; j++)
1277 if (mixerProp[j][SND_PCM_STREAM_PLAYBACK].routes & device) {
1279 mixer_info_t *info = mixerProp[j][SND_PCM_STREAM_PLAYBACK].mInfo;
1280 if (!info || !info->elem) return INVALID_OPERATION;
1282 long minVol = info->min;
1283 long maxVol = info->max;
1285 // Make sure volume is between bounds.
1286 long vol = minVol + volume * (maxVol - minVol);
1287 if (vol > maxVol) vol = maxVol;
1288 if (vol < minVol) vol = minVol;
1291 snd_mixer_selem_set_playback_volume_all (info->elem, vol);
1297 status_t ALSAMixer::setGain(uint32_t device, float gain)
1299 for (int j = 0; mixerProp[j][SND_PCM_STREAM_CAPTURE].routes; j++)
1300 if (mixerProp[j][SND_PCM_STREAM_CAPTURE].routes & device) {
1302 mixer_info_t *info = mixerProp[j][SND_PCM_STREAM_CAPTURE].mInfo;
1303 if (!info || !info->elem) return INVALID_OPERATION;
1305 long minVol = info->min;
1306 long maxVol = info->max;
1308 // Make sure volume is between bounds.
1309 long vol = minVol + gain * (maxVol - minVol);
1310 if (vol > maxVol) vol = maxVol;
1311 if (vol < minVol) vol = minVol;
1314 snd_mixer_selem_set_capture_volume_all (info->elem, vol);
1320 status_t ALSAMixer::setCaptureMuteState(uint32_t device, bool state)
1322 for (int j = 0; mixerProp[j][SND_PCM_STREAM_CAPTURE].routes; j++)
1323 if (mixerProp[j][SND_PCM_STREAM_CAPTURE].routes & device) {
1325 mixer_info_t *info = mixerProp[j][SND_PCM_STREAM_CAPTURE].mInfo;
1326 if (!info || !info->elem) return INVALID_OPERATION;
1328 if (snd_mixer_selem_has_capture_switch (info->elem)) {
1330 int err = snd_mixer_selem_set_capture_switch_all (info->elem, static_cast<int>(!state));
1332 LOGE("Unable to %s capture mixer switch %s",
1333 state ? "enable" : "disable", info->name);
1334 return INVALID_OPERATION;
1344 status_t ALSAMixer::getCaptureMuteState(uint32_t device, bool *state)
1346 if (! state) return BAD_VALUE;
1348 for (int j = 0; mixerProp[j][SND_PCM_STREAM_CAPTURE].routes; j++)
1349 if (mixerProp[j][SND_PCM_STREAM_CAPTURE].routes & device) {
1351 mixer_info_t *info = mixerProp[j][SND_PCM_STREAM_CAPTURE].mInfo;
1352 if (!info || !info->elem) return INVALID_OPERATION;
1354 *state = info->mute;
1361 status_t ALSAMixer::setPlaybackMuteState(uint32_t device, bool state)
1363 for (int j = 0; mixerProp[j][SND_PCM_STREAM_PLAYBACK].routes; j++)
1364 if (mixerProp[j][SND_PCM_STREAM_PLAYBACK].routes & device) {
1366 mixer_info_t *info = mixerProp[j][SND_PCM_STREAM_PLAYBACK].mInfo;
1367 if (!info || !info->elem) return INVALID_OPERATION;
1369 if (snd_mixer_selem_has_playback_switch (info->elem)) {
1371 int err = snd_mixer_selem_set_playback_switch_all (info->elem, static_cast<int>(!state));
1373 LOGE("Unable to %s playback mixer switch %s",
1374 state ? "enable" : "disable", info->name);
1375 return INVALID_OPERATION;
1385 status_t ALSAMixer::getPlaybackMuteState(uint32_t device, bool *state)
1387 if (! state) return BAD_VALUE;
1389 for (int j = 0; mixerProp[j][SND_PCM_STREAM_PLAYBACK].routes; j++)
1390 if (mixerProp[j][SND_PCM_STREAM_PLAYBACK].routes & device) {
1392 mixer_info_t *info = mixerProp[j][SND_PCM_STREAM_PLAYBACK].mInfo;
1393 if (!info || !info->elem) return INVALID_OPERATION;
1395 *state = info->mute;
1402 // ----------------------------------------------------------------------------
1404 }; // namespace android