HdmiCecLocalDevice.java revision 6e26f7f7b09dfd8495ec5478a7a4713dab346bc1
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 android.hardware.hdmi.HdmiDeviceInfo;
20import android.hardware.input.InputManager;
21import android.os.Handler;
22import android.os.Looper;
23import android.os.Message;
24import android.os.SystemClock;
25import android.util.Slog;
26import android.view.InputDevice;
27import android.view.KeyCharacterMap;
28import android.view.KeyEvent;
29
30import com.android.internal.annotations.GuardedBy;
31import com.android.internal.util.IndentingPrintWriter;
32import com.android.server.hdmi.HdmiAnnotations.ServiceThreadOnly;
33
34import java.util.ArrayList;
35import java.util.Collections;
36import java.util.Iterator;
37import java.util.List;
38
39/**
40 * Class that models a logical CEC device hosted in this system. Handles initialization,
41 * CEC commands that call for actions customized per device type.
42 */
43abstract class HdmiCecLocalDevice {
44    private static final String TAG = "HdmiCecLocalDevice";
45
46    private static final int MSG_DISABLE_DEVICE_TIMEOUT = 1;
47    private static final int MSG_USER_CONTROL_RELEASE_TIMEOUT = 2;
48    // Timeout in millisecond for device clean up (5s).
49    // Normal actions timeout is 2s but some of them would have several sequence of timeout.
50    private static final int DEVICE_CLEANUP_TIMEOUT = 5000;
51    // Within the timer, a received <User Control Pressed> will start "Press and Hold" behavior.
52    // When it expires, we can assume <User Control Release> is received.
53    private static final int FOLLOWER_SAFETY_TIMEOUT = 550;
54
55    protected final HdmiControlService mService;
56    protected final int mDeviceType;
57    protected int mAddress;
58    protected int mPreferredAddress;
59    protected HdmiDeviceInfo mDeviceInfo;
60    protected int mLastKeycode = HdmiCecKeycode.UNSUPPORTED_KEYCODE;
61    protected int mLastKeyRepeatCount = 0;
62
63    static class ActiveSource {
64        int logicalAddress;
65        int physicalAddress;
66
67        public ActiveSource() {
68            invalidate();
69        }
70        public ActiveSource(int logical, int physical) {
71            logicalAddress = logical;
72            physicalAddress = physical;
73        }
74        public static ActiveSource of(int logical, int physical) {
75            return new ActiveSource(logical, physical);
76        }
77        public boolean isValid() {
78            return HdmiUtils.isValidAddress(logicalAddress);
79        }
80        public void invalidate() {
81            logicalAddress = Constants.ADDR_INVALID;
82            physicalAddress = Constants.INVALID_PHYSICAL_ADDRESS;
83        }
84        public boolean equals(int logical, int physical) {
85            return logicalAddress == logical && physicalAddress == physical;
86        }
87        @Override
88        public boolean equals(Object obj) {
89            if (obj instanceof ActiveSource) {
90                ActiveSource that = (ActiveSource) obj;
91                return that.logicalAddress == logicalAddress &&
92                       that.physicalAddress == physicalAddress;
93            }
94            return false;
95        }
96        @Override
97        public int hashCode() {
98            return logicalAddress * 29 + physicalAddress;
99        }
100        @Override
101        public String toString() {
102            StringBuffer s = new StringBuffer();
103            String logicalAddressString = (logicalAddress == Constants.ADDR_INVALID)
104                    ? "invalid" : String.format("0x%02x", logicalAddress);
105            s.append("logical_address: ").append(logicalAddressString);
106            String physicalAddressString = (physicalAddress == Constants.INVALID_PHYSICAL_ADDRESS)
107                    ? "invalid" : String.format("0x%04x", physicalAddress);
108            s.append(", physical_address: ").append(physicalAddressString);
109            return s.toString();
110        }
111    }
112    // Logical address of the active source.
113    @GuardedBy("mLock")
114    protected final ActiveSource mActiveSource = new ActiveSource();
115
116    // Active routing path. Physical address of the active source but not all the time, such as
117    // when the new active source does not claim itself to be one. Note that we don't keep
118    // the active port id (or active input) since it can be gotten by {@link #pathToPortId(int)}.
119    @GuardedBy("mLock")
120    private int mActiveRoutingPath;
121
122    protected final HdmiCecMessageCache mCecMessageCache = new HdmiCecMessageCache();
123    protected final Object mLock;
124
125    // A collection of FeatureAction.
126    // Note that access to this collection should happen in service thread.
127    private final ArrayList<HdmiCecFeatureAction> mActions = new ArrayList<>();
128
129    private final Handler mHandler = new Handler () {
130        @Override
131        public void handleMessage(Message msg) {
132            switch (msg.what) {
133                case MSG_DISABLE_DEVICE_TIMEOUT:
134                    handleDisableDeviceTimeout();
135                    break;
136                case MSG_USER_CONTROL_RELEASE_TIMEOUT:
137                    handleUserControlReleased();
138                    break;
139            }
140        }
141    };
142
143    /**
144     * A callback interface to get notified when all pending action is cleared.
145     * It can be called when timeout happened.
146     */
147    interface PendingActionClearedCallback {
148        void onCleared(HdmiCecLocalDevice device);
149    }
150
151    protected PendingActionClearedCallback mPendingActionClearedCallback;
152
153    protected HdmiCecLocalDevice(HdmiControlService service, int deviceType) {
154        mService = service;
155        mDeviceType = deviceType;
156        mAddress = Constants.ADDR_UNREGISTERED;
157        mLock = service.getServiceLock();
158    }
159
160    // Factory method that returns HdmiCecLocalDevice of corresponding type.
161    static HdmiCecLocalDevice create(HdmiControlService service, int deviceType) {
162        switch (deviceType) {
163        case HdmiDeviceInfo.DEVICE_TV:
164            return new HdmiCecLocalDeviceTv(service);
165        case HdmiDeviceInfo.DEVICE_PLAYBACK:
166            return new HdmiCecLocalDevicePlayback(service);
167        default:
168            return null;
169        }
170    }
171
172    @ServiceThreadOnly
173    void init() {
174        assertRunOnServiceThread();
175        mPreferredAddress = getPreferredAddress();
176    }
177
178    /**
179     * Called once a logical address of the local device is allocated.
180     */
181    protected abstract void onAddressAllocated(int logicalAddress, int reason);
182
183    /**
184     * Get the preferred logical address from system properties.
185     */
186    protected abstract int getPreferredAddress();
187
188    /**
189     * Set the preferred logical address to system properties.
190     */
191    protected abstract void setPreferredAddress(int addr);
192
193    /**
194     * Returns true if the TV input associated with the CEC device is ready
195     * to accept further processing such as input switching. This is used
196     * to buffer certain CEC commands and process it later if the input is not
197     * ready yet. For other types of local devices(non-TV), this method returns
198     * true by default to let the commands be processed right away.
199     */
200    protected boolean isInputReady(int deviceId) {
201        return true;
202    }
203
204    /**
205     * Dispatch incoming message.
206     *
207     * @param message incoming message
208     * @return true if consumed a message; otherwise, return false.
209     */
210    @ServiceThreadOnly
211    boolean dispatchMessage(HdmiCecMessage message) {
212        assertRunOnServiceThread();
213        int dest = message.getDestination();
214        if (dest != mAddress && dest != Constants.ADDR_BROADCAST) {
215            return false;
216        }
217        // Cache incoming message. Note that it caches only white-listed one.
218        mCecMessageCache.cacheMessage(message);
219        return onMessage(message);
220    }
221
222    @ServiceThreadOnly
223    protected final boolean onMessage(HdmiCecMessage message) {
224        assertRunOnServiceThread();
225        if (dispatchMessageToAction(message)) {
226            return true;
227        }
228        switch (message.getOpcode()) {
229            case Constants.MESSAGE_ACTIVE_SOURCE:
230                return handleActiveSource(message);
231            case Constants.MESSAGE_INACTIVE_SOURCE:
232                return handleInactiveSource(message);
233            case Constants.MESSAGE_REQUEST_ACTIVE_SOURCE:
234                return handleRequestActiveSource(message);
235            case Constants.MESSAGE_GET_MENU_LANGUAGE:
236                return handleGetMenuLanguage(message);
237            case Constants.MESSAGE_GIVE_PHYSICAL_ADDRESS:
238                return handleGivePhysicalAddress();
239            case Constants.MESSAGE_GIVE_OSD_NAME:
240                return handleGiveOsdName(message);
241            case Constants.MESSAGE_GIVE_DEVICE_VENDOR_ID:
242                return handleGiveDeviceVendorId();
243            case Constants.MESSAGE_GET_CEC_VERSION:
244                return handleGetCecVersion(message);
245            case Constants.MESSAGE_REPORT_PHYSICAL_ADDRESS:
246                return handleReportPhysicalAddress(message);
247            case Constants.MESSAGE_ROUTING_CHANGE:
248                return handleRoutingChange(message);
249            case Constants.MESSAGE_ROUTING_INFORMATION:
250                return handleRoutingInformation(message);
251            case Constants.MESSAGE_INITIATE_ARC:
252                return handleInitiateArc(message);
253            case Constants.MESSAGE_TERMINATE_ARC:
254                return handleTerminateArc(message);
255            case Constants.MESSAGE_SET_SYSTEM_AUDIO_MODE:
256                return handleSetSystemAudioMode(message);
257            case Constants.MESSAGE_SYSTEM_AUDIO_MODE_STATUS:
258                return handleSystemAudioModeStatus(message);
259            case Constants.MESSAGE_REPORT_AUDIO_STATUS:
260                return handleReportAudioStatus(message);
261            case Constants.MESSAGE_STANDBY:
262                return handleStandby(message);
263            case Constants.MESSAGE_TEXT_VIEW_ON:
264                return handleTextViewOn(message);
265            case Constants.MESSAGE_IMAGE_VIEW_ON:
266                return handleImageViewOn(message);
267            case Constants.MESSAGE_USER_CONTROL_PRESSED:
268                return handleUserControlPressed(message);
269            case Constants.MESSAGE_USER_CONTROL_RELEASED:
270                return handleUserControlReleased();
271            case Constants.MESSAGE_SET_STREAM_PATH:
272                return handleSetStreamPath(message);
273            case Constants.MESSAGE_GIVE_DEVICE_POWER_STATUS:
274                return handleGiveDevicePowerStatus(message);
275            case Constants.MESSAGE_MENU_REQUEST:
276                return handleMenuRequest(message);
277            case Constants.MESSAGE_MENU_STATUS:
278                return handleMenuStatus(message);
279            case Constants.MESSAGE_VENDOR_COMMAND:
280                return handleVendorCommand(message);
281            case Constants.MESSAGE_VENDOR_COMMAND_WITH_ID:
282                return handleVendorCommandWithId(message);
283            case Constants.MESSAGE_SET_OSD_NAME:
284                return handleSetOsdName(message);
285            case Constants.MESSAGE_RECORD_TV_SCREEN:
286                return handleRecordTvScreen(message);
287            case Constants.MESSAGE_TIMER_CLEARED_STATUS:
288                return handleTimerClearedStatus(message);
289            case Constants.MESSAGE_REPORT_POWER_STATUS:
290                return handleReportPowerStatus(message);
291            case Constants.MESSAGE_TIMER_STATUS:
292                return handleTimerStatus(message);
293            case Constants.MESSAGE_RECORD_STATUS:
294                return handleRecordStatus(message);
295            default:
296                return false;
297        }
298    }
299
300    @ServiceThreadOnly
301    private boolean dispatchMessageToAction(HdmiCecMessage message) {
302        assertRunOnServiceThread();
303        boolean processed = false;
304        // Use copied action list in that processCommand may remove itself.
305        for (HdmiCecFeatureAction action : new ArrayList<>(mActions)) {
306            // Iterates all actions to check whether incoming message is consumed.
307            boolean result = action.processCommand(message);
308            processed = processed || result;
309        }
310        return processed;
311    }
312
313    @ServiceThreadOnly
314    protected boolean handleGivePhysicalAddress() {
315        assertRunOnServiceThread();
316
317        int physicalAddress = mService.getPhysicalAddress();
318        HdmiCecMessage cecMessage = HdmiCecMessageBuilder.buildReportPhysicalAddressCommand(
319                mAddress, physicalAddress, mDeviceType);
320        mService.sendCecCommand(cecMessage);
321        return true;
322    }
323
324    @ServiceThreadOnly
325    protected boolean handleGiveDeviceVendorId() {
326        assertRunOnServiceThread();
327        int vendorId = mService.getVendorId();
328        HdmiCecMessage cecMessage = HdmiCecMessageBuilder.buildDeviceVendorIdCommand(
329                mAddress, vendorId);
330        mService.sendCecCommand(cecMessage);
331        return true;
332    }
333
334    @ServiceThreadOnly
335    protected boolean handleGetCecVersion(HdmiCecMessage message) {
336        assertRunOnServiceThread();
337        int version = mService.getCecVersion();
338        HdmiCecMessage cecMessage = HdmiCecMessageBuilder.buildCecVersion(message.getDestination(),
339                message.getSource(), version);
340        mService.sendCecCommand(cecMessage);
341        return true;
342    }
343
344    @ServiceThreadOnly
345    protected boolean handleActiveSource(HdmiCecMessage message) {
346        return false;
347    }
348
349    @ServiceThreadOnly
350    protected boolean handleInactiveSource(HdmiCecMessage message) {
351        return false;
352    }
353
354    @ServiceThreadOnly
355    protected boolean handleRequestActiveSource(HdmiCecMessage message) {
356        return false;
357    }
358
359    @ServiceThreadOnly
360    protected boolean handleGetMenuLanguage(HdmiCecMessage message) {
361        assertRunOnServiceThread();
362        Slog.w(TAG, "Only TV can handle <Get Menu Language>:" + message.toString());
363        // 'return false' will cause to reply with <Feature Abort>.
364        return false;
365    }
366
367    @ServiceThreadOnly
368    protected boolean handleGiveOsdName(HdmiCecMessage message) {
369        assertRunOnServiceThread();
370        // Note that since this method is called after logical address allocation is done,
371        // mDeviceInfo should not be null.
372        HdmiCecMessage cecMessage = HdmiCecMessageBuilder.buildSetOsdNameCommand(
373                mAddress, message.getSource(), mDeviceInfo.getDisplayName());
374        if (cecMessage != null) {
375            mService.sendCecCommand(cecMessage);
376        } else {
377            Slog.w(TAG, "Failed to build <Get Osd Name>:" + mDeviceInfo.getDisplayName());
378        }
379        return true;
380    }
381
382    protected boolean handleRoutingChange(HdmiCecMessage message) {
383        return false;
384    }
385
386    protected boolean handleRoutingInformation(HdmiCecMessage message) {
387        return false;
388    }
389
390    protected boolean handleReportPhysicalAddress(HdmiCecMessage message) {
391        return false;
392    }
393
394    protected boolean handleSystemAudioModeStatus(HdmiCecMessage message) {
395        return false;
396    }
397
398    protected boolean handleSetSystemAudioMode(HdmiCecMessage message) {
399        return false;
400    }
401
402    protected boolean handleTerminateArc(HdmiCecMessage message) {
403        return false;
404    }
405
406    protected boolean handleInitiateArc(HdmiCecMessage message) {
407        return false;
408    }
409
410    protected boolean handleReportAudioStatus(HdmiCecMessage message) {
411        return false;
412    }
413
414    @ServiceThreadOnly
415    protected boolean handleStandby(HdmiCecMessage message) {
416        assertRunOnServiceThread();
417        // Seq #12
418        if (mService.isControlEnabled() && !mService.isProhibitMode()
419                && mService.isPowerOnOrTransient()) {
420            mService.standby();
421            return true;
422        }
423        return false;
424    }
425
426    @ServiceThreadOnly
427    protected boolean handleUserControlPressed(HdmiCecMessage message) {
428        assertRunOnServiceThread();
429        mHandler.removeMessages(MSG_USER_CONTROL_RELEASE_TIMEOUT);
430        if (mService.isPowerOnOrTransient() && isPowerOffOrToggleCommand(message)) {
431            mService.standby();
432            return true;
433        } else if (mService.isPowerStandbyOrTransient() && isPowerOnOrToggleCommand(message)) {
434            mService.wakeUp();
435            return true;
436        }
437
438        final long downTime = SystemClock.uptimeMillis();
439        final byte[] params = message.getParams();
440        final int keycode = HdmiCecKeycode.cecKeycodeAndParamsToAndroidKey(params);
441        int keyRepeatCount = 0;
442        if (mLastKeycode != HdmiCecKeycode.UNSUPPORTED_KEYCODE) {
443            if (keycode == mLastKeycode) {
444                keyRepeatCount = mLastKeyRepeatCount + 1;
445            } else {
446                injectKeyEvent(downTime, KeyEvent.ACTION_UP, mLastKeycode, 0);
447            }
448        }
449        mLastKeycode = keycode;
450        mLastKeyRepeatCount = keyRepeatCount;
451
452        if (keycode != HdmiCecKeycode.UNSUPPORTED_KEYCODE) {
453            injectKeyEvent(downTime, KeyEvent.ACTION_DOWN, keycode, keyRepeatCount);
454            mHandler.sendMessageDelayed(Message.obtain(mHandler, MSG_USER_CONTROL_RELEASE_TIMEOUT),
455                    FOLLOWER_SAFETY_TIMEOUT);
456            return true;
457        }
458        return false;
459    }
460
461    @ServiceThreadOnly
462    protected boolean handleUserControlReleased() {
463        assertRunOnServiceThread();
464        mHandler.removeMessages(MSG_USER_CONTROL_RELEASE_TIMEOUT);
465        mLastKeyRepeatCount = 0;
466        if (mLastKeycode != HdmiCecKeycode.UNSUPPORTED_KEYCODE) {
467            final long upTime = SystemClock.uptimeMillis();
468            injectKeyEvent(upTime, KeyEvent.ACTION_UP, mLastKeycode, 0);
469            mLastKeycode = HdmiCecKeycode.UNSUPPORTED_KEYCODE;
470            return true;
471        }
472        return false;
473    }
474
475    static void injectKeyEvent(long time, int action, int keycode, int repeat) {
476        KeyEvent keyEvent = KeyEvent.obtain(time, time, action, keycode,
477                repeat, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FROM_SYSTEM,
478                InputDevice.SOURCE_HDMI, null);
479        InputManager.getInstance().injectInputEvent(keyEvent,
480                InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
481        keyEvent.recycle();
482   }
483
484    static boolean isPowerOnOrToggleCommand(HdmiCecMessage message) {
485        byte[] params = message.getParams();
486        return message.getOpcode() == Constants.MESSAGE_USER_CONTROL_PRESSED
487                && (params[0] == HdmiCecKeycode.CEC_KEYCODE_POWER
488                        || params[0] == HdmiCecKeycode.CEC_KEYCODE_POWER_ON_FUNCTION
489                        || params[0] == HdmiCecKeycode.CEC_KEYCODE_POWER_TOGGLE_FUNCTION);
490    }
491
492    static boolean isPowerOffOrToggleCommand(HdmiCecMessage message) {
493        byte[] params = message.getParams();
494        return message.getOpcode() == Constants.MESSAGE_USER_CONTROL_PRESSED
495                && (params[0] == HdmiCecKeycode.CEC_KEYCODE_POWER
496                        || params[0] == HdmiCecKeycode.CEC_KEYCODE_POWER_OFF_FUNCTION
497                        || params[0] == HdmiCecKeycode.CEC_KEYCODE_POWER_TOGGLE_FUNCTION);
498    }
499
500    protected boolean handleTextViewOn(HdmiCecMessage message) {
501        return false;
502    }
503
504    protected boolean handleImageViewOn(HdmiCecMessage message) {
505        return false;
506    }
507
508    protected boolean handleSetStreamPath(HdmiCecMessage message) {
509        return false;
510    }
511
512    protected boolean handleGiveDevicePowerStatus(HdmiCecMessage message) {
513        mService.sendCecCommand(HdmiCecMessageBuilder.buildReportPowerStatus(
514                mAddress, message.getSource(), mService.getPowerStatus()));
515        return true;
516    }
517
518    protected boolean handleMenuRequest(HdmiCecMessage message) {
519        // Always report menu active to receive Remote Control.
520        mService.sendCecCommand(HdmiCecMessageBuilder.buildReportMenuStatus(
521                mAddress, message.getSource(), Constants.MENU_STATE_ACTIVATED));
522        return true;
523    }
524
525    protected boolean handleMenuStatus(HdmiCecMessage message) {
526        return false;
527    }
528
529    protected boolean handleVendorCommand(HdmiCecMessage message) {
530        if (!mService.invokeVendorCommandListenersOnReceived(mDeviceType, message.getSource(),
531                message.getDestination(), message.getParams(), false)) {
532            // Vendor command listener may not have been registered yet. Respond with
533            // <Feature Abort> [NOT_IN_CORRECT_MODE] so that the sender can try again later.
534            mService.maySendFeatureAbortCommand(message, Constants.ABORT_NOT_IN_CORRECT_MODE);
535        }
536        return true;
537    }
538
539    protected boolean handleVendorCommandWithId(HdmiCecMessage message) {
540        byte[] params = message.getParams();
541        int vendorId = HdmiUtils.threeBytesToInt(params);
542        if (vendorId == mService.getVendorId()) {
543            if (!mService.invokeVendorCommandListenersOnReceived(mDeviceType, message.getSource(),
544                    message.getDestination(), params, true)) {
545                mService.maySendFeatureAbortCommand(message, Constants.ABORT_NOT_IN_CORRECT_MODE);
546            }
547        } else if (message.getDestination() != Constants.ADDR_BROADCAST &&
548                message.getSource() != Constants.ADDR_UNREGISTERED) {
549            Slog.v(TAG, "Wrong direct vendor command. Replying with <Feature Abort>");
550            mService.maySendFeatureAbortCommand(message, Constants.ABORT_UNRECOGNIZED_OPCODE);
551        } else {
552            Slog.v(TAG, "Wrong broadcast vendor command. Ignoring");
553        }
554        return true;
555    }
556
557    protected void sendStandby(int deviceId) {
558        // Do nothing.
559    }
560
561    protected boolean handleSetOsdName(HdmiCecMessage message) {
562        // The default behavior of <Set Osd Name> is doing nothing.
563        return true;
564    }
565
566    protected boolean handleRecordTvScreen(HdmiCecMessage message) {
567        // The default behavior of <Record TV Screen> is replying <Feature Abort> with
568        // "Cannot provide source".
569        mService.maySendFeatureAbortCommand(message, Constants.ABORT_CANNOT_PROVIDE_SOURCE);
570        return true;
571    }
572
573    protected boolean handleTimerClearedStatus(HdmiCecMessage message) {
574        return false;
575    }
576
577    protected boolean handleReportPowerStatus(HdmiCecMessage message) {
578        return false;
579    }
580
581    protected boolean handleTimerStatus(HdmiCecMessage message) {
582        return false;
583    }
584
585    protected boolean handleRecordStatus(HdmiCecMessage message) {
586        return false;
587    }
588
589    @ServiceThreadOnly
590    final void handleAddressAllocated(int logicalAddress, int reason) {
591        assertRunOnServiceThread();
592        mAddress = mPreferredAddress = logicalAddress;
593        onAddressAllocated(logicalAddress, reason);
594        setPreferredAddress(logicalAddress);
595    }
596
597    int getType() {
598        return mDeviceType;
599    }
600
601    @ServiceThreadOnly
602    HdmiDeviceInfo getDeviceInfo() {
603        assertRunOnServiceThread();
604        return mDeviceInfo;
605    }
606
607    @ServiceThreadOnly
608    void setDeviceInfo(HdmiDeviceInfo info) {
609        assertRunOnServiceThread();
610        mDeviceInfo = info;
611    }
612
613    // Returns true if the logical address is same as the argument.
614    @ServiceThreadOnly
615    boolean isAddressOf(int addr) {
616        assertRunOnServiceThread();
617        return addr == mAddress;
618    }
619
620    // Resets the logical address to unregistered(15), meaning the logical device is invalid.
621    @ServiceThreadOnly
622    void clearAddress() {
623        assertRunOnServiceThread();
624        mAddress = Constants.ADDR_UNREGISTERED;
625    }
626
627    @ServiceThreadOnly
628    void addAndStartAction(final HdmiCecFeatureAction action) {
629        assertRunOnServiceThread();
630        mActions.add(action);
631        if (mService.isPowerStandbyOrTransient()) {
632            Slog.i(TAG, "Not ready to start action. Queued for deferred start:" + action);
633            return;
634        }
635        action.start();
636    }
637
638    @ServiceThreadOnly
639    void startQueuedActions() {
640        assertRunOnServiceThread();
641        for (HdmiCecFeatureAction action : mActions) {
642            if (!action.started()) {
643                Slog.i(TAG, "Starting queued action:" + action);
644                action.start();
645            }
646        }
647    }
648
649    // See if we have an action of a given type in progress.
650    @ServiceThreadOnly
651    <T extends HdmiCecFeatureAction> boolean hasAction(final Class<T> clazz) {
652        assertRunOnServiceThread();
653        for (HdmiCecFeatureAction action : mActions) {
654            if (action.getClass().equals(clazz)) {
655                return true;
656            }
657        }
658        return false;
659    }
660
661    // Returns all actions matched with given class type.
662    @ServiceThreadOnly
663    <T extends HdmiCecFeatureAction> List<T> getActions(final Class<T> clazz) {
664        assertRunOnServiceThread();
665        List<T> actions = Collections.<T>emptyList();
666        for (HdmiCecFeatureAction action : mActions) {
667            if (action.getClass().equals(clazz)) {
668                if (actions.isEmpty()) {
669                    actions = new ArrayList<T>();
670                }
671                actions.add((T) action);
672            }
673        }
674        return actions;
675    }
676
677    /**
678     * Remove the given {@link HdmiCecFeatureAction} object from the action queue.
679     *
680     * @param action {@link HdmiCecFeatureAction} to remove
681     */
682    @ServiceThreadOnly
683    void removeAction(final HdmiCecFeatureAction action) {
684        assertRunOnServiceThread();
685        action.finish(false);
686        mActions.remove(action);
687        checkIfPendingActionsCleared();
688    }
689
690    // Remove all actions matched with the given Class type.
691    @ServiceThreadOnly
692    <T extends HdmiCecFeatureAction> void removeAction(final Class<T> clazz) {
693        assertRunOnServiceThread();
694        removeActionExcept(clazz, null);
695    }
696
697    // Remove all actions matched with the given Class type besides |exception|.
698    @ServiceThreadOnly
699    <T extends HdmiCecFeatureAction> void removeActionExcept(final Class<T> clazz,
700            final HdmiCecFeatureAction exception) {
701        assertRunOnServiceThread();
702        Iterator<HdmiCecFeatureAction> iter = mActions.iterator();
703        while (iter.hasNext()) {
704            HdmiCecFeatureAction action = iter.next();
705            if (action != exception && action.getClass().equals(clazz)) {
706                action.finish(false);
707                iter.remove();
708            }
709        }
710        checkIfPendingActionsCleared();
711    }
712
713    protected void checkIfPendingActionsCleared() {
714        if (mActions.isEmpty() && mPendingActionClearedCallback != null) {
715            PendingActionClearedCallback callback = mPendingActionClearedCallback;
716            // To prevent from calling the callback again during handling the callback itself.
717            mPendingActionClearedCallback = null;
718            callback.onCleared(this);
719        }
720    }
721
722    protected void assertRunOnServiceThread() {
723        if (Looper.myLooper() != mService.getServiceLooper()) {
724            throw new IllegalStateException("Should run on service thread.");
725        }
726    }
727
728    /**
729     * Called when a hot-plug event issued.
730     *
731     * @param portId id of port where a hot-plug event happened
732     * @param connected whether to connected or not on the event
733     */
734    void onHotplug(int portId, boolean connected) {
735    }
736
737    final HdmiControlService getService() {
738        return mService;
739    }
740
741    @ServiceThreadOnly
742    final boolean isConnectedToArcPort(int path) {
743        assertRunOnServiceThread();
744        return mService.isConnectedToArcPort(path);
745    }
746
747    ActiveSource getActiveSource() {
748        synchronized (mLock) {
749            return mActiveSource;
750        }
751    }
752
753    void setActiveSource(ActiveSource newActive) {
754        setActiveSource(newActive.logicalAddress, newActive.physicalAddress);
755    }
756
757    void setActiveSource(HdmiDeviceInfo info) {
758        setActiveSource(info.getLogicalAddress(), info.getPhysicalAddress());
759    }
760
761    void setActiveSource(int logicalAddress, int physicalAddress) {
762        synchronized (mLock) {
763            mActiveSource.logicalAddress = logicalAddress;
764            mActiveSource.physicalAddress = physicalAddress;
765        }
766        mService.setLastInputForMhl(Constants.INVALID_PORT_ID);
767    }
768
769    int getActivePath() {
770        synchronized (mLock) {
771            return mActiveRoutingPath;
772        }
773    }
774
775    void setActivePath(int path) {
776        synchronized (mLock) {
777            mActiveRoutingPath = path;
778        }
779        mService.setActivePortId(pathToPortId(path));
780    }
781
782    /**
783     * Returns the ID of the active HDMI port. The active port is the one that has the active
784     * routing path connected to it directly or indirectly under the device hierarchy.
785     */
786    int getActivePortId() {
787        synchronized (mLock) {
788            return mService.pathToPortId(mActiveRoutingPath);
789        }
790    }
791
792    /**
793     * Update the active port.
794     *
795     * @param portId the new active port id
796     */
797    void setActivePortId(int portId) {
798        // We update active routing path instead, since we get the active port id from
799        // the active routing path.
800        setActivePath(mService.portIdToPath(portId));
801    }
802
803    @ServiceThreadOnly
804    HdmiCecMessageCache getCecMessageCache() {
805        assertRunOnServiceThread();
806        return mCecMessageCache;
807    }
808
809    @ServiceThreadOnly
810    int pathToPortId(int newPath) {
811        assertRunOnServiceThread();
812        return mService.pathToPortId(newPath);
813    }
814
815    /**
816     * Called when the system goes to standby mode.
817     *
818     * @param initiatedByCec true if this power sequence is initiated
819     *        by the reception the CEC messages like &lt;Standby&gt;
820     */
821    protected void onStandby(boolean initiatedByCec) {}
822
823    /**
824     * Disable device. {@code callback} is used to get notified when all pending
825     * actions are completed or timeout is issued.
826     *
827     * @param initiatedByCec true if this sequence is initiated
828     *        by the reception the CEC messages like &lt;Standby&gt;
829     * @param origialCallback callback interface to get notified when all pending actions are
830     *        cleared
831     */
832    protected void disableDevice(boolean initiatedByCec,
833            final PendingActionClearedCallback origialCallback) {
834        mPendingActionClearedCallback = new PendingActionClearedCallback() {
835            @Override
836            public void onCleared(HdmiCecLocalDevice device) {
837                mHandler.removeMessages(MSG_DISABLE_DEVICE_TIMEOUT);
838                origialCallback.onCleared(device);
839            }
840        };
841        mHandler.sendMessageDelayed(Message.obtain(mHandler, MSG_DISABLE_DEVICE_TIMEOUT),
842                DEVICE_CLEANUP_TIMEOUT);
843    }
844
845    @ServiceThreadOnly
846    private void handleDisableDeviceTimeout() {
847        assertRunOnServiceThread();
848
849        // If all actions are not cleared in DEVICE_CLEANUP_TIMEOUT, enforce to finish them.
850        // onCleard will be called at the last action's finish method.
851        Iterator<HdmiCecFeatureAction> iter = mActions.iterator();
852        while (iter.hasNext()) {
853            HdmiCecFeatureAction action = iter.next();
854            action.finish(false);
855            iter.remove();
856        }
857    }
858
859    /**
860     * Send a key event to other device.
861     *
862     * @param keyCode key code defined in {@link android.view.KeyEvent}
863     * @param isPressed {@code true} for key down event
864     */
865    protected void sendKeyEvent(int keyCode, boolean isPressed) {
866        Slog.w(TAG, "sendKeyEvent not implemented");
867    }
868
869    void sendUserControlPressedAndReleased(int targetAddress, int cecKeycode) {
870        mService.sendCecCommand(HdmiCecMessageBuilder.buildUserControlPressed(
871                mAddress, targetAddress, cecKeycode));
872        mService.sendCecCommand(HdmiCecMessageBuilder.buildUserControlReleased(
873                mAddress, targetAddress));
874    }
875
876    /**
877     * Dump internal status of HdmiCecLocalDevice object.
878     */
879    protected void dump(final IndentingPrintWriter pw) {
880        pw.println("mDeviceType: " + mDeviceType);
881        pw.println("mAddress: " + mAddress);
882        pw.println("mPreferredAddress: " + mPreferredAddress);
883        pw.println("mDeviceInfo: " + mDeviceInfo);
884        pw.println("mActiveSource: " + mActiveSource);
885        pw.println(String.format("mActiveRoutingPath: 0x%04x", mActiveRoutingPath));
886    }
887}
888