voidbind(int contextNumber, int busNumber, CarAudioDeviceInfo info) { if (mBusToCarAudioDeviceInfo.size() == 0) { mStepSize = info.getAudioGain().stepValue(); } else { Preconditions.checkArgument( info.getAudioGain().stepValue() == mStepSize, "Gain controls within one group must have same step value"); }
if (info.getDefaultGain() > mDefaultGain) { // We're arbitrarily selecting the highest bus default gain as the group's default. mDefaultGain = info.getDefaultGain(); } if (info.getMaxGain() > mMaxGain) { mMaxGain = info.getMaxGain(); } if (info.getMinGain() < mMinGain) { mMinGain = info.getMinGain(); } // ... 增益索引恢复逻辑 }
这条 Preconditions.checkArgument 是崩溃的常见来源:同一个 volume group 里,如果两个 bus 的硬件增益步进(step value)不同,bind() 会直接抛 IllegalArgumentException。
注释 // We're arbitrarily selecting the highest bus default gain as the group's default. 也值得注意——AOSP 承认这个默认值选择是”随意的(arbitrarily)”,它取了组内最高的默认增益。这意味着多 bus 场景下开机默认音量可能偏高。
privatevoidsetupAudioDynamicRoutingForGroup(CarVolumeGroup group, AudioPolicy.Builder builder) { // Note that one can not register audio mix for same bus more than once. for (int busNumber : group.getBusNumbers()) { booleanhasContext=false; CarAudioDeviceInfoinfo= group.getCarAudioDeviceInfoForBus(busNumber); AudioFormatmixFormat=newAudioFormat.Builder() .setSampleRate(info.getSampleRate()) .setEncoding(info.getEncodingFormat()) .setChannelMask(info.getChannelCount()) .build(); AudioMixingRule.BuildermixingRuleBuilder=newAudioMixingRule.Builder(); for (int contextNumber : group.getContextsForBus(busNumber)) { hasContext = true; int[] usages = getUsagesForContext(contextNumber); for (int usage : usages) { mixingRuleBuilder.addRule( newAudioAttributes.Builder().setUsage(usage).build(), AudioMixingRule.RULE_MATCH_ATTRIBUTE_USAGE); } Log.d(CarLog.TAG_AUDIO, "Bus number: " + busNumber + " contextNumber: " + contextNumber + " sampleRate: " + info.getSampleRate() + " channels: " + info.getChannelCount() + " usages: " + Arrays.toString(usages)); } if (hasContext) { AudioMixaudioMix=newAudioMix.Builder(mixingRuleBuilder.build()) .setFormat(mixFormat) .setDevice(info.getAudioDeviceInfo()) .setRouteFlags(AudioMix.ROUTE_FLAG_RENDER) .build(); builder.addMix(audioMix); } } }
我逐行拆解这张矩阵是怎么长出来的:
flowchart TD
START(["🔧 setupAudioDynamicRouting"]) --> Z["遍历每个 CarAudioZone"]
Z --> G["遍历 zone 里每个 volumeGroup"]
G --> B["遍历 group 里每个 bus"]
B --> FMT["按 bus 的 sampleRate/encoding/channelMask<br/>造一个 AudioFormat"]
FMT --> CTX["遍历这个 bus 上的所有 context"]
CTX --> MAP["getUsagesForContext: 反查每个 context<br/>对应哪些 usage"]
MAP --> RULE["每个 usage 加一条<br/>RULE_MATCH_ATTRIBUTE_USAGE 规则"]
RULE --> HAS{"hasContext<br/>= 这个 bus 有 context?"}
HAS -->|"是"| MIX["✅ 构造 AudioMix<br/>挂到 builder"]
HAS -->|"否"| SKIP["⏭️ 跳过,不建 AudioMix"]
MIX --> NEXT["下一个 bus"]
SKIP --> NEXT
NEXT -->|"还有 bus"| B
NEXT -->|"遍历完"| OUT(["📋 AudioPolicy.Builder<br/>拿到完整矩阵"])
style START fill:#C7CEEA,stroke:#9FA8DA,color:#333
style Z fill:#E8D5F5,stroke:#CE93D8,color:#333
style G fill:#E8D5F5,stroke:#CE93D8,color:#333
style B fill:#E8D5F5,stroke:#CE93D8,color:#333
style FMT fill:#FFF9C4,stroke:#F9A825,color:#333
style CTX fill:#FFF9C4,stroke:#F9A825,color:#333
style MAP fill:#FFDAB9,stroke:#FFAB76,color:#333
style RULE fill:#FFDAB9,stroke:#FFAB76,color:#333
style HAS fill:#FFF9C4,stroke:#F9A825,color:#333
style MIX fill:#B5EAD7,stroke:#80CBC4,color:#333
style SKIP fill:#F5F5F5,stroke:#BDBDBD,color:#333
style NEXT fill:#E8D5F5,stroke:#CE93D8,color:#333
style OUT fill:#B5EAD7,stroke:#80CBC4,color:#333
4.1 关键认知:矩阵的列是 bus,不是 context
很多人第一反应会以为”路由矩阵 = 8 个 context × N 个设备”的笛卡尔积。错。
AudioMix 是按 bus 建的,不是按 context 建的。一个 bus 上有几个 context,它们的 usages 就合并进同一个AudioMixingRule。所以:
bus 数 = AudioMix 数 = 矩阵的列数(不是 context 数)
每个 bus 对应一个独立的 AudioFormat(采样率/声道数由该 bus 的硬件决定)
同一个 AudioMix 里的所有 context,走同一套混音参数和同一个设备
这就是为什么”两个 context 绑同一 bus 就音量绑死”——它们连 AudioMix 都是同一个,共享同一套输出链路。
4.2 hasContext 这个开关:为什么有设备但没 context 的 bus 要跳过
1 2 3 4 5 6 7 8
if (hasContext) { // It's a valid case that an audio output bus is defined in // audio_policy_configuration and no context is assigned to it. // In such case, do not build a policy mix with zero rules. AudioMixaudioMix=newAudioMix.Builder(mixingRuleBuilder.build()) ... builder.addMix(audioMix); }
注释说得很清楚:audio_policy_configuration.xml 里定义的 bus 不一定都有 context 分配(可能留给未来用、或者专门给某个 HAL 用)。这种情况下不能建一个零规则的 AudioMix,否则会在 registerAudioPolicy() 时出问题。
booleanvalidateVolumeGroups() { Set<Integer> contextSet = newHashSet<>(); Set<Integer> busNumberSet = newHashSet<>(); for (CarVolumeGroup group : mVolumeGroups) { // One context should not appear in two groups for (int context : group.getContexts()) { if (contextSet.contains(context)) { Log.e(CarLog.TAG_AUDIO, "Context appears in two groups: " + context); returnfalse; } contextSet.add(context); } // One bus should not appear in two groups for (int busNumber : group.getBusNumbers()) { if (busNumberSet.contains(busNumber)) { Log.e(CarLog.TAG_AUDIO, "Bus appears in two groups: " + busNumber); returnfalse; } busNumberSet.add(busNumber); } } // All contexts are assigned if (contextSet.size() != CarAudioDynamicRouting.CONTEXT_NUMBERS.length) { Log.e(CarLog.TAG_AUDIO, "Some contexts are not assigned to group"); ... returnfalse; } returntrue; }
// Given a group level gain index, return the computed gain in millibels // TODO (randolphs) If we ever want to add index to gain curves other than lock-stepped // linear, this would be the place to do it. privateintgetGainForIndex(int gainIndex) { return mMinGain + gainIndex * mStepSize; }
setCurrentGain 会写到 group 内每一个 bus——再次印证”group 内音量不可分”
最后 Settings.Global.putInt 持久化,key 由 getVolumeSettingsKeyForGroup(zoneId, groupId) 生成,每个 zone 的每个 group 各存一份
6.3 开机增益恢复:优先用上次存的值
bind() 末尾有一段增益索引恢复逻辑:
1 2 3 4 5 6 7
if (mStoredGainIndex < getMinGainIndex() || mStoredGainIndex > getMaxGainIndex()) { // We expected to load a value from last boot, but if we didn't (perhaps this is the // first boot ever?), then use the highest "default" we've seen to initialize ourselves. mCurrentGainIndex = getIndexForGain(mDefaultGain); } else { mCurrentGainIndex = mStoredGainIndex; }
// For legacy stream type based volume control. // Values in STREAM_TYPES and STREAM_TYPE_USAGES should be aligned. staticfinalint[] STREAM_TYPES = newint[] { AudioManager.STREAM_MUSIC, AudioManager.STREAM_ALARM, AudioManager.STREAM_RING }; staticfinalint[] STREAM_TYPE_USAGES = newint[] { AudioAttributes.USAGE_MEDIA, AudioAttributes.USAGE_ALARM, AudioAttributes.USAGE_NOTIFICATION_RINGTONE };
老模型只有 3 个音量组(music/alarm/ring),对应 3 个 stream type。动态路由把它扩展到”每 zone 多个 volume group,每 group N 个 context”。
7.5·1 三个数组的平行索引陷阱
注意源码里那两行数组和注释:
1
// Values in STREAM_TYPES and STREAM_TYPE_USAGES should be aligned.
sequenceDiagram
participant SYS as 🖥️ SystemServer
participant CAS as 🎵 CarAudioService
participant HLP as 📄 Helper(XML)
participant ZON as 🗂️ CarAudioZone[]
participant DR as 🔀 DynamicRouting
participant AM as 🎚️ AudioManager
participant AF as 🔊 AudioPolicyService
SYS->>CAS: onCreate()
CAS->>CAS: mUseDynamicRouting = getBoolean(audioUseDynamicRouting)
alt legacy mode
CAS->>CAS: 走 STREAM_TYPES 老路径
else dynamic routing
CAS->>HLP: parse audio_policy_configuration + car_audio_configuration
HPL-->>CAS: busToCarAudioDeviceInfo (bus0/1/2/3...)
CAS->>HLP: loadAudioZones()
HPL-->>CAS: CarAudioZone[] (含 volumeGroups + contextToBus)
CAS->>CAS: zone.validateVolumeGroups() ⚠️ 失败即抛异常
CAS->>DR: setupAudioDynamicRouting(builder)
DR->>DR: 逐 bus 构造 AudioMixingRule
DR-->>CAS: builder 里已有 N 个 AudioMix
CAS->>CAS: builder.setAudioPolicyVolumeCallback(...)
CAS->>AM: registerAudioPolicy(mAudioPolicy)
AM->>AF: 下发矩阵
AF-->>AM: ok
end
Note over CAS,AF: ⚠️ 矩阵此后冻结,进程存活期间不再重算
style participant
8.1 validateVolumeGroups() 的调用点决定了失败时机
在 CarAudioService.setupDynamicRouting() 里,顺序是这样的:
1 2 3 4
for (CarAudioZone zone : mCarAudioZones) { Preconditions.checkArgument(zone.validateVolumeGroups(), "CarAudioZone: " + zone.getName() + " has invalid volume groups"); }
Preconditions.checkArgument 失败时抛 IllegalArgumentException。这个异常发生在 CarAudioService.onCreate() 里,会导致整个 car service 启动失败——表现为主驾屏上语音助手、CarLauncher 全都打不开,只能进 recovery。
每个 bus 的 AudioFormat 来自它自己的硬件(CarAudioDeviceInfo.getSampleRate() 等)。这不是全局统一值——实践中常见的情况是:
bus 类型
典型采样率
典型声道
备注
MEDIA 输出
48000 Hz
立体声(mask=3)
DAC 直通
CALL 输入+输出
16000 Hz 单声道
单声道(mask=1)
为语音带宽省资源
系统提示音
44100 Hz
立体声
遗留设备常见 44.1k
如果你的 app 用 44100 Hz 推流,而 MUSIC 那个 bus 是 48000 Hz,AudioFlinger 会在混音时重采样。重采样本身不致命,但它引入延迟和失真——这正是 Day 18 那篇延迟预算文章里”声学前端占 73%”的一部分背景:格式不匹配的重采样,会把音频挤到 fast mixer 之外,掉进普通混音线程。
结论:车机应用的音频采样率必须和目标 bus 对齐。对齐方法不是猜,而是 AudioTrack 起来之后读 getNativeOutputSampleRate(),或者在 audio_policy_configuration.xml 里显式声明。
defrules_for(bus_to_ctx, U2C): """统计某种 bus 划分下的 AudioMix 数和 mixing rule 总数""" inv = {} for u, c in U2C.items(): inv.setdefault(c, []).append(u) n_mix = n_rule = 0 per_bus = {} for bus, ctxs in bus_to_ctx.items(): ifnot ctxs: continue# hasContext==false 分支,跳过 n_mix += 1 r = sum(len(inv.get(c, [])) for c in ctxs) per_bus[bus] = r n_rule += r return n_mix, n_rule, per_bus
ALL = list(range(1, 9)) # 8 个 context strategies = { "A 全塞 1 个 bus": {0: ALL}, "B 音乐/语音 1 bus": {0: [1, 8, 2], 1: [5, 6]}, "C 细粒度 4 bus": {0: [1], 1: [8, 2], 2: [4, 3], 3: [5, 6, 7]}, "D 极致 8 bus": {i: [c] for i, c inenumerate(ALL)}, } for name, m in strategies.items(): nm, nr, per = rules_for(m, U2C) print(f"{name:<22} bus数={len(m):>2} AudioMix={nm:>2} 总rule={nr:>2}{per}")
MVP 真实输出:
1 2 3 4
A 全塞 1 个 bus bus数= 1 AudioMix= 1 总rule=16 B 音乐/语音 1 bus bus数= 2 AudioMix= 2 总rule= 9 C 细粒度 4 bus bus数= 4 AudioMix= 4 总rule=16 D 极致 8 bus bus数= 8 AudioMix= 8 总rule=16
def get_usages_for_context(context_number): """复刻 CarAudioDynamicRouting.getUsagesForContext()""" return sorted(u for u, c in USAGE_TO_CONTEXT.items() if c == context_number)
def part1_usage_fanout(): print("=" * 78) print("[Part 1] USAGE -> CONTEXT 反向映射") print("=" * 78) for c in CONTEXT_NUMBERS: us = get_usages_for_context(c) print(f" {CONTEXT_NAMES[c]:<15} -> {len(us):>2} usages: {[USAGE_NAMES[u] for u in us]}") black_hole = [u for u, c in USAGE_TO_CONTEXT.items() if c == INVALID] print(f"\n 映射到 INVALID(黑洞): {[USAGE_NAMES[u] for u in black_hole]}") assert len(black_hole) == 1 and black_hole[0] == USAGE_VIRTUAL_SOURCE print(" ✅ Part1 通过")
defget_usages_for_context(context_number): """复刻 CarAudioDynamicRouting.getUsagesForContext():反向查表""" returnsorted(u for u, c in USAGE_TO_CONTEXT.items() if c == context_number)
# ═══════════════════════════════════════════════════════════════ # 1. 反向映射统计:哪些 usage 打到了 INVALID(= 黑洞) # ═══════════════════════════════════════════════════════════════ defpart1_usage_fanout(): print("=" * 78) print("[Part 1] USAGE -> CONTEXT 反向映射:每个 context 挂多少个 usage") print("=" * 78) fanout = {c: get_usages_for_context(c) for c in CONTEXT_NUMBERS} total_assigned = 0 for c in CONTEXT_NUMBERS: us = fanout[c] total_assigned += len(us) print(f" {CONTEXT_NAMES[c]:<15} -> {len(us):>2} usages: " f"{[USAGE_NAMES[u] for u in us]}") print(f"\n 被绑定的 usage 总数 = {total_assigned} / USAGE_TO_CONTEXT 大小 {len(USAGE_TO_CONTEXT)}") black_hole = [u for u, c in USAGE_TO_CONTEXT.items() if c == INVALID] print(f" 映射到 INVALID(= ContextNumber.INVALID,mix 里永远不会被 rule 命中): " f"{[USAGE_NAMES[u] for u in black_hole]}") assertlen(black_hole) == 1and black_hole[0] == USAGE_VIRTUAL_SOURCE # 每个 usage 恰好映射一次 → 反查总数应等于表大小 assert total_assigned + len(black_hole) == len(USAGE_TO_CONTEXT) return fanout
defpart2_build_routing_matrix(): print("\n" + "=" * 78) print("[Part 2] setupAudioDynamicRoutingForGroup(): 逐 bus 构造 AudioMix") print("=" * 78) mixes = [] # (zoneId, groupId, bus, contexts, usages, sampleRate, channels) for zone in ZONES: for grp in zone["groups"]: for bus, (ming, maxg) insorted(grp["devices"].items()): ctxs = sorted([c for c, b in grp["contexts"].items() if b == bus]) usages = [] for c in ctxs: usages.extend(get_usages_for_context(c)) usages = sorted(set(usages)) # 源码: if (hasContext) 才 build mix —— 空 context 的 bus 跳过 ifnot ctxs: print(f" [SKIP] zone{zone['id']} g{grp['groupId']} bus {bus}: " f"有设备但 0 context -> 不建 AudioMix") continue mixes.append((zone["id"], grp["groupId"], bus, ctxs, usages)) print(f" zone{zone['id']} g{grp['groupId']} bus {bus:>3} " f"gain=[{ming},{maxg}] step={grp['step']}mB " f"contexts={[CONTEXT_NAMES[c] for c in ctxs]}") print(f"{'':>26} mixing-rule usages({len(usages)})=" f"{[USAGE_NAMES[u] for u in usages]}") print(f"\n 共构造 AudioMix = {len(mixes)} 个") return mixes
# ═══════════════════════════════════════════════════════════════ # 3. validateVolumeGroups() 的 3 条约束逐条验证 # ═══════════════════════════════════════════════════════════════ defpart3_validate(zone): print(f"\n--- 校验 zone{zone['id']} ({zone['name']}) ---") ctx_seen, bus_seen = set(), set() ok = True for grp in zone["groups"]: for c in grp["contexts"]: if c in ctx_seen: print(f" ❌ Constraint#1 违反: context {CONTEXT_NAMES[c]} 出现在两个 group") ok = False ctx_seen.add(c) for b in grp["devices"]: if b in bus_seen: print(f" ❌ Constraint#2 违反: bus {b} 出现在两个 group") ok = False bus_seen.add(b) # step size 一致性(CarVolumeGroup.bind() 的 Preconditions) for grp in zone["groups"]: iflen(set([g["step"] for g in zone["groups"] if g["groupId"] == grp["groupId"]])) > 1: print(f" ❌ Constraint#3 违反: group{grp['groupId']} 内 step 不一致") ok = False
iflen(ctx_seen) != len(CONTEXT_NUMBERS): missing = [CONTEXT_NAMES[c] for c in CONTEXT_NUMBERS if c notin ctx_seen] print(f" ❌ Constraint#all 违反: 还有 {len(missing)} 个 context 未分配 -> {missing}") ok = False else: print(f" ✅ 8 个 context 全部分配,无重复") print(f" ✅ 约束检查结果: {'PASS'if ok else'FAIL'}") return ok
defpart3_negative(): """反例:故意把一个 context 挪到另一个 group,看 validate 是否真的返回 false""" print("\n--- 反例:把 MUSIC 从 group0 挪到 group1(同 zone) ---") bad = {"id": 99, "name": "bad_zone", "groups": [ {"groupId": 0, "step": 25, "devices": {0: (-3600, 0)}, "contexts": {MUSIC: 0}}, {"groupId": 1, "step": 50, "devices": {2: (-3600, 0)}, "contexts": {MUSIC: 2, ALARM: 2, NOTIFICATION: 2, CALL: 2, CALL_RING: 2}}, ]} # 手工执行 Constraint#1 seen = set(); dup = None for grp in bad["groups"]: for c in grp["contexts"]: if c in seen and dup isNone: dup = c seen.add(c) print(f" 重复的 context = {CONTEXT_NAMES[dup] if dup else'None'}") assert dup == MUSIC print(f" → validateVolumeGroups() 会在第一个 if 就 return false") print(f" → 后果:setupDynamicRouting() 抛 IllegalArgumentException," f"整个 CarAudioService 起不来")