1/*
2 * Copyright (C) 2008 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
17package com.android.server;
18
19import android.content.BroadcastReceiver;
20import android.content.Context;
21import android.content.Intent;
22import android.content.IntentFilter;
23import android.os.Handler;
24import android.os.Looper;
25import android.os.Message;
26import android.os.PowerManager;
27import android.os.PowerManager.WakeLock;
28import android.os.UEventObserver;
29import android.util.Slog;
30import android.media.AudioManager;
31import android.util.Log;
32import android.view.InputDevice;
33
34import com.android.internal.R;
35import com.android.server.input.InputManagerService;
36import com.android.server.input.InputManagerService.WiredAccessoryCallbacks;
37import static com.android.server.input.InputManagerService.SW_HEADPHONE_INSERT;
38import static com.android.server.input.InputManagerService.SW_MICROPHONE_INSERT;
39import static com.android.server.input.InputManagerService.SW_LINEOUT_INSERT;
40import static com.android.server.input.InputManagerService.SW_HEADPHONE_INSERT_BIT;
41import static com.android.server.input.InputManagerService.SW_MICROPHONE_INSERT_BIT;
42import static com.android.server.input.InputManagerService.SW_LINEOUT_INSERT_BIT;
43
44import java.io.File;
45import java.io.FileReader;
46import java.io.FileNotFoundException;
47import java.util.ArrayList;
48import java.util.List;
49import java.util.Locale;
50
51/**
52 * <p>WiredAccessoryManager monitors for a wired headset on the main board or dock using
53 * both the InputManagerService notifyWiredAccessoryChanged interface and the UEventObserver
54 * subsystem.
55 */
56final class WiredAccessoryManager implements WiredAccessoryCallbacks {
57    private static final String TAG = WiredAccessoryManager.class.getSimpleName();
58    private static final boolean LOG = true;
59
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);
69
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";
74
75    private static final int MSG_NEW_DEVICE_STATE = 1;
76    private static final int MSG_SYSTEM_READY = 2;
77
78    private final Object mLock = new Object();
79
80    private final WakeLock mWakeLock;  // held while there is a pending route change
81    private final AudioManager mAudioManager;
82
83    private int mHeadsetState;
84
85    private int mSwitchValues;
86
87    private final WiredAccessoryObserver mObserver;
88    private final InputManagerService mInputManager;
89
90    private final boolean mUseDevInputEventForAudioJack;
91
92    public WiredAccessoryManager(Context context, InputManagerService inputManager) {
93        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
94        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "WiredAccessoryManager");
95        mWakeLock.setReferenceCounted(false);
96        mAudioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
97        mInputManager = inputManager;
98
99        mUseDevInputEventForAudioJack =
100                context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);
101
102        mObserver = new WiredAccessoryObserver();
103    }
104
105    private void onSystemReady() {
106        if (mUseDevInputEventForAudioJack) {
107            int switchValues = 0;
108            if (mInputManager.getSwitchState(-1, InputDevice.SOURCE_ANY, SW_HEADPHONE_INSERT) == 1) {
109                switchValues |= SW_HEADPHONE_INSERT_BIT;
110            }
111            if (mInputManager.getSwitchState(-1, InputDevice.SOURCE_ANY, SW_MICROPHONE_INSERT) == 1) {
112                switchValues |= SW_MICROPHONE_INSERT_BIT;
113            }
114            if (mInputManager.getSwitchState(-1, InputDevice.SOURCE_ANY, SW_LINEOUT_INSERT) == 1) {
115                switchValues |= SW_LINEOUT_INSERT_BIT;
116            }
117            notifyWiredAccessoryChanged(0, switchValues,
118                    SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_LINEOUT_INSERT_BIT);
119        }
120
121        mObserver.init();
122    }
123
124    @Override
125    public void notifyWiredAccessoryChanged(long whenNanos, int switchValues, int switchMask) {
126        if (LOG) Slog.v(TAG, "notifyWiredAccessoryChanged: when=" + whenNanos
127                + " bits=" + switchCodeToString(switchValues, switchMask)
128                + " mask=" + Integer.toHexString(switchMask));
129
130        synchronized (mLock) {
131            int headset;
132            mSwitchValues = (mSwitchValues & ~switchMask) | switchValues;
133            switch (mSwitchValues &
134                (SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_LINEOUT_INSERT_BIT)) {
135                case 0:
136                    headset = 0;
137                    break;
138
139                case SW_HEADPHONE_INSERT_BIT:
140                    headset = BIT_HEADSET_NO_MIC;
141                    break;
142
143                case SW_LINEOUT_INSERT_BIT:
144                    headset = BIT_LINEOUT;
145                    break;
146
147                case SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT:
148                    headset = BIT_HEADSET;
149                    break;
150
151                case SW_MICROPHONE_INSERT_BIT:
152                    headset = BIT_HEADSET;
153                    break;
154
155                default:
156                    headset = 0;
157                    break;
158            }
159
160            updateLocked(NAME_H2W,
161                (mHeadsetState & ~(BIT_HEADSET | BIT_HEADSET_NO_MIC | BIT_LINEOUT)) | headset);
162        }
163    }
164
165    @Override
166    public void systemReady() {
167        synchronized (mLock) {
168            mWakeLock.acquire();
169
170            Message msg = mHandler.obtainMessage(MSG_SYSTEM_READY, 0, 0, null);
171            mHandler.sendMessage(msg);
172        }
173    }
174
175    /**
176     * Compare the existing headset state with the new state and pass along accordingly. Note
177     * that this only supports a single headset at a time. Inserting both a usb and jacked headset
178     * results in support for the last one plugged in. Similarly, unplugging either is seen as
179     * unplugging all.
180     *
181     * @param newName One of the NAME_xxx variables defined above.
182     * @param newState 0 or one of the BIT_xxx variables defined above.
183     */
184    private void updateLocked(String newName, int newState) {
185        // Retain only relevant bits
186        int headsetState = newState & SUPPORTED_HEADSETS;
187        int usb_headset_anlg = headsetState & BIT_USB_HEADSET_ANLG;
188        int usb_headset_dgtl = headsetState & BIT_USB_HEADSET_DGTL;
189        int h2w_headset = headsetState & (BIT_HEADSET | BIT_HEADSET_NO_MIC | BIT_LINEOUT);
190        boolean h2wStateChange = true;
191        boolean usbStateChange = true;
192        if (LOG) Slog.v(TAG, "newName=" + newName
193                + " newState=" + newState
194                + " headsetState=" + headsetState
195                + " prev headsetState=" + mHeadsetState);
196
197        if (mHeadsetState == headsetState) {
198            Log.e(TAG, "No state change.");
199            return;
200        }
201
202        // reject all suspect transitions: only accept state changes from:
203        // - a: 0 headset to 1 headset
204        // - b: 1 headset to 0 headset
205        if (h2w_headset == (BIT_HEADSET | BIT_HEADSET_NO_MIC | BIT_LINEOUT)) {
206            Log.e(TAG, "Invalid combination, unsetting h2w flag");
207            h2wStateChange = false;
208        }
209        // - c: 0 usb headset to 1 usb headset
210        // - d: 1 usb headset to 0 usb headset
211        if (usb_headset_anlg == BIT_USB_HEADSET_ANLG && usb_headset_dgtl == BIT_USB_HEADSET_DGTL) {
212            Log.e(TAG, "Invalid combination, unsetting usb flag");
213            usbStateChange = false;
214        }
215        if (!h2wStateChange && !usbStateChange) {
216            Log.e(TAG, "invalid transition, returning ...");
217            return;
218        }
219
220        mWakeLock.acquire();
221
222        Message msg = mHandler.obtainMessage(MSG_NEW_DEVICE_STATE, headsetState,
223                mHeadsetState, newName);
224        mHandler.sendMessage(msg);
225
226        mHeadsetState = headsetState;
227    }
228
229    private final Handler mHandler = new Handler(Looper.myLooper(), null, true) {
230        @Override
231        public void handleMessage(Message msg) {
232            switch (msg.what) {
233                case MSG_NEW_DEVICE_STATE:
234                    setDevicesState(msg.arg1, msg.arg2, (String)msg.obj);
235                    mWakeLock.release();
236                    break;
237                case MSG_SYSTEM_READY:
238                    onSystemReady();
239                    mWakeLock.release();
240                    break;
241            }
242        }
243    };
244
245    private void setDevicesState(
246            int headsetState, int prevHeadsetState, String headsetName) {
247        synchronized (mLock) {
248            int allHeadsets = SUPPORTED_HEADSETS;
249            for (int curHeadset = 1; allHeadsets != 0; curHeadset <<= 1) {
250                if ((curHeadset & allHeadsets) != 0) {
251                    setDeviceStateLocked(curHeadset, headsetState, prevHeadsetState, headsetName);
252                    allHeadsets &= ~curHeadset;
253                }
254            }
255        }
256    }
257
258    private void setDeviceStateLocked(int headset,
259            int headsetState, int prevHeadsetState, String headsetName) {
260        if ((headsetState & headset) != (prevHeadsetState & headset)) {
261            int outDevice = 0;
262            int inDevice = 0;
263            int state;
264
265            if ((headsetState & headset) != 0) {
266                state = 1;
267            } else {
268                state = 0;
269            }
270
271            if (headset == BIT_HEADSET) {
272                outDevice = AudioManager.DEVICE_OUT_WIRED_HEADSET;
273                inDevice = AudioManager.DEVICE_IN_WIRED_HEADSET;
274            } else if (headset == BIT_HEADSET_NO_MIC){
275                outDevice = AudioManager.DEVICE_OUT_WIRED_HEADPHONE;
276            } else if (headset == BIT_LINEOUT){
277                outDevice = AudioManager.DEVICE_OUT_LINE;
278            } else if (headset == BIT_USB_HEADSET_ANLG) {
279                outDevice = AudioManager.DEVICE_OUT_ANLG_DOCK_HEADSET;
280            } else if (headset == BIT_USB_HEADSET_DGTL) {
281                outDevice = AudioManager.DEVICE_OUT_DGTL_DOCK_HEADSET;
282            } else if (headset == BIT_HDMI_AUDIO) {
283                outDevice = AudioManager.DEVICE_OUT_HDMI;
284            } else {
285                Slog.e(TAG, "setDeviceState() invalid headset type: "+headset);
286                return;
287            }
288
289            if (LOG)
290                Slog.v(TAG, "device "+headsetName+((state == 1) ? " connected" : " disconnected"));
291
292            if (outDevice != 0) {
293              mAudioManager.setWiredDeviceConnectionState(outDevice, state, headsetName);
294            }
295            if (inDevice != 0) {
296              mAudioManager.setWiredDeviceConnectionState(inDevice, state, headsetName);
297            }
298        }
299    }
300
301    private String switchCodeToString(int switchValues, int switchMask) {
302        StringBuffer sb = new StringBuffer();
303        if ((switchMask & SW_HEADPHONE_INSERT_BIT) != 0 &&
304                (switchValues & SW_HEADPHONE_INSERT_BIT) != 0) {
305            sb.append("SW_HEADPHONE_INSERT ");
306        }
307        if ((switchMask & SW_MICROPHONE_INSERT_BIT) != 0 &&
308                (switchValues & SW_MICROPHONE_INSERT_BIT) != 0) {
309            sb.append("SW_MICROPHONE_INSERT");
310        }
311        return sb.toString();
312    }
313
314    class WiredAccessoryObserver extends UEventObserver {
315        private final List<UEventInfo> mUEventInfo;
316
317        public WiredAccessoryObserver() {
318            mUEventInfo = makeObservedUEventList();
319        }
320
321        void init() {
322            synchronized (mLock) {
323                if (LOG) Slog.v(TAG, "init()");
324                char[] buffer = new char[1024];
325
326                for (int i = 0; i < mUEventInfo.size(); ++i) {
327                    UEventInfo uei = mUEventInfo.get(i);
328                    try {
329                        int curState;
330                        FileReader file = new FileReader(uei.getSwitchStatePath());
331                        int len = file.read(buffer, 0, 1024);
332                        file.close();
333                        curState = Integer.valueOf((new String(buffer, 0, len)).trim());
334
335                        if (curState > 0) {
336                            updateStateLocked(uei.getDevPath(), uei.getDevName(), curState);
337                        }
338                    } catch (FileNotFoundException e) {
339                        Slog.w(TAG, uei.getSwitchStatePath() +
340                                " not found while attempting to determine initial switch state");
341                    } catch (Exception e) {
342                        Slog.e(TAG, "" , e);
343                    }
344                }
345            }
346
347            // At any given time accessories could be inserted
348            // one on the board, one on the dock and one on HDMI:
349            // observe three UEVENTs
350            for (int i = 0; i < mUEventInfo.size(); ++i) {
351                UEventInfo uei = mUEventInfo.get(i);
352                startObserving("DEVPATH="+uei.getDevPath());
353            }
354        }
355
356        private List<UEventInfo> makeObservedUEventList() {
357            List<UEventInfo> retVal = new ArrayList<UEventInfo>();
358            UEventInfo uei;
359
360            // Monitor h2w
361            if (!mUseDevInputEventForAudioJack) {
362                uei = new UEventInfo(NAME_H2W, BIT_HEADSET, BIT_HEADSET_NO_MIC, BIT_LINEOUT);
363                if (uei.checkSwitchExists()) {
364                    retVal.add(uei);
365                } else {
366                    Slog.w(TAG, "This kernel does not have wired headset support");
367                }
368            }
369
370            // Monitor USB
371            uei = new UEventInfo(NAME_USB_AUDIO, BIT_USB_HEADSET_ANLG, BIT_USB_HEADSET_DGTL, 0);
372            if (uei.checkSwitchExists()) {
373                retVal.add(uei);
374            } else {
375                Slog.w(TAG, "This kernel does not have usb audio support");
376            }
377
378            // Monitor HDMI
379            //
380            // If the kernel has support for the "hdmi_audio" switch, use that.  It will be
381            // signalled only when the HDMI driver has a video mode configured, and the downstream
382            // sink indicates support for audio in its EDID.
383            //
384            // If the kernel does not have an "hdmi_audio" switch, just fall back on the older
385            // "hdmi" switch instead.
386            uei = new UEventInfo(NAME_HDMI_AUDIO, BIT_HDMI_AUDIO, 0, 0);
387            if (uei.checkSwitchExists()) {
388                retVal.add(uei);
389            } else {
390                uei = new UEventInfo(NAME_HDMI, BIT_HDMI_AUDIO, 0, 0);
391                if (uei.checkSwitchExists()) {
392                    retVal.add(uei);
393                } else {
394                    Slog.w(TAG, "This kernel does not have HDMI audio support");
395                }
396            }
397
398            return retVal;
399        }
400
401        @Override
402        public void onUEvent(UEventObserver.UEvent event) {
403            if (LOG) Slog.v(TAG, "Headset UEVENT: " + event.toString());
404
405            try {
406                String devPath = event.get("DEVPATH");
407                String name = event.get("SWITCH_NAME");
408                int state = Integer.parseInt(event.get("SWITCH_STATE"));
409                synchronized (mLock) {
410                    updateStateLocked(devPath, name, state);
411                }
412            } catch (NumberFormatException e) {
413                Slog.e(TAG, "Could not parse switch state from event " + event);
414            }
415        }
416
417        private void updateStateLocked(String devPath, String name, int state) {
418            for (int i = 0; i < mUEventInfo.size(); ++i) {
419                UEventInfo uei = mUEventInfo.get(i);
420                if (devPath.equals(uei.getDevPath())) {
421                    updateLocked(name, uei.computeNewHeadsetState(mHeadsetState, state));
422                    return;
423                }
424            }
425        }
426
427        private final class UEventInfo {
428            private final String mDevName;
429            private final int mState1Bits;
430            private final int mState2Bits;
431            private final int mStateNbits;
432
433            public UEventInfo(String devName, int state1Bits, int state2Bits, int stateNbits) {
434                mDevName = devName;
435                mState1Bits = state1Bits;
436                mState2Bits = state2Bits;
437                mStateNbits = stateNbits;
438            }
439
440            public String getDevName() { return mDevName; }
441
442            public String getDevPath() {
443                return String.format(Locale.US, "/devices/virtual/switch/%s", mDevName);
444            }
445
446            public String getSwitchStatePath() {
447                return String.format(Locale.US, "/sys/class/switch/%s/state", mDevName);
448            }
449
450            public boolean checkSwitchExists() {
451                File f = new File(getSwitchStatePath());
452                return f.exists();
453            }
454
455            public int computeNewHeadsetState(int headsetState, int switchState) {
456                int preserveMask = ~(mState1Bits | mState2Bits | mStateNbits);
457                int setBits = ((switchState == 1) ? mState1Bits :
458                              ((switchState == 2) ? mState2Bits :
459                              ((switchState == mStateNbits) ? mStateNbits : 0)));
460
461                return ((headsetState & preserveMask) | setBits);
462            }
463        }
464    }
465}
466