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