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