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