Home | History | Annotate | Download | only in libaudio
      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 
     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 
     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 
     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 
    210 void HDMIAudioCaps::reset() {
    211     Mutex::Autolock _l(mLock);
    212     reset_l();
    213 }
    214 
    215 void HDMIAudioCaps::reset_l() {
    216     mBasicAudioSupported = false;
    217     mSpeakerAlloc = 0;
    218     mModes.clear();
    219 }
    220 
    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 
    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 
    310 void HDMIAudioCaps::getChannelMasksForAF(String8& masks, bool skipStereo) {
    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     // Don't list stereo modes if the caller requests it.  This is mostly to
    319     // support the hack which ends up routing multichannel audio to the special
    320     // multichannel audio stream out, but not native stereo tracks.
    321     if (!skipStereo)
    322         masks.append("AUDIO_CHANNEL_OUT_STEREO");
    323 
    324     // To keep things simple, only report mode information for the PCM mode
    325     // which supports the maximum number of channels.
    326     ssize_t ndx = getMaxChModeNdx_l();
    327     if (ndx < 0)
    328         return;
    329 
    330     if (mModes[ndx].max_ch >= 6) {
    331         if (masks.length())
    332             masks.append("|");
    333 
    334         masks.append((mModes[ndx].max_ch >= 8)
    335                 ? "AUDIO_CHANNEL_OUT_5POINT1|AUDIO_CHANNEL_OUT_7POINT1"
    336                 : "AUDIO_CHANNEL_OUT_5POINT1");
    337     }
    338 }
    339 
    340 ssize_t HDMIAudioCaps::getMaxChModeNdx_l() {
    341     ssize_t max_ch_ndx = -1;
    342     uint32_t max_ch = 0;
    343 
    344     for (size_t i = 0; i < mModes.size(); ++i) {
    345         if ((mModes[i].fmt == kFmtLPCM) && (max_ch < mModes[i].max_ch)) {
    346             max_ch < mModes[i].max_ch;
    347             max_ch_ndx = i;
    348         }
    349     }
    350 
    351     return max_ch_ndx;
    352 }
    353 
    354 bool HDMIAudioCaps::supportsFormat(audio_format_t format,
    355                                       uint32_t sampleRate,
    356                                       uint32_t channelCount) {
    357     Mutex::Autolock _l(mLock);
    358 
    359     // If the sink does not support basic audio, then it supports no audio.
    360     if (!mBasicAudioSupported)
    361         return false;
    362 
    363     AudFormat alsaFormat;
    364     switch (format & AUDIO_FORMAT_MAIN_MASK) {
    365         case AUDIO_FORMAT_PCM: alsaFormat = kFmtLPCM; break;
    366         case AUDIO_FORMAT_AC3: alsaFormat = kFmtAC3; break;
    367         case AUDIO_FORMAT_E_AC3: alsaFormat = kFmtAC3; break;
    368         default: return false;
    369     }
    370 
    371     SRMask srMask;
    372     switch (sampleRate) {
    373         case 32000:  srMask = kSR_32000;  break;
    374         case 44100:  srMask = kSR_44100;  break;
    375         case 48000:  srMask = kSR_48000;  break;
    376         case 88200:  srMask = kSR_88200;  break;
    377         case 96000:  srMask = kSR_96000;  break;
    378         case 176400: srMask = kSR_176400; break;
    379         case 192000: srMask = kSR_192000; break;
    380         default: return false;
    381     }
    382 
    383     // if PCM then determine actual bits per sample.
    384     if (alsaFormat == kFmtLPCM) {
    385         uint32_t subFormat = format & AUDIO_FORMAT_SUB_MASK;
    386         BPSMask bpsMask;
    387         switch (subFormat) {
    388             case AUDIO_FORMAT_PCM_SUB_16_BIT: bpsMask = kBPS_16bit; break;
    389             default: return false;
    390         }
    391 
    392         // Is the caller requesting basic audio?  If so, we should be good to go.
    393         // Otherwise, we need to check the mode table.
    394         if ((2 == channelCount) && (sampleRate <= 48000))
    395             return true;
    396 
    397         // Check the modes in the table to see if there is one which
    398         // supports the caller's format.
    399         for (size_t i = 0; i < mModes.size(); ++i) {
    400             const Mode& m = mModes[i];
    401             if ((m.fmt == kFmtLPCM) &&
    402                 (m.max_ch >= channelCount) &&
    403                 (m.sr_bitmask & srMask) &&
    404                 (m.bps_bitmask & bpsMask))
    405                 return true;
    406         }
    407     } else {
    408         // Check the modes in the table to see if there is one which
    409         // supports the caller's format.
    410         for (size_t i = 0; i < mModes.size(); ++i) {
    411             const Mode& m = mModes[i];
    412             // ignore bps_bitmask
    413             if ((m.fmt == alsaFormat) &&
    414                 (m.max_ch >= channelCount) &&
    415                 (m.sr_bitmask & srMask))
    416                 return true;
    417         }
    418     }
    419 
    420     // Looks like no compatible modes were found.
    421     return false;
    422 }
    423 
    424 bool HDMIAudioCaps::sanityCheckMode(const Mode& m) {
    425     if ((m.fmt < kFmtLPCM) || (m.fmt > kFmtMPGSUR))
    426         return false;
    427 
    428     if (m.max_ch > 8)
    429         return false;
    430 
    431     if (m.sr_bitmask & ~(kSR_32000 | kSR_44100 | kSR_48000 | kSR_88200 |
    432                          kSR_96000 | kSR_176400 | kSR_192000))
    433         return false;
    434 
    435     if (m.bps_bitmask & ~(kBPS_16bit | kBPS_20bit | kBPS_24bit))
    436         return false;
    437 
    438     return true;
    439 }
    440 
    441 const char* HDMIAudioCaps::fmtToString(AudFormat fmt) {
    442     static const char* fmts[] = {
    443         "invalid", "LPCM", "AC-3", "MPEG-1", "MPEG-1 Layer 3",
    444         "MPEG-2", "AAC-LC", "DTS", "ATRAC", "DSD", "E-AC3",
    445         "DTS-HD", "MLP", "DST", "WMA Pro", "Extended" };
    446 
    447     if (fmt >= NELEM(fmts))
    448         return "invalid";
    449 
    450     return fmts[fmt];
    451 }
    452 
    453 uint32_t HDMIAudioCaps::srMaskToSR(uint32_t mask) {
    454     switch (mask) {
    455         case kSR_32000: return 32000;
    456         case kSR_44100: return 44100;
    457         case kSR_48000: return 48000;
    458         case kSR_88200: return 88200;
    459         case kSR_96000: return 96000;
    460         case kSR_176400: return 176400;
    461         case kSR_192000: return 192000;
    462         default: return 0;
    463     }
    464 }
    465 
    466 uint32_t HDMIAudioCaps::bpsMaskToBPS(uint32_t mask) {
    467     switch (mask) {
    468         case kBPS_16bit: return 16;
    469         case kBPS_20bit: return 20;
    470         case kBPS_24bit: return 24;
    471         default: return 0;
    472     }
    473 }
    474 
    475 const char* HDMIAudioCaps::saMaskToString(uint32_t mask) {
    476     switch (mask) {
    477         case kSA_FLFR:   return "Front Left/Right";
    478         case kSA_LFE:    return "LFE";
    479         case kSA_FC:     return "Front Center";
    480         case kSA_RLRR:   return "Rear Left/Right";
    481         case kSA_RC:     return "Rear Center";
    482         case kSA_FLCFRC: return "Front Left/Right Center";
    483         case kSA_RLCRRC: return "Rear Left/Right Center";
    484         case kSA_FLWFRW: return "Front Left/Right Wide";
    485         case kSA_FLHFRH: return "Front Left/Right High";
    486         case kSA_TC:     return "Top Center (overhead)";
    487         case kSA_FCH:    return "Front Center High";
    488         default: return "unknown";
    489     }
    490 }
    491 
    492 }  // namespace android
    493 #endif  // __cplusplus
    494