HdmiCecLocalDeviceTv.java revision cb8661c08f4a7b00eaa2ede06a30c32dd3cbc53b
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 %X not found; 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        } else {
521            // No HDMI port to switch to was found. Notify the input change listers to
522            // switch to the lastly shown internal input.
523            mActiveSource.invalidate();
524            setActivePath(Constants.INVALID_PHYSICAL_ADDRESS);
525            mService.invokeInputChangeListener(HdmiDeviceInfo.INACTIVE_DEVICE);
526        }
527        return true;
528    }
529
530    @Override
531    @ServiceThreadOnly
532    protected boolean handleRequestActiveSource(HdmiCecMessage message) {
533        assertRunOnServiceThread();
534        // Seq #19
535        if (mAddress == getActiveSource().logicalAddress) {
536            mService.sendCecCommand(
537                    HdmiCecMessageBuilder.buildActiveSource(mAddress, getActivePath()));
538        }
539        return true;
540    }
541
542    @Override
543    @ServiceThreadOnly
544    protected boolean handleGetMenuLanguage(HdmiCecMessage message) {
545        assertRunOnServiceThread();
546        if (!broadcastMenuLanguage(mService.getLanguage())) {
547            Slog.w(TAG, "Failed to respond to <Get Menu Language>: " + message.toString());
548        }
549        return true;
550    }
551
552    @ServiceThreadOnly
553    boolean broadcastMenuLanguage(String language) {
554        assertRunOnServiceThread();
555        HdmiCecMessage command = HdmiCecMessageBuilder.buildSetMenuLanguageCommand(
556                mAddress, language);
557        if (command != null) {
558            mService.sendCecCommand(command);
559            return true;
560        }
561        return false;
562    }
563
564    @Override
565    @ServiceThreadOnly
566    protected boolean handleReportPhysicalAddress(HdmiCecMessage message) {
567        assertRunOnServiceThread();
568        int path = HdmiUtils.twoBytesToInt(message.getParams());
569        int address = message.getSource();
570        int type = message.getParams()[2];
571
572        if (updateCecSwitchInfo(address, type, path)) return true;
573
574        // Ignore if [Device Discovery Action] is going on.
575        if (hasAction(DeviceDiscoveryAction.class)) {
576            Slog.i(TAG, "Ignored while Device Discovery Action is in progress: " + message);
577            return true;
578        }
579
580        if (!isInDeviceList(address, path)) {
581            handleNewDeviceAtTheTailOfActivePath(path);
582        }
583        startNewDeviceAction(ActiveSource.of(address, path), type);
584        return true;
585    }
586
587    @Override
588    protected boolean handleReportPowerStatus(HdmiCecMessage command) {
589        int newStatus = command.getParams()[0] & 0xFF;
590        updateDevicePowerStatus(command.getSource(), newStatus);
591        return true;
592    }
593
594    @Override
595    protected boolean handleTimerStatus(HdmiCecMessage message) {
596        // Do nothing.
597        return true;
598    }
599
600    @Override
601    protected boolean handleRecordStatus(HdmiCecMessage message) {
602        // Do nothing.
603        return true;
604    }
605
606    boolean updateCecSwitchInfo(int address, int type, int path) {
607        if (address == Constants.ADDR_UNREGISTERED
608                && type == HdmiDeviceInfo.DEVICE_PURE_CEC_SWITCH) {
609            mCecSwitches.add(path);
610            updateSafeDeviceInfoList();
611            return true;  // Pure switch does not need further processing. Return here.
612        }
613        if (type == HdmiDeviceInfo.DEVICE_AUDIO_SYSTEM) {
614            mCecSwitches.add(path);
615        }
616        return false;
617    }
618
619    void startNewDeviceAction(ActiveSource activeSource, int deviceType) {
620        for (NewDeviceAction action : getActions(NewDeviceAction.class)) {
621            // If there is new device action which has the same logical address and path
622            // ignore new request.
623            // NewDeviceAction is created whenever it receives <Report Physical Address>.
624            // And there is a chance starting NewDeviceAction for the same source.
625            // Usually, new device sends <Report Physical Address> when it's plugged
626            // in. However, TV can detect a new device from HotPlugDetectionAction,
627            // which sends <Give Physical Address> to the source for newly detected
628            // device.
629            if (action.isActionOf(activeSource)) {
630                return;
631            }
632        }
633
634        addAndStartAction(new NewDeviceAction(this, activeSource.logicalAddress,
635                activeSource.physicalAddress, deviceType));
636    }
637
638    private boolean handleNewDeviceAtTheTailOfActivePath(int path) {
639        // Seq #22
640        if (isTailOfActivePath(path, getActivePath())) {
641            int newPath = mService.portIdToPath(getActivePortId());
642            setActivePath(newPath);
643            startRoutingControl(getActivePath(), newPath, false, null);
644            return true;
645        }
646        return false;
647    }
648
649    /**
650     * Whether the given path is located in the tail of current active path.
651     *
652     * @param path to be tested
653     * @param activePath current active path
654     * @return true if the given path is located in the tail of current active path; otherwise,
655     *         false
656     */
657    static boolean isTailOfActivePath(int path, int activePath) {
658        // If active routing path is internal source, return false.
659        if (activePath == 0) {
660            return false;
661        }
662        for (int i = 12; i >= 0; i -= 4) {
663            int curActivePath = (activePath >> i) & 0xF;
664            if (curActivePath == 0) {
665                return true;
666            } else {
667                int curPath = (path >> i) & 0xF;
668                if (curPath != curActivePath) {
669                    return false;
670                }
671            }
672        }
673        return false;
674    }
675
676    @Override
677    @ServiceThreadOnly
678    protected boolean handleRoutingChange(HdmiCecMessage message) {
679        assertRunOnServiceThread();
680        // Seq #21
681        byte[] params = message.getParams();
682        int currentPath = HdmiUtils.twoBytesToInt(params);
683        if (HdmiUtils.isAffectingActiveRoutingPath(getActivePath(), currentPath)) {
684            mActiveSource.invalidate();
685            removeAction(RoutingControlAction.class);
686            int newPath = HdmiUtils.twoBytesToInt(params, 2);
687            addAndStartAction(new RoutingControlAction(this, newPath, true, null));
688        }
689        return true;
690    }
691
692    @Override
693    @ServiceThreadOnly
694    protected boolean handleReportAudioStatus(HdmiCecMessage message) {
695        assertRunOnServiceThread();
696
697        byte params[] = message.getParams();
698        int mute = params[0] & 0x80;
699        int volume = params[0] & 0x7F;
700        setAudioStatus(mute == 0x80, volume);
701        return true;
702    }
703
704    @Override
705    @ServiceThreadOnly
706    protected boolean handleTextViewOn(HdmiCecMessage message) {
707        assertRunOnServiceThread();
708        if (mService.isPowerStandbyOrTransient() && mAutoWakeup) {
709            mService.wakeUp();
710        }
711        return true;
712    }
713
714    @Override
715    @ServiceThreadOnly
716    protected boolean handleImageViewOn(HdmiCecMessage message) {
717        assertRunOnServiceThread();
718        // Currently, it's the same as <Text View On>.
719        return handleTextViewOn(message);
720    }
721
722    @Override
723    @ServiceThreadOnly
724    protected boolean handleSetOsdName(HdmiCecMessage message) {
725        int source = message.getSource();
726        HdmiDeviceInfo deviceInfo = getCecDeviceInfo(source);
727        // If the device is not in device list, ignore it.
728        if (deviceInfo == null) {
729            Slog.e(TAG, "No source device info for <Set Osd Name>." + message);
730            return true;
731        }
732        String osdName = null;
733        try {
734            osdName = new String(message.getParams(), "US-ASCII");
735        } catch (UnsupportedEncodingException e) {
736            Slog.e(TAG, "Invalid <Set Osd Name> request:" + message, e);
737            return true;
738        }
739
740        if (deviceInfo.getDisplayName().equals(osdName)) {
741            Slog.i(TAG, "Ignore incoming <Set Osd Name> having same osd name:" + message);
742            return true;
743        }
744
745        addCecDevice(new HdmiDeviceInfo(deviceInfo.getLogicalAddress(),
746                deviceInfo.getPhysicalAddress(), deviceInfo.getPortId(),
747                deviceInfo.getDeviceType(), deviceInfo.getVendorId(), osdName));
748        return true;
749    }
750
751    @ServiceThreadOnly
752    private void launchDeviceDiscovery() {
753        assertRunOnServiceThread();
754        clearDeviceInfoList();
755        DeviceDiscoveryAction action = new DeviceDiscoveryAction(this,
756                new DeviceDiscoveryCallback() {
757                    @Override
758                    public void onDeviceDiscoveryDone(List<HdmiDeviceInfo> deviceInfos) {
759                        for (HdmiDeviceInfo info : deviceInfos) {
760                            addCecDevice(info);
761                        }
762
763                        // Since we removed all devices when it's start and
764                        // device discovery action does not poll local devices,
765                        // we should put device info of local device manually here
766                        for (HdmiCecLocalDevice device : mService.getAllLocalDevices()) {
767                            addCecDevice(device.getDeviceInfo());
768                        }
769
770                        addAndStartAction(new HotplugDetectionAction(HdmiCecLocalDeviceTv.this));
771                        addAndStartAction(new PowerStatusMonitorAction(HdmiCecLocalDeviceTv.this));
772
773                        // If there is AVR, initiate System Audio Auto initiation action,
774                        // which turns on and off system audio according to last system
775                        // audio setting.
776                        HdmiDeviceInfo avr = getAvrDeviceInfo();
777                        if (avr != null) {
778                            onNewAvrAdded(avr);
779                        }
780                    }
781                });
782        addAndStartAction(action);
783    }
784
785    @ServiceThreadOnly
786    void onNewAvrAdded(HdmiDeviceInfo avr) {
787        assertRunOnServiceThread();
788        if (getSystemAudioModeSetting() && !isSystemAudioActivated()) {
789            addAndStartAction(new SystemAudioAutoInitiationAction(this, avr.getLogicalAddress()));
790        }
791        if (isArcFeatureEnabled() && !hasAction(SetArcTransmissionStateAction.class)) {
792            startArcAction(true);
793        }
794    }
795
796    // Clear all device info.
797    @ServiceThreadOnly
798    private void clearDeviceInfoList() {
799        assertRunOnServiceThread();
800        for (HdmiDeviceInfo info : mSafeExternalInputs) {
801            invokeDeviceEventListener(info, HdmiControlManager.DEVICE_EVENT_REMOVE_DEVICE);
802        }
803        mDeviceInfos.clear();
804        updateSafeDeviceInfoList();
805    }
806
807    @ServiceThreadOnly
808    // Seq #32
809    void changeSystemAudioMode(boolean enabled, IHdmiControlCallback callback) {
810        assertRunOnServiceThread();
811        if (!mService.isControlEnabled() || hasAction(DeviceDiscoveryAction.class)) {
812            setSystemAudioMode(false, true);
813            invokeCallback(callback, HdmiControlManager.RESULT_INCORRECT_MODE);
814            return;
815        }
816        HdmiDeviceInfo avr = getAvrDeviceInfo();
817        if (avr == null) {
818            setSystemAudioMode(false, true);
819            invokeCallback(callback, HdmiControlManager.RESULT_TARGET_NOT_AVAILABLE);
820            return;
821        }
822
823        addAndStartAction(
824                new SystemAudioActionFromTv(this, avr.getLogicalAddress(), enabled, callback));
825    }
826
827    // # Seq 25
828    void setSystemAudioMode(boolean on, boolean updateSetting) {
829        HdmiLogger.debug("System Audio Mode change[old:%b new:%b]", mSystemAudioActivated, on);
830
831        if (updateSetting) {
832            mService.writeBooleanSetting(Global.HDMI_SYSTEM_AUDIO_ENABLED, on);
833        }
834        updateAudioManagerForSystemAudio(on);
835        synchronized (mLock) {
836            if (mSystemAudioActivated != on) {
837                mSystemAudioActivated = on;
838                mService.announceSystemAudioModeChange(on);
839            }
840        }
841    }
842
843    private void updateAudioManagerForSystemAudio(boolean on) {
844        int device = mService.getAudioManager().setHdmiSystemAudioSupported(on);
845        HdmiLogger.debug("[A]UpdateSystemAudio mode[on=%b] output=[%X]", on, device);
846    }
847
848    boolean isSystemAudioActivated() {
849        if (!hasSystemAudioDevice()) {
850            return false;
851        }
852        synchronized (mLock) {
853            return mSystemAudioActivated;
854        }
855    }
856
857    boolean getSystemAudioModeSetting() {
858        return mService.readBooleanSetting(Global.HDMI_SYSTEM_AUDIO_ENABLED, false);
859    }
860
861    /**
862     * Change ARC status into the given {@code enabled} status.
863     *
864     * @return {@code true} if ARC was in "Enabled" status
865     */
866    @ServiceThreadOnly
867    boolean setArcStatus(boolean enabled) {
868        assertRunOnServiceThread();
869
870        HdmiLogger.debug("Set Arc Status[old:%b new:%b]", mArcEstablished, enabled);
871        boolean oldStatus = mArcEstablished;
872        // 1. Enable/disable ARC circuit.
873        mService.setAudioReturnChannel(getAvrDeviceInfo().getPortId(), enabled);
874        // 2. Notify arc status to audio service.
875        notifyArcStatusToAudioService(enabled);
876        // 3. Update arc status;
877        mArcEstablished = enabled;
878        return oldStatus;
879    }
880
881    private void notifyArcStatusToAudioService(boolean enabled) {
882        // Note that we don't set any name to ARC.
883        mService.getAudioManager().setWiredDeviceConnectionState(
884                AudioSystem.DEVICE_OUT_HDMI_ARC,
885                enabled ? 1 : 0, "");
886    }
887
888    /**
889     * Returns whether ARC is enabled or not.
890     */
891    @ServiceThreadOnly
892    boolean isArcEstabilished() {
893        assertRunOnServiceThread();
894        return mArcFeatureEnabled && mArcEstablished;
895    }
896
897    @ServiceThreadOnly
898    void changeArcFeatureEnabled(boolean enabled) {
899        assertRunOnServiceThread();
900
901        if (mArcFeatureEnabled != enabled) {
902            mArcFeatureEnabled = enabled;
903            if (enabled) {
904                if (!mArcEstablished) {
905                    startArcAction(true);
906                }
907            } else {
908                if (mArcEstablished) {
909                    startArcAction(false);
910                }
911            }
912        }
913    }
914
915    @ServiceThreadOnly
916    boolean isArcFeatureEnabled() {
917        assertRunOnServiceThread();
918        return mArcFeatureEnabled;
919    }
920
921    @ServiceThreadOnly
922    void startArcAction(boolean enabled) {
923        assertRunOnServiceThread();
924        HdmiDeviceInfo info = getAvrDeviceInfo();
925        if (info == null) {
926            Slog.w(TAG, "Failed to start arc action; No AVR device.");
927            return;
928        }
929        if (!canStartArcUpdateAction(info.getLogicalAddress(), enabled)) {
930            Slog.w(TAG, "Failed to start arc action; ARC configuration check failed.");
931            if (enabled && !isConnectedToArcPort(info.getPhysicalAddress())) {
932                displayOsd(OSD_MESSAGE_ARC_CONNECTED_INVALID_PORT);
933            }
934            return;
935        }
936
937        // Terminate opposite action and start action if not exist.
938        if (enabled) {
939            removeAction(RequestArcTerminationAction.class);
940            if (!hasAction(RequestArcInitiationAction.class)) {
941                addAndStartAction(new RequestArcInitiationAction(this, info.getLogicalAddress()));
942            }
943        } else {
944            removeAction(RequestArcInitiationAction.class);
945            if (!hasAction(RequestArcTerminationAction.class)) {
946                addAndStartAction(new RequestArcTerminationAction(this, info.getLogicalAddress()));
947            }
948        }
949    }
950
951    private boolean isDirectConnectAddress(int physicalAddress) {
952        return (physicalAddress & Constants.ROUTING_PATH_TOP_MASK) == physicalAddress;
953    }
954
955    void setAudioStatus(boolean mute, int volume) {
956        synchronized (mLock) {
957            mSystemAudioMute = mute;
958            mSystemAudioVolume = volume;
959            int maxVolume = mService.getAudioManager().getStreamMaxVolume(
960                    AudioManager.STREAM_MUSIC);
961            mService.setAudioStatus(mute,
962                    VolumeControlAction.scaleToCustomVolume(volume, maxVolume));
963            displayOsd(HdmiControlManager.OSD_MESSAGE_AVR_VOLUME_CHANGED,
964                    mute ? HdmiControlManager.AVR_VOLUME_MUTED : volume);
965        }
966    }
967
968    @ServiceThreadOnly
969    void changeVolume(int curVolume, int delta, int maxVolume) {
970        assertRunOnServiceThread();
971        if (delta == 0 || !isSystemAudioActivated()) {
972            return;
973        }
974
975        int targetVolume = curVolume + delta;
976        int cecVolume = VolumeControlAction.scaleToCecVolume(targetVolume, maxVolume);
977        synchronized (mLock) {
978            // If new volume is the same as current system audio volume, just ignore it.
979            // Note that UNKNOWN_VOLUME is not in range of cec volume scale.
980            if (cecVolume == mSystemAudioVolume) {
981                // Update tv volume with system volume value.
982                mService.setAudioStatus(false,
983                        VolumeControlAction.scaleToCustomVolume(mSystemAudioVolume, maxVolume));
984                return;
985            }
986        }
987
988        List<VolumeControlAction> actions = getActions(VolumeControlAction.class);
989        if (actions.isEmpty()) {
990            addAndStartAction(new VolumeControlAction(this,
991                    getAvrDeviceInfo().getLogicalAddress(), delta > 0));
992        } else {
993            actions.get(0).handleVolumeChange(delta > 0);
994        }
995    }
996
997    @ServiceThreadOnly
998    void changeMute(boolean mute) {
999        assertRunOnServiceThread();
1000        HdmiLogger.debug("[A]:Change mute:%b", mute);
1001        synchronized (mLock) {
1002            if (mSystemAudioMute == mute) {
1003                HdmiLogger.debug("No need to change mute.");
1004                return;
1005            }
1006        }
1007        if (!isSystemAudioActivated()) {
1008            HdmiLogger.debug("[A]:System audio is not activated.");
1009            return;
1010        }
1011
1012        // Remove existing volume action.
1013        removeAction(VolumeControlAction.class);
1014        sendUserControlPressedAndReleased(getAvrDeviceInfo().getLogicalAddress(),
1015                mute ? HdmiCecKeycode.CEC_KEYCODE_MUTE_FUNCTION :
1016                        HdmiCecKeycode.CEC_KEYCODE_RESTORE_VOLUME_FUNCTION);
1017    }
1018
1019    @Override
1020    @ServiceThreadOnly
1021    protected boolean handleInitiateArc(HdmiCecMessage message) {
1022        assertRunOnServiceThread();
1023
1024        if (!canStartArcUpdateAction(message.getSource(), true)) {
1025            if (getAvrDeviceInfo() == null) {
1026                // AVR may not have been discovered yet. Delay the message processing.
1027                mDelayedMessageBuffer.add(message);
1028                return true;
1029            }
1030            mService.maySendFeatureAbortCommand(message, Constants.ABORT_REFUSED);
1031            if (!isConnectedToArcPort(message.getSource())) {
1032                displayOsd(OSD_MESSAGE_ARC_CONNECTED_INVALID_PORT);
1033            }
1034            return true;
1035        }
1036
1037        // In case where <Initiate Arc> is started by <Request ARC Initiation>
1038        // need to clean up RequestArcInitiationAction.
1039        removeAction(RequestArcInitiationAction.class);
1040        SetArcTransmissionStateAction action = new SetArcTransmissionStateAction(this,
1041                message.getSource(), true);
1042        addAndStartAction(action);
1043        return true;
1044    }
1045
1046    private boolean canStartArcUpdateAction(int avrAddress, boolean shouldCheckArcFeatureEnabled) {
1047        HdmiDeviceInfo avr = getAvrDeviceInfo();
1048        if (avr != null
1049                && (avrAddress == avr.getLogicalAddress())
1050                && isConnectedToArcPort(avr.getPhysicalAddress())
1051                && isDirectConnectAddress(avr.getPhysicalAddress())) {
1052            if (shouldCheckArcFeatureEnabled) {
1053                return isArcFeatureEnabled();
1054            } else {
1055                return true;
1056            }
1057        } else {
1058            return false;
1059        }
1060    }
1061
1062    @Override
1063    @ServiceThreadOnly
1064    protected boolean handleTerminateArc(HdmiCecMessage message) {
1065        assertRunOnServiceThread();
1066        // In cast of termination, do not check ARC configuration in that AVR device
1067        // might be removed already.
1068
1069        // In case where <Terminate Arc> is started by <Request ARC Termination>
1070        // need to clean up RequestArcInitiationAction.
1071        removeAction(RequestArcTerminationAction.class);
1072        SetArcTransmissionStateAction action = new SetArcTransmissionStateAction(this,
1073                message.getSource(), false);
1074        addAndStartAction(action);
1075        return true;
1076    }
1077
1078    @Override
1079    @ServiceThreadOnly
1080    protected boolean handleSetSystemAudioMode(HdmiCecMessage message) {
1081        assertRunOnServiceThread();
1082        if (!isMessageForSystemAudio(message)) {
1083            if (getAvrDeviceInfo() == null) {
1084                // AVR may not have been discovered yet. Delay the message processing.
1085                mDelayedMessageBuffer.add(message);
1086                return true;
1087            }
1088            HdmiLogger.warning("Invalid <Set System Audio Mode> message:" + message);
1089            mService.maySendFeatureAbortCommand(message, Constants.ABORT_REFUSED);
1090            return true;
1091        }
1092        SystemAudioActionFromAvr action = new SystemAudioActionFromAvr(this,
1093                message.getSource(), HdmiUtils.parseCommandParamSystemAudioStatus(message), null);
1094        addAndStartAction(action);
1095        return true;
1096    }
1097
1098    @Override
1099    @ServiceThreadOnly
1100    protected boolean handleSystemAudioModeStatus(HdmiCecMessage message) {
1101        assertRunOnServiceThread();
1102        if (!isMessageForSystemAudio(message)) {
1103            HdmiLogger.warning("Invalid <System Audio Mode Status> message:" + message);
1104            // Ignore this message.
1105            return true;
1106        }
1107        setSystemAudioMode(HdmiUtils.parseCommandParamSystemAudioStatus(message), true);
1108        return true;
1109    }
1110
1111    // Seq #53
1112    @Override
1113    @ServiceThreadOnly
1114    protected boolean handleRecordTvScreen(HdmiCecMessage message) {
1115        List<OneTouchRecordAction> actions = getActions(OneTouchRecordAction.class);
1116        if (!actions.isEmpty()) {
1117            // Assumes only one OneTouchRecordAction.
1118            OneTouchRecordAction action = actions.get(0);
1119            if (action.getRecorderAddress() != message.getSource()) {
1120                announceOneTouchRecordResult(
1121                        message.getSource(),
1122                        HdmiControlManager.ONE_TOUCH_RECORD_PREVIOUS_RECORDING_IN_PROGRESS);
1123            }
1124            return super.handleRecordTvScreen(message);
1125        }
1126
1127        int recorderAddress = message.getSource();
1128        byte[] recordSource = mService.invokeRecordRequestListener(recorderAddress);
1129        int reason = startOneTouchRecord(recorderAddress, recordSource);
1130        if (reason != Constants.ABORT_NO_ERROR) {
1131            mService.maySendFeatureAbortCommand(message, reason);
1132        }
1133        return true;
1134    }
1135
1136    @Override
1137    protected boolean handleTimerClearedStatus(HdmiCecMessage message) {
1138        byte[] params = message.getParams();
1139        int timerClearedStatusData = params[0] & 0xFF;
1140        announceTimerRecordingResult(message.getSource(), timerClearedStatusData);
1141        return true;
1142    }
1143
1144    void announceOneTouchRecordResult(int recorderAddress, int result) {
1145        mService.invokeOneTouchRecordResult(recorderAddress, result);
1146    }
1147
1148    void announceTimerRecordingResult(int recorderAddress, int result) {
1149        mService.invokeTimerRecordingResult(recorderAddress, result);
1150    }
1151
1152    void announceClearTimerRecordingResult(int recorderAddress, int result) {
1153        mService.invokeClearTimerRecordingResult(recorderAddress, result);
1154    }
1155
1156    private boolean isMessageForSystemAudio(HdmiCecMessage message) {
1157        return mService.isControlEnabled()
1158                && message.getSource() == Constants.ADDR_AUDIO_SYSTEM
1159                && (message.getDestination() == Constants.ADDR_TV
1160                        || message.getDestination() == Constants.ADDR_BROADCAST)
1161                && getAvrDeviceInfo() != null;
1162    }
1163
1164    /**
1165     * Add a new {@link HdmiDeviceInfo}. It returns old device info which has the same
1166     * logical address as new device info's.
1167     *
1168     * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
1169     *
1170     * @param deviceInfo a new {@link HdmiDeviceInfo} to be added.
1171     * @return {@code null} if it is new device. Otherwise, returns old {@HdmiDeviceInfo}
1172     *         that has the same logical address as new one has.
1173     */
1174    @ServiceThreadOnly
1175    private HdmiDeviceInfo addDeviceInfo(HdmiDeviceInfo deviceInfo) {
1176        assertRunOnServiceThread();
1177        HdmiDeviceInfo oldDeviceInfo = getCecDeviceInfo(deviceInfo.getLogicalAddress());
1178        if (oldDeviceInfo != null) {
1179            removeDeviceInfo(deviceInfo.getId());
1180        }
1181        mDeviceInfos.append(deviceInfo.getId(), deviceInfo);
1182        updateSafeDeviceInfoList();
1183        return oldDeviceInfo;
1184    }
1185
1186    /**
1187     * Remove a device info corresponding to the given {@code logicalAddress}.
1188     * It returns removed {@link HdmiDeviceInfo} if exists.
1189     *
1190     * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
1191     *
1192     * @param id id of device to be removed
1193     * @return removed {@link HdmiDeviceInfo} it exists. Otherwise, returns {@code null}
1194     */
1195    @ServiceThreadOnly
1196    private HdmiDeviceInfo removeDeviceInfo(int id) {
1197        assertRunOnServiceThread();
1198        HdmiDeviceInfo deviceInfo = mDeviceInfos.get(id);
1199        if (deviceInfo != null) {
1200            mDeviceInfos.remove(id);
1201        }
1202        updateSafeDeviceInfoList();
1203        return deviceInfo;
1204    }
1205
1206    /**
1207     * Return a list of all {@link HdmiDeviceInfo}.
1208     *
1209     * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
1210     * This is not thread-safe. For thread safety, call {@link #getSafeExternalInputsLocked} which
1211     * does not include local device.
1212     */
1213    @ServiceThreadOnly
1214    List<HdmiDeviceInfo> getDeviceInfoList(boolean includeLocalDevice) {
1215        assertRunOnServiceThread();
1216        if (includeLocalDevice) {
1217            return HdmiUtils.sparseArrayToList(mDeviceInfos);
1218        } else {
1219            ArrayList<HdmiDeviceInfo> infoList = new ArrayList<>();
1220            for (int i = 0; i < mDeviceInfos.size(); ++i) {
1221                HdmiDeviceInfo info = mDeviceInfos.valueAt(i);
1222                if (!isLocalDeviceAddress(info.getLogicalAddress())) {
1223                    infoList.add(info);
1224                }
1225            }
1226            return infoList;
1227        }
1228    }
1229
1230    /**
1231     * Return external input devices.
1232     */
1233    List<HdmiDeviceInfo> getSafeExternalInputsLocked() {
1234        return mSafeExternalInputs;
1235    }
1236
1237    @ServiceThreadOnly
1238    private void updateSafeDeviceInfoList() {
1239        assertRunOnServiceThread();
1240        List<HdmiDeviceInfo> copiedDevices = HdmiUtils.sparseArrayToList(mDeviceInfos);
1241        List<HdmiDeviceInfo> externalInputs = getInputDevices();
1242        synchronized (mLock) {
1243            mSafeAllDeviceInfos = copiedDevices;
1244            mSafeExternalInputs = externalInputs;
1245        }
1246    }
1247
1248    /**
1249     * Return a list of external cec input (source) devices.
1250     *
1251     * <p>Note that this effectively excludes non-source devices like system audio,
1252     * secondary TV.
1253     */
1254    private List<HdmiDeviceInfo> getInputDevices() {
1255        ArrayList<HdmiDeviceInfo> infoList = new ArrayList<>();
1256        for (int i = 0; i < mDeviceInfos.size(); ++i) {
1257            HdmiDeviceInfo info = mDeviceInfos.valueAt(i);
1258            if (isLocalDeviceAddress(info.getLogicalAddress())) {
1259                continue;
1260            }
1261            if (info.isSourceType() && !hideDevicesBehindLegacySwitch(info)) {
1262                infoList.add(info);
1263            }
1264        }
1265        return infoList;
1266    }
1267
1268    // Check if we are hiding CEC devices connected to a legacy (non-CEC) switch.
1269    // Returns true if the policy is set to true, and the device to check does not have
1270    // a parent CEC device (which should be the CEC-enabled switch) in the list.
1271    private boolean hideDevicesBehindLegacySwitch(HdmiDeviceInfo info) {
1272        return HdmiConfig.HIDE_DEVICES_BEHIND_LEGACY_SWITCH
1273                && !isConnectedToCecSwitch(info.getPhysicalAddress(), mCecSwitches);
1274    }
1275
1276    private static boolean isConnectedToCecSwitch(int path, Collection<Integer> switches) {
1277        for (int switchPath : switches) {
1278            if (isParentPath(switchPath, path)) {
1279                return true;
1280            }
1281        }
1282        return false;
1283    }
1284
1285    private static boolean isParentPath(int parentPath, int childPath) {
1286        // (A000, AB00) (AB00, ABC0), (ABC0, ABCD)
1287        // If child's last non-zero nibble is removed, the result equals to the parent.
1288        for (int i = 0; i <= 12; i += 4) {
1289            int nibble = (childPath >> i) & 0xF;
1290            if (nibble != 0) {
1291                int parentNibble = (parentPath >> i) & 0xF;
1292                return parentNibble == 0 && (childPath >> i+4) == (parentPath >> i+4);
1293            }
1294        }
1295        return false;
1296    }
1297
1298    private void invokeDeviceEventListener(HdmiDeviceInfo info, int status) {
1299        if (!hideDevicesBehindLegacySwitch(info)) {
1300            mService.invokeDeviceEventListeners(info, status);
1301        }
1302    }
1303
1304    private boolean isLocalDeviceAddress(int address) {
1305        return mLocalDeviceAddresses.contains(address);
1306    }
1307
1308    @ServiceThreadOnly
1309    HdmiDeviceInfo getAvrDeviceInfo() {
1310        assertRunOnServiceThread();
1311        return getCecDeviceInfo(Constants.ADDR_AUDIO_SYSTEM);
1312    }
1313
1314    /**
1315     * Return a {@link HdmiDeviceInfo} corresponding to the given {@code logicalAddress}.
1316     *
1317     * This is not thread-safe. For thread safety, call {@link #getSafeCecDeviceInfo(int)}.
1318     *
1319     * @param logicalAddress logical address of the device to be retrieved
1320     * @return {@link HdmiDeviceInfo} matched with the given {@code logicalAddress}.
1321     *         Returns null if no logical address matched
1322     */
1323    @ServiceThreadOnly
1324    HdmiDeviceInfo getCecDeviceInfo(int logicalAddress) {
1325        assertRunOnServiceThread();
1326        return mDeviceInfos.get(HdmiDeviceInfo.idForCecDevice(logicalAddress));
1327    }
1328
1329    boolean hasSystemAudioDevice() {
1330        return getSafeAvrDeviceInfo() != null;
1331    }
1332
1333    HdmiDeviceInfo getSafeAvrDeviceInfo() {
1334        return getSafeCecDeviceInfo(Constants.ADDR_AUDIO_SYSTEM);
1335    }
1336
1337    /**
1338     * Thread safe version of {@link #getCecDeviceInfo(int)}.
1339     *
1340     * @param logicalAddress logical address to be retrieved
1341     * @return {@link HdmiDeviceInfo} matched with the given {@code logicalAddress}.
1342     *         Returns null if no logical address matched
1343     */
1344    HdmiDeviceInfo getSafeCecDeviceInfo(int logicalAddress) {
1345        synchronized (mLock) {
1346            for (HdmiDeviceInfo info : mSafeAllDeviceInfos) {
1347                if (info.isCecDevice() && info.getLogicalAddress() == logicalAddress) {
1348                    return info;
1349                }
1350            }
1351            return null;
1352        }
1353    }
1354
1355    List<HdmiDeviceInfo> getSafeCecDevicesLocked() {
1356        ArrayList<HdmiDeviceInfo> infoList = new ArrayList<>();
1357        for (HdmiDeviceInfo info : mSafeAllDeviceInfos) {
1358            if (isLocalDeviceAddress(info.getLogicalAddress())) {
1359                continue;
1360            }
1361            infoList.add(info);
1362        }
1363        return infoList;
1364    }
1365
1366    /**
1367     * Called when a device is newly added or a new device is detected or
1368     * existing device is updated.
1369     *
1370     * @param info device info of a new device.
1371     */
1372    @ServiceThreadOnly
1373    final void addCecDevice(HdmiDeviceInfo info) {
1374        assertRunOnServiceThread();
1375        HdmiDeviceInfo old = addDeviceInfo(info);
1376        if (info.getLogicalAddress() == mAddress) {
1377            // The addition of TV device itself should not be notified.
1378            return;
1379        }
1380        if (old == null) {
1381            invokeDeviceEventListener(info, HdmiControlManager.DEVICE_EVENT_ADD_DEVICE);
1382        } else if (!old.equals(info)) {
1383            invokeDeviceEventListener(old, HdmiControlManager.DEVICE_EVENT_REMOVE_DEVICE);
1384            invokeDeviceEventListener(info, HdmiControlManager.DEVICE_EVENT_ADD_DEVICE);
1385        }
1386    }
1387
1388    /**
1389     * Called when a device is removed or removal of device is detected.
1390     *
1391     * @param address a logical address of a device to be removed
1392     */
1393    @ServiceThreadOnly
1394    final void removeCecDevice(int address) {
1395        assertRunOnServiceThread();
1396        HdmiDeviceInfo info = removeDeviceInfo(HdmiDeviceInfo.idForCecDevice(address));
1397
1398        mCecMessageCache.flushMessagesFrom(address);
1399        invokeDeviceEventListener(info, HdmiControlManager.DEVICE_EVENT_REMOVE_DEVICE);
1400    }
1401
1402    @ServiceThreadOnly
1403    void handleRemoveActiveRoutingPath(int path) {
1404        assertRunOnServiceThread();
1405        // Seq #23
1406        if (isTailOfActivePath(path, getActivePath())) {
1407            int newPath = mService.portIdToPath(getActivePortId());
1408            startRoutingControl(getActivePath(), newPath, true, null);
1409        }
1410    }
1411
1412    /**
1413     * Launch routing control process.
1414     *
1415     * @param routingForBootup true if routing control is initiated due to One Touch Play
1416     *        or TV power on
1417     */
1418    @ServiceThreadOnly
1419    void launchRoutingControl(boolean routingForBootup) {
1420        assertRunOnServiceThread();
1421        // Seq #24
1422        if (getActivePortId() != Constants.INVALID_PORT_ID) {
1423            if (!routingForBootup && !isProhibitMode()) {
1424                int newPath = mService.portIdToPath(getActivePortId());
1425                setActivePath(newPath);
1426                startRoutingControl(getActivePath(), newPath, routingForBootup, null);
1427            }
1428        } else {
1429            int activePath = mService.getPhysicalAddress();
1430            setActivePath(activePath);
1431            if (!routingForBootup
1432                    && !mDelayedMessageBuffer.isBuffered(Constants.MESSAGE_ACTIVE_SOURCE)) {
1433                mService.sendCecCommand(HdmiCecMessageBuilder.buildActiveSource(mAddress,
1434                        activePath));
1435            }
1436        }
1437    }
1438
1439    /**
1440     * Returns the {@link HdmiDeviceInfo} instance whose physical address matches
1441     * the given routing path. CEC devices use routing path for its physical address to
1442     * describe the hierarchy of the devices in the network.
1443     *
1444     * @param path routing path or physical address
1445     * @return {@link HdmiDeviceInfo} if the matched info is found; otherwise null
1446     */
1447    @ServiceThreadOnly
1448    final HdmiDeviceInfo getDeviceInfoByPath(int path) {
1449        assertRunOnServiceThread();
1450        for (HdmiDeviceInfo info : getDeviceInfoList(false)) {
1451            if (info.getPhysicalAddress() == path) {
1452                return info;
1453            }
1454        }
1455        return null;
1456    }
1457
1458    /**
1459     * Whether a device of the specified physical address and logical address exists
1460     * in a device info list. However, both are minimal condition and it could
1461     * be different device from the original one.
1462     *
1463     * @param logicalAddress logical address of a device to be searched
1464     * @param physicalAddress physical address of a device to be searched
1465     * @return true if exist; otherwise false
1466     */
1467    @ServiceThreadOnly
1468    private boolean isInDeviceList(int logicalAddress, int physicalAddress) {
1469        assertRunOnServiceThread();
1470        HdmiDeviceInfo device = getCecDeviceInfo(logicalAddress);
1471        if (device == null) {
1472            return false;
1473        }
1474        return device.getPhysicalAddress() == physicalAddress;
1475    }
1476
1477    @Override
1478    @ServiceThreadOnly
1479    void onHotplug(int portId, boolean connected) {
1480        assertRunOnServiceThread();
1481
1482        if (!connected) {
1483            removeCecSwitches(portId);
1484        }
1485        // Tv device will have permanent HotplugDetectionAction.
1486        List<HotplugDetectionAction> hotplugActions = getActions(HotplugDetectionAction.class);
1487        if (!hotplugActions.isEmpty()) {
1488            // Note that hotplug action is single action running on a machine.
1489            // "pollAllDevicesNow" cleans up timer and start poll action immediately.
1490            // It covers seq #40, #43.
1491            hotplugActions.get(0).pollAllDevicesNow();
1492        }
1493    }
1494
1495    private void removeCecSwitches(int portId) {
1496        Iterator<Integer> it = mCecSwitches.iterator();
1497        while (!it.hasNext()) {
1498            int path = it.next();
1499            if (pathToPortId(path) == portId) {
1500                it.remove();
1501            }
1502        }
1503    }
1504
1505    @ServiceThreadOnly
1506    void setAutoDeviceOff(boolean enabled) {
1507        assertRunOnServiceThread();
1508        mAutoDeviceOff = enabled;
1509    }
1510
1511    @ServiceThreadOnly
1512    void setAutoWakeup(boolean enabled) {
1513        assertRunOnServiceThread();
1514        mAutoWakeup = enabled;
1515    }
1516
1517    @ServiceThreadOnly
1518    boolean getAutoWakeup() {
1519        assertRunOnServiceThread();
1520        return mAutoWakeup;
1521    }
1522
1523    @Override
1524    @ServiceThreadOnly
1525    protected void disableDevice(boolean initiatedByCec, PendingActionClearedCallback callback) {
1526        super.disableDevice(initiatedByCec, callback);
1527        assertRunOnServiceThread();
1528        mService.unregisterTvInputCallback(mTvInputCallback);
1529        // Remove any repeated working actions.
1530        // HotplugDetectionAction will be reinstated during the wake up process.
1531        // HdmiControlService.onWakeUp() -> initializeLocalDevices() ->
1532        //     LocalDeviceTv.onAddressAllocated() -> launchDeviceDiscovery().
1533        removeAction(DeviceDiscoveryAction.class);
1534        removeAction(HotplugDetectionAction.class);
1535        removeAction(PowerStatusMonitorAction.class);
1536        // Remove recording actions.
1537        removeAction(OneTouchRecordAction.class);
1538        removeAction(TimerRecordingAction.class);
1539
1540        disableSystemAudioIfExist();
1541        disableArcIfExist();
1542        clearDeviceInfoList();
1543        checkIfPendingActionsCleared();
1544    }
1545
1546    @ServiceThreadOnly
1547    private void disableSystemAudioIfExist() {
1548        assertRunOnServiceThread();
1549        if (getAvrDeviceInfo() == null) {
1550            return;
1551        }
1552
1553        // Seq #31.
1554        removeAction(SystemAudioActionFromAvr.class);
1555        removeAction(SystemAudioActionFromTv.class);
1556        removeAction(SystemAudioAutoInitiationAction.class);
1557        removeAction(SystemAudioStatusAction.class);
1558        removeAction(VolumeControlAction.class);
1559
1560        // Turn off the mode but do not write it the settings, so that the next time TV powers on
1561        // the system audio mode setting can be restored automatically.
1562        setSystemAudioMode(false, false);
1563    }
1564
1565    @ServiceThreadOnly
1566    private void disableArcIfExist() {
1567        assertRunOnServiceThread();
1568        HdmiDeviceInfo avr = getAvrDeviceInfo();
1569        if (avr == null) {
1570            return;
1571        }
1572
1573        // Seq #44.
1574        removeAction(RequestArcInitiationAction.class);
1575        if (!hasAction(RequestArcTerminationAction.class) && isArcEstabilished()) {
1576            addAndStartAction(new RequestArcTerminationAction(this, avr.getLogicalAddress()));
1577        }
1578    }
1579
1580    @Override
1581    @ServiceThreadOnly
1582    protected void onStandby(boolean initiatedByCec) {
1583        assertRunOnServiceThread();
1584        // Seq #11
1585        if (!mService.isControlEnabled()) {
1586            return;
1587        }
1588        if (!initiatedByCec && mAutoDeviceOff) {
1589            mService.sendCecCommand(HdmiCecMessageBuilder.buildStandby(
1590                    mAddress, Constants.ADDR_BROADCAST));
1591        }
1592    }
1593
1594    boolean isProhibitMode() {
1595        return mService.isProhibitMode();
1596    }
1597
1598    boolean isPowerStandbyOrTransient() {
1599        return mService.isPowerStandbyOrTransient();
1600    }
1601
1602    @ServiceThreadOnly
1603    void displayOsd(int messageId) {
1604        assertRunOnServiceThread();
1605        mService.displayOsd(messageId);
1606    }
1607
1608    @ServiceThreadOnly
1609    void displayOsd(int messageId, int extra) {
1610        assertRunOnServiceThread();
1611        mService.displayOsd(messageId, extra);
1612    }
1613
1614    // Seq #54 and #55
1615    @ServiceThreadOnly
1616    int startOneTouchRecord(int recorderAddress, byte[] recordSource) {
1617        assertRunOnServiceThread();
1618        if (!mService.isControlEnabled()) {
1619            Slog.w(TAG, "Can not start one touch record. CEC control is disabled.");
1620            announceOneTouchRecordResult(recorderAddress, ONE_TOUCH_RECORD_CEC_DISABLED);
1621            return Constants.ABORT_NOT_IN_CORRECT_MODE;
1622        }
1623
1624        if (!checkRecorder(recorderAddress)) {
1625            Slog.w(TAG, "Invalid recorder address:" + recorderAddress);
1626            announceOneTouchRecordResult(recorderAddress,
1627                    ONE_TOUCH_RECORD_CHECK_RECORDER_CONNECTION);
1628            return Constants.ABORT_NOT_IN_CORRECT_MODE;
1629        }
1630
1631        if (!checkRecordSource(recordSource)) {
1632            Slog.w(TAG, "Invalid record source." + Arrays.toString(recordSource));
1633            announceOneTouchRecordResult(recorderAddress,
1634                    ONE_TOUCH_RECORD_FAIL_TO_RECORD_DISPLAYED_SCREEN);
1635            return Constants.ABORT_CANNOT_PROVIDE_SOURCE;
1636        }
1637
1638        addAndStartAction(new OneTouchRecordAction(this, recorderAddress, recordSource));
1639        Slog.i(TAG, "Start new [One Touch Record]-Target:" + recorderAddress + ", recordSource:"
1640                + Arrays.toString(recordSource));
1641        return Constants.ABORT_NO_ERROR;
1642    }
1643
1644    @ServiceThreadOnly
1645    void stopOneTouchRecord(int recorderAddress) {
1646        assertRunOnServiceThread();
1647        if (!mService.isControlEnabled()) {
1648            Slog.w(TAG, "Can not stop one touch record. CEC control is disabled.");
1649            announceOneTouchRecordResult(recorderAddress, ONE_TOUCH_RECORD_CEC_DISABLED);
1650            return;
1651        }
1652
1653        if (!checkRecorder(recorderAddress)) {
1654            Slog.w(TAG, "Invalid recorder address:" + recorderAddress);
1655            announceOneTouchRecordResult(recorderAddress,
1656                    ONE_TOUCH_RECORD_CHECK_RECORDER_CONNECTION);
1657            return;
1658        }
1659
1660        // Remove one touch record action so that other one touch record can be started.
1661        removeAction(OneTouchRecordAction.class);
1662        mService.sendCecCommand(HdmiCecMessageBuilder.buildRecordOff(mAddress, recorderAddress));
1663        Slog.i(TAG, "Stop [One Touch Record]-Target:" + recorderAddress);
1664    }
1665
1666    private boolean checkRecorder(int recorderAddress) {
1667        HdmiDeviceInfo device = getCecDeviceInfo(recorderAddress);
1668        return (device != null)
1669                && (HdmiUtils.getTypeFromAddress(recorderAddress)
1670                        == HdmiDeviceInfo.DEVICE_RECORDER);
1671    }
1672
1673    private boolean checkRecordSource(byte[] recordSource) {
1674        return (recordSource != null) && HdmiRecordSources.checkRecordSource(recordSource);
1675    }
1676
1677    @ServiceThreadOnly
1678    void startTimerRecording(int recorderAddress, int sourceType, byte[] recordSource) {
1679        assertRunOnServiceThread();
1680        if (!mService.isControlEnabled()) {
1681            Slog.w(TAG, "Can not start one touch record. CEC control is disabled.");
1682            announceTimerRecordingResult(recorderAddress,
1683                    TIMER_RECORDING_RESULT_EXTRA_CEC_DISABLED);
1684            return;
1685        }
1686
1687        if (!checkRecorder(recorderAddress)) {
1688            Slog.w(TAG, "Invalid recorder address:" + recorderAddress);
1689            announceTimerRecordingResult(recorderAddress,
1690                    TIMER_RECORDING_RESULT_EXTRA_CHECK_RECORDER_CONNECTION);
1691            return;
1692        }
1693
1694        if (!checkTimerRecordingSource(sourceType, recordSource)) {
1695            Slog.w(TAG, "Invalid record source." + Arrays.toString(recordSource));
1696            announceTimerRecordingResult(
1697                    recorderAddress,
1698                    TIMER_RECORDING_RESULT_EXTRA_FAIL_TO_RECORD_SELECTED_SOURCE);
1699            return;
1700        }
1701
1702        addAndStartAction(
1703                new TimerRecordingAction(this, recorderAddress, sourceType, recordSource));
1704        Slog.i(TAG, "Start [Timer Recording]-Target:" + recorderAddress + ", SourceType:"
1705                + sourceType + ", RecordSource:" + Arrays.toString(recordSource));
1706    }
1707
1708    private boolean checkTimerRecordingSource(int sourceType, byte[] recordSource) {
1709        return (recordSource != null)
1710                && HdmiTimerRecordSources.checkTimerRecordSource(sourceType, recordSource);
1711    }
1712
1713    @ServiceThreadOnly
1714    void clearTimerRecording(int recorderAddress, int sourceType, byte[] recordSource) {
1715        assertRunOnServiceThread();
1716        if (!mService.isControlEnabled()) {
1717            Slog.w(TAG, "Can not start one touch record. CEC control is disabled.");
1718            announceClearTimerRecordingResult(recorderAddress, CLEAR_TIMER_STATUS_CEC_DISABLE);
1719            return;
1720        }
1721
1722        if (!checkRecorder(recorderAddress)) {
1723            Slog.w(TAG, "Invalid recorder address:" + recorderAddress);
1724            announceClearTimerRecordingResult(recorderAddress,
1725                    CLEAR_TIMER_STATUS_CHECK_RECORDER_CONNECTION);
1726            return;
1727        }
1728
1729        if (!checkTimerRecordingSource(sourceType, recordSource)) {
1730            Slog.w(TAG, "Invalid record source." + Arrays.toString(recordSource));
1731            announceClearTimerRecordingResult(recorderAddress,
1732                    CLEAR_TIMER_STATUS_FAIL_TO_CLEAR_SELECTED_SOURCE);
1733            return;
1734        }
1735
1736        sendClearTimerMessage(recorderAddress, sourceType, recordSource);
1737    }
1738
1739    private void sendClearTimerMessage(final int recorderAddress, int sourceType,
1740            byte[] recordSource) {
1741        HdmiCecMessage message = null;
1742        switch (sourceType) {
1743            case TIMER_RECORDING_TYPE_DIGITAL:
1744                message = HdmiCecMessageBuilder.buildClearDigitalTimer(mAddress, recorderAddress,
1745                        recordSource);
1746                break;
1747            case TIMER_RECORDING_TYPE_ANALOGUE:
1748                message = HdmiCecMessageBuilder.buildClearAnalogueTimer(mAddress, recorderAddress,
1749                        recordSource);
1750                break;
1751            case TIMER_RECORDING_TYPE_EXTERNAL:
1752                message = HdmiCecMessageBuilder.buildClearExternalTimer(mAddress, recorderAddress,
1753                        recordSource);
1754                break;
1755            default:
1756                Slog.w(TAG, "Invalid source type:" + recorderAddress);
1757                announceClearTimerRecordingResult(recorderAddress,
1758                        CLEAR_TIMER_STATUS_FAIL_TO_CLEAR_SELECTED_SOURCE);
1759                return;
1760
1761        }
1762        mService.sendCecCommand(message, new SendMessageCallback() {
1763            @Override
1764            public void onSendCompleted(int error) {
1765                if (error != Constants.SEND_RESULT_SUCCESS) {
1766                    announceClearTimerRecordingResult(recorderAddress,
1767                            CLEAR_TIMER_STATUS_FAIL_TO_CLEAR_SELECTED_SOURCE);
1768                }
1769            }
1770        });
1771    }
1772
1773    void updateDevicePowerStatus(int logicalAddress, int newPowerStatus) {
1774        HdmiDeviceInfo info = getCecDeviceInfo(logicalAddress);
1775        if (info == null) {
1776            Slog.w(TAG, "Can not update power status of non-existing device:" + logicalAddress);
1777            return;
1778        }
1779
1780        if (info.getDevicePowerStatus() == newPowerStatus) {
1781            return;
1782        }
1783
1784        HdmiDeviceInfo newInfo = HdmiUtils.cloneHdmiDeviceInfo(info, newPowerStatus);
1785        // addDeviceInfo replaces old device info with new one if exists.
1786        addDeviceInfo(newInfo);
1787
1788        invokeDeviceEventListener(newInfo, HdmiControlManager.DEVICE_EVENT_UPDATE_DEVICE);
1789    }
1790
1791    @Override
1792    protected boolean handleMenuStatus(HdmiCecMessage message) {
1793        // Do nothing and just return true not to prevent from responding <Feature Abort>.
1794        return true;
1795    }
1796
1797    @Override
1798    protected void sendStandby(int deviceId) {
1799        HdmiDeviceInfo targetDevice = mDeviceInfos.get(deviceId);
1800        if (targetDevice == null) {
1801            return;
1802        }
1803        int targetAddress = targetDevice.getLogicalAddress();
1804        mService.sendCecCommand(HdmiCecMessageBuilder.buildStandby(mAddress, targetAddress));
1805    }
1806
1807    @ServiceThreadOnly
1808    void processAllDelayedMessages() {
1809        assertRunOnServiceThread();
1810        mDelayedMessageBuffer.processAllMessages();
1811    }
1812
1813    @ServiceThreadOnly
1814    void processDelayedMessages(int address) {
1815        assertRunOnServiceThread();
1816        mDelayedMessageBuffer.processMessagesForDevice(address);
1817    }
1818
1819    @ServiceThreadOnly
1820    void processDelayedActiveSource(int address) {
1821        assertRunOnServiceThread();
1822        mDelayedMessageBuffer.processActiveSource(address);
1823    }
1824
1825    @Override
1826    protected void dump(final IndentingPrintWriter pw) {
1827        super.dump(pw);
1828        pw.println("mArcEstablished: " + mArcEstablished);
1829        pw.println("mArcFeatureEnabled: " + mArcFeatureEnabled);
1830        pw.println("mSystemAudioActivated: " + mSystemAudioActivated);
1831        pw.println("mSystemAudioMute: " + mSystemAudioMute);
1832        pw.println("mAutoDeviceOff: " + mAutoDeviceOff);
1833        pw.println("mAutoWakeup: " + mAutoWakeup);
1834        pw.println("mSkipRoutingControl: " + mSkipRoutingControl);
1835        pw.println("mPrevPortId: " + mPrevPortId);
1836        pw.println("CEC devices:");
1837        pw.increaseIndent();
1838        for (HdmiDeviceInfo info : mSafeAllDeviceInfos) {
1839            pw.println(info);
1840        }
1841        pw.decreaseIndent();
1842    }
1843}
1844