MediaFocusControl.java revision 7ddd226e7c6e759feaf2747a90be1cc06acf37a3
1/*
2 * Copyright (C) 2013 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 android.media;
18
19import android.app.Activity;
20import android.app.AppOpsManager;
21import android.app.KeyguardManager;
22import android.app.PendingIntent;
23import android.app.PendingIntent.CanceledException;
24import android.app.PendingIntent.OnFinished;
25import android.content.ActivityNotFoundException;
26import android.content.BroadcastReceiver;
27import android.content.ComponentName;
28import android.content.ContentResolver;
29import android.content.Context;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.content.pm.PackageManager;
33import android.os.Binder;
34import android.os.Bundle;
35import android.os.Handler;
36import android.os.IBinder;
37import android.os.Looper;
38import android.os.Message;
39import android.os.PowerManager;
40import android.os.RemoteException;
41import android.os.UserHandle;
42import android.os.IBinder.DeathRecipient;
43import android.provider.Settings;
44import android.speech.RecognizerIntent;
45import android.telephony.PhoneStateListener;
46import android.telephony.TelephonyManager;
47import android.util.Log;
48import android.view.KeyEvent;
49
50import java.io.FileDescriptor;
51import java.io.PrintWriter;
52import java.util.ArrayList;
53import java.util.Iterator;
54import java.util.Stack;
55
56/**
57 * @hide
58 *
59 */
60public class MediaFocusControl implements OnFinished {
61
62    private static final String TAG = "MediaFocusControl";
63
64    /** Debug remote control client/display feature */
65    protected static final boolean DEBUG_RC = false;
66    /** Debug volumes */
67    protected static final boolean DEBUG_VOL = false;
68
69    /** Used to alter media button redirection when the phone is ringing. */
70    private boolean mIsRinging = false;
71
72    private final PowerManager.WakeLock mMediaEventWakeLock;
73    private final MediaEventHandler mEventHandler;
74    private final Context mContext;
75    private final ContentResolver mContentResolver;
76    private final VolumeController mVolumeController;
77    private final BroadcastReceiver mReceiver = new PackageIntentsReceiver();
78    private final AppOpsManager mAppOps;
79    private final KeyguardManager mKeyguardManager;
80    private final AudioService mAudioService;
81
82    protected MediaFocusControl(Looper looper, Context cntxt,
83            VolumeController volumeCtrl, AudioService as) {
84        mEventHandler = new MediaEventHandler(looper);
85        mContext = cntxt;
86        mContentResolver = mContext.getContentResolver();
87        mVolumeController = volumeCtrl;
88        mAudioService = as;
89
90        PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
91        mMediaEventWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "handleMediaEvent");
92        mMainRemote = new RemotePlaybackState(-1,
93                AudioService.getMaxStreamVolume(AudioManager.STREAM_MUSIC),
94                AudioService.getMaxStreamVolume(AudioManager.STREAM_MUSIC));
95
96        // Register for phone state monitoring
97        TelephonyManager tmgr = (TelephonyManager)
98                mContext.getSystemService(Context.TELEPHONY_SERVICE);
99        tmgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
100
101        // Register for package addition/removal/change intent broadcasts
102        //    for media button receiver persistence
103        IntentFilter pkgFilter = new IntentFilter();
104        pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
105        pkgFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
106        pkgFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
107        pkgFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
108        pkgFilter.addDataScheme("package");
109        mContext.registerReceiver(mReceiver, pkgFilter);
110
111        mAppOps = (AppOpsManager)mContext.getSystemService(Context.APP_OPS_SERVICE);
112        mKeyguardManager =
113                (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
114
115        mHasRemotePlayback = false;
116        mMainRemoteIsActive = false;
117        postReevaluateRemote();
118    }
119
120    protected void dump(PrintWriter pw) {
121        dumpFocusStack(pw);
122        dumpRCStack(pw);
123        dumpRCCStack(pw);
124        dumpRCDList(pw);
125    }
126
127    //==========================================================================================
128    // Internal event handling
129    //==========================================================================================
130
131    // event handler messages
132    private static final int MSG_PERSIST_MEDIABUTTONRECEIVER = 0;
133    private static final int MSG_RCDISPLAY_CLEAR = 1;
134    private static final int MSG_RCDISPLAY_UPDATE = 2;
135    private static final int MSG_REEVALUATE_REMOTE = 3;
136    private static final int MSG_RCC_NEW_PLAYBACK_INFO = 4;
137    private static final int MSG_RCC_NEW_VOLUME_OBS = 5;
138    private static final int MSG_PROMOTE_RCC = 6;
139    private static final int MSG_RCC_NEW_PLAYBACK_STATE = 7;
140    private static final int MSG_RCC_SEEK_REQUEST = 8;
141    private static final int MSG_RCC_UPDATE_METADATA = 9;
142
143    // sendMsg() flags
144    /** If the msg is already queued, replace it with this one. */
145    private static final int SENDMSG_REPLACE = 0;
146    /** If the msg is already queued, ignore this one and leave the old. */
147    private static final int SENDMSG_NOOP = 1;
148    /** If the msg is already queued, queue this one and leave the old. */
149    private static final int SENDMSG_QUEUE = 2;
150
151    private static void sendMsg(Handler handler, int msg,
152            int existingMsgPolicy, int arg1, int arg2, Object obj, int delay) {
153
154        if (existingMsgPolicy == SENDMSG_REPLACE) {
155            handler.removeMessages(msg);
156        } else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) {
157            return;
158        }
159
160        handler.sendMessageDelayed(handler.obtainMessage(msg, arg1, arg2, obj), delay);
161    }
162
163    private class MediaEventHandler extends Handler {
164        MediaEventHandler(Looper looper) {
165            super(looper);
166        }
167
168        @Override
169        public void handleMessage(Message msg) {
170            switch(msg.what) {
171                case MSG_PERSIST_MEDIABUTTONRECEIVER:
172                    onHandlePersistMediaButtonReceiver( (ComponentName) msg.obj );
173                    break;
174
175                case MSG_RCDISPLAY_CLEAR:
176                    onRcDisplayClear();
177                    break;
178
179                case MSG_RCDISPLAY_UPDATE:
180                    // msg.obj is guaranteed to be non null
181                    onRcDisplayUpdate( (RemoteControlStackEntry) msg.obj, msg.arg1);
182                    break;
183
184                case MSG_REEVALUATE_REMOTE:
185                    onReevaluateRemote();
186                    break;
187
188                case MSG_RCC_NEW_PLAYBACK_INFO:
189                    onNewPlaybackInfoForRcc(msg.arg1 /* rccId */, msg.arg2 /* key */,
190                            ((Integer)msg.obj).intValue() /* value */);
191                    break;
192
193                case MSG_RCC_NEW_VOLUME_OBS:
194                    onRegisterVolumeObserverForRcc(msg.arg1 /* rccId */,
195                            (IRemoteVolumeObserver)msg.obj /* rvo */);
196                    break;
197
198                case MSG_RCC_NEW_PLAYBACK_STATE:
199                    onNewPlaybackStateForRcc(msg.arg1 /* rccId */,
200                            msg.arg2 /* state */,
201                            (RccPlaybackState)msg.obj /* newState */);
202                    break;
203
204                case MSG_RCC_SEEK_REQUEST:
205                    onSetRemoteControlClientPlaybackPosition(
206                            msg.arg1 /* generationId */, ((Long)msg.obj).longValue() /* timeMs */);
207                    break;
208
209                case MSG_RCC_UPDATE_METADATA:
210                    onUpdateRemoteControlClientMetadata(msg.arg1 /*genId*/, msg.arg2 /*key*/,
211                            (Rating) msg.obj /* value */);
212                    break;
213
214                case MSG_PROMOTE_RCC:
215                    onPromoteRcc(msg.arg1);
216                    break;
217            }
218        }
219    }
220
221
222    //==========================================================================================
223    // AudioFocus
224    //==========================================================================================
225
226    /* constant to identify focus stack entry that is used to hold the focus while the phone
227     * is ringing or during a call. Used by com.android.internal.telephony.CallManager when
228     * entering and exiting calls.
229     */
230    protected final static String IN_VOICE_COMM_FOCUS_ID = "AudioFocus_For_Phone_Ring_And_Calls";
231
232    private final static Object mAudioFocusLock = new Object();
233
234    private final static Object mRingingLock = new Object();
235
236    private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
237        @Override
238        public void onCallStateChanged(int state, String incomingNumber) {
239            if (state == TelephonyManager.CALL_STATE_RINGING) {
240                //Log.v(TAG, " CALL_STATE_RINGING");
241                synchronized(mRingingLock) {
242                    mIsRinging = true;
243                }
244            } else if ((state == TelephonyManager.CALL_STATE_OFFHOOK)
245                    || (state == TelephonyManager.CALL_STATE_IDLE)) {
246                synchronized(mRingingLock) {
247                    mIsRinging = false;
248                }
249            }
250        }
251    };
252
253    /**
254     * Discard the current audio focus owner.
255     * Notify top of audio focus stack that it lost focus (regardless of possibility to reassign
256     * focus), remove it from the stack, and clear the remote control display.
257     */
258    protected void discardAudioFocusOwner() {
259        synchronized(mAudioFocusLock) {
260            if (!mFocusStack.empty()) {
261                // notify the current focus owner it lost focus after removing it from stack
262                final FocusRequester exFocusOwner = mFocusStack.pop();
263                exFocusOwner.handleFocusLoss(AudioManager.AUDIOFOCUS_LOSS);
264                exFocusOwner.release();
265                // clear RCD
266                synchronized(mRCStack) {
267                    clearRemoteControlDisplay_syncAfRcs();
268                }
269            }
270        }
271    }
272
273    private void notifyTopOfAudioFocusStack() {
274        // notify the top of the stack it gained focus
275        if (!mFocusStack.empty()) {
276            if (canReassignAudioFocus()) {
277                mFocusStack.peek().handleFocusGain(AudioManager.AUDIOFOCUS_GAIN);
278            }
279        }
280    }
281
282    /**
283     * Focus is requested, propagate the associated loss throughout the stack.
284     * @param focusGain the new focus gain that will later be added at the top of the stack
285     */
286    private void propagateFocusLossFromGain_syncAf(int focusGain) {
287        // going through the audio focus stack to signal new focus, traversing order doesn't
288        // matter as all entries respond to the same external focus gain
289        Iterator<FocusRequester> stackIterator = mFocusStack.iterator();
290        while(stackIterator.hasNext()) {
291            stackIterator.next().handleExternalFocusGain(focusGain);
292        }
293    }
294
295    private final Stack<FocusRequester> mFocusStack = new Stack<FocusRequester>();
296
297    /**
298     * Helper function:
299     * Display in the log the current entries in the audio focus stack
300     */
301    private void dumpFocusStack(PrintWriter pw) {
302        pw.println("\nAudio Focus stack entries (last is top of stack):");
303        synchronized(mAudioFocusLock) {
304            Iterator<FocusRequester> stackIterator = mFocusStack.iterator();
305            while(stackIterator.hasNext()) {
306                stackIterator.next().dump(pw);
307            }
308        }
309    }
310
311    /**
312     * Helper function:
313     * Called synchronized on mAudioFocusLock
314     * Remove a focus listener from the focus stack.
315     * @param clientToRemove the focus listener
316     * @param signal if true and the listener was at the top of the focus stack, i.e. it was holding
317     *   focus, notify the next item in the stack it gained focus.
318     */
319    private void removeFocusStackEntry(String clientToRemove, boolean signal) {
320        // is the current top of the focus stack abandoning focus? (because of request, not death)
321        if (!mFocusStack.empty() && mFocusStack.peek().hasSameClient(clientToRemove))
322        {
323            //Log.i(TAG, "   removeFocusStackEntry() removing top of stack");
324            FocusRequester fr = mFocusStack.pop();
325            fr.release();
326            if (signal) {
327                // notify the new top of the stack it gained focus
328                notifyTopOfAudioFocusStack();
329                // there's a new top of the stack, let the remote control know
330                synchronized(mRCStack) {
331                    checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
332                }
333            }
334        } else {
335            // focus is abandoned by a client that's not at the top of the stack,
336            // no need to update focus.
337            // (using an iterator on the stack so we can safely remove an entry after having
338            //  evaluated it, traversal order doesn't matter here)
339            Iterator<FocusRequester> stackIterator = mFocusStack.iterator();
340            while(stackIterator.hasNext()) {
341                FocusRequester fr = (FocusRequester)stackIterator.next();
342                if(fr.hasSameClient(clientToRemove)) {
343                    Log.i(TAG, "AudioFocus  removeFocusStackEntry(): removing entry for "
344                            + clientToRemove);
345                    stackIterator.remove();
346                    fr.release();
347                }
348            }
349        }
350    }
351
352    /**
353     * Helper function:
354     * Called synchronized on mAudioFocusLock
355     * Remove focus listeners from the focus stack for a particular client when it has died.
356     */
357    private void removeFocusStackEntryForClient(IBinder cb) {
358        // is the owner of the audio focus part of the client to remove?
359        boolean isTopOfStackForClientToRemove = !mFocusStack.isEmpty() &&
360                mFocusStack.peek().hasSameBinder(cb);
361        // (using an iterator on the stack so we can safely remove an entry after having
362        //  evaluated it, traversal order doesn't matter here)
363        Iterator<FocusRequester> stackIterator = mFocusStack.iterator();
364        while(stackIterator.hasNext()) {
365            FocusRequester fr = (FocusRequester)stackIterator.next();
366            if(fr.hasSameBinder(cb)) {
367                Log.i(TAG, "AudioFocus  removeFocusStackEntry(): removing entry for " + cb);
368                stackIterator.remove();
369                // the client just died, no need to unlink to its death
370            }
371        }
372        if (isTopOfStackForClientToRemove) {
373            // we removed an entry at the top of the stack:
374            //  notify the new top of the stack it gained focus.
375            notifyTopOfAudioFocusStack();
376            // there's a new top of the stack, let the remote control know
377            synchronized(mRCStack) {
378                checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
379            }
380        }
381    }
382
383    /**
384     * Helper function:
385     * Returns true if the system is in a state where the focus can be reevaluated, false otherwise.
386     */
387    private boolean canReassignAudioFocus() {
388        // focus requests are rejected during a phone call or when the phone is ringing
389        // this is equivalent to IN_VOICE_COMM_FOCUS_ID having the focus
390        if (!mFocusStack.isEmpty() && mFocusStack.peek().hasSameClient(IN_VOICE_COMM_FOCUS_ID)) {
391            return false;
392        }
393        return true;
394    }
395
396    /**
397     * Inner class to monitor audio focus client deaths, and remove them from the audio focus
398     * stack if necessary.
399     */
400    protected class AudioFocusDeathHandler implements IBinder.DeathRecipient {
401        private IBinder mCb; // To be notified of client's death
402
403        AudioFocusDeathHandler(IBinder cb) {
404            mCb = cb;
405        }
406
407        public void binderDied() {
408            synchronized(mAudioFocusLock) {
409                Log.w(TAG, "  AudioFocus   audio focus client died");
410                removeFocusStackEntryForClient(mCb);
411            }
412        }
413
414        public IBinder getBinder() {
415            return mCb;
416        }
417    }
418
419    protected int getCurrentAudioFocus() {
420        synchronized(mAudioFocusLock) {
421            if (mFocusStack.empty()) {
422                return AudioManager.AUDIOFOCUS_NONE;
423            } else {
424                return mFocusStack.peek().getGainRequest();
425            }
426        }
427    }
428
429    /** @see AudioManager#requestAudioFocus(AudioManager.OnAudioFocusChangeListener, int, int)  */
430    protected int requestAudioFocus(int mainStreamType, int focusChangeHint, IBinder cb,
431            IAudioFocusDispatcher fd, String clientId, String callingPackageName) {
432        Log.i(TAG, " AudioFocus  requestAudioFocus() from " + clientId);
433        // we need a valid binder callback for clients
434        if (!cb.pingBinder()) {
435            Log.e(TAG, " AudioFocus DOA client for requestAudioFocus(), aborting.");
436            return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
437        }
438
439        if (mAppOps.noteOp(AppOpsManager.OP_TAKE_AUDIO_FOCUS, Binder.getCallingUid(),
440                callingPackageName) != AppOpsManager.MODE_ALLOWED) {
441            return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
442        }
443
444        synchronized(mAudioFocusLock) {
445            if (!canReassignAudioFocus()) {
446                return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
447            }
448
449            // handle the potential premature death of the new holder of the focus
450            // (premature death == death before abandoning focus)
451            // Register for client death notification
452            AudioFocusDeathHandler afdh = new AudioFocusDeathHandler(cb);
453            try {
454                cb.linkToDeath(afdh, 0);
455            } catch (RemoteException e) {
456                // client has already died!
457                Log.w(TAG, "AudioFocus  requestAudioFocus() could not link to "+cb+" binder death");
458                return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
459            }
460
461            if (!mFocusStack.empty() && mFocusStack.peek().hasSameClient(clientId)) {
462                // if focus is already owned by this client and the reason for acquiring the focus
463                // hasn't changed, don't do anything
464                if (mFocusStack.peek().getGainRequest() == focusChangeHint) {
465                    // unlink death handler so it can be gc'ed.
466                    // linkToDeath() creates a JNI global reference preventing collection.
467                    cb.unlinkToDeath(afdh, 0);
468                    return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
469                }
470                // the reason for the audio focus request has changed: remove the current top of
471                // stack and respond as if we had a new focus owner
472                FocusRequester fr = mFocusStack.pop();
473                fr.release();
474            }
475
476            // focus requester might already be somewhere below in the stack, remove it
477            removeFocusStackEntry(clientId, false /* signal */);
478
479            // propagate the focus change through the stack
480            if (!mFocusStack.empty()) {
481                propagateFocusLossFromGain_syncAf(focusChangeHint);
482            }
483
484            // push focus requester at the top of the audio focus stack
485            mFocusStack.push(new FocusRequester(mainStreamType, focusChangeHint, fd, cb,
486                    clientId, afdh, callingPackageName, Binder.getCallingUid()));
487
488            // there's a new top of the stack, let the remote control know
489            synchronized(mRCStack) {
490                checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
491            }
492        }//synchronized(mAudioFocusLock)
493
494        return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
495    }
496
497    /** @see AudioManager#abandonAudioFocus(AudioManager.OnAudioFocusChangeListener)  */
498    protected int abandonAudioFocus(IAudioFocusDispatcher fl, String clientId) {
499        Log.i(TAG, " AudioFocus  abandonAudioFocus() from " + clientId);
500        try {
501            // this will take care of notifying the new focus owner if needed
502            synchronized(mAudioFocusLock) {
503                removeFocusStackEntry(clientId, true /*signal*/);
504            }
505        } catch (java.util.ConcurrentModificationException cme) {
506            // Catching this exception here is temporary. It is here just to prevent
507            // a crash seen when the "Silent" notification is played. This is believed to be fixed
508            // but this try catch block is left just to be safe.
509            Log.e(TAG, "FATAL EXCEPTION AudioFocus  abandonAudioFocus() caused " + cme);
510            cme.printStackTrace();
511        }
512
513        return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
514    }
515
516
517    protected void unregisterAudioFocusClient(String clientId) {
518        synchronized(mAudioFocusLock) {
519            removeFocusStackEntry(clientId, false);
520        }
521    }
522
523
524    //==========================================================================================
525    // RemoteControl
526    //==========================================================================================
527    protected void dispatchMediaKeyEvent(KeyEvent keyEvent) {
528        filterMediaKeyEvent(keyEvent, false /*needWakeLock*/);
529    }
530
531    protected void dispatchMediaKeyEventUnderWakelock(KeyEvent keyEvent) {
532        filterMediaKeyEvent(keyEvent, true /*needWakeLock*/);
533    }
534
535    private void filterMediaKeyEvent(KeyEvent keyEvent, boolean needWakeLock) {
536        // sanity check on the incoming key event
537        if (!isValidMediaKeyEvent(keyEvent)) {
538            Log.e(TAG, "not dispatching invalid media key event " + keyEvent);
539            return;
540        }
541        // event filtering for telephony
542        synchronized(mRingingLock) {
543            synchronized(mRCStack) {
544                if ((mMediaReceiverForCalls != null) &&
545                        (mIsRinging || (mAudioService.getMode() == AudioSystem.MODE_IN_CALL))) {
546                    dispatchMediaKeyEventForCalls(keyEvent, needWakeLock);
547                    return;
548                }
549            }
550        }
551        // event filtering based on voice-based interactions
552        if (isValidVoiceInputKeyCode(keyEvent.getKeyCode())) {
553            filterVoiceInputKeyEvent(keyEvent, needWakeLock);
554        } else {
555            dispatchMediaKeyEvent(keyEvent, needWakeLock);
556        }
557    }
558
559    /**
560     * Handles the dispatching of the media button events to the telephony package.
561     * Precondition: mMediaReceiverForCalls != null
562     * @param keyEvent a non-null KeyEvent whose key code is one of the supported media buttons
563     * @param needWakeLock true if a PARTIAL_WAKE_LOCK needs to be held while this key event
564     *     is dispatched.
565     */
566    private void dispatchMediaKeyEventForCalls(KeyEvent keyEvent, boolean needWakeLock) {
567        Intent keyIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
568        keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
569        keyIntent.setPackage(mMediaReceiverForCalls.getPackageName());
570        if (needWakeLock) {
571            mMediaEventWakeLock.acquire();
572            keyIntent.putExtra(EXTRA_WAKELOCK_ACQUIRED, WAKELOCK_RELEASE_ON_FINISHED);
573        }
574        final long ident = Binder.clearCallingIdentity();
575        try {
576            mContext.sendOrderedBroadcastAsUser(keyIntent, UserHandle.ALL,
577                    null, mKeyEventDone, mEventHandler, Activity.RESULT_OK, null, null);
578        } finally {
579            Binder.restoreCallingIdentity(ident);
580        }
581    }
582
583    /**
584     * Handles the dispatching of the media button events to one of the registered listeners,
585     * or if there was none, broadcast an ACTION_MEDIA_BUTTON intent to the rest of the system.
586     * @param keyEvent a non-null KeyEvent whose key code is one of the supported media buttons
587     * @param needWakeLock true if a PARTIAL_WAKE_LOCK needs to be held while this key event
588     *     is dispatched.
589     */
590    private void dispatchMediaKeyEvent(KeyEvent keyEvent, boolean needWakeLock) {
591        if (needWakeLock) {
592            mMediaEventWakeLock.acquire();
593        }
594        Intent keyIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
595        keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
596        synchronized(mRCStack) {
597            if (!mRCStack.empty()) {
598                // send the intent that was registered by the client
599                try {
600                    mRCStack.peek().mMediaIntent.send(mContext,
601                            needWakeLock ? WAKELOCK_RELEASE_ON_FINISHED : 0 /*code*/,
602                            keyIntent, this, mEventHandler);
603                } catch (CanceledException e) {
604                    Log.e(TAG, "Error sending pending intent " + mRCStack.peek());
605                    e.printStackTrace();
606                }
607            } else {
608                // legacy behavior when nobody registered their media button event receiver
609                //    through AudioManager
610                if (needWakeLock) {
611                    keyIntent.putExtra(EXTRA_WAKELOCK_ACQUIRED, WAKELOCK_RELEASE_ON_FINISHED);
612                }
613                final long ident = Binder.clearCallingIdentity();
614                try {
615                    mContext.sendOrderedBroadcastAsUser(keyIntent, UserHandle.ALL,
616                            null, mKeyEventDone,
617                            mEventHandler, Activity.RESULT_OK, null, null);
618                } finally {
619                    Binder.restoreCallingIdentity(ident);
620                }
621            }
622        }
623    }
624
625    /**
626     * The different actions performed in response to a voice button key event.
627     */
628    private final static int VOICEBUTTON_ACTION_DISCARD_CURRENT_KEY_PRESS = 1;
629    private final static int VOICEBUTTON_ACTION_START_VOICE_INPUT = 2;
630    private final static int VOICEBUTTON_ACTION_SIMULATE_KEY_PRESS = 3;
631
632    private final Object mVoiceEventLock = new Object();
633    private boolean mVoiceButtonDown;
634    private boolean mVoiceButtonHandled;
635
636    /**
637     * Filter key events that may be used for voice-based interactions
638     * @param keyEvent a non-null KeyEvent whose key code is that of one of the supported
639     *    media buttons that can be used to trigger voice-based interactions.
640     * @param needWakeLock true if a PARTIAL_WAKE_LOCK needs to be held while this key event
641     *     is dispatched.
642     */
643    private void filterVoiceInputKeyEvent(KeyEvent keyEvent, boolean needWakeLock) {
644        if (DEBUG_RC) {
645            Log.v(TAG, "voice input key event: " + keyEvent + ", needWakeLock=" + needWakeLock);
646        }
647
648        int voiceButtonAction = VOICEBUTTON_ACTION_DISCARD_CURRENT_KEY_PRESS;
649        int keyAction = keyEvent.getAction();
650        synchronized (mVoiceEventLock) {
651            if (keyAction == KeyEvent.ACTION_DOWN) {
652                if (keyEvent.getRepeatCount() == 0) {
653                    // initial down
654                    mVoiceButtonDown = true;
655                    mVoiceButtonHandled = false;
656                } else if (mVoiceButtonDown && !mVoiceButtonHandled
657                        && (keyEvent.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0) {
658                    // long-press, start voice-based interactions
659                    mVoiceButtonHandled = true;
660                    voiceButtonAction = VOICEBUTTON_ACTION_START_VOICE_INPUT;
661                }
662            } else if (keyAction == KeyEvent.ACTION_UP) {
663                if (mVoiceButtonDown) {
664                    // voice button up
665                    mVoiceButtonDown = false;
666                    if (!mVoiceButtonHandled && !keyEvent.isCanceled()) {
667                        voiceButtonAction = VOICEBUTTON_ACTION_SIMULATE_KEY_PRESS;
668                    }
669                }
670            }
671        }//synchronized (mVoiceEventLock)
672
673        // take action after media button event filtering for voice-based interactions
674        switch (voiceButtonAction) {
675            case VOICEBUTTON_ACTION_DISCARD_CURRENT_KEY_PRESS:
676                if (DEBUG_RC) Log.v(TAG, "   ignore key event");
677                break;
678            case VOICEBUTTON_ACTION_START_VOICE_INPUT:
679                if (DEBUG_RC) Log.v(TAG, "   start voice-based interactions");
680                // then start the voice-based interactions
681                startVoiceBasedInteractions(needWakeLock);
682                break;
683            case VOICEBUTTON_ACTION_SIMULATE_KEY_PRESS:
684                if (DEBUG_RC) Log.v(TAG, "   send simulated key event, wakelock=" + needWakeLock);
685                sendSimulatedMediaButtonEvent(keyEvent, needWakeLock);
686                break;
687        }
688    }
689
690    private void sendSimulatedMediaButtonEvent(KeyEvent originalKeyEvent, boolean needWakeLock) {
691        // send DOWN event
692        KeyEvent keyEvent = KeyEvent.changeAction(originalKeyEvent, KeyEvent.ACTION_DOWN);
693        dispatchMediaKeyEvent(keyEvent, needWakeLock);
694        // send UP event
695        keyEvent = KeyEvent.changeAction(originalKeyEvent, KeyEvent.ACTION_UP);
696        dispatchMediaKeyEvent(keyEvent, needWakeLock);
697
698    }
699
700    private class PackageIntentsReceiver extends BroadcastReceiver {
701        @Override
702        public void onReceive(Context context, Intent intent) {
703            String action = intent.getAction();
704            if (action.equals(Intent.ACTION_PACKAGE_REMOVED)
705                    || action.equals(Intent.ACTION_PACKAGE_DATA_CLEARED)) {
706                if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
707                    // a package is being removed, not replaced
708                    String packageName = intent.getData().getSchemeSpecificPart();
709                    if (packageName != null) {
710                        cleanupMediaButtonReceiverForPackage(packageName, true);
711                    }
712                }
713            } else if (action.equals(Intent.ACTION_PACKAGE_ADDED)
714                    || action.equals(Intent.ACTION_PACKAGE_CHANGED)) {
715                String packageName = intent.getData().getSchemeSpecificPart();
716                if (packageName != null) {
717                    cleanupMediaButtonReceiverForPackage(packageName, false);
718                }
719            }
720        }
721    }
722
723    protected static boolean isMediaKeyCode(int keyCode) {
724        switch (keyCode) {
725            case KeyEvent.KEYCODE_MUTE:
726            case KeyEvent.KEYCODE_HEADSETHOOK:
727            case KeyEvent.KEYCODE_MEDIA_PLAY:
728            case KeyEvent.KEYCODE_MEDIA_PAUSE:
729            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
730            case KeyEvent.KEYCODE_MEDIA_STOP:
731            case KeyEvent.KEYCODE_MEDIA_NEXT:
732            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
733            case KeyEvent.KEYCODE_MEDIA_REWIND:
734            case KeyEvent.KEYCODE_MEDIA_RECORD:
735            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
736            case KeyEvent.KEYCODE_MEDIA_CLOSE:
737            case KeyEvent.KEYCODE_MEDIA_EJECT:
738            case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK:
739                return true;
740            default:
741                return false;
742        }
743    }
744
745    private static boolean isValidMediaKeyEvent(KeyEvent keyEvent) {
746        if (keyEvent == null) {
747            return false;
748        }
749        return MediaFocusControl.isMediaKeyCode(keyEvent.getKeyCode());
750    }
751
752    /**
753     * Checks whether the given key code is one that can trigger the launch of voice-based
754     *   interactions.
755     * @param keyCode the key code associated with the key event
756     * @return true if the key is one of the supported voice-based interaction triggers
757     */
758    private static boolean isValidVoiceInputKeyCode(int keyCode) {
759        if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK) {
760            return true;
761        } else {
762            return false;
763        }
764    }
765
766    /**
767     * Tell the system to start voice-based interactions / voice commands
768     */
769    private void startVoiceBasedInteractions(boolean needWakeLock) {
770        Intent voiceIntent = null;
771        // select which type of search to launch:
772        // - screen on and device unlocked: action is ACTION_WEB_SEARCH
773        // - device locked or screen off: action is ACTION_VOICE_SEARCH_HANDS_FREE
774        //    with EXTRA_SECURE set to true if the device is securely locked
775        PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
776        boolean isLocked = mKeyguardManager != null && mKeyguardManager.isKeyguardLocked();
777        if (!isLocked && pm.isScreenOn()) {
778            voiceIntent = new Intent(android.speech.RecognizerIntent.ACTION_WEB_SEARCH);
779            Log.i(TAG, "voice-based interactions: about to use ACTION_WEB_SEARCH");
780        } else {
781            voiceIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
782            voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE,
783                    isLocked && mKeyguardManager.isKeyguardSecure());
784            Log.i(TAG, "voice-based interactions: about to use ACTION_VOICE_SEARCH_HANDS_FREE");
785        }
786        // start the search activity
787        if (needWakeLock) {
788            mMediaEventWakeLock.acquire();
789        }
790        final long identity = Binder.clearCallingIdentity();
791        try {
792            if (voiceIntent != null) {
793                voiceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
794                        | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
795                mContext.startActivityAsUser(voiceIntent, UserHandle.CURRENT);
796            }
797        } catch (ActivityNotFoundException e) {
798            Log.w(TAG, "No activity for search: " + e);
799        } finally {
800            Binder.restoreCallingIdentity(identity);
801            if (needWakeLock) {
802                mMediaEventWakeLock.release();
803            }
804        }
805    }
806
807    private static final int WAKELOCK_RELEASE_ON_FINISHED = 1980; //magic number
808
809    // only set when wakelock was acquired, no need to check value when received
810    private static final String EXTRA_WAKELOCK_ACQUIRED =
811            "android.media.AudioService.WAKELOCK_ACQUIRED";
812
813    public void onSendFinished(PendingIntent pendingIntent, Intent intent,
814            int resultCode, String resultData, Bundle resultExtras) {
815        if (resultCode == WAKELOCK_RELEASE_ON_FINISHED) {
816            mMediaEventWakeLock.release();
817        }
818    }
819
820    BroadcastReceiver mKeyEventDone = new BroadcastReceiver() {
821        public void onReceive(Context context, Intent intent) {
822            if (intent == null) {
823                return;
824            }
825            Bundle extras = intent.getExtras();
826            if (extras == null) {
827                return;
828            }
829            if (extras.containsKey(EXTRA_WAKELOCK_ACQUIRED)) {
830                mMediaEventWakeLock.release();
831            }
832        }
833    };
834
835    /**
836     * Synchronization on mCurrentRcLock always inside a block synchronized on mRCStack
837     */
838    private final Object mCurrentRcLock = new Object();
839    /**
840     * The one remote control client which will receive a request for display information.
841     * This object may be null.
842     * Access protected by mCurrentRcLock.
843     */
844    private IRemoteControlClient mCurrentRcClient = null;
845
846    private final static int RC_INFO_NONE = 0;
847    private final static int RC_INFO_ALL =
848        RemoteControlClient.FLAG_INFORMATION_REQUEST_ALBUM_ART |
849        RemoteControlClient.FLAG_INFORMATION_REQUEST_KEY_MEDIA |
850        RemoteControlClient.FLAG_INFORMATION_REQUEST_METADATA |
851        RemoteControlClient.FLAG_INFORMATION_REQUEST_PLAYSTATE;
852
853    /**
854     * A monotonically increasing generation counter for mCurrentRcClient.
855     * Only accessed with a lock on mCurrentRcLock.
856     * No value wrap-around issues as we only act on equal values.
857     */
858    private int mCurrentRcClientGen = 0;
859
860    /**
861     * Inner class to monitor remote control client deaths, and remove the client for the
862     * remote control stack if necessary.
863     */
864    private class RcClientDeathHandler implements IBinder.DeathRecipient {
865        final private IBinder mCb; // To be notified of client's death
866        final private PendingIntent mMediaIntent;
867
868        RcClientDeathHandler(IBinder cb, PendingIntent pi) {
869            mCb = cb;
870            mMediaIntent = pi;
871        }
872
873        public void binderDied() {
874            Log.w(TAG, "  RemoteControlClient died");
875            // remote control client died, make sure the displays don't use it anymore
876            //  by setting its remote control client to null
877            registerRemoteControlClient(mMediaIntent, null/*rcClient*/, null/*ignored*/);
878            // the dead client was maybe handling remote playback, reevaluate
879            postReevaluateRemote();
880        }
881
882        public IBinder getBinder() {
883            return mCb;
884        }
885    }
886
887    /**
888     * A global counter for RemoteControlClient identifiers
889     */
890    private static int sLastRccId = 0;
891
892    private class RemotePlaybackState {
893        int mRccId;
894        int mVolume;
895        int mVolumeMax;
896        int mVolumeHandling;
897
898        private RemotePlaybackState(int id, int vol, int volMax) {
899            mRccId = id;
900            mVolume = vol;
901            mVolumeMax = volMax;
902            mVolumeHandling = RemoteControlClient.DEFAULT_PLAYBACK_VOLUME_HANDLING;
903        }
904    }
905
906    /**
907     * Internal cache for the playback information of the RemoteControlClient whose volume gets to
908     * be controlled by the volume keys ("main"), so we don't have to iterate over the RC stack
909     * every time we need this info.
910     */
911    private RemotePlaybackState mMainRemote;
912    /**
913     * Indicates whether the "main" RemoteControlClient is considered active.
914     * Use synchronized on mMainRemote.
915     */
916    private boolean mMainRemoteIsActive;
917    /**
918     * Indicates whether there is remote playback going on. True even if there is no "active"
919     * remote playback (mMainRemoteIsActive is false), but a RemoteControlClient has declared it
920     * handles remote playback.
921     * Use synchronized on mMainRemote.
922     */
923    private boolean mHasRemotePlayback;
924
925    private static class RccPlaybackState {
926        public int mState;
927        public long mPositionMs;
928        public float mSpeed;
929
930        public RccPlaybackState(int state, long positionMs, float speed) {
931            mState = state;
932            mPositionMs = positionMs;
933            mSpeed = speed;
934        }
935
936        public void reset() {
937            mState = RemoteControlClient.PLAYSTATE_STOPPED;
938            mPositionMs = RemoteControlClient.PLAYBACK_POSITION_INVALID;
939            mSpeed = RemoteControlClient.PLAYBACK_SPEED_1X;
940        }
941
942        @Override
943        public String toString() {
944            return stateToString() + ", " + posToString() + ", " + mSpeed + "X";
945        }
946
947        private String posToString() {
948            if (mPositionMs == RemoteControlClient.PLAYBACK_POSITION_INVALID) {
949                return "PLAYBACK_POSITION_INVALID";
950            } else if (mPositionMs == RemoteControlClient.PLAYBACK_POSITION_ALWAYS_UNKNOWN) {
951                return "PLAYBACK_POSITION_ALWAYS_UNKNOWN";
952            } else {
953                return (String.valueOf(mPositionMs) + "ms");
954            }
955        }
956
957        private String stateToString() {
958            switch (mState) {
959                case RemoteControlClient.PLAYSTATE_NONE:
960                    return "PLAYSTATE_NONE";
961                case RemoteControlClient.PLAYSTATE_STOPPED:
962                    return "PLAYSTATE_STOPPED";
963                case RemoteControlClient.PLAYSTATE_PAUSED:
964                    return "PLAYSTATE_PAUSED";
965                case RemoteControlClient.PLAYSTATE_PLAYING:
966                    return "PLAYSTATE_PLAYING";
967                case RemoteControlClient.PLAYSTATE_FAST_FORWARDING:
968                    return "PLAYSTATE_FAST_FORWARDING";
969                case RemoteControlClient.PLAYSTATE_REWINDING:
970                    return "PLAYSTATE_REWINDING";
971                case RemoteControlClient.PLAYSTATE_SKIPPING_FORWARDS:
972                    return "PLAYSTATE_SKIPPING_FORWARDS";
973                case RemoteControlClient.PLAYSTATE_SKIPPING_BACKWARDS:
974                    return "PLAYSTATE_SKIPPING_BACKWARDS";
975                case RemoteControlClient.PLAYSTATE_BUFFERING:
976                    return "PLAYSTATE_BUFFERING";
977                case RemoteControlClient.PLAYSTATE_ERROR:
978                    return "PLAYSTATE_ERROR";
979                default:
980                    return "[invalid playstate]";
981            }
982        }
983    }
984
985    protected static class RemoteControlStackEntry implements DeathRecipient {
986        public int mRccId = RemoteControlClient.RCSE_ID_UNREGISTERED;
987        final public MediaFocusControl mController;
988        /**
989         * The target for the ACTION_MEDIA_BUTTON events.
990         * Always non null.
991         */
992        final public PendingIntent mMediaIntent;
993        /**
994         * The registered media button event receiver.
995         * Always non null.
996         */
997        final public ComponentName mReceiverComponent;
998        public IBinder mToken;
999        public String mCallingPackageName;
1000        public int mCallingUid;
1001        /**
1002         * Provides access to the information to display on the remote control.
1003         * May be null (when a media button event receiver is registered,
1004         *     but no remote control client has been registered) */
1005        public IRemoteControlClient mRcClient;
1006        public RcClientDeathHandler mRcClientDeathHandler;
1007        /**
1008         * Information only used for non-local playback
1009         */
1010        public int mPlaybackType;
1011        public int mPlaybackVolume;
1012        public int mPlaybackVolumeMax;
1013        public int mPlaybackVolumeHandling;
1014        public int mPlaybackStream;
1015        public RccPlaybackState mPlaybackState;
1016        public IRemoteVolumeObserver mRemoteVolumeObs;
1017
1018        public void resetPlaybackInfo() {
1019            mPlaybackType = RemoteControlClient.PLAYBACK_TYPE_LOCAL;
1020            mPlaybackVolume = RemoteControlClient.DEFAULT_PLAYBACK_VOLUME;
1021            mPlaybackVolumeMax = RemoteControlClient.DEFAULT_PLAYBACK_VOLUME;
1022            mPlaybackVolumeHandling = RemoteControlClient.DEFAULT_PLAYBACK_VOLUME_HANDLING;
1023            mPlaybackStream = AudioManager.STREAM_MUSIC;
1024            mPlaybackState.reset();
1025            mRemoteVolumeObs = null;
1026        }
1027
1028        /** precondition: mediaIntent != null */
1029        public RemoteControlStackEntry(MediaFocusControl controller, PendingIntent mediaIntent,
1030                ComponentName eventReceiver, IBinder token) {
1031            mController = controller;
1032            mMediaIntent = mediaIntent;
1033            mReceiverComponent = eventReceiver;
1034            mToken = token;
1035            mCallingUid = -1;
1036            mRcClient = null;
1037            mRccId = ++sLastRccId;
1038            mPlaybackState = new RccPlaybackState(
1039                    RemoteControlClient.PLAYSTATE_STOPPED,
1040                    RemoteControlClient.PLAYBACK_POSITION_INVALID,
1041                    RemoteControlClient.PLAYBACK_SPEED_1X);
1042
1043            resetPlaybackInfo();
1044            if (mToken != null) {
1045                try {
1046                    mToken.linkToDeath(this, 0);
1047                } catch (RemoteException e) {
1048                    mController.mEventHandler.post(new Runnable() {
1049                        @Override public void run() {
1050                            mController.unregisterMediaButtonIntent(mMediaIntent);
1051                        }
1052                    });
1053                }
1054            }
1055        }
1056
1057        public void unlinkToRcClientDeath() {
1058            if ((mRcClientDeathHandler != null) && (mRcClientDeathHandler.mCb != null)) {
1059                try {
1060                    mRcClientDeathHandler.mCb.unlinkToDeath(mRcClientDeathHandler, 0);
1061                    mRcClientDeathHandler = null;
1062                } catch (java.util.NoSuchElementException e) {
1063                    // not much we can do here
1064                    Log.e(TAG, "Encountered " + e + " in unlinkToRcClientDeath()");
1065                    e.printStackTrace();
1066                }
1067            }
1068        }
1069
1070        public void destroy() {
1071            unlinkToRcClientDeath();
1072            if (mToken != null) {
1073                mToken.unlinkToDeath(this, 0);
1074                mToken = null;
1075            }
1076        }
1077
1078        @Override
1079        public void binderDied() {
1080            mController.unregisterMediaButtonIntent(mMediaIntent);
1081        }
1082
1083        @Override
1084        protected void finalize() throws Throwable {
1085            destroy(); // unlink exception handled inside method
1086            super.finalize();
1087        }
1088    }
1089
1090    /**
1091     *  The stack of remote control event receivers.
1092     *  Code sections and methods that modify the remote control event receiver stack are
1093     *  synchronized on mRCStack, but also BEFORE on mFocusLock as any change in either
1094     *  stack, audio focus or RC, can lead to a change in the remote control display
1095     */
1096    private final Stack<RemoteControlStackEntry> mRCStack = new Stack<RemoteControlStackEntry>();
1097
1098    /**
1099     * The component the telephony package can register so telephony calls have priority to
1100     * handle media button events
1101     */
1102    private ComponentName mMediaReceiverForCalls = null;
1103
1104    /**
1105     * Helper function:
1106     * Display in the log the current entries in the remote control focus stack
1107     */
1108    private void dumpRCStack(PrintWriter pw) {
1109        pw.println("\nRemote Control stack entries (last is top of stack):");
1110        synchronized(mRCStack) {
1111            Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
1112            while(stackIterator.hasNext()) {
1113                RemoteControlStackEntry rcse = stackIterator.next();
1114                pw.println("  pi: " + rcse.mMediaIntent +
1115                        " -- pack: " + rcse.mCallingPackageName +
1116                        "  -- ercvr: " + rcse.mReceiverComponent +
1117                        "  -- client: " + rcse.mRcClient +
1118                        "  -- uid: " + rcse.mCallingUid +
1119                        "  -- type: " + rcse.mPlaybackType +
1120                        "  state: " + rcse.mPlaybackState);
1121            }
1122        }
1123    }
1124
1125    /**
1126     * Helper function:
1127     * Display in the log the current entries in the remote control stack, focusing
1128     * on RemoteControlClient data
1129     */
1130    private void dumpRCCStack(PrintWriter pw) {
1131        pw.println("\nRemote Control Client stack entries (last is top of stack):");
1132        synchronized(mRCStack) {
1133            Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
1134            while(stackIterator.hasNext()) {
1135                RemoteControlStackEntry rcse = stackIterator.next();
1136                pw.println("  uid: " + rcse.mCallingUid +
1137                        "  -- id: " + rcse.mRccId +
1138                        "  -- type: " + rcse.mPlaybackType +
1139                        "  -- state: " + rcse.mPlaybackState +
1140                        "  -- vol handling: " + rcse.mPlaybackVolumeHandling +
1141                        "  -- vol: " + rcse.mPlaybackVolume +
1142                        "  -- volMax: " + rcse.mPlaybackVolumeMax +
1143                        "  -- volObs: " + rcse.mRemoteVolumeObs);
1144            }
1145            synchronized(mCurrentRcLock) {
1146                pw.println("\nCurrent remote control generation ID = " + mCurrentRcClientGen);
1147            }
1148        }
1149        synchronized (mMainRemote) {
1150            pw.println("\nRemote Volume State:");
1151            pw.println("  has remote: " + mHasRemotePlayback);
1152            pw.println("  is remote active: " + mMainRemoteIsActive);
1153            pw.println("  rccId: " + mMainRemote.mRccId);
1154            pw.println("  volume handling: "
1155                    + ((mMainRemote.mVolumeHandling == RemoteControlClient.PLAYBACK_VOLUME_FIXED) ?
1156                            "PLAYBACK_VOLUME_FIXED(0)" : "PLAYBACK_VOLUME_VARIABLE(1)"));
1157            pw.println("  volume: " + mMainRemote.mVolume);
1158            pw.println("  volume steps: " + mMainRemote.mVolumeMax);
1159        }
1160    }
1161
1162    /**
1163     * Helper function:
1164     * Display in the log the current entries in the list of remote control displays
1165     */
1166    private void dumpRCDList(PrintWriter pw) {
1167        pw.println("\nRemote Control Display list entries:");
1168        synchronized(mRCStack) {
1169            final Iterator<DisplayInfoForServer> displayIterator = mRcDisplays.iterator();
1170            while (displayIterator.hasNext()) {
1171                final DisplayInfoForServer di = (DisplayInfoForServer) displayIterator.next();
1172                pw.println("  IRCD: " + di.mRcDisplay +
1173                        "  -- w:" + di.mArtworkExpectedWidth +
1174                        "  -- h:" + di.mArtworkExpectedHeight+
1175                        "  -- wantsPosSync:" + di.mWantsPositionSync);
1176            }
1177        }
1178    }
1179
1180    /**
1181     * Helper function:
1182     * Remove any entry in the remote control stack that has the same package name as packageName
1183     * Pre-condition: packageName != null
1184     */
1185    private void cleanupMediaButtonReceiverForPackage(String packageName, boolean removeAll) {
1186        synchronized(mRCStack) {
1187            if (mRCStack.empty()) {
1188                return;
1189            } else {
1190                final PackageManager pm = mContext.getPackageManager();
1191                RemoteControlStackEntry oldTop = mRCStack.peek();
1192                Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
1193                // iterate over the stack entries
1194                // (using an iterator on the stack so we can safely remove an entry after having
1195                //  evaluated it, traversal order doesn't matter here)
1196                while(stackIterator.hasNext()) {
1197                    RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next();
1198                    if (removeAll && packageName.equals(rcse.mMediaIntent.getCreatorPackage())) {
1199                        // a stack entry is from the package being removed, remove it from the stack
1200                        stackIterator.remove();
1201                        rcse.destroy();
1202                    } else if (rcse.mReceiverComponent != null) {
1203                        try {
1204                            // Check to see if this receiver still exists.
1205                            pm.getReceiverInfo(rcse.mReceiverComponent, 0);
1206                        } catch (PackageManager.NameNotFoundException e) {
1207                            // Not found -- remove it!
1208                            stackIterator.remove();
1209                            rcse.destroy();
1210                        }
1211                    }
1212                }
1213                if (mRCStack.empty()) {
1214                    // no saved media button receiver
1215                    mEventHandler.sendMessage(
1216                            mEventHandler.obtainMessage(MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0,
1217                                    null));
1218                } else if (oldTop != mRCStack.peek()) {
1219                    // the top of the stack has changed, save it in the system settings
1220                    // by posting a message to persist it; only do this however if it has
1221                    // a concrete component name (is not a transient registration)
1222                    RemoteControlStackEntry rcse = mRCStack.peek();
1223                    if (rcse.mReceiverComponent != null) {
1224                        mEventHandler.sendMessage(
1225                                mEventHandler.obtainMessage(MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0,
1226                                        rcse.mReceiverComponent));
1227                    }
1228                }
1229            }
1230        }
1231    }
1232
1233    /**
1234     * Helper function:
1235     * Restore remote control receiver from the system settings.
1236     */
1237    protected void restoreMediaButtonReceiver() {
1238        String receiverName = Settings.System.getStringForUser(mContentResolver,
1239                Settings.System.MEDIA_BUTTON_RECEIVER, UserHandle.USER_CURRENT);
1240        if ((null != receiverName) && !receiverName.isEmpty()) {
1241            ComponentName eventReceiver = ComponentName.unflattenFromString(receiverName);
1242            if (eventReceiver == null) {
1243                // an invalid name was persisted
1244                return;
1245            }
1246            // construct a PendingIntent targeted to the restored component name
1247            // for the media button and register it
1248            Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
1249            //     the associated intent will be handled by the component being registered
1250            mediaButtonIntent.setComponent(eventReceiver);
1251            PendingIntent pi = PendingIntent.getBroadcast(mContext,
1252                    0/*requestCode, ignored*/, mediaButtonIntent, 0/*flags*/);
1253            registerMediaButtonIntent(pi, eventReceiver, null);
1254        }
1255    }
1256
1257    /**
1258     * Helper function:
1259     * Set the new remote control receiver at the top of the RC focus stack.
1260     * Called synchronized on mAudioFocusLock, then mRCStack
1261     * precondition: mediaIntent != null
1262     */
1263    private void pushMediaButtonReceiver_syncAfRcs(PendingIntent mediaIntent, ComponentName target,
1264            IBinder token) {
1265        // already at top of stack?
1266        if (!mRCStack.empty() && mRCStack.peek().mMediaIntent.equals(mediaIntent)) {
1267            return;
1268        }
1269        if (mAppOps.noteOp(AppOpsManager.OP_TAKE_MEDIA_BUTTONS, Binder.getCallingUid(),
1270                mediaIntent.getCreatorPackage()) != AppOpsManager.MODE_ALLOWED) {
1271            return;
1272        }
1273        RemoteControlStackEntry rcse = null;
1274        boolean wasInsideStack = false;
1275        try {
1276            for (int index = mRCStack.size()-1; index >= 0; index--) {
1277                rcse = mRCStack.elementAt(index);
1278                if(rcse.mMediaIntent.equals(mediaIntent)) {
1279                    // ok to remove element while traversing the stack since we're leaving the loop
1280                    mRCStack.removeElementAt(index);
1281                    wasInsideStack = true;
1282                    break;
1283                }
1284            }
1285        } catch (ArrayIndexOutOfBoundsException e) {
1286            // not expected to happen, indicates improper concurrent modification
1287            Log.e(TAG, "Wrong index accessing media button stack, lock error? ", e);
1288        }
1289        if (!wasInsideStack) {
1290            rcse = new RemoteControlStackEntry(this, mediaIntent, target, token);
1291        }
1292        mRCStack.push(rcse); // rcse is never null
1293
1294        // post message to persist the default media button receiver
1295        if (target != null) {
1296            mEventHandler.sendMessage( mEventHandler.obtainMessage(
1297                    MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0, target/*obj*/) );
1298        }
1299    }
1300
1301    /**
1302     * Helper function:
1303     * Remove the remote control receiver from the RC focus stack.
1304     * Called synchronized on mAudioFocusLock, then mRCStack
1305     * precondition: pi != null
1306     */
1307    private void removeMediaButtonReceiver_syncAfRcs(PendingIntent pi) {
1308        try {
1309            for (int index = mRCStack.size()-1; index >= 0; index--) {
1310                final RemoteControlStackEntry rcse = mRCStack.elementAt(index);
1311                if (rcse.mMediaIntent.equals(pi)) {
1312                    rcse.destroy();
1313                    // ok to remove element while traversing the stack since we're leaving the loop
1314                    mRCStack.removeElementAt(index);
1315                    break;
1316                }
1317            }
1318        } catch (ArrayIndexOutOfBoundsException e) {
1319            // not expected to happen, indicates improper concurrent modification
1320            Log.e(TAG, "Wrong index accessing media button stack, lock error? ", e);
1321        }
1322    }
1323
1324    /**
1325     * Helper function:
1326     * Called synchronized on mRCStack
1327     */
1328    private boolean isCurrentRcController(PendingIntent pi) {
1329        if (!mRCStack.empty() && mRCStack.peek().mMediaIntent.equals(pi)) {
1330            return true;
1331        }
1332        return false;
1333    }
1334
1335    private void onHandlePersistMediaButtonReceiver(ComponentName receiver) {
1336        Settings.System.putStringForUser(mContentResolver,
1337                                         Settings.System.MEDIA_BUTTON_RECEIVER,
1338                                         receiver == null ? "" : receiver.flattenToString(),
1339                                         UserHandle.USER_CURRENT);
1340    }
1341
1342    //==========================================================================================
1343    // Remote control display / client
1344    //==========================================================================================
1345    /**
1346     * Update the remote control displays with the new "focused" client generation
1347     */
1348    private void setNewRcClientOnDisplays_syncRcsCurrc(int newClientGeneration,
1349            PendingIntent newMediaIntent, boolean clearing) {
1350        synchronized(mRCStack) {
1351            if (mRcDisplays.size() > 0) {
1352                final Iterator<DisplayInfoForServer> displayIterator = mRcDisplays.iterator();
1353                while (displayIterator.hasNext()) {
1354                    final DisplayInfoForServer di = displayIterator.next();
1355                    try {
1356                        di.mRcDisplay.setCurrentClientId(
1357                                newClientGeneration, newMediaIntent, clearing);
1358                    } catch (RemoteException e) {
1359                        Log.e(TAG, "Dead display in setNewRcClientOnDisplays_syncRcsCurrc()",e);
1360                        di.release();
1361                        displayIterator.remove();
1362                    }
1363                }
1364            }
1365        }
1366    }
1367
1368    /**
1369     * Update the remote control clients with the new "focused" client generation
1370     */
1371    private void setNewRcClientGenerationOnClients_syncRcsCurrc(int newClientGeneration) {
1372        // (using an iterator on the stack so we can safely remove an entry if needed,
1373        //  traversal order doesn't matter here as we update all entries)
1374        Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
1375        while(stackIterator.hasNext()) {
1376            RemoteControlStackEntry se = stackIterator.next();
1377            if ((se != null) && (se.mRcClient != null)) {
1378                try {
1379                    se.mRcClient.setCurrentClientGenerationId(newClientGeneration);
1380                } catch (RemoteException e) {
1381                    Log.w(TAG, "Dead client in setNewRcClientGenerationOnClients_syncRcsCurrc()",e);
1382                    stackIterator.remove();
1383                    se.unlinkToRcClientDeath();
1384                }
1385            }
1386        }
1387    }
1388
1389    /**
1390     * Update the displays and clients with the new "focused" client generation and name
1391     * @param newClientGeneration the new generation value matching a client update
1392     * @param newMediaIntent the media button event receiver associated with the client.
1393     *    May be null, which implies there is no registered media button event receiver.
1394     * @param clearing true if the new client generation value maps to a remote control update
1395     *    where the display should be cleared.
1396     */
1397    private void setNewRcClient_syncRcsCurrc(int newClientGeneration,
1398            PendingIntent newMediaIntent, boolean clearing) {
1399        // send the new valid client generation ID to all displays
1400        setNewRcClientOnDisplays_syncRcsCurrc(newClientGeneration, newMediaIntent, clearing);
1401        // send the new valid client generation ID to all clients
1402        setNewRcClientGenerationOnClients_syncRcsCurrc(newClientGeneration);
1403    }
1404
1405    /**
1406     * Called when processing MSG_RCDISPLAY_CLEAR event
1407     */
1408    private void onRcDisplayClear() {
1409        if (DEBUG_RC) Log.i(TAG, "Clear remote control display");
1410
1411        synchronized(mRCStack) {
1412            synchronized(mCurrentRcLock) {
1413                mCurrentRcClientGen++;
1414                // synchronously update the displays and clients with the new client generation
1415                setNewRcClient_syncRcsCurrc(mCurrentRcClientGen,
1416                        null /*newMediaIntent*/, true /*clearing*/);
1417            }
1418        }
1419    }
1420
1421    /**
1422     * Called when processing MSG_RCDISPLAY_UPDATE event
1423     */
1424    private void onRcDisplayUpdate(RemoteControlStackEntry rcse, int flags /* USED ?*/) {
1425        synchronized(mRCStack) {
1426            synchronized(mCurrentRcLock) {
1427                if ((mCurrentRcClient != null) && (mCurrentRcClient.equals(rcse.mRcClient))) {
1428                    if (DEBUG_RC) Log.i(TAG, "Display/update remote control ");
1429
1430                    mCurrentRcClientGen++;
1431                    // synchronously update the displays and clients with
1432                    //      the new client generation
1433                    setNewRcClient_syncRcsCurrc(mCurrentRcClientGen,
1434                            rcse.mMediaIntent /*newMediaIntent*/,
1435                            false /*clearing*/);
1436
1437                    // tell the current client that it needs to send info
1438                    try {
1439                        mCurrentRcClient.onInformationRequested(mCurrentRcClientGen, flags);
1440                    } catch (RemoteException e) {
1441                        Log.e(TAG, "Current valid remote client is dead: "+e);
1442                        mCurrentRcClient = null;
1443                    }
1444                } else {
1445                    // the remote control display owner has changed between the
1446                    // the message to update the display was sent, and the time it
1447                    // gets to be processed (now)
1448                }
1449            }
1450        }
1451    }
1452
1453
1454    /**
1455     * Helper function:
1456     * Called synchronized on mRCStack
1457     */
1458    private void clearRemoteControlDisplay_syncAfRcs() {
1459        synchronized(mCurrentRcLock) {
1460            mCurrentRcClient = null;
1461        }
1462        // will cause onRcDisplayClear() to be called in AudioService's handler thread
1463        mEventHandler.sendMessage( mEventHandler.obtainMessage(MSG_RCDISPLAY_CLEAR) );
1464    }
1465
1466    /**
1467     * Helper function for code readability: only to be called from
1468     *    checkUpdateRemoteControlDisplay_syncAfRcs() which checks the preconditions for
1469     *    this method.
1470     * Preconditions:
1471     *    - called synchronized mAudioFocusLock then on mRCStack
1472     *    - mRCStack.isEmpty() is false
1473     */
1474    private void updateRemoteControlDisplay_syncAfRcs(int infoChangedFlags) {
1475        RemoteControlStackEntry rcse = mRCStack.peek();
1476        int infoFlagsAboutToBeUsed = infoChangedFlags;
1477        // this is where we enforce opt-in for information display on the remote controls
1478        //   with the new AudioManager.registerRemoteControlClient() API
1479        if (rcse.mRcClient == null) {
1480            //Log.w(TAG, "Can't update remote control display with null remote control client");
1481            clearRemoteControlDisplay_syncAfRcs();
1482            return;
1483        }
1484        synchronized(mCurrentRcLock) {
1485            if (!rcse.mRcClient.equals(mCurrentRcClient)) {
1486                // new RC client, assume every type of information shall be queried
1487                infoFlagsAboutToBeUsed = RC_INFO_ALL;
1488            }
1489            mCurrentRcClient = rcse.mRcClient;
1490        }
1491        // will cause onRcDisplayUpdate() to be called in AudioService's handler thread
1492        mEventHandler.sendMessage( mEventHandler.obtainMessage(MSG_RCDISPLAY_UPDATE,
1493                infoFlagsAboutToBeUsed /* arg1 */, 0, rcse /* obj, != null */) );
1494    }
1495
1496    /**
1497     * Helper function:
1498     * Called synchronized on mAudioFocusLock, then mRCStack
1499     * Check whether the remote control display should be updated, triggers the update if required
1500     * @param infoChangedFlags the flags corresponding to the remote control client information
1501     *     that has changed, if applicable (checking for the update conditions might trigger a
1502     *     clear, rather than an update event).
1503     */
1504    private void checkUpdateRemoteControlDisplay_syncAfRcs(int infoChangedFlags) {
1505        // determine whether the remote control display should be refreshed
1506        // if either stack is empty, there is a mismatch, so clear the RC display
1507        if (mRCStack.isEmpty() || mFocusStack.isEmpty()) {
1508            clearRemoteControlDisplay_syncAfRcs();
1509            return;
1510        }
1511
1512        // determine which entry in the AudioFocus stack to consider, and compare against the
1513        // top of the stack for the media button event receivers : simply using the top of the
1514        // stack would make the entry disappear from the RemoteControlDisplay in conditions such as
1515        // notifications playing during music playback.
1516        // Crawl the AudioFocus stack from the top until an entry is found with the following
1517        // characteristics:
1518        // - focus gain on STREAM_MUSIC stream
1519        // - non-transient focus gain on a stream other than music
1520        FocusRequester af = null;
1521        try {
1522            for (int index = mFocusStack.size()-1; index >= 0; index--) {
1523                FocusRequester fr = mFocusStack.elementAt(index);
1524                if ((fr.getStreamType() == AudioManager.STREAM_MUSIC)
1525                        || (fr.getGainRequest() == AudioManager.AUDIOFOCUS_GAIN)) {
1526                    af = fr;
1527                    break;
1528                }
1529            }
1530        } catch (ArrayIndexOutOfBoundsException e) {
1531            Log.e(TAG, "Wrong index accessing audio focus stack when updating RCD: " + e);
1532            af = null;
1533        }
1534        if (af == null) {
1535            clearRemoteControlDisplay_syncAfRcs();
1536            return;
1537        }
1538
1539        // if the audio focus and RC owners belong to different packages, there is a mismatch, clear
1540        if (!af.hasSamePackage(mRCStack.peek().mCallingPackageName)) {
1541            clearRemoteControlDisplay_syncAfRcs();
1542            return;
1543        }
1544        // if the audio focus didn't originate from the same Uid as the one in which the remote
1545        //   control information will be retrieved, clear
1546        if (!af.hasSameUid(mRCStack.peek().mCallingUid)) {
1547            clearRemoteControlDisplay_syncAfRcs();
1548            return;
1549        }
1550
1551        // refresh conditions were verified: update the remote controls
1552        // ok to call: synchronized mAudioFocusLock then on mRCStack, mRCStack is not empty
1553        updateRemoteControlDisplay_syncAfRcs(infoChangedFlags);
1554    }
1555
1556    /**
1557     * Helper function:
1558     * Post a message to asynchronously move the media button event receiver associated with the
1559     * given remote control client ID to the top of the remote control stack
1560     * @param rccId
1561     */
1562    private void postPromoteRcc(int rccId) {
1563        sendMsg(mEventHandler, MSG_PROMOTE_RCC, SENDMSG_REPLACE,
1564                rccId /*arg1*/, 0, null, 0/*delay*/);
1565    }
1566
1567    private void onPromoteRcc(int rccId) {
1568        if (DEBUG_RC) { Log.d(TAG, "Promoting RCC " + rccId); }
1569        synchronized(mAudioFocusLock) {
1570            synchronized(mRCStack) {
1571                // ignore if given RCC ID is already at top of remote control stack
1572                if (!mRCStack.isEmpty() && (mRCStack.peek().mRccId == rccId)) {
1573                    return;
1574                }
1575                int indexToPromote = -1;
1576                try {
1577                    for (int index = mRCStack.size()-1; index >= 0; index--) {
1578                        final RemoteControlStackEntry rcse = mRCStack.elementAt(index);
1579                        if (rcse.mRccId == rccId) {
1580                            indexToPromote = index;
1581                            break;
1582                        }
1583                    }
1584                    if (indexToPromote >= 0) {
1585                        if (DEBUG_RC) { Log.d(TAG, "  moving RCC from index " + indexToPromote
1586                                + " to " + (mRCStack.size()-1)); }
1587                        final RemoteControlStackEntry rcse = mRCStack.remove(indexToPromote);
1588                        mRCStack.push(rcse);
1589                        // the RC stack changed, reevaluate the display
1590                        checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
1591                    }
1592                } catch (ArrayIndexOutOfBoundsException e) {
1593                    // not expected to happen, indicates improper concurrent modification
1594                    Log.e(TAG, "Wrong index accessing RC stack, lock error? ", e);
1595                }
1596            }//synchronized(mRCStack)
1597        }//synchronized(mAudioFocusLock)
1598    }
1599
1600    /**
1601     * see AudioManager.registerMediaButtonIntent(PendingIntent pi, ComponentName c)
1602     * precondition: mediaIntent != null
1603     */
1604    protected void registerMediaButtonIntent(PendingIntent mediaIntent, ComponentName eventReceiver,
1605            IBinder token) {
1606        Log.i(TAG, "  Remote Control   registerMediaButtonIntent() for " + mediaIntent);
1607
1608        synchronized(mAudioFocusLock) {
1609            synchronized(mRCStack) {
1610                pushMediaButtonReceiver_syncAfRcs(mediaIntent, eventReceiver, token);
1611                // new RC client, assume every type of information shall be queried
1612                checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
1613            }
1614        }
1615    }
1616
1617    /**
1618     * see AudioManager.unregisterMediaButtonIntent(PendingIntent mediaIntent)
1619     * precondition: mediaIntent != null, eventReceiver != null
1620     */
1621    protected void unregisterMediaButtonIntent(PendingIntent mediaIntent)
1622    {
1623        Log.i(TAG, "  Remote Control   unregisterMediaButtonIntent() for " + mediaIntent);
1624
1625        synchronized(mAudioFocusLock) {
1626            synchronized(mRCStack) {
1627                boolean topOfStackWillChange = isCurrentRcController(mediaIntent);
1628                removeMediaButtonReceiver_syncAfRcs(mediaIntent);
1629                if (topOfStackWillChange) {
1630                    // current RC client will change, assume every type of info needs to be queried
1631                    checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
1632                }
1633            }
1634        }
1635    }
1636
1637    /**
1638     * see AudioManager.registerMediaButtonEventReceiverForCalls(ComponentName c)
1639     * precondition: c != null
1640     */
1641    protected void registerMediaButtonEventReceiverForCalls(ComponentName c) {
1642        if (mContext.checkCallingPermission("android.permission.MODIFY_PHONE_STATE")
1643                != PackageManager.PERMISSION_GRANTED) {
1644            Log.e(TAG, "Invalid permissions to register media button receiver for calls");
1645            return;
1646        }
1647        synchronized(mRCStack) {
1648            mMediaReceiverForCalls = c;
1649        }
1650    }
1651
1652    /**
1653     * see AudioManager.unregisterMediaButtonEventReceiverForCalls()
1654     */
1655    protected void unregisterMediaButtonEventReceiverForCalls() {
1656        if (mContext.checkCallingPermission("android.permission.MODIFY_PHONE_STATE")
1657                != PackageManager.PERMISSION_GRANTED) {
1658            Log.e(TAG, "Invalid permissions to unregister media button receiver for calls");
1659            return;
1660        }
1661        synchronized(mRCStack) {
1662            mMediaReceiverForCalls = null;
1663        }
1664    }
1665
1666    /**
1667     * see AudioManager.registerRemoteControlClient(ComponentName eventReceiver, ...)
1668     * @return the unique ID of the RemoteControlStackEntry associated with the RemoteControlClient
1669     * Note: using this method with rcClient == null is a way to "disable" the IRemoteControlClient
1670     *     without modifying the RC stack, but while still causing the display to refresh (will
1671     *     become blank as a result of this)
1672     */
1673    protected int registerRemoteControlClient(PendingIntent mediaIntent,
1674            IRemoteControlClient rcClient, String callingPackageName) {
1675        if (DEBUG_RC) Log.i(TAG, "Register remote control client rcClient="+rcClient);
1676        int rccId = RemoteControlClient.RCSE_ID_UNREGISTERED;
1677        synchronized(mAudioFocusLock) {
1678            synchronized(mRCStack) {
1679                // store the new display information
1680                try {
1681                    for (int index = mRCStack.size()-1; index >= 0; index--) {
1682                        final RemoteControlStackEntry rcse = mRCStack.elementAt(index);
1683                        if(rcse.mMediaIntent.equals(mediaIntent)) {
1684                            // already had a remote control client?
1685                            if (rcse.mRcClientDeathHandler != null) {
1686                                // stop monitoring the old client's death
1687                                rcse.unlinkToRcClientDeath();
1688                            }
1689                            // save the new remote control client
1690                            rcse.mRcClient = rcClient;
1691                            rcse.mCallingPackageName = callingPackageName;
1692                            rcse.mCallingUid = Binder.getCallingUid();
1693                            if (rcClient == null) {
1694                                // here rcse.mRcClientDeathHandler is null;
1695                                rcse.resetPlaybackInfo();
1696                                break;
1697                            }
1698                            rccId = rcse.mRccId;
1699
1700                            // there is a new (non-null) client:
1701                            // 1/ give the new client the displays (if any)
1702                            if (mRcDisplays.size() > 0) {
1703                                plugRemoteControlDisplaysIntoClient_syncRcStack(rcse.mRcClient);
1704                            }
1705                            // 2/ monitor the new client's death
1706                            IBinder b = rcse.mRcClient.asBinder();
1707                            RcClientDeathHandler rcdh =
1708                                    new RcClientDeathHandler(b, rcse.mMediaIntent);
1709                            try {
1710                                b.linkToDeath(rcdh, 0);
1711                            } catch (RemoteException e) {
1712                                // remote control client is DOA, disqualify it
1713                                Log.w(TAG, "registerRemoteControlClient() has a dead client " + b);
1714                                rcse.mRcClient = null;
1715                            }
1716                            rcse.mRcClientDeathHandler = rcdh;
1717                            break;
1718                        }
1719                    }//for
1720                } catch (ArrayIndexOutOfBoundsException e) {
1721                    // not expected to happen, indicates improper concurrent modification
1722                    Log.e(TAG, "Wrong index accessing RC stack, lock error? ", e);
1723                }
1724
1725                // if the eventReceiver is at the top of the stack
1726                // then check for potential refresh of the remote controls
1727                if (isCurrentRcController(mediaIntent)) {
1728                    checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
1729                }
1730            }//synchronized(mRCStack)
1731        }//synchronized(mAudioFocusLock)
1732        return rccId;
1733    }
1734
1735    /**
1736     * see AudioManager.unregisterRemoteControlClient(PendingIntent pi, ...)
1737     * rcClient is guaranteed non-null
1738     */
1739    protected void unregisterRemoteControlClient(PendingIntent mediaIntent,
1740            IRemoteControlClient rcClient) {
1741        if (DEBUG_RC) Log.i(TAG, "Unregister remote control client rcClient="+rcClient);
1742        synchronized(mAudioFocusLock) {
1743            synchronized(mRCStack) {
1744                boolean topRccChange = false;
1745                try {
1746                    for (int index = mRCStack.size()-1; index >= 0; index--) {
1747                        final RemoteControlStackEntry rcse = mRCStack.elementAt(index);
1748                        if ((rcse.mMediaIntent.equals(mediaIntent))
1749                                && rcClient.equals(rcse.mRcClient)) {
1750                            // we found the IRemoteControlClient to unregister
1751                            // stop monitoring its death
1752                            rcse.unlinkToRcClientDeath();
1753                            // reset the client-related fields
1754                            rcse.mRcClient = null;
1755                            rcse.mCallingPackageName = null;
1756                            topRccChange = (index == mRCStack.size()-1);
1757                            // there can only be one matching RCC in the RC stack, we're done
1758                            break;
1759                        }
1760                    }
1761                } catch (ArrayIndexOutOfBoundsException e) {
1762                    // not expected to happen, indicates improper concurrent modification
1763                    Log.e(TAG, "Wrong index accessing RC stack, lock error? ", e);
1764                }
1765                if (topRccChange) {
1766                    // no more RCC for the RCD, check for potential refresh of the remote controls
1767                    checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
1768                }
1769            }
1770        }
1771    }
1772
1773
1774    /**
1775     * A class to encapsulate all the information about a remote control display.
1776     * After instanciation, init() must always be called before the object is added in the list
1777     * of displays.
1778     * Before being removed from the list of displays, release() must always be called (otherwise
1779     * it will leak death handlers).
1780     */
1781    private class DisplayInfoForServer implements IBinder.DeathRecipient {
1782        /** may never be null */
1783        private IRemoteControlDisplay mRcDisplay;
1784        private IBinder mRcDisplayBinder;
1785        private int mArtworkExpectedWidth = -1;
1786        private int mArtworkExpectedHeight = -1;
1787        private boolean mWantsPositionSync = false;
1788
1789        public DisplayInfoForServer(IRemoteControlDisplay rcd, int w, int h) {
1790            if (DEBUG_RC) Log.i(TAG, "new DisplayInfoForServer for " + rcd + " w=" + w + " h=" + h);
1791            mRcDisplay = rcd;
1792            mRcDisplayBinder = rcd.asBinder();
1793            mArtworkExpectedWidth = w;
1794            mArtworkExpectedHeight = h;
1795        }
1796
1797        public boolean init() {
1798            try {
1799                mRcDisplayBinder.linkToDeath(this, 0);
1800            } catch (RemoteException e) {
1801                // remote control display is DOA, disqualify it
1802                Log.w(TAG, "registerRemoteControlDisplay() has a dead client " + mRcDisplayBinder);
1803                return false;
1804            }
1805            return true;
1806        }
1807
1808        public void release() {
1809            try {
1810                mRcDisplayBinder.unlinkToDeath(this, 0);
1811            } catch (java.util.NoSuchElementException e) {
1812                // not much we can do here, the display should have been unregistered anyway
1813                Log.e(TAG, "Error in DisplaInfoForServer.relase()", e);
1814            }
1815        }
1816
1817        public void binderDied() {
1818            synchronized(mRCStack) {
1819                Log.w(TAG, "RemoteControl: display " + mRcDisplay + " died");
1820                // remove the display from the list
1821                final Iterator<DisplayInfoForServer> displayIterator = mRcDisplays.iterator();
1822                while (displayIterator.hasNext()) {
1823                    final DisplayInfoForServer di = (DisplayInfoForServer) displayIterator.next();
1824                    if (di.mRcDisplay == mRcDisplay) {
1825                        if (DEBUG_RC) Log.w(TAG, " RCD removed from list");
1826                        displayIterator.remove();
1827                        return;
1828                    }
1829                }
1830            }
1831        }
1832    }
1833
1834    /**
1835     * The remote control displays.
1836     * Access synchronized on mRCStack
1837     */
1838    private ArrayList<DisplayInfoForServer> mRcDisplays = new ArrayList<DisplayInfoForServer>(1);
1839
1840    /**
1841     * Plug each registered display into the specified client
1842     * @param rcc, guaranteed non null
1843     */
1844    private void plugRemoteControlDisplaysIntoClient_syncRcStack(IRemoteControlClient rcc) {
1845        final Iterator<DisplayInfoForServer> displayIterator = mRcDisplays.iterator();
1846        while (displayIterator.hasNext()) {
1847            final DisplayInfoForServer di = (DisplayInfoForServer) displayIterator.next();
1848            try {
1849                rcc.plugRemoteControlDisplay(di.mRcDisplay, di.mArtworkExpectedWidth,
1850                        di.mArtworkExpectedHeight);
1851                if (di.mWantsPositionSync) {
1852                    rcc.setWantsSyncForDisplay(di.mRcDisplay, true);
1853                }
1854            } catch (RemoteException e) {
1855                Log.e(TAG, "Error connecting RCD to RCC in RCC registration",e);
1856            }
1857        }
1858    }
1859
1860    /**
1861     * Is the remote control display interface already registered
1862     * @param rcd
1863     * @return true if the IRemoteControlDisplay is already in the list of displays
1864     */
1865    private boolean rcDisplayIsPluggedIn_syncRcStack(IRemoteControlDisplay rcd) {
1866        final Iterator<DisplayInfoForServer> displayIterator = mRcDisplays.iterator();
1867        while (displayIterator.hasNext()) {
1868            final DisplayInfoForServer di = (DisplayInfoForServer) displayIterator.next();
1869            if (di.mRcDisplay.asBinder().equals(rcd.asBinder())) {
1870                return true;
1871            }
1872        }
1873        return false;
1874    }
1875
1876    /**
1877     * Register an IRemoteControlDisplay.
1878     * Notify all IRemoteControlClient of the new display and cause the RemoteControlClient
1879     * at the top of the stack to update the new display with its information.
1880     * @see android.media.IAudioService#registerRemoteControlDisplay(android.media.IRemoteControlDisplay, int, int)
1881     * @param rcd the IRemoteControlDisplay to register. No effect if null.
1882     * @param w the maximum width of the expected bitmap. Negative or zero values indicate this
1883     *   display doesn't need to receive artwork.
1884     * @param h the maximum height of the expected bitmap. Negative or zero values indicate this
1885     *   display doesn't need to receive artwork.
1886     */
1887    protected void registerRemoteControlDisplay(IRemoteControlDisplay rcd, int w, int h) {
1888        if (DEBUG_RC) Log.d(TAG, ">>> registerRemoteControlDisplay("+rcd+")");
1889        synchronized(mAudioFocusLock) {
1890            synchronized(mRCStack) {
1891                if ((rcd == null) || rcDisplayIsPluggedIn_syncRcStack(rcd)) {
1892                    return;
1893                }
1894                DisplayInfoForServer di = new DisplayInfoForServer(rcd, w, h);
1895                if (!di.init()) {
1896                    if (DEBUG_RC) Log.e(TAG, " error registering RCD");
1897                    return;
1898                }
1899                // add RCD to list of displays
1900                mRcDisplays.add(di);
1901
1902                // let all the remote control clients know there is a new display (so the remote
1903                //   control stack traversal order doesn't matter).
1904                Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
1905                while(stackIterator.hasNext()) {
1906                    RemoteControlStackEntry rcse = stackIterator.next();
1907                    if(rcse.mRcClient != null) {
1908                        try {
1909                            rcse.mRcClient.plugRemoteControlDisplay(rcd, w, h);
1910                        } catch (RemoteException e) {
1911                            Log.e(TAG, "Error connecting RCD to client: ", e);
1912                        }
1913                    }
1914                }
1915
1916                // we have a new display, of which all the clients are now aware: have it be updated
1917                checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
1918            }
1919        }
1920    }
1921
1922    /**
1923     * Unregister an IRemoteControlDisplay.
1924     * No effect if the IRemoteControlDisplay hasn't been successfully registered.
1925     * @see android.media.IAudioService#unregisterRemoteControlDisplay(android.media.IRemoteControlDisplay)
1926     * @param rcd the IRemoteControlDisplay to unregister. No effect if null.
1927     */
1928    protected void unregisterRemoteControlDisplay(IRemoteControlDisplay rcd) {
1929        if (DEBUG_RC) Log.d(TAG, "<<< unregisterRemoteControlDisplay("+rcd+")");
1930        synchronized(mRCStack) {
1931            if (rcd == null) {
1932                return;
1933            }
1934
1935            boolean displayWasPluggedIn = false;
1936            final Iterator<DisplayInfoForServer> displayIterator = mRcDisplays.iterator();
1937            while (displayIterator.hasNext() && !displayWasPluggedIn) {
1938                final DisplayInfoForServer di = (DisplayInfoForServer) displayIterator.next();
1939                if (di.mRcDisplay.asBinder().equals(rcd.asBinder())) {
1940                    displayWasPluggedIn = true;
1941                    di.release();
1942                    displayIterator.remove();
1943                }
1944            }
1945
1946            if (displayWasPluggedIn) {
1947                // disconnect this remote control display from all the clients, so the remote
1948                //   control stack traversal order doesn't matter
1949                final Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
1950                while(stackIterator.hasNext()) {
1951                    final RemoteControlStackEntry rcse = stackIterator.next();
1952                    if(rcse.mRcClient != null) {
1953                        try {
1954                            rcse.mRcClient.unplugRemoteControlDisplay(rcd);
1955                        } catch (RemoteException e) {
1956                            Log.e(TAG, "Error disconnecting remote control display to client: ", e);
1957                        }
1958                    }
1959                }
1960            } else {
1961                if (DEBUG_RC) Log.w(TAG, "  trying to unregister unregistered RCD");
1962            }
1963        }
1964    }
1965
1966    /**
1967     * Update the size of the artwork used by an IRemoteControlDisplay.
1968     * @see android.media.IAudioService#remoteControlDisplayUsesBitmapSize(android.media.IRemoteControlDisplay, int, int)
1969     * @param rcd the IRemoteControlDisplay with the new artwork size requirement
1970     * @param w the maximum width of the expected bitmap. Negative or zero values indicate this
1971     *   display doesn't need to receive artwork.
1972     * @param h the maximum height of the expected bitmap. Negative or zero values indicate this
1973     *   display doesn't need to receive artwork.
1974     */
1975    protected void remoteControlDisplayUsesBitmapSize(IRemoteControlDisplay rcd, int w, int h) {
1976        synchronized(mRCStack) {
1977            final Iterator<DisplayInfoForServer> displayIterator = mRcDisplays.iterator();
1978            boolean artworkSizeUpdate = false;
1979            while (displayIterator.hasNext() && !artworkSizeUpdate) {
1980                final DisplayInfoForServer di = (DisplayInfoForServer) displayIterator.next();
1981                if (di.mRcDisplay.asBinder().equals(rcd.asBinder())) {
1982                    if ((di.mArtworkExpectedWidth != w) || (di.mArtworkExpectedHeight != h)) {
1983                        di.mArtworkExpectedWidth = w;
1984                        di.mArtworkExpectedHeight = h;
1985                        artworkSizeUpdate = true;
1986                    }
1987                }
1988            }
1989            if (artworkSizeUpdate) {
1990                // RCD is currently plugged in and its artwork size has changed, notify all RCCs,
1991                // stack traversal order doesn't matter
1992                final Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
1993                while(stackIterator.hasNext()) {
1994                    final RemoteControlStackEntry rcse = stackIterator.next();
1995                    if(rcse.mRcClient != null) {
1996                        try {
1997                            rcse.mRcClient.setBitmapSizeForDisplay(rcd, w, h);
1998                        } catch (RemoteException e) {
1999                            Log.e(TAG, "Error setting bitmap size for RCD on RCC: ", e);
2000                        }
2001                    }
2002                }
2003            }
2004        }
2005    }
2006
2007    /**
2008     * Controls whether a remote control display needs periodic checks of the RemoteControlClient
2009     * playback position to verify that the estimated position has not drifted from the actual
2010     * position. By default the check is not performed.
2011     * The IRemoteControlDisplay must have been previously registered for this to have any effect.
2012     * @param rcd the IRemoteControlDisplay for which the anti-drift mechanism will be enabled
2013     *     or disabled. Not null.
2014     * @param wantsSync if true, RemoteControlClient instances which expose their playback position
2015     *     to the framework will regularly compare the estimated playback position with the actual
2016     *     position, and will update the IRemoteControlDisplay implementation whenever a drift is
2017     *     detected.
2018     */
2019    protected void remoteControlDisplayWantsPlaybackPositionSync(IRemoteControlDisplay rcd,
2020            boolean wantsSync) {
2021        synchronized(mRCStack) {
2022            boolean rcdRegistered = false;
2023            // store the information about this display
2024            // (display stack traversal order doesn't matter).
2025            final Iterator<DisplayInfoForServer> displayIterator = mRcDisplays.iterator();
2026            while (displayIterator.hasNext()) {
2027                final DisplayInfoForServer di = (DisplayInfoForServer) displayIterator.next();
2028                if (di.mRcDisplay.asBinder().equals(rcd.asBinder())) {
2029                    di.mWantsPositionSync = wantsSync;
2030                    rcdRegistered = true;
2031                    break;
2032                }
2033            }
2034            if (!rcdRegistered) {
2035                return;
2036            }
2037            // notify all current RemoteControlClients
2038            // (stack traversal order doesn't matter as we notify all RCCs)
2039            final Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
2040            while (stackIterator.hasNext()) {
2041                final RemoteControlStackEntry rcse = stackIterator.next();
2042                if (rcse.mRcClient != null) {
2043                    try {
2044                        rcse.mRcClient.setWantsSyncForDisplay(rcd, wantsSync);
2045                    } catch (RemoteException e) {
2046                        Log.e(TAG, "Error setting position sync flag for RCD on RCC: ", e);
2047                    }
2048                }
2049            }
2050        }
2051    }
2052
2053    protected void setRemoteControlClientPlaybackPosition(int generationId, long timeMs) {
2054        // ignore position change requests if invalid generation ID
2055        synchronized(mRCStack) {
2056            synchronized(mCurrentRcLock) {
2057                if (mCurrentRcClientGen != generationId) {
2058                    return;
2059                }
2060            }
2061        }
2062        // discard any unprocessed seek request in the message queue, and replace with latest
2063        sendMsg(mEventHandler, MSG_RCC_SEEK_REQUEST, SENDMSG_REPLACE, generationId /* arg1 */,
2064                0 /* arg2 ignored*/, new Long(timeMs) /* obj */, 0 /* delay */);
2065    }
2066
2067    private void onSetRemoteControlClientPlaybackPosition(int generationId, long timeMs) {
2068        if(DEBUG_RC) Log.d(TAG, "onSetRemoteControlClientPlaybackPosition(genId=" + generationId +
2069                ", timeMs=" + timeMs + ")");
2070        synchronized(mRCStack) {
2071            synchronized(mCurrentRcLock) {
2072                if ((mCurrentRcClient != null) && (mCurrentRcClientGen == generationId)) {
2073                    // tell the current client to seek to the requested location
2074                    try {
2075                        mCurrentRcClient.seekTo(generationId, timeMs);
2076                    } catch (RemoteException e) {
2077                        Log.e(TAG, "Current valid remote client is dead: "+e);
2078                        mCurrentRcClient = null;
2079                    }
2080                }
2081            }
2082        }
2083    }
2084
2085    protected void updateRemoteControlClientMetadata(int genId, int key, Rating value) {
2086        sendMsg(mEventHandler, MSG_RCC_UPDATE_METADATA, SENDMSG_QUEUE,
2087                genId /* arg1 */, key /* arg2 */, value /* obj */, 0 /* delay */);
2088    }
2089
2090    private void onUpdateRemoteControlClientMetadata(int genId, int key, Rating value) {
2091        if(DEBUG_RC) Log.d(TAG, "onUpdateRemoteControlClientMetadata(genId=" + genId +
2092                ", what=" + key + ",rating=" + value + ")");
2093        synchronized(mRCStack) {
2094            synchronized(mCurrentRcLock) {
2095                if ((mCurrentRcClient != null) && (mCurrentRcClientGen == genId)) {
2096                    try {
2097                        switch (key) {
2098                            case MediaMetadataEditor.RATING_KEY_BY_USER:
2099                                mCurrentRcClient.updateMetadata(genId, key, value);
2100                                break;
2101                            default:
2102                                Log.e(TAG, "unhandled metadata key " + key + " update for RCC "
2103                                        + genId);
2104                                break;
2105                        }
2106                    } catch (RemoteException e) {
2107                        Log.e(TAG, "Current valid remote client is dead", e);
2108                        mCurrentRcClient = null;
2109                    }
2110                }
2111            }
2112        }
2113    }
2114
2115    protected void setPlaybackInfoForRcc(int rccId, int what, int value) {
2116        sendMsg(mEventHandler, MSG_RCC_NEW_PLAYBACK_INFO, SENDMSG_QUEUE,
2117                rccId /* arg1 */, what /* arg2 */, Integer.valueOf(value) /* obj */, 0 /* delay */);
2118    }
2119
2120    // handler for MSG_RCC_NEW_PLAYBACK_INFO
2121    private void onNewPlaybackInfoForRcc(int rccId, int key, int value) {
2122        if(DEBUG_RC) Log.d(TAG, "onNewPlaybackInfoForRcc(id=" + rccId +
2123                ", what=" + key + ",val=" + value + ")");
2124        synchronized(mRCStack) {
2125            // iterating from top of stack as playback information changes are more likely
2126            //   on entries at the top of the remote control stack
2127            try {
2128                for (int index = mRCStack.size()-1; index >= 0; index--) {
2129                    final RemoteControlStackEntry rcse = mRCStack.elementAt(index);
2130                    if (rcse.mRccId == rccId) {
2131                        switch (key) {
2132                            case RemoteControlClient.PLAYBACKINFO_PLAYBACK_TYPE:
2133                                rcse.mPlaybackType = value;
2134                                postReevaluateRemote();
2135                                break;
2136                            case RemoteControlClient.PLAYBACKINFO_VOLUME:
2137                                rcse.mPlaybackVolume = value;
2138                                synchronized (mMainRemote) {
2139                                    if (rccId == mMainRemote.mRccId) {
2140                                        mMainRemote.mVolume = value;
2141                                        mVolumeController.postHasNewRemotePlaybackInfo();
2142                                    }
2143                                }
2144                                break;
2145                            case RemoteControlClient.PLAYBACKINFO_VOLUME_MAX:
2146                                rcse.mPlaybackVolumeMax = value;
2147                                synchronized (mMainRemote) {
2148                                    if (rccId == mMainRemote.mRccId) {
2149                                        mMainRemote.mVolumeMax = value;
2150                                        mVolumeController.postHasNewRemotePlaybackInfo();
2151                                    }
2152                                }
2153                                break;
2154                            case RemoteControlClient.PLAYBACKINFO_VOLUME_HANDLING:
2155                                rcse.mPlaybackVolumeHandling = value;
2156                                synchronized (mMainRemote) {
2157                                    if (rccId == mMainRemote.mRccId) {
2158                                        mMainRemote.mVolumeHandling = value;
2159                                        mVolumeController.postHasNewRemotePlaybackInfo();
2160                                    }
2161                                }
2162                                break;
2163                            case RemoteControlClient.PLAYBACKINFO_USES_STREAM:
2164                                rcse.mPlaybackStream = value;
2165                                break;
2166                            default:
2167                                Log.e(TAG, "unhandled key " + key + " for RCC " + rccId);
2168                                break;
2169                        }
2170                        return;
2171                    }
2172                }//for
2173            } catch (ArrayIndexOutOfBoundsException e) {
2174                // not expected to happen, indicates improper concurrent modification
2175                Log.e(TAG, "Wrong index mRCStack on onNewPlaybackInfoForRcc, lock error? ", e);
2176            }
2177        }
2178    }
2179
2180    protected void setPlaybackStateForRcc(int rccId, int state, long timeMs, float speed) {
2181        sendMsg(mEventHandler, MSG_RCC_NEW_PLAYBACK_STATE, SENDMSG_QUEUE,
2182                rccId /* arg1 */, state /* arg2 */,
2183                new RccPlaybackState(state, timeMs, speed) /* obj */, 0 /* delay */);
2184    }
2185
2186    private void onNewPlaybackStateForRcc(int rccId, int state, RccPlaybackState newState) {
2187        if(DEBUG_RC) Log.d(TAG, "onNewPlaybackStateForRcc(id=" + rccId + ", state=" + state
2188                + ", time=" + newState.mPositionMs + ", speed=" + newState.mSpeed + ")");
2189        synchronized(mRCStack) {
2190            // iterating from top of stack as playback information changes are more likely
2191            //   on entries at the top of the remote control stack
2192            try {
2193                for (int index = mRCStack.size()-1; index >= 0; index--) {
2194                    final RemoteControlStackEntry rcse = mRCStack.elementAt(index);
2195                    if (rcse.mRccId == rccId) {
2196                        rcse.mPlaybackState = newState;
2197                        synchronized (mMainRemote) {
2198                            if (rccId == mMainRemote.mRccId) {
2199                                mMainRemoteIsActive = isPlaystateActive(state);
2200                                postReevaluateRemote();
2201                            }
2202                        }
2203                        // an RCC moving to a "playing" state should become the media button
2204                        //   event receiver so it can be controlled, without requiring the
2205                        //   app to re-register its receiver
2206                        if (isPlaystateActive(state)) {
2207                            postPromoteRcc(rccId);
2208                        }
2209                    }
2210                }//for
2211            } catch (ArrayIndexOutOfBoundsException e) {
2212                // not expected to happen, indicates improper concurrent modification
2213                Log.e(TAG, "Wrong index on mRCStack in onNewPlaybackStateForRcc, lock error? ", e);
2214            }
2215        }
2216    }
2217
2218    protected void registerRemoteVolumeObserverForRcc(int rccId, IRemoteVolumeObserver rvo) {
2219        sendMsg(mEventHandler, MSG_RCC_NEW_VOLUME_OBS, SENDMSG_QUEUE,
2220                rccId /* arg1 */, 0, rvo /* obj */, 0 /* delay */);
2221    }
2222
2223    // handler for MSG_RCC_NEW_VOLUME_OBS
2224    private void onRegisterVolumeObserverForRcc(int rccId, IRemoteVolumeObserver rvo) {
2225        synchronized(mRCStack) {
2226            // The stack traversal order doesn't matter because there is only one stack entry
2227            //  with this RCC ID, but the matching ID is more likely at the top of the stack, so
2228            //  start iterating from the top.
2229            try {
2230                for (int index = mRCStack.size()-1; index >= 0; index--) {
2231                    final RemoteControlStackEntry rcse = mRCStack.elementAt(index);
2232                    if (rcse.mRccId == rccId) {
2233                        rcse.mRemoteVolumeObs = rvo;
2234                        break;
2235                    }
2236                }
2237            } catch (ArrayIndexOutOfBoundsException e) {
2238                // not expected to happen, indicates improper concurrent modification
2239                Log.e(TAG, "Wrong index accessing media button stack, lock error? ", e);
2240            }
2241        }
2242    }
2243
2244    /**
2245     * Checks if a remote client is active on the supplied stream type. Update the remote stream
2246     * volume state if found and playing
2247     * @param streamType
2248     * @return false if no remote playing is currently playing
2249     */
2250    protected boolean checkUpdateRemoteStateIfActive(int streamType) {
2251        synchronized(mRCStack) {
2252            // iterating from top of stack as active playback is more likely on entries at the top
2253            try {
2254                for (int index = mRCStack.size()-1; index >= 0; index--) {
2255                    final RemoteControlStackEntry rcse = mRCStack.elementAt(index);
2256                    if ((rcse.mPlaybackType == RemoteControlClient.PLAYBACK_TYPE_REMOTE)
2257                            && isPlaystateActive(rcse.mPlaybackState.mState)
2258                            && (rcse.mPlaybackStream == streamType)) {
2259                        if (DEBUG_RC) Log.d(TAG, "remote playback active on stream " + streamType
2260                                + ", vol =" + rcse.mPlaybackVolume);
2261                        synchronized (mMainRemote) {
2262                            mMainRemote.mRccId = rcse.mRccId;
2263                            mMainRemote.mVolume = rcse.mPlaybackVolume;
2264                            mMainRemote.mVolumeMax = rcse.mPlaybackVolumeMax;
2265                            mMainRemote.mVolumeHandling = rcse.mPlaybackVolumeHandling;
2266                            mMainRemoteIsActive = true;
2267                        }
2268                        return true;
2269                    }
2270                }
2271            } catch (ArrayIndexOutOfBoundsException e) {
2272                // not expected to happen, indicates improper concurrent modification
2273                Log.e(TAG, "Wrong index accessing RC stack, lock error? ", e);
2274            }
2275        }
2276        synchronized (mMainRemote) {
2277            mMainRemoteIsActive = false;
2278        }
2279        return false;
2280    }
2281
2282    /**
2283     * Returns true if the given playback state is considered "active", i.e. it describes a state
2284     * where playback is happening, or about to
2285     * @param playState the playback state to evaluate
2286     * @return true if active, false otherwise (inactive or unknown)
2287     */
2288    private static boolean isPlaystateActive(int playState) {
2289        switch (playState) {
2290            case RemoteControlClient.PLAYSTATE_PLAYING:
2291            case RemoteControlClient.PLAYSTATE_BUFFERING:
2292            case RemoteControlClient.PLAYSTATE_FAST_FORWARDING:
2293            case RemoteControlClient.PLAYSTATE_REWINDING:
2294            case RemoteControlClient.PLAYSTATE_SKIPPING_BACKWARDS:
2295            case RemoteControlClient.PLAYSTATE_SKIPPING_FORWARDS:
2296                return true;
2297            default:
2298                return false;
2299        }
2300    }
2301
2302    protected void adjustRemoteVolume(int streamType, int direction, int flags) {
2303        int rccId = RemoteControlClient.RCSE_ID_UNREGISTERED;
2304        boolean volFixed = false;
2305        synchronized (mMainRemote) {
2306            if (!mMainRemoteIsActive) {
2307                if (DEBUG_VOL) Log.w(TAG, "adjustRemoteVolume didn't find an active client");
2308                return;
2309            }
2310            rccId = mMainRemote.mRccId;
2311            volFixed = (mMainRemote.mVolumeHandling ==
2312                    RemoteControlClient.PLAYBACK_VOLUME_FIXED);
2313        }
2314        // unlike "local" stream volumes, we can't compute the new volume based on the direction,
2315        // we can only notify the remote that volume needs to be updated, and we'll get an async'
2316        // update through setPlaybackInfoForRcc()
2317        if (!volFixed) {
2318            sendVolumeUpdateToRemote(rccId, direction);
2319        }
2320
2321        // fire up the UI
2322        mVolumeController.postRemoteVolumeChanged(streamType, flags);
2323    }
2324
2325    private void sendVolumeUpdateToRemote(int rccId, int direction) {
2326        if (DEBUG_VOL) { Log.d(TAG, "sendVolumeUpdateToRemote(rccId="+rccId+" , dir="+direction); }
2327        if (direction == 0) {
2328            // only handling discrete events
2329            return;
2330        }
2331        IRemoteVolumeObserver rvo = null;
2332        synchronized (mRCStack) {
2333            // The stack traversal order doesn't matter because there is only one stack entry
2334            //  with this RCC ID, but the matching ID is more likely at the top of the stack, so
2335            //  start iterating from the top.
2336            try {
2337                for (int index = mRCStack.size()-1; index >= 0; index--) {
2338                    final RemoteControlStackEntry rcse = mRCStack.elementAt(index);
2339                    //FIXME OPTIMIZE store this info in mMainRemote so we don't have to iterate?
2340                    if (rcse.mRccId == rccId) {
2341                        rvo = rcse.mRemoteVolumeObs;
2342                        break;
2343                    }
2344                }
2345            } catch (ArrayIndexOutOfBoundsException e) {
2346                // not expected to happen, indicates improper concurrent modification
2347                Log.e(TAG, "Wrong index accessing media button stack, lock error? ", e);
2348            }
2349        }
2350        if (rvo != null) {
2351            try {
2352                rvo.dispatchRemoteVolumeUpdate(direction, -1);
2353            } catch (RemoteException e) {
2354                Log.e(TAG, "Error dispatching relative volume update", e);
2355            }
2356        }
2357    }
2358
2359    protected int getRemoteStreamMaxVolume() {
2360        synchronized (mMainRemote) {
2361            if (mMainRemote.mRccId == RemoteControlClient.RCSE_ID_UNREGISTERED) {
2362                return 0;
2363            }
2364            return mMainRemote.mVolumeMax;
2365        }
2366    }
2367
2368    protected int getRemoteStreamVolume() {
2369        synchronized (mMainRemote) {
2370            if (mMainRemote.mRccId == RemoteControlClient.RCSE_ID_UNREGISTERED) {
2371                return 0;
2372            }
2373            return mMainRemote.mVolume;
2374        }
2375    }
2376
2377    protected void setRemoteStreamVolume(int vol) {
2378        if (DEBUG_VOL) { Log.d(TAG, "setRemoteStreamVolume(vol="+vol+")"); }
2379        int rccId = RemoteControlClient.RCSE_ID_UNREGISTERED;
2380        synchronized (mMainRemote) {
2381            if (mMainRemote.mRccId == RemoteControlClient.RCSE_ID_UNREGISTERED) {
2382                return;
2383            }
2384            rccId = mMainRemote.mRccId;
2385        }
2386        IRemoteVolumeObserver rvo = null;
2387        synchronized (mRCStack) {
2388            // The stack traversal order doesn't matter because there is only one stack entry
2389            //  with this RCC ID, but the matching ID is more likely at the top of the stack, so
2390            //  start iterating from the top.
2391            try {
2392                for (int index = mRCStack.size()-1; index >= 0; index--) {
2393                    final RemoteControlStackEntry rcse = mRCStack.elementAt(index);
2394                    //FIXME OPTIMIZE store this info in mMainRemote so we don't have to iterate?
2395                    if (rcse.mRccId == rccId) {
2396                        rvo = rcse.mRemoteVolumeObs;
2397                        break;
2398                    }
2399                }
2400            } catch (ArrayIndexOutOfBoundsException e) {
2401                // not expected to happen, indicates improper concurrent modification
2402                Log.e(TAG, "Wrong index accessing media button stack, lock error? ", e);
2403            }
2404        }
2405        if (rvo != null) {
2406            try {
2407                rvo.dispatchRemoteVolumeUpdate(0, vol);
2408            } catch (RemoteException e) {
2409                Log.e(TAG, "Error dispatching absolute volume update", e);
2410            }
2411        }
2412    }
2413
2414    /**
2415     * Call to make AudioService reevaluate whether it's in a mode where remote players should
2416     * have their volume controlled. In this implementation this is only to reset whether
2417     * VolumePanel should display remote volumes
2418     */
2419    private void postReevaluateRemote() {
2420        sendMsg(mEventHandler, MSG_REEVALUATE_REMOTE, SENDMSG_QUEUE, 0, 0, null, 0);
2421    }
2422
2423    private void onReevaluateRemote() {
2424        if (DEBUG_VOL) { Log.w(TAG, "onReevaluateRemote()"); }
2425        // is there a registered RemoteControlClient that is handling remote playback
2426        boolean hasRemotePlayback = false;
2427        synchronized (mRCStack) {
2428            // iteration stops when PLAYBACK_TYPE_REMOTE is found, so remote control stack
2429            //   traversal order doesn't matter
2430            Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
2431            while(stackIterator.hasNext()) {
2432                RemoteControlStackEntry rcse = stackIterator.next();
2433                if (rcse.mPlaybackType == RemoteControlClient.PLAYBACK_TYPE_REMOTE) {
2434                    hasRemotePlayback = true;
2435                    break;
2436                }
2437            }
2438        }
2439        synchronized (mMainRemote) {
2440            if (mHasRemotePlayback != hasRemotePlayback) {
2441                mHasRemotePlayback = hasRemotePlayback;
2442                mVolumeController.postRemoteSliderVisibility(hasRemotePlayback);
2443            }
2444        }
2445    }
2446
2447}
2448