AudioPort.cpp revision 138f77425a0956d867f078881f91628518ae8258
1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "APM::AudioPort"
18//#define LOG_NDEBUG 0
19#include <media/AudioResamplerPublic.h>
20#include "AudioPort.h"
21#include "HwModule.h"
22#include "AudioGain.h"
23#include "ConfigParsingUtils.h"
24#include "audio_policy_conf.h"
25#include <policy.h>
26
27namespace android {
28
29int32_t volatile AudioPort::mNextUniqueId = 1;
30
31// --- AudioPort class implementation
32
33AudioPort::AudioPort(const String8& name, audio_port_type_t type,
34                     audio_port_role_t role) :
35    mName(name), mType(type), mRole(role), mFlags(0)
36{
37    mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
38                    ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
39}
40
41void AudioPort::attach(const sp<HwModule>& module)
42{
43    mModule = module;
44}
45
46audio_port_handle_t AudioPort::getNextUniqueId()
47{
48    return static_cast<audio_port_handle_t>(android_atomic_inc(&mNextUniqueId));
49}
50
51audio_module_handle_t AudioPort::getModuleHandle() const
52{
53    if (mModule == 0) {
54        return 0;
55    }
56    return mModule->mHandle;
57}
58
59uint32_t AudioPort::getModuleVersion() const
60{
61    if (mModule == 0) {
62        return 0;
63    }
64    return mModule->mHalVersion;
65}
66
67const char *AudioPort::getModuleName() const
68{
69    if (mModule == 0) {
70        return "";
71    }
72    return mModule->mName;
73}
74
75void AudioPort::toAudioPort(struct audio_port *port) const
76{
77    port->role = mRole;
78    port->type = mType;
79    strlcpy(port->name, mName, AUDIO_PORT_MAX_NAME_LEN);
80    unsigned int i;
81    for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
82        if (mSamplingRates[i] != 0) {
83            port->sample_rates[i] = mSamplingRates[i];
84        }
85    }
86    port->num_sample_rates = i;
87    for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
88        if (mChannelMasks[i] != 0) {
89            port->channel_masks[i] = mChannelMasks[i];
90        }
91    }
92    port->num_channel_masks = i;
93    for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
94        if (mFormats[i] != 0) {
95            port->formats[i] = mFormats[i];
96        }
97    }
98    port->num_formats = i;
99
100    ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
101
102    for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
103        port->gains[i] = mGains[i]->mGain;
104    }
105    port->num_gains = i;
106}
107
108void AudioPort::importAudioPort(const sp<AudioPort> port) {
109    for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
110        const uint32_t rate = port->mSamplingRates.itemAt(k);
111        if (rate != 0) { // skip "dynamic" rates
112            bool hasRate = false;
113            for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
114                if (rate == mSamplingRates.itemAt(l)) {
115                    hasRate = true;
116                    break;
117                }
118            }
119            if (!hasRate) { // never import a sampling rate twice
120                mSamplingRates.add(rate);
121            }
122        }
123    }
124    for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
125        const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
126        if (mask != 0) { // skip "dynamic" masks
127            bool hasMask = false;
128            for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
129                if (mask == mChannelMasks.itemAt(l)) {
130                    hasMask = true;
131                    break;
132                }
133            }
134            if (!hasMask) { // never import a channel mask twice
135                mChannelMasks.add(mask);
136            }
137        }
138    }
139    for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
140        const audio_format_t format = port->mFormats.itemAt(k);
141        if (format != 0) { // skip "dynamic" formats
142            bool hasFormat = false;
143            for (size_t l = 0 ; l < mFormats.size() ; l++) {
144                if (format == mFormats.itemAt(l)) {
145                    hasFormat = true;
146                    break;
147                }
148            }
149            if (!hasFormat) { // never import a format twice
150                mFormats.add(format);
151            }
152        }
153    }
154    for (size_t k = 0 ; k < port->mGains.size() ; k++) {
155        sp<AudioGain> gain = port->mGains.itemAt(k);
156        if (gain != 0) {
157            bool hasGain = false;
158            for (size_t l = 0 ; l < mGains.size() ; l++) {
159                if (gain == mGains.itemAt(l)) {
160                    hasGain = true;
161                    break;
162                }
163            }
164            if (!hasGain) { // never import a gain twice
165                mGains.add(gain);
166            }
167        }
168    }
169}
170
171void AudioPort::clearCapabilities() {
172    mChannelMasks.clear();
173    mFormats.clear();
174    mSamplingRates.clear();
175    mGains.clear();
176}
177
178void AudioPort::loadSamplingRates(char *name)
179{
180    char *str = strtok(name, "|");
181
182    // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
183    // rates should be read from the output stream after it is opened for the first time
184    if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
185        mSamplingRates.add(0);
186        return;
187    }
188
189    while (str != NULL) {
190        uint32_t rate = atoi(str);
191        if (rate != 0) {
192            ALOGV("loadSamplingRates() adding rate %d", rate);
193            mSamplingRates.add(rate);
194        }
195        str = strtok(NULL, "|");
196    }
197}
198
199void AudioPort::loadFormats(char *name)
200{
201    char *str = strtok(name, "|");
202
203    // by convention, "0' in the first entry in mFormats indicates the supported formats
204    // should be read from the output stream after it is opened for the first time
205    if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
206        mFormats.add(AUDIO_FORMAT_DEFAULT);
207        return;
208    }
209
210    while (str != NULL) {
211        audio_format_t format = (audio_format_t)ConfigParsingUtils::stringToEnum(sFormatNameToEnumTable,
212                                                             ARRAY_SIZE(sFormatNameToEnumTable),
213                                                             str);
214        if (format != AUDIO_FORMAT_DEFAULT) {
215            mFormats.add(format);
216        }
217        str = strtok(NULL, "|");
218    }
219    // we sort from worst to best, so that AUDIO_FORMAT_DEFAULT is always the first entry.
220    // TODO: compareFormats could be a lambda to convert between pointer-to-format to format:
221    // [](const audio_format_t *format1, const audio_format_t *format2) {
222    //     return compareFormats(*format1, *format2);
223    // }
224    mFormats.sort(compareFormats);
225}
226
227void AudioPort::loadInChannels(char *name)
228{
229    const char *str = strtok(name, "|");
230
231    ALOGV("loadInChannels() %s", name);
232
233    if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
234        mChannelMasks.add(0);
235        return;
236    }
237
238    while (str != NULL) {
239        audio_channel_mask_t channelMask =
240                (audio_channel_mask_t)ConfigParsingUtils::stringToEnum(sInChannelsNameToEnumTable,
241                                                   ARRAY_SIZE(sInChannelsNameToEnumTable),
242                                                   str);
243        if (channelMask == 0) { // if not found, check the channel index table
244            channelMask = (audio_channel_mask_t)
245                      ConfigParsingUtils::stringToEnum(sIndexChannelsNameToEnumTable,
246                              ARRAY_SIZE(sIndexChannelsNameToEnumTable),
247                              str);
248        }
249        if (channelMask != 0) {
250            ALOGV("loadInChannels() adding channelMask %#x", channelMask);
251            mChannelMasks.add(channelMask);
252        }
253        str = strtok(NULL, "|");
254    }
255}
256
257void AudioPort::loadOutChannels(char *name)
258{
259    const char *str = strtok(name, "|");
260
261    ALOGV("loadOutChannels() %s", name);
262
263    // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
264    // masks should be read from the output stream after it is opened for the first time
265    if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
266        mChannelMasks.add(0);
267        return;
268    }
269
270    while (str != NULL) {
271        audio_channel_mask_t channelMask =
272                (audio_channel_mask_t)ConfigParsingUtils::stringToEnum(sOutChannelsNameToEnumTable,
273                                                   ARRAY_SIZE(sOutChannelsNameToEnumTable),
274                                                   str);
275        if (channelMask != 0) {
276            mChannelMasks.add(channelMask);
277        }
278        str = strtok(NULL, "|");
279    }
280    return;
281}
282
283audio_gain_mode_t AudioPort::loadGainMode(char *name)
284{
285    const char *str = strtok(name, "|");
286
287    ALOGV("loadGainMode() %s", name);
288    audio_gain_mode_t mode = 0;
289    while (str != NULL) {
290        mode |= (audio_gain_mode_t)ConfigParsingUtils::stringToEnum(sGainModeNameToEnumTable,
291                                                ARRAY_SIZE(sGainModeNameToEnumTable),
292                                                str);
293        str = strtok(NULL, "|");
294    }
295    return mode;
296}
297
298void AudioPort::loadGain(cnode *root, int index)
299{
300    cnode *node = root->first_child;
301
302    sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
303
304    while (node) {
305        if (strcmp(node->name, GAIN_MODE) == 0) {
306            gain->mGain.mode = loadGainMode((char *)node->value);
307        } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
308            if (mUseInChannelMask) {
309                gain->mGain.channel_mask =
310                        (audio_channel_mask_t)ConfigParsingUtils::stringToEnum(sInChannelsNameToEnumTable,
311                                                           ARRAY_SIZE(sInChannelsNameToEnumTable),
312                                                           (char *)node->value);
313            } else {
314                gain->mGain.channel_mask =
315                        (audio_channel_mask_t)ConfigParsingUtils::stringToEnum(sOutChannelsNameToEnumTable,
316                                                           ARRAY_SIZE(sOutChannelsNameToEnumTable),
317                                                           (char *)node->value);
318            }
319        } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
320            gain->mGain.min_value = atoi((char *)node->value);
321        } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
322            gain->mGain.max_value = atoi((char *)node->value);
323        } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
324            gain->mGain.default_value = atoi((char *)node->value);
325        } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
326            gain->mGain.step_value = atoi((char *)node->value);
327        } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
328            gain->mGain.min_ramp_ms = atoi((char *)node->value);
329        } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
330            gain->mGain.max_ramp_ms = atoi((char *)node->value);
331        }
332        node = node->next;
333    }
334
335    ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
336          gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
337
338    if (gain->mGain.mode == 0) {
339        return;
340    }
341    mGains.add(gain);
342}
343
344void AudioPort::loadGains(cnode *root)
345{
346    cnode *node = root->first_child;
347    int index = 0;
348    while (node) {
349        ALOGV("loadGains() loading gain %s", node->name);
350        loadGain(node, index++);
351        node = node->next;
352    }
353}
354
355status_t AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
356{
357    if (mSamplingRates.isEmpty()) {
358        return NO_ERROR;
359    }
360
361    for (size_t i = 0; i < mSamplingRates.size(); i ++) {
362        if (mSamplingRates[i] == samplingRate) {
363            return NO_ERROR;
364        }
365    }
366    return BAD_VALUE;
367}
368
369status_t AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
370        uint32_t *updatedSamplingRate) const
371{
372    if (mSamplingRates.isEmpty()) {
373        if (updatedSamplingRate != NULL) {
374            *updatedSamplingRate = samplingRate;
375        }
376        return NO_ERROR;
377    }
378
379    // Search for the closest supported sampling rate that is above (preferred)
380    // or below (acceptable) the desired sampling rate, within a permitted ratio.
381    // The sampling rates do not need to be sorted in ascending order.
382    ssize_t maxBelow = -1;
383    ssize_t minAbove = -1;
384    uint32_t candidate;
385    for (size_t i = 0; i < mSamplingRates.size(); i++) {
386        candidate = mSamplingRates[i];
387        if (candidate == samplingRate) {
388            if (updatedSamplingRate != NULL) {
389                *updatedSamplingRate = candidate;
390            }
391            return NO_ERROR;
392        }
393        // candidate < desired
394        if (candidate < samplingRate) {
395            if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
396                maxBelow = i;
397            }
398        // candidate > desired
399        } else {
400            if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
401                minAbove = i;
402            }
403        }
404    }
405
406    // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
407    if (minAbove >= 0) {
408        candidate = mSamplingRates[minAbove];
409        if (candidate / AUDIO_RESAMPLER_DOWN_RATIO_MAX <= samplingRate) {
410            if (updatedSamplingRate != NULL) {
411                *updatedSamplingRate = candidate;
412            }
413            return NO_ERROR;
414        }
415    }
416    // But if we have to up-sample from a lower sampling rate, that's OK.
417    if (maxBelow >= 0) {
418        candidate = mSamplingRates[maxBelow];
419        if (candidate * AUDIO_RESAMPLER_UP_RATIO_MAX >= samplingRate) {
420            if (updatedSamplingRate != NULL) {
421                *updatedSamplingRate = candidate;
422            }
423            return NO_ERROR;
424        }
425    }
426    // leave updatedSamplingRate unmodified
427    return BAD_VALUE;
428}
429
430status_t AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
431{
432    if (mChannelMasks.isEmpty()) {
433        return NO_ERROR;
434    }
435
436    for (size_t i = 0; i < mChannelMasks.size(); i++) {
437        if (mChannelMasks[i] == channelMask) {
438            return NO_ERROR;
439        }
440    }
441    return BAD_VALUE;
442}
443
444status_t AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask,
445        audio_channel_mask_t *updatedChannelMask) const
446{
447    if (mChannelMasks.isEmpty()) {
448        if (updatedChannelMask != NULL) {
449            *updatedChannelMask = channelMask;
450        }
451        return NO_ERROR;
452    }
453
454    const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
455    const bool isIndex = audio_channel_mask_get_representation(channelMask)
456            == AUDIO_CHANNEL_REPRESENTATION_INDEX;
457    int bestMatch = 0;
458    for (size_t i = 0; i < mChannelMasks.size(); i ++) {
459        audio_channel_mask_t supported = mChannelMasks[i];
460        if (supported == channelMask) {
461            // Exact matches always taken.
462            if (updatedChannelMask != NULL) {
463                *updatedChannelMask = channelMask;
464            }
465            return NO_ERROR;
466        }
467
468        // AUDIO_CHANNEL_NONE (value: 0) is used for dynamic channel support
469        if (isRecordThread && supported != AUDIO_CHANNEL_NONE) {
470            // Approximate (best) match:
471            // The match score measures how well the supported channel mask matches the
472            // desired mask, where increasing-is-better.
473            //
474            // TODO: Some tweaks may be needed.
475            // Should be a static function of the data processing library.
476            //
477            // In priority:
478            // match score = 1000 if legacy channel conversion equivalent (always prefer this)
479            // OR
480            // match score += 100 if the channel mask representations match
481            // match score += number of channels matched.
482            //
483            // If there are no matched channels, the mask may still be accepted
484            // but the playback or record will be silent.
485            const bool isSupportedIndex = (audio_channel_mask_get_representation(supported)
486                    == AUDIO_CHANNEL_REPRESENTATION_INDEX);
487            int match;
488            if (isIndex && isSupportedIndex) {
489                // index equivalence
490                match = 100 + __builtin_popcount(
491                        audio_channel_mask_get_bits(channelMask)
492                            & audio_channel_mask_get_bits(supported));
493            } else if (isIndex && !isSupportedIndex) {
494                const uint32_t equivalentBits =
495                        (1 << audio_channel_count_from_in_mask(supported)) - 1 ;
496                match = __builtin_popcount(
497                        audio_channel_mask_get_bits(channelMask) & equivalentBits);
498            } else if (!isIndex && isSupportedIndex) {
499                const uint32_t equivalentBits =
500                        (1 << audio_channel_count_from_in_mask(channelMask)) - 1;
501                match = __builtin_popcount(
502                        equivalentBits & audio_channel_mask_get_bits(supported));
503            } else {
504                // positional equivalence
505                match = 100 + __builtin_popcount(
506                        audio_channel_mask_get_bits(channelMask)
507                            & audio_channel_mask_get_bits(supported));
508                switch (supported) {
509                case AUDIO_CHANNEL_IN_FRONT_BACK:
510                case AUDIO_CHANNEL_IN_STEREO:
511                    if (channelMask == AUDIO_CHANNEL_IN_MONO) {
512                        match = 1000;
513                    }
514                    break;
515                case AUDIO_CHANNEL_IN_MONO:
516                    if (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
517                            || channelMask == AUDIO_CHANNEL_IN_STEREO) {
518                        match = 1000;
519                    }
520                    break;
521                default:
522                    break;
523                }
524            }
525            if (match > bestMatch) {
526                bestMatch = match;
527                if (updatedChannelMask != NULL) {
528                    *updatedChannelMask = supported;
529                } else {
530                    return NO_ERROR; // any match will do in this case.
531                }
532            }
533        }
534    }
535    return bestMatch > 0 ? NO_ERROR : BAD_VALUE;
536}
537
538status_t AudioPort::checkExactFormat(audio_format_t format) const
539{
540    if (mFormats.isEmpty()) {
541        return NO_ERROR;
542    }
543
544    for (size_t i = 0; i < mFormats.size(); i ++) {
545        if (mFormats[i] == format) {
546            return NO_ERROR;
547        }
548    }
549    return BAD_VALUE;
550}
551
552status_t AudioPort::checkCompatibleFormat(audio_format_t format, audio_format_t *updatedFormat)
553        const
554{
555    if (mFormats.isEmpty()) {
556        if (updatedFormat != NULL) {
557            *updatedFormat = format;
558        }
559        return NO_ERROR;
560    }
561
562    const bool checkInexact = // when port is input and format is linear pcm
563            mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK
564            && audio_is_linear_pcm(format);
565
566    // iterate from best format to worst format (reverse order)
567    for (ssize_t i = mFormats.size() - 1; i >= 0 ; --i) {
568        if (mFormats[i] == format ||
569                (checkInexact
570                        && mFormats[i] != AUDIO_FORMAT_DEFAULT
571                        && audio_is_linear_pcm(mFormats[i]))) {
572            // for inexact checks we take the first linear pcm format due to sorting.
573            if (updatedFormat != NULL) {
574                *updatedFormat = mFormats[i];
575            }
576            return NO_ERROR;
577        }
578    }
579    return BAD_VALUE;
580}
581
582uint32_t AudioPort::pickSamplingRate() const
583{
584    // special case for uninitialized dynamic profile
585    if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
586        return 0;
587    }
588
589    // For direct outputs, pick minimum sampling rate: this helps ensuring that the
590    // channel count / sampling rate combination chosen will be supported by the connected
591    // sink
592    if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
593            (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
594        uint32_t samplingRate = UINT_MAX;
595        for (size_t i = 0; i < mSamplingRates.size(); i ++) {
596            if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
597                samplingRate = mSamplingRates[i];
598            }
599        }
600        return (samplingRate == UINT_MAX) ? 0 : samplingRate;
601    }
602
603    uint32_t samplingRate = 0;
604    uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
605
606    // For mixed output and inputs, use max mixer sampling rates. Do not
607    // limit sampling rate otherwise
608    if (mType != AUDIO_PORT_TYPE_MIX) {
609        maxRate = UINT_MAX;
610    }
611    for (size_t i = 0; i < mSamplingRates.size(); i ++) {
612        if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
613            samplingRate = mSamplingRates[i];
614        }
615    }
616    return samplingRate;
617}
618
619audio_channel_mask_t AudioPort::pickChannelMask() const
620{
621    // special case for uninitialized dynamic profile
622    if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
623        return AUDIO_CHANNEL_NONE;
624    }
625    audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
626
627    // For direct outputs, pick minimum channel count: this helps ensuring that the
628    // channel count / sampling rate combination chosen will be supported by the connected
629    // sink
630    if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
631            (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
632        uint32_t channelCount = UINT_MAX;
633        for (size_t i = 0; i < mChannelMasks.size(); i ++) {
634            uint32_t cnlCount;
635            if (mUseInChannelMask) {
636                cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
637            } else {
638                cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
639            }
640            if ((cnlCount < channelCount) && (cnlCount > 0)) {
641                channelMask = mChannelMasks[i];
642                channelCount = cnlCount;
643            }
644        }
645        return channelMask;
646    }
647
648    uint32_t channelCount = 0;
649    uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
650
651    // For mixed output and inputs, use max mixer channel count. Do not
652    // limit channel count otherwise
653    if (mType != AUDIO_PORT_TYPE_MIX) {
654        maxCount = UINT_MAX;
655    }
656    for (size_t i = 0; i < mChannelMasks.size(); i ++) {
657        uint32_t cnlCount;
658        if (mUseInChannelMask) {
659            cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
660        } else {
661            cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
662        }
663        if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
664            channelMask = mChannelMasks[i];
665            channelCount = cnlCount;
666        }
667    }
668    return channelMask;
669}
670
671/* format in order of increasing preference */
672const audio_format_t AudioPort::sPcmFormatCompareTable[] = {
673        AUDIO_FORMAT_DEFAULT,
674        AUDIO_FORMAT_PCM_16_BIT,
675        AUDIO_FORMAT_PCM_8_24_BIT,
676        AUDIO_FORMAT_PCM_24_BIT_PACKED,
677        AUDIO_FORMAT_PCM_32_BIT,
678        AUDIO_FORMAT_PCM_FLOAT,
679};
680
681int AudioPort::compareFormats(audio_format_t format1,
682                                                  audio_format_t format2)
683{
684    // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
685    // compressed format and better than any PCM format. This is by design of pickFormat()
686    if (!audio_is_linear_pcm(format1)) {
687        if (!audio_is_linear_pcm(format2)) {
688            return 0;
689        }
690        return 1;
691    }
692    if (!audio_is_linear_pcm(format2)) {
693        return -1;
694    }
695
696    int index1 = -1, index2 = -1;
697    for (size_t i = 0;
698            (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
699            i ++) {
700        if (sPcmFormatCompareTable[i] == format1) {
701            index1 = i;
702        }
703        if (sPcmFormatCompareTable[i] == format2) {
704            index2 = i;
705        }
706    }
707    // format1 not found => index1 < 0 => format2 > format1
708    // format2 not found => index2 < 0 => format2 < format1
709    return index1 - index2;
710}
711
712audio_format_t AudioPort::pickFormat() const
713{
714    // special case for uninitialized dynamic profile
715    if (mFormats.size() == 1 && mFormats[0] == 0) {
716        return AUDIO_FORMAT_DEFAULT;
717    }
718
719    audio_format_t format = AUDIO_FORMAT_DEFAULT;
720    audio_format_t bestFormat =
721            AudioPort::sPcmFormatCompareTable[
722                ARRAY_SIZE(AudioPort::sPcmFormatCompareTable) - 1];
723    // For mixed output and inputs, use best mixer output format. Do not
724    // limit format otherwise
725    if ((mType != AUDIO_PORT_TYPE_MIX) ||
726            ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
727             (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
728        bestFormat = AUDIO_FORMAT_INVALID;
729    }
730
731    for (size_t i = 0; i < mFormats.size(); i ++) {
732        if ((compareFormats(mFormats[i], format) > 0) &&
733                (compareFormats(mFormats[i], bestFormat) <= 0)) {
734            format = mFormats[i];
735        }
736    }
737    return format;
738}
739
740status_t AudioPort::checkGain(const struct audio_gain_config *gainConfig,
741                                                  int index) const
742{
743    if (index < 0 || (size_t)index >= mGains.size()) {
744        return BAD_VALUE;
745    }
746    return mGains[index]->checkConfig(gainConfig);
747}
748
749void AudioPort::dump(int fd, int spaces) const
750{
751    const size_t SIZE = 256;
752    char buffer[SIZE];
753    String8 result;
754
755    if (mName.length() != 0) {
756        snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
757        result.append(buffer);
758    }
759
760    if (mSamplingRates.size() != 0) {
761        snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
762        result.append(buffer);
763        for (size_t i = 0; i < mSamplingRates.size(); i++) {
764            if (i == 0 && mSamplingRates[i] == 0) {
765                snprintf(buffer, SIZE, "Dynamic");
766            } else {
767                snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
768            }
769            result.append(buffer);
770            result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
771        }
772        result.append("\n");
773    }
774
775    if (mChannelMasks.size() != 0) {
776        snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
777        result.append(buffer);
778        for (size_t i = 0; i < mChannelMasks.size(); i++) {
779            ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
780
781            if (i == 0 && mChannelMasks[i] == 0) {
782                snprintf(buffer, SIZE, "Dynamic");
783            } else {
784                snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
785            }
786            result.append(buffer);
787            result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
788        }
789        result.append("\n");
790    }
791
792    if (mFormats.size() != 0) {
793        snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
794        result.append(buffer);
795        for (size_t i = 0; i < mFormats.size(); i++) {
796            const char *formatStr = ConfigParsingUtils::enumToString(sFormatNameToEnumTable,
797                                                 ARRAY_SIZE(sFormatNameToEnumTable),
798                                                 mFormats[i]);
799            const bool isEmptyStr = formatStr[0] == 0;
800            if (i == 0 && isEmptyStr) {
801                snprintf(buffer, SIZE, "Dynamic");
802            } else {
803                if (isEmptyStr) {
804                    snprintf(buffer, SIZE, "%#x", mFormats[i]);
805                } else {
806                    snprintf(buffer, SIZE, "%s", formatStr);
807                }
808            }
809            result.append(buffer);
810            result.append(i == (mFormats.size() - 1) ? "" : ", ");
811        }
812        result.append("\n");
813    }
814    write(fd, result.string(), result.size());
815    if (mGains.size() != 0) {
816        snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
817        write(fd, buffer, strlen(buffer) + 1);
818        for (size_t i = 0; i < mGains.size(); i++) {
819            mGains[i]->dump(fd, spaces + 2, i);
820        }
821    }
822}
823
824void AudioPort::log(const char* indent) const
825{
826    ALOGI("%s Port[nm:%s, type:%d, role:%d]", indent, mName.string(), mType, mRole);
827}
828
829// --- AudioPortConfig class implementation
830
831AudioPortConfig::AudioPortConfig()
832{
833    mSamplingRate = 0;
834    mChannelMask = AUDIO_CHANNEL_NONE;
835    mFormat = AUDIO_FORMAT_INVALID;
836    mGain.index = -1;
837}
838
839status_t AudioPortConfig::applyAudioPortConfig(
840                                                        const struct audio_port_config *config,
841                                                        struct audio_port_config *backupConfig)
842{
843    struct audio_port_config localBackupConfig;
844    status_t status = NO_ERROR;
845
846    localBackupConfig.config_mask = config->config_mask;
847    toAudioPortConfig(&localBackupConfig);
848
849    sp<AudioPort> audioport = getAudioPort();
850    if (audioport == 0) {
851        status = NO_INIT;
852        goto exit;
853    }
854    if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
855        status = audioport->checkExactSamplingRate(config->sample_rate);
856        if (status != NO_ERROR) {
857            goto exit;
858        }
859        mSamplingRate = config->sample_rate;
860    }
861    if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
862        status = audioport->checkExactChannelMask(config->channel_mask);
863        if (status != NO_ERROR) {
864            goto exit;
865        }
866        mChannelMask = config->channel_mask;
867    }
868    if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
869        status = audioport->checkExactFormat(config->format);
870        if (status != NO_ERROR) {
871            goto exit;
872        }
873        mFormat = config->format;
874    }
875    if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
876        status = audioport->checkGain(&config->gain, config->gain.index);
877        if (status != NO_ERROR) {
878            goto exit;
879        }
880        mGain = config->gain;
881    }
882
883exit:
884    if (status != NO_ERROR) {
885        applyAudioPortConfig(&localBackupConfig);
886    }
887    if (backupConfig != NULL) {
888        *backupConfig = localBackupConfig;
889    }
890    return status;
891}
892
893void AudioPortConfig::toAudioPortConfig(struct audio_port_config *dstConfig,
894                                        const struct audio_port_config *srcConfig) const
895{
896    if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
897        dstConfig->sample_rate = mSamplingRate;
898        if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
899            dstConfig->sample_rate = srcConfig->sample_rate;
900        }
901    } else {
902        dstConfig->sample_rate = 0;
903    }
904    if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
905        dstConfig->channel_mask = mChannelMask;
906        if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
907            dstConfig->channel_mask = srcConfig->channel_mask;
908        }
909    } else {
910        dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
911    }
912    if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
913        dstConfig->format = mFormat;
914        if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
915            dstConfig->format = srcConfig->format;
916        }
917    } else {
918        dstConfig->format = AUDIO_FORMAT_INVALID;
919    }
920    if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
921        dstConfig->gain = mGain;
922        if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
923            dstConfig->gain = srcConfig->gain;
924        }
925    } else {
926        dstConfig->gain.index = -1;
927    }
928    if (dstConfig->gain.index != -1) {
929        dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
930    } else {
931        dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
932    }
933}
934
935}; // namespace android
936