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