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