getPortInfo() {
return mPortInfo;
}
/**
* Returns HDMI port information for the given port id.
*
* @param portId HDMI port id
* @return {@link HdmiPortInfo} for the given port
*/
HdmiPortInfo getPortInfo(int portId) {
return mPortInfoMap.get(portId, null);
}
/**
* Returns the routing path (physical address) of the HDMI port for the given
* port id.
*/
int portIdToPath(int portId) {
HdmiPortInfo portInfo = getPortInfo(portId);
if (portInfo == null) {
Slog.e(TAG, "Cannot find the port info: " + portId);
return Constants.INVALID_PHYSICAL_ADDRESS;
}
return portInfo.getAddress();
}
/**
* Returns the id of HDMI port located at the top of the hierarchy of
* the specified routing path. For the routing path 0x1220 (1.2.2.0), for instance,
* the port id to be returned is the ID associated with the port address
* 0x1000 (1.0.0.0) which is the topmost path of the given routing path.
*/
int pathToPortId(int path) {
int portAddress = path & Constants.ROUTING_PATH_TOP_MASK;
return mPortIdMap.get(portAddress, Constants.INVALID_PORT_ID);
}
boolean isValidPortId(int portId) {
return getPortInfo(portId) != null;
}
/**
* Returns {@link Looper} for IO operation.
*
* Declared as package-private.
*/
Looper getIoLooper() {
return mIoThread.getLooper();
}
/**
* Returns {@link Looper} of main thread. Use this {@link Looper} instance
* for tasks that are running on main service thread.
*
*
Declared as package-private.
*/
Looper getServiceLooper() {
return mHandler.getLooper();
}
/**
* Returns physical address of the device.
*/
int getPhysicalAddress() {
return mCecController.getPhysicalAddress();
}
/**
* Returns vendor id of CEC service.
*/
int getVendorId() {
return mCecController.getVendorId();
}
@ServiceThreadOnly
HdmiDeviceInfo getDeviceInfo(int logicalAddress) {
assertRunOnServiceThread();
HdmiCecLocalDeviceTv tv = tv();
if (tv == null) {
return null;
}
return tv.getCecDeviceInfo(logicalAddress);
}
/**
* Returns version of CEC.
*/
int getCecVersion() {
return mCecController.getVersion();
}
/**
* Whether a device of the specified physical address is connected to ARC enabled port.
*/
boolean isConnectedToArcPort(int physicalAddress) {
int portId = pathToPortId(physicalAddress);
if (portId != Constants.INVALID_PORT_ID) {
return mPortInfoMap.get(portId).isArcSupported();
}
return false;
}
void runOnServiceThread(Runnable runnable) {
mHandler.post(runnable);
}
void runOnServiceThreadAtFrontOfQueue(Runnable runnable) {
mHandler.postAtFrontOfQueue(runnable);
}
private void assertRunOnServiceThread() {
if (Looper.myLooper() != mHandler.getLooper()) {
throw new IllegalStateException("Should run on service thread.");
}
}
/**
* Transmit a CEC command to CEC bus.
*
* @param command CEC command to send out
* @param callback interface used to the result of send command
*/
@ServiceThreadOnly
void sendCecCommand(HdmiCecMessage command, @Nullable SendMessageCallback callback) {
assertRunOnServiceThread();
if (mMessageValidator.isValid(command)) {
mCecController.sendCommand(command, callback);
} else {
HdmiLogger.error("Invalid message type:" + command);
if (callback != null) {
callback.onSendCompleted(Constants.SEND_RESULT_FAILURE);
}
}
}
@ServiceThreadOnly
void sendCecCommand(HdmiCecMessage command) {
assertRunOnServiceThread();
sendCecCommand(command, null);
}
/**
* Send command on the given CEC message if possible.
* If the aborted message is invalid, then it wont send the message.
* @param command original command to be aborted
* @param reason reason of feature abort
*/
@ServiceThreadOnly
void maySendFeatureAbortCommand(HdmiCecMessage command, int reason) {
assertRunOnServiceThread();
mCecController.maySendFeatureAbortCommand(command, reason);
}
@ServiceThreadOnly
boolean handleCecCommand(HdmiCecMessage message) {
assertRunOnServiceThread();
if (!mMessageValidator.isValid(message)) {
return false;
}
return dispatchMessageToLocalDevice(message);
}
void setAudioReturnChannel(boolean enabled) {
mCecController.setAudioReturnChannel(enabled);
}
@ServiceThreadOnly
private boolean dispatchMessageToLocalDevice(HdmiCecMessage message) {
assertRunOnServiceThread();
for (HdmiCecLocalDevice device : mCecController.getLocalDeviceList()) {
if (device.dispatchMessage(message)
&& message.getDestination() != Constants.ADDR_BROADCAST) {
return true;
}
}
if (message.getDestination() != Constants.ADDR_BROADCAST) {
HdmiLogger.warning("Unhandled cec command:" + message);
}
return false;
}
/**
* Called when a new hotplug event is issued.
*
* @param portId hdmi port number where hot plug event issued.
* @param connected whether to be plugged in or not
*/
@ServiceThreadOnly
void onHotplug(int portId, boolean connected) {
assertRunOnServiceThread();
ArrayList localDevices = new ArrayList<>();
for (int type : mLocalDevices) {
if (type == HdmiDeviceInfo.DEVICE_TV) {
// Skip the reallocation of the logical address on TV.
continue;
}
HdmiCecLocalDevice localDevice = mCecController.getLocalDevice(type);
if (localDevice == null) {
localDevice = HdmiCecLocalDevice.create(this, type);
localDevice.init();
}
localDevices.add(localDevice);
}
allocateLogicalAddress(localDevices, INITIATED_BY_HOTPLUG);
for (HdmiCecLocalDevice device : mCecController.getLocalDeviceList()) {
device.onHotplug(portId, connected);
}
announceHotplugEvent(portId, connected);
}
/**
* Poll all remote devices. It sends <Polling Message> to all remote
* devices.
*
* @param callback an interface used to get a list of all remote devices' address
* @param sourceAddress a logical address of source device where sends polling message
* @param pickStrategy strategy how to pick polling candidates
* @param retryCount the number of retry used to send polling message to remote devices
* @throw IllegalArgumentException if {@code pickStrategy} is invalid value
*/
@ServiceThreadOnly
void pollDevices(DevicePollingCallback callback, int sourceAddress, int pickStrategy,
int retryCount) {
assertRunOnServiceThread();
mCecController.pollDevices(callback, sourceAddress, checkPollStrategy(pickStrategy),
retryCount);
}
private int checkPollStrategy(int pickStrategy) {
int strategy = pickStrategy & Constants.POLL_STRATEGY_MASK;
if (strategy == 0) {
throw new IllegalArgumentException("Invalid poll strategy:" + pickStrategy);
}
int iterationStrategy = pickStrategy & Constants.POLL_ITERATION_STRATEGY_MASK;
if (iterationStrategy == 0) {
throw new IllegalArgumentException("Invalid iteration strategy:" + pickStrategy);
}
return strategy | iterationStrategy;
}
List getAllLocalDevices() {
assertRunOnServiceThread();
return mCecController.getLocalDeviceList();
}
Object getServiceLock() {
return mLock;
}
void setAudioStatus(boolean mute, int volume) {
AudioManager audioManager = getAudioManager();
boolean muted = audioManager.isStreamMute(AudioManager.STREAM_MUSIC);
if (mute) {
if (!muted) {
audioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
}
} else {
if (muted) {
audioManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
}
// FLAG_HDMI_SYSTEM_AUDIO_VOLUME prevents audio manager from announcing
// volume change notification back to hdmi control service.
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume,
AudioManager.FLAG_HDMI_SYSTEM_AUDIO_VOLUME);
}
}
void announceSystemAudioModeChange(boolean enabled) {
synchronized (mLock) {
for (SystemAudioModeChangeListenerRecord record :
mSystemAudioModeChangeListenerRecords) {
invokeSystemAudioModeChangeLocked(record.mListener, enabled);
}
}
}
private HdmiDeviceInfo createDeviceInfo(int logicalAddress, int deviceType, int powerStatus) {
// TODO: find better name instead of model name.
String displayName = Build.MODEL;
return new HdmiDeviceInfo(logicalAddress,
getPhysicalAddress(), pathToPortId(getPhysicalAddress()), deviceType,
getVendorId(), displayName);
}
@ServiceThreadOnly
void sendMhlSubcommand(int portId, HdmiMhlSubcommand command) {
assertRunOnServiceThread();
sendMhlSubcommand(portId, command, null);
}
@ServiceThreadOnly
void sendMhlSubcommand(int portId, HdmiMhlSubcommand command, SendMessageCallback callback) {
assertRunOnServiceThread();
mMhlController.sendSubcommand(portId, command, callback);
}
@ServiceThreadOnly
boolean handleMhlSubcommand(int portId, HdmiMhlSubcommand message) {
assertRunOnServiceThread();
HdmiMhlLocalDevice device = mMhlController.getLocalDevice(portId);
if (device != null) {
return device.handleSubcommand(message);
}
Slog.w(TAG, "No mhl device exists[portId:" + portId + ", message:" + message);
return false;
}
@ServiceThreadOnly
void handleMhlHotplugEvent(int portId, boolean connected) {
assertRunOnServiceThread();
if (connected) {
HdmiMhlLocalDevice newDevice = new HdmiMhlLocalDevice(this, portId);
HdmiMhlLocalDevice oldDevice = mMhlController.addLocalDevice(newDevice);
if (oldDevice != null) {
oldDevice.onDeviceRemoved();
Slog.i(TAG, "Old device of port " + portId + " is removed");
}
} else {
HdmiMhlLocalDevice device = mMhlController.removeLocalDevice(portId);
if (device != null) {
device.onDeviceRemoved();
// There is no explicit event for device removal unlike capability register event
// used for device addition . Hence we remove the device on hotplug event.
HdmiDeviceInfo deviceInfo = device.getInfo();
if (deviceInfo != null) {
invokeDeviceEventListeners(deviceInfo, DEVICE_EVENT_REMOVE_DEVICE);
updateSafeMhlInput();
}
} else {
Slog.w(TAG, "No device to remove:[portId=" + portId);
}
}
announceHotplugEvent(portId, connected);
}
@ServiceThreadOnly
void handleMhlCbusModeChanged(int portId, int cbusmode) {
assertRunOnServiceThread();
HdmiMhlLocalDevice device = mMhlController.getLocalDevice(portId);
if (device != null) {
device.setCbusMode(cbusmode);
} else {
Slog.w(TAG, "No mhl device exists for cbus mode change[portId:" + portId +
", cbusmode:" + cbusmode + "]");
}
}
@ServiceThreadOnly
void handleMhlVbusOvercurrent(int portId, boolean on) {
assertRunOnServiceThread();
HdmiMhlLocalDevice device = mMhlController.getLocalDevice(portId);
if (device != null) {
device.onVbusOvercurrentDetected(on);
} else {
Slog.w(TAG, "No mhl device exists for vbus overcurrent event[portId:" + portId + "]");
}
}
@ServiceThreadOnly
void handleMhlCapabilityRegisterChanged(int portId, int adopterId, int deviceId) {
assertRunOnServiceThread();
HdmiMhlLocalDevice device = mMhlController.getLocalDevice(portId);
// Hotplug event should already have been called before capability register change event.
if (device != null) {
device.setCapabilityRegister(adopterId, deviceId);
invokeDeviceEventListeners(device.getInfo(), DEVICE_EVENT_ADD_DEVICE);
updateSafeMhlInput();
} else {
Slog.w(TAG, "No mhl device exists for capability register change event[portId:"
+ portId + ", adopterId:" + adopterId + ", deviceId:" + deviceId + "]");
}
}
@ServiceThreadOnly
private void updateSafeMhlInput() {
assertRunOnServiceThread();
List inputs = Collections.emptyList();
SparseArray devices = mMhlController.getAllLocalDevices();
for (int i = 0; i < devices.size(); ++i) {
HdmiMhlLocalDevice device = devices.valueAt(i);
HdmiDeviceInfo info = device.getInfo();
if (info != null) {
if (inputs.isEmpty()) {
inputs = new ArrayList<>();
}
inputs.add(device.getInfo());
}
}
synchronized (mLock) {
mMhlDevices = inputs;
}
}
private List getMhlDevicesLocked() {
return mMhlDevices;
}
private class HdmiMhlVendorCommandListenerRecord implements IBinder.DeathRecipient {
private final IHdmiMhlVendorCommandListener mListener;
public HdmiMhlVendorCommandListenerRecord(IHdmiMhlVendorCommandListener listener) {
mListener = listener;
}
@Override
public void binderDied() {
mMhlVendorCommandListenerRecords.remove(this);
}
}
// Record class that monitors the event of the caller of being killed. Used to clean up
// the listener list and record list accordingly.
private final class HotplugEventListenerRecord implements IBinder.DeathRecipient {
private final IHdmiHotplugEventListener mListener;
public HotplugEventListenerRecord(IHdmiHotplugEventListener listener) {
mListener = listener;
}
@Override
public void binderDied() {
synchronized (mLock) {
mHotplugEventListenerRecords.remove(this);
}
}
}
private final class DeviceEventListenerRecord implements IBinder.DeathRecipient {
private final IHdmiDeviceEventListener mListener;
public DeviceEventListenerRecord(IHdmiDeviceEventListener listener) {
mListener = listener;
}
@Override
public void binderDied() {
synchronized (mLock) {
mDeviceEventListenerRecords.remove(this);
}
}
}
private final class SystemAudioModeChangeListenerRecord implements IBinder.DeathRecipient {
private final IHdmiSystemAudioModeChangeListener mListener;
public SystemAudioModeChangeListenerRecord(IHdmiSystemAudioModeChangeListener listener) {
mListener = listener;
}
@Override
public void binderDied() {
synchronized (mLock) {
mSystemAudioModeChangeListenerRecords.remove(this);
}
}
}
class VendorCommandListenerRecord implements IBinder.DeathRecipient {
private final IHdmiVendorCommandListener mListener;
private final int mDeviceType;
public VendorCommandListenerRecord(IHdmiVendorCommandListener listener, int deviceType) {
mListener = listener;
mDeviceType = deviceType;
}
@Override
public void binderDied() {
synchronized (mLock) {
mVendorCommandListenerRecords.remove(this);
}
}
}
private class HdmiRecordListenerRecord implements IBinder.DeathRecipient {
private final IHdmiRecordListener mListener;
public HdmiRecordListenerRecord(IHdmiRecordListener listener) {
mListener = listener;
}
@Override
public void binderDied() {
synchronized (mLock) {
mRecordListenerRecord = null;
}
}
}
private void enforceAccessPermission() {
getContext().enforceCallingOrSelfPermission(PERMISSION, TAG);
}
private final class BinderService extends IHdmiControlService.Stub {
@Override
public int[] getSupportedTypes() {
enforceAccessPermission();
// mLocalDevices is an unmodifiable list - no lock necesary.
int[] localDevices = new int[mLocalDevices.size()];
for (int i = 0; i < localDevices.length; ++i) {
localDevices[i] = mLocalDevices.get(i);
}
return localDevices;
}
@Override
public HdmiDeviceInfo getActiveSource() {
HdmiCecLocalDeviceTv tv = tv();
if (tv == null) {
Slog.w(TAG, "Local tv device not available");
return null;
}
ActiveSource activeSource = tv.getActiveSource();
if (activeSource.isValid()) {
return new HdmiDeviceInfo(activeSource.logicalAddress,
activeSource.physicalAddress, HdmiDeviceInfo.PORT_INVALID,
HdmiDeviceInfo.DEVICE_INACTIVE, 0, "");
}
int activePath = tv.getActivePath();
if (activePath != HdmiDeviceInfo.PATH_INVALID) {
return new HdmiDeviceInfo(activePath, tv.getActivePortId());
}
return null;
}
@Override
public void deviceSelect(final int deviceId, final IHdmiControlCallback callback) {
enforceAccessPermission();
runOnServiceThread(new Runnable() {
@Override
public void run() {
if (callback == null) {
Slog.e(TAG, "Callback cannot be null");
return;
}
HdmiCecLocalDeviceTv tv = tv();
if (tv == null) {
Slog.w(TAG, "Local tv device not available");
invokeCallback(callback, HdmiControlManager.RESULT_SOURCE_NOT_AVAILABLE);
return;
}
HdmiMhlLocalDevice device = mMhlController.getLocalDeviceById(deviceId);
if (device != null) {
if (device.getPortId() == tv.getActivePortId()) {
invokeCallback(callback, HdmiControlManager.RESULT_SUCCESS);
return;
}
// Upon selecting MHL device, we send RAP[Content On] to wake up
// the connected mobile device, start routing control to switch ports.
// callback is handled by MHL action.
device.turnOn(callback);
tv.doManualPortSwitching(device.getPortId(), null);
return;
}
tv.deviceSelect(deviceId, callback);
}
});
}
@Override
public void portSelect(final int portId, final IHdmiControlCallback callback) {
enforceAccessPermission();
runOnServiceThread(new Runnable() {
@Override
public void run() {
if (callback == null) {
Slog.e(TAG, "Callback cannot be null");
return;
}
HdmiCecLocalDeviceTv tv = tv();
if (tv == null) {
Slog.w(TAG, "Local tv device not available");
invokeCallback(callback, HdmiControlManager.RESULT_SOURCE_NOT_AVAILABLE);
return;
}
tv.doManualPortSwitching(portId, callback);
}
});
}
@Override
public void sendKeyEvent(final int deviceType, final int keyCode, final boolean isPressed) {
enforceAccessPermission();
runOnServiceThread(new Runnable() {
@Override
public void run() {
HdmiMhlLocalDevice device = mMhlController.getLocalDevice(mActivePortId);
if (device != null) {
device.sendKeyEvent(keyCode, isPressed);
return;
}
if (mCecController != null) {
HdmiCecLocalDevice localDevice = mCecController.getLocalDevice(deviceType);
if (localDevice == null) {
Slog.w(TAG, "Local device not available");
return;
}
localDevice.sendKeyEvent(keyCode, isPressed);
}
}
});
}
@Override
public void oneTouchPlay(final IHdmiControlCallback callback) {
enforceAccessPermission();
runOnServiceThread(new Runnable() {
@Override
public void run() {
HdmiControlService.this.oneTouchPlay(callback);
}
});
}
@Override
public void queryDisplayStatus(final IHdmiControlCallback callback) {
enforceAccessPermission();
runOnServiceThread(new Runnable() {
@Override
public void run() {
HdmiControlService.this.queryDisplayStatus(callback);
}
});
}
@Override
public void addHotplugEventListener(final IHdmiHotplugEventListener listener) {
enforceAccessPermission();
HdmiControlService.this.addHotplugEventListener(listener);
}
@Override
public void removeHotplugEventListener(final IHdmiHotplugEventListener listener) {
enforceAccessPermission();
HdmiControlService.this.removeHotplugEventListener(listener);
}
@Override
public void addDeviceEventListener(final IHdmiDeviceEventListener listener) {
enforceAccessPermission();
HdmiControlService.this.addDeviceEventListener(listener);
}
@Override
public List getPortInfo() {
enforceAccessPermission();
return HdmiControlService.this.getPortInfo();
}
@Override
public boolean canChangeSystemAudioMode() {
enforceAccessPermission();
HdmiCecLocalDeviceTv tv = tv();
if (tv == null) {
return false;
}
return tv.hasSystemAudioDevice();
}
@Override
public boolean getSystemAudioMode() {
enforceAccessPermission();
HdmiCecLocalDeviceTv tv = tv();
if (tv == null) {
return false;
}
return tv.isSystemAudioActivated();
}
@Override
public void setSystemAudioMode(final boolean enabled, final IHdmiControlCallback callback) {
enforceAccessPermission();
runOnServiceThread(new Runnable() {
@Override
public void run() {
HdmiCecLocalDeviceTv tv = tv();
if (tv == null) {
Slog.w(TAG, "Local tv device not available");
invokeCallback(callback, HdmiControlManager.RESULT_SOURCE_NOT_AVAILABLE);
return;
}
tv.changeSystemAudioMode(enabled, callback);
}
});
}
@Override
public void addSystemAudioModeChangeListener(
final IHdmiSystemAudioModeChangeListener listener) {
enforceAccessPermission();
HdmiControlService.this.addSystemAudioModeChangeListner(listener);
}
@Override
public void removeSystemAudioModeChangeListener(
final IHdmiSystemAudioModeChangeListener listener) {
enforceAccessPermission();
HdmiControlService.this.removeSystemAudioModeChangeListener(listener);
}
@Override
public void setInputChangeListener(final IHdmiInputChangeListener listener) {
enforceAccessPermission();
HdmiControlService.this.setInputChangeListener(listener);
}
@Override
public List getInputDevices() {
enforceAccessPermission();
// No need to hold the lock for obtaining TV device as the local device instance
// is preserved while the HDMI control is enabled.
HdmiCecLocalDeviceTv tv = tv();
synchronized (mLock) {
List cecDevices = (tv == null)
? Collections.emptyList()
: tv.getSafeExternalInputsLocked();
return HdmiUtils.mergeToUnmodifiableList(cecDevices, getMhlDevicesLocked());
}
}
@Override
public void setSystemAudioVolume(final int oldIndex, final int newIndex,
final int maxIndex) {
enforceAccessPermission();
runOnServiceThread(new Runnable() {
@Override
public void run() {
HdmiCecLocalDeviceTv tv = tv();
if (tv == null) {
Slog.w(TAG, "Local tv device not available");
return;
}
tv.changeVolume(oldIndex, newIndex - oldIndex, maxIndex);
}
});
}
@Override
public void setSystemAudioMute(final boolean mute) {
enforceAccessPermission();
runOnServiceThread(new Runnable() {
@Override
public void run() {
HdmiCecLocalDeviceTv tv = tv();
if (tv == null) {
Slog.w(TAG, "Local tv device not available");
return;
}
tv.changeMute(mute);
}
});
}
@Override
public void setArcMode(final boolean enabled) {
enforceAccessPermission();
runOnServiceThread(new Runnable() {
@Override
public void run() {
HdmiCecLocalDeviceTv tv = tv();
if (tv == null) {
Slog.w(TAG, "Local tv device not available to change arc mode.");
return;
}
}
});
}
@Override
public void setProhibitMode(final boolean enabled) {
enforceAccessPermission();
if (!isTvDevice()) {
return;
}
HdmiControlService.this.setProhibitMode(enabled);
}
@Override
public void addVendorCommandListener(final IHdmiVendorCommandListener listener,
final int deviceType) {
enforceAccessPermission();
HdmiControlService.this.addVendorCommandListener(listener, deviceType);
}
@Override
public void sendVendorCommand(final int deviceType, final int targetAddress,
final byte[] params, final boolean hasVendorId) {
enforceAccessPermission();
runOnServiceThread(new Runnable() {
@Override
public void run() {
HdmiCecLocalDevice device = mCecController.getLocalDevice(deviceType);
if (device == null) {
Slog.w(TAG, "Local device not available");
return;
}
if (hasVendorId) {
sendCecCommand(HdmiCecMessageBuilder.buildVendorCommandWithId(
device.getDeviceInfo().getLogicalAddress(), targetAddress,
getVendorId(), params));
} else {
sendCecCommand(HdmiCecMessageBuilder.buildVendorCommand(
device.getDeviceInfo().getLogicalAddress(), targetAddress, params));
}
}
});
}
@Override
public void setHdmiRecordListener(IHdmiRecordListener listener) {
HdmiControlService.this.setHdmiRecordListener(listener);
}
@Override
public void startOneTouchRecord(final int recorderAddress, final byte[] recordSource) {
runOnServiceThread(new Runnable() {
@Override
public void run() {
if (!isTvDevice()) {
Slog.w(TAG, "No TV is available.");
return;
}
tv().startOneTouchRecord(recorderAddress, recordSource);
}
});
}
@Override
public void stopOneTouchRecord(final int recorderAddress) {
runOnServiceThread(new Runnable() {
@Override
public void run() {
if (!isTvDevice()) {
Slog.w(TAG, "No TV is available.");
return;
}
tv().stopOneTouchRecord(recorderAddress);
}
});
}
@Override
public void startTimerRecording(final int recorderAddress, final int sourceType,
final byte[] recordSource) {
runOnServiceThread(new Runnable() {
@Override
public void run() {
if (!isTvDevice()) {
Slog.w(TAG, "No TV is available.");
return;
}
tv().startTimerRecording(recorderAddress, sourceType, recordSource);
}
});
}
@Override
public void clearTimerRecording(final int recorderAddress, final int sourceType,
final byte[] recordSource) {
runOnServiceThread(new Runnable() {
@Override
public void run() {
if (!isTvDevice()) {
Slog.w(TAG, "No TV is available.");
return;
}
tv().clearTimerRecording(recorderAddress, sourceType, recordSource);
}
});
}
@Override
public void sendMhlVendorCommand(final int portId, final int offset, final int length,
final byte[] data) {
enforceAccessPermission();
runOnServiceThread(new Runnable() {
@Override
public void run() {
if (!isControlEnabled()) {
Slog.w(TAG, "Hdmi control is disabled.");
return ;
}
HdmiMhlLocalDevice device = mMhlController.getLocalDevice(portId);
if (device == null) {
Slog.w(TAG, "Invalid port id:" + portId);
return;
}
mMhlController.sendVendorCommand(portId, offset, length, data);
}
});
}
@Override
public void addHdmiMhlVendorCommandListener(
IHdmiMhlVendorCommandListener listener) {
enforceAccessPermission();
HdmiControlService.this.addHdmiMhlVendorCommandListener(listener);
}
@Override
protected void dump(FileDescriptor fd, final PrintWriter writer, String[] args) {
getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
pw.println("mHdmiControlEnabled: " + mHdmiControlEnabled);
pw.println("mProhibitMode: " + mProhibitMode);
if (mCecController != null) {
pw.println("mCecController: ");
pw.increaseIndent();
mCecController.dump(pw);
pw.decreaseIndent();
}
pw.println("mPortInfo: ");
pw.increaseIndent();
for (HdmiPortInfo hdmiPortInfo : mPortInfo) {
pw.println("- " + hdmiPortInfo);
}
pw.decreaseIndent();
pw.println("mPowerStatus: " + mPowerStatus);
}
}
@ServiceThreadOnly
private void oneTouchPlay(final IHdmiControlCallback callback) {
assertRunOnServiceThread();
HdmiCecLocalDevicePlayback source = playback();
if (source == null) {
Slog.w(TAG, "Local playback device not available");
invokeCallback(callback, HdmiControlManager.RESULT_SOURCE_NOT_AVAILABLE);
return;
}
source.oneTouchPlay(callback);
}
@ServiceThreadOnly
private void queryDisplayStatus(final IHdmiControlCallback callback) {
assertRunOnServiceThread();
HdmiCecLocalDevicePlayback source = playback();
if (source == null) {
Slog.w(TAG, "Local playback device not available");
invokeCallback(callback, HdmiControlManager.RESULT_SOURCE_NOT_AVAILABLE);
return;
}
source.queryDisplayStatus(callback);
}
private void addHotplugEventListener(IHdmiHotplugEventListener listener) {
HotplugEventListenerRecord record = new HotplugEventListenerRecord(listener);
try {
listener.asBinder().linkToDeath(record, 0);
} catch (RemoteException e) {
Slog.w(TAG, "Listener already died");
return;
}
synchronized (mLock) {
mHotplugEventListenerRecords.add(record);
}
}
private void removeHotplugEventListener(IHdmiHotplugEventListener listener) {
synchronized (mLock) {
for (HotplugEventListenerRecord record : mHotplugEventListenerRecords) {
if (record.mListener.asBinder() == listener.asBinder()) {
listener.asBinder().unlinkToDeath(record, 0);
mHotplugEventListenerRecords.remove(record);
break;
}
}
}
}
private void addDeviceEventListener(IHdmiDeviceEventListener listener) {
DeviceEventListenerRecord record = new DeviceEventListenerRecord(listener);
try {
listener.asBinder().linkToDeath(record, 0);
} catch (RemoteException e) {
Slog.w(TAG, "Listener already died");
return;
}
synchronized (mLock) {
mDeviceEventListenerRecords.add(record);
}
}
void invokeDeviceEventListeners(HdmiDeviceInfo device, int status) {
synchronized (mLock) {
for (DeviceEventListenerRecord record : mDeviceEventListenerRecords) {
try {
record.mListener.onStatusChanged(device, status);
} catch (RemoteException e) {
Slog.e(TAG, "Failed to report device event:" + e);
}
}
}
}
private void addSystemAudioModeChangeListner(IHdmiSystemAudioModeChangeListener listener) {
SystemAudioModeChangeListenerRecord record = new SystemAudioModeChangeListenerRecord(
listener);
try {
listener.asBinder().linkToDeath(record, 0);
} catch (RemoteException e) {
Slog.w(TAG, "Listener already died");
return;
}
synchronized (mLock) {
mSystemAudioModeChangeListenerRecords.add(record);
}
}
private void removeSystemAudioModeChangeListener(IHdmiSystemAudioModeChangeListener listener) {
synchronized (mLock) {
for (SystemAudioModeChangeListenerRecord record :
mSystemAudioModeChangeListenerRecords) {
if (record.mListener.asBinder() == listener) {
listener.asBinder().unlinkToDeath(record, 0);
mSystemAudioModeChangeListenerRecords.remove(record);
break;
}
}
}
}
private final class InputChangeListenerRecord implements IBinder.DeathRecipient {
private final IHdmiInputChangeListener mListener;
public InputChangeListenerRecord(IHdmiInputChangeListener listener) {
mListener = listener;
}
@Override
public void binderDied() {
synchronized (mLock) {
mInputChangeListenerRecord = null;
}
}
}
private void setInputChangeListener(IHdmiInputChangeListener listener) {
synchronized (mLock) {
mInputChangeListenerRecord = new InputChangeListenerRecord(listener);
try {
listener.asBinder().linkToDeath(mInputChangeListenerRecord, 0);
} catch (RemoteException e) {
Slog.w(TAG, "Listener already died");
return;
}
}
}
void invokeInputChangeListener(HdmiDeviceInfo info) {
synchronized (mLock) {
if (mInputChangeListenerRecord != null) {
try {
mInputChangeListenerRecord.mListener.onChanged(info);
} catch (RemoteException e) {
Slog.w(TAG, "Exception thrown by IHdmiInputChangeListener: " + e);
}
}
}
}
private void setHdmiRecordListener(IHdmiRecordListener listener) {
synchronized (mLock) {
mRecordListenerRecord = new HdmiRecordListenerRecord(listener);
try {
listener.asBinder().linkToDeath(mRecordListenerRecord, 0);
} catch (RemoteException e) {
Slog.w(TAG, "Listener already died.", e);
}
}
}
byte[] invokeRecordRequestListener(int recorderAddress) {
synchronized (mLock) {
if (mRecordListenerRecord != null) {
try {
return mRecordListenerRecord.mListener.getOneTouchRecordSource(recorderAddress);
} catch (RemoteException e) {
Slog.w(TAG, "Failed to start record.", e);
}
}
return EmptyArray.BYTE;
}
}
void invokeOneTouchRecordResult(int result) {
synchronized (mLock) {
if (mRecordListenerRecord != null) {
try {
mRecordListenerRecord.mListener.onOneTouchRecordResult(result);
} catch (RemoteException e) {
Slog.w(TAG, "Failed to call onOneTouchRecordResult.", e);
}
}
}
}
void invokeTimerRecordingResult(int result) {
synchronized (mLock) {
if (mRecordListenerRecord != null) {
try {
mRecordListenerRecord.mListener.onTimerRecordingResult(result);
} catch (RemoteException e) {
Slog.w(TAG, "Failed to call onTimerRecordingResult.", e);
}
}
}
}
void invokeClearTimerRecordingResult(int result) {
synchronized (mLock) {
if (mRecordListenerRecord != null) {
try {
mRecordListenerRecord.mListener.onClearTimerRecordingResult(result);
} catch (RemoteException e) {
Slog.w(TAG, "Failed to call onClearTimerRecordingResult.", e);
}
}
}
}
private void invokeCallback(IHdmiControlCallback callback, int result) {
try {
callback.onComplete(result);
} catch (RemoteException e) {
Slog.e(TAG, "Invoking callback failed:" + e);
}
}
private void invokeSystemAudioModeChangeLocked(IHdmiSystemAudioModeChangeListener listener,
boolean enabled) {
try {
listener.onStatusChanged(enabled);
} catch (RemoteException e) {
Slog.e(TAG, "Invoking callback failed:" + e);
}
}
private void announceHotplugEvent(int portId, boolean connected) {
HdmiHotplugEvent event = new HdmiHotplugEvent(portId, connected);
synchronized (mLock) {
for (HotplugEventListenerRecord record : mHotplugEventListenerRecords) {
invokeHotplugEventListenerLocked(record.mListener, event);
}
}
}
private void invokeHotplugEventListenerLocked(IHdmiHotplugEventListener listener,
HdmiHotplugEvent event) {
try {
listener.onReceived(event);
} catch (RemoteException e) {
Slog.e(TAG, "Failed to report hotplug event:" + event.toString(), e);
}
}
private HdmiCecLocalDeviceTv tv() {
return (HdmiCecLocalDeviceTv) mCecController.getLocalDevice(HdmiDeviceInfo.DEVICE_TV);
}
boolean isTvDevice() {
return tv() != null;
}
private HdmiCecLocalDevicePlayback playback() {
return (HdmiCecLocalDevicePlayback)
mCecController.getLocalDevice(HdmiDeviceInfo.DEVICE_PLAYBACK);
}
AudioManager getAudioManager() {
return (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
}
boolean isControlEnabled() {
synchronized (mLock) {
return mHdmiControlEnabled;
}
}
@ServiceThreadOnly
int getPowerStatus() {
assertRunOnServiceThread();
return mPowerStatus;
}
@ServiceThreadOnly
boolean isPowerOnOrTransient() {
assertRunOnServiceThread();
return mPowerStatus == HdmiControlManager.POWER_STATUS_ON
|| mPowerStatus == HdmiControlManager.POWER_STATUS_TRANSIENT_TO_ON;
}
@ServiceThreadOnly
boolean isPowerStandbyOrTransient() {
assertRunOnServiceThread();
return mPowerStatus == HdmiControlManager.POWER_STATUS_STANDBY
|| mPowerStatus == HdmiControlManager.POWER_STATUS_TRANSIENT_TO_STANDBY;
}
@ServiceThreadOnly
boolean isPowerStandby() {
assertRunOnServiceThread();
return mPowerStatus == HdmiControlManager.POWER_STATUS_STANDBY;
}
@ServiceThreadOnly
void wakeUp() {
assertRunOnServiceThread();
mWakeUpMessageReceived = true;
PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
pm.wakeUp(SystemClock.uptimeMillis());
// PowerManger will send the broadcast Intent.ACTION_SCREEN_ON and after this gets
// the intent, the sequence will continue at onWakeUp().
}
@ServiceThreadOnly
void standby() {
assertRunOnServiceThread();
mStandbyMessageReceived = true;
PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
pm.goToSleep(SystemClock.uptimeMillis(), PowerManager.GO_TO_SLEEP_REASON_HDMI, 0);
// PowerManger will send the broadcast Intent.ACTION_SCREEN_OFF and after this gets
// the intent, the sequence will continue at onStandby().
}
@ServiceThreadOnly
private void onWakeUp() {
assertRunOnServiceThread();
mPowerStatus = HdmiControlManager.POWER_STATUS_TRANSIENT_TO_ON;
if (mCecController != null) {
if (mHdmiControlEnabled) {
int startReason = INITIATED_BY_SCREEN_ON;
if (mWakeUpMessageReceived) {
startReason = INITIATED_BY_WAKE_UP_MESSAGE;
}
initializeCec(startReason);
}
} else {
Slog.i(TAG, "Device does not support HDMI-CEC.");
}
// TODO: Initialize MHL local devices.
}
@ServiceThreadOnly
private void onStandby() {
assertRunOnServiceThread();
mPowerStatus = HdmiControlManager.POWER_STATUS_TRANSIENT_TO_STANDBY;
final List devices = getAllLocalDevices();
disableDevices(new PendingActionClearedCallback() {
@Override
public void onCleared(HdmiCecLocalDevice device) {
Slog.v(TAG, "On standby-action cleared:" + device.mDeviceType);
devices.remove(device);
if (devices.isEmpty()) {
onStandbyCompleted();
// We will not clear local devices here, since some OEM/SOC will keep passing
// the received packets until the application processor enters to the sleep
// actually.
}
}
});
}
@ServiceThreadOnly
private void onLanguageChanged(String language) {
assertRunOnServiceThread();
mLanguage = language;
if (isTvDevice()) {
tv().broadcastMenuLanguage(language);
}
}
@ServiceThreadOnly
String getLanguage() {
assertRunOnServiceThread();
return mLanguage;
}
private void disableDevices(PendingActionClearedCallback callback) {
if (mCecController != null) {
for (HdmiCecLocalDevice device : mCecController.getLocalDeviceList()) {
device.disableDevice(mStandbyMessageReceived, callback);
}
if (isTvDevice()) {
unregisterSettingsObserver();
}
}
mMhlController.clearAllLocalDevices();
}
@ServiceThreadOnly
private void clearLocalDevices() {
assertRunOnServiceThread();
if (mCecController == null) {
return;
}
mCecController.clearLogicalAddress();
mCecController.clearLocalDevices();
}
@ServiceThreadOnly
private void onStandbyCompleted() {
assertRunOnServiceThread();
Slog.v(TAG, "onStandbyCompleted");
if (mPowerStatus != HdmiControlManager.POWER_STATUS_TRANSIENT_TO_STANDBY) {
return;
}
mPowerStatus = HdmiControlManager.POWER_STATUS_STANDBY;
for (HdmiCecLocalDevice device : mCecController.getLocalDeviceList()) {
device.onStandby(mStandbyMessageReceived);
}
mStandbyMessageReceived = false;
mCecController.setOption(OPTION_CEC_SERVICE_CONTROL, DISABLED);
}
private void addVendorCommandListener(IHdmiVendorCommandListener listener, int deviceType) {
VendorCommandListenerRecord record = new VendorCommandListenerRecord(listener, deviceType);
try {
listener.asBinder().linkToDeath(record, 0);
} catch (RemoteException e) {
Slog.w(TAG, "Listener already died");
return;
}
synchronized (mLock) {
mVendorCommandListenerRecords.add(record);
}
}
void invokeVendorCommandListeners(int deviceType, int srcAddress, byte[] params,
boolean hasVendorId) {
synchronized (mLock) {
for (VendorCommandListenerRecord record : mVendorCommandListenerRecords) {
if (record.mDeviceType != deviceType) {
continue;
}
try {
record.mListener.onReceived(srcAddress, params, hasVendorId);
} catch (RemoteException e) {
Slog.e(TAG, "Failed to notify vendor command reception", e);
}
}
}
}
private void addHdmiMhlVendorCommandListener(IHdmiMhlVendorCommandListener listener) {
HdmiMhlVendorCommandListenerRecord record =
new HdmiMhlVendorCommandListenerRecord(listener);
try {
listener.asBinder().linkToDeath(record, 0);
} catch (RemoteException e) {
Slog.w(TAG, "Listener already died.");
return;
}
synchronized (mLock) {
mMhlVendorCommandListenerRecords.add(record);
}
}
void invokeMhlVendorCommandListeners(int portId, int offest, int length, byte[] data) {
synchronized (mLock) {
for (HdmiMhlVendorCommandListenerRecord record : mMhlVendorCommandListenerRecords) {
try {
record.mListener.onReceived(portId, offest, length, data);
} catch (RemoteException e) {
Slog.e(TAG, "Failed to notify MHL vendor command", e);
}
}
}
}
boolean isProhibitMode() {
synchronized (mLock) {
return mProhibitMode;
}
}
void setProhibitMode(boolean enabled) {
synchronized (mLock) {
mProhibitMode = enabled;
}
}
@ServiceThreadOnly
void setCecOption(int key, int value) {
assertRunOnServiceThread();
mCecController.setOption(key, value);
}
@ServiceThreadOnly
void setControlEnabled(boolean enabled) {
assertRunOnServiceThread();
int value = toInt(enabled);
mCecController.setOption(OPTION_CEC_ENABLE, value);
mMhlController.setOption(OPTION_MHL_ENABLE, value);
synchronized (mLock) {
mHdmiControlEnabled = enabled;
}
if (enabled) {
initializeCec(INITIATED_BY_ENABLE_CEC);
} else {
disableDevices(new PendingActionClearedCallback() {
@Override
public void onCleared(HdmiCecLocalDevice device) {
assertRunOnServiceThread();
clearLocalDevices();
}
});
}
}
@ServiceThreadOnly
void setActivePortId(int portId) {
assertRunOnServiceThread();
mActivePortId = portId;
// Resets last input for MHL, which stays valid only after the MHL device was selected,
// and no further switching is done.
setLastInputForMhl(Constants.INVALID_PORT_ID);
}
@ServiceThreadOnly
void setLastInputForMhl(int portId) {
assertRunOnServiceThread();
mLastInputMhl = portId;
}
@ServiceThreadOnly
int getLastInputForMhl() {
assertRunOnServiceThread();
return mLastInputMhl;
}
/**
* Performs input change, routing control for MHL device.
*
* @param portId MHL port, or the last port to go back to if {@code contentOn} is false
* @param contentOn {@code true} if RAP data is content on; otherwise false
*/
@ServiceThreadOnly
void changeInputForMhl(int portId, boolean contentOn) {
assertRunOnServiceThread();
final int lastInput = contentOn ? tv().getActivePortId() : Constants.INVALID_PORT_ID;
tv().doManualPortSwitching(portId, new IHdmiControlCallback.Stub() {
@Override
public void onComplete(int result) throws RemoteException {
// Keep the last input to switch back later when RAP[ContentOff] is received.
// This effectively sets the port to invalid one if the switching is for
// RAP[ContentOff].
setLastInputForMhl(lastInput);
}
});
// MHL device is always directly connected to the port. Update the active port ID to avoid
// unnecessary post-routing control task.
tv().setActivePortId(portId);
// The port is either the MHL-enabled port where the mobile device is connected, or
// the last port to go back to when turnoff command is received. Note that the last port
// may not be the MHL-enabled one. In this case the device info to be passed to
// input change listener should be the one describing the corresponding HDMI port.
HdmiMhlLocalDevice device = mMhlController.getLocalDevice(portId);
HdmiDeviceInfo info = (device != null && device.getInfo() != null)
? device.getInfo()
: mPortDeviceMap.get(portId);
invokeInputChangeListener(info);
}
void setMhlInputChangeEnabled(boolean enabled) {
mMhlController.setOption(OPTION_MHL_INPUT_SWITCHING, toInt(enabled));
synchronized (mLock) {
mMhlInputChangeEnabled = enabled;
}
}
boolean isMhlInputChangeEnabled() {
synchronized (mLock) {
return mMhlInputChangeEnabled;
}
}
@ServiceThreadOnly
void displayOsd(int messageId) {
assertRunOnServiceThread();
Intent intent = new Intent(HdmiControlManager.ACTION_OSD_MESSAGE);
intent.putExtra(HdmiControlManager.EXTRA_MESSAGE_ID, messageId);
getContext().sendBroadcastAsUser(intent, UserHandle.ALL,
HdmiControlService.PERMISSION);
}
@ServiceThreadOnly
void displayOsd(int messageId, int extra) {
assertRunOnServiceThread();
Intent intent = new Intent(HdmiControlManager.ACTION_OSD_MESSAGE);
intent.putExtra(HdmiControlManager.EXTRA_MESSAGE_ID, messageId);
intent.putExtra(HdmiControlManager.EXTRA_MESSAGE_EXTRAM_PARAM1, extra);
getContext().sendBroadcastAsUser(intent, UserHandle.ALL,
HdmiControlService.PERMISSION);
}
}