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