1 /*
2 **
3 ** Copyright 2014, 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 #define LOG_TAG "AudioHAL:alsa_utils"
19
20 #include "alsa_utils.h"
21
22 #ifndef ALSA_UTILS_PRINT_FORMATS
23 #define ALSA_UTILS_PRINT_FORMATS 1
24 #endif
25
find_alsa_card_by_name(const char * name)26 int find_alsa_card_by_name(const char* name) {
27 int card_id = 0;
28 int ret = -1;
29 int fd;
30
31 do {
32 int fd;
33 int amt;
34 char tmp[256];
35
36 snprintf(tmp, sizeof(tmp), "/proc/asound/card%d/id", card_id);
37 tmp[sizeof(tmp) - 1] = 0;
38 fd = open(tmp, O_RDONLY);
39 if (fd < 0)
40 break;
41
42 amt = read(fd, tmp, sizeof(tmp) - 1);
43 if (amt > 0) {
44 // replace the '\n' at the end of the proc file with '\0'
45 tmp[amt - 1] = 0;
46 if (!strcmp(name, tmp))
47 ret = card_id;
48 }
49
50 close(fd);
51
52 card_id++;
53 } while (ret < 0);
54
55 ALOGI("%s: returning card %d for name %s", __func__, ret, name);
56 return ret;
57 }
58
59 #ifdef __cplusplus
60 #include <tinyalsa/asoundlib.h>
61 #include <utils/misc.h>
62
63 namespace android {
64
65 static const char *kCtrlNames[] = {
66 "Basic Audio Supported",
67 "Speaker Allocation",
68 "Audio Mode Count",
69 "Audio Mode To Query",
70 "Query Mode : Format",
71 "Query Mode : Max Ch Count",
72 "Query Mode : Sample Rate Mask",
73 "Query Mode : PCM Bits/Sample Mask",
74 "Query Mode : Max Compressed Bitrate"
75 };
76 static const size_t kCtrlCount = sizeof(kCtrlNames)/sizeof(*kCtrlNames);
77 static const size_t kBasicAudNdx = 0;
78 static const size_t kSpeakerAlloc = 1;
79 static const size_t kModeCntNdx = 2;
80 static const size_t kModeSelNdx = 3;
81 static const size_t kFmtNdx = 4;
82 static const size_t kMaxChCntNdx = 5;
83 static const size_t kSampRateNdx = 6;
84 static const size_t kBPSNdx = 7;
85 static const size_t kMaxCompBRNdx = 8;
86
HDMIAudioCaps()87 HDMIAudioCaps::HDMIAudioCaps()
88 {
89 // Its unlikely we will need storage for more than 16 modes, but if we do,
90 // the vector will resize for us.
91 mModes.setCapacity(16);
92 reset();
93 }
94
loadCaps(int ALSADeviceID)95 bool HDMIAudioCaps::loadCaps(int ALSADeviceID) {
96 bool ret = false;
97 struct mixer* mixer = NULL;
98 struct mixer_ctl* ctrls[kCtrlCount] = {NULL};
99 int tmp, mode_cnt;
100 Mutex::Autolock _l(mLock);
101
102 ALOGE("%s: start", __func__);
103
104 reset_l();
105
106 // Open the mixer for the chosen ALSA device
107 if (NULL == (mixer = mixer_open(ALSADeviceID))) {
108 ALOGE("%s: mixer_open(%d) failed", __func__, ALSADeviceID);
109 goto bailout;
110 }
111
112 // Gather handles to all of the controls we will need in order to enumerate
113 // the audio capabilities of this HDMI link. No need to free/release these
114 // later, they are just pointers into the tinyalsa mixer structure itself.
115 for (size_t i = 0; i < kCtrlCount; ++i) {
116 ctrls[i] = mixer_get_ctl_by_name(mixer, kCtrlNames[i]);
117 if (NULL == ctrls[i]) {
118 ALOGE("%s: mixer_get_ctrl_by_name(%s) failed", __func__, kCtrlNames[i]);
119 goto bailout;
120 }
121 }
122
123 // Start by checking to see if this HDMI connection supports even basic
124 // audio. If it does not, there is no point in proceeding.
125 if ((tmp = mixer_ctl_get_value(ctrls[kBasicAudNdx], 0)) <= 0) {
126 ALOGI("%s: Basic audio not supported by attached device", __func__);
127 goto bailout;
128 }
129
130 // Looks like we support basic audio. Get a count of the available
131 // non-basic modes.
132 mBasicAudioSupported = true;
133 if ((mode_cnt = mixer_ctl_get_value(ctrls[kModeCntNdx], 0)) < 0)
134 goto bailout;
135
136 // Fetch the speaker allocation data block, if available.
137 if ((tmp = mixer_ctl_get_value(ctrls[kSpeakerAlloc], 0)) < 0)
138 goto bailout;
139 mSpeakerAlloc = static_cast<uint16_t>(tmp);
140 ALOGI("%s: Speaker Allocation Map for attached device is: 0x%hx", __func__, mSpeakerAlloc);
141
142 // If there are no non-basic modes available, then we are done. Be sure to
143 // flag this as a successful operation.
144 if (!mode_cnt) {
145 ret = true;
146 goto bailout;
147 }
148
149 // Now enumerate the non-basic modes. Any errors at this point in time
150 // should indicate that the HDMI cable was unplugged and we should just
151 // abort with an empty set of audio capabilities.
152 for (int i = 0; i < mode_cnt; ++i) {
153 Mode m;
154
155 // Pick the mode we want to fetch info for.
156 if (mixer_ctl_set_value(ctrls[kModeSelNdx], 0, i) < 0)
157 goto bailout;
158
159 // Now fetch the common fields.
160 if ((tmp = mixer_ctl_get_value(ctrls[kFmtNdx], 0)) < 0)
161 goto bailout;
162 m.fmt = static_cast<AudFormat>(tmp);
163 ALOGI("Got mode %d from ALSA driver.", m.fmt);
164
165 if ((tmp = mixer_ctl_get_value(ctrls[kMaxChCntNdx], 0)) < 0)
166 goto bailout;
167 m.max_ch = static_cast<uint32_t>(tmp);
168
169 if ((tmp = mixer_ctl_get_value(ctrls[kSampRateNdx], 0)) < 0)
170 goto bailout;
171 m.sr_bitmask = static_cast<uint32_t>(tmp);
172
173 // Now for the mode dependent fields. Only LPCM has the bits-per-sample
174 // mask. Only AC3 through ATRAC have the compressed bitrate field.
175 m.bps_bitmask = 0;
176 m.comp_bitrate = 0;
177
178 if (m.fmt == kFmtLPCM) {
179 if ((tmp = mixer_ctl_get_value(ctrls[kBPSNdx], 0)) < 0)
180 goto bailout;
181 m.bps_bitmask = static_cast<uint32_t>(tmp);
182 } else if ((m.fmt >= kFmtAC3) && (m.fmt <= kFmtATRAC)) { // FIXME ATRAC is not last format!?
183 // FIXME SHould we extend the range up to kFmtDTSHD or kFmtMPGSUR?
184 if ((tmp = mixer_ctl_get_value(ctrls[kMaxCompBRNdx], 0)) < 0)
185 goto bailout;
186 m.comp_bitrate = static_cast<uint32_t>(tmp);
187 }
188
189 // Finally, sanity check the info. If it passes, add it to the vector
190 // of available modes.
191 if (sanityCheckMode(m)) {
192 ALOGI("Passed sanity check for mode %d from ALSA driver.", m.fmt);
193 mModes.add(m);
194 }
195 }
196
197 // Looks like we managed to enumerate all of the modes before someone
198 // unplugged the HDMI cable. Signal success and get out.
199 ret = true;
200
201 bailout:
202 if (NULL != mixer)
203 mixer_close(mixer);
204
205 if (!ret)
206 reset_l();
207
208 return ret;
209 }
210
reset()211 void HDMIAudioCaps::reset() {
212 Mutex::Autolock _l(mLock);
213 reset_l();
214 }
215
reset_l()216 void HDMIAudioCaps::reset_l() {
217 mBasicAudioSupported = false;
218 mSpeakerAlloc = 0;
219 mModes.clear();
220 }
221
getRatesForAF(String8 & rates)222 void HDMIAudioCaps::getRatesForAF(String8& rates) {
223 Mutex::Autolock _l(mLock);
224 rates.clear();
225
226 // If the sink does not support basic audio, then it supports no audio.
227 if (!mBasicAudioSupported)
228 return;
229
230 // Basic audio always supports from 32k through 38k.
231 uint32_t tmp = kSR_32000 | kSR_44100 | kSR_48000;
232
233 // To keep things simple, only report mode information for the PCM mode
234 // which supports the maximum number of channels.
235 ssize_t ndx = getMaxChModeNdx_l();
236 if (ndx >= 0)
237 tmp |= mModes[ndx].sr_bitmask;
238
239 bool first = true;
240 for (uint32_t i = 1; tmp; i <<= 1) {
241 if (i & tmp) {
242 rates.appendFormat(first ? "%d" : "|%d", srMaskToSR(i));
243 first = false;
244 tmp &= ~i;
245 }
246 }
247 }
248
getFmtsForAF(String8 & fmts)249 void HDMIAudioCaps::getFmtsForAF(String8& fmts) {
250 Mutex::Autolock _l(mLock);
251 fmts.clear();
252
253 // If the sink does not support basic audio, then it supports no audio.
254 if (!mBasicAudioSupported) {
255 ALOGI("ALSAFORMATS: basic audio not supported");
256 return;
257 }
258
259 fmts.append("AUDIO_FORMAT_PCM_16_BIT|AUDIO_FORMAT_PCM_8_24_BIT");
260 // TODO: when we can start to expect 20 and 24 bit audio modes coming from
261 // AF, we need to implement support to enumerate those modes.
262
263 // These names must match formats in android.media.AudioFormat
264 for (size_t i = 0; i < mModes.size(); ++i) {
265 switch (mModes[i].fmt) {
266 case kFmtAC3:
267 fmts.append("|AUDIO_FORMAT_AC3");
268 break;
269 case kFmtEAC3:
270 fmts.append("|AUDIO_FORMAT_E_AC3");
271 break;
272 case kFmtDTS:
273 fmts.append("|AUDIO_FORMAT_DTS");
274 break;
275 case kFmtDTSHD:
276 fmts.append("|AUDIO_FORMAT_DTS_HD");
277 break;
278 default:
279 break;
280 }
281 }
282
283 #if ALSA_UTILS_PRINT_FORMATS
284 ALOGI("ALSAFORMATS: formats = %s", fmts.string());
285
286 for (size_t i = 0; i < mModes.size(); ++i) {
287 ALOGI("ALSAFORMATS: ------- fmt[%d] = 0x%08X = %s",
288 i, mModes[i].fmt, fmtToString(mModes[i].fmt));
289 ALOGI("ALSAFORMATS: comp_bitrate[%d] = 0x%08X = %d",
290 i, mModes[i].comp_bitrate, mModes[i].comp_bitrate);
291 ALOGI("ALSAFORMATS: max_ch[%d] = 0x%08X = %d",
292 i, mModes[i].max_ch, mModes[i].max_ch);
293 ALOGI("ALSAFORMATS: bps_bitmask[%d] = 0x%08X", i, mModes[i].bps_bitmask);
294 uint32_t bpsm = mModes[i].bps_bitmask;
295 while(bpsm) {
296 uint32_t bpsm_next = bpsm & (bpsm - 1);
297 uint32_t bpsm_single = bpsm ^ bpsm_next;
298 if (bpsm_single) {
299 ALOGI("ALSAFORMATS: bits = %d", bpsMaskToBPS(bpsm_single));
300 }
301 bpsm = bpsm_next;
302 }
303 ALOGI("ALSAFORMATS: sr_bitmask[%d] = 0x%08X", i, mModes[i].sr_bitmask);
304 uint32_t srs = mModes[i].sr_bitmask;
305 while(srs) {
306 uint32_t srs_next = srs & (srs - 1);
307 uint32_t srs_single = srs ^ srs_next;
308 if (srs_single) {
309 ALOGI("ALSAFORMATS: srate = %d", srMaskToSR(srs_single));
310 }
311 srs = srs_next;
312 }
313 }
314 #endif /* ALSA_UTILS_PRINT_FORMATS */
315 }
316
getChannelMasksForAF(String8 & masks)317 void HDMIAudioCaps::getChannelMasksForAF(String8& masks) {
318 Mutex::Autolock _l(mLock);
319 masks.clear();
320
321 // If the sink does not support basic audio, then it supports no audio.
322 if (!mBasicAudioSupported)
323 return;
324
325 masks.append("AUDIO_CHANNEL_OUT_STEREO");
326
327 // To keep things simple, only report mode information for the mode
328 // which supports the maximum number of channels.
329 ssize_t ndx = getMaxChModeNdx_l();
330 if (ndx < 0)
331 return;
332
333 if (mModes[ndx].max_ch >= 6) {
334 if (masks.length())
335 masks.append("|");
336
337 masks.append((mModes[ndx].max_ch >= 8)
338 ? "AUDIO_CHANNEL_OUT_5POINT1|AUDIO_CHANNEL_OUT_7POINT1"
339 : "AUDIO_CHANNEL_OUT_5POINT1");
340 }
341 }
342
getMaxChModeNdx_l()343 ssize_t HDMIAudioCaps::getMaxChModeNdx_l() {
344 ssize_t max_ch_ndx = -1;
345 uint32_t max_ch = 0;
346
347 for (size_t i = 0; i < mModes.size(); ++i) {
348 if (max_ch < mModes[i].max_ch) {
349 max_ch = mModes[i].max_ch;
350 max_ch_ndx = i;
351 }
352 }
353
354 return max_ch_ndx;
355 }
356
supportsFormat(audio_format_t format,uint32_t sampleRate,uint32_t channelCount,bool isIec958NonAudio)357 bool HDMIAudioCaps::supportsFormat(audio_format_t format,
358 uint32_t sampleRate,
359 uint32_t channelCount,
360 bool isIec958NonAudio) {
361 Mutex::Autolock _l(mLock);
362
363 ALOGV("supportsFormat() format = 0x%08X, sampleRate = %u, channels = 0x%08X, iec958 = %d",
364 format, sampleRate, channelCount, isIec958NonAudio ? 1 : 0);
365 // If the sink does not support basic audio, then it supports no audio.
366 if (!mBasicAudioSupported)
367 return false;
368
369 AudFormat alsaFormat;
370 switch (format & AUDIO_FORMAT_MAIN_MASK) {
371 case AUDIO_FORMAT_PCM: alsaFormat = kFmtLPCM; break;
372 case AUDIO_FORMAT_AC3: alsaFormat = kFmtAC3; break;
373 case AUDIO_FORMAT_E_AC3: alsaFormat = kFmtAC3; break; // FIXME should this be kFmtEAC3?
374 case AUDIO_FORMAT_DTS: alsaFormat = kFmtDTS; break;
375 case AUDIO_FORMAT_DTS_HD: alsaFormat = kFmtDTSHD; break;
376 default: return false;
377 }
378
379 // EAC3 uses a PCM sample rate of 4X the base rate.
380 // We try to detect that situation and allow 4X rate even if the
381 // EDID does not report that it is supported.
382 // This rate was chosen because it is between the region of typical PCM rates
383 // and the extreme rates used for IEC61973.
384 // It is > 96000 and < 4*32000.
385 const uint32_t maxReasonableRate = 100000; // FIXME review for N
386 if (isIec958NonAudio && (alsaFormat == kFmtLPCM) && (sampleRate > maxReasonableRate)) {
387 ALOGI("supportsFormat() dividing sample %u by 4 to test support for EAC3 over HDMI",
388 sampleRate);
389 sampleRate = sampleRate / 4;
390 }
391
392 SRMask srMask;
393 switch (sampleRate) {
394 case 32000: srMask = kSR_32000; break;
395 case 44100: srMask = kSR_44100; break;
396 case 48000: srMask = kSR_48000; break;
397 case 88200: srMask = kSR_88200; break;
398 case 96000: srMask = kSR_96000; break;
399 case 176400: srMask = kSR_176400; break;
400 case 192000: srMask = kSR_192000; break;
401 default: return false;
402 }
403
404 // if PCM then determine actual bits per sample.
405 if (alsaFormat == kFmtLPCM) {
406 uint32_t subFormat = format & AUDIO_FORMAT_SUB_MASK;
407 BPSMask bpsMask;
408 switch (subFormat) {
409 // FIXME: (legacy code). We match on 16 bits, but on Fugu we hard code to use
410 // PCM_FORMAT_S24_LE.
411 case AUDIO_FORMAT_PCM_SUB_16_BIT: // fall through
412 case AUDIO_FORMAT_PCM_SUB_8_24_BIT: bpsMask = kBPS_16bit; break;
413 default: return false;
414 }
415
416 // Is the caller requesting basic audio? If so, we should be good to go.
417 // Otherwise, we need to check the mode table.
418 if ((2 == channelCount) && (sampleRate <= 48000))
419 return true;
420
421 // Check the modes in the table to see if there is one which
422 // supports the caller's format.
423 for (size_t i = 0; i < mModes.size(); ++i) {
424 const Mode& m = mModes[i];
425 if ((m.fmt == kFmtLPCM) &&
426 (m.max_ch >= channelCount) &&
427 (m.sr_bitmask & srMask) &&
428 (m.bps_bitmask & bpsMask))
429 return true;
430 }
431 } else {
432 // Check the modes in the table to see if there is one which
433 // supports the caller's format.
434 for (size_t i = 0; i < mModes.size(); ++i) {
435 const Mode& m = mModes[i];
436 // ignore bps_bitmask
437 if ((m.fmt == alsaFormat) &&
438 (m.max_ch >= channelCount) &&
439 (m.sr_bitmask & srMask))
440 return true;
441 }
442 }
443
444 // Looks like no compatible modes were found.
445 return false;
446 }
447
sanityCheckMode(const Mode & m)448 bool HDMIAudioCaps::sanityCheckMode(const Mode& m) {
449 if ((m.fmt < kFmtLPCM) || (m.fmt > kFmtMPGSUR))
450 return false;
451
452 if (m.max_ch > 8)
453 return false;
454
455 if (m.sr_bitmask & ~(kSR_32000 | kSR_44100 | kSR_48000 | kSR_88200 |
456 kSR_96000 | kSR_176400 | kSR_192000))
457 return false;
458
459 if (m.bps_bitmask & ~(kBPS_16bit | kBPS_20bit | kBPS_24bit))
460 return false;
461
462 return true;
463 }
464
fmtToString(AudFormat fmt)465 const char* HDMIAudioCaps::fmtToString(AudFormat fmt) {
466 static const char* fmts[] = {
467 "invalid", "LPCM", "AC-3", "MPEG-1", "MPEG-1 Layer 3",
468 "MPEG-2", "AAC-LC", "DTS", "ATRAC", "DSD", "E-AC3",
469 "DTS-HD", "MLP", "DST", "WMA Pro", "Extended" };
470
471 if (fmt >= NELEM(fmts))
472 return "invalid";
473
474 return fmts[fmt];
475 }
476
srMaskToSR(uint32_t mask)477 uint32_t HDMIAudioCaps::srMaskToSR(uint32_t mask) {
478 switch (mask) {
479 case kSR_32000: return 32000;
480 case kSR_44100: return 44100;
481 case kSR_48000: return 48000;
482 case kSR_88200: return 88200;
483 case kSR_96000: return 96000;
484 case kSR_176400: return 176400;
485 case kSR_192000: return 192000;
486 default: return 0;
487 }
488 }
489
bpsMaskToBPS(uint32_t mask)490 uint32_t HDMIAudioCaps::bpsMaskToBPS(uint32_t mask) {
491 switch (mask) {
492 case kBPS_16bit: return 16;
493 case kBPS_20bit: return 20;
494 case kBPS_24bit: return 24;
495 default: return 0;
496 }
497 }
498
saMaskToString(uint32_t mask)499 const char* HDMIAudioCaps::saMaskToString(uint32_t mask) {
500 switch (mask) {
501 case kSA_FLFR: return "Front Left/Right";
502 case kSA_LFE: return "LFE";
503 case kSA_FC: return "Front Center";
504 case kSA_RLRR: return "Rear Left/Right";
505 case kSA_RC: return "Rear Center";
506 case kSA_FLCFRC: return "Front Left/Right Center";
507 case kSA_RLCRRC: return "Rear Left/Right Center";
508 case kSA_FLWFRW: return "Front Left/Right Wide";
509 case kSA_FLHFRH: return "Front Left/Right High";
510 case kSA_TC: return "Top Center (overhead)";
511 case kSA_FCH: return "Front Center High";
512 default: return "unknown";
513 }
514 }
515
516 } // namespace android
517 #endif // __cplusplus
518