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             if ((tmp = mixer_ctl_get_value(ctrls[kMaxCompBRNdx], 0)) < 0)
184                 goto bailout;
185             m.comp_bitrate = static_cast<uint32_t>(tmp);
186         }
187 
188         // Finally, sanity check the info.  If it passes, add it to the vector
189         // of available modes.
190         if (sanityCheckMode(m))  {
191             ALOGI("Passed sanity check for mode %d from ALSA driver.", m.fmt);
192             mModes.add(m);
193         }
194     }
195 
196     // Looks like we managed to enumerate all of the modes before someone
197     // unplugged the HDMI cable.  Signal success and get out.
198     ret = true;
199 
200 bailout:
201     if (NULL != mixer)
202         mixer_close(mixer);
203 
204     if (!ret)
205         reset_l();
206 
207     return ret;
208 }
209 
reset()210 void HDMIAudioCaps::reset() {
211     Mutex::Autolock _l(mLock);
212     reset_l();
213 }
214 
reset_l()215 void HDMIAudioCaps::reset_l() {
216     mBasicAudioSupported = false;
217     mSpeakerAlloc = 0;
218     mModes.clear();
219 }
220 
getRatesForAF(String8 & rates)221 void HDMIAudioCaps::getRatesForAF(String8& rates) {
222     Mutex::Autolock _l(mLock);
223     rates.clear();
224 
225     // If the sink does not support basic audio, then it supports no audio.
226     if (!mBasicAudioSupported)
227         return;
228 
229     // Basic audio always supports from 32k through 38k.
230     uint32_t tmp = kSR_32000 | kSR_44100 | kSR_48000;
231 
232     // To keep things simple, only report mode information for the PCM mode
233     // which supports the maximum number of channels.
234     ssize_t ndx = getMaxChModeNdx_l();
235     if (ndx >= 0)
236         tmp |= mModes[ndx].sr_bitmask;
237 
238     bool first = true;
239     for (uint32_t i = 1; tmp; i <<= 1) {
240         if (i & tmp) {
241             rates.appendFormat(first ? "%d" : "|%d", srMaskToSR(i));
242             first = false;
243             tmp &= ~i;
244         }
245     }
246 }
247 
getFmtsForAF(String8 & fmts)248 void HDMIAudioCaps::getFmtsForAF(String8& fmts) {
249     Mutex::Autolock _l(mLock);
250     fmts.clear();
251 
252     // If the sink does not support basic audio, then it supports no audio.
253     if (!mBasicAudioSupported) {
254         ALOGI("ALSAFORMATS: basic audio not supported");
255         return;
256     }
257 
258     fmts.append("AUDIO_FORMAT_PCM_16_BIT");
259     // TODO: when we can start to expect 20 and 24 bit audio modes coming from
260     // AF, we need to implement support to enumerate those modes.
261 
262     // These names must match formats in android.media.AudioFormat
263     for (size_t i = 0; i < mModes.size(); ++i) {
264         switch (mModes[i].fmt) {
265             case kFmtAC3:
266                 fmts.append("|AUDIO_FORMAT_AC3");
267                 break;
268             case kFmtEAC3:
269                 fmts.append("|AUDIO_FORMAT_E_AC3");
270                 break;
271             default:
272                 break;
273         }
274     }
275 
276 #if ALSA_UTILS_PRINT_FORMATS
277     ALOGI("ALSAFORMATS: formats = %s", fmts.string());
278 
279     for (size_t i = 0; i < mModes.size(); ++i) {
280         ALOGI("ALSAFORMATS: ------- fmt[%d] = 0x%08X = %s",
281             i, mModes[i].fmt, fmtToString(mModes[i].fmt));
282         ALOGI("ALSAFORMATS:   comp_bitrate[%d] = 0x%08X = %d",
283             i, mModes[i].comp_bitrate, mModes[i].comp_bitrate);
284         ALOGI("ALSAFORMATS:   max_ch[%d] = 0x%08X = %d",
285             i, mModes[i].max_ch, mModes[i].max_ch);
286         ALOGI("ALSAFORMATS:   bps_bitmask[%d] = 0x%08X", i, mModes[i].bps_bitmask);
287         uint32_t bpsm = mModes[i].bps_bitmask;
288         while(bpsm) {
289             uint32_t bpsm_next = bpsm & (bpsm - 1);
290             uint32_t bpsm_single = bpsm ^ bpsm_next;
291             if (bpsm_single) {
292                 ALOGI("ALSAFORMATS:      bits  = %d", bpsMaskToBPS(bpsm_single));
293             }
294             bpsm = bpsm_next;
295         }
296         ALOGI("ALSAFORMATS:   sr_bitmask[%d] = 0x%08X", i, mModes[i].sr_bitmask);
297         uint32_t srs = mModes[i].sr_bitmask;
298         while(srs) {
299             uint32_t srs_next = srs & (srs - 1);
300             uint32_t srs_single = srs ^ srs_next;
301             if (srs_single) {
302                 ALOGI("ALSAFORMATS:      srate = %d", srMaskToSR(srs_single));
303             }
304             srs = srs_next;
305         }
306     }
307 #endif /* ALSA_UTILS_PRINT_FORMATS */
308 }
309 
getChannelMasksForAF(String8 & masks)310 void HDMIAudioCaps::getChannelMasksForAF(String8& masks) {
311     Mutex::Autolock _l(mLock);
312     masks.clear();
313 
314     // If the sink does not support basic audio, then it supports no audio.
315     if (!mBasicAudioSupported)
316         return;
317 
318     masks.append("AUDIO_CHANNEL_OUT_STEREO");
319 
320     // To keep things simple, only report mode information for the mode
321     // which supports the maximum number of channels.
322     ssize_t ndx = getMaxChModeNdx_l();
323     if (ndx < 0)
324         return;
325 
326     if (mModes[ndx].max_ch >= 6) {
327         if (masks.length())
328             masks.append("|");
329 
330         masks.append((mModes[ndx].max_ch >= 8)
331                 ? "AUDIO_CHANNEL_OUT_5POINT1|AUDIO_CHANNEL_OUT_7POINT1"
332                 : "AUDIO_CHANNEL_OUT_5POINT1");
333     }
334 }
335 
getMaxChModeNdx_l()336 ssize_t HDMIAudioCaps::getMaxChModeNdx_l() {
337     ssize_t max_ch_ndx = -1;
338     uint32_t max_ch = 0;
339 
340     for (size_t i = 0; i < mModes.size(); ++i) {
341         if (max_ch < mModes[i].max_ch) {
342             max_ch = mModes[i].max_ch;
343             max_ch_ndx = i;
344         }
345     }
346 
347     return max_ch_ndx;
348 }
349 
supportsFormat(audio_format_t format,uint32_t sampleRate,uint32_t channelCount)350 bool HDMIAudioCaps::supportsFormat(audio_format_t format,
351                                       uint32_t sampleRate,
352                                       uint32_t channelCount) {
353     Mutex::Autolock _l(mLock);
354 
355     // If the sink does not support basic audio, then it supports no audio.
356     if (!mBasicAudioSupported)
357         return false;
358 
359     AudFormat alsaFormat;
360     switch (format & AUDIO_FORMAT_MAIN_MASK) {
361         case AUDIO_FORMAT_PCM: alsaFormat = kFmtLPCM; break;
362         case AUDIO_FORMAT_AC3: alsaFormat = kFmtAC3; break;
363         case AUDIO_FORMAT_E_AC3: alsaFormat = kFmtAC3; break;
364         default: return false;
365     }
366 
367     SRMask srMask;
368     switch (sampleRate) {
369         case 32000:  srMask = kSR_32000;  break;
370         case 44100:  srMask = kSR_44100;  break;
371         case 48000:  srMask = kSR_48000;  break;
372         case 88200:  srMask = kSR_88200;  break;
373         case 96000:  srMask = kSR_96000;  break;
374         case 176400: srMask = kSR_176400; break;
375         case 192000: srMask = kSR_192000; break;
376         default: return false;
377     }
378 
379     // if PCM then determine actual bits per sample.
380     if (alsaFormat == kFmtLPCM) {
381         uint32_t subFormat = format & AUDIO_FORMAT_SUB_MASK;
382         BPSMask bpsMask;
383         switch (subFormat) {
384             case AUDIO_FORMAT_PCM_SUB_16_BIT: bpsMask = kBPS_16bit; break;
385             default: return false;
386         }
387 
388         // Is the caller requesting basic audio?  If so, we should be good to go.
389         // Otherwise, we need to check the mode table.
390         if ((2 == channelCount) && (sampleRate <= 48000))
391             return true;
392 
393         // Check the modes in the table to see if there is one which
394         // supports the caller's format.
395         for (size_t i = 0; i < mModes.size(); ++i) {
396             const Mode& m = mModes[i];
397             if ((m.fmt == kFmtLPCM) &&
398                 (m.max_ch >= channelCount) &&
399                 (m.sr_bitmask & srMask) &&
400                 (m.bps_bitmask & bpsMask))
401                 return true;
402         }
403     } else {
404         // Check the modes in the table to see if there is one which
405         // supports the caller's format.
406         for (size_t i = 0; i < mModes.size(); ++i) {
407             const Mode& m = mModes[i];
408             // ignore bps_bitmask
409             if ((m.fmt == alsaFormat) &&
410                 (m.max_ch >= channelCount) &&
411                 (m.sr_bitmask & srMask))
412                 return true;
413         }
414     }
415 
416     // Looks like no compatible modes were found.
417     return false;
418 }
419 
sanityCheckMode(const Mode & m)420 bool HDMIAudioCaps::sanityCheckMode(const Mode& m) {
421     if ((m.fmt < kFmtLPCM) || (m.fmt > kFmtMPGSUR))
422         return false;
423 
424     if (m.max_ch > 8)
425         return false;
426 
427     if (m.sr_bitmask & ~(kSR_32000 | kSR_44100 | kSR_48000 | kSR_88200 |
428                          kSR_96000 | kSR_176400 | kSR_192000))
429         return false;
430 
431     if (m.bps_bitmask & ~(kBPS_16bit | kBPS_20bit | kBPS_24bit))
432         return false;
433 
434     return true;
435 }
436 
fmtToString(AudFormat fmt)437 const char* HDMIAudioCaps::fmtToString(AudFormat fmt) {
438     static const char* fmts[] = {
439         "invalid", "LPCM", "AC-3", "MPEG-1", "MPEG-1 Layer 3",
440         "MPEG-2", "AAC-LC", "DTS", "ATRAC", "DSD", "E-AC3",
441         "DTS-HD", "MLP", "DST", "WMA Pro", "Extended" };
442 
443     if (fmt >= NELEM(fmts))
444         return "invalid";
445 
446     return fmts[fmt];
447 }
448 
srMaskToSR(uint32_t mask)449 uint32_t HDMIAudioCaps::srMaskToSR(uint32_t mask) {
450     switch (mask) {
451         case kSR_32000: return 32000;
452         case kSR_44100: return 44100;
453         case kSR_48000: return 48000;
454         case kSR_88200: return 88200;
455         case kSR_96000: return 96000;
456         case kSR_176400: return 176400;
457         case kSR_192000: return 192000;
458         default: return 0;
459     }
460 }
461 
bpsMaskToBPS(uint32_t mask)462 uint32_t HDMIAudioCaps::bpsMaskToBPS(uint32_t mask) {
463     switch (mask) {
464         case kBPS_16bit: return 16;
465         case kBPS_20bit: return 20;
466         case kBPS_24bit: return 24;
467         default: return 0;
468     }
469 }
470 
saMaskToString(uint32_t mask)471 const char* HDMIAudioCaps::saMaskToString(uint32_t mask) {
472     switch (mask) {
473         case kSA_FLFR:   return "Front Left/Right";
474         case kSA_LFE:    return "LFE";
475         case kSA_FC:     return "Front Center";
476         case kSA_RLRR:   return "Rear Left/Right";
477         case kSA_RC:     return "Rear Center";
478         case kSA_FLCFRC: return "Front Left/Right Center";
479         case kSA_RLCRRC: return "Rear Left/Right Center";
480         case kSA_FLWFRW: return "Front Left/Right Wide";
481         case kSA_FLHFRH: return "Front Left/Right High";
482         case kSA_TC:     return "Top Center (overhead)";
483         case kSA_FCH:    return "Front Center High";
484         default: return "unknown";
485     }
486 }
487 
488 }  // namespace android
489 #endif  // __cplusplus
490