TvInputHardwareManager.java revision e92f857d50d7259a4cf7ef5b88309e098338c9c1
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.tv; 18 19import static android.media.tv.TvInputManager.INPUT_STATE_CONNECTED; 20import static android.media.tv.TvInputManager.INPUT_STATE_DISCONNECTED; 21 22import android.content.Context; 23import android.content.Intent; 24import android.hardware.hdmi.HdmiControlManager; 25import android.hardware.hdmi.HdmiDeviceInfo; 26import android.hardware.hdmi.HdmiHotplugEvent; 27import android.hardware.hdmi.IHdmiControlService; 28import android.hardware.hdmi.IHdmiDeviceEventListener; 29import android.hardware.hdmi.IHdmiHotplugEventListener; 30import android.hardware.hdmi.IHdmiInputChangeListener; 31import android.hardware.hdmi.IHdmiSystemAudioModeChangeListener; 32import android.media.AudioDevicePort; 33import android.media.AudioFormat; 34import android.media.AudioGain; 35import android.media.AudioGainConfig; 36import android.media.AudioManager; 37import android.media.AudioPatch; 38import android.media.AudioPort; 39import android.media.AudioPortConfig; 40import android.media.tv.ITvInputHardware; 41import android.media.tv.ITvInputHardwareCallback; 42import android.media.tv.TvContract; 43import android.media.tv.TvInputHardwareInfo; 44import android.media.tv.TvInputInfo; 45import android.media.tv.TvStreamConfig; 46import android.os.Handler; 47import android.os.IBinder; 48import android.os.Message; 49import android.os.RemoteException; 50import android.os.ServiceManager; 51import android.util.ArrayMap; 52import android.util.Slog; 53import android.util.SparseArray; 54import android.util.SparseBooleanArray; 55import android.view.KeyEvent; 56import android.view.Surface; 57 58import com.android.internal.os.SomeArgs; 59import com.android.server.SystemService; 60 61import java.util.ArrayList; 62import java.util.Arrays; 63import java.util.Collections; 64import java.util.Iterator; 65import java.util.LinkedList; 66import java.util.List; 67import java.util.Map; 68 69/** 70 * A helper class for TvInputManagerService to handle TV input hardware. 71 * 72 * This class does a basic connection management and forwarding calls to TvInputHal which eventually 73 * calls to tv_input HAL module. 74 * 75 * @hide 76 */ 77class TvInputHardwareManager implements TvInputHal.Callback { 78 private static final String TAG = TvInputHardwareManager.class.getSimpleName(); 79 80 private final Context mContext; 81 private final Listener mListener; 82 private final TvInputHal mHal = new TvInputHal(this); 83 private final SparseArray<Connection> mConnections = new SparseArray<>(); 84 private final List<TvInputHardwareInfo> mHardwareList = new ArrayList<>(); 85 private final List<HdmiDeviceInfo> mHdmiDeviceList = new LinkedList<>(); 86 /* A map from a device ID to the matching TV input ID. */ 87 private final SparseArray<String> mHardwareInputIdMap = new SparseArray<>(); 88 /* A map from a HDMI logical address to the matching TV input ID. */ 89 private final SparseArray<String> mHdmiInputIdMap = new SparseArray<>(); 90 private final Map<String, TvInputInfo> mInputMap = new ArrayMap<>(); 91 92 private final AudioManager mAudioManager; 93 private IHdmiControlService mHdmiControlService; 94 private final IHdmiHotplugEventListener mHdmiHotplugEventListener = 95 new HdmiHotplugEventListener(); 96 private final IHdmiDeviceEventListener mHdmiDeviceEventListener = new HdmiDeviceEventListener(); 97 private final IHdmiSystemAudioModeChangeListener mHdmiSystemAudioModeChangeListener = 98 new HdmiSystemAudioModeChangeListener(); 99 100 // TODO: Should handle STANDBY case. 101 private final SparseBooleanArray mHdmiStateMap = new SparseBooleanArray(); 102 private final List<Message> mPendingHdmiDeviceEvents = new LinkedList<>(); 103 104 // Calls to mListener should happen here. 105 private final Handler mHandler = new ListenerHandler(); 106 107 private final Object mLock = new Object(); 108 109 public TvInputHardwareManager(Context context, Listener listener) { 110 mContext = context; 111 mListener = listener; 112 mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 113 mHal.init(); 114 } 115 116 public void onBootPhase(int phase) { 117 if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY) { 118 mHdmiControlService = IHdmiControlService.Stub.asInterface(ServiceManager.getService( 119 Context.HDMI_CONTROL_SERVICE)); 120 if (mHdmiControlService != null) { 121 try { 122 mHdmiControlService.addHotplugEventListener(mHdmiHotplugEventListener); 123 mHdmiControlService.addDeviceEventListener(mHdmiDeviceEventListener); 124 mHdmiControlService.addSystemAudioModeChangeListener( 125 mHdmiSystemAudioModeChangeListener); 126 mHdmiDeviceList.addAll(mHdmiControlService.getInputDevices()); 127 } catch (RemoteException e) { 128 Slog.w(TAG, "Error registering listeners to HdmiControlService:", e); 129 } 130 } 131 } 132 } 133 134 @Override 135 public void onDeviceAvailable(TvInputHardwareInfo info, TvStreamConfig[] configs) { 136 synchronized (mLock) { 137 Connection connection = new Connection(info); 138 connection.updateConfigsLocked(configs); 139 mConnections.put(info.getDeviceId(), connection); 140 buildHardwareListLocked(); 141 mHandler.obtainMessage( 142 ListenerHandler.HARDWARE_DEVICE_ADDED, 0, 0, info).sendToTarget(); 143 if (info.getType() == TvInputHardwareInfo.TV_INPUT_TYPE_HDMI) { 144 processPendingHdmiDeviceEventsLocked(); 145 } 146 } 147 } 148 149 private void buildHardwareListLocked() { 150 mHardwareList.clear(); 151 for (int i = 0; i < mConnections.size(); ++i) { 152 mHardwareList.add(mConnections.valueAt(i).getHardwareInfoLocked()); 153 } 154 } 155 156 @Override 157 public void onDeviceUnavailable(int deviceId) { 158 synchronized (mLock) { 159 Connection connection = mConnections.get(deviceId); 160 if (connection == null) { 161 Slog.e(TAG, "onDeviceUnavailable: Cannot find a connection with " + deviceId); 162 return; 163 } 164 connection.resetLocked(null, null, null, null, null); 165 mConnections.remove(deviceId); 166 buildHardwareListLocked(); 167 TvInputHardwareInfo info = connection.getHardwareInfoLocked(); 168 if (info.getType() == TvInputHardwareInfo.TV_INPUT_TYPE_HDMI) { 169 // Remove HDMI devices linked with this hardware. 170 for (Iterator<HdmiDeviceInfo> it = mHdmiDeviceList.iterator(); it.hasNext();) { 171 HdmiDeviceInfo deviceInfo = it.next(); 172 if (deviceInfo.getPortId() == info.getHdmiPortId()) { 173 mHandler.obtainMessage(ListenerHandler.HDMI_DEVICE_REMOVED, 0, 0, 174 deviceInfo).sendToTarget(); 175 it.remove(); 176 } 177 } 178 } 179 mHandler.obtainMessage( 180 ListenerHandler.HARDWARE_DEVICE_REMOVED, 0, 0, info).sendToTarget(); 181 } 182 } 183 184 @Override 185 public void onStreamConfigurationChanged(int deviceId, TvStreamConfig[] configs) { 186 synchronized (mLock) { 187 Connection connection = mConnections.get(deviceId); 188 if (connection == null) { 189 Slog.e(TAG, "StreamConfigurationChanged: Cannot find a connection with " 190 + deviceId); 191 return; 192 } 193 connection.updateConfigsLocked(configs); 194 try { 195 connection.getCallbackLocked().onStreamConfigChanged(configs); 196 } catch (RemoteException e) { 197 Slog.e(TAG, "error in onStreamConfigurationChanged", e); 198 } 199 } 200 } 201 202 @Override 203 public void onFirstFrameCaptured(int deviceId, int streamId) { 204 synchronized (mLock) { 205 Connection connection = mConnections.get(deviceId); 206 if (connection == null) { 207 Slog.e(TAG, "FirstFrameCaptured: Cannot find a connection with " 208 + deviceId); 209 return; 210 } 211 Runnable runnable = connection.getOnFirstFrameCapturedLocked(); 212 if (runnable != null) { 213 runnable.run(); 214 connection.setOnFirstFrameCapturedLocked(null); 215 } 216 } 217 } 218 219 public List<TvInputHardwareInfo> getHardwareList() { 220 synchronized (mLock) { 221 return Collections.unmodifiableList(mHardwareList); 222 } 223 } 224 225 public List<HdmiDeviceInfo> getHdmiDeviceList() { 226 synchronized (mLock) { 227 return Collections.unmodifiableList(mHdmiDeviceList); 228 } 229 } 230 231 private boolean checkUidChangedLocked( 232 Connection connection, int callingUid, int resolvedUserId) { 233 Integer connectionCallingUid = connection.getCallingUidLocked(); 234 Integer connectionResolvedUserId = connection.getResolvedUserIdLocked(); 235 if (connectionCallingUid == null || connectionResolvedUserId == null) { 236 return true; 237 } 238 if (connectionCallingUid != callingUid || connectionResolvedUserId != resolvedUserId) { 239 return true; 240 } 241 return false; 242 } 243 244 private int convertConnectedToState(boolean connected) { 245 if (connected) { 246 return INPUT_STATE_CONNECTED; 247 } else { 248 return INPUT_STATE_DISCONNECTED; 249 } 250 } 251 252 public void addHardwareTvInput(int deviceId, TvInputInfo info) { 253 synchronized (mLock) { 254 String oldInputId = mHardwareInputIdMap.get(deviceId); 255 if (oldInputId != null) { 256 Slog.w(TAG, "Trying to override previous registration: old = " 257 + mInputMap.get(oldInputId) + ":" + deviceId + ", new = " 258 + info + ":" + deviceId); 259 } 260 mHardwareInputIdMap.put(deviceId, info.getId()); 261 mInputMap.put(info.getId(), info); 262 263 for (int i = 0; i < mHdmiStateMap.size(); ++i) { 264 TvInputHardwareInfo hardwareInfo = 265 findHardwareInfoForHdmiPortLocked(mHdmiStateMap.keyAt(i)); 266 if (hardwareInfo == null) { 267 continue; 268 } 269 String inputId = mHardwareInputIdMap.get(hardwareInfo.getDeviceId()); 270 if (inputId != null && inputId.equals(info.getId())) { 271 mHandler.obtainMessage(ListenerHandler.STATE_CHANGED, 272 convertConnectedToState(mHdmiStateMap.valueAt(i)), 0, 273 inputId).sendToTarget(); 274 } 275 } 276 } 277 } 278 279 private static <T> int indexOfEqualValue(SparseArray<T> map, T value) { 280 for (int i = 0; i < map.size(); ++i) { 281 if (map.valueAt(i).equals(value)) { 282 return i; 283 } 284 } 285 return -1; 286 } 287 288 public void addHdmiTvInput(int logicalAddress, TvInputInfo info) { 289 if (info.getType() != TvInputInfo.TYPE_HDMI) { 290 throw new IllegalArgumentException("info (" + info + ") has non-HDMI type."); 291 } 292 synchronized (mLock) { 293 String parentId = info.getParentId(); 294 int parentIndex = indexOfEqualValue(mHardwareInputIdMap, parentId); 295 if (parentIndex < 0) { 296 throw new IllegalArgumentException("info (" + info + ") has invalid parentId."); 297 } 298 String oldInputId = mHdmiInputIdMap.get(logicalAddress); 299 if (oldInputId != null) { 300 Slog.w(TAG, "Trying to override previous registration: old = " 301 + mInputMap.get(oldInputId) + ":" + logicalAddress + ", new = " 302 + info + ":" + logicalAddress); 303 } 304 mHdmiInputIdMap.put(logicalAddress, info.getId()); 305 mInputMap.put(info.getId(), info); 306 } 307 } 308 309 public void removeTvInput(String inputId) { 310 synchronized (mLock) { 311 mInputMap.remove(inputId); 312 int hardwareIndex = indexOfEqualValue(mHardwareInputIdMap, inputId); 313 if (hardwareIndex >= 0) { 314 mHardwareInputIdMap.removeAt(hardwareIndex); 315 } 316 int deviceIndex = indexOfEqualValue(mHdmiInputIdMap, inputId); 317 if (deviceIndex >= 0) { 318 mHdmiInputIdMap.removeAt(deviceIndex); 319 } 320 } 321 } 322 323 /** 324 * Create a TvInputHardware object with a specific deviceId. One service at a time can access 325 * the object, and if more than one process attempts to create hardware with the same deviceId, 326 * the latest service will get the object and all the other hardware are released. The 327 * release is notified via ITvInputHardwareCallback.onReleased(). 328 */ 329 public ITvInputHardware acquireHardware(int deviceId, ITvInputHardwareCallback callback, 330 TvInputInfo info, int callingUid, int resolvedUserId) { 331 if (callback == null) { 332 throw new NullPointerException(); 333 } 334 synchronized (mLock) { 335 Connection connection = mConnections.get(deviceId); 336 if (connection == null) { 337 Slog.e(TAG, "Invalid deviceId : " + deviceId); 338 return null; 339 } 340 if (checkUidChangedLocked(connection, callingUid, resolvedUserId)) { 341 TvInputHardwareImpl hardware = 342 new TvInputHardwareImpl(connection.getHardwareInfoLocked()); 343 try { 344 callback.asBinder().linkToDeath(connection, 0); 345 } catch (RemoteException e) { 346 hardware.release(); 347 return null; 348 } 349 connection.resetLocked(hardware, callback, info, callingUid, resolvedUserId); 350 } 351 return connection.getHardwareLocked(); 352 } 353 } 354 355 /** 356 * Release the specified hardware. 357 */ 358 public void releaseHardware(int deviceId, ITvInputHardware hardware, int callingUid, 359 int resolvedUserId) { 360 synchronized (mLock) { 361 Connection connection = mConnections.get(deviceId); 362 if (connection == null) { 363 Slog.e(TAG, "Invalid deviceId : " + deviceId); 364 return; 365 } 366 if (connection.getHardwareLocked() != hardware 367 || checkUidChangedLocked(connection, callingUid, resolvedUserId)) { 368 return; 369 } 370 connection.resetLocked(null, null, null, null, null); 371 } 372 } 373 374 private TvInputHardwareInfo findHardwareInfoForHdmiPortLocked(int port) { 375 for (TvInputHardwareInfo hardwareInfo : mHardwareList) { 376 if (hardwareInfo.getType() == TvInputHardwareInfo.TV_INPUT_TYPE_HDMI 377 && hardwareInfo.getHdmiPortId() == port) { 378 return hardwareInfo; 379 } 380 } 381 return null; 382 } 383 384 private int findDeviceIdForInputIdLocked(String inputId) { 385 for (int i = 0; i < mConnections.size(); ++i) { 386 Connection connection = mConnections.get(i); 387 if (connection.getInfoLocked().getId().equals(inputId)) { 388 return i; 389 } 390 } 391 return -1; 392 } 393 394 /** 395 * Get the list of TvStreamConfig which is buffered mode. 396 */ 397 public List<TvStreamConfig> getAvailableTvStreamConfigList(String inputId, int callingUid, 398 int resolvedUserId) { 399 List<TvStreamConfig> configsList = new ArrayList<TvStreamConfig>(); 400 synchronized (mLock) { 401 int deviceId = findDeviceIdForInputIdLocked(inputId); 402 if (deviceId < 0) { 403 Slog.e(TAG, "Invalid inputId : " + inputId); 404 return configsList; 405 } 406 Connection connection = mConnections.get(deviceId); 407 for (TvStreamConfig config : connection.getConfigsLocked()) { 408 if (config.getType() == TvStreamConfig.STREAM_TYPE_BUFFER_PRODUCER) { 409 configsList.add(config); 410 } 411 } 412 } 413 return configsList; 414 } 415 416 /** 417 * Take a snapshot of the given TV input into the provided Surface. 418 */ 419 public boolean captureFrame(String inputId, Surface surface, final TvStreamConfig config, 420 int callingUid, int resolvedUserId) { 421 synchronized (mLock) { 422 int deviceId = findDeviceIdForInputIdLocked(inputId); 423 if (deviceId < 0) { 424 Slog.e(TAG, "Invalid inputId : " + inputId); 425 return false; 426 } 427 Connection connection = mConnections.get(deviceId); 428 final TvInputHardwareImpl hardwareImpl = connection.getHardwareImplLocked(); 429 if (hardwareImpl != null) { 430 // Stop previous capture. 431 Runnable runnable = connection.getOnFirstFrameCapturedLocked(); 432 if (runnable != null) { 433 runnable.run(); 434 connection.setOnFirstFrameCapturedLocked(null); 435 } 436 437 boolean result = hardwareImpl.startCapture(surface, config); 438 if (result) { 439 connection.setOnFirstFrameCapturedLocked(new Runnable() { 440 @Override 441 public void run() { 442 hardwareImpl.stopCapture(config); 443 } 444 }); 445 } 446 return result; 447 } 448 } 449 return false; 450 } 451 452 private void processPendingHdmiDeviceEventsLocked() { 453 for (Iterator<Message> it = mPendingHdmiDeviceEvents.iterator(); it.hasNext(); ) { 454 Message msg = it.next(); 455 HdmiDeviceInfo deviceInfo = (HdmiDeviceInfo) msg.obj; 456 TvInputHardwareInfo hardwareInfo = 457 findHardwareInfoForHdmiPortLocked(deviceInfo.getPortId()); 458 if (hardwareInfo != null) { 459 msg.sendToTarget(); 460 it.remove(); 461 } 462 } 463 } 464 465 private class Connection implements IBinder.DeathRecipient { 466 private final TvInputHardwareInfo mHardwareInfo; 467 private TvInputInfo mInfo; 468 private TvInputHardwareImpl mHardware = null; 469 private ITvInputHardwareCallback mCallback; 470 private TvStreamConfig[] mConfigs = null; 471 private Integer mCallingUid = null; 472 private Integer mResolvedUserId = null; 473 private Runnable mOnFirstFrameCaptured; 474 475 public Connection(TvInputHardwareInfo hardwareInfo) { 476 mHardwareInfo = hardwareInfo; 477 } 478 479 // *Locked methods assume TvInputHardwareManager.mLock is held. 480 481 public void resetLocked(TvInputHardwareImpl hardware, ITvInputHardwareCallback callback, 482 TvInputInfo info, Integer callingUid, Integer resolvedUserId) { 483 if (mHardware != null) { 484 try { 485 mCallback.onReleased(); 486 } catch (RemoteException e) { 487 Slog.e(TAG, "error in Connection::resetLocked", e); 488 } 489 mHardware.release(); 490 } 491 mHardware = hardware; 492 mCallback = callback; 493 mInfo = info; 494 mCallingUid = callingUid; 495 mResolvedUserId = resolvedUserId; 496 mOnFirstFrameCaptured = null; 497 498 if (mHardware != null && mCallback != null) { 499 try { 500 mCallback.onStreamConfigChanged(getConfigsLocked()); 501 } catch (RemoteException e) { 502 Slog.e(TAG, "error in Connection::resetLocked", e); 503 } 504 } 505 } 506 507 public void updateConfigsLocked(TvStreamConfig[] configs) { 508 mConfigs = configs; 509 } 510 511 public TvInputHardwareInfo getHardwareInfoLocked() { 512 return mHardwareInfo; 513 } 514 515 public TvInputInfo getInfoLocked() { 516 return mInfo; 517 } 518 519 public ITvInputHardware getHardwareLocked() { 520 return mHardware; 521 } 522 523 public TvInputHardwareImpl getHardwareImplLocked() { 524 return mHardware; 525 } 526 527 public ITvInputHardwareCallback getCallbackLocked() { 528 return mCallback; 529 } 530 531 public TvStreamConfig[] getConfigsLocked() { 532 return mConfigs; 533 } 534 535 public Integer getCallingUidLocked() { 536 return mCallingUid; 537 } 538 539 public Integer getResolvedUserIdLocked() { 540 return mResolvedUserId; 541 } 542 543 public void setOnFirstFrameCapturedLocked(Runnable runnable) { 544 mOnFirstFrameCaptured = runnable; 545 } 546 547 public Runnable getOnFirstFrameCapturedLocked() { 548 return mOnFirstFrameCaptured; 549 } 550 551 @Override 552 public void binderDied() { 553 synchronized (mLock) { 554 resetLocked(null, null, null, null, null); 555 } 556 } 557 } 558 559 private class TvInputHardwareImpl extends ITvInputHardware.Stub { 560 private final TvInputHardwareInfo mInfo; 561 private boolean mReleased = false; 562 private final Object mImplLock = new Object(); 563 564 private final AudioManager.OnAudioPortUpdateListener mAudioListener = 565 new AudioManager.OnAudioPortUpdateListener() { 566 @Override 567 public void onAudioPortListUpdate(AudioPort[] portList) { 568 synchronized (mImplLock) { 569 updateAudioConfigLocked(); 570 } 571 } 572 573 @Override 574 public void onAudioPatchListUpdate(AudioPatch[] patchList) { 575 // No-op 576 } 577 578 @Override 579 public void onServiceDied() { 580 synchronized (mImplLock) { 581 mAudioSource = null; 582 mAudioSink = null; 583 mAudioPatch = null; 584 } 585 } 586 }; 587 private int mOverrideAudioType = AudioManager.DEVICE_NONE; 588 private String mOverrideAudioAddress = ""; 589 private AudioDevicePort mAudioSource; 590 private AudioDevicePort mAudioSink; 591 private AudioPatch mAudioPatch = null; 592 private float mCommittedVolume = 0.0f; 593 private float mVolume = 0.0f; 594 595 private TvStreamConfig mActiveConfig = null; 596 597 private int mDesiredSamplingRate = 0; 598 private int mDesiredChannelMask = AudioFormat.CHANNEL_OUT_DEFAULT; 599 private int mDesiredFormat = AudioFormat.ENCODING_DEFAULT; 600 601 public TvInputHardwareImpl(TvInputHardwareInfo info) { 602 mInfo = info; 603 mAudioManager.registerAudioPortUpdateListener(mAudioListener); 604 if (mInfo.getAudioType() != AudioManager.DEVICE_NONE) { 605 mAudioSource = findAudioDevicePort(mInfo.getAudioType(), mInfo.getAudioAddress()); 606 mAudioSink = findAudioSinkFromAudioPolicy(); 607 } 608 } 609 610 private AudioDevicePort findAudioSinkFromAudioPolicy() { 611 ArrayList<AudioPort> devicePorts = new ArrayList<AudioPort>(); 612 if (mAudioManager.listAudioDevicePorts(devicePorts) == AudioManager.SUCCESS) { 613 int sinkDevice = mAudioManager.getDevicesForStream(AudioManager.STREAM_MUSIC); 614 for (AudioPort port : devicePorts) { 615 AudioDevicePort devicePort = (AudioDevicePort) port; 616 if ((devicePort.type() & sinkDevice) != 0) { 617 return devicePort; 618 } 619 } 620 } 621 return null; 622 } 623 624 private AudioDevicePort findAudioDevicePort(int type, String address) { 625 if (type == AudioManager.DEVICE_NONE) { 626 return null; 627 } 628 ArrayList<AudioPort> devicePorts = new ArrayList<AudioPort>(); 629 if (mAudioManager.listAudioDevicePorts(devicePorts) != AudioManager.SUCCESS) { 630 return null; 631 } 632 for (AudioPort port : devicePorts) { 633 AudioDevicePort devicePort = (AudioDevicePort) port; 634 if (devicePort.type() == type && devicePort.address().equals(address)) { 635 return devicePort; 636 } 637 } 638 return null; 639 } 640 641 public void release() { 642 synchronized (mImplLock) { 643 mAudioManager.unregisterAudioPortUpdateListener(mAudioListener); 644 if (mAudioPatch != null) { 645 mAudioManager.releaseAudioPatch(mAudioPatch); 646 mAudioPatch = null; 647 } 648 mReleased = true; 649 } 650 } 651 652 // A TvInputHardwareImpl object holds only one active session. Therefore, if a client 653 // attempts to call setSurface with different TvStreamConfig objects, the last call will 654 // prevail. 655 @Override 656 public boolean setSurface(Surface surface, TvStreamConfig config) 657 throws RemoteException { 658 synchronized (mImplLock) { 659 if (mReleased) { 660 throw new IllegalStateException("Device already released."); 661 } 662 if (surface != null && config == null) { 663 return false; 664 } 665 if (surface == null && mActiveConfig == null) { 666 return false; 667 } 668 669 int result = TvInputHal.ERROR_UNKNOWN; 670 if (surface == null) { 671 result = mHal.removeStream(mInfo.getDeviceId(), mActiveConfig); 672 mActiveConfig = null; 673 } else { 674 if (config != mActiveConfig && mActiveConfig != null) { 675 result = mHal.removeStream(mInfo.getDeviceId(), mActiveConfig); 676 if (result != TvInputHal.SUCCESS) { 677 mActiveConfig = null; 678 return false; 679 } 680 } 681 result = mHal.addStream(mInfo.getDeviceId(), surface, config); 682 if (result == TvInputHal.SUCCESS) { 683 mActiveConfig = config; 684 } 685 } 686 updateAudioConfigLocked(); 687 return result == TvInputHal.SUCCESS; 688 } 689 } 690 691 /** 692 * Update audio configuration (source, sink, patch) all up to current state. 693 */ 694 private void updateAudioConfigLocked() { 695 boolean sinkUpdated = updateAudioSinkLocked(); 696 boolean sourceUpdated = updateAudioSourceLocked(); 697 // We can't do updated = updateAudioSinkLocked() || updateAudioSourceLocked() here 698 // because Java won't evaluate the latter if the former is true. 699 700 if (mAudioSource == null || mAudioSink == null || mActiveConfig == null) { 701 if (mAudioPatch != null) { 702 mAudioManager.releaseAudioPatch(mAudioPatch); 703 mAudioPatch = null; 704 } 705 return; 706 } 707 708 AudioGainConfig sourceGainConfig = null; 709 if (mAudioSource.gains().length > 0 && mVolume != mCommittedVolume) { 710 AudioGain sourceGain = null; 711 for (AudioGain gain : mAudioSource.gains()) { 712 if ((gain.mode() & AudioGain.MODE_JOINT) != 0) { 713 sourceGain = gain; 714 break; 715 } 716 } 717 // NOTE: we only change the source gain in MODE_JOINT here. 718 if (sourceGain != null) { 719 int steps = (sourceGain.maxValue() - sourceGain.minValue()) 720 / sourceGain.stepValue(); 721 int gainValue = sourceGain.minValue(); 722 if (mVolume < 1.0f) { 723 gainValue += sourceGain.stepValue() * (int) (mVolume * steps + 0.5); 724 } else { 725 gainValue = sourceGain.maxValue(); 726 } 727 int numChannels = 0; 728 for (int mask = sourceGain.channelMask(); mask > 0; mask >>= 1) { 729 numChannels += (mask & 1); 730 } 731 int[] gainValues = new int[numChannels]; 732 Arrays.fill(gainValues, gainValue); 733 sourceGainConfig = sourceGain.buildConfig(AudioGain.MODE_JOINT, 734 sourceGain.channelMask(), gainValues, 0); 735 } else { 736 Slog.w(TAG, "No audio source gain with MODE_JOINT support exists."); 737 } 738 } 739 740 AudioPortConfig sourceConfig = mAudioSource.activeConfig(); 741 AudioPortConfig sinkConfig = mAudioSink.activeConfig(); 742 AudioPatch[] audioPatchArray = new AudioPatch[] { mAudioPatch }; 743 boolean shouldRecreateAudioPatch = sourceUpdated || sinkUpdated; 744 if (sinkConfig == null 745 || (mDesiredSamplingRate != 0 746 && sinkConfig.samplingRate() != mDesiredSamplingRate) 747 || (mDesiredChannelMask != AudioFormat.CHANNEL_OUT_DEFAULT 748 && sinkConfig.channelMask() != mDesiredChannelMask) 749 || (mDesiredFormat != AudioFormat.ENCODING_DEFAULT 750 && sinkConfig.format() != mDesiredFormat)) { 751 sinkConfig = mAudioSource.buildConfig(mDesiredSamplingRate, mDesiredChannelMask, 752 mDesiredFormat, null); 753 shouldRecreateAudioPatch = true; 754 } 755 if (sourceConfig == null || sourceGainConfig != null) { 756 sourceConfig = mAudioSource.buildConfig(sinkConfig.samplingRate(), 757 sinkConfig.channelMask(), sinkConfig.format(), sourceGainConfig); 758 shouldRecreateAudioPatch = true; 759 } 760 if (shouldRecreateAudioPatch) { 761 mCommittedVolume = mVolume; 762 mAudioManager.createAudioPatch( 763 audioPatchArray, 764 new AudioPortConfig[] { sourceConfig }, 765 new AudioPortConfig[] { sinkConfig }); 766 mAudioPatch = audioPatchArray[0]; 767 } 768 } 769 770 @Override 771 public void setStreamVolume(float volume) throws RemoteException { 772 synchronized (mImplLock) { 773 if (mReleased) { 774 throw new IllegalStateException("Device already released."); 775 } 776 mVolume = volume; 777 updateAudioConfigLocked(); 778 } 779 } 780 781 @Override 782 public boolean dispatchKeyEventToHdmi(KeyEvent event) throws RemoteException { 783 synchronized (mImplLock) { 784 if (mReleased) { 785 throw new IllegalStateException("Device already released."); 786 } 787 } 788 if (mInfo.getType() != TvInputHardwareInfo.TV_INPUT_TYPE_HDMI) { 789 return false; 790 } 791 // TODO(hdmi): mHdmiClient.sendKeyEvent(event); 792 return false; 793 } 794 795 private boolean startCapture(Surface surface, TvStreamConfig config) { 796 synchronized (mImplLock) { 797 if (mReleased) { 798 return false; 799 } 800 if (surface == null || config == null) { 801 return false; 802 } 803 if (config.getType() != TvStreamConfig.STREAM_TYPE_BUFFER_PRODUCER) { 804 return false; 805 } 806 807 int result = mHal.addStream(mInfo.getDeviceId(), surface, config); 808 return result == TvInputHal.SUCCESS; 809 } 810 } 811 812 private boolean stopCapture(TvStreamConfig config) { 813 synchronized (mImplLock) { 814 if (mReleased) { 815 return false; 816 } 817 if (config == null) { 818 return false; 819 } 820 821 int result = mHal.removeStream(mInfo.getDeviceId(), config); 822 return result == TvInputHal.SUCCESS; 823 } 824 } 825 826 private boolean updateAudioSourceLocked() { 827 if (mInfo.getAudioType() == AudioManager.DEVICE_NONE) { 828 return false; 829 } 830 AudioDevicePort previousSource = mAudioSource; 831 mAudioSource = findAudioDevicePort(mInfo.getAudioType(), mInfo.getAudioAddress()); 832 return mAudioSource == null ? (previousSource != null) 833 : !mAudioSource.equals(previousSource); 834 } 835 836 private boolean updateAudioSinkLocked() { 837 if (mInfo.getAudioType() == AudioManager.DEVICE_NONE) { 838 return false; 839 } 840 AudioDevicePort previousSink = mAudioSink; 841 if (mOverrideAudioType == AudioManager.DEVICE_NONE) { 842 mAudioSink = findAudioSinkFromAudioPolicy(); 843 } else { 844 AudioDevicePort audioSink = 845 findAudioDevicePort(mOverrideAudioType, mOverrideAudioAddress); 846 if (audioSink != null) { 847 mAudioSink = audioSink; 848 } 849 } 850 return mAudioSink == null ? (previousSink != null) : !mAudioSink.equals(previousSink); 851 } 852 853 private void handleAudioSinkUpdated() { 854 synchronized (mImplLock) { 855 updateAudioConfigLocked(); 856 } 857 } 858 859 @Override 860 public void overrideAudioSink(int audioType, String audioAddress, int samplingRate, 861 int channelMask, int format) { 862 synchronized (mImplLock) { 863 mOverrideAudioType = audioType; 864 mOverrideAudioAddress = audioAddress; 865 866 mDesiredSamplingRate = samplingRate; 867 mDesiredChannelMask = channelMask; 868 mDesiredFormat = format; 869 870 updateAudioConfigLocked(); 871 } 872 } 873 } 874 875 interface Listener { 876 public void onStateChanged(String inputId, int state); 877 public void onHardwareDeviceAdded(TvInputHardwareInfo info); 878 public void onHardwareDeviceRemoved(TvInputHardwareInfo info); 879 public void onHdmiDeviceAdded(HdmiDeviceInfo device); 880 public void onHdmiDeviceRemoved(HdmiDeviceInfo device); 881 public void onHdmiDeviceUpdated(String inputId, HdmiDeviceInfo device); 882 } 883 884 private class ListenerHandler extends Handler { 885 private static final int STATE_CHANGED = 1; 886 private static final int HARDWARE_DEVICE_ADDED = 2; 887 private static final int HARDWARE_DEVICE_REMOVED = 3; 888 private static final int HDMI_DEVICE_ADDED = 4; 889 private static final int HDMI_DEVICE_REMOVED = 5; 890 private static final int HDMI_DEVICE_UPDATED = 6; 891 892 @Override 893 public final void handleMessage(Message msg) { 894 switch (msg.what) { 895 case STATE_CHANGED: { 896 String inputId = (String) msg.obj; 897 int state = msg.arg1; 898 mListener.onStateChanged(inputId, state); 899 break; 900 } 901 case HARDWARE_DEVICE_ADDED: { 902 TvInputHardwareInfo info = (TvInputHardwareInfo) msg.obj; 903 mListener.onHardwareDeviceAdded(info); 904 break; 905 } 906 case HARDWARE_DEVICE_REMOVED: { 907 TvInputHardwareInfo info = (TvInputHardwareInfo) msg.obj; 908 mListener.onHardwareDeviceRemoved(info); 909 break; 910 } 911 case HDMI_DEVICE_ADDED: { 912 HdmiDeviceInfo info = (HdmiDeviceInfo) msg.obj; 913 mListener.onHdmiDeviceAdded(info); 914 break; 915 } 916 case HDMI_DEVICE_REMOVED: { 917 HdmiDeviceInfo info = (HdmiDeviceInfo) msg.obj; 918 mListener.onHdmiDeviceRemoved(info); 919 break; 920 } 921 case HDMI_DEVICE_UPDATED: { 922 SomeArgs args = (SomeArgs) msg.obj; 923 String inputId = (String) args.arg1; 924 HdmiDeviceInfo info = (HdmiDeviceInfo) args.arg2; 925 args.recycle(); 926 mListener.onHdmiDeviceUpdated(inputId, info); 927 } 928 default: { 929 Slog.w(TAG, "Unhandled message: " + msg); 930 break; 931 } 932 } 933 } 934 } 935 936 // Listener implementations for HdmiControlService 937 938 private final class HdmiHotplugEventListener extends IHdmiHotplugEventListener.Stub { 939 @Override 940 public void onReceived(HdmiHotplugEvent event) { 941 synchronized (mLock) { 942 mHdmiStateMap.put(event.getPort(), event.isConnected()); 943 TvInputHardwareInfo hardwareInfo = 944 findHardwareInfoForHdmiPortLocked(event.getPort()); 945 if (hardwareInfo == null) { 946 return; 947 } 948 String inputId = mHardwareInputIdMap.get(hardwareInfo.getDeviceId()); 949 if (inputId == null) { 950 return; 951 } 952 mHandler.obtainMessage(ListenerHandler.STATE_CHANGED, 953 convertConnectedToState(event.isConnected()), 0, inputId).sendToTarget(); 954 } 955 } 956 } 957 958 private final class HdmiDeviceEventListener extends IHdmiDeviceEventListener.Stub { 959 @Override 960 public void onStatusChanged(HdmiDeviceInfo deviceInfo, int status) { 961 synchronized (mLock) { 962 int messageType = 0; 963 Object obj = null; 964 switch (status) { 965 case HdmiControlManager.DEVICE_EVENT_ADD_DEVICE: { 966 if (!mHdmiDeviceList.contains(deviceInfo)) { 967 mHdmiDeviceList.add(deviceInfo); 968 } else { 969 Slog.w(TAG, "The list already contains " + deviceInfo + "; ignoring."); 970 return; 971 } 972 messageType = ListenerHandler.HDMI_DEVICE_ADDED; 973 obj = deviceInfo; 974 break; 975 } 976 case HdmiControlManager.DEVICE_EVENT_REMOVE_DEVICE: { 977 if (!mHdmiDeviceList.remove(deviceInfo)) { 978 Slog.w(TAG, "The list doesn't contain " + deviceInfo + "; ignoring."); 979 return; 980 } 981 messageType = ListenerHandler.HDMI_DEVICE_REMOVED; 982 obj = deviceInfo; 983 break; 984 } 985 case HdmiControlManager.DEVICE_EVENT_UPDATE_DEVICE: { 986 if (!mHdmiDeviceList.remove(deviceInfo)) { 987 Slog.w(TAG, "The list doesn't contain " + deviceInfo + "; ignoring."); 988 return; 989 } 990 mHdmiDeviceList.add(deviceInfo); 991 messageType = ListenerHandler.HDMI_DEVICE_UPDATED; 992 String inputId = mHdmiInputIdMap.get(deviceInfo.getLogicalAddress()); 993 SomeArgs args = SomeArgs.obtain(); 994 args.arg1 = inputId; 995 args.arg2 = deviceInfo; 996 obj = args; 997 break; 998 } 999 } 1000 1001 Message msg = mHandler.obtainMessage(messageType, 0, 0, obj); 1002 if (findHardwareInfoForHdmiPortLocked(deviceInfo.getPortId()) != null) { 1003 msg.sendToTarget(); 1004 } else { 1005 mPendingHdmiDeviceEvents.add(msg); 1006 } 1007 } 1008 } 1009 } 1010 1011 private final class HdmiSystemAudioModeChangeListener extends 1012 IHdmiSystemAudioModeChangeListener.Stub { 1013 @Override 1014 public void onStatusChanged(boolean enabled) throws RemoteException { 1015 synchronized (mLock) { 1016 for (int i = 0; i < mConnections.size(); ++i) { 1017 TvInputHardwareImpl impl = mConnections.valueAt(i).getHardwareImplLocked(); 1018 impl.handleAudioSinkUpdated(); 1019 } 1020 } 1021 } 1022 } 1023} 1024