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     // These names must match formats in android.media.AudioFormat
260     fmts.append("AUDIO_FORMAT_PCM_16_BIT|AUDIO_FORMAT_PCM_8_24_BIT");
261     // TODO: when we can start to expect 20 and 24 bit audio modes coming from
262     // AF, we need to implement support to enumerate those modes.
263 
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     // HDMI supports IEC61937 S/PDIF audio wrapper.
283     fmts.append("|AUDIO_FORMAT_IEC61937");
284 
285 #if ALSA_UTILS_PRINT_FORMATS
286     ALOGI("ALSAFORMATS: formats = %s", fmts.string());
287 
288     for (size_t i = 0; i < mModes.size(); ++i) {
289         ALOGI("ALSAFORMATS: ------- fmt[%d] = 0x%08X = %s",
290             i, mModes[i].fmt, fmtToString(mModes[i].fmt));
291         ALOGI("ALSAFORMATS:   comp_bitrate[%d] = 0x%08X = %d",
292             i, mModes[i].comp_bitrate, mModes[i].comp_bitrate);
293         ALOGI("ALSAFORMATS:   max_ch[%d] = 0x%08X = %d",
294             i, mModes[i].max_ch, mModes[i].max_ch);
295         ALOGI("ALSAFORMATS:   bps_bitmask[%d] = 0x%08X", i, mModes[i].bps_bitmask);
296         uint32_t bpsm = mModes[i].bps_bitmask;
297         while(bpsm) {
298             uint32_t bpsm_next = bpsm & (bpsm - 1);
299             uint32_t bpsm_single = bpsm ^ bpsm_next;
300             if (bpsm_single) {
301                 ALOGI("ALSAFORMATS:      bits  = %d", bpsMaskToBPS(bpsm_single));
302             }
303             bpsm = bpsm_next;
304         }
305         ALOGI("ALSAFORMATS:   sr_bitmask[%d] = 0x%08X", i, mModes[i].sr_bitmask);
306         uint32_t srs = mModes[i].sr_bitmask;
307         while(srs) {
308             uint32_t srs_next = srs & (srs - 1);
309             uint32_t srs_single = srs ^ srs_next;
310             if (srs_single) {
311                 ALOGI("ALSAFORMATS:      srate = %d", srMaskToSR(srs_single));
312             }
313             srs = srs_next;
314         }
315     }
316 #endif /* ALSA_UTILS_PRINT_FORMATS */
317 }
318 
getChannelMasksForAF(String8 & masks)319 void HDMIAudioCaps::getChannelMasksForAF(String8& masks) {
320     Mutex::Autolock _l(mLock);
321     masks.clear();
322 
323     // If the sink does not support basic audio, then it supports no audio.
324     if (!mBasicAudioSupported)
325         return;
326 
327     masks.append("AUDIO_CHANNEL_OUT_STEREO");
328 
329     // To keep things simple, only report mode information for the mode
330     // which supports the maximum number of channels.
331     ssize_t ndx = getMaxChModeNdx_l();
332     if (ndx < 0)
333         return;
334 
335     if (mModes[ndx].max_ch >= 6) {
336         if (masks.length())
337             masks.append("|");
338 
339         masks.append((mModes[ndx].max_ch >= 8)
340                 ? "AUDIO_CHANNEL_OUT_5POINT1|AUDIO_CHANNEL_OUT_7POINT1"
341                 : "AUDIO_CHANNEL_OUT_5POINT1");
342     }
343 }
344 
getMaxChModeNdx_l()345 ssize_t HDMIAudioCaps::getMaxChModeNdx_l() {
346     ssize_t max_ch_ndx = -1;
347     uint32_t max_ch = 0;
348 
349     for (size_t i = 0; i < mModes.size(); ++i) {
350         if (max_ch < mModes[i].max_ch) {
351             max_ch = mModes[i].max_ch;
352             max_ch_ndx = i;
353         }
354     }
355 
356     return max_ch_ndx;
357 }
358 
supportsFormat(audio_format_t format,uint32_t sampleRate,uint32_t channelCount,bool isIec958NonAudio)359 bool HDMIAudioCaps::supportsFormat(audio_format_t format,
360                                       uint32_t sampleRate,
361                                       uint32_t channelCount,
362                                       bool isIec958NonAudio) {
363     Mutex::Autolock _l(mLock);
364 
365     ALOGV("supportsFormat() format = 0x%08X, sampleRate = %u, channels = 0x%08X, iec958 = %d",
366                 format, sampleRate, channelCount, isIec958NonAudio ? 1 : 0);
367     // If the sink does not support basic audio, then it supports no audio.
368     if (!mBasicAudioSupported)
369         return false;
370 
371     AudFormat alsaFormat;
372     switch (audio_get_main_format(format)) {
373         case AUDIO_FORMAT_PCM: alsaFormat = kFmtLPCM; break;
374         case AUDIO_FORMAT_AC3: alsaFormat = kFmtAC3; break;
375         case AUDIO_FORMAT_E_AC3: alsaFormat = kFmtAC3; break; // FIXME should this be kFmtEAC3?
376         case AUDIO_FORMAT_DTS: alsaFormat = kFmtDTS; break;
377         case AUDIO_FORMAT_DTS_HD: alsaFormat = kFmtDTSHD; break;
378         case AUDIO_FORMAT_IEC61937:
379             alsaFormat = kFmtLPCM;
380             isIec958NonAudio = true;
381             break;
382         default:
383             ALOGE("supportsFormat() says format %#x not supported", format);
384             return false;
385     }
386 
387     // EAC3 uses a PCM sample rate of 4X the base rate.
388     // We try to detect that situation and allow 4X rate even if the
389     // EDID does not report that it is supported.
390     // This rate was chosen because it is between the region of typical PCM rates
391     // and the extreme rates used for IEC61973.
392     // It is > 96000 and < 4*32000.
393     const uint32_t maxReasonableRate = 100000; // FIXME review for N
394     if (isIec958NonAudio && (alsaFormat == kFmtLPCM) && (sampleRate > maxReasonableRate)) {
395         ALOGI("supportsFormat() dividing sample %u by 4 to test support for EAC3 over HDMI",
396                 sampleRate);
397         sampleRate = sampleRate / 4;
398     }
399 
400     SRMask srMask;
401     switch (sampleRate) {
402         case 32000:  srMask = kSR_32000;  break;
403         case 44100:  srMask = kSR_44100;  break;
404         case 48000:  srMask = kSR_48000;  break;
405         case 88200:  srMask = kSR_88200;  break;
406         case 96000:  srMask = kSR_96000;  break;
407         case 176400: srMask = kSR_176400; break;
408         case 192000: srMask = kSR_192000; break;
409         default: return false;
410     }
411 
412     // if PCM then determine actual bits per sample.
413     if (alsaFormat == kFmtLPCM) {
414         BPSMask bpsMask;
415         switch (format) {
416         // FIXME: (legacy code). We match on 16 bits, but on Fugu we hard code to use
417         // PCM_FORMAT_S24_LE.
418             case AUDIO_FORMAT_PCM_16_BIT: // fall through
419             case AUDIO_FORMAT_PCM_8_24_BIT:
420             case AUDIO_FORMAT_IEC61937:
421                 bpsMask = kBPS_16bit;
422                 break;
423             default:
424                 return false;
425         }
426 
427         // Is the caller requesting basic audio?  If so, we should be good to go.
428         // Otherwise, we need to check the mode table.
429         if ((2 == channelCount) && (sampleRate <= 48000))
430             return true;
431 
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             if ((m.fmt == kFmtLPCM) &&
437                 (m.max_ch >= channelCount) &&
438                 (m.sr_bitmask & srMask) &&
439                 (m.bps_bitmask & bpsMask))
440                 return true;
441         }
442     } else {
443         // Check the modes in the table to see if there is one which
444         // supports the caller's format.
445         for (size_t i = 0; i < mModes.size(); ++i) {
446             const Mode& m = mModes[i];
447             // ignore bps_bitmask
448             if ((m.fmt == alsaFormat) &&
449                 (m.max_ch >= channelCount) &&
450                 (m.sr_bitmask & srMask))
451                 return true;
452         }
453     }
454 
455     // Looks like no compatible modes were found.
456     return false;
457 }
458 
sanityCheckMode(const Mode & m)459 bool HDMIAudioCaps::sanityCheckMode(const Mode& m) {
460     if ((m.fmt < kFmtLPCM) || (m.fmt > kFmtMPGSUR))
461         return false;
462 
463     if (m.max_ch > 8)
464         return false;
465 
466     if (m.sr_bitmask & ~(kSR_32000 | kSR_44100 | kSR_48000 | kSR_88200 |
467                          kSR_96000 | kSR_176400 | kSR_192000))
468         return false;
469 
470     if (m.bps_bitmask & ~(kBPS_16bit | kBPS_20bit | kBPS_24bit))
471         return false;
472 
473     return true;
474 }
475 
fmtToString(AudFormat fmt)476 const char* HDMIAudioCaps::fmtToString(AudFormat fmt) {
477     static const char* fmts[] = {
478         "invalid", "LPCM", "AC-3", "MPEG-1", "MPEG-1 Layer 3",
479         "MPEG-2", "AAC-LC", "DTS", "ATRAC", "DSD", "E-AC3",
480         "DTS-HD", "MLP", "DST", "WMA Pro", "Extended" };
481 
482     if (fmt >= NELEM(fmts))
483         return "invalid";
484 
485     return fmts[fmt];
486 }
487 
srMaskToSR(uint32_t mask)488 uint32_t HDMIAudioCaps::srMaskToSR(uint32_t mask) {
489     switch (mask) {
490         case kSR_32000: return 32000;
491         case kSR_44100: return 44100;
492         case kSR_48000: return 48000;
493         case kSR_88200: return 88200;
494         case kSR_96000: return 96000;
495         case kSR_176400: return 176400;
496         case kSR_192000: return 192000;
497         default: return 0;
498     }
499 }
500 
bpsMaskToBPS(uint32_t mask)501 uint32_t HDMIAudioCaps::bpsMaskToBPS(uint32_t mask) {
502     switch (mask) {
503         case kBPS_16bit: return 16;
504         case kBPS_20bit: return 20;
505         case kBPS_24bit: return 24;
506         default: return 0;
507     }
508 }
509 
saMaskToString(uint32_t mask)510 const char* HDMIAudioCaps::saMaskToString(uint32_t mask) {
511     switch (mask) {
512         case kSA_FLFR:   return "Front Left/Right";
513         case kSA_LFE:    return "LFE";
514         case kSA_FC:     return "Front Center";
515         case kSA_RLRR:   return "Rear Left/Right";
516         case kSA_RC:     return "Rear Center";
517         case kSA_FLCFRC: return "Front Left/Right Center";
518         case kSA_RLCRRC: return "Rear Left/Right Center";
519         case kSA_FLWFRW: return "Front Left/Right Wide";
520         case kSA_FLHFRH: return "Front Left/Right High";
521         case kSA_TC:     return "Top Center (overhead)";
522         case kSA_FCH:    return "Front Center High";
523         default: return "unknown";
524     }
525 }
526 
527 }  // namespace android
528 #endif  // __cplusplus
529