MediaSessionRecord.java revision 7aef77bbf5b983b9f949936ed6cd174251697ca8
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.media; 18 19import android.app.PendingIntent; 20import android.content.ComponentName; 21import android.content.Context; 22import android.content.Intent; 23import android.content.pm.ParceledListSlice; 24import android.media.AudioManager; 25import android.media.MediaMetadata; 26import android.media.Rating; 27import android.media.VolumeProvider; 28import android.media.routing.IMediaRouter; 29import android.media.routing.IMediaRouterDelegate; 30import android.media.routing.IMediaRouterStateCallback; 31import android.media.session.ISession; 32import android.media.session.ISessionCallback; 33import android.media.session.ISessionController; 34import android.media.session.ISessionControllerCallback; 35import android.media.session.MediaController; 36import android.media.session.MediaSession; 37import android.media.session.ParcelableVolumeInfo; 38import android.media.session.PlaybackState; 39import android.media.AudioAttributes; 40import android.net.Uri; 41import android.os.Binder; 42import android.os.Bundle; 43import android.os.DeadObjectException; 44import android.os.Handler; 45import android.os.IBinder; 46import android.os.Looper; 47import android.os.Message; 48import android.os.RemoteException; 49import android.os.ResultReceiver; 50import android.os.SystemClock; 51import android.util.Log; 52import android.util.Slog; 53import android.view.KeyEvent; 54 55import java.io.PrintWriter; 56import java.util.ArrayList; 57import java.util.UUID; 58 59/** 60 * This is the system implementation of a Session. Apps will interact with the 61 * MediaSession wrapper class instead. 62 */ 63public class MediaSessionRecord implements IBinder.DeathRecipient { 64 private static final String TAG = "MediaSessionRecord"; 65 private static final boolean DEBUG = false; 66 67 /** 68 * The length of time a session will still be considered active after 69 * pausing in ms. 70 */ 71 private static final int ACTIVE_BUFFER = 30000; 72 73 /** 74 * The amount of time we'll send an assumed volume after the last volume 75 * command before reverting to the last reported volume. 76 */ 77 private static final int OPTIMISTIC_VOLUME_TIMEOUT = 1000; 78 79 private final MessageHandler mHandler; 80 81 private final int mOwnerPid; 82 private final int mOwnerUid; 83 private final int mUserId; 84 private final String mPackageName; 85 private final String mTag; 86 private final ControllerStub mController; 87 private final SessionStub mSession; 88 private final SessionCb mSessionCb; 89 private final MediaSessionService mService; 90 91 private final Object mLock = new Object(); 92 private final ArrayList<ISessionControllerCallback> mControllerCallbacks = 93 new ArrayList<ISessionControllerCallback>(); 94 95 private long mFlags; 96 private IMediaRouter mMediaRouter; 97 private PendingIntent mMediaButtonReceiver; 98 private PendingIntent mLaunchIntent; 99 100 // TransportPerformer fields 101 102 private Bundle mExtras; 103 private MediaMetadata mMetadata; 104 private PlaybackState mPlaybackState; 105 private ParceledListSlice mQueue; 106 private CharSequence mQueueTitle; 107 private int mRatingType; 108 private long mLastActiveTime; 109 // End TransportPerformer fields 110 111 // Volume handling fields 112 private AudioAttributes mAudioAttrs; 113 private AudioManager mAudioManager; 114 private int mVolumeType = MediaSession.PLAYBACK_TYPE_LOCAL; 115 private int mVolumeControlType = VolumeProvider.VOLUME_CONTROL_ABSOLUTE; 116 private int mMaxVolume = 0; 117 private int mCurrentVolume = 0; 118 private int mOptimisticVolume = -1; 119 // End volume handling fields 120 121 private boolean mIsActive = false; 122 private boolean mDestroyed = false; 123 124 public MediaSessionRecord(int ownerPid, int ownerUid, int userId, String ownerPackageName, 125 ISessionCallback cb, String tag, MediaSessionService service, Handler handler) { 126 mOwnerPid = ownerPid; 127 mOwnerUid = ownerUid; 128 mUserId = userId; 129 mPackageName = ownerPackageName; 130 mTag = tag; 131 mController = new ControllerStub(); 132 mSession = new SessionStub(); 133 mSessionCb = new SessionCb(cb); 134 mService = service; 135 mHandler = new MessageHandler(handler.getLooper()); 136 mAudioManager = (AudioManager) service.getContext().getSystemService(Context.AUDIO_SERVICE); 137 mAudioAttrs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).build(); 138 } 139 140 /** 141 * Get the binder for the {@link MediaSession}. 142 * 143 * @return The session binder apps talk to. 144 */ 145 public ISession getSessionBinder() { 146 return mSession; 147 } 148 149 /** 150 * Get the binder for the {@link MediaController}. 151 * 152 * @return The controller binder apps talk to. 153 */ 154 public ISessionController getControllerBinder() { 155 return mController; 156 } 157 158 /** 159 * Get the info for this session. 160 * 161 * @return Info that identifies this session. 162 */ 163 public String getPackageName() { 164 return mPackageName; 165 } 166 167 /** 168 * Get the tag for the session. 169 * 170 * @return The session's tag. 171 */ 172 public String getTag() { 173 return mTag; 174 } 175 176 /** 177 * Get the intent the app set for their media button receiver. 178 * 179 * @return The pending intent set by the app or null. 180 */ 181 public PendingIntent getMediaButtonReceiver() { 182 return mMediaButtonReceiver; 183 } 184 185 /** 186 * Get this session's flags. 187 * 188 * @return The flags for this session. 189 */ 190 public long getFlags() { 191 return mFlags; 192 } 193 194 /** 195 * Check if this session has the specified flag. 196 * 197 * @param flag The flag to check. 198 * @return True if this session has that flag set, false otherwise. 199 */ 200 public boolean hasFlag(int flag) { 201 return (mFlags & flag) != 0; 202 } 203 204 /** 205 * Get the user id this session was created for. 206 * 207 * @return The user id for this session. 208 */ 209 public int getUserId() { 210 return mUserId; 211 } 212 213 /** 214 * Check if this session has system priorty and should receive media buttons 215 * before any other sessions. 216 * 217 * @return True if this is a system priority session, false otherwise 218 */ 219 public boolean isSystemPriority() { 220 return (mFlags & MediaSession.FLAG_EXCLUSIVE_GLOBAL_PRIORITY) != 0; 221 } 222 223 /** 224 * Send a volume adjustment to the session owner. Direction must be one of 225 * {@link AudioManager#ADJUST_LOWER}, {@link AudioManager#ADJUST_RAISE}, 226 * {@link AudioManager#ADJUST_SAME}. 227 * 228 * @param direction The direction to adjust volume in. 229 */ 230 public void adjustVolume(int direction, int flags) { 231 if (isPlaybackActive(false)) { 232 flags &= ~AudioManager.FLAG_PLAY_SOUND; 233 } 234 if (direction > 1) { 235 direction = 1; 236 } else if (direction < -1) { 237 direction = -1; 238 } 239 if (mVolumeType == MediaSession.PLAYBACK_TYPE_LOCAL) { 240 int stream = AudioAttributes.toLegacyStreamType(mAudioAttrs); 241 mAudioManager.adjustStreamVolume(stream, direction, flags); 242 } else { 243 if (mVolumeControlType == VolumeProvider.VOLUME_CONTROL_FIXED) { 244 // Nothing to do, the volume cannot be changed 245 return; 246 } 247 mSessionCb.adjustVolume(direction); 248 249 int volumeBefore = (mOptimisticVolume < 0 ? mCurrentVolume : mOptimisticVolume); 250 mOptimisticVolume = volumeBefore + direction; 251 mOptimisticVolume = Math.max(0, Math.min(mOptimisticVolume, mMaxVolume)); 252 mHandler.removeCallbacks(mClearOptimisticVolumeRunnable); 253 mHandler.postDelayed(mClearOptimisticVolumeRunnable, OPTIMISTIC_VOLUME_TIMEOUT); 254 if (volumeBefore != mOptimisticVolume) { 255 pushVolumeUpdate(); 256 } 257 258 if (DEBUG) { 259 Log.d(TAG, "Adjusted optimistic volume to " + mOptimisticVolume + " max is " 260 + mMaxVolume); 261 } 262 } 263 } 264 265 public void setVolumeTo(int value, int flags) { 266 if (mVolumeType == MediaSession.PLAYBACK_TYPE_LOCAL) { 267 int stream = AudioAttributes.toLegacyStreamType(mAudioAttrs); 268 mAudioManager.setStreamVolume(stream, value, flags); 269 } else { 270 if (mVolumeControlType != VolumeProvider.VOLUME_CONTROL_ABSOLUTE) { 271 // Nothing to do. The volume can't be set directly. 272 return; 273 } 274 value = Math.max(0, Math.min(value, mMaxVolume)); 275 mSessionCb.setVolumeTo(value); 276 277 int volumeBefore = (mOptimisticVolume < 0 ? mCurrentVolume : mOptimisticVolume); 278 mOptimisticVolume = Math.max(0, Math.min(value, mMaxVolume)); 279 mHandler.removeCallbacks(mClearOptimisticVolumeRunnable); 280 mHandler.postDelayed(mClearOptimisticVolumeRunnable, OPTIMISTIC_VOLUME_TIMEOUT); 281 if (volumeBefore != mOptimisticVolume) { 282 pushVolumeUpdate(); 283 } 284 285 if (DEBUG) { 286 Log.d(TAG, "Set optimistic volume to " + mOptimisticVolume + " max is " 287 + mMaxVolume); 288 } 289 } 290 } 291 292 /** 293 * Check if this session has been set to active by the app. 294 * 295 * @return True if the session is active, false otherwise. 296 */ 297 public boolean isActive() { 298 return mIsActive && !mDestroyed; 299 } 300 301 /** 302 * Check if the session is currently performing playback. This will also 303 * return true if the session was recently paused. 304 * 305 * @param includeRecentlyActive True if playback that was recently paused 306 * should count, false if it shouldn't. 307 * @return True if the session is performing playback, false otherwise. 308 */ 309 public boolean isPlaybackActive(boolean includeRecentlyActive) { 310 int state = mPlaybackState == null ? 0 : mPlaybackState.getState(); 311 if (MediaSession.isActiveState(state)) { 312 return true; 313 } 314 if (includeRecentlyActive && state == mPlaybackState.STATE_PAUSED) { 315 long inactiveTime = SystemClock.uptimeMillis() - mLastActiveTime; 316 if (inactiveTime < ACTIVE_BUFFER) { 317 return true; 318 } 319 } 320 return false; 321 } 322 323 /** 324 * Get the type of playback, either local or remote. 325 * 326 * @return The current type of playback. 327 */ 328 public int getPlaybackType() { 329 return mVolumeType; 330 } 331 332 /** 333 * Get the local audio stream being used. Only valid if playback type is 334 * local. 335 * 336 * @return The audio stream the session is using. 337 */ 338 public AudioAttributes getAudioAttributes() { 339 return mAudioAttrs; 340 } 341 342 /** 343 * Get the type of volume control. Only valid if playback type is remote. 344 * 345 * @return The volume control type being used. 346 */ 347 public int getVolumeControl() { 348 return mVolumeControlType; 349 } 350 351 /** 352 * Get the max volume that can be set. Only valid if playback type is 353 * remote. 354 * 355 * @return The max volume that can be set. 356 */ 357 public int getMaxVolume() { 358 return mMaxVolume; 359 } 360 361 /** 362 * Get the current volume for this session. Only valid if playback type is 363 * remote. 364 * 365 * @return The current volume of the remote playback. 366 */ 367 public int getCurrentVolume() { 368 return mCurrentVolume; 369 } 370 371 /** 372 * Get the volume we'd like it to be set to. This is only valid for a short 373 * while after a call to adjust or set volume. 374 * 375 * @return The current optimistic volume or -1. 376 */ 377 public int getOptimisticVolume() { 378 return mOptimisticVolume; 379 } 380 381 public boolean isTransportControlEnabled() { 382 return hasFlag(MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS); 383 } 384 385 @Override 386 public void binderDied() { 387 mService.sessionDied(this); 388 } 389 390 /** 391 * Finish cleaning up this session, including disconnecting if connected and 392 * removing the death observer from the callback binder. 393 */ 394 public void onDestroy() { 395 synchronized (mLock) { 396 if (mDestroyed) { 397 return; 398 } 399 mDestroyed = true; 400 } 401 } 402 403 public ISessionCallback getCallback() { 404 return mSessionCb.mCb; 405 } 406 407 public void sendMediaButton(KeyEvent ke, int sequenceId, ResultReceiver cb) { 408 mSessionCb.sendMediaButton(ke, sequenceId, cb); 409 } 410 411 public void dump(PrintWriter pw, String prefix) { 412 pw.println(prefix + mTag + " " + this); 413 414 final String indent = prefix + " "; 415 pw.println(indent + "ownerPid=" + mOwnerPid + ", ownerUid=" + mOwnerUid 416 + ", userId=" + mUserId); 417 pw.println(indent + "package=" + mPackageName); 418 pw.println(indent + "launchIntent=" + mLaunchIntent); 419 pw.println(indent + "mediaButtonReceiver=" + mMediaButtonReceiver); 420 pw.println(indent + "active=" + mIsActive); 421 pw.println(indent + "flags=" + mFlags); 422 pw.println(indent + "rating type=" + mRatingType); 423 pw.println(indent + "controllers: " + mControllerCallbacks.size()); 424 pw.println(indent + "state=" + (mPlaybackState == null ? null : mPlaybackState.toString())); 425 pw.println(indent + "audioAttrs=" + mAudioAttrs); 426 pw.println(indent + "volumeType=" + mVolumeType + ", controlType=" + mVolumeControlType 427 + ", max=" + mMaxVolume + ", current=" + mCurrentVolume); 428 pw.println(indent + "metadata:" + getShortMetadataString()); 429 pw.println(indent + "queueTitle=" + mQueueTitle + ", size=" 430 + (mQueue == null ? 0 : mQueue.getList().size())); 431 } 432 433 @Override 434 public String toString() { 435 return mPackageName + "/" + mTag; 436 } 437 438 private String getShortMetadataString() { 439 int fields = mMetadata == null ? 0 : mMetadata.size(); 440 MediaMetadata.Description description = mMetadata == null ? null : mMetadata 441 .getDescription(); 442 return "size=" + fields + ", description=" + description; 443 } 444 445 private void pushPlaybackStateUpdate() { 446 synchronized (mLock) { 447 if (mDestroyed) { 448 return; 449 } 450 for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) { 451 ISessionControllerCallback cb = mControllerCallbacks.get(i); 452 try { 453 cb.onPlaybackStateChanged(mPlaybackState); 454 } catch (DeadObjectException e) { 455 mControllerCallbacks.remove(i); 456 Log.w(TAG, "Removed dead callback in pushPlaybackStateUpdate.", e); 457 } catch (RemoteException e) { 458 Log.w(TAG, "unexpected exception in pushPlaybackStateUpdate.", e); 459 } 460 } 461 } 462 } 463 464 private void pushMetadataUpdate() { 465 synchronized (mLock) { 466 if (mDestroyed) { 467 return; 468 } 469 for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) { 470 ISessionControllerCallback cb = mControllerCallbacks.get(i); 471 try { 472 cb.onMetadataChanged(mMetadata); 473 } catch (DeadObjectException e) { 474 Log.w(TAG, "Removing dead callback in pushMetadataUpdate. ", e); 475 mControllerCallbacks.remove(i); 476 } catch (RemoteException e) { 477 Log.w(TAG, "unexpected exception in pushMetadataUpdate. ", e); 478 } 479 } 480 } 481 } 482 483 private void pushQueueUpdate() { 484 synchronized (mLock) { 485 if (mDestroyed) { 486 return; 487 } 488 for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) { 489 ISessionControllerCallback cb = mControllerCallbacks.get(i); 490 try { 491 cb.onQueueChanged(mQueue); 492 } catch (DeadObjectException e) { 493 mControllerCallbacks.remove(i); 494 Log.w(TAG, "Removed dead callback in pushQueueUpdate.", e); 495 } catch (RemoteException e) { 496 Log.w(TAG, "unexpected exception in pushQueueUpdate.", e); 497 } 498 } 499 } 500 } 501 502 private void pushQueueTitleUpdate() { 503 synchronized (mLock) { 504 if (mDestroyed) { 505 return; 506 } 507 for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) { 508 ISessionControllerCallback cb = mControllerCallbacks.get(i); 509 try { 510 cb.onQueueTitleChanged(mQueueTitle); 511 } catch (DeadObjectException e) { 512 mControllerCallbacks.remove(i); 513 Log.w(TAG, "Removed dead callback in pushQueueTitleUpdate.", e); 514 } catch (RemoteException e) { 515 Log.w(TAG, "unexpected exception in pushQueueTitleUpdate.", e); 516 } 517 } 518 } 519 } 520 521 private void pushExtrasUpdate() { 522 synchronized (mLock) { 523 if (mDestroyed) { 524 return; 525 } 526 for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) { 527 ISessionControllerCallback cb = mControllerCallbacks.get(i); 528 try { 529 cb.onExtrasChanged(mExtras); 530 } catch (DeadObjectException e) { 531 mControllerCallbacks.remove(i); 532 Log.w(TAG, "Removed dead callback in pushExtrasUpdate.", e); 533 } catch (RemoteException e) { 534 Log.w(TAG, "unexpected exception in pushExtrasUpdate.", e); 535 } 536 } 537 } 538 } 539 540 private void pushVolumeUpdate() { 541 synchronized (mLock) { 542 if (mDestroyed) { 543 return; 544 } 545 ParcelableVolumeInfo info = mController.getVolumeAttributes(); 546 for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) { 547 ISessionControllerCallback cb = mControllerCallbacks.get(i); 548 try { 549 cb.onVolumeInfoChanged(info); 550 } catch (DeadObjectException e) { 551 Log.w(TAG, "Removing dead callback in pushVolumeUpdate. ", e); 552 } catch (RemoteException e) { 553 Log.w(TAG, "Unexpected exception in pushVolumeUpdate. ", e); 554 } 555 } 556 } 557 } 558 559 private void pushEvent(String event, Bundle data) { 560 synchronized (mLock) { 561 if (mDestroyed) { 562 return; 563 } 564 for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) { 565 ISessionControllerCallback cb = mControllerCallbacks.get(i); 566 try { 567 cb.onEvent(event, data); 568 } catch (DeadObjectException e) { 569 Log.w(TAG, "Removing dead callback in pushEvent.", e); 570 mControllerCallbacks.remove(i); 571 } catch (RemoteException e) { 572 Log.w(TAG, "unexpected exception in pushEvent.", e); 573 } 574 } 575 } 576 } 577 578 private PlaybackState getStateWithUpdatedPosition() { 579 PlaybackState state = mPlaybackState; 580 long duration = -1; 581 if (mMetadata != null && mMetadata.containsKey(MediaMetadata.METADATA_KEY_DURATION)) { 582 duration = mMetadata.getLong(MediaMetadata.METADATA_KEY_DURATION); 583 } 584 PlaybackState result = null; 585 if (state != null) { 586 if (state.getState() == PlaybackState.STATE_PLAYING 587 || state.getState() == PlaybackState.STATE_FAST_FORWARDING 588 || state.getState() == PlaybackState.STATE_REWINDING) { 589 long updateTime = state.getLastPositionUpdateTime(); 590 long currentTime = SystemClock.elapsedRealtime(); 591 if (updateTime > 0) { 592 long position = (long) (state.getPlaybackSpeed() 593 * (currentTime - updateTime)) + state.getPosition(); 594 if (duration >= 0 && position > duration) { 595 position = duration; 596 } else if (position < 0) { 597 position = 0; 598 } 599 PlaybackState.Builder builder = new PlaybackState.Builder(state); 600 builder.setState(state.getState(), position, state.getPlaybackSpeed(), 601 currentTime); 602 result = builder.build(); 603 } 604 } 605 } 606 return result == null ? state : result; 607 } 608 609 private int getControllerCbIndexForCb(ISessionControllerCallback cb) { 610 IBinder binder = cb.asBinder(); 611 for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) { 612 if (binder.equals(mControllerCallbacks.get(i).asBinder())) { 613 return i; 614 } 615 } 616 return -1; 617 } 618 619 private final Runnable mClearOptimisticVolumeRunnable = new Runnable() { 620 @Override 621 public void run() { 622 boolean needUpdate = (mOptimisticVolume != mCurrentVolume); 623 mOptimisticVolume = -1; 624 if (needUpdate) { 625 pushVolumeUpdate(); 626 } 627 } 628 }; 629 630 private final class SessionStub extends ISession.Stub { 631 @Override 632 public void destroy() { 633 mService.destroySession(MediaSessionRecord.this); 634 } 635 636 @Override 637 public void sendEvent(String event, Bundle data) { 638 mHandler.post(MessageHandler.MSG_SEND_EVENT, event, data); 639 } 640 641 @Override 642 public ISessionController getController() { 643 return mController; 644 } 645 646 @Override 647 public void setActive(boolean active) { 648 mIsActive = active; 649 mService.updateSession(MediaSessionRecord.this); 650 mHandler.post(MessageHandler.MSG_UPDATE_SESSION_STATE); 651 } 652 653 @Override 654 public void setFlags(int flags) { 655 if ((flags & MediaSession.FLAG_EXCLUSIVE_GLOBAL_PRIORITY) != 0) { 656 int pid = getCallingPid(); 657 int uid = getCallingUid(); 658 mService.enforcePhoneStatePermission(pid, uid); 659 } 660 mFlags = flags; 661 mHandler.post(MessageHandler.MSG_UPDATE_SESSION_STATE); 662 } 663 664 @Override 665 public void setMediaRouter(IMediaRouter router) { 666 mMediaRouter = router; 667 mHandler.post(MessageHandler.MSG_UPDATE_SESSION_STATE); 668 } 669 670 @Override 671 public void setMediaButtonReceiver(PendingIntent pi) { 672 mMediaButtonReceiver = pi; 673 } 674 675 @Override 676 public void setLaunchPendingIntent(PendingIntent pi) { 677 mLaunchIntent = pi; 678 } 679 680 @Override 681 public void setMetadata(MediaMetadata metadata) { 682 mMetadata = metadata; 683 mHandler.post(MessageHandler.MSG_UPDATE_METADATA); 684 } 685 686 @Override 687 public void setPlaybackState(PlaybackState state) { 688 int oldState = mPlaybackState == null ? 0 : mPlaybackState.getState(); 689 int newState = state == null ? 0 : state.getState(); 690 if (MediaSession.isActiveState(oldState) && newState == PlaybackState.STATE_PAUSED) { 691 mLastActiveTime = SystemClock.elapsedRealtime(); 692 } 693 mPlaybackState = state; 694 mService.onSessionPlaystateChange(MediaSessionRecord.this, oldState, newState); 695 mHandler.post(MessageHandler.MSG_UPDATE_PLAYBACK_STATE); 696 } 697 698 @Override 699 public void setQueue(ParceledListSlice queue) { 700 mQueue = queue; 701 mHandler.post(MessageHandler.MSG_UPDATE_QUEUE); 702 } 703 704 @Override 705 public void setQueueTitle(CharSequence title) { 706 mQueueTitle = title; 707 mHandler.post(MessageHandler.MSG_UPDATE_QUEUE_TITLE); 708 } 709 710 @Override 711 public void setExtras(Bundle extras) { 712 mExtras = extras; 713 mHandler.post(MessageHandler.MSG_UPDATE_EXTRAS); 714 } 715 716 @Override 717 public void setRatingType(int type) { 718 mRatingType = type; 719 } 720 721 @Override 722 public void setCurrentVolume(int volume) { 723 mCurrentVolume = volume; 724 mHandler.post(MessageHandler.MSG_UPDATE_VOLUME); 725 } 726 727 @Override 728 public void setPlaybackToLocal(AudioAttributes attributes) { 729 boolean typeChanged; 730 synchronized (mLock) { 731 typeChanged = mVolumeType == MediaSession.PLAYBACK_TYPE_REMOTE; 732 mVolumeType = MediaSession.PLAYBACK_TYPE_LOCAL; 733 if (attributes != null) { 734 mAudioAttrs = attributes; 735 } else { 736 Log.e(TAG, "Received null audio attributes, using existing attributes"); 737 } 738 } 739 if (typeChanged) { 740 mService.onSessionPlaybackTypeChanged(MediaSessionRecord.this); 741 } 742 } 743 744 @Override 745 public void setPlaybackToRemote(int control, int max) { 746 boolean typeChanged; 747 synchronized (mLock) { 748 typeChanged = mVolumeType == MediaSession.PLAYBACK_TYPE_LOCAL; 749 mVolumeType = MediaSession.PLAYBACK_TYPE_REMOTE; 750 mVolumeControlType = control; 751 mMaxVolume = max; 752 } 753 if (typeChanged) { 754 mService.onSessionPlaybackTypeChanged(MediaSessionRecord.this); 755 } 756 } 757 } 758 759 class SessionCb { 760 private final ISessionCallback mCb; 761 762 public SessionCb(ISessionCallback cb) { 763 mCb = cb; 764 } 765 766 public boolean sendMediaButton(KeyEvent keyEvent, int sequenceId, ResultReceiver cb) { 767 Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); 768 mediaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent); 769 try { 770 mCb.onMediaButton(mediaButtonIntent, sequenceId, cb); 771 return true; 772 } catch (RemoteException e) { 773 Slog.e(TAG, "Remote failure in sendMediaRequest.", e); 774 } 775 return false; 776 } 777 778 public void sendCommand(String command, Bundle args, ResultReceiver cb) { 779 try { 780 mCb.onCommand(command, args, cb); 781 } catch (RemoteException e) { 782 Slog.e(TAG, "Remote failure in sendCommand.", e); 783 } 784 } 785 786 public void sendCustomAction(String action, Bundle args) { 787 try { 788 mCb.onCustomAction(action, args); 789 } catch (RemoteException e) { 790 Slog.e(TAG, "Remote failure in sendCustomAction.", e); 791 } 792 } 793 794 public void play() { 795 try { 796 mCb.onPlay(); 797 } catch (RemoteException e) { 798 Slog.e(TAG, "Remote failure in play.", e); 799 } 800 } 801 802 public void playUri(Uri uri, Bundle extras) { 803 try { 804 mCb.onPlayUri(uri, extras); 805 } catch (RemoteException e) { 806 Slog.e(TAG, "Remote failure in playUri.", e); 807 } 808 } 809 810 public void playFromSearch(String query, Bundle extras) { 811 try { 812 mCb.onPlayFromSearch(query, extras); 813 } catch (RemoteException e) { 814 Slog.e(TAG, "Remote failure in playFromSearch.", e); 815 } 816 } 817 818 public void skipToTrack(long id) { 819 try { 820 mCb.onSkipToTrack(id); 821 } catch (RemoteException e) { 822 Slog.e(TAG, "Remote failure in skipToTrack", e); 823 } 824 } 825 826 public void pause() { 827 try { 828 mCb.onPause(); 829 } catch (RemoteException e) { 830 Slog.e(TAG, "Remote failure in pause.", e); 831 } 832 } 833 834 public void stop() { 835 try { 836 mCb.onStop(); 837 } catch (RemoteException e) { 838 Slog.e(TAG, "Remote failure in stop.", e); 839 } 840 } 841 842 public void next() { 843 try { 844 mCb.onNext(); 845 } catch (RemoteException e) { 846 Slog.e(TAG, "Remote failure in next.", e); 847 } 848 } 849 850 public void previous() { 851 try { 852 mCb.onPrevious(); 853 } catch (RemoteException e) { 854 Slog.e(TAG, "Remote failure in previous.", e); 855 } 856 } 857 858 public void fastForward() { 859 try { 860 mCb.onFastForward(); 861 } catch (RemoteException e) { 862 Slog.e(TAG, "Remote failure in fastForward.", e); 863 } 864 } 865 866 public void rewind() { 867 try { 868 mCb.onRewind(); 869 } catch (RemoteException e) { 870 Slog.e(TAG, "Remote failure in rewind.", e); 871 } 872 } 873 874 public void seekTo(long pos) { 875 try { 876 mCb.onSeekTo(pos); 877 } catch (RemoteException e) { 878 Slog.e(TAG, "Remote failure in seekTo.", e); 879 } 880 } 881 882 public void rate(Rating rating) { 883 try { 884 mCb.onRate(rating); 885 } catch (RemoteException e) { 886 Slog.e(TAG, "Remote failure in rate.", e); 887 } 888 } 889 890 public void adjustVolume(int direction) { 891 try { 892 mCb.onAdjustVolume(direction); 893 } catch (RemoteException e) { 894 Slog.e(TAG, "Remote failure in adjustVolume.", e); 895 } 896 } 897 898 public void setVolumeTo(int value) { 899 try { 900 mCb.onSetVolumeTo(value); 901 } catch (RemoteException e) { 902 Slog.e(TAG, "Remote failure in setVolumeTo.", e); 903 } 904 } 905 } 906 907 class ControllerStub extends ISessionController.Stub { 908 @Override 909 public void sendCommand(String command, Bundle args, ResultReceiver cb) 910 throws RemoteException { 911 mSessionCb.sendCommand(command, args, cb); 912 } 913 914 @Override 915 public boolean sendMediaButton(KeyEvent mediaButtonIntent) { 916 return mSessionCb.sendMediaButton(mediaButtonIntent, 0, null); 917 } 918 919 @Override 920 public void registerCallbackListener(ISessionControllerCallback cb) { 921 synchronized (mLock) { 922 if (getControllerCbIndexForCb(cb) < 0) { 923 mControllerCallbacks.add(cb); 924 if (DEBUG) { 925 Log.d(TAG, "registering controller callback " + cb); 926 } 927 } 928 } 929 } 930 931 @Override 932 public void unregisterCallbackListener(ISessionControllerCallback cb) 933 throws RemoteException { 934 synchronized (mLock) { 935 int index = getControllerCbIndexForCb(cb); 936 if (index != -1) { 937 mControllerCallbacks.remove(index); 938 } 939 if (DEBUG) { 940 Log.d(TAG, "unregistering callback " + cb + ". index=" + index); 941 } 942 } 943 } 944 945 @Override 946 public String getPackageName() { 947 return mPackageName; 948 } 949 950 @Override 951 public String getTag() { 952 return mTag; 953 } 954 955 @Override 956 public PendingIntent getLaunchPendingIntent() { 957 return mLaunchIntent; 958 } 959 960 @Override 961 public long getFlags() { 962 return mFlags; 963 } 964 965 @Override 966 public ParcelableVolumeInfo getVolumeAttributes() { 967 synchronized (mLock) { 968 int type; 969 int max; 970 int current; 971 if (mVolumeType == MediaSession.PLAYBACK_TYPE_REMOTE) { 972 type = mVolumeControlType; 973 max = mMaxVolume; 974 current = mOptimisticVolume != -1 ? mOptimisticVolume 975 : mCurrentVolume; 976 } else { 977 int stream = AudioAttributes.toLegacyStreamType(mAudioAttrs); 978 type = VolumeProvider.VOLUME_CONTROL_ABSOLUTE; 979 max = mAudioManager.getStreamMaxVolume(stream); 980 current = mAudioManager.getStreamVolume(stream); 981 } 982 return new ParcelableVolumeInfo(mVolumeType, mAudioAttrs, type, max, current); 983 } 984 } 985 986 @Override 987 public void adjustVolume(int direction, int flags) { 988 final long token = Binder.clearCallingIdentity(); 989 try { 990 MediaSessionRecord.this.adjustVolume(direction, flags); 991 } finally { 992 Binder.restoreCallingIdentity(token); 993 } 994 } 995 996 @Override 997 public void setVolumeTo(int value, int flags) { 998 final long token = Binder.clearCallingIdentity(); 999 try { 1000 MediaSessionRecord.this.setVolumeTo(value, flags); 1001 } finally { 1002 Binder.restoreCallingIdentity(token); 1003 } 1004 } 1005 1006 @Override 1007 public void play() throws RemoteException { 1008 mSessionCb.play(); 1009 } 1010 1011 @Override 1012 public void playUri(Uri uri, Bundle extras) throws RemoteException { 1013 mSessionCb.playUri(uri, extras); 1014 } 1015 1016 @Override 1017 public void playFromSearch(String query, Bundle extras) throws RemoteException { 1018 mSessionCb.playFromSearch(query, extras); 1019 } 1020 1021 @Override 1022 public void skipToTrack(long id) { 1023 mSessionCb.skipToTrack(id); 1024 } 1025 1026 1027 @Override 1028 public void pause() throws RemoteException { 1029 mSessionCb.pause(); 1030 } 1031 1032 @Override 1033 public void stop() throws RemoteException { 1034 mSessionCb.stop(); 1035 } 1036 1037 @Override 1038 public void next() throws RemoteException { 1039 mSessionCb.next(); 1040 } 1041 1042 @Override 1043 public void previous() throws RemoteException { 1044 mSessionCb.previous(); 1045 } 1046 1047 @Override 1048 public void fastForward() throws RemoteException { 1049 mSessionCb.fastForward(); 1050 } 1051 1052 @Override 1053 public void rewind() throws RemoteException { 1054 mSessionCb.rewind(); 1055 } 1056 1057 @Override 1058 public void seekTo(long pos) throws RemoteException { 1059 mSessionCb.seekTo(pos); 1060 } 1061 1062 @Override 1063 public void rate(Rating rating) throws RemoteException { 1064 mSessionCb.rate(rating); 1065 } 1066 1067 @Override 1068 public void sendCustomAction(String action, Bundle args) 1069 throws RemoteException { 1070 mSessionCb.sendCustomAction(action, args); 1071 } 1072 1073 1074 @Override 1075 public MediaMetadata getMetadata() { 1076 return mMetadata; 1077 } 1078 1079 @Override 1080 public PlaybackState getPlaybackState() { 1081 return getStateWithUpdatedPosition(); 1082 } 1083 1084 @Override 1085 public ParceledListSlice getQueue() { 1086 return mQueue; 1087 } 1088 1089 @Override 1090 public CharSequence getQueueTitle() { 1091 return mQueueTitle; 1092 } 1093 1094 @Override 1095 public Bundle getExtras() { 1096 return mExtras; 1097 } 1098 1099 @Override 1100 public int getRatingType() { 1101 return mRatingType; 1102 } 1103 1104 @Override 1105 public boolean isTransportControlEnabled() { 1106 return MediaSessionRecord.this.isTransportControlEnabled(); 1107 } 1108 1109 @Override 1110 public IMediaRouterDelegate createMediaRouterDelegate( 1111 IMediaRouterStateCallback callback) { 1112 // todo 1113 return null; 1114 } 1115 } 1116 1117 private class MessageHandler extends Handler { 1118 private static final int MSG_UPDATE_METADATA = 1; 1119 private static final int MSG_UPDATE_PLAYBACK_STATE = 2; 1120 private static final int MSG_UPDATE_QUEUE = 3; 1121 private static final int MSG_UPDATE_QUEUE_TITLE = 4; 1122 private static final int MSG_UPDATE_EXTRAS = 5; 1123 private static final int MSG_SEND_EVENT = 6; 1124 private static final int MSG_UPDATE_SESSION_STATE = 7; 1125 private static final int MSG_UPDATE_VOLUME = 8; 1126 1127 public MessageHandler(Looper looper) { 1128 super(looper); 1129 } 1130 @Override 1131 public void handleMessage(Message msg) { 1132 switch (msg.what) { 1133 case MSG_UPDATE_METADATA: 1134 pushMetadataUpdate(); 1135 break; 1136 case MSG_UPDATE_PLAYBACK_STATE: 1137 pushPlaybackStateUpdate(); 1138 break; 1139 case MSG_UPDATE_QUEUE: 1140 pushQueueUpdate(); 1141 break; 1142 case MSG_UPDATE_QUEUE_TITLE: 1143 pushQueueTitleUpdate(); 1144 break; 1145 case MSG_UPDATE_EXTRAS: 1146 pushExtrasUpdate(); 1147 break; 1148 case MSG_SEND_EVENT: 1149 pushEvent((String) msg.obj, msg.getData()); 1150 break; 1151 case MSG_UPDATE_SESSION_STATE: 1152 // TODO add session state 1153 break; 1154 case MSG_UPDATE_VOLUME: 1155 pushVolumeUpdate(); 1156 break; 1157 } 1158 } 1159 1160 public void post(int what) { 1161 post(what, null); 1162 } 1163 1164 public void post(int what, Object obj) { 1165 obtainMessage(what, obj).sendToTarget(); 1166 } 1167 1168 public void post(int what, Object obj, Bundle data) { 1169 Message msg = obtainMessage(what, obj); 1170 msg.setData(data); 1171 msg.sendToTarget(); 1172 } 1173 } 1174 1175} 1176