2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.server;
19 import static com.android.server.input.InputManagerService.SW_HEADPHONE_INSERT;
20 import static com.android.server.input.InputManagerService.SW_HEADPHONE_INSERT_BIT;
21 import static com.android.server.input.InputManagerService.SW_LINEOUT_INSERT;
22 import static com.android.server.input.InputManagerService.SW_LINEOUT_INSERT_BIT;
23 import static com.android.server.input.InputManagerService.SW_MICROPHONE_INSERT;
24 import static com.android.server.input.InputManagerService.SW_MICROPHONE_INSERT_BIT;
26 import android.content.Context;
27 import android.media.AudioManager;
28 import android.os.Handler;
29 import android.os.Looper;
30 import android.os.Message;
31 import android.os.PowerManager;
32 import android.os.PowerManager.WakeLock;
33 import android.os.UEventObserver;
34 import android.util.Log;
35 import android.util.Pair;
36 import android.util.Slog;
37 import android.view.InputDevice;
39 import com.android.internal.R;
40 import com.android.server.input.InputManagerService;
41 import com.android.server.input.InputManagerService.WiredAccessoryCallbacks;
44 import java.io.FileNotFoundException;
45 import java.io.FileReader;
46 import java.io.IOException;
47 import java.util.ArrayList;
48 import java.util.List;
49 import java.util.Locale;
52 * <p>WiredAccessoryManager monitors for a wired headset on the main board or dock using
53 * both the InputManagerService notifyWiredAccessoryChanged interface and the UEventObserver
56 final class WiredAccessoryManager implements WiredAccessoryCallbacks {
57 private static final String TAG = WiredAccessoryManager.class.getSimpleName();
58 private static final boolean LOG = false;
60 private static final int BIT_HEADSET = (1 << 0);
61 private static final int BIT_HEADSET_NO_MIC = (1 << 1);
62 private static final int BIT_USB_HEADSET_ANLG = (1 << 2);
63 private static final int BIT_USB_HEADSET_DGTL = (1 << 3);
64 private static final int BIT_HDMI_AUDIO = (1 << 4);
65 private static final int BIT_LINEOUT = (1 << 5);
66 private static final int SUPPORTED_HEADSETS = (BIT_HEADSET | BIT_HEADSET_NO_MIC |
67 BIT_USB_HEADSET_ANLG | BIT_USB_HEADSET_DGTL |
68 BIT_HDMI_AUDIO | BIT_LINEOUT);
70 private static final String NAME_H2W = "h2w";
71 private static final String NAME_USB_AUDIO = "usb_audio";
72 private static final String NAME_HDMI_AUDIO = "hdmi_audio";
73 private static final String NAME_HDMI = "hdmi";
75 private static final int MSG_NEW_DEVICE_STATE = 1;
76 private static final int MSG_SYSTEM_READY = 2;
78 private final Object mLock = new Object();
80 private final WakeLock mWakeLock; // held while there is a pending route change
81 private final AudioManager mAudioManager;
83 private int mHeadsetState;
85 private int mSwitchValues;
87 private final WiredAccessoryObserver mObserver;
88 private final WiredAccessoryExtconObserver mExtconObserver;
89 private final InputManagerService mInputManager;
91 private final boolean mUseDevInputEventForAudioJack;
93 public WiredAccessoryManager(Context context, InputManagerService inputManager) {
94 PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
95 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "WiredAccessoryManager");
96 mWakeLock.setReferenceCounted(false);
97 mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
98 mInputManager = inputManager;
100 mUseDevInputEventForAudioJack =
101 context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);
103 mExtconObserver = new WiredAccessoryExtconObserver();
104 mObserver = new WiredAccessoryObserver();
107 private void onSystemReady() {
108 if (mUseDevInputEventForAudioJack) {
109 int switchValues = 0;
110 if (mInputManager.getSwitchState(-1, InputDevice.SOURCE_ANY, SW_HEADPHONE_INSERT)
112 switchValues |= SW_HEADPHONE_INSERT_BIT;
114 if (mInputManager.getSwitchState(-1, InputDevice.SOURCE_ANY, SW_MICROPHONE_INSERT)
116 switchValues |= SW_MICROPHONE_INSERT_BIT;
118 if (mInputManager.getSwitchState(-1, InputDevice.SOURCE_ANY, SW_LINEOUT_INSERT) == 1) {
119 switchValues |= SW_LINEOUT_INSERT_BIT;
121 notifyWiredAccessoryChanged(0, switchValues,
122 SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_LINEOUT_INSERT_BIT);
126 if (ExtconUEventObserver.extconExists()) {
127 if (mUseDevInputEventForAudioJack) {
128 Log.w(TAG, "Both input event and extcon are used for audio jack,"
129 + " please just choose one.");
131 mExtconObserver.init();
138 public void notifyWiredAccessoryChanged(long whenNanos, int switchValues, int switchMask) {
140 Slog.v(TAG, "notifyWiredAccessoryChanged: when=" + whenNanos
141 + " bits=" + switchCodeToString(switchValues, switchMask)
142 + " mask=" + Integer.toHexString(switchMask));
145 synchronized (mLock) {
147 mSwitchValues = (mSwitchValues & ~switchMask) | switchValues;
148 switch (mSwitchValues &
149 (SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_LINEOUT_INSERT_BIT)) {
154 case SW_HEADPHONE_INSERT_BIT:
155 headset = BIT_HEADSET_NO_MIC;
158 case SW_LINEOUT_INSERT_BIT:
159 headset = BIT_LINEOUT;
162 case SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT:
163 headset = BIT_HEADSET;
166 case SW_MICROPHONE_INSERT_BIT:
167 headset = BIT_HEADSET;
175 updateLocked(NAME_H2W,
176 (mHeadsetState & ~(BIT_HEADSET | BIT_HEADSET_NO_MIC | BIT_LINEOUT)) | headset);
181 public void systemReady() {
182 synchronized (mLock) {
185 Message msg = mHandler.obtainMessage(MSG_SYSTEM_READY, 0, 0, null);
186 mHandler.sendMessage(msg);
191 * Compare the existing headset state with the new state and pass along accordingly. Note
192 * that this only supports a single headset at a time. Inserting both a usb and jacked headset
193 * results in support for the last one plugged in. Similarly, unplugging either is seen as
196 * @param newName One of the NAME_xxx variables defined above.
197 * @param newState 0 or one of the BIT_xxx variables defined above.
199 private void updateLocked(String newName, int newState) {
200 // Retain only relevant bits
201 int headsetState = newState & SUPPORTED_HEADSETS;
202 int usb_headset_anlg = headsetState & BIT_USB_HEADSET_ANLG;
203 int usb_headset_dgtl = headsetState & BIT_USB_HEADSET_DGTL;
204 int h2w_headset = headsetState & (BIT_HEADSET | BIT_HEADSET_NO_MIC | BIT_LINEOUT);
205 boolean h2wStateChange = true;
206 boolean usbStateChange = true;
208 Slog.v(TAG, "newName=" + newName
209 + " newState=" + newState
210 + " headsetState=" + headsetState
211 + " prev headsetState=" + mHeadsetState);
214 if (mHeadsetState == headsetState) {
215 Log.e(TAG, "No state change.");
219 // reject all suspect transitions: only accept state changes from:
220 // - a: 0 headset to 1 headset
221 // - b: 1 headset to 0 headset
222 if (h2w_headset == (BIT_HEADSET | BIT_HEADSET_NO_MIC | BIT_LINEOUT)) {
223 Log.e(TAG, "Invalid combination, unsetting h2w flag");
224 h2wStateChange = false;
226 // - c: 0 usb headset to 1 usb headset
227 // - d: 1 usb headset to 0 usb headset
228 if (usb_headset_anlg == BIT_USB_HEADSET_ANLG && usb_headset_dgtl == BIT_USB_HEADSET_DGTL) {
229 Log.e(TAG, "Invalid combination, unsetting usb flag");
230 usbStateChange = false;
232 if (!h2wStateChange && !usbStateChange) {
233 Log.e(TAG, "invalid transition, returning ...");
239 Log.i(TAG, "MSG_NEW_DEVICE_STATE");
240 Message msg = mHandler.obtainMessage(MSG_NEW_DEVICE_STATE, headsetState,
242 mHandler.sendMessage(msg);
244 mHeadsetState = headsetState;
247 private final Handler mHandler = new Handler(Looper.myLooper(), null, true) {
249 public void handleMessage(Message msg) {
251 case MSG_NEW_DEVICE_STATE:
252 setDevicesState(msg.arg1, msg.arg2, (String) msg.obj);
255 case MSG_SYSTEM_READY:
263 private void setDevicesState(
264 int headsetState, int prevHeadsetState, String headsetName) {
265 synchronized (mLock) {
266 int allHeadsets = SUPPORTED_HEADSETS;
267 for (int curHeadset = 1; allHeadsets != 0; curHeadset <<= 1) {
268 if ((curHeadset & allHeadsets) != 0) {
269 setDeviceStateLocked(curHeadset, headsetState, prevHeadsetState, headsetName);
270 allHeadsets &= ~curHeadset;
276 private void setDeviceStateLocked(int headset,
277 int headsetState, int prevHeadsetState, String headsetName) {
278 if ((headsetState & headset) != (prevHeadsetState & headset)) {
283 if ((headsetState & headset) != 0) {
289 if (headset == BIT_HEADSET) {
290 outDevice = AudioManager.DEVICE_OUT_WIRED_HEADSET;
291 inDevice = AudioManager.DEVICE_IN_WIRED_HEADSET;
292 } else if (headset == BIT_HEADSET_NO_MIC) {
293 outDevice = AudioManager.DEVICE_OUT_WIRED_HEADPHONE;
294 } else if (headset == BIT_LINEOUT) {
295 outDevice = AudioManager.DEVICE_OUT_LINE;
296 } else if (headset == BIT_USB_HEADSET_ANLG) {
297 outDevice = AudioManager.DEVICE_OUT_ANLG_DOCK_HEADSET;
298 } else if (headset == BIT_USB_HEADSET_DGTL) {
299 outDevice = AudioManager.DEVICE_OUT_DGTL_DOCK_HEADSET;
300 } else if (headset == BIT_HDMI_AUDIO) {
301 outDevice = AudioManager.DEVICE_OUT_HDMI;
303 Slog.e(TAG, "setDeviceState() invalid headset type: " + headset);
308 Slog.v(TAG, "headsetName: " + headsetName +
309 (state == 1 ? " connected" : " disconnected"));
312 if (outDevice != 0) {
313 mAudioManager.setWiredDeviceConnectionState(outDevice, state, "", headsetName);
316 mAudioManager.setWiredDeviceConnectionState(inDevice, state, "", headsetName);
321 private String switchCodeToString(int switchValues, int switchMask) {
322 StringBuffer sb = new StringBuffer();
323 if ((switchMask & SW_HEADPHONE_INSERT_BIT) != 0 &&
324 (switchValues & SW_HEADPHONE_INSERT_BIT) != 0) {
325 sb.append("SW_HEADPHONE_INSERT ");
327 if ((switchMask & SW_MICROPHONE_INSERT_BIT) != 0 &&
328 (switchValues & SW_MICROPHONE_INSERT_BIT) != 0) {
329 sb.append("SW_MICROPHONE_INSERT");
331 return sb.toString();
334 class WiredAccessoryObserver extends UEventObserver {
335 private final List<UEventInfo> mUEventInfo;
337 public WiredAccessoryObserver() {
338 mUEventInfo = makeObservedUEventList();
342 synchronized (mLock) {
343 if (LOG) Slog.v(TAG, "init()");
344 char[] buffer = new char[1024];
346 for (int i = 0; i < mUEventInfo.size(); ++i) {
347 UEventInfo uei = mUEventInfo.get(i);
350 FileReader file = new FileReader(uei.getSwitchStatePath());
351 int len = file.read(buffer, 0, 1024);
353 curState = Integer.parseInt((new String(buffer, 0, len)).trim());
356 updateStateLocked(uei.getDevPath(), uei.getDevName(), curState);
358 } catch (FileNotFoundException e) {
359 Slog.w(TAG, uei.getSwitchStatePath() +
360 " not found while attempting to determine initial switch state");
361 } catch (Exception e) {
362 Slog.e(TAG, "Error while attempting to determine initial switch state for "
363 + uei.getDevName(), e);
368 // At any given time accessories could be inserted
369 // one on the board, one on the dock and one on HDMI:
370 // observe three UEVENTs
371 for (int i = 0; i < mUEventInfo.size(); ++i) {
372 UEventInfo uei = mUEventInfo.get(i);
373 startObserving("DEVPATH=" + uei.getDevPath());
377 private List<UEventInfo> makeObservedUEventList() {
378 List<UEventInfo> retVal = new ArrayList<UEventInfo>();
382 if (!mUseDevInputEventForAudioJack) {
383 uei = new UEventInfo(NAME_H2W, BIT_HEADSET, BIT_HEADSET_NO_MIC, BIT_LINEOUT);
384 if (uei.checkSwitchExists()) {
387 Slog.w(TAG, "This kernel does not have wired headset support");
392 uei = new UEventInfo(NAME_USB_AUDIO, BIT_USB_HEADSET_ANLG, BIT_USB_HEADSET_DGTL, 0);
393 if (uei.checkSwitchExists()) {
396 Slog.w(TAG, "This kernel does not have usb audio support");
401 // If the kernel has support for the "hdmi_audio" switch, use that. It will be
402 // signalled only when the HDMI driver has a video mode configured, and the downstream
403 // sink indicates support for audio in its EDID.
405 // If the kernel does not have an "hdmi_audio" switch, just fall back on the older
406 // "hdmi" switch instead.
407 uei = new UEventInfo(NAME_HDMI_AUDIO, BIT_HDMI_AUDIO, 0, 0);
408 if (uei.checkSwitchExists()) {
411 uei = new UEventInfo(NAME_HDMI, BIT_HDMI_AUDIO, 0, 0);
412 if (uei.checkSwitchExists()) {
415 Slog.w(TAG, "This kernel does not have HDMI audio support");
423 public void onUEvent(UEventObserver.UEvent event) {
424 if (LOG) Slog.v(TAG, "Headset UEVENT: " + event.toString());
427 String devPath = event.get("DEVPATH");
428 String name = event.get("SWITCH_NAME");
429 int state = Integer.parseInt(event.get("SWITCH_STATE"));
430 synchronized (mLock) {
431 updateStateLocked(devPath, name, state);
433 } catch (NumberFormatException e) {
434 Slog.e(TAG, "Could not parse switch state from event " + event);
438 private void updateStateLocked(String devPath, String name, int state) {
439 for (int i = 0; i < mUEventInfo.size(); ++i) {
440 UEventInfo uei = mUEventInfo.get(i);
441 if (devPath.equals(uei.getDevPath())) {
442 updateLocked(name, uei.computeNewHeadsetState(mHeadsetState, state));
448 private final class UEventInfo {
449 private final String mDevName;
450 private final int mState1Bits;
451 private final int mState2Bits;
452 private final int mStateNbits;
454 public UEventInfo(String devName, int state1Bits, int state2Bits, int stateNbits) {
456 mState1Bits = state1Bits;
457 mState2Bits = state2Bits;
458 mStateNbits = stateNbits;
461 public String getDevName() {
465 public String getDevPath() {
466 return String.format(Locale.US, "/devices/virtual/switch/%s", mDevName);
469 public String getSwitchStatePath() {
470 return String.format(Locale.US, "/sys/class/switch/%s/state", mDevName);
473 public boolean checkSwitchExists() {
474 File f = new File(getSwitchStatePath());
478 public int computeNewHeadsetState(int headsetState, int switchState) {
479 int preserveMask = ~(mState1Bits | mState2Bits | mStateNbits);
480 int setBits = ((switchState == 1) ? mState1Bits :
481 ((switchState == 2) ? mState2Bits :
482 ((switchState == mStateNbits) ? mStateNbits : 0)));
484 return ((headsetState & preserveMask) | setBits);
489 private class WiredAccessoryExtconObserver extends ExtconStateObserver<Pair<Integer, Integer>> {
490 private final List<ExtconInfo> mExtconInfos;
492 WiredAccessoryExtconObserver() {
493 mExtconInfos = ExtconInfo.getExtconInfos(".*audio.*");
497 private void init() {
498 for (ExtconInfo extconInfo : mExtconInfos) {
499 Pair<Integer, Integer> state = null;
501 state = parseStateFromFile(extconInfo);
502 } catch (FileNotFoundException e) {
503 Slog.w(TAG, extconInfo.getStatePath()
504 + " not found while attempting to determine initial state", e);
505 } catch (IOException e) {
508 "Error reading " + extconInfo.getStatePath()
509 + " while attempting to determine initial state",
513 updateState(extconInfo, extconInfo.getName(), state);
515 if (LOG) Slog.d(TAG, "observing " + extconInfo.getName());
516 startObserving(extconInfo);
522 public Pair<Integer, Integer> parseState(ExtconInfo extconInfo, String status) {
523 if (LOG) Slog.v(TAG, "status " + status);
524 int []maskAndState = {0,0};
525 // extcon event state changes from kernel4.9
526 // new state will be like STATE=MICROPHONE=1\nHEADPHONE=0
527 updateBit(maskAndState, BIT_HEADSET_NO_MIC, status, "HEADPHONE") ;
528 updateBit(maskAndState, BIT_HEADSET, status,"MICROPHONE") ;
529 updateBit(maskAndState, BIT_HDMI_AUDIO, status,"HDMI") ;
530 updateBit(maskAndState, BIT_LINEOUT, status,"LINE-OUT") ;
531 if (LOG) Slog.v(TAG, "mask " + maskAndState[0] + " state " + maskAndState[1]);
532 return Pair.create(maskAndState[0],maskAndState[1]);
536 public void updateState(ExtconInfo extconInfo, String name,
537 Pair<Integer, Integer> maskAndState) {
538 synchronized (mLock) {
539 int mask = maskAndState.first;
540 int state = maskAndState.second;
541 updateLocked(name, mHeadsetState & ~(mask & ~state) | (mask & state));
548 * Updates the mask bit at {@code position} to 1 and the state bit at {@code position} to true
549 * if {@code name=1} or false if {}@code name=0} is contained in {@code state}.
551 private static void updateBit(int[] maskAndState, int position, String state, String name) {
552 maskAndState[0] |= position;
553 if (state.contains(name + "=1")) {
554 maskAndState[0] |= position;
555 maskAndState[1] |= position;
556 } else if (state.contains(name + "=0")) {
557 maskAndState[0] |= position;
558 maskAndState[1] &= ~position;