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