HdmiControlService.java revision f17024873b10dabed069e502030dd85d6257c0c4
1/*
2 * Copyright (C) 2014 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.hdmi;
18
19import static android.hardware.hdmi.HdmiControlManager.DEVICE_EVENT_ADD_DEVICE;
20import static android.hardware.hdmi.HdmiControlManager.DEVICE_EVENT_REMOVE_DEVICE;
21import static com.android.server.hdmi.Constants.DISABLED;
22import static com.android.server.hdmi.Constants.ENABLED;
23import static com.android.server.hdmi.Constants.OPTION_CEC_AUTO_WAKEUP;
24import static com.android.server.hdmi.Constants.OPTION_CEC_ENABLE;
25import static com.android.server.hdmi.Constants.OPTION_CEC_SERVICE_CONTROL;
26import static com.android.server.hdmi.Constants.OPTION_MHL_ENABLE;
27import static com.android.server.hdmi.Constants.OPTION_MHL_INPUT_SWITCHING;
28import static com.android.server.hdmi.Constants.OPTION_MHL_POWER_CHARGE;
29
30import android.annotation.Nullable;
31import android.content.BroadcastReceiver;
32import android.content.ContentResolver;
33import android.content.Context;
34import android.content.Intent;
35import android.content.IntentFilter;
36import android.database.ContentObserver;
37import android.hardware.hdmi.HdmiControlManager;
38import android.hardware.hdmi.HdmiDeviceInfo;
39import android.hardware.hdmi.HdmiHotplugEvent;
40import android.hardware.hdmi.HdmiPortInfo;
41import android.hardware.hdmi.IHdmiControlCallback;
42import android.hardware.hdmi.IHdmiControlService;
43import android.hardware.hdmi.IHdmiDeviceEventListener;
44import android.hardware.hdmi.IHdmiHotplugEventListener;
45import android.hardware.hdmi.IHdmiInputChangeListener;
46import android.hardware.hdmi.IHdmiMhlVendorCommandListener;
47import android.hardware.hdmi.IHdmiRecordListener;
48import android.hardware.hdmi.IHdmiSystemAudioModeChangeListener;
49import android.hardware.hdmi.IHdmiVendorCommandListener;
50import android.media.AudioManager;
51import android.media.tv.TvInputManager;
52import android.media.tv.TvInputManager.TvInputCallback;
53import android.net.Uri;
54import android.os.Build;
55import android.os.Handler;
56import android.os.HandlerThread;
57import android.os.IBinder;
58import android.os.Looper;
59import android.os.PowerManager;
60import android.os.RemoteException;
61import android.os.SystemClock;
62import android.os.SystemProperties;
63import android.os.UserHandle;
64import android.provider.Settings.Global;
65import android.text.TextUtils;
66import android.util.ArraySet;
67import android.util.Slog;
68import android.util.SparseArray;
69import android.util.SparseIntArray;
70
71import com.android.internal.annotations.GuardedBy;
72import com.android.internal.util.IndentingPrintWriter;
73import com.android.server.SystemService;
74import com.android.server.hdmi.HdmiAnnotations.ServiceThreadOnly;
75import com.android.server.hdmi.HdmiCecController.AllocateAddressCallback;
76import com.android.server.hdmi.HdmiCecLocalDevice.ActiveSource;
77import com.android.server.hdmi.HdmiCecLocalDevice.PendingActionClearedCallback;
78
79import libcore.util.EmptyArray;
80
81import java.io.FileDescriptor;
82import java.io.PrintWriter;
83import java.util.ArrayList;
84import java.util.Arrays;
85import java.util.Collections;
86import java.util.List;
87import java.util.Locale;
88
89/**
90 * Provides a service for sending and processing HDMI control messages,
91 * HDMI-CEC and MHL control command, and providing the information on both standard.
92 */
93public final class HdmiControlService extends SystemService {
94    private static final String TAG = "HdmiControlService";
95    private final Locale HONG_KONG = new Locale("zh", "HK");
96    private final Locale MACAU = new Locale("zh", "MO");
97
98    static final String PERMISSION = "android.permission.HDMI_CEC";
99
100    // The reason code to initiate intializeCec().
101    static final int INITIATED_BY_ENABLE_CEC = 0;
102    static final int INITIATED_BY_BOOT_UP = 1;
103    static final int INITIATED_BY_SCREEN_ON = 2;
104    static final int INITIATED_BY_WAKE_UP_MESSAGE = 3;
105    static final int INITIATED_BY_HOTPLUG = 4;
106
107    /**
108     * Interface to report send result.
109     */
110    interface SendMessageCallback {
111        /**
112         * Called when {@link HdmiControlService#sendCecCommand} is completed.
113         *
114         * @param error result of send request.
115         * <ul>
116         * <li>{@link Constants#SEND_RESULT_SUCCESS}
117         * <li>{@link Constants#SEND_RESULT_NAK}
118         * <li>{@link Constants#SEND_RESULT_FAILURE}
119         * </ul>
120         */
121        void onSendCompleted(int error);
122    }
123
124    /**
125     * Interface to get a list of available logical devices.
126     */
127    interface DevicePollingCallback {
128        /**
129         * Called when device polling is finished.
130         *
131         * @param ackedAddress a list of logical addresses of available devices
132         */
133        void onPollingFinished(List<Integer> ackedAddress);
134    }
135
136    private class HdmiControlBroadcastReceiver extends BroadcastReceiver {
137        @ServiceThreadOnly
138        @Override
139        public void onReceive(Context context, Intent intent) {
140            assertRunOnServiceThread();
141            switch (intent.getAction()) {
142                case Intent.ACTION_SCREEN_OFF:
143                    if (isPowerOnOrTransient()) {
144                        onStandby();
145                    }
146                    break;
147                case Intent.ACTION_SCREEN_ON:
148                    if (isPowerStandbyOrTransient()) {
149                        onWakeUp();
150                    }
151                    break;
152                case Intent.ACTION_CONFIGURATION_CHANGED:
153                    String language = getMenuLanguage();
154                    if (!mLanguage.equals(language)) {
155                        onLanguageChanged(language);
156                    }
157                    break;
158            }
159        }
160
161        private String getMenuLanguage() {
162            Locale locale = Locale.getDefault();
163            if (locale.equals(Locale.TAIWAN) || locale.equals(HONG_KONG) || locale.equals(MACAU)) {
164                // Android always returns "zho" for all Chinese variants.
165                // Use "bibliographic" code defined in CEC639-2 for traditional
166                // Chinese used in Taiwan/Hong Kong/Macau.
167                return "chi";
168            } else {
169                return locale.getISO3Language();
170            }
171        }
172    }
173
174    // A thread to handle synchronous IO of CEC and MHL control service.
175    // Since all of CEC and MHL HAL interfaces processed in short time (< 200ms)
176    // and sparse call it shares a thread to handle IO operations.
177    private final HandlerThread mIoThread = new HandlerThread("Hdmi Control Io Thread");
178
179    // Used to synchronize the access to the service.
180    private final Object mLock = new Object();
181
182    // Type of logical devices hosted in the system. Stored in the unmodifiable list.
183    private final List<Integer> mLocalDevices;
184
185    // List of records for hotplug event listener to handle the the caller killed in action.
186    @GuardedBy("mLock")
187    private final ArrayList<HotplugEventListenerRecord> mHotplugEventListenerRecords =
188            new ArrayList<>();
189
190    // List of records for device event listener to handle the caller killed in action.
191    @GuardedBy("mLock")
192    private final ArrayList<DeviceEventListenerRecord> mDeviceEventListenerRecords =
193            new ArrayList<>();
194
195    // List of records for vendor command listener to handle the caller killed in action.
196    @GuardedBy("mLock")
197    private final ArrayList<VendorCommandListenerRecord> mVendorCommandListenerRecords =
198            new ArrayList<>();
199
200    @GuardedBy("mLock")
201    private InputChangeListenerRecord mInputChangeListenerRecord;
202
203    @GuardedBy("mLock")
204    private HdmiRecordListenerRecord mRecordListenerRecord;
205
206    // Set to true while HDMI control is enabled. If set to false, HDMI-CEC/MHL protocol
207    // handling will be disabled and no request will be handled.
208    @GuardedBy("mLock")
209    private boolean mHdmiControlEnabled;
210
211    // Set to true while the service is in normal mode. While set to false, no input change is
212    // allowed. Used for situations where input change can confuse users such as channel auto-scan,
213    // system upgrade, etc., a.k.a. "prohibit mode".
214    @GuardedBy("mLock")
215    private boolean mProhibitMode;
216
217    // List of records for system audio mode change to handle the the caller killed in action.
218    private final ArrayList<SystemAudioModeChangeListenerRecord>
219            mSystemAudioModeChangeListenerRecords = new ArrayList<>();
220
221    // Handler used to run a task in service thread.
222    private final Handler mHandler = new Handler();
223
224    private final SettingsObserver mSettingsObserver;
225
226    private final HdmiControlBroadcastReceiver
227            mHdmiControlBroadcastReceiver = new HdmiControlBroadcastReceiver();
228
229    @Nullable
230    private HdmiCecController mCecController;
231
232    // HDMI port information. Stored in the unmodifiable list to keep the static information
233    // from being modified.
234    private List<HdmiPortInfo> mPortInfo;
235
236    // Map from path(physical address) to port ID.
237    private UnmodifiableSparseIntArray mPortIdMap;
238
239    // Map from port ID to HdmiPortInfo.
240    private UnmodifiableSparseArray<HdmiPortInfo> mPortInfoMap;
241
242    // Map from port ID to HdmiDeviceInfo.
243    private UnmodifiableSparseArray<HdmiDeviceInfo> mPortDeviceMap;
244
245    private HdmiCecMessageValidator mMessageValidator;
246
247    @ServiceThreadOnly
248    private int mPowerStatus = HdmiControlManager.POWER_STATUS_STANDBY;
249
250    @ServiceThreadOnly
251    private String mLanguage = Locale.getDefault().getISO3Language();
252
253    @ServiceThreadOnly
254    private boolean mStandbyMessageReceived = false;
255
256    @ServiceThreadOnly
257    private boolean mWakeUpMessageReceived = false;
258
259    @ServiceThreadOnly
260    private int mActivePortId = Constants.INVALID_PORT_ID;
261
262    // Set to true while the input change by MHL is allowed.
263    @GuardedBy("mLock")
264    private boolean mMhlInputChangeEnabled;
265
266    // List of records for MHL Vendor command listener to handle the caller killed in action.
267    @GuardedBy("mLock")
268    private final ArrayList<HdmiMhlVendorCommandListenerRecord>
269            mMhlVendorCommandListenerRecords = new ArrayList<>();
270
271    @GuardedBy("mLock")
272    private List<HdmiDeviceInfo> mMhlDevices;
273
274    @Nullable
275    private HdmiMhlControllerStub mMhlController;
276
277    @Nullable
278    private TvInputManager mTvInputManager;
279
280    // Last input port before switching to the MHL port. Should switch back to this port
281    // when the mobile device sends the request one touch play with off.
282    // Gets invalidated if we go to other port/input.
283    @ServiceThreadOnly
284    private int mLastInputMhl = Constants.INVALID_PORT_ID;
285
286    public HdmiControlService(Context context) {
287        super(context);
288        mLocalDevices = getIntList(SystemProperties.get(Constants.PROPERTY_DEVICE_TYPE));
289        mSettingsObserver = new SettingsObserver(mHandler);
290    }
291
292    private static List<Integer> getIntList(String string) {
293        ArrayList<Integer> list = new ArrayList<>();
294        TextUtils.SimpleStringSplitter splitter = new TextUtils.SimpleStringSplitter(',');
295        splitter.setString(string);
296        for (String item : splitter) {
297            try {
298                list.add(Integer.parseInt(item));
299            } catch (NumberFormatException e) {
300                Slog.w(TAG, "Can't parseInt: " + item);
301            }
302        }
303        return Collections.unmodifiableList(list);
304    }
305
306    @Override
307    public void onStart() {
308        mIoThread.start();
309        mPowerStatus = HdmiControlManager.POWER_STATUS_TRANSIENT_TO_ON;
310        mProhibitMode = false;
311        mHdmiControlEnabled = readBooleanSetting(Global.HDMI_CONTROL_ENABLED, true);
312        mMhlInputChangeEnabled = readBooleanSetting(Global.MHL_INPUT_SWITCHING_ENABLED, true);
313
314        mCecController = HdmiCecController.create(this);
315        if (mCecController != null) {
316            // TODO: Remove this as soon as OEM's HAL implementation is corrected.
317            mCecController.setOption(OPTION_CEC_ENABLE, ENABLED);
318
319            // TODO: load value for mHdmiControlEnabled from preference.
320            if (mHdmiControlEnabled) {
321                initializeCec(INITIATED_BY_BOOT_UP);
322            }
323        } else {
324            Slog.i(TAG, "Device does not support HDMI-CEC.");
325            return;
326        }
327
328        mMhlController = HdmiMhlControllerStub.create(this);
329        if (!mMhlController.isReady()) {
330            Slog.i(TAG, "Device does not support MHL-control.");
331        }
332        mMhlDevices = Collections.emptyList();
333
334        initPortInfo();
335        mMessageValidator = new HdmiCecMessageValidator(this);
336        publishBinderService(Context.HDMI_CONTROL_SERVICE, new BinderService());
337
338        if (mCecController != null) {
339            // Register broadcast receiver for power state change.
340            IntentFilter filter = new IntentFilter();
341            filter.addAction(Intent.ACTION_SCREEN_OFF);
342            filter.addAction(Intent.ACTION_SCREEN_ON);
343            filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
344            getContext().registerReceiver(mHdmiControlBroadcastReceiver, filter);
345
346            // Register ContentObserver to monitor the settings change.
347            registerContentObserver();
348        }
349    }
350
351    @Override
352    public void onBootPhase(int phase) {
353        if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY) {
354            mTvInputManager = (TvInputManager) getContext().getSystemService(
355                    Context.TV_INPUT_SERVICE);
356        }
357    }
358
359    TvInputManager getTvInputManager() {
360        return mTvInputManager;
361    }
362
363    void registerTvInputCallback(TvInputCallback callback) {
364        if (mTvInputManager == null) return;
365        mTvInputManager.registerCallback(callback, mHandler);
366    }
367
368    void unregisterTvInputCallback(TvInputCallback callback) {
369        if (mTvInputManager == null) return;
370        mTvInputManager.unregisterCallback(callback);
371    }
372
373    /**
374     * Called when the initialization of local devices is complete.
375     */
376    private void onInitializeCecComplete(int initiatedBy) {
377        if (mPowerStatus == HdmiControlManager.POWER_STATUS_TRANSIENT_TO_ON) {
378            mPowerStatus = HdmiControlManager.POWER_STATUS_ON;
379        }
380        mWakeUpMessageReceived = false;
381
382        if (isTvDevice()) {
383            mCecController.setOption(OPTION_CEC_AUTO_WAKEUP, toInt(tv().getAutoWakeup()));
384        }
385        int reason = -1;
386        switch (initiatedBy) {
387            case INITIATED_BY_BOOT_UP:
388                reason = HdmiControlManager.CONTROL_STATE_CHANGED_REASON_START;
389                break;
390            case INITIATED_BY_ENABLE_CEC:
391                reason = HdmiControlManager.CONTROL_STATE_CHANGED_REASON_SETTING;
392                break;
393            case INITIATED_BY_SCREEN_ON:
394            case INITIATED_BY_WAKE_UP_MESSAGE:
395                reason = HdmiControlManager.CONTROL_STATE_CHANGED_REASON_WAKEUP;
396                break;
397        }
398        if (reason != -1) {
399            invokeVendorCommandListenersOnControlStateChanged(true, reason);
400        }
401    }
402
403    private void registerContentObserver() {
404        ContentResolver resolver = getContext().getContentResolver();
405        String[] settings = new String[] {
406                Global.HDMI_CONTROL_ENABLED,
407                Global.HDMI_CONTROL_AUTO_WAKEUP_ENABLED,
408                Global.HDMI_CONTROL_AUTO_DEVICE_OFF_ENABLED,
409                Global.MHL_INPUT_SWITCHING_ENABLED,
410                Global.MHL_POWER_CHARGE_ENABLED
411        };
412        for (String s : settings) {
413            resolver.registerContentObserver(Global.getUriFor(s), false, mSettingsObserver,
414                    UserHandle.USER_ALL);
415        }
416    }
417
418    private class SettingsObserver extends ContentObserver {
419        public SettingsObserver(Handler handler) {
420            super(handler);
421        }
422
423        // onChange is set up to run in service thread.
424        @Override
425        public void onChange(boolean selfChange, Uri uri) {
426            String option = uri.getLastPathSegment();
427            boolean enabled = readBooleanSetting(option, true);
428            switch (option) {
429                case Global.HDMI_CONTROL_ENABLED:
430                    setControlEnabled(enabled);
431                    break;
432                case Global.HDMI_CONTROL_AUTO_WAKEUP_ENABLED:
433                    tv().setAutoWakeup(enabled);
434                    setCecOption(OPTION_CEC_AUTO_WAKEUP, toInt(enabled));
435                    break;
436                case Global.HDMI_CONTROL_AUTO_DEVICE_OFF_ENABLED:
437                    tv().setAutoDeviceOff(enabled);
438                    // No need to propagate to HAL.
439                    break;
440                case Global.MHL_INPUT_SWITCHING_ENABLED:
441                    setMhlInputChangeEnabled(enabled);
442                    break;
443                case Global.MHL_POWER_CHARGE_ENABLED:
444                    mMhlController.setOption(OPTION_MHL_POWER_CHARGE, toInt(enabled));
445                    break;
446            }
447        }
448    }
449
450    private static int toInt(boolean enabled) {
451        return enabled ? ENABLED : DISABLED;
452    }
453
454    boolean readBooleanSetting(String key, boolean defVal) {
455        ContentResolver cr = getContext().getContentResolver();
456        return Global.getInt(cr, key, toInt(defVal)) == ENABLED;
457    }
458
459    void writeBooleanSetting(String key, boolean value) {
460        ContentResolver cr = getContext().getContentResolver();
461        Global.putInt(cr, key, toInt(value));
462    }
463
464    private void initializeCec(int initiatedBy) {
465        mCecController.setOption(OPTION_CEC_SERVICE_CONTROL, ENABLED);
466        initializeLocalDevices(initiatedBy);
467    }
468
469    @ServiceThreadOnly
470    private void initializeLocalDevices(final int initiatedBy) {
471        assertRunOnServiceThread();
472        // A container for [Device type, Local device info].
473        ArrayList<HdmiCecLocalDevice> localDevices = new ArrayList<>();
474        for (int type : mLocalDevices) {
475            HdmiCecLocalDevice localDevice = mCecController.getLocalDevice(type);
476            if (localDevice == null) {
477                localDevice = HdmiCecLocalDevice.create(this, type);
478            }
479            localDevice.init();
480            localDevices.add(localDevice);
481        }
482        // It's now safe to flush existing local devices from mCecController since they were
483        // already moved to 'localDevices'.
484        clearLocalDevices();
485        allocateLogicalAddress(localDevices, initiatedBy);
486    }
487
488    @ServiceThreadOnly
489    private void allocateLogicalAddress(final ArrayList<HdmiCecLocalDevice> allocatingDevices,
490            final int initiatedBy) {
491        assertRunOnServiceThread();
492        mCecController.clearLogicalAddress();
493        final ArrayList<HdmiCecLocalDevice> allocatedDevices = new ArrayList<>();
494        final int[] finished = new int[1];
495        for (final HdmiCecLocalDevice localDevice : allocatingDevices) {
496            mCecController.allocateLogicalAddress(localDevice.getType(),
497                    localDevice.getPreferredAddress(), new AllocateAddressCallback() {
498                @Override
499                public void onAllocated(int deviceType, int logicalAddress) {
500                    if (logicalAddress == Constants.ADDR_UNREGISTERED) {
501                        Slog.e(TAG, "Failed to allocate address:[device_type:" + deviceType + "]");
502                    } else {
503                        // Set POWER_STATUS_ON to all local devices because they share lifetime
504                        // with system.
505                        HdmiDeviceInfo deviceInfo = createDeviceInfo(logicalAddress, deviceType,
506                                HdmiControlManager.POWER_STATUS_ON);
507                        localDevice.setDeviceInfo(deviceInfo);
508                        mCecController.addLocalDevice(deviceType, localDevice);
509                        mCecController.addLogicalAddress(logicalAddress);
510                        allocatedDevices.add(localDevice);
511                    }
512
513                    // Address allocation completed for all devices. Notify each device.
514                    if (allocatingDevices.size() == ++finished[0]) {
515                        if (initiatedBy != INITIATED_BY_HOTPLUG) {
516                            // In case of the hotplug we don't call onInitializeCecComplete()
517                            // since we reallocate the logical address only.
518                            onInitializeCecComplete(initiatedBy);
519                        }
520                        notifyAddressAllocated(allocatedDevices, initiatedBy);
521                    }
522                }
523            });
524        }
525    }
526
527    @ServiceThreadOnly
528    private void notifyAddressAllocated(ArrayList<HdmiCecLocalDevice> devices, int initiatedBy) {
529        assertRunOnServiceThread();
530        for (HdmiCecLocalDevice device : devices) {
531            int address = device.getDeviceInfo().getLogicalAddress();
532            device.handleAddressAllocated(address, initiatedBy);
533        }
534    }
535
536    // Initialize HDMI port information. Combine the information from CEC and MHL HAL and
537    // keep them in one place.
538    @ServiceThreadOnly
539    private void initPortInfo() {
540        assertRunOnServiceThread();
541        HdmiPortInfo[] cecPortInfo = null;
542
543        // CEC HAL provides majority of the info while MHL does only MHL support flag for
544        // each port. Return empty array if CEC HAL didn't provide the info.
545        if (mCecController != null) {
546            cecPortInfo = mCecController.getPortInfos();
547        }
548        if (cecPortInfo == null) {
549            return;
550        }
551
552        SparseArray<HdmiPortInfo> portInfoMap = new SparseArray<>();
553        SparseIntArray portIdMap = new SparseIntArray();
554        SparseArray<HdmiDeviceInfo> portDeviceMap = new SparseArray<>();
555        for (HdmiPortInfo info : cecPortInfo) {
556            portIdMap.put(info.getAddress(), info.getId());
557            portInfoMap.put(info.getId(), info);
558            portDeviceMap.put(info.getId(), new HdmiDeviceInfo(info.getAddress(), info.getId()));
559        }
560        mPortIdMap = new UnmodifiableSparseIntArray(portIdMap);
561        mPortInfoMap = new UnmodifiableSparseArray<>(portInfoMap);
562        mPortDeviceMap = new UnmodifiableSparseArray<>(portDeviceMap);
563
564        HdmiPortInfo[] mhlPortInfo = mMhlController.getPortInfos();
565        ArraySet<Integer> mhlSupportedPorts = new ArraySet<Integer>(mhlPortInfo.length);
566        for (HdmiPortInfo info : mhlPortInfo) {
567            if (info.isMhlSupported()) {
568                mhlSupportedPorts.add(info.getId());
569            }
570        }
571
572        // Build HDMI port info list with CEC port info plus MHL supported flag. We can just use
573        // cec port info if we do not have have port that supports MHL.
574        if (mhlSupportedPorts.isEmpty()) {
575            mPortInfo = Collections.unmodifiableList(Arrays.asList(cecPortInfo));
576            return;
577        }
578        ArrayList<HdmiPortInfo> result = new ArrayList<>(cecPortInfo.length);
579        for (HdmiPortInfo info : cecPortInfo) {
580            if (mhlSupportedPorts.contains(info.getId())) {
581                result.add(new HdmiPortInfo(info.getId(), info.getType(), info.getAddress(),
582                        info.isCecSupported(), true, info.isArcSupported()));
583            } else {
584                result.add(info);
585            }
586        }
587        mPortInfo = Collections.unmodifiableList(result);
588    }
589
590    List<HdmiPortInfo> getPortInfo() {
591        return mPortInfo;
592    }
593
594    /**
595     * Returns HDMI port information for the given port id.
596     *
597     * @param portId HDMI port id
598     * @return {@link HdmiPortInfo} for the given port
599     */
600    HdmiPortInfo getPortInfo(int portId) {
601        return mPortInfoMap.get(portId, null);
602    }
603
604    /**
605     * Returns the routing path (physical address) of the HDMI port for the given
606     * port id.
607     */
608    int portIdToPath(int portId) {
609        HdmiPortInfo portInfo = getPortInfo(portId);
610        if (portInfo == null) {
611            Slog.e(TAG, "Cannot find the port info: " + portId);
612            return Constants.INVALID_PHYSICAL_ADDRESS;
613        }
614        return portInfo.getAddress();
615    }
616
617    /**
618     * Returns the id of HDMI port located at the top of the hierarchy of
619     * the specified routing path. For the routing path 0x1220 (1.2.2.0), for instance,
620     * the port id to be returned is the ID associated with the port address
621     * 0x1000 (1.0.0.0) which is the topmost path of the given routing path.
622     */
623    int pathToPortId(int path) {
624        int portAddress = path & Constants.ROUTING_PATH_TOP_MASK;
625        return mPortIdMap.get(portAddress, Constants.INVALID_PORT_ID);
626    }
627
628    boolean isValidPortId(int portId) {
629        return getPortInfo(portId) != null;
630    }
631
632    /**
633     * Returns {@link Looper} for IO operation.
634     *
635     * <p>Declared as package-private.
636     */
637    Looper getIoLooper() {
638        return mIoThread.getLooper();
639    }
640
641    /**
642     * Returns {@link Looper} of main thread. Use this {@link Looper} instance
643     * for tasks that are running on main service thread.
644     *
645     * <p>Declared as package-private.
646     */
647    Looper getServiceLooper() {
648        return mHandler.getLooper();
649    }
650
651    /**
652     * Returns physical address of the device.
653     */
654    int getPhysicalAddress() {
655        return mCecController.getPhysicalAddress();
656    }
657
658    /**
659     * Returns vendor id of CEC service.
660     */
661    int getVendorId() {
662        return mCecController.getVendorId();
663    }
664
665    @ServiceThreadOnly
666    HdmiDeviceInfo getDeviceInfo(int logicalAddress) {
667        assertRunOnServiceThread();
668        HdmiCecLocalDeviceTv tv = tv();
669        if (tv == null) {
670            return null;
671        }
672        return tv.getCecDeviceInfo(logicalAddress);
673    }
674
675    /**
676     * Returns version of CEC.
677     */
678    int getCecVersion() {
679        return mCecController.getVersion();
680    }
681
682    /**
683     * Whether a device of the specified physical address is connected to ARC enabled port.
684     */
685    boolean isConnectedToArcPort(int physicalAddress) {
686        int portId = pathToPortId(physicalAddress);
687        if (portId != Constants.INVALID_PORT_ID) {
688            return mPortInfoMap.get(portId).isArcSupported();
689        }
690        return false;
691    }
692
693    void runOnServiceThread(Runnable runnable) {
694        mHandler.post(runnable);
695    }
696
697    void runOnServiceThreadAtFrontOfQueue(Runnable runnable) {
698        mHandler.postAtFrontOfQueue(runnable);
699    }
700
701    private void assertRunOnServiceThread() {
702        if (Looper.myLooper() != mHandler.getLooper()) {
703            throw new IllegalStateException("Should run on service thread.");
704        }
705    }
706
707    /**
708     * Transmit a CEC command to CEC bus.
709     *
710     * @param command CEC command to send out
711     * @param callback interface used to the result of send command
712     */
713    @ServiceThreadOnly
714    void sendCecCommand(HdmiCecMessage command, @Nullable SendMessageCallback callback) {
715        assertRunOnServiceThread();
716        if (mMessageValidator.isValid(command) == HdmiCecMessageValidator.OK) {
717            mCecController.sendCommand(command, callback);
718        } else {
719            HdmiLogger.error("Invalid message type:" + command);
720            if (callback != null) {
721                callback.onSendCompleted(Constants.SEND_RESULT_FAILURE);
722            }
723        }
724    }
725
726    @ServiceThreadOnly
727    void sendCecCommand(HdmiCecMessage command) {
728        assertRunOnServiceThread();
729        sendCecCommand(command, null);
730    }
731
732    /**
733     * Send <Feature Abort> command on the given CEC message if possible.
734     * If the aborted message is invalid, then it wont send the message.
735     * @param command original command to be aborted
736     * @param reason reason of feature abort
737     */
738    @ServiceThreadOnly
739    void maySendFeatureAbortCommand(HdmiCecMessage command, int reason) {
740        assertRunOnServiceThread();
741        mCecController.maySendFeatureAbortCommand(command, reason);
742    }
743
744    @ServiceThreadOnly
745    boolean handleCecCommand(HdmiCecMessage message) {
746        assertRunOnServiceThread();
747        int errorCode = mMessageValidator.isValid(message);
748        if (errorCode != HdmiCecMessageValidator.OK) {
749            // We'll not response on the messages with the invalid source or destination
750            // or with parameter length shorter than specified in the standard.
751            if (errorCode == HdmiCecMessageValidator.ERROR_PARAMETER) {
752                maySendFeatureAbortCommand(message, Constants.ABORT_INVALID_OPERAND);
753            }
754            return true;
755        }
756        return dispatchMessageToLocalDevice(message);
757    }
758
759    void setAudioReturnChannel(boolean enabled) {
760        mCecController.setAudioReturnChannel(enabled);
761    }
762
763    @ServiceThreadOnly
764    private boolean dispatchMessageToLocalDevice(HdmiCecMessage message) {
765        assertRunOnServiceThread();
766        for (HdmiCecLocalDevice device : mCecController.getLocalDeviceList()) {
767            if (device.dispatchMessage(message)
768                    && message.getDestination() != Constants.ADDR_BROADCAST) {
769                return true;
770            }
771        }
772
773        if (message.getDestination() != Constants.ADDR_BROADCAST) {
774            HdmiLogger.warning("Unhandled cec command:" + message);
775        }
776        return false;
777    }
778
779    /**
780     * Called when a new hotplug event is issued.
781     *
782     * @param portId hdmi port number where hot plug event issued.
783     * @param connected whether to be plugged in or not
784     */
785    @ServiceThreadOnly
786    void onHotplug(int portId, boolean connected) {
787        assertRunOnServiceThread();
788
789        if (connected && !isTvDevice()) {
790            ArrayList<HdmiCecLocalDevice> localDevices = new ArrayList<>();
791            for (int type : mLocalDevices) {
792                HdmiCecLocalDevice localDevice = mCecController.getLocalDevice(type);
793                if (localDevice == null) {
794                    localDevice = HdmiCecLocalDevice.create(this, type);
795                    localDevice.init();
796                }
797                localDevices.add(localDevice);
798            }
799            allocateLogicalAddress(localDevices, INITIATED_BY_HOTPLUG);
800        }
801
802        for (HdmiCecLocalDevice device : mCecController.getLocalDeviceList()) {
803            device.onHotplug(portId, connected);
804        }
805        announceHotplugEvent(portId, connected);
806    }
807
808    /**
809     * Poll all remote devices. It sends &lt;Polling Message&gt; to all remote
810     * devices.
811     *
812     * @param callback an interface used to get a list of all remote devices' address
813     * @param sourceAddress a logical address of source device where sends polling message
814     * @param pickStrategy strategy how to pick polling candidates
815     * @param retryCount the number of retry used to send polling message to remote devices
816     * @throw IllegalArgumentException if {@code pickStrategy} is invalid value
817     */
818    @ServiceThreadOnly
819    void pollDevices(DevicePollingCallback callback, int sourceAddress, int pickStrategy,
820            int retryCount) {
821        assertRunOnServiceThread();
822        mCecController.pollDevices(callback, sourceAddress, checkPollStrategy(pickStrategy),
823                retryCount);
824    }
825
826    private int checkPollStrategy(int pickStrategy) {
827        int strategy = pickStrategy & Constants.POLL_STRATEGY_MASK;
828        if (strategy == 0) {
829            throw new IllegalArgumentException("Invalid poll strategy:" + pickStrategy);
830        }
831        int iterationStrategy = pickStrategy & Constants.POLL_ITERATION_STRATEGY_MASK;
832        if (iterationStrategy == 0) {
833            throw new IllegalArgumentException("Invalid iteration strategy:" + pickStrategy);
834        }
835        return strategy | iterationStrategy;
836    }
837
838    List<HdmiCecLocalDevice> getAllLocalDevices() {
839        assertRunOnServiceThread();
840        return mCecController.getLocalDeviceList();
841    }
842
843    Object getServiceLock() {
844        return mLock;
845    }
846
847    void setAudioStatus(boolean mute, int volume) {
848        AudioManager audioManager = getAudioManager();
849        boolean muted = audioManager.isStreamMute(AudioManager.STREAM_MUSIC);
850        if (mute) {
851            if (!muted) {
852                audioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
853            }
854        } else {
855            if (muted) {
856                audioManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
857            }
858            // FLAG_HDMI_SYSTEM_AUDIO_VOLUME prevents audio manager from announcing
859            // volume change notification back to hdmi control service.
860            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume,
861                    AudioManager.FLAG_SHOW_UI | AudioManager.FLAG_HDMI_SYSTEM_AUDIO_VOLUME);
862        }
863    }
864
865    void announceSystemAudioModeChange(boolean enabled) {
866        synchronized (mLock) {
867            for (SystemAudioModeChangeListenerRecord record :
868                    mSystemAudioModeChangeListenerRecords) {
869                invokeSystemAudioModeChangeLocked(record.mListener, enabled);
870            }
871        }
872    }
873
874    private HdmiDeviceInfo createDeviceInfo(int logicalAddress, int deviceType, int powerStatus) {
875        // TODO: find better name instead of model name.
876        String displayName = Build.MODEL;
877        return new HdmiDeviceInfo(logicalAddress,
878                getPhysicalAddress(), pathToPortId(getPhysicalAddress()), deviceType,
879                getVendorId(), displayName);
880    }
881
882    @ServiceThreadOnly
883    void handleMhlHotplugEvent(int portId, boolean connected) {
884        assertRunOnServiceThread();
885        // Hotplug event is used to add/remove MHL devices as TV input.
886        if (connected) {
887            HdmiMhlLocalDeviceStub newDevice = new HdmiMhlLocalDeviceStub(this, portId);
888            HdmiMhlLocalDeviceStub oldDevice = mMhlController.addLocalDevice(newDevice);
889            if (oldDevice != null) {
890                oldDevice.onDeviceRemoved();
891                Slog.i(TAG, "Old device of port " + portId + " is removed");
892            }
893            invokeDeviceEventListeners(newDevice.getInfo(), DEVICE_EVENT_ADD_DEVICE);
894            updateSafeMhlInput();
895        } else {
896            HdmiMhlLocalDeviceStub device = mMhlController.removeLocalDevice(portId);
897            if (device != null) {
898                device.onDeviceRemoved();
899                invokeDeviceEventListeners(device.getInfo(), DEVICE_EVENT_REMOVE_DEVICE);
900                updateSafeMhlInput();
901            } else {
902                Slog.w(TAG, "No device to remove:[portId=" + portId);
903            }
904        }
905        announceHotplugEvent(portId, connected);
906    }
907
908    @ServiceThreadOnly
909    void handleMhlBusModeChanged(int portId, int busmode) {
910        assertRunOnServiceThread();
911        HdmiMhlLocalDeviceStub device = mMhlController.getLocalDevice(portId);
912        if (device != null) {
913            device.setBusMode(busmode);
914        } else {
915            Slog.w(TAG, "No mhl device exists for bus mode change[portId:" + portId +
916                    ", busmode:" + busmode + "]");
917        }
918    }
919
920    @ServiceThreadOnly
921    void handleMhlBusOvercurrent(int portId, boolean on) {
922        assertRunOnServiceThread();
923        HdmiMhlLocalDeviceStub device = mMhlController.getLocalDevice(portId);
924        if (device != null) {
925            device.onBusOvercurrentDetected(on);
926        } else {
927            Slog.w(TAG, "No mhl device exists for bus overcurrent event[portId:" + portId + "]");
928        }
929    }
930
931    @ServiceThreadOnly
932    void handleMhlDeviceStatusChanged(int portId, int adopterId, int deviceId) {
933        assertRunOnServiceThread();
934        HdmiMhlLocalDeviceStub device = mMhlController.getLocalDevice(portId);
935
936        if (device != null) {
937            device.setDeviceStatusChange(adopterId, deviceId);
938        } else {
939            Slog.w(TAG, "No mhl device exists for device status event[portId:"
940                    + portId + ", adopterId:" + adopterId + ", deviceId:" + deviceId + "]");
941        }
942    }
943
944    @ServiceThreadOnly
945    private void updateSafeMhlInput() {
946        assertRunOnServiceThread();
947        List<HdmiDeviceInfo> inputs = Collections.emptyList();
948        SparseArray<HdmiMhlLocalDeviceStub> devices = mMhlController.getAllLocalDevices();
949        for (int i = 0; i < devices.size(); ++i) {
950            HdmiMhlLocalDeviceStub device = devices.valueAt(i);
951            HdmiDeviceInfo info = device.getInfo();
952            if (info != null) {
953                if (inputs.isEmpty()) {
954                    inputs = new ArrayList<>();
955                }
956                inputs.add(device.getInfo());
957            }
958        }
959        synchronized (mLock) {
960            mMhlDevices = inputs;
961        }
962    }
963
964    private List<HdmiDeviceInfo> getMhlDevicesLocked() {
965        return mMhlDevices;
966    }
967
968    private class HdmiMhlVendorCommandListenerRecord implements IBinder.DeathRecipient {
969        private final IHdmiMhlVendorCommandListener mListener;
970
971        public HdmiMhlVendorCommandListenerRecord(IHdmiMhlVendorCommandListener listener) {
972            mListener = listener;
973        }
974
975        @Override
976        public void binderDied() {
977            mMhlVendorCommandListenerRecords.remove(this);
978        }
979    }
980
981    // Record class that monitors the event of the caller of being killed. Used to clean up
982    // the listener list and record list accordingly.
983    private final class HotplugEventListenerRecord implements IBinder.DeathRecipient {
984        private final IHdmiHotplugEventListener mListener;
985
986        public HotplugEventListenerRecord(IHdmiHotplugEventListener listener) {
987            mListener = listener;
988        }
989
990        @Override
991        public void binderDied() {
992            synchronized (mLock) {
993                mHotplugEventListenerRecords.remove(this);
994            }
995        }
996    }
997
998    private final class DeviceEventListenerRecord implements IBinder.DeathRecipient {
999        private final IHdmiDeviceEventListener mListener;
1000
1001        public DeviceEventListenerRecord(IHdmiDeviceEventListener listener) {
1002            mListener = listener;
1003        }
1004
1005        @Override
1006        public void binderDied() {
1007            synchronized (mLock) {
1008                mDeviceEventListenerRecords.remove(this);
1009            }
1010        }
1011    }
1012
1013    private final class SystemAudioModeChangeListenerRecord implements IBinder.DeathRecipient {
1014        private final IHdmiSystemAudioModeChangeListener mListener;
1015
1016        public SystemAudioModeChangeListenerRecord(IHdmiSystemAudioModeChangeListener listener) {
1017            mListener = listener;
1018        }
1019
1020        @Override
1021        public void binderDied() {
1022            synchronized (mLock) {
1023                mSystemAudioModeChangeListenerRecords.remove(this);
1024            }
1025        }
1026    }
1027
1028    class VendorCommandListenerRecord implements IBinder.DeathRecipient {
1029        private final IHdmiVendorCommandListener mListener;
1030        private final int mDeviceType;
1031
1032        public VendorCommandListenerRecord(IHdmiVendorCommandListener listener, int deviceType) {
1033            mListener = listener;
1034            mDeviceType = deviceType;
1035        }
1036
1037        @Override
1038        public void binderDied() {
1039            synchronized (mLock) {
1040                mVendorCommandListenerRecords.remove(this);
1041            }
1042        }
1043    }
1044
1045    private class HdmiRecordListenerRecord implements IBinder.DeathRecipient {
1046        private final IHdmiRecordListener mListener;
1047
1048        public HdmiRecordListenerRecord(IHdmiRecordListener listener) {
1049            mListener = listener;
1050        }
1051
1052        @Override
1053        public void binderDied() {
1054            synchronized (mLock) {
1055                mRecordListenerRecord = null;
1056            }
1057        }
1058    }
1059
1060    private void enforceAccessPermission() {
1061        getContext().enforceCallingOrSelfPermission(PERMISSION, TAG);
1062    }
1063
1064    private final class BinderService extends IHdmiControlService.Stub {
1065        @Override
1066        public int[] getSupportedTypes() {
1067            enforceAccessPermission();
1068            // mLocalDevices is an unmodifiable list - no lock necesary.
1069            int[] localDevices = new int[mLocalDevices.size()];
1070            for (int i = 0; i < localDevices.length; ++i) {
1071                localDevices[i] = mLocalDevices.get(i);
1072            }
1073            return localDevices;
1074        }
1075
1076        @Override
1077        public HdmiDeviceInfo getActiveSource() {
1078            enforceAccessPermission();
1079            HdmiCecLocalDeviceTv tv = tv();
1080            if (tv == null) {
1081                Slog.w(TAG, "Local tv device not available");
1082                return null;
1083            }
1084            ActiveSource activeSource = tv.getActiveSource();
1085            if (activeSource.isValid()) {
1086                return new HdmiDeviceInfo(activeSource.logicalAddress,
1087                        activeSource.physicalAddress, HdmiDeviceInfo.PORT_INVALID,
1088                        HdmiDeviceInfo.DEVICE_INACTIVE, 0, "");
1089            }
1090            int activePath = tv.getActivePath();
1091            if (activePath != HdmiDeviceInfo.PATH_INVALID) {
1092                return new HdmiDeviceInfo(activePath, tv.getActivePortId());
1093            }
1094            return null;
1095        }
1096
1097        @Override
1098        public void deviceSelect(final int deviceId, final IHdmiControlCallback callback) {
1099            enforceAccessPermission();
1100            runOnServiceThread(new Runnable() {
1101                @Override
1102                public void run() {
1103                    if (callback == null) {
1104                        Slog.e(TAG, "Callback cannot be null");
1105                        return;
1106                    }
1107                    HdmiCecLocalDeviceTv tv = tv();
1108                    if (tv == null) {
1109                        Slog.w(TAG, "Local tv device not available");
1110                        invokeCallback(callback, HdmiControlManager.RESULT_SOURCE_NOT_AVAILABLE);
1111                        return;
1112                    }
1113                    HdmiMhlLocalDeviceStub device = mMhlController.getLocalDeviceById(deviceId);
1114                    if (device != null) {
1115                        if (device.getPortId() == tv.getActivePortId()) {
1116                            invokeCallback(callback, HdmiControlManager.RESULT_SUCCESS);
1117                            return;
1118                        }
1119                        // Upon selecting MHL device, we send RAP[Content On] to wake up
1120                        // the connected mobile device, start routing control to switch ports.
1121                        // callback is handled by MHL action.
1122                        device.turnOn(callback);
1123                        tv.doManualPortSwitching(device.getPortId(), null);
1124                        return;
1125                    }
1126                    tv.deviceSelect(deviceId, callback);
1127                }
1128            });
1129        }
1130
1131        @Override
1132        public void portSelect(final int portId, final IHdmiControlCallback callback) {
1133            enforceAccessPermission();
1134            runOnServiceThread(new Runnable() {
1135                @Override
1136                public void run() {
1137                    if (callback == null) {
1138                        Slog.e(TAG, "Callback cannot be null");
1139                        return;
1140                    }
1141                    HdmiCecLocalDeviceTv tv = tv();
1142                    if (tv == null) {
1143                        Slog.w(TAG, "Local tv device not available");
1144                        invokeCallback(callback, HdmiControlManager.RESULT_SOURCE_NOT_AVAILABLE);
1145                        return;
1146                    }
1147                    tv.doManualPortSwitching(portId, callback);
1148                }
1149            });
1150        }
1151
1152        @Override
1153        public void sendKeyEvent(final int deviceType, final int keyCode, final boolean isPressed) {
1154            enforceAccessPermission();
1155            runOnServiceThread(new Runnable() {
1156                @Override
1157                public void run() {
1158                    HdmiMhlLocalDeviceStub device = mMhlController.getLocalDevice(mActivePortId);
1159                    if (device != null) {
1160                        device.sendKeyEvent(keyCode, isPressed);
1161                        return;
1162                    }
1163                    if (mCecController != null) {
1164                        HdmiCecLocalDevice localDevice = mCecController.getLocalDevice(deviceType);
1165                        if (localDevice == null) {
1166                            Slog.w(TAG, "Local device not available");
1167                            return;
1168                        }
1169                        localDevice.sendKeyEvent(keyCode, isPressed);
1170                    }
1171                }
1172            });
1173        }
1174
1175        @Override
1176        public void oneTouchPlay(final IHdmiControlCallback callback) {
1177            enforceAccessPermission();
1178            runOnServiceThread(new Runnable() {
1179                @Override
1180                public void run() {
1181                    HdmiControlService.this.oneTouchPlay(callback);
1182                }
1183            });
1184        }
1185
1186        @Override
1187        public void queryDisplayStatus(final IHdmiControlCallback callback) {
1188            enforceAccessPermission();
1189            runOnServiceThread(new Runnable() {
1190                @Override
1191                public void run() {
1192                    HdmiControlService.this.queryDisplayStatus(callback);
1193                }
1194            });
1195        }
1196
1197        @Override
1198        public void addHotplugEventListener(final IHdmiHotplugEventListener listener) {
1199            enforceAccessPermission();
1200            HdmiControlService.this.addHotplugEventListener(listener);
1201        }
1202
1203        @Override
1204        public void removeHotplugEventListener(final IHdmiHotplugEventListener listener) {
1205            enforceAccessPermission();
1206            HdmiControlService.this.removeHotplugEventListener(listener);
1207        }
1208
1209        @Override
1210        public void addDeviceEventListener(final IHdmiDeviceEventListener listener) {
1211            enforceAccessPermission();
1212            HdmiControlService.this.addDeviceEventListener(listener);
1213        }
1214
1215        @Override
1216        public List<HdmiPortInfo> getPortInfo() {
1217            enforceAccessPermission();
1218            return HdmiControlService.this.getPortInfo();
1219        }
1220
1221        @Override
1222        public boolean canChangeSystemAudioMode() {
1223            enforceAccessPermission();
1224            HdmiCecLocalDeviceTv tv = tv();
1225            if (tv == null) {
1226                return false;
1227            }
1228            return tv.hasSystemAudioDevice();
1229        }
1230
1231        @Override
1232        public boolean getSystemAudioMode() {
1233            enforceAccessPermission();
1234            HdmiCecLocalDeviceTv tv = tv();
1235            if (tv == null) {
1236                return false;
1237            }
1238            return tv.isSystemAudioActivated();
1239        }
1240
1241        @Override
1242        public void setSystemAudioMode(final boolean enabled, final IHdmiControlCallback callback) {
1243            enforceAccessPermission();
1244            runOnServiceThread(new Runnable() {
1245                @Override
1246                public void run() {
1247                    HdmiCecLocalDeviceTv tv = tv();
1248                    if (tv == null) {
1249                        Slog.w(TAG, "Local tv device not available");
1250                        invokeCallback(callback, HdmiControlManager.RESULT_SOURCE_NOT_AVAILABLE);
1251                        return;
1252                    }
1253                    tv.changeSystemAudioMode(enabled, callback);
1254                }
1255            });
1256        }
1257
1258        @Override
1259        public void addSystemAudioModeChangeListener(
1260                final IHdmiSystemAudioModeChangeListener listener) {
1261            enforceAccessPermission();
1262            HdmiControlService.this.addSystemAudioModeChangeListner(listener);
1263        }
1264
1265        @Override
1266        public void removeSystemAudioModeChangeListener(
1267                final IHdmiSystemAudioModeChangeListener listener) {
1268            enforceAccessPermission();
1269            HdmiControlService.this.removeSystemAudioModeChangeListener(listener);
1270        }
1271
1272        @Override
1273        public void setInputChangeListener(final IHdmiInputChangeListener listener) {
1274            enforceAccessPermission();
1275            HdmiControlService.this.setInputChangeListener(listener);
1276        }
1277
1278        @Override
1279        public List<HdmiDeviceInfo> getInputDevices() {
1280            enforceAccessPermission();
1281            // No need to hold the lock for obtaining TV device as the local device instance
1282            // is preserved while the HDMI control is enabled.
1283            HdmiCecLocalDeviceTv tv = tv();
1284            synchronized (mLock) {
1285                List<HdmiDeviceInfo> cecDevices = (tv == null)
1286                        ? Collections.<HdmiDeviceInfo>emptyList()
1287                        : tv.getSafeExternalInputsLocked();
1288                return HdmiUtils.mergeToUnmodifiableList(cecDevices, getMhlDevicesLocked());
1289            }
1290        }
1291
1292        // Returns all the CEC devices on the bus including system audio, switch,
1293        // even those of reserved type.
1294        @Override
1295        public List<HdmiDeviceInfo> getDeviceList() {
1296            enforceAccessPermission();
1297            HdmiCecLocalDeviceTv tv = tv();
1298            synchronized (mLock) {
1299                return (tv == null)
1300                        ? Collections.<HdmiDeviceInfo>emptyList()
1301                        : tv.getSafeCecDevicesLocked();
1302            }
1303        }
1304
1305        @Override
1306        public void setSystemAudioVolume(final int oldIndex, final int newIndex,
1307                final int maxIndex) {
1308            enforceAccessPermission();
1309            runOnServiceThread(new Runnable() {
1310                @Override
1311                public void run() {
1312                    HdmiCecLocalDeviceTv tv = tv();
1313                    if (tv == null) {
1314                        Slog.w(TAG, "Local tv device not available");
1315                        return;
1316                    }
1317                    tv.changeVolume(oldIndex, newIndex - oldIndex, maxIndex);
1318                }
1319            });
1320        }
1321
1322        @Override
1323        public void setSystemAudioMute(final boolean mute) {
1324            enforceAccessPermission();
1325            runOnServiceThread(new Runnable() {
1326                @Override
1327                public void run() {
1328                    HdmiCecLocalDeviceTv tv = tv();
1329                    if (tv == null) {
1330                        Slog.w(TAG, "Local tv device not available");
1331                        return;
1332                    }
1333                    tv.changeMute(mute);
1334                }
1335            });
1336        }
1337
1338        @Override
1339        public void setArcMode(final boolean enabled) {
1340            enforceAccessPermission();
1341            runOnServiceThread(new Runnable() {
1342                @Override
1343                public void run() {
1344                    HdmiCecLocalDeviceTv tv = tv();
1345                    if (tv == null) {
1346                        Slog.w(TAG, "Local tv device not available to change arc mode.");
1347                        return;
1348                    }
1349                }
1350            });
1351        }
1352
1353        @Override
1354        public void setProhibitMode(final boolean enabled) {
1355            enforceAccessPermission();
1356            if (!isTvDevice()) {
1357                return;
1358            }
1359            HdmiControlService.this.setProhibitMode(enabled);
1360        }
1361
1362        @Override
1363        public void addVendorCommandListener(final IHdmiVendorCommandListener listener,
1364                final int deviceType) {
1365            enforceAccessPermission();
1366            HdmiControlService.this.addVendorCommandListener(listener, deviceType);
1367        }
1368
1369        @Override
1370        public void sendVendorCommand(final int deviceType, final int targetAddress,
1371                final byte[] params, final boolean hasVendorId) {
1372            enforceAccessPermission();
1373            runOnServiceThread(new Runnable() {
1374                @Override
1375                public void run() {
1376                    HdmiCecLocalDevice device = mCecController.getLocalDevice(deviceType);
1377                    if (device == null) {
1378                        Slog.w(TAG, "Local device not available");
1379                        return;
1380                    }
1381                    if (hasVendorId) {
1382                        sendCecCommand(HdmiCecMessageBuilder.buildVendorCommandWithId(
1383                                device.getDeviceInfo().getLogicalAddress(), targetAddress,
1384                                getVendorId(), params));
1385                    } else {
1386                        sendCecCommand(HdmiCecMessageBuilder.buildVendorCommand(
1387                                device.getDeviceInfo().getLogicalAddress(), targetAddress, params));
1388                    }
1389                }
1390            });
1391        }
1392
1393        @Override
1394        public void sendStandby(final int deviceType, final int deviceId) {
1395            enforceAccessPermission();
1396            runOnServiceThread(new Runnable() {
1397                @Override
1398                public void run() {
1399                    HdmiCecLocalDevice device = mCecController.getLocalDevice(deviceType);
1400                    if (device == null) {
1401                        Slog.w(TAG, "Local device not available");
1402                        return;
1403                    }
1404                    device.sendStandby(deviceId);
1405                }
1406            });
1407        }
1408
1409        @Override
1410        public void setHdmiRecordListener(IHdmiRecordListener listener) {
1411            enforceAccessPermission();
1412            HdmiControlService.this.setHdmiRecordListener(listener);
1413        }
1414
1415        @Override
1416        public void startOneTouchRecord(final int recorderAddress, final byte[] recordSource) {
1417            enforceAccessPermission();
1418            runOnServiceThread(new Runnable() {
1419                @Override
1420                public void run() {
1421                    if (!isTvDevice()) {
1422                        Slog.w(TAG, "No TV is available.");
1423                        return;
1424                    }
1425                    tv().startOneTouchRecord(recorderAddress, recordSource);
1426                }
1427            });
1428        }
1429
1430        @Override
1431        public void stopOneTouchRecord(final int recorderAddress) {
1432            enforceAccessPermission();
1433            runOnServiceThread(new Runnable() {
1434                @Override
1435                public void run() {
1436                    if (!isTvDevice()) {
1437                        Slog.w(TAG, "No TV is available.");
1438                        return;
1439                    }
1440                    tv().stopOneTouchRecord(recorderAddress);
1441                }
1442            });
1443        }
1444
1445        @Override
1446        public void startTimerRecording(final int recorderAddress, final int sourceType,
1447                final byte[] recordSource) {
1448            enforceAccessPermission();
1449            runOnServiceThread(new Runnable() {
1450                @Override
1451                public void run() {
1452                    if (!isTvDevice()) {
1453                        Slog.w(TAG, "No TV is available.");
1454                        return;
1455                    }
1456                    tv().startTimerRecording(recorderAddress, sourceType, recordSource);
1457                }
1458            });
1459        }
1460
1461        @Override
1462        public void clearTimerRecording(final int recorderAddress, final int sourceType,
1463                final byte[] recordSource) {
1464            enforceAccessPermission();
1465            runOnServiceThread(new Runnable() {
1466                @Override
1467                public void run() {
1468                    if (!isTvDevice()) {
1469                        Slog.w(TAG, "No TV is available.");
1470                        return;
1471                    }
1472                    tv().clearTimerRecording(recorderAddress, sourceType, recordSource);
1473                }
1474            });
1475        }
1476
1477        @Override
1478        public void sendMhlVendorCommand(final int portId, final int offset, final int length,
1479                final byte[] data) {
1480            enforceAccessPermission();
1481            runOnServiceThread(new Runnable() {
1482                @Override
1483                public void run() {
1484                    if (!isControlEnabled()) {
1485                        Slog.w(TAG, "Hdmi control is disabled.");
1486                        return ;
1487                    }
1488                    HdmiMhlLocalDeviceStub device = mMhlController.getLocalDevice(portId);
1489                    if (device == null) {
1490                        Slog.w(TAG, "Invalid port id:" + portId);
1491                        return;
1492                    }
1493                    mMhlController.sendVendorCommand(portId, offset, length, data);
1494                }
1495            });
1496        }
1497
1498        @Override
1499        public void addHdmiMhlVendorCommandListener(
1500                IHdmiMhlVendorCommandListener listener) {
1501            enforceAccessPermission();
1502            HdmiControlService.this.addHdmiMhlVendorCommandListener(listener);
1503        }
1504
1505        @Override
1506        protected void dump(FileDescriptor fd, final PrintWriter writer, String[] args) {
1507            getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1508            final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
1509
1510            pw.println("mHdmiControlEnabled: " + mHdmiControlEnabled);
1511            pw.println("mProhibitMode: " + mProhibitMode);
1512            if (mCecController != null) {
1513                pw.println("mCecController: ");
1514                pw.increaseIndent();
1515                mCecController.dump(pw);
1516                pw.decreaseIndent();
1517            }
1518            pw.println("mPortInfo: ");
1519            pw.increaseIndent();
1520            for (HdmiPortInfo hdmiPortInfo : mPortInfo) {
1521                pw.println("- " + hdmiPortInfo);
1522            }
1523            pw.decreaseIndent();
1524            pw.println("mPowerStatus: " + mPowerStatus);
1525        }
1526    }
1527
1528    @ServiceThreadOnly
1529    private void oneTouchPlay(final IHdmiControlCallback callback) {
1530        assertRunOnServiceThread();
1531        HdmiCecLocalDevicePlayback source = playback();
1532        if (source == null) {
1533            Slog.w(TAG, "Local playback device not available");
1534            invokeCallback(callback, HdmiControlManager.RESULT_SOURCE_NOT_AVAILABLE);
1535            return;
1536        }
1537        source.oneTouchPlay(callback);
1538    }
1539
1540    @ServiceThreadOnly
1541    private void queryDisplayStatus(final IHdmiControlCallback callback) {
1542        assertRunOnServiceThread();
1543        HdmiCecLocalDevicePlayback source = playback();
1544        if (source == null) {
1545            Slog.w(TAG, "Local playback device not available");
1546            invokeCallback(callback, HdmiControlManager.RESULT_SOURCE_NOT_AVAILABLE);
1547            return;
1548        }
1549        source.queryDisplayStatus(callback);
1550    }
1551
1552    private void addHotplugEventListener(IHdmiHotplugEventListener listener) {
1553        HotplugEventListenerRecord record = new HotplugEventListenerRecord(listener);
1554        try {
1555            listener.asBinder().linkToDeath(record, 0);
1556        } catch (RemoteException e) {
1557            Slog.w(TAG, "Listener already died");
1558            return;
1559        }
1560        synchronized (mLock) {
1561            mHotplugEventListenerRecords.add(record);
1562        }
1563    }
1564
1565    private void removeHotplugEventListener(IHdmiHotplugEventListener listener) {
1566        synchronized (mLock) {
1567            for (HotplugEventListenerRecord record : mHotplugEventListenerRecords) {
1568                if (record.mListener.asBinder() == listener.asBinder()) {
1569                    listener.asBinder().unlinkToDeath(record, 0);
1570                    mHotplugEventListenerRecords.remove(record);
1571                    break;
1572                }
1573            }
1574        }
1575    }
1576
1577    private void addDeviceEventListener(IHdmiDeviceEventListener listener) {
1578        DeviceEventListenerRecord record = new DeviceEventListenerRecord(listener);
1579        try {
1580            listener.asBinder().linkToDeath(record, 0);
1581        } catch (RemoteException e) {
1582            Slog.w(TAG, "Listener already died");
1583            return;
1584        }
1585        synchronized (mLock) {
1586            mDeviceEventListenerRecords.add(record);
1587        }
1588    }
1589
1590    void invokeDeviceEventListeners(HdmiDeviceInfo device, int status) {
1591        synchronized (mLock) {
1592            for (DeviceEventListenerRecord record : mDeviceEventListenerRecords) {
1593                try {
1594                    record.mListener.onStatusChanged(device, status);
1595                } catch (RemoteException e) {
1596                    Slog.e(TAG, "Failed to report device event:" + e);
1597                }
1598            }
1599        }
1600    }
1601
1602    private void addSystemAudioModeChangeListner(IHdmiSystemAudioModeChangeListener listener) {
1603        SystemAudioModeChangeListenerRecord record = new SystemAudioModeChangeListenerRecord(
1604                listener);
1605        try {
1606            listener.asBinder().linkToDeath(record, 0);
1607        } catch (RemoteException e) {
1608            Slog.w(TAG, "Listener already died");
1609            return;
1610        }
1611        synchronized (mLock) {
1612            mSystemAudioModeChangeListenerRecords.add(record);
1613        }
1614    }
1615
1616    private void removeSystemAudioModeChangeListener(IHdmiSystemAudioModeChangeListener listener) {
1617        synchronized (mLock) {
1618            for (SystemAudioModeChangeListenerRecord record :
1619                    mSystemAudioModeChangeListenerRecords) {
1620                if (record.mListener.asBinder() == listener) {
1621                    listener.asBinder().unlinkToDeath(record, 0);
1622                    mSystemAudioModeChangeListenerRecords.remove(record);
1623                    break;
1624                }
1625            }
1626        }
1627    }
1628
1629    private final class InputChangeListenerRecord implements IBinder.DeathRecipient {
1630        private final IHdmiInputChangeListener mListener;
1631
1632        public InputChangeListenerRecord(IHdmiInputChangeListener listener) {
1633            mListener = listener;
1634        }
1635
1636        @Override
1637        public void binderDied() {
1638            synchronized (mLock) {
1639                mInputChangeListenerRecord = null;
1640            }
1641        }
1642    }
1643
1644    private void setInputChangeListener(IHdmiInputChangeListener listener) {
1645        synchronized (mLock) {
1646            mInputChangeListenerRecord = new InputChangeListenerRecord(listener);
1647            try {
1648                listener.asBinder().linkToDeath(mInputChangeListenerRecord, 0);
1649            } catch (RemoteException e) {
1650                Slog.w(TAG, "Listener already died");
1651                return;
1652            }
1653        }
1654    }
1655
1656    void invokeInputChangeListener(HdmiDeviceInfo info) {
1657        synchronized (mLock) {
1658            if (mInputChangeListenerRecord != null) {
1659                try {
1660                    mInputChangeListenerRecord.mListener.onChanged(info);
1661                } catch (RemoteException e) {
1662                    Slog.w(TAG, "Exception thrown by IHdmiInputChangeListener: " + e);
1663                }
1664            }
1665        }
1666    }
1667
1668    private void setHdmiRecordListener(IHdmiRecordListener listener) {
1669        synchronized (mLock) {
1670            mRecordListenerRecord = new HdmiRecordListenerRecord(listener);
1671            try {
1672                listener.asBinder().linkToDeath(mRecordListenerRecord, 0);
1673            } catch (RemoteException e) {
1674                Slog.w(TAG, "Listener already died.", e);
1675            }
1676        }
1677    }
1678
1679    byte[] invokeRecordRequestListener(int recorderAddress) {
1680        synchronized (mLock) {
1681            if (mRecordListenerRecord != null) {
1682                try {
1683                    return mRecordListenerRecord.mListener.getOneTouchRecordSource(recorderAddress);
1684                } catch (RemoteException e) {
1685                    Slog.w(TAG, "Failed to start record.", e);
1686                }
1687            }
1688            return EmptyArray.BYTE;
1689        }
1690    }
1691
1692    void invokeOneTouchRecordResult(int recorderAddress, int result) {
1693        synchronized (mLock) {
1694            if (mRecordListenerRecord != null) {
1695                try {
1696                    mRecordListenerRecord.mListener.onOneTouchRecordResult(recorderAddress, result);
1697                } catch (RemoteException e) {
1698                    Slog.w(TAG, "Failed to call onOneTouchRecordResult.", e);
1699                }
1700            }
1701        }
1702    }
1703
1704    void invokeTimerRecordingResult(int recorderAddress, int result) {
1705        synchronized (mLock) {
1706            if (mRecordListenerRecord != null) {
1707                try {
1708                    mRecordListenerRecord.mListener.onTimerRecordingResult(recorderAddress, result);
1709                } catch (RemoteException e) {
1710                    Slog.w(TAG, "Failed to call onTimerRecordingResult.", e);
1711                }
1712            }
1713        }
1714    }
1715
1716    void invokeClearTimerRecordingResult(int recorderAddress, int result) {
1717        synchronized (mLock) {
1718            if (mRecordListenerRecord != null) {
1719                try {
1720                    mRecordListenerRecord.mListener.onClearTimerRecordingResult(recorderAddress,
1721                            result);
1722                } catch (RemoteException e) {
1723                    Slog.w(TAG, "Failed to call onClearTimerRecordingResult.", e);
1724                }
1725            }
1726        }
1727    }
1728
1729    private void invokeCallback(IHdmiControlCallback callback, int result) {
1730        try {
1731            callback.onComplete(result);
1732        } catch (RemoteException e) {
1733            Slog.e(TAG, "Invoking callback failed:" + e);
1734        }
1735    }
1736
1737    private void invokeSystemAudioModeChangeLocked(IHdmiSystemAudioModeChangeListener listener,
1738            boolean enabled) {
1739        try {
1740            listener.onStatusChanged(enabled);
1741        } catch (RemoteException e) {
1742            Slog.e(TAG, "Invoking callback failed:" + e);
1743        }
1744    }
1745
1746    private void announceHotplugEvent(int portId, boolean connected) {
1747        HdmiHotplugEvent event = new HdmiHotplugEvent(portId, connected);
1748        synchronized (mLock) {
1749            for (HotplugEventListenerRecord record : mHotplugEventListenerRecords) {
1750                invokeHotplugEventListenerLocked(record.mListener, event);
1751            }
1752        }
1753    }
1754
1755    private void invokeHotplugEventListenerLocked(IHdmiHotplugEventListener listener,
1756            HdmiHotplugEvent event) {
1757        try {
1758            listener.onReceived(event);
1759        } catch (RemoteException e) {
1760            Slog.e(TAG, "Failed to report hotplug event:" + event.toString(), e);
1761        }
1762    }
1763
1764    private HdmiCecLocalDeviceTv tv() {
1765        return (HdmiCecLocalDeviceTv) mCecController.getLocalDevice(HdmiDeviceInfo.DEVICE_TV);
1766    }
1767
1768    boolean isTvDevice() {
1769        return mLocalDevices.contains(HdmiDeviceInfo.DEVICE_TV);
1770    }
1771
1772    private HdmiCecLocalDevicePlayback playback() {
1773        return (HdmiCecLocalDevicePlayback)
1774                mCecController.getLocalDevice(HdmiDeviceInfo.DEVICE_PLAYBACK);
1775    }
1776
1777    AudioManager getAudioManager() {
1778        return (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
1779    }
1780
1781    boolean isControlEnabled() {
1782        synchronized (mLock) {
1783            return mHdmiControlEnabled;
1784        }
1785    }
1786
1787    @ServiceThreadOnly
1788    int getPowerStatus() {
1789        assertRunOnServiceThread();
1790        return mPowerStatus;
1791    }
1792
1793    @ServiceThreadOnly
1794    boolean isPowerOnOrTransient() {
1795        assertRunOnServiceThread();
1796        return mPowerStatus == HdmiControlManager.POWER_STATUS_ON
1797                || mPowerStatus == HdmiControlManager.POWER_STATUS_TRANSIENT_TO_ON;
1798    }
1799
1800    @ServiceThreadOnly
1801    boolean isPowerStandbyOrTransient() {
1802        assertRunOnServiceThread();
1803        return mPowerStatus == HdmiControlManager.POWER_STATUS_STANDBY
1804                || mPowerStatus == HdmiControlManager.POWER_STATUS_TRANSIENT_TO_STANDBY;
1805    }
1806
1807    @ServiceThreadOnly
1808    boolean isPowerStandby() {
1809        assertRunOnServiceThread();
1810        return mPowerStatus == HdmiControlManager.POWER_STATUS_STANDBY;
1811    }
1812
1813    @ServiceThreadOnly
1814    void wakeUp() {
1815        assertRunOnServiceThread();
1816        mWakeUpMessageReceived = true;
1817        PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
1818        pm.wakeUp(SystemClock.uptimeMillis());
1819        // PowerManger will send the broadcast Intent.ACTION_SCREEN_ON and after this gets
1820        // the intent, the sequence will continue at onWakeUp().
1821    }
1822
1823    @ServiceThreadOnly
1824    void standby() {
1825        assertRunOnServiceThread();
1826        mStandbyMessageReceived = true;
1827        PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
1828        pm.goToSleep(SystemClock.uptimeMillis(), PowerManager.GO_TO_SLEEP_REASON_HDMI, 0);
1829        // PowerManger will send the broadcast Intent.ACTION_SCREEN_OFF and after this gets
1830        // the intent, the sequence will continue at onStandby().
1831    }
1832
1833    @ServiceThreadOnly
1834    private void onWakeUp() {
1835        assertRunOnServiceThread();
1836        mPowerStatus = HdmiControlManager.POWER_STATUS_TRANSIENT_TO_ON;
1837        if (mCecController != null) {
1838            if (mHdmiControlEnabled) {
1839                int startReason = INITIATED_BY_SCREEN_ON;
1840                if (mWakeUpMessageReceived) {
1841                    startReason = INITIATED_BY_WAKE_UP_MESSAGE;
1842                }
1843                initializeCec(startReason);
1844            }
1845        } else {
1846            Slog.i(TAG, "Device does not support HDMI-CEC.");
1847        }
1848        // TODO: Initialize MHL local devices.
1849    }
1850
1851    @ServiceThreadOnly
1852    private void onStandby() {
1853        assertRunOnServiceThread();
1854        mPowerStatus = HdmiControlManager.POWER_STATUS_TRANSIENT_TO_STANDBY;
1855        invokeVendorCommandListenersOnControlStateChanged(false,
1856                HdmiControlManager.CONTROL_STATE_CHANGED_REASON_STANDBY);
1857
1858        final List<HdmiCecLocalDevice> devices = getAllLocalDevices();
1859        disableDevices(new PendingActionClearedCallback() {
1860            @Override
1861            public void onCleared(HdmiCecLocalDevice device) {
1862                Slog.v(TAG, "On standby-action cleared:" + device.mDeviceType);
1863                devices.remove(device);
1864                if (devices.isEmpty()) {
1865                    onStandbyCompleted();
1866                    // We will not clear local devices here, since some OEM/SOC will keep passing
1867                    // the received packets until the application processor enters to the sleep
1868                    // actually.
1869                }
1870            }
1871        });
1872    }
1873
1874    @ServiceThreadOnly
1875    private void onLanguageChanged(String language) {
1876        assertRunOnServiceThread();
1877        mLanguage = language;
1878
1879        if (isTvDevice()) {
1880            tv().broadcastMenuLanguage(language);
1881        }
1882    }
1883
1884    @ServiceThreadOnly
1885    String getLanguage() {
1886        assertRunOnServiceThread();
1887        return mLanguage;
1888    }
1889
1890    private void disableDevices(PendingActionClearedCallback callback) {
1891        if (mCecController != null) {
1892            for (HdmiCecLocalDevice device : mCecController.getLocalDeviceList()) {
1893                device.disableDevice(mStandbyMessageReceived, callback);
1894            }
1895        }
1896
1897        mMhlController.clearAllLocalDevices();
1898    }
1899
1900    @ServiceThreadOnly
1901    private void clearLocalDevices() {
1902        assertRunOnServiceThread();
1903        if (mCecController == null) {
1904            return;
1905        }
1906        mCecController.clearLogicalAddress();
1907        mCecController.clearLocalDevices();
1908    }
1909
1910    @ServiceThreadOnly
1911    private void onStandbyCompleted() {
1912        assertRunOnServiceThread();
1913        Slog.v(TAG, "onStandbyCompleted");
1914
1915        if (mPowerStatus != HdmiControlManager.POWER_STATUS_TRANSIENT_TO_STANDBY) {
1916            return;
1917        }
1918        mPowerStatus = HdmiControlManager.POWER_STATUS_STANDBY;
1919        for (HdmiCecLocalDevice device : mCecController.getLocalDeviceList()) {
1920            device.onStandby(mStandbyMessageReceived);
1921        }
1922        mStandbyMessageReceived = false;
1923        mCecController.setOption(OPTION_CEC_SERVICE_CONTROL, DISABLED);
1924    }
1925
1926    private void addVendorCommandListener(IHdmiVendorCommandListener listener, int deviceType) {
1927        VendorCommandListenerRecord record = new VendorCommandListenerRecord(listener, deviceType);
1928        try {
1929            listener.asBinder().linkToDeath(record, 0);
1930        } catch (RemoteException e) {
1931            Slog.w(TAG, "Listener already died");
1932            return;
1933        }
1934        synchronized (mLock) {
1935            mVendorCommandListenerRecords.add(record);
1936        }
1937    }
1938
1939    boolean invokeVendorCommandListenersOnReceived(int deviceType, int srcAddress, int destAddress,
1940            byte[] params, boolean hasVendorId) {
1941        synchronized (mLock) {
1942            if (mVendorCommandListenerRecords.isEmpty()) {
1943                return false;
1944            }
1945            for (VendorCommandListenerRecord record : mVendorCommandListenerRecords) {
1946                if (record.mDeviceType != deviceType) {
1947                    continue;
1948                }
1949                try {
1950                    record.mListener.onReceived(srcAddress, destAddress, params, hasVendorId);
1951                } catch (RemoteException e) {
1952                    Slog.e(TAG, "Failed to notify vendor command reception", e);
1953                }
1954            }
1955            return true;
1956        }
1957    }
1958
1959    boolean invokeVendorCommandListenersOnControlStateChanged(boolean enabled, int reason) {
1960        synchronized (mLock) {
1961            if (mVendorCommandListenerRecords.isEmpty()) {
1962                return false;
1963            }
1964            for (VendorCommandListenerRecord record : mVendorCommandListenerRecords) {
1965                try {
1966                    record.mListener.onControlStateChanged(enabled, reason);
1967                } catch (RemoteException e) {
1968                    Slog.e(TAG, "Failed to notify control-state-changed to vendor handler", e);
1969                }
1970            }
1971            return true;
1972        }
1973    }
1974
1975    private void addHdmiMhlVendorCommandListener(IHdmiMhlVendorCommandListener listener) {
1976        HdmiMhlVendorCommandListenerRecord record =
1977                new HdmiMhlVendorCommandListenerRecord(listener);
1978        try {
1979            listener.asBinder().linkToDeath(record, 0);
1980        } catch (RemoteException e) {
1981            Slog.w(TAG, "Listener already died.");
1982            return;
1983        }
1984
1985        synchronized (mLock) {
1986            mMhlVendorCommandListenerRecords.add(record);
1987        }
1988    }
1989
1990    void invokeMhlVendorCommandListeners(int portId, int offest, int length, byte[] data) {
1991        synchronized (mLock) {
1992            for (HdmiMhlVendorCommandListenerRecord record : mMhlVendorCommandListenerRecords) {
1993                try {
1994                    record.mListener.onReceived(portId, offest, length, data);
1995                } catch (RemoteException e) {
1996                    Slog.e(TAG, "Failed to notify MHL vendor command", e);
1997                }
1998            }
1999        }
2000    }
2001
2002    boolean isProhibitMode() {
2003        synchronized (mLock) {
2004            return mProhibitMode;
2005        }
2006    }
2007
2008    void setProhibitMode(boolean enabled) {
2009        synchronized (mLock) {
2010            mProhibitMode = enabled;
2011        }
2012    }
2013
2014    @ServiceThreadOnly
2015    void setCecOption(int key, int value) {
2016        assertRunOnServiceThread();
2017        mCecController.setOption(key, value);
2018    }
2019
2020    @ServiceThreadOnly
2021    void setControlEnabled(boolean enabled) {
2022        assertRunOnServiceThread();
2023
2024        synchronized (mLock) {
2025            mHdmiControlEnabled = enabled;
2026        }
2027
2028        if (enabled) {
2029            enableHdmiControlService();
2030            return;
2031        }
2032        // Call the vendor handler before the service is disabled.
2033        invokeVendorCommandListenersOnControlStateChanged(false,
2034                HdmiControlManager.CONTROL_STATE_CHANGED_REASON_SETTING);
2035        // Post the remained tasks in the service thread again to give the vendor-issued-tasks
2036        // a chance to run.
2037        runOnServiceThread(new Runnable() {
2038            @Override
2039            public void run() {
2040                disableHdmiControlService();
2041            }
2042        });
2043        return;
2044    }
2045
2046    @ServiceThreadOnly
2047    private void enableHdmiControlService() {
2048        mCecController.setOption(OPTION_CEC_ENABLE, ENABLED);
2049        mMhlController.setOption(OPTION_MHL_ENABLE, ENABLED);
2050
2051        initializeCec(INITIATED_BY_ENABLE_CEC);
2052    }
2053
2054    @ServiceThreadOnly
2055    private void disableHdmiControlService() {
2056        disableDevices(new PendingActionClearedCallback() {
2057            @Override
2058            public void onCleared(HdmiCecLocalDevice device) {
2059                assertRunOnServiceThread();
2060                mCecController.flush(new Runnable() {
2061                    @Override
2062                    public void run() {
2063                        mCecController.setOption(OPTION_CEC_ENABLE, DISABLED);
2064                        mMhlController.setOption(OPTION_MHL_ENABLE, DISABLED);
2065                        clearLocalDevices();
2066                    }
2067                });
2068            }
2069        });
2070    }
2071
2072    @ServiceThreadOnly
2073    void setActivePortId(int portId) {
2074        assertRunOnServiceThread();
2075        mActivePortId = portId;
2076
2077        // Resets last input for MHL, which stays valid only after the MHL device was selected,
2078        // and no further switching is done.
2079        setLastInputForMhl(Constants.INVALID_PORT_ID);
2080    }
2081
2082    @ServiceThreadOnly
2083    void setLastInputForMhl(int portId) {
2084        assertRunOnServiceThread();
2085        mLastInputMhl = portId;
2086    }
2087
2088    @ServiceThreadOnly
2089    int getLastInputForMhl() {
2090        assertRunOnServiceThread();
2091        return mLastInputMhl;
2092    }
2093
2094    /**
2095     * Performs input change, routing control for MHL device.
2096     *
2097     * @param portId MHL port, or the last port to go back to if {@code contentOn} is false
2098     * @param contentOn {@code true} if RAP data is content on; otherwise false
2099     */
2100    @ServiceThreadOnly
2101    void changeInputForMhl(int portId, boolean contentOn) {
2102        assertRunOnServiceThread();
2103        final int lastInput = contentOn ? tv().getActivePortId() : Constants.INVALID_PORT_ID;
2104        tv().doManualPortSwitching(portId, new IHdmiControlCallback.Stub() {
2105            @Override
2106            public void onComplete(int result) throws RemoteException {
2107                // Keep the last input to switch back later when RAP[ContentOff] is received.
2108                // This effectively sets the port to invalid one if the switching is for
2109                // RAP[ContentOff].
2110                setLastInputForMhl(lastInput);
2111            }
2112        });
2113
2114        // MHL device is always directly connected to the port. Update the active port ID to avoid
2115        // unnecessary post-routing control task.
2116        tv().setActivePortId(portId);
2117
2118        // The port is either the MHL-enabled port where the mobile device is connected, or
2119        // the last port to go back to when turnoff command is received. Note that the last port
2120        // may not be the MHL-enabled one. In this case the device info to be passed to
2121        // input change listener should be the one describing the corresponding HDMI port.
2122        HdmiMhlLocalDeviceStub device = mMhlController.getLocalDevice(portId);
2123        HdmiDeviceInfo info = (device != null) ? device.getInfo() : mPortDeviceMap.get(portId);
2124        invokeInputChangeListener(info);
2125    }
2126
2127   void setMhlInputChangeEnabled(boolean enabled) {
2128       mMhlController.setOption(OPTION_MHL_INPUT_SWITCHING, toInt(enabled));
2129
2130        synchronized (mLock) {
2131            mMhlInputChangeEnabled = enabled;
2132        }
2133    }
2134
2135    boolean isMhlInputChangeEnabled() {
2136        synchronized (mLock) {
2137            return mMhlInputChangeEnabled;
2138        }
2139    }
2140
2141    @ServiceThreadOnly
2142    void displayOsd(int messageId) {
2143        assertRunOnServiceThread();
2144        Intent intent = new Intent(HdmiControlManager.ACTION_OSD_MESSAGE);
2145        intent.putExtra(HdmiControlManager.EXTRA_MESSAGE_ID, messageId);
2146        getContext().sendBroadcastAsUser(intent, UserHandle.ALL,
2147                HdmiControlService.PERMISSION);
2148    }
2149
2150    @ServiceThreadOnly
2151    void displayOsd(int messageId, int extra) {
2152        assertRunOnServiceThread();
2153        Intent intent = new Intent(HdmiControlManager.ACTION_OSD_MESSAGE);
2154        intent.putExtra(HdmiControlManager.EXTRA_MESSAGE_ID, messageId);
2155        intent.putExtra(HdmiControlManager.EXTRA_MESSAGE_EXTRA_PARAM1, extra);
2156        getContext().sendBroadcastAsUser(intent, UserHandle.ALL,
2157                HdmiControlService.PERMISSION);
2158    }
2159}
2160