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