HdmiCecLocalDeviceTv.java revision d47abefc8269dae7fdfa2bb102bcb89cbea7c7b0
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.CLEAR_TIMER_STATUS_CEC_DISABLE;
20import static android.hardware.hdmi.HdmiControlManager.CLEAR_TIMER_STATUS_CHECK_RECORDER_CONNECTION;
21import static android.hardware.hdmi.HdmiControlManager.CLEAR_TIMER_STATUS_FAIL_TO_CLEAR_SELECTED_SOURCE;
22import static android.hardware.hdmi.HdmiControlManager.ONE_TOUCH_RECORD_CEC_DISABLED;
23import static android.hardware.hdmi.HdmiControlManager.ONE_TOUCH_RECORD_CHECK_RECORDER_CONNECTION;
24import static android.hardware.hdmi.HdmiControlManager.ONE_TOUCH_RECORD_FAIL_TO_RECORD_DISPLAYED_SCREEN;
25import static android.hardware.hdmi.HdmiControlManager.OSD_MESSAGE_ARC_CONNECTED_INVALID_PORT;
26import static android.hardware.hdmi.HdmiControlManager.TIMER_RECORDING_RESULT_EXTRA_CEC_DISABLED;
27import static android.hardware.hdmi.HdmiControlManager.TIMER_RECORDING_RESULT_EXTRA_CHECK_RECORDER_CONNECTION;
28import static android.hardware.hdmi.HdmiControlManager.TIMER_RECORDING_RESULT_EXTRA_FAIL_TO_RECORD_SELECTED_SOURCE;
29import static android.hardware.hdmi.HdmiControlManager.TIMER_RECORDING_TYPE_ANALOGUE;
30import static android.hardware.hdmi.HdmiControlManager.TIMER_RECORDING_TYPE_DIGITAL;
31import static android.hardware.hdmi.HdmiControlManager.TIMER_RECORDING_TYPE_EXTERNAL;
32
33import android.annotation.Nullable;
34import android.content.Context;
35import android.hardware.hdmi.HdmiControlManager;
36import android.hardware.hdmi.HdmiDeviceInfo;
37import android.hardware.hdmi.HdmiRecordSources;
38import android.hardware.hdmi.HdmiTimerRecordSources;
39import android.hardware.hdmi.IHdmiControlCallback;
40import android.media.AudioManager;
41import android.media.AudioSystem;
42import android.media.tv.TvInputInfo;
43import android.media.tv.TvInputManager;
44import android.media.tv.TvInputManager.TvInputCallback;
45import android.os.RemoteException;
46import android.os.SystemProperties;
47import android.provider.Settings.Global;
48import android.util.ArraySet;
49import android.util.Slog;
50import android.util.SparseArray;
51
52import com.android.internal.annotations.GuardedBy;
53import com.android.internal.util.IndentingPrintWriter;
54import com.android.server.hdmi.DeviceDiscoveryAction.DeviceDiscoveryCallback;
55import com.android.server.hdmi.HdmiAnnotations.ServiceThreadOnly;
56import com.android.server.hdmi.HdmiControlService.SendMessageCallback;
57import com.android.server.SystemService;
58
59import java.io.UnsupportedEncodingException;
60import java.util.ArrayList;
61import java.util.Arrays;
62import java.util.Collection;
63import java.util.Collections;
64import java.util.Iterator;
65import java.util.List;
66import java.util.HashMap;
67
68/**
69 * Represent a logical device of type TV residing in Android system.
70 */
71final class HdmiCecLocalDeviceTv extends HdmiCecLocalDevice {
72    private static final String TAG = "HdmiCecLocalDeviceTv";
73
74    // Whether ARC is available or not. "true" means that ARC is established between TV and
75    // AVR as audio receiver.
76    @ServiceThreadOnly
77    private boolean mArcEstablished = false;
78
79    // Whether ARC feature is enabled or not. The default value is true.
80    // TODO: once adding system setting for it, read the value to it.
81    private boolean mArcFeatureEnabled = true;
82
83    // Whether System audio mode is activated or not.
84    // This becomes true only when all system audio sequences are finished.
85    @GuardedBy("mLock")
86    private boolean mSystemAudioActivated = false;
87
88    // The previous port id (input) before switching to the new one. This is remembered in order to
89    // be able to switch to it upon receiving <Inactive Source> from currently active source.
90    // This remains valid only when the active source was switched via one touch play operation
91    // (either by TV or source device). Manual port switching invalidates this value to
92    // Constants.PORT_INVALID, for which case <Inactive Source> does not do anything.
93    @GuardedBy("mLock")
94    private int mPrevPortId;
95
96    @GuardedBy("mLock")
97    private int mSystemAudioVolume = Constants.UNKNOWN_VOLUME;
98
99    @GuardedBy("mLock")
100    private boolean mSystemAudioMute = false;
101
102    // Copy of mDeviceInfos to guarantee thread-safety.
103    @GuardedBy("mLock")
104    private List<HdmiDeviceInfo> mSafeAllDeviceInfos = Collections.emptyList();
105    // All external cec input(source) devices. Does not include system audio device.
106    @GuardedBy("mLock")
107    private List<HdmiDeviceInfo> mSafeExternalInputs = Collections.emptyList();
108
109    // Map-like container of all cec devices including local ones.
110    // device id is used as key of container.
111    // This is not thread-safe. For external purpose use mSafeDeviceInfos.
112    private final SparseArray<HdmiDeviceInfo> mDeviceInfos = new SparseArray<>();
113
114    // If true, TV going to standby mode puts other devices also to standby.
115    private boolean mAutoDeviceOff;
116
117    // If true, TV wakes itself up when receiving <Text/Image View On>.
118    private boolean mAutoWakeup;
119
120    // List of the logical address of local CEC devices. Unmodifiable, thread-safe.
121    private List<Integer> mLocalDeviceAddresses;
122
123    private final HdmiCecStandbyModeHandler mStandbyHandler;
124
125    // If true, do not do routing control/send active source for internal source.
126    // Set to true when the device was woken up by <Text/Image View On>.
127    private boolean mSkipRoutingControl;
128
129    // Set of physical addresses of CEC switches on the CEC bus. Managed independently from
130    // other CEC devices since they might not have logical address.
131    private final ArraySet<Integer> mCecSwitches = new ArraySet<Integer>();
132
133    // Message buffer used to buffer selected messages to process later. <Active Source>
134    // from a source device, for instance, needs to be buffered if the device is not
135    // discovered yet. The buffered commands are taken out and when they are ready to
136    // handle.
137    private final DelayedMessageBuffer mDelayedMessageBuffer = new DelayedMessageBuffer(this);
138
139    // Defines the callback invoked when TV input framework is updated with input status.
140    // We are interested in the notification for HDMI input addition event, in order to
141    // process any CEC commands that arrived before the input is added.
142    private final TvInputCallback mTvInputCallback = new TvInputCallback() {
143        @Override
144        public void onInputAdded(String inputId) {
145            TvInputInfo tvInfo = mService.getTvInputManager().getTvInputInfo(inputId);
146            HdmiDeviceInfo info = tvInfo.getHdmiDeviceInfo();
147            if (info == null) return;
148            addTvInput(inputId, info.getId());
149            if (info.isCecDevice()) {
150                processDelayedActiveSource(info.getLogicalAddress());
151            }
152        }
153
154        @Override
155        public void onInputRemoved(String inputId) {
156            removeTvInput(inputId);
157        }
158    };
159
160    // Keeps the mapping (TV input ID, HDMI device ID) to keep track of the TV inputs ready to
161    // accept input switching request from HDMI devices. Requests for which the corresponding
162    // input ID is not yet registered by TV input framework need to be buffered for delayed
163    // processing.
164    private final HashMap<String, Integer> mTvInputs = new HashMap<>();
165
166    @ServiceThreadOnly
167    private void addTvInput(String inputId, int deviceId) {
168        assertRunOnServiceThread();
169        mTvInputs.put(inputId, deviceId);
170    }
171
172    @ServiceThreadOnly
173    private void removeTvInput(String inputId) {
174        assertRunOnServiceThread();
175        mTvInputs.remove(inputId);
176    }
177
178    @Override
179    @ServiceThreadOnly
180    protected boolean isInputReady(int deviceId) {
181        assertRunOnServiceThread();
182        return mTvInputs.containsValue(deviceId);
183    }
184
185    HdmiCecLocalDeviceTv(HdmiControlService service) {
186        super(service, HdmiDeviceInfo.DEVICE_TV);
187        mPrevPortId = Constants.INVALID_PORT_ID;
188        mAutoDeviceOff = mService.readBooleanSetting(Global.HDMI_CONTROL_AUTO_DEVICE_OFF_ENABLED,
189                true);
190        mAutoWakeup = mService.readBooleanSetting(Global.HDMI_CONTROL_AUTO_WAKEUP_ENABLED, true);
191        mStandbyHandler = new HdmiCecStandbyModeHandler(service, this);
192    }
193
194    @Override
195    @ServiceThreadOnly
196    protected void onAddressAllocated(int logicalAddress, int reason) {
197        assertRunOnServiceThread();
198        mService.registerTvInputCallback(mTvInputCallback);
199        mService.sendCecCommand(HdmiCecMessageBuilder.buildReportPhysicalAddressCommand(
200                mAddress, mService.getPhysicalAddress(), mDeviceType));
201        mService.sendCecCommand(HdmiCecMessageBuilder.buildDeviceVendorIdCommand(
202                mAddress, mService.getVendorId()));
203        mCecSwitches.add(mService.getPhysicalAddress());  // TV is a CEC switch too.
204        mTvInputs.clear();
205        mSkipRoutingControl = (reason == HdmiControlService.INITIATED_BY_WAKE_UP_MESSAGE);
206        launchRoutingControl(reason != HdmiControlService.INITIATED_BY_ENABLE_CEC &&
207                reason != HdmiControlService.INITIATED_BY_BOOT_UP);
208        mLocalDeviceAddresses = initLocalDeviceAddresses();
209        launchDeviceDiscovery();
210        startQueuedActions();
211    }
212
213
214    @ServiceThreadOnly
215    private List<Integer> initLocalDeviceAddresses() {
216        assertRunOnServiceThread();
217        List<Integer> addresses = new ArrayList<>();
218        for (HdmiCecLocalDevice device : mService.getAllLocalDevices()) {
219            addresses.add(device.getDeviceInfo().getLogicalAddress());
220        }
221        return Collections.unmodifiableList(addresses);
222    }
223
224    @Override
225    protected int getPreferredAddress() {
226        return Constants.ADDR_TV;
227    }
228
229    @Override
230    protected void setPreferredAddress(int addr) {
231        Slog.w(TAG, "Preferred addres will not be stored for TV");
232    }
233
234    @Override
235    @ServiceThreadOnly
236    boolean dispatchMessage(HdmiCecMessage message) {
237        assertRunOnServiceThread();
238        if (mService.isPowerStandby() && mStandbyHandler.handleCommand(message)) {
239            return true;
240        }
241        return super.onMessage(message);
242    }
243
244    /**
245     * Performs the action 'device select', or 'one touch play' initiated by TV.
246     *
247     * @param id id of HDMI device to select
248     * @param callback callback object to report the result with
249     */
250    @ServiceThreadOnly
251    void deviceSelect(int id, IHdmiControlCallback callback) {
252        assertRunOnServiceThread();
253        HdmiDeviceInfo targetDevice = mDeviceInfos.get(id);
254        if (targetDevice == null) {
255            invokeCallback(callback, HdmiControlManager.RESULT_TARGET_NOT_AVAILABLE);
256            return;
257        }
258        int targetAddress = targetDevice.getLogicalAddress();
259        ActiveSource active = getActiveSource();
260        if (active.isValid() && targetAddress == active.logicalAddress) {
261            invokeCallback(callback, HdmiControlManager.RESULT_SUCCESS);
262            return;
263        }
264        if (targetAddress == Constants.ADDR_INTERNAL) {
265            handleSelectInternalSource();
266            // Switching to internal source is always successful even when CEC control is disabled.
267            setActiveSource(targetAddress, mService.getPhysicalAddress());
268            setActivePath(mService.getPhysicalAddress());
269            invokeCallback(callback, HdmiControlManager.RESULT_SUCCESS);
270            return;
271        }
272        if (!mService.isControlEnabled()) {
273            setActiveSource(targetDevice);
274            invokeCallback(callback, HdmiControlManager.RESULT_INCORRECT_MODE);
275            return;
276        }
277        removeAction(DeviceSelectAction.class);
278        addAndStartAction(new DeviceSelectAction(this, targetDevice, callback));
279    }
280
281    @ServiceThreadOnly
282    private void handleSelectInternalSource() {
283        assertRunOnServiceThread();
284        // Seq #18
285        if (mService.isControlEnabled() && mActiveSource.logicalAddress != mAddress) {
286            updateActiveSource(mAddress, mService.getPhysicalAddress());
287            if (mSkipRoutingControl) {
288                mSkipRoutingControl = false;
289                return;
290            }
291            HdmiCecMessage activeSource = HdmiCecMessageBuilder.buildActiveSource(
292                    mAddress, mService.getPhysicalAddress());
293            mService.sendCecCommand(activeSource);
294        }
295    }
296
297    @ServiceThreadOnly
298    void updateActiveSource(int logicalAddress, int physicalAddress) {
299        assertRunOnServiceThread();
300        updateActiveSource(ActiveSource.of(logicalAddress, physicalAddress));
301    }
302
303    @ServiceThreadOnly
304    void updateActiveSource(ActiveSource newActive) {
305        assertRunOnServiceThread();
306        // Seq #14
307        if (mActiveSource.equals(newActive)) {
308            return;
309        }
310        setActiveSource(newActive);
311        int logicalAddress = newActive.logicalAddress;
312        if (getCecDeviceInfo(logicalAddress) != null && logicalAddress != mAddress) {
313            if (mService.pathToPortId(newActive.physicalAddress) == getActivePortId()) {
314                setPrevPortId(getActivePortId());
315            }
316            // TODO: Show the OSD banner related to the new active source device.
317        } else {
318            // TODO: If displayed, remove the OSD banner related to the previous
319            //       active source device.
320        }
321    }
322
323    int getPortId(int physicalAddress) {
324        return mService.pathToPortId(physicalAddress);
325    }
326
327    /**
328     * Returns the previous port id kept to handle input switching on <Inactive Source>.
329     */
330    int getPrevPortId() {
331        synchronized (mLock) {
332            return mPrevPortId;
333        }
334    }
335
336    /**
337     * Sets the previous port id. INVALID_PORT_ID invalidates it, hence no actions will be
338     * taken for <Inactive Source>.
339     */
340    void setPrevPortId(int portId) {
341        synchronized (mLock) {
342            mPrevPortId = portId;
343        }
344    }
345
346    @ServiceThreadOnly
347    void updateActiveInput(int path, boolean notifyInputChange) {
348        assertRunOnServiceThread();
349        // Seq #15
350        setPrevPortId(getActivePortId());
351        setActivePath(path);
352        // TODO: Handle PAP/PIP case.
353        // Show OSD port change banner
354        if (notifyInputChange) {
355            ActiveSource activeSource = getActiveSource();
356            HdmiDeviceInfo info = getCecDeviceInfo(activeSource.logicalAddress);
357            if (info == null) {
358                info = mService.getDeviceInfoByPort(getActivePortId());
359                if (info == null) {
360                    // No CEC/MHL device is present at the port. Attempt to switch to
361                    // the hardware port itself for non-CEC devices that may be connected.
362                    info = new HdmiDeviceInfo(path, getActivePortId());
363                }
364            }
365            mService.invokeInputChangeListener(info);
366        }
367    }
368
369    @ServiceThreadOnly
370    void doManualPortSwitching(int portId, IHdmiControlCallback callback) {
371        assertRunOnServiceThread();
372        // Seq #20
373        if (!mService.isValidPortId(portId)) {
374            invokeCallback(callback, HdmiControlManager.RESULT_INCORRECT_MODE);
375            return;
376        }
377        if (portId == getActivePortId()) {
378            invokeCallback(callback, HdmiControlManager.RESULT_SUCCESS);
379            return;
380        }
381        mActiveSource.invalidate();
382        if (!mService.isControlEnabled()) {
383            setActivePortId(portId);
384            invokeCallback(callback, HdmiControlManager.RESULT_INCORRECT_MODE);
385            return;
386        }
387        int oldPath = getActivePortId() != Constants.INVALID_PORT_ID
388                ? mService.portIdToPath(getActivePortId()) : getDeviceInfo().getPhysicalAddress();
389        setActivePath(oldPath);
390        if (mSkipRoutingControl) {
391            mSkipRoutingControl = false;
392            return;
393        }
394        int newPath = mService.portIdToPath(portId);
395        startRoutingControl(oldPath, newPath, true, callback);
396    }
397
398    @ServiceThreadOnly
399    void startRoutingControl(int oldPath, int newPath, boolean queryDevicePowerStatus,
400            IHdmiControlCallback callback) {
401        assertRunOnServiceThread();
402        if (oldPath == newPath) {
403            return;
404        }
405        HdmiCecMessage routingChange =
406                HdmiCecMessageBuilder.buildRoutingChange(mAddress, oldPath, newPath);
407        mService.sendCecCommand(routingChange);
408        removeAction(RoutingControlAction.class);
409        addAndStartAction(
410                new RoutingControlAction(this, newPath, queryDevicePowerStatus, callback));
411    }
412
413    @ServiceThreadOnly
414    int getPowerStatus() {
415        assertRunOnServiceThread();
416        return mService.getPowerStatus();
417    }
418
419    /**
420     * Sends key to a target CEC device.
421     *
422     * @param keyCode key code to send. Defined in {@link android.view.KeyEvent}.
423     * @param isPressed true if this is key press event
424     */
425    @Override
426    @ServiceThreadOnly
427    protected void sendKeyEvent(int keyCode, boolean isPressed) {
428        assertRunOnServiceThread();
429        if (!HdmiCecKeycode.isSupportedKeycode(keyCode)) {
430            Slog.w(TAG, "Unsupported key: " + keyCode);
431            return;
432        }
433        List<SendKeyAction> action = getActions(SendKeyAction.class);
434        if (!action.isEmpty()) {
435            action.get(0).processKeyEvent(keyCode, isPressed);
436        } else {
437            if (isPressed) {
438                int logicalAddress = findKeyReceiverAddress();
439                if (logicalAddress != Constants.ADDR_INVALID) {
440                    addAndStartAction(new SendKeyAction(this, logicalAddress, keyCode));
441                    return;
442                }
443            }
444            Slog.w(TAG, "Discard key event: " + keyCode + " pressed:" + isPressed);
445        }
446    }
447
448    private int findKeyReceiverAddress() {
449        if (getActiveSource().isValid()) {
450            return getActiveSource().logicalAddress;
451        }
452        HdmiDeviceInfo info = getDeviceInfoByPath(getActivePath());
453        if (info != null) {
454            return info.getLogicalAddress();
455        }
456        return Constants.ADDR_INVALID;
457    }
458
459    private static void invokeCallback(IHdmiControlCallback callback, int result) {
460        if (callback == null) {
461            return;
462        }
463        try {
464            callback.onComplete(result);
465        } catch (RemoteException e) {
466            Slog.e(TAG, "Invoking callback failed:" + e);
467        }
468    }
469
470    @Override
471    @ServiceThreadOnly
472    protected boolean handleActiveSource(HdmiCecMessage message) {
473        assertRunOnServiceThread();
474        int logicalAddress = message.getSource();
475        int physicalAddress = HdmiUtils.twoBytesToInt(message.getParams());
476        HdmiDeviceInfo info = getCecDeviceInfo(logicalAddress);
477        if (info == null) {
478            if (!handleNewDeviceAtTheTailOfActivePath(physicalAddress)) {
479                HdmiLogger.debug("Device info not found: %X; buffering the command", logicalAddress);
480                mDelayedMessageBuffer.add(message);
481            }
482        } else if (!isInputReady(info.getId())) {
483            HdmiLogger.debug("Input not ready for device: %X; buffering the command", info.getId());
484            mDelayedMessageBuffer.add(message);
485        } else {
486            ActiveSource activeSource = ActiveSource.of(logicalAddress, physicalAddress);
487            ActiveSourceHandler.create(this, null).process(activeSource, info.getDeviceType());
488        }
489        return true;
490    }
491
492    @Override
493    @ServiceThreadOnly
494    protected boolean handleInactiveSource(HdmiCecMessage message) {
495        assertRunOnServiceThread();
496        // Seq #10
497
498        // Ignore <Inactive Source> from non-active source device.
499        if (getActiveSource().logicalAddress != message.getSource()) {
500            return true;
501        }
502        if (isProhibitMode()) {
503            return true;
504        }
505        int portId = getPrevPortId();
506        if (portId != Constants.INVALID_PORT_ID) {
507            // TODO: Do this only if TV is not showing multiview like PIP/PAP.
508
509            HdmiDeviceInfo inactiveSource = getCecDeviceInfo(message.getSource());
510            if (inactiveSource == null) {
511                return true;
512            }
513            if (mService.pathToPortId(inactiveSource.getPhysicalAddress()) == portId) {
514                return true;
515            }
516            // TODO: Switch the TV freeze mode off
517
518            doManualPortSwitching(portId, null);
519            setPrevPortId(Constants.INVALID_PORT_ID);
520        }
521        return true;
522    }
523
524    @Override
525    @ServiceThreadOnly
526    protected boolean handleRequestActiveSource(HdmiCecMessage message) {
527        assertRunOnServiceThread();
528        // Seq #19
529        if (mAddress == getActiveSource().logicalAddress) {
530            mService.sendCecCommand(
531                    HdmiCecMessageBuilder.buildActiveSource(mAddress, getActivePath()));
532        }
533        return true;
534    }
535
536    @Override
537    @ServiceThreadOnly
538    protected boolean handleGetMenuLanguage(HdmiCecMessage message) {
539        assertRunOnServiceThread();
540        if (!broadcastMenuLanguage(mService.getLanguage())) {
541            Slog.w(TAG, "Failed to respond to <Get Menu Language>: " + message.toString());
542        }
543        return true;
544    }
545
546    @ServiceThreadOnly
547    boolean broadcastMenuLanguage(String language) {
548        assertRunOnServiceThread();
549        HdmiCecMessage command = HdmiCecMessageBuilder.buildSetMenuLanguageCommand(
550                mAddress, language);
551        if (command != null) {
552            mService.sendCecCommand(command);
553            return true;
554        }
555        return false;
556    }
557
558    @Override
559    @ServiceThreadOnly
560    protected boolean handleReportPhysicalAddress(HdmiCecMessage message) {
561        assertRunOnServiceThread();
562        int path = HdmiUtils.twoBytesToInt(message.getParams());
563        int address = message.getSource();
564        int type = message.getParams()[2];
565
566        if (updateCecSwitchInfo(address, type, path)) return true;
567
568        // Ignore if [Device Discovery Action] is going on.
569        if (hasAction(DeviceDiscoveryAction.class)) {
570            Slog.i(TAG, "Ignored while Device Discovery Action is in progress: " + message);
571            return true;
572        }
573
574        if (!isInDeviceList(address, path)) {
575            handleNewDeviceAtTheTailOfActivePath(path);
576        }
577        startNewDeviceAction(ActiveSource.of(address, path), type);
578        return true;
579    }
580
581    @Override
582    protected boolean handleReportPowerStatus(HdmiCecMessage command) {
583        int newStatus = command.getParams()[0] & 0xFF;
584        updateDevicePowerStatus(command.getSource(), newStatus);
585        return true;
586    }
587
588    @Override
589    protected boolean handleTimerStatus(HdmiCecMessage message) {
590        // Do nothing.
591        return true;
592    }
593
594    @Override
595    protected boolean handleRecordStatus(HdmiCecMessage message) {
596        // Do nothing.
597        return true;
598    }
599
600    boolean updateCecSwitchInfo(int address, int type, int path) {
601        if (address == Constants.ADDR_UNREGISTERED
602                && type == HdmiDeviceInfo.DEVICE_PURE_CEC_SWITCH) {
603            mCecSwitches.add(path);
604            updateSafeDeviceInfoList();
605            return true;  // Pure switch does not need further processing. Return here.
606        }
607        if (type == HdmiDeviceInfo.DEVICE_AUDIO_SYSTEM) {
608            mCecSwitches.add(path);
609        }
610        return false;
611    }
612
613    void startNewDeviceAction(ActiveSource activeSource, int deviceType) {
614        for (NewDeviceAction action : getActions(NewDeviceAction.class)) {
615            // If there is new device action which has the same logical address and path
616            // ignore new request.
617            // NewDeviceAction is created whenever it receives <Report Physical Address>.
618            // And there is a chance starting NewDeviceAction for the same source.
619            // Usually, new device sends <Report Physical Address> when it's plugged
620            // in. However, TV can detect a new device from HotPlugDetectionAction,
621            // which sends <Give Physical Address> to the source for newly detected
622            // device.
623            if (action.isActionOf(activeSource)) {
624                return;
625            }
626        }
627
628        addAndStartAction(new NewDeviceAction(this, activeSource.logicalAddress,
629                activeSource.physicalAddress, deviceType));
630    }
631
632    private boolean handleNewDeviceAtTheTailOfActivePath(int path) {
633        // Seq #22
634        if (isTailOfActivePath(path, getActivePath())) {
635            int newPath = mService.portIdToPath(getActivePortId());
636            setActivePath(newPath);
637            startRoutingControl(getActivePath(), newPath, false, null);
638            return true;
639        }
640        return false;
641    }
642
643    /**
644     * Whether the given path is located in the tail of current active path.
645     *
646     * @param path to be tested
647     * @param activePath current active path
648     * @return true if the given path is located in the tail of current active path; otherwise,
649     *         false
650     */
651    static boolean isTailOfActivePath(int path, int activePath) {
652        // If active routing path is internal source, return false.
653        if (activePath == 0) {
654            return false;
655        }
656        for (int i = 12; i >= 0; i -= 4) {
657            int curActivePath = (activePath >> i) & 0xF;
658            if (curActivePath == 0) {
659                return true;
660            } else {
661                int curPath = (path >> i) & 0xF;
662                if (curPath != curActivePath) {
663                    return false;
664                }
665            }
666        }
667        return false;
668    }
669
670    @Override
671    @ServiceThreadOnly
672    protected boolean handleRoutingChange(HdmiCecMessage message) {
673        assertRunOnServiceThread();
674        // Seq #21
675        byte[] params = message.getParams();
676        int currentPath = HdmiUtils.twoBytesToInt(params);
677        if (HdmiUtils.isAffectingActiveRoutingPath(getActivePath(), currentPath)) {
678            mActiveSource.invalidate();
679            removeAction(RoutingControlAction.class);
680            int newPath = HdmiUtils.twoBytesToInt(params, 2);
681            addAndStartAction(new RoutingControlAction(this, newPath, true, null));
682        }
683        return true;
684    }
685
686    @Override
687    @ServiceThreadOnly
688    protected boolean handleReportAudioStatus(HdmiCecMessage message) {
689        assertRunOnServiceThread();
690
691        byte params[] = message.getParams();
692        int mute = params[0] & 0x80;
693        int volume = params[0] & 0x7F;
694        setAudioStatus(mute == 0x80, volume);
695        return true;
696    }
697
698    @Override
699    @ServiceThreadOnly
700    protected boolean handleTextViewOn(HdmiCecMessage message) {
701        assertRunOnServiceThread();
702        if (mService.isPowerStandbyOrTransient() && mAutoWakeup) {
703            mService.wakeUp();
704        }
705        return true;
706    }
707
708    @Override
709    @ServiceThreadOnly
710    protected boolean handleImageViewOn(HdmiCecMessage message) {
711        assertRunOnServiceThread();
712        // Currently, it's the same as <Text View On>.
713        return handleTextViewOn(message);
714    }
715
716    @Override
717    @ServiceThreadOnly
718    protected boolean handleSetOsdName(HdmiCecMessage message) {
719        int source = message.getSource();
720        HdmiDeviceInfo deviceInfo = getCecDeviceInfo(source);
721        // If the device is not in device list, ignore it.
722        if (deviceInfo == null) {
723            Slog.e(TAG, "No source device info for <Set Osd Name>." + message);
724            return true;
725        }
726        String osdName = null;
727        try {
728            osdName = new String(message.getParams(), "US-ASCII");
729        } catch (UnsupportedEncodingException e) {
730            Slog.e(TAG, "Invalid <Set Osd Name> request:" + message, e);
731            return true;
732        }
733
734        if (deviceInfo.getDisplayName().equals(osdName)) {
735            Slog.i(TAG, "Ignore incoming <Set Osd Name> having same osd name:" + message);
736            return true;
737        }
738
739        addCecDevice(new HdmiDeviceInfo(deviceInfo.getLogicalAddress(),
740                deviceInfo.getPhysicalAddress(), deviceInfo.getPortId(),
741                deviceInfo.getDeviceType(), deviceInfo.getVendorId(), osdName));
742        return true;
743    }
744
745    @ServiceThreadOnly
746    private void launchDeviceDiscovery() {
747        assertRunOnServiceThread();
748        clearDeviceInfoList();
749        DeviceDiscoveryAction action = new DeviceDiscoveryAction(this,
750                new DeviceDiscoveryCallback() {
751                    @Override
752                    public void onDeviceDiscoveryDone(List<HdmiDeviceInfo> deviceInfos) {
753                        for (HdmiDeviceInfo info : deviceInfos) {
754                            addCecDevice(info);
755                        }
756
757                        // Since we removed all devices when it's start and
758                        // device discovery action does not poll local devices,
759                        // we should put device info of local device manually here
760                        for (HdmiCecLocalDevice device : mService.getAllLocalDevices()) {
761                            addCecDevice(device.getDeviceInfo());
762                        }
763
764                        addAndStartAction(new HotplugDetectionAction(HdmiCecLocalDeviceTv.this));
765                        addAndStartAction(new PowerStatusMonitorAction(HdmiCecLocalDeviceTv.this));
766
767                        // If there is AVR, initiate System Audio Auto initiation action,
768                        // which turns on and off system audio according to last system
769                        // audio setting.
770                        HdmiDeviceInfo avr = getAvrDeviceInfo();
771                        if (avr != null) {
772                            onNewAvrAdded(avr);
773                        }
774                    }
775                });
776        addAndStartAction(action);
777    }
778
779    @ServiceThreadOnly
780    void onNewAvrAdded(HdmiDeviceInfo avr) {
781        assertRunOnServiceThread();
782        if (getSystemAudioModeSetting() && !isSystemAudioActivated()) {
783            addAndStartAction(new SystemAudioAutoInitiationAction(this, avr.getLogicalAddress()));
784        }
785        if (isArcFeatureEnabled() && !hasAction(SetArcTransmissionStateAction.class)) {
786            startArcAction(true);
787        }
788    }
789
790    // Clear all device info.
791    @ServiceThreadOnly
792    private void clearDeviceInfoList() {
793        assertRunOnServiceThread();
794        for (HdmiDeviceInfo info : mSafeExternalInputs) {
795            invokeDeviceEventListener(info, HdmiControlManager.DEVICE_EVENT_REMOVE_DEVICE);
796        }
797        mDeviceInfos.clear();
798        updateSafeDeviceInfoList();
799    }
800
801    @ServiceThreadOnly
802    // Seq #32
803    void changeSystemAudioMode(boolean enabled, IHdmiControlCallback callback) {
804        assertRunOnServiceThread();
805        if (!mService.isControlEnabled() || hasAction(DeviceDiscoveryAction.class)) {
806            setSystemAudioMode(false, true);
807            invokeCallback(callback, HdmiControlManager.RESULT_INCORRECT_MODE);
808            return;
809        }
810        HdmiDeviceInfo avr = getAvrDeviceInfo();
811        if (avr == null) {
812            setSystemAudioMode(false, true);
813            invokeCallback(callback, HdmiControlManager.RESULT_TARGET_NOT_AVAILABLE);
814            return;
815        }
816
817        addAndStartAction(
818                new SystemAudioActionFromTv(this, avr.getLogicalAddress(), enabled, callback));
819    }
820
821    // # Seq 25
822    void setSystemAudioMode(boolean on, boolean updateSetting) {
823        HdmiLogger.debug("System Audio Mode change[old:%b new:%b]", mSystemAudioActivated, on);
824
825        if (updateSetting) {
826            mService.writeBooleanSetting(Global.HDMI_SYSTEM_AUDIO_ENABLED, on);
827        }
828        updateAudioManagerForSystemAudio(on);
829        synchronized (mLock) {
830            if (mSystemAudioActivated != on) {
831                mSystemAudioActivated = on;
832                mService.announceSystemAudioModeChange(on);
833            }
834        }
835    }
836
837    private void updateAudioManagerForSystemAudio(boolean on) {
838        int device = mService.getAudioManager().setHdmiSystemAudioSupported(on);
839        HdmiLogger.debug("[A]UpdateSystemAudio mode[on=%b] output=[%X]", on, device);
840    }
841
842    boolean isSystemAudioActivated() {
843        if (!hasSystemAudioDevice()) {
844            return false;
845        }
846        synchronized (mLock) {
847            return mSystemAudioActivated;
848        }
849    }
850
851    boolean getSystemAudioModeSetting() {
852        return mService.readBooleanSetting(Global.HDMI_SYSTEM_AUDIO_ENABLED, false);
853    }
854
855    /**
856     * Change ARC status into the given {@code enabled} status.
857     *
858     * @return {@code true} if ARC was in "Enabled" status
859     */
860    @ServiceThreadOnly
861    boolean setArcStatus(boolean enabled) {
862        assertRunOnServiceThread();
863
864        HdmiLogger.debug("Set Arc Status[old:%b new:%b]", mArcEstablished, enabled);
865        boolean oldStatus = mArcEstablished;
866        // 1. Enable/disable ARC circuit.
867        mService.setAudioReturnChannel(getAvrDeviceInfo().getPortId(), enabled);
868        // 2. Notify arc status to audio service.
869        notifyArcStatusToAudioService(enabled);
870        // 3. Update arc status;
871        mArcEstablished = enabled;
872        return oldStatus;
873    }
874
875    private void notifyArcStatusToAudioService(boolean enabled) {
876        // Note that we don't set any name to ARC.
877        mService.getAudioManager().setWiredDeviceConnectionState(
878                AudioSystem.DEVICE_OUT_HDMI_ARC,
879                enabled ? 1 : 0, "");
880    }
881
882    /**
883     * Returns whether ARC is enabled or not.
884     */
885    @ServiceThreadOnly
886    boolean isArcEstabilished() {
887        assertRunOnServiceThread();
888        return mArcFeatureEnabled && mArcEstablished;
889    }
890
891    @ServiceThreadOnly
892    void changeArcFeatureEnabled(boolean enabled) {
893        assertRunOnServiceThread();
894
895        if (mArcFeatureEnabled != enabled) {
896            mArcFeatureEnabled = enabled;
897            if (enabled) {
898                if (!mArcEstablished) {
899                    startArcAction(true);
900                }
901            } else {
902                if (mArcEstablished) {
903                    startArcAction(false);
904                }
905            }
906        }
907    }
908
909    @ServiceThreadOnly
910    boolean isArcFeatureEnabled() {
911        assertRunOnServiceThread();
912        return mArcFeatureEnabled;
913    }
914
915    @ServiceThreadOnly
916    void startArcAction(boolean enabled) {
917        assertRunOnServiceThread();
918        HdmiDeviceInfo info = getAvrDeviceInfo();
919        if (info == null) {
920            Slog.w(TAG, "Failed to start arc action; No AVR device.");
921            return;
922        }
923        if (!canStartArcUpdateAction(info.getLogicalAddress(), enabled)) {
924            Slog.w(TAG, "Failed to start arc action; ARC configuration check failed.");
925            if (enabled && !isConnectedToArcPort(info.getPhysicalAddress())) {
926                displayOsd(OSD_MESSAGE_ARC_CONNECTED_INVALID_PORT);
927            }
928            return;
929        }
930
931        // Terminate opposite action and start action if not exist.
932        if (enabled) {
933            removeAction(RequestArcTerminationAction.class);
934            if (!hasAction(RequestArcInitiationAction.class)) {
935                addAndStartAction(new RequestArcInitiationAction(this, info.getLogicalAddress()));
936            }
937        } else {
938            removeAction(RequestArcInitiationAction.class);
939            if (!hasAction(RequestArcTerminationAction.class)) {
940                addAndStartAction(new RequestArcTerminationAction(this, info.getLogicalAddress()));
941            }
942        }
943    }
944
945    private boolean isDirectConnectAddress(int physicalAddress) {
946        return (physicalAddress & Constants.ROUTING_PATH_TOP_MASK) == physicalAddress;
947    }
948
949    void setAudioStatus(boolean mute, int volume) {
950        synchronized (mLock) {
951            mSystemAudioMute = mute;
952            mSystemAudioVolume = volume;
953            int maxVolume = mService.getAudioManager().getStreamMaxVolume(
954                    AudioManager.STREAM_MUSIC);
955            mService.setAudioStatus(mute,
956                    VolumeControlAction.scaleToCustomVolume(volume, maxVolume));
957            displayOsd(HdmiControlManager.OSD_MESSAGE_AVR_VOLUME_CHANGED,
958                    mute ? HdmiControlManager.AVR_VOLUME_MUTED : volume);
959        }
960    }
961
962    @ServiceThreadOnly
963    void changeVolume(int curVolume, int delta, int maxVolume) {
964        assertRunOnServiceThread();
965        if (delta == 0 || !isSystemAudioActivated()) {
966            return;
967        }
968
969        int targetVolume = curVolume + delta;
970        int cecVolume = VolumeControlAction.scaleToCecVolume(targetVolume, maxVolume);
971        synchronized (mLock) {
972            // If new volume is the same as current system audio volume, just ignore it.
973            // Note that UNKNOWN_VOLUME is not in range of cec volume scale.
974            if (cecVolume == mSystemAudioVolume) {
975                // Update tv volume with system volume value.
976                mService.setAudioStatus(false,
977                        VolumeControlAction.scaleToCustomVolume(mSystemAudioVolume, maxVolume));
978                return;
979            }
980        }
981
982        List<VolumeControlAction> actions = getActions(VolumeControlAction.class);
983        if (actions.isEmpty()) {
984            addAndStartAction(new VolumeControlAction(this,
985                    getAvrDeviceInfo().getLogicalAddress(), delta > 0));
986        } else {
987            actions.get(0).handleVolumeChange(delta > 0);
988        }
989    }
990
991    @ServiceThreadOnly
992    void changeMute(boolean mute) {
993        assertRunOnServiceThread();
994        HdmiLogger.debug("[A]:Change mute:%b", mute);
995        synchronized (mLock) {
996            if (mSystemAudioMute == mute) {
997                HdmiLogger.debug("No need to change mute.");
998                return;
999            }
1000        }
1001        if (!isSystemAudioActivated()) {
1002            HdmiLogger.debug("[A]:System audio is not activated.");
1003            return;
1004        }
1005
1006        // Remove existing volume action.
1007        removeAction(VolumeControlAction.class);
1008        sendUserControlPressedAndReleased(getAvrDeviceInfo().getLogicalAddress(),
1009                mute ? HdmiCecKeycode.CEC_KEYCODE_MUTE_FUNCTION :
1010                        HdmiCecKeycode.CEC_KEYCODE_RESTORE_VOLUME_FUNCTION);
1011    }
1012
1013    @Override
1014    @ServiceThreadOnly
1015    protected boolean handleInitiateArc(HdmiCecMessage message) {
1016        assertRunOnServiceThread();
1017
1018        if (!canStartArcUpdateAction(message.getSource(), true)) {
1019            if (getAvrDeviceInfo() == null) {
1020                // AVR may not have been discovered yet. Delay the message processing.
1021                mDelayedMessageBuffer.add(message);
1022                return true;
1023            }
1024            mService.maySendFeatureAbortCommand(message, Constants.ABORT_REFUSED);
1025            if (!isConnectedToArcPort(message.getSource())) {
1026                displayOsd(OSD_MESSAGE_ARC_CONNECTED_INVALID_PORT);
1027            }
1028            return true;
1029        }
1030
1031        // In case where <Initiate Arc> is started by <Request ARC Initiation>
1032        // need to clean up RequestArcInitiationAction.
1033        removeAction(RequestArcInitiationAction.class);
1034        SetArcTransmissionStateAction action = new SetArcTransmissionStateAction(this,
1035                message.getSource(), true);
1036        addAndStartAction(action);
1037        return true;
1038    }
1039
1040    private boolean canStartArcUpdateAction(int avrAddress, boolean shouldCheckArcFeatureEnabled) {
1041        HdmiDeviceInfo avr = getAvrDeviceInfo();
1042        if (avr != null
1043                && (avrAddress == avr.getLogicalAddress())
1044                && isConnectedToArcPort(avr.getPhysicalAddress())
1045                && isDirectConnectAddress(avr.getPhysicalAddress())) {
1046            if (shouldCheckArcFeatureEnabled) {
1047                return isArcFeatureEnabled();
1048            } else {
1049                return true;
1050            }
1051        } else {
1052            return false;
1053        }
1054    }
1055
1056    @Override
1057    @ServiceThreadOnly
1058    protected boolean handleTerminateArc(HdmiCecMessage message) {
1059        assertRunOnServiceThread();
1060        // In cast of termination, do not check ARC configuration in that AVR device
1061        // might be removed already.
1062
1063        // In case where <Terminate Arc> is started by <Request ARC Termination>
1064        // need to clean up RequestArcInitiationAction.
1065        removeAction(RequestArcTerminationAction.class);
1066        SetArcTransmissionStateAction action = new SetArcTransmissionStateAction(this,
1067                message.getSource(), false);
1068        addAndStartAction(action);
1069        return true;
1070    }
1071
1072    @Override
1073    @ServiceThreadOnly
1074    protected boolean handleSetSystemAudioMode(HdmiCecMessage message) {
1075        assertRunOnServiceThread();
1076        if (!isMessageForSystemAudio(message)) {
1077            if (getAvrDeviceInfo() == null) {
1078                // AVR may not have been discovered yet. Delay the message processing.
1079                mDelayedMessageBuffer.add(message);
1080                return true;
1081            }
1082            HdmiLogger.warning("Invalid <Set System Audio Mode> message:" + message);
1083            mService.maySendFeatureAbortCommand(message, Constants.ABORT_REFUSED);
1084            return true;
1085        }
1086        SystemAudioActionFromAvr action = new SystemAudioActionFromAvr(this,
1087                message.getSource(), HdmiUtils.parseCommandParamSystemAudioStatus(message), null);
1088        addAndStartAction(action);
1089        return true;
1090    }
1091
1092    @Override
1093    @ServiceThreadOnly
1094    protected boolean handleSystemAudioModeStatus(HdmiCecMessage message) {
1095        assertRunOnServiceThread();
1096        if (!isMessageForSystemAudio(message)) {
1097            HdmiLogger.warning("Invalid <System Audio Mode Status> message:" + message);
1098            // Ignore this message.
1099            return true;
1100        }
1101        setSystemAudioMode(HdmiUtils.parseCommandParamSystemAudioStatus(message), true);
1102        return true;
1103    }
1104
1105    // Seq #53
1106    @Override
1107    @ServiceThreadOnly
1108    protected boolean handleRecordTvScreen(HdmiCecMessage message) {
1109        List<OneTouchRecordAction> actions = getActions(OneTouchRecordAction.class);
1110        if (!actions.isEmpty()) {
1111            // Assumes only one OneTouchRecordAction.
1112            OneTouchRecordAction action = actions.get(0);
1113            if (action.getRecorderAddress() != message.getSource()) {
1114                announceOneTouchRecordResult(
1115                        message.getSource(),
1116                        HdmiControlManager.ONE_TOUCH_RECORD_PREVIOUS_RECORDING_IN_PROGRESS);
1117            }
1118            return super.handleRecordTvScreen(message);
1119        }
1120
1121        int recorderAddress = message.getSource();
1122        byte[] recordSource = mService.invokeRecordRequestListener(recorderAddress);
1123        int reason = startOneTouchRecord(recorderAddress, recordSource);
1124        if (reason != Constants.ABORT_NO_ERROR) {
1125            mService.maySendFeatureAbortCommand(message, reason);
1126        }
1127        return true;
1128    }
1129
1130    @Override
1131    protected boolean handleTimerClearedStatus(HdmiCecMessage message) {
1132        byte[] params = message.getParams();
1133        int timerClearedStatusData = params[0] & 0xFF;
1134        announceTimerRecordingResult(message.getSource(), timerClearedStatusData);
1135        return true;
1136    }
1137
1138    void announceOneTouchRecordResult(int recorderAddress, int result) {
1139        mService.invokeOneTouchRecordResult(recorderAddress, result);
1140    }
1141
1142    void announceTimerRecordingResult(int recorderAddress, int result) {
1143        mService.invokeTimerRecordingResult(recorderAddress, result);
1144    }
1145
1146    void announceClearTimerRecordingResult(int recorderAddress, int result) {
1147        mService.invokeClearTimerRecordingResult(recorderAddress, result);
1148    }
1149
1150    private boolean isMessageForSystemAudio(HdmiCecMessage message) {
1151        return mService.isControlEnabled()
1152                && message.getSource() == Constants.ADDR_AUDIO_SYSTEM
1153                && (message.getDestination() == Constants.ADDR_TV
1154                        || message.getDestination() == Constants.ADDR_BROADCAST)
1155                && getAvrDeviceInfo() != null;
1156    }
1157
1158    /**
1159     * Add a new {@link HdmiDeviceInfo}. It returns old device info which has the same
1160     * logical address as new device info's.
1161     *
1162     * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
1163     *
1164     * @param deviceInfo a new {@link HdmiDeviceInfo} to be added.
1165     * @return {@code null} if it is new device. Otherwise, returns old {@HdmiDeviceInfo}
1166     *         that has the same logical address as new one has.
1167     */
1168    @ServiceThreadOnly
1169    private HdmiDeviceInfo addDeviceInfo(HdmiDeviceInfo deviceInfo) {
1170        assertRunOnServiceThread();
1171        HdmiDeviceInfo oldDeviceInfo = getCecDeviceInfo(deviceInfo.getLogicalAddress());
1172        if (oldDeviceInfo != null) {
1173            removeDeviceInfo(deviceInfo.getId());
1174        }
1175        mDeviceInfos.append(deviceInfo.getId(), deviceInfo);
1176        updateSafeDeviceInfoList();
1177        return oldDeviceInfo;
1178    }
1179
1180    /**
1181     * Remove a device info corresponding to the given {@code logicalAddress}.
1182     * It returns removed {@link HdmiDeviceInfo} if exists.
1183     *
1184     * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
1185     *
1186     * @param id id of device to be removed
1187     * @return removed {@link HdmiDeviceInfo} it exists. Otherwise, returns {@code null}
1188     */
1189    @ServiceThreadOnly
1190    private HdmiDeviceInfo removeDeviceInfo(int id) {
1191        assertRunOnServiceThread();
1192        HdmiDeviceInfo deviceInfo = mDeviceInfos.get(id);
1193        if (deviceInfo != null) {
1194            mDeviceInfos.remove(id);
1195        }
1196        updateSafeDeviceInfoList();
1197        return deviceInfo;
1198    }
1199
1200    /**
1201     * Return a list of all {@link HdmiDeviceInfo}.
1202     *
1203     * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
1204     * This is not thread-safe. For thread safety, call {@link #getSafeExternalInputsLocked} which
1205     * does not include local device.
1206     */
1207    @ServiceThreadOnly
1208    List<HdmiDeviceInfo> getDeviceInfoList(boolean includeLocalDevice) {
1209        assertRunOnServiceThread();
1210        if (includeLocalDevice) {
1211            return HdmiUtils.sparseArrayToList(mDeviceInfos);
1212        } else {
1213            ArrayList<HdmiDeviceInfo> infoList = new ArrayList<>();
1214            for (int i = 0; i < mDeviceInfos.size(); ++i) {
1215                HdmiDeviceInfo info = mDeviceInfos.valueAt(i);
1216                if (!isLocalDeviceAddress(info.getLogicalAddress())) {
1217                    infoList.add(info);
1218                }
1219            }
1220            return infoList;
1221        }
1222    }
1223
1224    /**
1225     * Return external input devices.
1226     */
1227    List<HdmiDeviceInfo> getSafeExternalInputsLocked() {
1228        return mSafeExternalInputs;
1229    }
1230
1231    @ServiceThreadOnly
1232    private void updateSafeDeviceInfoList() {
1233        assertRunOnServiceThread();
1234        List<HdmiDeviceInfo> copiedDevices = HdmiUtils.sparseArrayToList(mDeviceInfos);
1235        List<HdmiDeviceInfo> externalInputs = getInputDevices();
1236        synchronized (mLock) {
1237            mSafeAllDeviceInfos = copiedDevices;
1238            mSafeExternalInputs = externalInputs;
1239        }
1240    }
1241
1242    /**
1243     * Return a list of external cec input (source) devices.
1244     *
1245     * <p>Note that this effectively excludes non-source devices like system audio,
1246     * secondary TV.
1247     */
1248    private List<HdmiDeviceInfo> getInputDevices() {
1249        ArrayList<HdmiDeviceInfo> infoList = new ArrayList<>();
1250        for (int i = 0; i < mDeviceInfos.size(); ++i) {
1251            HdmiDeviceInfo info = mDeviceInfos.valueAt(i);
1252            if (isLocalDeviceAddress(info.getLogicalAddress())) {
1253                continue;
1254            }
1255            if (info.isSourceType() && !hideDevicesBehindLegacySwitch(info)) {
1256                infoList.add(info);
1257            }
1258        }
1259        return infoList;
1260    }
1261
1262    // Check if we are hiding CEC devices connected to a legacy (non-CEC) switch.
1263    // Returns true if the policy is set to true, and the device to check does not have
1264    // a parent CEC device (which should be the CEC-enabled switch) in the list.
1265    private boolean hideDevicesBehindLegacySwitch(HdmiDeviceInfo info) {
1266        return HdmiConfig.HIDE_DEVICES_BEHIND_LEGACY_SWITCH
1267                && !isConnectedToCecSwitch(info.getPhysicalAddress(), mCecSwitches);
1268    }
1269
1270    private static boolean isConnectedToCecSwitch(int path, Collection<Integer> switches) {
1271        for (int switchPath : switches) {
1272            if (isParentPath(switchPath, path)) {
1273                return true;
1274            }
1275        }
1276        return false;
1277    }
1278
1279    private static boolean isParentPath(int parentPath, int childPath) {
1280        // (A000, AB00) (AB00, ABC0), (ABC0, ABCD)
1281        // If child's last non-zero nibble is removed, the result equals to the parent.
1282        for (int i = 0; i <= 12; i += 4) {
1283            int nibble = (childPath >> i) & 0xF;
1284            if (nibble != 0) {
1285                int parentNibble = (parentPath >> i) & 0xF;
1286                return parentNibble == 0 && (childPath >> i+4) == (parentPath >> i+4);
1287            }
1288        }
1289        return false;
1290    }
1291
1292    private void invokeDeviceEventListener(HdmiDeviceInfo info, int status) {
1293        if (!hideDevicesBehindLegacySwitch(info)) {
1294            mService.invokeDeviceEventListeners(info, status);
1295        }
1296    }
1297
1298    private boolean isLocalDeviceAddress(int address) {
1299        return mLocalDeviceAddresses.contains(address);
1300    }
1301
1302    @ServiceThreadOnly
1303    HdmiDeviceInfo getAvrDeviceInfo() {
1304        assertRunOnServiceThread();
1305        return getCecDeviceInfo(Constants.ADDR_AUDIO_SYSTEM);
1306    }
1307
1308    /**
1309     * Return a {@link HdmiDeviceInfo} corresponding to the given {@code logicalAddress}.
1310     *
1311     * This is not thread-safe. For thread safety, call {@link #getSafeCecDeviceInfo(int)}.
1312     *
1313     * @param logicalAddress logical address of the device to be retrieved
1314     * @return {@link HdmiDeviceInfo} matched with the given {@code logicalAddress}.
1315     *         Returns null if no logical address matched
1316     */
1317    @ServiceThreadOnly
1318    HdmiDeviceInfo getCecDeviceInfo(int logicalAddress) {
1319        assertRunOnServiceThread();
1320        return mDeviceInfos.get(HdmiDeviceInfo.idForCecDevice(logicalAddress));
1321    }
1322
1323    boolean hasSystemAudioDevice() {
1324        return getSafeAvrDeviceInfo() != null;
1325    }
1326
1327    HdmiDeviceInfo getSafeAvrDeviceInfo() {
1328        return getSafeCecDeviceInfo(Constants.ADDR_AUDIO_SYSTEM);
1329    }
1330
1331    /**
1332     * Thread safe version of {@link #getCecDeviceInfo(int)}.
1333     *
1334     * @param logicalAddress logical address to be retrieved
1335     * @return {@link HdmiDeviceInfo} matched with the given {@code logicalAddress}.
1336     *         Returns null if no logical address matched
1337     */
1338    HdmiDeviceInfo getSafeCecDeviceInfo(int logicalAddress) {
1339        synchronized (mLock) {
1340            for (HdmiDeviceInfo info : mSafeAllDeviceInfos) {
1341                if (info.isCecDevice() && info.getLogicalAddress() == logicalAddress) {
1342                    return info;
1343                }
1344            }
1345            return null;
1346        }
1347    }
1348
1349    List<HdmiDeviceInfo> getSafeCecDevicesLocked() {
1350        ArrayList<HdmiDeviceInfo> infoList = new ArrayList<>();
1351        for (HdmiDeviceInfo info : mSafeAllDeviceInfos) {
1352            if (isLocalDeviceAddress(info.getLogicalAddress())) {
1353                continue;
1354            }
1355            infoList.add(info);
1356        }
1357        return infoList;
1358    }
1359
1360    /**
1361     * Called when a device is newly added or a new device is detected or
1362     * existing device is updated.
1363     *
1364     * @param info device info of a new device.
1365     */
1366    @ServiceThreadOnly
1367    final void addCecDevice(HdmiDeviceInfo info) {
1368        assertRunOnServiceThread();
1369        HdmiDeviceInfo old = addDeviceInfo(info);
1370        if (info.getLogicalAddress() == mAddress) {
1371            // The addition of TV device itself should not be notified.
1372            return;
1373        }
1374        if (old == null) {
1375            invokeDeviceEventListener(info, HdmiControlManager.DEVICE_EVENT_ADD_DEVICE);
1376        } else if (!old.equals(info)) {
1377            invokeDeviceEventListener(old, HdmiControlManager.DEVICE_EVENT_REMOVE_DEVICE);
1378            invokeDeviceEventListener(info, HdmiControlManager.DEVICE_EVENT_ADD_DEVICE);
1379        }
1380    }
1381
1382    /**
1383     * Called when a device is removed or removal of device is detected.
1384     *
1385     * @param address a logical address of a device to be removed
1386     */
1387    @ServiceThreadOnly
1388    final void removeCecDevice(int address) {
1389        assertRunOnServiceThread();
1390        HdmiDeviceInfo info = removeDeviceInfo(HdmiDeviceInfo.idForCecDevice(address));
1391
1392        mCecMessageCache.flushMessagesFrom(address);
1393        invokeDeviceEventListener(info, HdmiControlManager.DEVICE_EVENT_REMOVE_DEVICE);
1394    }
1395
1396    @ServiceThreadOnly
1397    void handleRemoveActiveRoutingPath(int path) {
1398        assertRunOnServiceThread();
1399        // Seq #23
1400        if (isTailOfActivePath(path, getActivePath())) {
1401            int newPath = mService.portIdToPath(getActivePortId());
1402            startRoutingControl(getActivePath(), newPath, true, null);
1403        }
1404    }
1405
1406    /**
1407     * Launch routing control process.
1408     *
1409     * @param routingForBootup true if routing control is initiated due to One Touch Play
1410     *        or TV power on
1411     */
1412    @ServiceThreadOnly
1413    void launchRoutingControl(boolean routingForBootup) {
1414        assertRunOnServiceThread();
1415        // Seq #24
1416        if (getActivePortId() != Constants.INVALID_PORT_ID) {
1417            if (!routingForBootup && !isProhibitMode()) {
1418                int newPath = mService.portIdToPath(getActivePortId());
1419                setActivePath(newPath);
1420                startRoutingControl(getActivePath(), newPath, routingForBootup, null);
1421            }
1422        } else {
1423            int activePath = mService.getPhysicalAddress();
1424            setActivePath(activePath);
1425            if (!routingForBootup
1426                    && !mDelayedMessageBuffer.isBuffered(Constants.MESSAGE_ACTIVE_SOURCE)) {
1427                mService.sendCecCommand(HdmiCecMessageBuilder.buildActiveSource(mAddress,
1428                        activePath));
1429            }
1430        }
1431    }
1432
1433    /**
1434     * Returns the {@link HdmiDeviceInfo} instance whose physical address matches
1435     * the given routing path. CEC devices use routing path for its physical address to
1436     * describe the hierarchy of the devices in the network.
1437     *
1438     * @param path routing path or physical address
1439     * @return {@link HdmiDeviceInfo} if the matched info is found; otherwise null
1440     */
1441    @ServiceThreadOnly
1442    final HdmiDeviceInfo getDeviceInfoByPath(int path) {
1443        assertRunOnServiceThread();
1444        for (HdmiDeviceInfo info : getDeviceInfoList(false)) {
1445            if (info.getPhysicalAddress() == path) {
1446                return info;
1447            }
1448        }
1449        return null;
1450    }
1451
1452    /**
1453     * Whether a device of the specified physical address and logical address exists
1454     * in a device info list. However, both are minimal condition and it could
1455     * be different device from the original one.
1456     *
1457     * @param logicalAddress logical address of a device to be searched
1458     * @param physicalAddress physical address of a device to be searched
1459     * @return true if exist; otherwise false
1460     */
1461    @ServiceThreadOnly
1462    private boolean isInDeviceList(int logicalAddress, int physicalAddress) {
1463        assertRunOnServiceThread();
1464        HdmiDeviceInfo device = getCecDeviceInfo(logicalAddress);
1465        if (device == null) {
1466            return false;
1467        }
1468        return device.getPhysicalAddress() == physicalAddress;
1469    }
1470
1471    @Override
1472    @ServiceThreadOnly
1473    void onHotplug(int portId, boolean connected) {
1474        assertRunOnServiceThread();
1475
1476        if (!connected) {
1477            removeCecSwitches(portId);
1478        }
1479        // Tv device will have permanent HotplugDetectionAction.
1480        List<HotplugDetectionAction> hotplugActions = getActions(HotplugDetectionAction.class);
1481        if (!hotplugActions.isEmpty()) {
1482            // Note that hotplug action is single action running on a machine.
1483            // "pollAllDevicesNow" cleans up timer and start poll action immediately.
1484            // It covers seq #40, #43.
1485            hotplugActions.get(0).pollAllDevicesNow();
1486        }
1487    }
1488
1489    private void removeCecSwitches(int portId) {
1490        Iterator<Integer> it = mCecSwitches.iterator();
1491        while (!it.hasNext()) {
1492            int path = it.next();
1493            if (pathToPortId(path) == portId) {
1494                it.remove();
1495            }
1496        }
1497    }
1498
1499    @ServiceThreadOnly
1500    void setAutoDeviceOff(boolean enabled) {
1501        assertRunOnServiceThread();
1502        mAutoDeviceOff = enabled;
1503    }
1504
1505    @ServiceThreadOnly
1506    void setAutoWakeup(boolean enabled) {
1507        assertRunOnServiceThread();
1508        mAutoWakeup = enabled;
1509    }
1510
1511    @ServiceThreadOnly
1512    boolean getAutoWakeup() {
1513        assertRunOnServiceThread();
1514        return mAutoWakeup;
1515    }
1516
1517    @Override
1518    @ServiceThreadOnly
1519    protected void disableDevice(boolean initiatedByCec, PendingActionClearedCallback callback) {
1520        super.disableDevice(initiatedByCec, callback);
1521        assertRunOnServiceThread();
1522        mService.unregisterTvInputCallback(mTvInputCallback);
1523        // Remove any repeated working actions.
1524        // HotplugDetectionAction will be reinstated during the wake up process.
1525        // HdmiControlService.onWakeUp() -> initializeLocalDevices() ->
1526        //     LocalDeviceTv.onAddressAllocated() -> launchDeviceDiscovery().
1527        removeAction(DeviceDiscoveryAction.class);
1528        removeAction(HotplugDetectionAction.class);
1529        removeAction(PowerStatusMonitorAction.class);
1530        // Remove recording actions.
1531        removeAction(OneTouchRecordAction.class);
1532        removeAction(TimerRecordingAction.class);
1533
1534        disableSystemAudioIfExist();
1535        disableArcIfExist();
1536        clearDeviceInfoList();
1537        checkIfPendingActionsCleared();
1538    }
1539
1540    @ServiceThreadOnly
1541    private void disableSystemAudioIfExist() {
1542        assertRunOnServiceThread();
1543        if (getAvrDeviceInfo() == null) {
1544            return;
1545        }
1546
1547        // Seq #31.
1548        removeAction(SystemAudioActionFromAvr.class);
1549        removeAction(SystemAudioActionFromTv.class);
1550        removeAction(SystemAudioAutoInitiationAction.class);
1551        removeAction(SystemAudioStatusAction.class);
1552        removeAction(VolumeControlAction.class);
1553
1554        // Turn off the mode but do not write it the settings, so that the next time TV powers on
1555        // the system audio mode setting can be restored automatically.
1556        setSystemAudioMode(false, false);
1557    }
1558
1559    @ServiceThreadOnly
1560    private void disableArcIfExist() {
1561        assertRunOnServiceThread();
1562        HdmiDeviceInfo avr = getAvrDeviceInfo();
1563        if (avr == null) {
1564            return;
1565        }
1566
1567        // Seq #44.
1568        removeAction(RequestArcInitiationAction.class);
1569        if (!hasAction(RequestArcTerminationAction.class) && isArcEstabilished()) {
1570            addAndStartAction(new RequestArcTerminationAction(this, avr.getLogicalAddress()));
1571        }
1572    }
1573
1574    @Override
1575    @ServiceThreadOnly
1576    protected void onStandby(boolean initiatedByCec) {
1577        assertRunOnServiceThread();
1578        // Seq #11
1579        if (!mService.isControlEnabled()) {
1580            return;
1581        }
1582        if (!initiatedByCec && mAutoDeviceOff) {
1583            mService.sendCecCommand(HdmiCecMessageBuilder.buildStandby(
1584                    mAddress, Constants.ADDR_BROADCAST));
1585        }
1586    }
1587
1588    boolean isProhibitMode() {
1589        return mService.isProhibitMode();
1590    }
1591
1592    boolean isPowerStandbyOrTransient() {
1593        return mService.isPowerStandbyOrTransient();
1594    }
1595
1596    @ServiceThreadOnly
1597    void displayOsd(int messageId) {
1598        assertRunOnServiceThread();
1599        mService.displayOsd(messageId);
1600    }
1601
1602    @ServiceThreadOnly
1603    void displayOsd(int messageId, int extra) {
1604        assertRunOnServiceThread();
1605        mService.displayOsd(messageId, extra);
1606    }
1607
1608    // Seq #54 and #55
1609    @ServiceThreadOnly
1610    int startOneTouchRecord(int recorderAddress, byte[] recordSource) {
1611        assertRunOnServiceThread();
1612        if (!mService.isControlEnabled()) {
1613            Slog.w(TAG, "Can not start one touch record. CEC control is disabled.");
1614            announceOneTouchRecordResult(recorderAddress, ONE_TOUCH_RECORD_CEC_DISABLED);
1615            return Constants.ABORT_NOT_IN_CORRECT_MODE;
1616        }
1617
1618        if (!checkRecorder(recorderAddress)) {
1619            Slog.w(TAG, "Invalid recorder address:" + recorderAddress);
1620            announceOneTouchRecordResult(recorderAddress,
1621                    ONE_TOUCH_RECORD_CHECK_RECORDER_CONNECTION);
1622            return Constants.ABORT_NOT_IN_CORRECT_MODE;
1623        }
1624
1625        if (!checkRecordSource(recordSource)) {
1626            Slog.w(TAG, "Invalid record source." + Arrays.toString(recordSource));
1627            announceOneTouchRecordResult(recorderAddress,
1628                    ONE_TOUCH_RECORD_FAIL_TO_RECORD_DISPLAYED_SCREEN);
1629            return Constants.ABORT_CANNOT_PROVIDE_SOURCE;
1630        }
1631
1632        addAndStartAction(new OneTouchRecordAction(this, recorderAddress, recordSource));
1633        Slog.i(TAG, "Start new [One Touch Record]-Target:" + recorderAddress + ", recordSource:"
1634                + Arrays.toString(recordSource));
1635        return Constants.ABORT_NO_ERROR;
1636    }
1637
1638    @ServiceThreadOnly
1639    void stopOneTouchRecord(int recorderAddress) {
1640        assertRunOnServiceThread();
1641        if (!mService.isControlEnabled()) {
1642            Slog.w(TAG, "Can not stop one touch record. CEC control is disabled.");
1643            announceOneTouchRecordResult(recorderAddress, ONE_TOUCH_RECORD_CEC_DISABLED);
1644            return;
1645        }
1646
1647        if (!checkRecorder(recorderAddress)) {
1648            Slog.w(TAG, "Invalid recorder address:" + recorderAddress);
1649            announceOneTouchRecordResult(recorderAddress,
1650                    ONE_TOUCH_RECORD_CHECK_RECORDER_CONNECTION);
1651            return;
1652        }
1653
1654        // Remove one touch record action so that other one touch record can be started.
1655        removeAction(OneTouchRecordAction.class);
1656        mService.sendCecCommand(HdmiCecMessageBuilder.buildRecordOff(mAddress, recorderAddress));
1657        Slog.i(TAG, "Stop [One Touch Record]-Target:" + recorderAddress);
1658    }
1659
1660    private boolean checkRecorder(int recorderAddress) {
1661        HdmiDeviceInfo device = getCecDeviceInfo(recorderAddress);
1662        return (device != null)
1663                && (HdmiUtils.getTypeFromAddress(recorderAddress)
1664                        == HdmiDeviceInfo.DEVICE_RECORDER);
1665    }
1666
1667    private boolean checkRecordSource(byte[] recordSource) {
1668        return (recordSource != null) && HdmiRecordSources.checkRecordSource(recordSource);
1669    }
1670
1671    @ServiceThreadOnly
1672    void startTimerRecording(int recorderAddress, int sourceType, byte[] recordSource) {
1673        assertRunOnServiceThread();
1674        if (!mService.isControlEnabled()) {
1675            Slog.w(TAG, "Can not start one touch record. CEC control is disabled.");
1676            announceTimerRecordingResult(recorderAddress,
1677                    TIMER_RECORDING_RESULT_EXTRA_CEC_DISABLED);
1678            return;
1679        }
1680
1681        if (!checkRecorder(recorderAddress)) {
1682            Slog.w(TAG, "Invalid recorder address:" + recorderAddress);
1683            announceTimerRecordingResult(recorderAddress,
1684                    TIMER_RECORDING_RESULT_EXTRA_CHECK_RECORDER_CONNECTION);
1685            return;
1686        }
1687
1688        if (!checkTimerRecordingSource(sourceType, recordSource)) {
1689            Slog.w(TAG, "Invalid record source." + Arrays.toString(recordSource));
1690            announceTimerRecordingResult(
1691                    recorderAddress,
1692                    TIMER_RECORDING_RESULT_EXTRA_FAIL_TO_RECORD_SELECTED_SOURCE);
1693            return;
1694        }
1695
1696        addAndStartAction(
1697                new TimerRecordingAction(this, recorderAddress, sourceType, recordSource));
1698        Slog.i(TAG, "Start [Timer Recording]-Target:" + recorderAddress + ", SourceType:"
1699                + sourceType + ", RecordSource:" + Arrays.toString(recordSource));
1700    }
1701
1702    private boolean checkTimerRecordingSource(int sourceType, byte[] recordSource) {
1703        return (recordSource != null)
1704                && HdmiTimerRecordSources.checkTimerRecordSource(sourceType, recordSource);
1705    }
1706
1707    @ServiceThreadOnly
1708    void clearTimerRecording(int recorderAddress, int sourceType, byte[] recordSource) {
1709        assertRunOnServiceThread();
1710        if (!mService.isControlEnabled()) {
1711            Slog.w(TAG, "Can not start one touch record. CEC control is disabled.");
1712            announceClearTimerRecordingResult(recorderAddress, CLEAR_TIMER_STATUS_CEC_DISABLE);
1713            return;
1714        }
1715
1716        if (!checkRecorder(recorderAddress)) {
1717            Slog.w(TAG, "Invalid recorder address:" + recorderAddress);
1718            announceClearTimerRecordingResult(recorderAddress,
1719                    CLEAR_TIMER_STATUS_CHECK_RECORDER_CONNECTION);
1720            return;
1721        }
1722
1723        if (!checkTimerRecordingSource(sourceType, recordSource)) {
1724            Slog.w(TAG, "Invalid record source." + Arrays.toString(recordSource));
1725            announceClearTimerRecordingResult(recorderAddress,
1726                    CLEAR_TIMER_STATUS_FAIL_TO_CLEAR_SELECTED_SOURCE);
1727            return;
1728        }
1729
1730        sendClearTimerMessage(recorderAddress, sourceType, recordSource);
1731    }
1732
1733    private void sendClearTimerMessage(final int recorderAddress, int sourceType,
1734            byte[] recordSource) {
1735        HdmiCecMessage message = null;
1736        switch (sourceType) {
1737            case TIMER_RECORDING_TYPE_DIGITAL:
1738                message = HdmiCecMessageBuilder.buildClearDigitalTimer(mAddress, recorderAddress,
1739                        recordSource);
1740                break;
1741            case TIMER_RECORDING_TYPE_ANALOGUE:
1742                message = HdmiCecMessageBuilder.buildClearAnalogueTimer(mAddress, recorderAddress,
1743                        recordSource);
1744                break;
1745            case TIMER_RECORDING_TYPE_EXTERNAL:
1746                message = HdmiCecMessageBuilder.buildClearExternalTimer(mAddress, recorderAddress,
1747                        recordSource);
1748                break;
1749            default:
1750                Slog.w(TAG, "Invalid source type:" + recorderAddress);
1751                announceClearTimerRecordingResult(recorderAddress,
1752                        CLEAR_TIMER_STATUS_FAIL_TO_CLEAR_SELECTED_SOURCE);
1753                return;
1754
1755        }
1756        mService.sendCecCommand(message, new SendMessageCallback() {
1757            @Override
1758            public void onSendCompleted(int error) {
1759                if (error != Constants.SEND_RESULT_SUCCESS) {
1760                    announceClearTimerRecordingResult(recorderAddress,
1761                            CLEAR_TIMER_STATUS_FAIL_TO_CLEAR_SELECTED_SOURCE);
1762                }
1763            }
1764        });
1765    }
1766
1767    void updateDevicePowerStatus(int logicalAddress, int newPowerStatus) {
1768        HdmiDeviceInfo info = getCecDeviceInfo(logicalAddress);
1769        if (info == null) {
1770            Slog.w(TAG, "Can not update power status of non-existing device:" + logicalAddress);
1771            return;
1772        }
1773
1774        if (info.getDevicePowerStatus() == newPowerStatus) {
1775            return;
1776        }
1777
1778        HdmiDeviceInfo newInfo = HdmiUtils.cloneHdmiDeviceInfo(info, newPowerStatus);
1779        // addDeviceInfo replaces old device info with new one if exists.
1780        addDeviceInfo(newInfo);
1781
1782        invokeDeviceEventListener(newInfo, HdmiControlManager.DEVICE_EVENT_UPDATE_DEVICE);
1783    }
1784
1785    @Override
1786    protected boolean handleMenuStatus(HdmiCecMessage message) {
1787        // Do nothing and just return true not to prevent from responding <Feature Abort>.
1788        return true;
1789    }
1790
1791    @Override
1792    protected void sendStandby(int deviceId) {
1793        HdmiDeviceInfo targetDevice = mDeviceInfos.get(deviceId);
1794        if (targetDevice == null) {
1795            return;
1796        }
1797        int targetAddress = targetDevice.getLogicalAddress();
1798        mService.sendCecCommand(HdmiCecMessageBuilder.buildStandby(mAddress, targetAddress));
1799    }
1800
1801    @ServiceThreadOnly
1802    void processAllDelayedMessages() {
1803        assertRunOnServiceThread();
1804        mDelayedMessageBuffer.processAllMessages();
1805    }
1806
1807    @ServiceThreadOnly
1808    void processDelayedMessages(int address) {
1809        assertRunOnServiceThread();
1810        mDelayedMessageBuffer.processMessagesForDevice(address);
1811    }
1812
1813    @ServiceThreadOnly
1814    void processDelayedActiveSource(int address) {
1815        assertRunOnServiceThread();
1816        mDelayedMessageBuffer.processActiveSource(address);
1817    }
1818
1819    @Override
1820    protected void dump(final IndentingPrintWriter pw) {
1821        super.dump(pw);
1822        pw.println("mArcEstablished: " + mArcEstablished);
1823        pw.println("mArcFeatureEnabled: " + mArcFeatureEnabled);
1824        pw.println("mSystemAudioActivated: " + mSystemAudioActivated);
1825        pw.println("mSystemAudioMute: " + mSystemAudioMute);
1826        pw.println("mAutoDeviceOff: " + mAutoDeviceOff);
1827        pw.println("mAutoWakeup: " + mAutoWakeup);
1828        pw.println("mSkipRoutingControl: " + mSkipRoutingControl);
1829        pw.println("CEC devices:");
1830        pw.increaseIndent();
1831        for (HdmiDeviceInfo info : mSafeAllDeviceInfos) {
1832            pw.println(info);
1833        }
1834        pw.decreaseIndent();
1835    }
1836}
1837