HdmiControlService.java revision a9f10629f4bc1a82761917645ff4d2b6d42e47b3
1/* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.hdmi; 18 19import android.annotation.Nullable; 20import android.content.BroadcastReceiver; 21import android.content.ContentResolver; 22import android.content.Context; 23import android.content.Intent; 24import android.content.IntentFilter; 25import android.hardware.hdmi.HdmiCecDeviceInfo; 26import android.hardware.hdmi.HdmiControlManager; 27import android.hardware.hdmi.HdmiHotplugEvent; 28import android.hardware.hdmi.HdmiPortInfo; 29import android.hardware.hdmi.HdmiTvClient; 30import android.hardware.hdmi.IHdmiControlCallback; 31import android.hardware.hdmi.IHdmiControlService; 32import android.hardware.hdmi.IHdmiDeviceEventListener; 33import android.hardware.hdmi.IHdmiHotplugEventListener; 34import android.hardware.hdmi.IHdmiInputChangeListener; 35import android.hardware.hdmi.IHdmiSystemAudioModeChangeListener; 36import android.hardware.hdmi.IHdmiVendorCommandListener; 37import android.media.AudioManager; 38import android.os.Build; 39import android.os.Handler; 40import android.os.HandlerThread; 41import android.os.IBinder; 42import android.os.Looper; 43import android.os.PowerManager; 44import android.os.RemoteException; 45import android.os.SystemClock; 46import android.provider.Settings.Global; 47import android.provider.Settings.SettingNotFoundException; 48import android.util.Slog; 49import android.util.SparseArray; 50import android.util.SparseIntArray; 51 52import com.android.internal.annotations.GuardedBy; 53import com.android.server.SystemService; 54import com.android.server.hdmi.HdmiAnnotations.ServiceThreadOnly; 55import com.android.server.hdmi.HdmiCecController.AllocateAddressCallback; 56import com.android.server.hdmi.HdmiCecLocalDevice.PendingActionClearedCallback; 57 58import java.util.ArrayList; 59import java.util.Collections; 60import java.util.List; 61 62/** 63 * Provides a service for sending and processing HDMI control messages, 64 * HDMI-CEC and MHL control command, and providing the information on both standard. 65 */ 66public final class HdmiControlService extends SystemService { 67 private static final String TAG = "HdmiControlService"; 68 69 static final String PERMISSION = "android.permission.HDMI_CEC"; 70 71 /** 72 * Interface to report send result. 73 */ 74 interface SendMessageCallback { 75 /** 76 * Called when {@link HdmiControlService#sendCecCommand} is completed. 77 * 78 * @param error result of send request. 79 * <ul> 80 * <li>{@link Constants#SEND_RESULT_SUCCESS} 81 * <li>{@link Constants#SEND_RESULT_NAK} 82 * <li>{@link Constants#SEND_RESULT_FAILURE} 83 * </ul> 84 */ 85 void onSendCompleted(int error); 86 } 87 88 /** 89 * Interface to get a list of available logical devices. 90 */ 91 interface DevicePollingCallback { 92 /** 93 * Called when device polling is finished. 94 * 95 * @param ackedAddress a list of logical addresses of available devices 96 */ 97 void onPollingFinished(List<Integer> ackedAddress); 98 } 99 100 private class PowerStateReceiver extends BroadcastReceiver { 101 @Override 102 public void onReceive(Context context, Intent intent) { 103 switch (intent.getAction()) { 104 case Intent.ACTION_SCREEN_OFF: 105 if (isPowerOnOrTransient()) { 106 onStandby(); 107 } 108 break; 109 case Intent.ACTION_SCREEN_ON: 110 if (isPowerStandbyOrTransient()) { 111 onWakeUp(); 112 } 113 break; 114 } 115 } 116 } 117 118 // A thread to handle synchronous IO of CEC and MHL control service. 119 // Since all of CEC and MHL HAL interfaces processed in short time (< 200ms) 120 // and sparse call it shares a thread to handle IO operations. 121 private final HandlerThread mIoThread = new HandlerThread("Hdmi Control Io Thread"); 122 123 // Used to synchronize the access to the service. 124 private final Object mLock = new Object(); 125 126 // Type of logical devices hosted in the system. Stored in the unmodifiable list. 127 private final List<Integer> mLocalDevices; 128 129 // List of listeners registered by callers that want to get notified of 130 // hotplug events. 131 @GuardedBy("mLock") 132 private final ArrayList<IHdmiHotplugEventListener> mHotplugEventListeners = new ArrayList<>(); 133 134 // List of records for hotplug event listener to handle the the caller killed in action. 135 @GuardedBy("mLock") 136 private final ArrayList<HotplugEventListenerRecord> mHotplugEventListenerRecords = 137 new ArrayList<>(); 138 139 // List of listeners registered by callers that want to get notified of 140 // device status events. 141 @GuardedBy("mLock") 142 private final ArrayList<IHdmiDeviceEventListener> mDeviceEventListeners = new ArrayList<>(); 143 144 // List of records for device event listener to handle the the caller killed in action. 145 @GuardedBy("mLock") 146 private final ArrayList<DeviceEventListenerRecord> mDeviceEventListenerRecords = 147 new ArrayList<>(); 148 149 // List of records for vendor command listener to handle the the caller killed in action. 150 @GuardedBy("mLock") 151 private final ArrayList<VendorCommandListenerRecord> mVendorCommandListenerRecords = 152 new ArrayList<>(); 153 154 @GuardedBy("mLock") 155 private IHdmiInputChangeListener mInputChangeListener; 156 157 @GuardedBy("mLock") 158 private InputChangeListenerRecord mInputChangeListenerRecord; 159 160 // Set to true while HDMI control is enabled. If set to false, HDMI-CEC/MHL protocol 161 // handling will be disabled and no request will be handled. 162 @GuardedBy("mLock") 163 private boolean mHdmiControlEnabled; 164 165 // Set to true while the service is in normal mode. While set to false, no input change is 166 // allowed. Used for situations where input change can confuse users such as channel auto-scan, 167 // system upgrade, etc., a.k.a. "prohibit mode". 168 @GuardedBy("mLock") 169 private boolean mProhibitMode; 170 171 // List of listeners registered by callers that want to get notified of 172 // system audio mode changes. 173 private final ArrayList<IHdmiSystemAudioModeChangeListener> 174 mSystemAudioModeChangeListeners = new ArrayList<>(); 175 // List of records for system audio mode change to handle the the caller killed in action. 176 private final ArrayList<SystemAudioModeChangeListenerRecord> 177 mSystemAudioModeChangeListenerRecords = new ArrayList<>(); 178 179 // Handler used to run a task in service thread. 180 private final Handler mHandler = new Handler(); 181 182 @Nullable 183 private HdmiCecController mCecController; 184 185 @Nullable 186 private HdmiMhlController mMhlController; 187 188 // HDMI port information. Stored in the unmodifiable list to keep the static information 189 // from being modified. 190 private List<HdmiPortInfo> mPortInfo; 191 192 private HdmiCecMessageValidator mMessageValidator; 193 194 private final PowerStateReceiver mPowerStateReceiver = new PowerStateReceiver(); 195 196 @ServiceThreadOnly 197 private int mPowerStatus = HdmiControlManager.POWER_STATUS_STANDBY; 198 199 @ServiceThreadOnly 200 private boolean mStandbyMessageReceived = false; 201 202 public HdmiControlService(Context context) { 203 super(context); 204 mLocalDevices = HdmiUtils.asImmutableList(getContext().getResources().getIntArray( 205 com.android.internal.R.array.config_hdmiCecLogicalDeviceType)); 206 } 207 208 @Override 209 public void onStart() { 210 mIoThread.start(); 211 mPowerStatus = HdmiControlManager.POWER_STATUS_TRANSIENT_TO_ON; 212 mProhibitMode = false; 213 mHdmiControlEnabled = readBooleanSetting(Global.HDMI_CONTROL_ENABLED, true); 214 215 mCecController = HdmiCecController.create(this); 216 if (mCecController != null) { 217 // TODO: Remove this as soon as OEM's HAL implementation is corrected. 218 mCecController.setOption(HdmiTvClient.OPTION_CEC_ENABLE, 219 HdmiTvClient.ENABLED); 220 221 // TODO: load value for mHdmiControlEnabled from preference. 222 if (mHdmiControlEnabled) { 223 initializeCec(true); 224 } 225 } else { 226 Slog.i(TAG, "Device does not support HDMI-CEC."); 227 } 228 229 mMhlController = HdmiMhlController.create(this); 230 if (mMhlController == null) { 231 Slog.i(TAG, "Device does not support MHL-control."); 232 } 233 mPortInfo = initPortInfo(); 234 mMessageValidator = new HdmiCecMessageValidator(this); 235 publishBinderService(Context.HDMI_CONTROL_SERVICE, new BinderService()); 236 237 // Register broadcast receiver for power state change. 238 if (mCecController != null || mMhlController != null) { 239 IntentFilter filter = new IntentFilter(); 240 filter.addAction(Intent.ACTION_SCREEN_OFF); 241 filter.addAction(Intent.ACTION_SCREEN_ON); 242 getContext().registerReceiver(mPowerStateReceiver, filter); 243 } 244 } 245 246 boolean readBooleanSetting(String key, boolean defVal) { 247 ContentResolver cr = getContext().getContentResolver(); 248 return Global.getInt(cr, key, defVal ? Constants.TRUE : Constants.FALSE) == Constants.TRUE; 249 } 250 251 void writeBooleanSetting(String key, boolean value) { 252 ContentResolver cr = getContext().getContentResolver(); 253 Global.putInt(cr, key, value ? Constants.TRUE : Constants.FALSE); 254 } 255 256 private void initializeCec(boolean fromBootup) { 257 mCecController.setOption(HdmiTvClient.OPTION_CEC_SERVICE_CONTROL, 258 HdmiTvClient.ENABLED); 259 initializeLocalDevices(mLocalDevices, fromBootup); 260 } 261 262 @ServiceThreadOnly 263 private void initializeLocalDevices(final List<Integer> deviceTypes, final boolean fromBootup) { 264 assertRunOnServiceThread(); 265 // A container for [Logical Address, Local device info]. 266 final SparseArray<HdmiCecLocalDevice> devices = new SparseArray<>(); 267 final SparseIntArray finished = new SparseIntArray(); 268 mCecController.clearLogicalAddress(); 269 for (int type : deviceTypes) { 270 final HdmiCecLocalDevice localDevice = HdmiCecLocalDevice.create(this, type); 271 localDevice.init(); 272 mCecController.allocateLogicalAddress(type, 273 localDevice.getPreferredAddress(), new AllocateAddressCallback() { 274 @Override 275 public void onAllocated(int deviceType, int logicalAddress) { 276 if (logicalAddress == Constants.ADDR_UNREGISTERED) { 277 Slog.e(TAG, "Failed to allocate address:[device_type:" + deviceType + "]"); 278 } else { 279 HdmiCecDeviceInfo deviceInfo = createDeviceInfo(logicalAddress, deviceType); 280 localDevice.setDeviceInfo(deviceInfo); 281 mCecController.addLocalDevice(deviceType, localDevice); 282 mCecController.addLogicalAddress(logicalAddress); 283 devices.append(logicalAddress, localDevice); 284 } 285 finished.append(deviceType, logicalAddress); 286 287 // Address allocation completed for all devices. Notify each device. 288 if (deviceTypes.size() == finished.size()) { 289 if (mPowerStatus == HdmiControlManager.POWER_STATUS_TRANSIENT_TO_ON) { 290 mPowerStatus = HdmiControlManager.POWER_STATUS_ON; 291 } 292 notifyAddressAllocated(devices, fromBootup); 293 } 294 } 295 }); 296 } 297 } 298 299 @ServiceThreadOnly 300 private void notifyAddressAllocated(SparseArray<HdmiCecLocalDevice> devices, 301 boolean fromBootup) { 302 assertRunOnServiceThread(); 303 for (int i = 0; i < devices.size(); ++i) { 304 int address = devices.keyAt(i); 305 HdmiCecLocalDevice device = devices.valueAt(i); 306 device.handleAddressAllocated(address, fromBootup); 307 } 308 } 309 310 // Initialize HDMI port information. Combine the information from CEC and MHL HAL and 311 // keep them in one place. 312 @ServiceThreadOnly 313 private List<HdmiPortInfo> initPortInfo() { 314 assertRunOnServiceThread(); 315 HdmiPortInfo[] cecPortInfo = null; 316 317 // CEC HAL provides majority of the info while MHL does only MHL support flag for 318 // each port. Return empty array if CEC HAL didn't provide the info. 319 if (mCecController != null) { 320 cecPortInfo = mCecController.getPortInfos(); 321 } 322 if (cecPortInfo == null) { 323 return Collections.emptyList(); 324 } 325 326 HdmiPortInfo[] mhlPortInfo = new HdmiPortInfo[0]; 327 if (mMhlController != null) { 328 // TODO: Implement plumbing logic to get MHL port information. 329 // mhlPortInfo = mMhlController.getPortInfos(); 330 } 331 332 // Use the id (port number) to find the matched info between CEC and MHL to combine them 333 // into one. Leave the field `mhlSupported` to false if matched MHL entry is not found. 334 ArrayList<HdmiPortInfo> result = new ArrayList<>(cecPortInfo.length); 335 for (int i = 0; i < cecPortInfo.length; ++i) { 336 HdmiPortInfo cec = cecPortInfo[i]; 337 int id = cec.getId(); 338 boolean mhlInfoFound = false; 339 for (HdmiPortInfo mhl : mhlPortInfo) { 340 if (id == mhl.getId()) { 341 result.add(new HdmiPortInfo(id, cec.getType(), cec.getAddress(), 342 cec.isCecSupported(), mhl.isMhlSupported(), cec.isArcSupported())); 343 mhlInfoFound = true; 344 break; 345 } 346 } 347 if (!mhlInfoFound) { 348 result.add(cec); 349 } 350 } 351 352 return Collections.unmodifiableList(result); 353 } 354 355 /** 356 * Returns HDMI port information for the given port id. 357 * 358 * @param portId HDMI port id 359 * @return {@link HdmiPortInfo} for the given port 360 */ 361 HdmiPortInfo getPortInfo(int portId) { 362 // mPortInfo is an unmodifiable list and the only reference to its inner list. 363 // No lock is necessary. 364 for (HdmiPortInfo info : mPortInfo) { 365 if (portId == info.getId()) { 366 return info; 367 } 368 } 369 return null; 370 } 371 372 /** 373 * Returns the routing path (physical address) of the HDMI port for the given 374 * port id. 375 */ 376 int portIdToPath(int portId) { 377 HdmiPortInfo portInfo = getPortInfo(portId); 378 if (portInfo == null) { 379 Slog.e(TAG, "Cannot find the port info: " + portId); 380 return Constants.INVALID_PHYSICAL_ADDRESS; 381 } 382 return portInfo.getAddress(); 383 } 384 385 /** 386 * Returns the id of HDMI port located at the top of the hierarchy of 387 * the specified routing path. For the routing path 0x1220 (1.2.2.0), for instance, 388 * the port id to be returned is the ID associated with the port address 389 * 0x1000 (1.0.0.0) which is the topmost path of the given routing path. 390 */ 391 int pathToPortId(int path) { 392 int portAddress = path & Constants.ROUTING_PATH_TOP_MASK; 393 for (HdmiPortInfo info : mPortInfo) { 394 if (portAddress == info.getAddress()) { 395 return info.getId(); 396 } 397 } 398 return Constants.INVALID_PORT_ID; 399 } 400 401 /** 402 * Returns {@link Looper} for IO operation. 403 * 404 * <p>Declared as package-private. 405 */ 406 Looper getIoLooper() { 407 return mIoThread.getLooper(); 408 } 409 410 /** 411 * Returns {@link Looper} of main thread. Use this {@link Looper} instance 412 * for tasks that are running on main service thread. 413 * 414 * <p>Declared as package-private. 415 */ 416 Looper getServiceLooper() { 417 return mHandler.getLooper(); 418 } 419 420 /** 421 * Returns physical address of the device. 422 */ 423 int getPhysicalAddress() { 424 return mCecController.getPhysicalAddress(); 425 } 426 427 /** 428 * Returns vendor id of CEC service. 429 */ 430 int getVendorId() { 431 return mCecController.getVendorId(); 432 } 433 434 @ServiceThreadOnly 435 HdmiCecDeviceInfo getDeviceInfo(int logicalAddress) { 436 assertRunOnServiceThread(); 437 HdmiCecLocalDeviceTv tv = tv(); 438 if (tv == null) { 439 return null; 440 } 441 return tv.getDeviceInfo(logicalAddress); 442 } 443 444 /** 445 * Returns version of CEC. 446 */ 447 int getCecVersion() { 448 return mCecController.getVersion(); 449 } 450 451 /** 452 * Whether a device of the specified physical address is connected to ARC enabled port. 453 */ 454 boolean isConnectedToArcPort(int physicalAddress) { 455 for (HdmiPortInfo portInfo : mPortInfo) { 456 if (hasSameTopPort(portInfo.getAddress(), physicalAddress) 457 && portInfo.isArcSupported()) { 458 return true; 459 } 460 } 461 return false; 462 } 463 464 void runOnServiceThread(Runnable runnable) { 465 mHandler.post(runnable); 466 } 467 468 void runOnServiceThreadAtFrontOfQueue(Runnable runnable) { 469 mHandler.postAtFrontOfQueue(runnable); 470 } 471 472 private void assertRunOnServiceThread() { 473 if (Looper.myLooper() != mHandler.getLooper()) { 474 throw new IllegalStateException("Should run on service thread."); 475 } 476 } 477 478 /** 479 * Transmit a CEC command to CEC bus. 480 * 481 * @param command CEC command to send out 482 * @param callback interface used to the result of send command 483 */ 484 @ServiceThreadOnly 485 void sendCecCommand(HdmiCecMessage command, @Nullable SendMessageCallback callback) { 486 assertRunOnServiceThread(); 487 mCecController.sendCommand(command, callback); 488 } 489 490 @ServiceThreadOnly 491 void sendCecCommand(HdmiCecMessage command) { 492 assertRunOnServiceThread(); 493 mCecController.sendCommand(command, null); 494 } 495 496 @ServiceThreadOnly 497 boolean handleCecCommand(HdmiCecMessage message) { 498 assertRunOnServiceThread(); 499 if (!mMessageValidator.isValid(message)) { 500 return false; 501 } 502 return dispatchMessageToLocalDevice(message); 503 } 504 505 void setAudioReturnChannel(boolean enabled) { 506 mCecController.setAudioReturnChannel(enabled); 507 } 508 509 @ServiceThreadOnly 510 private boolean dispatchMessageToLocalDevice(HdmiCecMessage message) { 511 assertRunOnServiceThread(); 512 for (HdmiCecLocalDevice device : mCecController.getLocalDeviceList()) { 513 if (device.dispatchMessage(message) 514 && message.getDestination() != Constants.ADDR_BROADCAST) { 515 return true; 516 } 517 } 518 519 if (message.getDestination() != Constants.ADDR_BROADCAST) { 520 Slog.w(TAG, "Unhandled cec command:" + message); 521 } 522 return false; 523 } 524 525 /** 526 * Called when a new hotplug event is issued. 527 * 528 * @param portNo hdmi port number where hot plug event issued. 529 * @param connected whether to be plugged in or not 530 */ 531 @ServiceThreadOnly 532 void onHotplug(int portNo, boolean connected) { 533 assertRunOnServiceThread(); 534 for (HdmiCecLocalDevice device : mCecController.getLocalDeviceList()) { 535 device.onHotplug(portNo, connected); 536 } 537 announceHotplugEvent(portNo, connected); 538 } 539 540 /** 541 * Poll all remote devices. It sends <Polling Message> to all remote 542 * devices. 543 * 544 * @param callback an interface used to get a list of all remote devices' address 545 * @param sourceAddress a logical address of source device where sends polling message 546 * @param pickStrategy strategy how to pick polling candidates 547 * @param retryCount the number of retry used to send polling message to remote devices 548 * @throw IllegalArgumentException if {@code pickStrategy} is invalid value 549 */ 550 @ServiceThreadOnly 551 void pollDevices(DevicePollingCallback callback, int sourceAddress, int pickStrategy, 552 int retryCount) { 553 assertRunOnServiceThread(); 554 mCecController.pollDevices(callback, sourceAddress, checkPollStrategy(pickStrategy), 555 retryCount); 556 } 557 558 private int checkPollStrategy(int pickStrategy) { 559 int strategy = pickStrategy & Constants.POLL_STRATEGY_MASK; 560 if (strategy == 0) { 561 throw new IllegalArgumentException("Invalid poll strategy:" + pickStrategy); 562 } 563 int iterationStrategy = pickStrategy & Constants.POLL_ITERATION_STRATEGY_MASK; 564 if (iterationStrategy == 0) { 565 throw new IllegalArgumentException("Invalid iteration strategy:" + pickStrategy); 566 } 567 return strategy | iterationStrategy; 568 } 569 570 List<HdmiCecLocalDevice> getAllLocalDevices() { 571 assertRunOnServiceThread(); 572 return mCecController.getLocalDeviceList(); 573 } 574 575 Object getServiceLock() { 576 return mLock; 577 } 578 579 void setAudioStatus(boolean mute, int volume) { 580 // TODO: Hook up with AudioManager. 581 } 582 583 void announceSystemAudioModeChange(boolean enabled) { 584 for (IHdmiSystemAudioModeChangeListener listener : mSystemAudioModeChangeListeners) { 585 invokeSystemAudioModeChange(listener, enabled); 586 } 587 } 588 589 private HdmiCecDeviceInfo createDeviceInfo(int logicalAddress, int deviceType) { 590 // TODO: find better name instead of model name. 591 String displayName = Build.MODEL; 592 return new HdmiCecDeviceInfo(logicalAddress, 593 getPhysicalAddress(), deviceType, getVendorId(), displayName); 594 } 595 596 // Record class that monitors the event of the caller of being killed. Used to clean up 597 // the listener list and record list accordingly. 598 private final class HotplugEventListenerRecord implements IBinder.DeathRecipient { 599 private final IHdmiHotplugEventListener mListener; 600 601 public HotplugEventListenerRecord(IHdmiHotplugEventListener listener) { 602 mListener = listener; 603 } 604 605 @Override 606 public void binderDied() { 607 synchronized (mLock) { 608 mHotplugEventListenerRecords.remove(this); 609 mHotplugEventListeners.remove(mListener); 610 } 611 } 612 } 613 614 private final class DeviceEventListenerRecord implements IBinder.DeathRecipient { 615 private final IHdmiDeviceEventListener mListener; 616 617 public DeviceEventListenerRecord(IHdmiDeviceEventListener listener) { 618 mListener = listener; 619 } 620 621 @Override 622 public void binderDied() { 623 synchronized (mLock) { 624 mDeviceEventListenerRecords.remove(this); 625 mDeviceEventListeners.remove(mListener); 626 } 627 } 628 } 629 630 private final class SystemAudioModeChangeListenerRecord implements IBinder.DeathRecipient { 631 private final IHdmiSystemAudioModeChangeListener mListener; 632 633 public SystemAudioModeChangeListenerRecord(IHdmiSystemAudioModeChangeListener listener) { 634 mListener = listener; 635 } 636 637 @Override 638 public void binderDied() { 639 synchronized (mLock) { 640 mSystemAudioModeChangeListenerRecords.remove(this); 641 mSystemAudioModeChangeListeners.remove(mListener); 642 } 643 } 644 } 645 646 class VendorCommandListenerRecord implements IBinder.DeathRecipient { 647 private final IHdmiVendorCommandListener mListener; 648 private final int mDeviceType; 649 650 public VendorCommandListenerRecord(IHdmiVendorCommandListener listener, int deviceType) { 651 mListener = listener; 652 mDeviceType = deviceType; 653 } 654 655 @Override 656 public void binderDied() { 657 synchronized (mLock) { 658 mVendorCommandListenerRecords.remove(this); 659 } 660 } 661 } 662 663 private void enforceAccessPermission() { 664 getContext().enforceCallingOrSelfPermission(PERMISSION, TAG); 665 } 666 667 private final class BinderService extends IHdmiControlService.Stub { 668 @Override 669 public int[] getSupportedTypes() { 670 enforceAccessPermission(); 671 // mLocalDevices is an unmodifiable list - no lock necesary. 672 int[] localDevices = new int[mLocalDevices.size()]; 673 for (int i = 0; i < localDevices.length; ++i) { 674 localDevices[i] = mLocalDevices.get(i); 675 } 676 return localDevices; 677 } 678 679 @Override 680 public void deviceSelect(final int logicalAddress, final IHdmiControlCallback callback) { 681 enforceAccessPermission(); 682 runOnServiceThread(new Runnable() { 683 @Override 684 public void run() { 685 HdmiCecLocalDeviceTv tv = tv(); 686 if (tv == null) { 687 Slog.w(TAG, "Local tv device not available"); 688 invokeCallback(callback, HdmiControlManager.RESULT_SOURCE_NOT_AVAILABLE); 689 return; 690 } 691 tv.deviceSelect(logicalAddress, callback); 692 } 693 }); 694 } 695 696 @Override 697 public void portSelect(final int portId, final IHdmiControlCallback callback) { 698 enforceAccessPermission(); 699 runOnServiceThread(new Runnable() { 700 @Override 701 public void run() { 702 HdmiCecLocalDeviceTv tv = tv(); 703 if (tv == null) { 704 Slog.w(TAG, "Local tv device not available"); 705 invokeCallback(callback, HdmiControlManager.RESULT_SOURCE_NOT_AVAILABLE); 706 return; 707 } 708 tv.doManualPortSwitching(portId, callback); 709 } 710 }); 711 } 712 713 @Override 714 public void sendKeyEvent(final int deviceType, final int keyCode, final boolean isPressed) { 715 enforceAccessPermission(); 716 runOnServiceThread(new Runnable() { 717 @Override 718 public void run() { 719 HdmiCecLocalDevice localDevice = mCecController.getLocalDevice(deviceType); 720 if (localDevice == null) { 721 Slog.w(TAG, "Local device not available"); 722 return; 723 } 724 localDevice.sendKeyEvent(keyCode, isPressed); 725 } 726 }); 727 } 728 729 @Override 730 public void oneTouchPlay(final IHdmiControlCallback callback) { 731 enforceAccessPermission(); 732 runOnServiceThread(new Runnable() { 733 @Override 734 public void run() { 735 HdmiControlService.this.oneTouchPlay(callback); 736 } 737 }); 738 } 739 740 @Override 741 public void queryDisplayStatus(final IHdmiControlCallback callback) { 742 enforceAccessPermission(); 743 runOnServiceThread(new Runnable() { 744 @Override 745 public void run() { 746 HdmiControlService.this.queryDisplayStatus(callback); 747 } 748 }); 749 } 750 751 @Override 752 public void addHotplugEventListener(final IHdmiHotplugEventListener listener) { 753 enforceAccessPermission(); 754 runOnServiceThread(new Runnable() { 755 @Override 756 public void run() { 757 HdmiControlService.this.addHotplugEventListener(listener); 758 } 759 }); 760 } 761 762 @Override 763 public void removeHotplugEventListener(final IHdmiHotplugEventListener listener) { 764 enforceAccessPermission(); 765 runOnServiceThread(new Runnable() { 766 @Override 767 public void run() { 768 HdmiControlService.this.removeHotplugEventListener(listener); 769 } 770 }); 771 } 772 773 @Override 774 public void addDeviceEventListener(final IHdmiDeviceEventListener listener) { 775 enforceAccessPermission(); 776 runOnServiceThread(new Runnable() { 777 @Override 778 public void run() { 779 HdmiControlService.this.addDeviceEventListener(listener); 780 } 781 }); 782 } 783 784 @Override 785 public List<HdmiPortInfo> getPortInfo() { 786 enforceAccessPermission(); 787 return mPortInfo; 788 } 789 790 @Override 791 public boolean canChangeSystemAudioMode() { 792 enforceAccessPermission(); 793 HdmiCecLocalDeviceTv tv = tv(); 794 if (tv == null) { 795 return false; 796 } 797 return tv.hasSystemAudioDevice(); 798 } 799 800 @Override 801 public boolean getSystemAudioMode() { 802 enforceAccessPermission(); 803 HdmiCecLocalDeviceTv tv = tv(); 804 if (tv == null) { 805 return false; 806 } 807 return tv.getSystemAudioMode(); 808 } 809 810 @Override 811 public void setSystemAudioMode(final boolean enabled, final IHdmiControlCallback callback) { 812 enforceAccessPermission(); 813 runOnServiceThread(new Runnable() { 814 @Override 815 public void run() { 816 HdmiCecLocalDeviceTv tv = tv(); 817 if (tv == null) { 818 Slog.w(TAG, "Local tv device not available"); 819 invokeCallback(callback, HdmiControlManager.RESULT_SOURCE_NOT_AVAILABLE); 820 return; 821 } 822 tv.changeSystemAudioMode(enabled, callback); 823 } 824 }); 825 } 826 827 @Override 828 public void addSystemAudioModeChangeListener( 829 final IHdmiSystemAudioModeChangeListener listener) { 830 enforceAccessPermission(); 831 HdmiControlService.this.addSystemAudioModeChangeListner(listener); 832 } 833 834 @Override 835 public void removeSystemAudioModeChangeListener( 836 final IHdmiSystemAudioModeChangeListener listener) { 837 enforceAccessPermission(); 838 HdmiControlService.this.removeSystemAudioModeChangeListener(listener); 839 } 840 841 @Override 842 public void setInputChangeListener(final IHdmiInputChangeListener listener) { 843 enforceAccessPermission(); 844 HdmiControlService.this.setInputChangeListener(listener); 845 } 846 847 @Override 848 public List<HdmiCecDeviceInfo> getInputDevices() { 849 enforceAccessPermission(); 850 // No need to hold the lock for obtaining TV device as the local device instance 851 // is preserved while the HDMI control is enabled. 852 HdmiCecLocalDeviceTv tv = tv(); 853 if (tv == null) { 854 return Collections.emptyList(); 855 } 856 return tv.getSafeExternalInputs(); 857 } 858 859 @Override 860 public void setControlEnabled(final boolean enabled) { 861 enforceAccessPermission(); 862 runOnServiceThread(new Runnable() { 863 @Override 864 public void run() { 865 handleHdmiControlStatusChanged(enabled); 866 867 } 868 }); 869 } 870 871 @Override 872 public void setSystemAudioVolume(final int oldIndex, final int newIndex, 873 final int maxIndex) { 874 enforceAccessPermission(); 875 runOnServiceThread(new Runnable() { 876 @Override 877 public void run() { 878 HdmiCecLocalDeviceTv tv = tv(); 879 if (tv == null) { 880 Slog.w(TAG, "Local tv device not available"); 881 return; 882 } 883 tv.changeVolume(oldIndex, newIndex - oldIndex, maxIndex); 884 } 885 }); 886 } 887 888 @Override 889 public void setSystemAudioMute(final boolean mute) { 890 enforceAccessPermission(); 891 runOnServiceThread(new Runnable() { 892 @Override 893 public void run() { 894 HdmiCecLocalDeviceTv tv = tv(); 895 if (tv == null) { 896 Slog.w(TAG, "Local tv device not available"); 897 return; 898 } 899 tv.changeMute(mute); 900 } 901 }); 902 } 903 904 @Override 905 public void setArcMode(final boolean enabled) { 906 enforceAccessPermission(); 907 runOnServiceThread(new Runnable() { 908 @Override 909 public void run() { 910 HdmiCecLocalDeviceTv tv = tv(); 911 if (tv == null) { 912 Slog.w(TAG, "Local tv device not available to change arc mode."); 913 return; 914 } 915 } 916 }); 917 } 918 919 @Override 920 public void setOption(final int key, final int value) { 921 enforceAccessPermission(); 922 if (!isTvDevice()) { 923 return; 924 } 925 switch (key) { 926 case HdmiTvClient.OPTION_CEC_AUTO_WAKEUP: 927 mCecController.setOption(key, value); 928 break; 929 case HdmiTvClient.OPTION_CEC_AUTO_DEVICE_OFF: 930 // No need to pass this option to HAL. 931 tv().setAutoDeviceOff(value == HdmiTvClient.ENABLED); 932 break; 933 case HdmiTvClient.OPTION_MHL_INPUT_SWITCHING: // Fall through 934 case HdmiTvClient.OPTION_MHL_POWER_CHARGE: 935 if (mMhlController != null) { 936 mMhlController.setOption(key, value); 937 } 938 break; 939 } 940 } 941 942 private boolean isTvDevice() { 943 return tv() != null; 944 } 945 946 @Override 947 public void setProhibitMode(final boolean enabled) { 948 enforceAccessPermission(); 949 if (!isTvDevice()) { 950 return; 951 } 952 HdmiControlService.this.setProhibitMode(enabled); 953 } 954 955 @Override 956 public void addVendorCommandListener(final IHdmiVendorCommandListener listener, 957 final int deviceType) { 958 enforceAccessPermission(); 959 runOnServiceThread(new Runnable() { 960 @Override 961 public void run() { 962 HdmiControlService.this.addVendorCommandListener(listener, deviceType); 963 } 964 }); 965 } 966 967 @Override 968 public void sendVendorCommand(final int deviceType, final int targetAddress, 969 final byte[] params, final boolean hasVendorId) { 970 enforceAccessPermission(); 971 runOnServiceThread(new Runnable() { 972 @Override 973 public void run() { 974 HdmiCecLocalDevice device = mCecController.getLocalDevice(deviceType); 975 if (device == null) { 976 Slog.w(TAG, "Local device not available"); 977 return; 978 } 979 if (hasVendorId) { 980 sendCecCommand(HdmiCecMessageBuilder.buildVendorCommandWithId( 981 device.getDeviceInfo().getLogicalAddress(), targetAddress, 982 getVendorId(), params)); 983 } else { 984 sendCecCommand(HdmiCecMessageBuilder.buildVendorCommand( 985 device.getDeviceInfo().getLogicalAddress(), targetAddress, params)); 986 } 987 } 988 }); 989 } 990 } 991 992 @ServiceThreadOnly 993 private void oneTouchPlay(final IHdmiControlCallback callback) { 994 assertRunOnServiceThread(); 995 HdmiCecLocalDevicePlayback source = playback(); 996 if (source == null) { 997 Slog.w(TAG, "Local playback device not available"); 998 invokeCallback(callback, HdmiControlManager.RESULT_SOURCE_NOT_AVAILABLE); 999 return; 1000 } 1001 source.oneTouchPlay(callback); 1002 } 1003 1004 @ServiceThreadOnly 1005 private void queryDisplayStatus(final IHdmiControlCallback callback) { 1006 assertRunOnServiceThread(); 1007 HdmiCecLocalDevicePlayback source = playback(); 1008 if (source == null) { 1009 Slog.w(TAG, "Local playback device not available"); 1010 invokeCallback(callback, HdmiControlManager.RESULT_SOURCE_NOT_AVAILABLE); 1011 return; 1012 } 1013 source.queryDisplayStatus(callback); 1014 } 1015 1016 private void addHotplugEventListener(IHdmiHotplugEventListener listener) { 1017 HotplugEventListenerRecord record = new HotplugEventListenerRecord(listener); 1018 try { 1019 listener.asBinder().linkToDeath(record, 0); 1020 } catch (RemoteException e) { 1021 Slog.w(TAG, "Listener already died"); 1022 return; 1023 } 1024 synchronized (mLock) { 1025 mHotplugEventListenerRecords.add(record); 1026 mHotplugEventListeners.add(listener); 1027 } 1028 } 1029 1030 private void removeHotplugEventListener(IHdmiHotplugEventListener listener) { 1031 synchronized (mLock) { 1032 for (HotplugEventListenerRecord record : mHotplugEventListenerRecords) { 1033 if (record.mListener.asBinder() == listener.asBinder()) { 1034 listener.asBinder().unlinkToDeath(record, 0); 1035 mHotplugEventListenerRecords.remove(record); 1036 break; 1037 } 1038 } 1039 mHotplugEventListeners.remove(listener); 1040 } 1041 } 1042 1043 private void addDeviceEventListener(IHdmiDeviceEventListener listener) { 1044 DeviceEventListenerRecord record = new DeviceEventListenerRecord(listener); 1045 try { 1046 listener.asBinder().linkToDeath(record, 0); 1047 } catch (RemoteException e) { 1048 Slog.w(TAG, "Listener already died"); 1049 return; 1050 } 1051 synchronized (mLock) { 1052 mDeviceEventListeners.add(listener); 1053 mDeviceEventListenerRecords.add(record); 1054 } 1055 } 1056 1057 void invokeDeviceEventListeners(HdmiCecDeviceInfo device, boolean activated) { 1058 synchronized (mLock) { 1059 for (IHdmiDeviceEventListener listener : mDeviceEventListeners) { 1060 try { 1061 listener.onStatusChanged(device, activated); 1062 } catch (RemoteException e) { 1063 Slog.e(TAG, "Failed to report device event:" + e); 1064 } 1065 } 1066 } 1067 } 1068 1069 private void addSystemAudioModeChangeListner(IHdmiSystemAudioModeChangeListener listener) { 1070 SystemAudioModeChangeListenerRecord record = new SystemAudioModeChangeListenerRecord( 1071 listener); 1072 try { 1073 listener.asBinder().linkToDeath(record, 0); 1074 } catch (RemoteException e) { 1075 Slog.w(TAG, "Listener already died"); 1076 return; 1077 } 1078 synchronized (mLock) { 1079 mSystemAudioModeChangeListeners.add(listener); 1080 mSystemAudioModeChangeListenerRecords.add(record); 1081 } 1082 } 1083 1084 private void removeSystemAudioModeChangeListener(IHdmiSystemAudioModeChangeListener listener) { 1085 synchronized (mLock) { 1086 for (SystemAudioModeChangeListenerRecord record : 1087 mSystemAudioModeChangeListenerRecords) { 1088 if (record.mListener.asBinder() == listener) { 1089 listener.asBinder().unlinkToDeath(record, 0); 1090 mSystemAudioModeChangeListenerRecords.remove(record); 1091 break; 1092 } 1093 } 1094 mSystemAudioModeChangeListeners.remove(listener); 1095 } 1096 } 1097 1098 private final class InputChangeListenerRecord implements IBinder.DeathRecipient { 1099 @Override 1100 public void binderDied() { 1101 synchronized (mLock) { 1102 mInputChangeListener = null; 1103 } 1104 } 1105 } 1106 1107 private void setInputChangeListener(IHdmiInputChangeListener listener) { 1108 synchronized (mLock) { 1109 mInputChangeListenerRecord = new InputChangeListenerRecord(); 1110 try { 1111 listener.asBinder().linkToDeath(mInputChangeListenerRecord, 0); 1112 } catch (RemoteException e) { 1113 Slog.w(TAG, "Listener already died"); 1114 return; 1115 } 1116 mInputChangeListener = listener; 1117 } 1118 } 1119 1120 void invokeInputChangeListener(int activeAddress) { 1121 synchronized (mLock) { 1122 if (mInputChangeListener != null) { 1123 HdmiCecDeviceInfo activeSource = getDeviceInfo(activeAddress); 1124 try { 1125 mInputChangeListener.onChanged(activeSource); 1126 } catch (RemoteException e) { 1127 Slog.w(TAG, "Exception thrown by IHdmiInputChangeListener: " + e); 1128 } 1129 } 1130 } 1131 } 1132 1133 private void invokeCallback(IHdmiControlCallback callback, int result) { 1134 try { 1135 callback.onComplete(result); 1136 } catch (RemoteException e) { 1137 Slog.e(TAG, "Invoking callback failed:" + e); 1138 } 1139 } 1140 1141 private void invokeSystemAudioModeChange(IHdmiSystemAudioModeChangeListener listener, 1142 boolean enabled) { 1143 try { 1144 listener.onStatusChanged(enabled); 1145 } catch (RemoteException e) { 1146 Slog.e(TAG, "Invoking callback failed:" + e); 1147 } 1148 } 1149 1150 private void announceHotplugEvent(int portId, boolean connected) { 1151 HdmiHotplugEvent event = new HdmiHotplugEvent(portId, connected); 1152 synchronized (mLock) { 1153 for (IHdmiHotplugEventListener listener : mHotplugEventListeners) { 1154 invokeHotplugEventListenerLocked(listener, event); 1155 } 1156 } 1157 } 1158 1159 private void invokeHotplugEventListenerLocked(IHdmiHotplugEventListener listener, 1160 HdmiHotplugEvent event) { 1161 try { 1162 listener.onReceived(event); 1163 } catch (RemoteException e) { 1164 Slog.e(TAG, "Failed to report hotplug event:" + event.toString(), e); 1165 } 1166 } 1167 1168 private static boolean hasSameTopPort(int path1, int path2) { 1169 return (path1 & Constants.ROUTING_PATH_TOP_MASK) 1170 == (path2 & Constants.ROUTING_PATH_TOP_MASK); 1171 } 1172 1173 private HdmiCecLocalDeviceTv tv() { 1174 return (HdmiCecLocalDeviceTv) mCecController.getLocalDevice(HdmiCecDeviceInfo.DEVICE_TV); 1175 } 1176 1177 private HdmiCecLocalDevicePlayback playback() { 1178 return (HdmiCecLocalDevicePlayback) 1179 mCecController.getLocalDevice(HdmiCecDeviceInfo.DEVICE_PLAYBACK); 1180 } 1181 1182 AudioManager getAudioManager() { 1183 return (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE); 1184 } 1185 1186 boolean isControlEnabled() { 1187 synchronized (mLock) { 1188 return mHdmiControlEnabled; 1189 } 1190 } 1191 1192 int getPowerStatus() { 1193 return mPowerStatus; 1194 } 1195 1196 boolean isPowerOnOrTransient() { 1197 return mPowerStatus == HdmiControlManager.POWER_STATUS_ON 1198 || mPowerStatus == HdmiControlManager.POWER_STATUS_TRANSIENT_TO_ON; 1199 } 1200 1201 boolean isPowerStandbyOrTransient() { 1202 return mPowerStatus == HdmiControlManager.POWER_STATUS_STANDBY 1203 || mPowerStatus == HdmiControlManager.POWER_STATUS_TRANSIENT_TO_STANDBY; 1204 } 1205 1206 boolean isPowerStandby() { 1207 return mPowerStatus == HdmiControlManager.POWER_STATUS_STANDBY; 1208 } 1209 1210 @ServiceThreadOnly 1211 void wakeUp() { 1212 assertRunOnServiceThread(); 1213 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE); 1214 pm.wakeUp(SystemClock.uptimeMillis()); 1215 // PowerManger will send the broadcast Intent.ACTION_SCREEN_ON and after this gets 1216 // the intent, the sequence will continue at onWakeUp(). 1217 } 1218 1219 @ServiceThreadOnly 1220 void standby() { 1221 assertRunOnServiceThread(); 1222 mStandbyMessageReceived = true; 1223 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE); 1224 pm.goToSleep(SystemClock.uptimeMillis()); 1225 // PowerManger will send the broadcast Intent.ACTION_SCREEN_OFF and after this gets 1226 // the intent, the sequence will continue at onStandby(). 1227 } 1228 1229 @ServiceThreadOnly 1230 private void onWakeUp() { 1231 assertRunOnServiceThread(); 1232 mPowerStatus = HdmiControlManager.POWER_STATUS_TRANSIENT_TO_ON; 1233 if (mCecController != null) { 1234 if (mHdmiControlEnabled) { 1235 initializeCec(true); 1236 } 1237 } else { 1238 Slog.i(TAG, "Device does not support HDMI-CEC."); 1239 } 1240 // TODO: Initialize MHL local devices. 1241 } 1242 1243 @ServiceThreadOnly 1244 private void onStandby() { 1245 assertRunOnServiceThread(); 1246 mPowerStatus = HdmiControlManager.POWER_STATUS_TRANSIENT_TO_STANDBY; 1247 1248 final List<HdmiCecLocalDevice> devices = getAllLocalDevices(); 1249 disableDevices(new PendingActionClearedCallback() { 1250 @Override 1251 public void onCleared(HdmiCecLocalDevice device) { 1252 Slog.v(TAG, "On standby-action cleared:" + device.mDeviceType); 1253 devices.remove(device); 1254 if (devices.isEmpty()) { 1255 clearLocalDevices(); 1256 onStandbyCompleted(); 1257 } 1258 } 1259 }); 1260 } 1261 1262 private void disableDevices(PendingActionClearedCallback callback) { 1263 for (HdmiCecLocalDevice device : mCecController.getLocalDeviceList()) { 1264 device.disableDevice(mStandbyMessageReceived, callback); 1265 } 1266 } 1267 1268 @ServiceThreadOnly 1269 private void clearLocalDevices() { 1270 assertRunOnServiceThread(); 1271 if (mCecController == null) { 1272 return; 1273 } 1274 mCecController.clearLogicalAddress(); 1275 mCecController.clearLocalDevices(); 1276 } 1277 1278 @ServiceThreadOnly 1279 private void onStandbyCompleted() { 1280 assertRunOnServiceThread(); 1281 Slog.v(TAG, "onStandbyCompleted"); 1282 1283 if (mPowerStatus != HdmiControlManager.POWER_STATUS_TRANSIENT_TO_STANDBY) { 1284 return; 1285 } 1286 mPowerStatus = HdmiControlManager.POWER_STATUS_STANDBY; 1287 for (HdmiCecLocalDevice device : mCecController.getLocalDeviceList()) { 1288 device.onStandby(mStandbyMessageReceived); 1289 } 1290 mStandbyMessageReceived = false; 1291 mCecController.setOption(HdmiTvClient.OPTION_CEC_SERVICE_CONTROL, HdmiTvClient.DISABLED); 1292 } 1293 1294 private void addVendorCommandListener(IHdmiVendorCommandListener listener, int deviceType) { 1295 VendorCommandListenerRecord record = new VendorCommandListenerRecord(listener, deviceType); 1296 try { 1297 listener.asBinder().linkToDeath(record, 0); 1298 } catch (RemoteException e) { 1299 Slog.w(TAG, "Listener already died"); 1300 return; 1301 } 1302 synchronized (mLock) { 1303 mVendorCommandListenerRecords.add(record); 1304 } 1305 } 1306 1307 void invokeVendorCommandListeners(int deviceType, int srcAddress, byte[] params, 1308 boolean hasVendorId) { 1309 synchronized (mLock) { 1310 for (VendorCommandListenerRecord record : mVendorCommandListenerRecords) { 1311 if (record.mDeviceType != deviceType) { 1312 continue; 1313 } 1314 try { 1315 record.mListener.onReceived(srcAddress, params, hasVendorId); 1316 } catch (RemoteException e) { 1317 Slog.e(TAG, "Failed to notify vendor command reception", e); 1318 } 1319 } 1320 } 1321 } 1322 1323 boolean isProhibitMode() { 1324 synchronized (mLock) { 1325 return mProhibitMode; 1326 } 1327 } 1328 1329 void setProhibitMode(boolean enabled) { 1330 synchronized (mLock) { 1331 mProhibitMode = enabled; 1332 } 1333 } 1334 1335 @ServiceThreadOnly 1336 private void handleHdmiControlStatusChanged(boolean enabled) { 1337 assertRunOnServiceThread(); 1338 1339 int value = enabled ? HdmiTvClient.ENABLED : HdmiTvClient.DISABLED; 1340 mCecController.setOption(HdmiTvClient.OPTION_CEC_ENABLE, value); 1341 if (mMhlController != null) { 1342 mMhlController.setOption(HdmiTvClient.OPTION_MHL_ENABLE, value); 1343 } 1344 1345 synchronized (mLock) { 1346 mHdmiControlEnabled = enabled; 1347 } 1348 1349 if (enabled) { 1350 initializeCec(false); 1351 } else { 1352 disableDevices(new PendingActionClearedCallback() { 1353 @Override 1354 public void onCleared(HdmiCecLocalDevice device) { 1355 assertRunOnServiceThread(); 1356 clearLocalDevices(); 1357 } 1358 }); 1359 } 1360 } 1361} 1362