ImsPhoneConnection.java revision 74c8509aede6fe748904e75c156049b4f1ba5e28
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 com.android.internal.telephony.imsphone;
18
19import android.content.Context;
20import android.net.Uri;
21import android.os.AsyncResult;
22import android.os.Bundle;
23import android.os.Handler;
24import android.os.Looper;
25import android.os.Message;
26import android.os.PersistableBundle;
27import android.os.PowerManager;
28import android.os.Registrant;
29import android.os.SystemClock;
30import android.telecom.VideoProfile;
31import android.telephony.CarrierConfigManager;
32import android.telephony.DisconnectCause;
33import android.telephony.PhoneNumberUtils;
34import android.telephony.Rlog;
35import android.telephony.ServiceState;
36import android.text.TextUtils;
37
38import com.android.ims.ImsException;
39import com.android.ims.ImsStreamMediaProfile;
40import com.android.ims.internal.ImsVideoCallProviderWrapper;
41import com.android.internal.telephony.CallStateException;
42import com.android.internal.telephony.Connection;
43import com.android.internal.telephony.Phone;
44import com.android.internal.telephony.PhoneConstants;
45import com.android.internal.telephony.UUSInfo;
46
47import com.android.ims.ImsCall;
48import com.android.ims.ImsCallProfile;
49
50import java.util.Objects;
51
52/**
53 * {@hide}
54 */
55public class ImsPhoneConnection extends Connection implements
56        ImsVideoCallProviderWrapper.ImsVideoProviderWrapperCallback {
57
58    private static final String LOG_TAG = "ImsPhoneConnection";
59    private static final boolean DBG = true;
60
61    //***** Instance Variables
62
63    private ImsPhoneCallTracker mOwner;
64    private ImsPhoneCall mParent;
65    private ImsCall mImsCall;
66    private Bundle mExtras = new Bundle();
67
68    private boolean mDisconnected;
69    private boolean mDisconnecting = false;
70
71    /*
72    int mIndex;          // index in ImsPhoneCallTracker.connections[], -1 if unassigned
73                        // The GSM index is 1 + this
74    */
75
76    /*
77     * These time/timespan values are based on System.currentTimeMillis(),
78     * i.e., "wall clock" time.
79     */
80    private long mDisconnectTime;
81
82    private UUSInfo mUusInfo;
83    private Handler mHandler;
84
85    private PowerManager.WakeLock mPartialWakeLock;
86
87    // The cached connect time of the connection when it turns into a conference.
88    private long mConferenceConnectTime = 0;
89
90    // The cached delay to be used between DTMF tones fetched from carrier config.
91    private int mDtmfToneDelay = 0;
92
93    private boolean mIsEmergency = false;
94
95    /**
96     * Used to indicate that video state changes detected by
97     * {@link #updateMediaCapabilities(ImsCall)} should be ignored.  When a video state change from
98     * unpaused to paused occurs, we set this flag and then update the existing video state when
99     * new {@link #onReceiveSessionModifyResponse(int, VideoProfile, VideoProfile)} callbacks come
100     * in.  When the video un-pauses we continue receiving the video state updates.
101     */
102    private boolean mShouldIgnoreVideoStateChanges = false;
103
104    /**
105     * Used to indicate whether the wifi state is based on
106     * {@link com.android.ims.ImsConnectionStateListener#
107     *      onFeatureCapabilityChanged(int, int[], int[])} callbacks, or values received via the
108     * {@link ImsCallProfile#EXTRA_CALL_RAT_TYPE} extra.  Util we receive a value via the extras,
109     * we will use the wifi state based on the {@code onFeatureCapabilityChanged}.  Once a value
110     * is received via the extras, we will prefer those values going forward.
111     */
112    private boolean mIsWifiStateFromExtras = false;
113
114    //***** Event Constants
115    private static final int EVENT_DTMF_DONE = 1;
116    private static final int EVENT_PAUSE_DONE = 2;
117    private static final int EVENT_NEXT_POST_DIAL = 3;
118    private static final int EVENT_WAKE_LOCK_TIMEOUT = 4;
119    private static final int EVENT_DTMF_DELAY_DONE = 5;
120
121    //***** Constants
122    private static final int PAUSE_DELAY_MILLIS = 3 * 1000;
123    private static final int WAKE_LOCK_TIMEOUT_MILLIS = 60*1000;
124
125    //***** Inner Classes
126
127    class MyHandler extends Handler {
128        MyHandler(Looper l) {super(l);}
129
130        @Override
131        public void
132        handleMessage(Message msg) {
133
134            switch (msg.what) {
135                case EVENT_NEXT_POST_DIAL:
136                case EVENT_DTMF_DELAY_DONE:
137                case EVENT_PAUSE_DONE:
138                    processNextPostDialChar();
139                    break;
140                case EVENT_WAKE_LOCK_TIMEOUT:
141                    releaseWakeLock();
142                    break;
143                case EVENT_DTMF_DONE:
144                    // We may need to add a delay specified by carrier between DTMF tones that are
145                    // sent out.
146                    mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_DTMF_DELAY_DONE),
147                            mDtmfToneDelay);
148                    break;
149            }
150        }
151    }
152
153    //***** Constructors
154
155    /** This is probably an MT call */
156    public ImsPhoneConnection(Phone phone, ImsCall imsCall, ImsPhoneCallTracker ct,
157           ImsPhoneCall parent, boolean isUnknown) {
158        super(PhoneConstants.PHONE_TYPE_IMS);
159        createWakeLock(phone.getContext());
160        acquireWakeLock();
161
162        mOwner = ct;
163        mHandler = new MyHandler(mOwner.getLooper());
164        mImsCall = imsCall;
165
166        if ((imsCall != null) && (imsCall.getCallProfile() != null)) {
167            mAddress = imsCall.getCallProfile().getCallExtra(ImsCallProfile.EXTRA_OI);
168            mCnapName = imsCall.getCallProfile().getCallExtra(ImsCallProfile.EXTRA_CNA);
169            mNumberPresentation = ImsCallProfile.OIRToPresentation(
170                    imsCall.getCallProfile().getCallExtraInt(ImsCallProfile.EXTRA_OIR));
171            mCnapNamePresentation = ImsCallProfile.OIRToPresentation(
172                    imsCall.getCallProfile().getCallExtraInt(ImsCallProfile.EXTRA_CNAP));
173            updateMediaCapabilities(imsCall);
174        } else {
175            mNumberPresentation = PhoneConstants.PRESENTATION_UNKNOWN;
176            mCnapNamePresentation = PhoneConstants.PRESENTATION_UNKNOWN;
177        }
178
179        mIsIncoming = !isUnknown;
180        mCreateTime = System.currentTimeMillis();
181        mUusInfo = null;
182
183        updateWifiState();
184
185        // Ensure any extras set on the ImsCallProfile at the start of the call are cached locally
186        // in the ImsPhoneConnection.  This isn't going to inform any listeners (since the original
187        // connection is not likely to be associated with a TelephonyConnection yet).
188        updateExtras(imsCall);
189
190        mParent = parent;
191        mParent.attach(this,
192                (mIsIncoming? ImsPhoneCall.State.INCOMING: ImsPhoneCall.State.DIALING));
193
194        fetchDtmfToneDelay(phone);
195
196        if (phone.getContext().getResources().getBoolean(
197                com.android.internal.R.bool.config_use_voip_mode_for_ims)) {
198            setAudioModeIsVoip(true);
199        }
200    }
201
202    /** This is an MO call, created when dialing */
203    public ImsPhoneConnection(Phone phone, String dialString, ImsPhoneCallTracker ct,
204            ImsPhoneCall parent, boolean isEmergency) {
205        super(PhoneConstants.PHONE_TYPE_IMS);
206        createWakeLock(phone.getContext());
207        acquireWakeLock();
208
209        mOwner = ct;
210        mHandler = new MyHandler(mOwner.getLooper());
211
212        mDialString = dialString;
213
214        mAddress = PhoneNumberUtils.extractNetworkPortionAlt(dialString);
215        mPostDialString = PhoneNumberUtils.extractPostDialPortion(dialString);
216
217        //mIndex = -1;
218
219        mIsIncoming = false;
220        mCnapName = null;
221        mCnapNamePresentation = PhoneConstants.PRESENTATION_ALLOWED;
222        mNumberPresentation = PhoneConstants.PRESENTATION_ALLOWED;
223        mCreateTime = System.currentTimeMillis();
224
225        mParent = parent;
226        parent.attachFake(this, ImsPhoneCall.State.DIALING);
227
228        mIsEmergency = isEmergency;
229
230        fetchDtmfToneDelay(phone);
231
232        if (phone.getContext().getResources().getBoolean(
233                com.android.internal.R.bool.config_use_voip_mode_for_ims)) {
234            setAudioModeIsVoip(true);
235        }
236    }
237
238    public void dispose() {
239    }
240
241    static boolean
242    equalsHandlesNulls (Object a, Object b) {
243        return (a == null) ? (b == null) : a.equals (b);
244    }
245
246    static boolean
247    equalsBaseDialString (String a, String b) {
248        return (a == null) ? (b == null) : (b != null && a.startsWith (b));
249    }
250
251    private static int applyLocalCallCapabilities(ImsCallProfile localProfile, int capabilities) {
252        Rlog.w(LOG_TAG, "applyLocalCallCapabilities - localProfile = "+localProfile);
253        capabilities = removeCapability(capabilities,
254                Connection.Capability.SUPPORTS_VT_LOCAL_BIDIRECTIONAL);
255
256        switch (localProfile.mCallType) {
257            case ImsCallProfile.CALL_TYPE_VT:
258                // Fall-through
259            case ImsCallProfile.CALL_TYPE_VIDEO_N_VOICE:
260                capabilities = addCapability(capabilities,
261                        Connection.Capability.SUPPORTS_VT_LOCAL_BIDIRECTIONAL);
262                break;
263        }
264        return capabilities;
265    }
266
267    private static int applyRemoteCallCapabilities(ImsCallProfile remoteProfile, int capabilities) {
268        Rlog.w(LOG_TAG, "applyRemoteCallCapabilities - remoteProfile = "+remoteProfile);
269        capabilities = removeCapability(capabilities,
270                Connection.Capability.SUPPORTS_VT_REMOTE_BIDIRECTIONAL);
271
272        switch (remoteProfile.mCallType) {
273            case ImsCallProfile.CALL_TYPE_VT:
274                // fall-through
275            case ImsCallProfile.CALL_TYPE_VIDEO_N_VOICE:
276                capabilities = addCapability(capabilities,
277                        Connection.Capability.SUPPORTS_VT_REMOTE_BIDIRECTIONAL);
278                break;
279        }
280        return capabilities;
281    }
282
283    @Override
284    public String getOrigDialString(){
285        return mDialString;
286    }
287
288    @Override
289    public ImsPhoneCall getCall() {
290        return mParent;
291    }
292
293    @Override
294    public long getDisconnectTime() {
295        return mDisconnectTime;
296    }
297
298    @Override
299    public long getHoldingStartTime() {
300        return mHoldingStartTime;
301    }
302
303    @Override
304    public long getHoldDurationMillis() {
305        if (getState() != ImsPhoneCall.State.HOLDING) {
306            // If not holding, return 0
307            return 0;
308        } else {
309            return SystemClock.elapsedRealtime() - mHoldingStartTime;
310        }
311    }
312
313    public void setDisconnectCause(int cause) {
314        mCause = cause;
315    }
316
317    @Override
318    public String getVendorDisconnectCause() {
319      return null;
320    }
321
322    public ImsPhoneCallTracker getOwner () {
323        return mOwner;
324    }
325
326    @Override
327    public ImsPhoneCall.State getState() {
328        if (mDisconnected) {
329            return ImsPhoneCall.State.DISCONNECTED;
330        } else {
331            return super.getState();
332        }
333    }
334
335    @Override
336    public void hangup() throws CallStateException {
337        if (!mDisconnected) {
338            mOwner.hangup(this);
339        } else {
340            throw new CallStateException ("disconnected");
341        }
342    }
343
344    @Override
345    public void separate() throws CallStateException {
346        throw new CallStateException ("not supported");
347    }
348
349    @Override
350    public void proceedAfterWaitChar() {
351        if (mPostDialState != PostDialState.WAIT) {
352            Rlog.w(LOG_TAG, "ImsPhoneConnection.proceedAfterWaitChar(): Expected "
353                    + "getPostDialState() to be WAIT but was " + mPostDialState);
354            return;
355        }
356
357        setPostDialState(PostDialState.STARTED);
358
359        processNextPostDialChar();
360    }
361
362    @Override
363    public void proceedAfterWildChar(String str) {
364        if (mPostDialState != PostDialState.WILD) {
365            Rlog.w(LOG_TAG, "ImsPhoneConnection.proceedAfterWaitChar(): Expected "
366                    + "getPostDialState() to be WILD but was " + mPostDialState);
367            return;
368        }
369
370        setPostDialState(PostDialState.STARTED);
371
372        // make a new postDialString, with the wild char replacement string
373        // at the beginning, followed by the remaining postDialString.
374
375        StringBuilder buf = new StringBuilder(str);
376        buf.append(mPostDialString.substring(mNextPostDialChar));
377        mPostDialString = buf.toString();
378        mNextPostDialChar = 0;
379        if (Phone.DEBUG_PHONE) {
380            Rlog.d(LOG_TAG, "proceedAfterWildChar: new postDialString is " +
381                    mPostDialString);
382        }
383
384        processNextPostDialChar();
385    }
386
387    @Override
388    public void cancelPostDial() {
389        setPostDialState(PostDialState.CANCELLED);
390    }
391
392    /**
393     * Called when this Connection is being hung up locally (eg, user pressed "end")
394     */
395    void
396    onHangupLocal() {
397        mDisconnecting = true;
398        mCause = DisconnectCause.LOCAL;
399    }
400
401    /**
402     * Return whether or not this connection is DISCONNECTING and waiting for a signal from the
403     * modem to disconnect.
404     */
405    boolean isDisconnecting() {
406        return mDisconnecting;
407    }
408
409    /** Called when the connection has been disconnected */
410    @Override
411    public boolean onDisconnect(int cause) {
412        Rlog.d(LOG_TAG, "onDisconnect: cause=" + cause);
413        if (mCause != DisconnectCause.LOCAL || cause == DisconnectCause.INCOMING_REJECTED) {
414            mCause = cause;
415        }
416        return onDisconnect();
417    }
418
419    public boolean onDisconnect() {
420        boolean changed = false;
421
422        if (!mDisconnected) {
423            //mIndex = -1;
424
425            mDisconnectTime = System.currentTimeMillis();
426            mDuration = SystemClock.elapsedRealtime() - mConnectTimeReal;
427            mDisconnecting = false;
428            mDisconnected = true;
429
430            mOwner.mPhone.notifyDisconnect(this);
431
432            if (mParent != null) {
433                changed = mParent.connectionDisconnected(this);
434            } else {
435                Rlog.d(LOG_TAG, "onDisconnect: no parent");
436            }
437            if (mImsCall != null) mImsCall.close();
438            mImsCall = null;
439        }
440        releaseWakeLock();
441        return changed;
442    }
443
444    /**
445     * An incoming or outgoing call has connected
446     */
447    void
448    onConnectedInOrOut() {
449        mConnectTime = System.currentTimeMillis();
450        mConnectTimeReal = SystemClock.elapsedRealtime();
451        mDuration = 0;
452
453        if (Phone.DEBUG_PHONE) {
454            Rlog.d(LOG_TAG, "onConnectedInOrOut: connectTime=" + mConnectTime);
455        }
456
457        if (!mIsIncoming) {
458            // outgoing calls only
459            processNextPostDialChar();
460        }
461        releaseWakeLock();
462    }
463
464    /*package*/ void
465    onStartedHolding() {
466        mHoldingStartTime = SystemClock.elapsedRealtime();
467    }
468    /**
469     * Performs the appropriate action for a post-dial char, but does not
470     * notify application. returns false if the character is invalid and
471     * should be ignored
472     */
473    private boolean
474    processPostDialChar(char c) {
475        if (PhoneNumberUtils.is12Key(c)) {
476            mOwner.sendDtmf(c, mHandler.obtainMessage(EVENT_DTMF_DONE));
477        } else if (c == PhoneNumberUtils.PAUSE) {
478            // From TS 22.101:
479            // It continues...
480            // Upon the called party answering the UE shall send the DTMF digits
481            // automatically to the network after a delay of 3 seconds( 20 ).
482            // The digits shall be sent according to the procedures and timing
483            // specified in 3GPP TS 24.008 [13]. The first occurrence of the
484            // "DTMF Control Digits Separator" shall be used by the ME to
485            // distinguish between the addressing digits (i.e. the phone number)
486            // and the DTMF digits. Upon subsequent occurrences of the
487            // separator,
488            // the UE shall pause again for 3 seconds ( 20 ) before sending
489            // any further DTMF digits.
490            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_PAUSE_DONE),
491                    PAUSE_DELAY_MILLIS);
492        } else if (c == PhoneNumberUtils.WAIT) {
493            setPostDialState(PostDialState.WAIT);
494        } else if (c == PhoneNumberUtils.WILD) {
495            setPostDialState(PostDialState.WILD);
496        } else {
497            return false;
498        }
499
500        return true;
501    }
502
503    @Override
504    protected void finalize() {
505        releaseWakeLock();
506    }
507
508    private void
509    processNextPostDialChar() {
510        char c = 0;
511        Registrant postDialHandler;
512
513        if (mPostDialState == PostDialState.CANCELLED) {
514            //Rlog.d(LOG_TAG, "##### processNextPostDialChar: postDialState == CANCELLED, bail");
515            return;
516        }
517
518        if (mPostDialString == null || mPostDialString.length() <= mNextPostDialChar) {
519            setPostDialState(PostDialState.COMPLETE);
520
521            // notifyMessage.arg1 is 0 on complete
522            c = 0;
523        } else {
524            boolean isValid;
525
526            setPostDialState(PostDialState.STARTED);
527
528            c = mPostDialString.charAt(mNextPostDialChar++);
529
530            isValid = processPostDialChar(c);
531
532            if (!isValid) {
533                // Will call processNextPostDialChar
534                mHandler.obtainMessage(EVENT_NEXT_POST_DIAL).sendToTarget();
535                // Don't notify application
536                Rlog.e(LOG_TAG, "processNextPostDialChar: c=" + c + " isn't valid!");
537                return;
538            }
539        }
540
541        notifyPostDialListenersNextChar(c);
542
543        // TODO: remove the following code since the handler no longer executes anything.
544        postDialHandler = mOwner.mPhone.getPostDialHandler();
545
546        Message notifyMessage;
547
548        if (postDialHandler != null
549                && (notifyMessage = postDialHandler.messageForRegistrant()) != null) {
550            // The AsyncResult.result is the Connection object
551            PostDialState state = mPostDialState;
552            AsyncResult ar = AsyncResult.forMessage(notifyMessage);
553            ar.result = this;
554            ar.userObj = state;
555
556            // arg1 is the character that was/is being processed
557            notifyMessage.arg1 = c;
558
559            //Rlog.v(LOG_TAG,
560            //      "##### processNextPostDialChar: send msg to postDialHandler, arg1=" + c);
561            notifyMessage.sendToTarget();
562        }
563    }
564
565    /**
566     * Set post dial state and acquire wake lock while switching to "started"
567     * state, the wake lock will be released if state switches out of "started"
568     * state or after WAKE_LOCK_TIMEOUT_MILLIS.
569     * @param s new PostDialState
570     */
571    private void setPostDialState(PostDialState s) {
572        if (mPostDialState != PostDialState.STARTED
573                && s == PostDialState.STARTED) {
574            acquireWakeLock();
575            Message msg = mHandler.obtainMessage(EVENT_WAKE_LOCK_TIMEOUT);
576            mHandler.sendMessageDelayed(msg, WAKE_LOCK_TIMEOUT_MILLIS);
577        } else if (mPostDialState == PostDialState.STARTED
578                && s != PostDialState.STARTED) {
579            mHandler.removeMessages(EVENT_WAKE_LOCK_TIMEOUT);
580            releaseWakeLock();
581        }
582        mPostDialState = s;
583        notifyPostDialListeners();
584    }
585
586    private void
587    createWakeLock(Context context) {
588        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
589        mPartialWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOG_TAG);
590    }
591
592    private void
593    acquireWakeLock() {
594        Rlog.d(LOG_TAG, "acquireWakeLock");
595        mPartialWakeLock.acquire();
596    }
597
598    void
599    releaseWakeLock() {
600        synchronized(mPartialWakeLock) {
601            if (mPartialWakeLock.isHeld()) {
602                Rlog.d(LOG_TAG, "releaseWakeLock");
603                mPartialWakeLock.release();
604            }
605        }
606    }
607
608    private void fetchDtmfToneDelay(Phone phone) {
609        CarrierConfigManager configMgr = (CarrierConfigManager)
610                phone.getContext().getSystemService(Context.CARRIER_CONFIG_SERVICE);
611        PersistableBundle b = configMgr.getConfigForSubId(phone.getSubId());
612        if (b != null) {
613            mDtmfToneDelay = b.getInt(CarrierConfigManager.KEY_IMS_DTMF_TONE_DELAY_INT);
614        }
615    }
616
617    @Override
618    public int getNumberPresentation() {
619        return mNumberPresentation;
620    }
621
622    @Override
623    public UUSInfo getUUSInfo() {
624        return mUusInfo;
625    }
626
627    @Override
628    public Connection getOrigConnection() {
629        return null;
630    }
631
632    @Override
633    public boolean isMultiparty() {
634        return mImsCall != null && mImsCall.isMultiparty();
635    }
636
637    /**
638     * Where {@link #isMultiparty()} is {@code true}, determines if this {@link ImsCall} is the
639     * origin of the conference call (i.e. {@code #isConferenceHost()} is {@code true}), or if this
640     * {@link ImsCall} is a member of a conference hosted on another device.
641     *
642     * @return {@code true} if this call is the origin of the conference call it is a member of,
643     *      {@code false} otherwise.
644     */
645    @Override
646    public boolean isConferenceHost() {
647        if (mImsCall == null) {
648            return false;
649        }
650        return mImsCall.isConferenceHost();
651    }
652
653    @Override
654    public boolean isMemberOfPeerConference() {
655        return !isConferenceHost();
656    }
657
658    public ImsCall getImsCall() {
659        return mImsCall;
660    }
661
662    public void setImsCall(ImsCall imsCall) {
663        mImsCall = imsCall;
664    }
665
666    public void changeParent(ImsPhoneCall parent) {
667        mParent = parent;
668    }
669
670    /**
671     * @return {@code true} if the {@link ImsPhoneConnection} or its media capabilities have been
672     *     changed, and {@code false} otherwise.
673     */
674    public boolean update(ImsCall imsCall, ImsPhoneCall.State state) {
675        if (state == ImsPhoneCall.State.ACTIVE) {
676            // If the state of the call is active, but there is a pending request to the RIL to hold
677            // the call, we will skip this update.  This is really a signalling delay or failure
678            // from the RIL, but we will prevent it from going through as we will end up erroneously
679            // making this call active when really it should be on hold.
680            if (imsCall.isPendingHold()) {
681                Rlog.w(LOG_TAG, "update : state is ACTIVE, but call is pending hold, skipping");
682                return false;
683            }
684
685            if (mParent.getState().isRinging() || mParent.getState().isDialing()) {
686                onConnectedInOrOut();
687            }
688
689            if (mParent.getState().isRinging() || mParent == mOwner.mBackgroundCall) {
690                //mForegroundCall should be IDLE
691                //when accepting WAITING call
692                //before accept WAITING call,
693                //the ACTIVE call should be held ahead
694                mParent.detach(this);
695                mParent = mOwner.mForegroundCall;
696                mParent.attach(this);
697            }
698        } else if (state == ImsPhoneCall.State.HOLDING) {
699            onStartedHolding();
700        }
701
702        boolean updateParent = mParent.update(this, imsCall, state);
703        boolean updateWifiState = updateWifiState();
704        boolean updateAddressDisplay = updateAddressDisplay(imsCall);
705        boolean updateMediaCapabilities = updateMediaCapabilities(imsCall);
706        boolean updateExtras = updateExtras(imsCall);
707
708        return updateParent || updateWifiState || updateAddressDisplay || updateMediaCapabilities
709                || updateExtras;
710    }
711
712    @Override
713    public int getPreciseDisconnectCause() {
714        return 0;
715    }
716
717    /**
718     * Notifies this Connection of a request to disconnect a participant of the conference managed
719     * by the connection.
720     *
721     * @param endpoint the {@link android.net.Uri} of the participant to disconnect.
722     */
723    @Override
724    public void onDisconnectConferenceParticipant(Uri endpoint) {
725        ImsCall imsCall = getImsCall();
726        if (imsCall == null) {
727            return;
728        }
729        try {
730            imsCall.removeParticipants(new String[]{endpoint.toString()});
731        } catch (ImsException e) {
732            // No session in place -- no change
733            Rlog.e(LOG_TAG, "onDisconnectConferenceParticipant: no session in place. "+
734                    "Failed to disconnect endpoint = " + endpoint);
735        }
736    }
737
738    /**
739     * Sets the conference connect time.  Used when an {@code ImsConference} is created to out of
740     * this phone connection.
741     *
742     * @param conferenceConnectTime The conference connect time.
743     */
744    public void setConferenceConnectTime(long conferenceConnectTime) {
745        mConferenceConnectTime = conferenceConnectTime;
746    }
747
748    /**
749     * @return The conference connect time.
750     */
751    public long getConferenceConnectTime() {
752        return mConferenceConnectTime;
753    }
754
755    /**
756     * Check for a change in the address display related fields for the {@link ImsCall}, and
757     * update the {@link ImsPhoneConnection} with this information.
758     *
759     * @param imsCall The call to check for changes in address display fields.
760     * @return Whether the address display fields have been changed.
761     */
762    public boolean updateAddressDisplay(ImsCall imsCall) {
763        if (imsCall == null) {
764            return false;
765        }
766
767        boolean changed = false;
768        ImsCallProfile callProfile = imsCall.getCallProfile();
769        if (callProfile != null) {
770            String address = callProfile.getCallExtra(ImsCallProfile.EXTRA_OI);
771            String name = callProfile.getCallExtra(ImsCallProfile.EXTRA_CNA);
772            int nump = ImsCallProfile.OIRToPresentation(
773                    callProfile.getCallExtraInt(ImsCallProfile.EXTRA_OIR));
774            int namep = ImsCallProfile.OIRToPresentation(
775                    callProfile.getCallExtraInt(ImsCallProfile.EXTRA_CNAP));
776            if (Phone.DEBUG_PHONE) {
777                Rlog.d(LOG_TAG, "address = " + Rlog.pii(LOG_TAG, address) + " name = " + name +
778                        " nump = " + nump + " namep = " + namep);
779            }
780            if(!equalsBaseDialString(mAddress, address)) {
781                mAddress = address;
782                changed = true;
783            }
784            if (TextUtils.isEmpty(name)) {
785                if (!TextUtils.isEmpty(mCnapName)) {
786                    mCnapName = "";
787                    changed = true;
788                }
789            } else if (!name.equals(mCnapName)) {
790                mCnapName = name;
791                changed = true;
792            }
793            if (mNumberPresentation != nump) {
794                mNumberPresentation = nump;
795                changed = true;
796            }
797            if (mCnapNamePresentation != namep) {
798                mCnapNamePresentation = namep;
799                changed = true;
800            }
801        }
802        return changed;
803    }
804
805    /**
806     * Check for a change in the video capabilities and audio quality for the {@link ImsCall}, and
807     * update the {@link ImsPhoneConnection} with this information.
808     *
809     * @param imsCall The call to check for changes in media capabilities.
810     * @return Whether the media capabilities have been changed.
811     */
812    public boolean updateMediaCapabilities(ImsCall imsCall) {
813        if (imsCall == null) {
814            return false;
815        }
816
817        boolean changed = false;
818
819        try {
820            // The actual call profile (negotiated between local and peer).
821            ImsCallProfile negotiatedCallProfile = imsCall.getCallProfile();
822
823            if (negotiatedCallProfile != null) {
824                int oldVideoState = getVideoState();
825                int newVideoState = ImsCallProfile
826                        .getVideoStateFromImsCallProfile(negotiatedCallProfile);
827
828                if (oldVideoState != newVideoState) {
829                    // The video state has changed.  See also code in onReceiveSessionModifyResponse
830                    // below.  When the video enters a paused state, subsequent changes to the video
831                    // state will not be reported by the modem.  In onReceiveSessionModifyResponse
832                    // we will be updating the current video state while paused to include any
833                    // changes the modem reports via the video provider.  When the video enters an
834                    // unpaused state, we will resume passing the video states from the modem as is.
835                    if (VideoProfile.isPaused(oldVideoState) &&
836                            !VideoProfile.isPaused(newVideoState)) {
837                        // Video entered un-paused state; recognize updates from now on; we want to
838                        // ensure that the new un-paused state is propagated to Telecom, so change
839                        // this now.
840                        mShouldIgnoreVideoStateChanges = false;
841                    }
842
843                    if (!mShouldIgnoreVideoStateChanges) {
844                        setVideoState(newVideoState);
845                        changed = true;
846                    } else {
847                        Rlog.d(LOG_TAG, "updateMediaCapabilities - ignoring video state change " +
848                                "due to paused state.");
849                    }
850
851                    if (!VideoProfile.isPaused(oldVideoState) &&
852                            VideoProfile.isPaused(newVideoState)) {
853                        // Video entered pause state; ignore updates until un-paused.  We do this
854                        // after setVideoState is called above to ensure Telecom is notified that
855                        // the device has entered paused state.
856                        mShouldIgnoreVideoStateChanges = true;
857                    }
858                }
859            }
860
861            // Check for a change in the capabilities for the call and update
862            // {@link ImsPhoneConnection} with this information.
863            int capabilities = getConnectionCapabilities();
864
865            // Use carrier config to determine if downgrading directly to audio-only is supported.
866            if (mOwner.isCarrierDowngradeOfVtCallSupported()) {
867                capabilities = addCapability(capabilities,
868                        Connection.Capability.SUPPORTS_DOWNGRADE_TO_VOICE_REMOTE |
869                                Capability.SUPPORTS_DOWNGRADE_TO_VOICE_LOCAL);
870            } else {
871                capabilities = removeCapability(capabilities,
872                        Connection.Capability.SUPPORTS_DOWNGRADE_TO_VOICE_REMOTE |
873                                Capability.SUPPORTS_DOWNGRADE_TO_VOICE_LOCAL);
874            }
875
876            // Get the current local call capabilities which might be voice or video or both.
877            ImsCallProfile localCallProfile = imsCall.getLocalCallProfile();
878            Rlog.v(LOG_TAG, "update localCallProfile=" + localCallProfile);
879            if (localCallProfile != null) {
880                capabilities = applyLocalCallCapabilities(localCallProfile, capabilities);
881            }
882
883            // Get the current remote call capabilities which might be voice or video or both.
884            ImsCallProfile remoteCallProfile = imsCall.getRemoteCallProfile();
885            Rlog.v(LOG_TAG, "update remoteCallProfile=" + remoteCallProfile);
886            if (remoteCallProfile != null) {
887                capabilities = applyRemoteCallCapabilities(remoteCallProfile, capabilities);
888            }
889            if (getConnectionCapabilities() != capabilities) {
890                setConnectionCapabilities(capabilities);
891                changed = true;
892            }
893
894            int newAudioQuality =
895                    getAudioQualityFromCallProfile(localCallProfile, remoteCallProfile);
896            if (getAudioQuality() != newAudioQuality) {
897                setAudioQuality(newAudioQuality);
898                changed = true;
899            }
900        } catch (ImsException e) {
901            // No session in place -- no change
902        }
903
904        return changed;
905    }
906
907    /**
908     * Check for a change in the wifi state of the ImsPhoneCallTracker and update the
909     * {@link ImsPhoneConnection} with this information.
910     *
911     * @return Whether the ImsPhoneCallTracker's usage of wifi has been changed.
912     */
913    public boolean updateWifiState() {
914        // If we've received the wifi state via the ImsCallProfile.EXTRA_CALL_RAT_TYPE extra, we
915        // will no longer use state updates which are based on the onFeatureCapabilityChanged
916        // callback.
917        if (mIsWifiStateFromExtras) {
918            return false;
919        }
920
921        Rlog.d(LOG_TAG, "updateWifiState: " + mOwner.isVowifiEnabled());
922        if (isWifi() != mOwner.isVowifiEnabled()) {
923            setWifi(mOwner.isVowifiEnabled());
924            return true;
925        }
926        return false;
927    }
928
929    /**
930     * Updates the wifi state based on the {@link ImsCallProfile#EXTRA_CALL_RAT_TYPE}.
931     * The call is considered to be a WIFI call if the extra value is
932     * {@link ServiceState#RIL_RADIO_TECHNOLOGY_IWLAN}.
933     *
934     * @param extras The ImsCallProfile extras.
935     */
936    private void updateWifiStateFromExtras(Bundle extras) {
937        if (extras.containsKey(ImsCallProfile.EXTRA_CALL_RAT_TYPE) ||
938                extras.containsKey(ImsCallProfile.EXTRA_CALL_RAT_TYPE_ALT)) {
939
940            // We've received the extra indicating the radio technology, so we will continue to
941            // prefer the radio technology received via this extra going forward.
942            mIsWifiStateFromExtras = true;
943
944            ImsCall call = getImsCall();
945            boolean isWifi = false;
946            if (call != null) {
947                isWifi = call.isWifiCall();
948            }
949
950            // Report any changes
951            if (isWifi() != isWifi) {
952                setWifi(isWifi);
953            }
954        }
955    }
956
957    /**
958     * Check for a change in call extras of {@link ImsCall}, and
959     * update the {@link ImsPhoneConnection} accordingly.
960     *
961     * @param imsCall The call to check for changes in extras.
962     * @return Whether the extras fields have been changed.
963     */
964     boolean updateExtras(ImsCall imsCall) {
965        if (imsCall == null) {
966            return false;
967        }
968
969        final ImsCallProfile callProfile = imsCall.getCallProfile();
970        final Bundle extras = callProfile != null ? callProfile.mCallExtras : null;
971        if (extras == null && DBG) {
972            Rlog.d(LOG_TAG, "Call profile extras are null.");
973        }
974
975        final boolean changed = !areBundlesEqual(extras, mExtras);
976        if (changed) {
977            updateWifiStateFromExtras(extras);
978
979            mExtras.clear();
980            mExtras.putAll(extras);
981            setConnectionExtras(mExtras);
982        }
983        return changed;
984    }
985
986    private static boolean areBundlesEqual(Bundle extras, Bundle newExtras) {
987        if (extras == null || newExtras == null) {
988            return extras == newExtras;
989        }
990
991        if (extras.size() != newExtras.size()) {
992            return false;
993        }
994
995        for(String key : extras.keySet()) {
996            if (key != null) {
997                final Object value = extras.get(key);
998                final Object newValue = newExtras.get(key);
999                if (!Objects.equals(value, newValue)) {
1000                    return false;
1001                }
1002            }
1003        }
1004        return true;
1005    }
1006
1007    /**
1008     * Determines the {@link ImsPhoneConnection} audio quality based on the local and remote
1009     * {@link ImsCallProfile}. Indicate a HD audio call if the local stream profile
1010     * is AMR_WB, EVRC_WB, EVS_WB, EVS_SWB, EVS_FB and
1011     * there is no remote restrict cause.
1012     *
1013     * @param localCallProfile The local call profile.
1014     * @param remoteCallProfile The remote call profile.
1015     * @return The audio quality.
1016     */
1017    private int getAudioQualityFromCallProfile(
1018            ImsCallProfile localCallProfile, ImsCallProfile remoteCallProfile) {
1019        if (localCallProfile == null || remoteCallProfile == null
1020                || localCallProfile.mMediaProfile == null) {
1021            return AUDIO_QUALITY_STANDARD;
1022        }
1023
1024        final boolean isEvsCodecHighDef = (localCallProfile.mMediaProfile.mAudioQuality
1025                        == ImsStreamMediaProfile.AUDIO_QUALITY_EVS_WB
1026                || localCallProfile.mMediaProfile.mAudioQuality
1027                        == ImsStreamMediaProfile.AUDIO_QUALITY_EVS_SWB
1028                || localCallProfile.mMediaProfile.mAudioQuality
1029                        == ImsStreamMediaProfile.AUDIO_QUALITY_EVS_FB);
1030
1031        final boolean isHighDef = (localCallProfile.mMediaProfile.mAudioQuality
1032                        == ImsStreamMediaProfile.AUDIO_QUALITY_AMR_WB
1033                || localCallProfile.mMediaProfile.mAudioQuality
1034                        == ImsStreamMediaProfile.AUDIO_QUALITY_EVRC_WB
1035                || isEvsCodecHighDef)
1036                && remoteCallProfile.mRestrictCause == ImsCallProfile.CALL_RESTRICT_CAUSE_NONE;
1037        return isHighDef ? AUDIO_QUALITY_HIGH_DEFINITION : AUDIO_QUALITY_STANDARD;
1038    }
1039
1040    /**
1041     * Provides a string representation of the {@link ImsPhoneConnection}.  Primarily intended for
1042     * use in log statements.
1043     *
1044     * @return String representation of call.
1045     */
1046    @Override
1047    public String toString() {
1048        StringBuilder sb = new StringBuilder();
1049        sb.append("[ImsPhoneConnection objId: ");
1050        sb.append(System.identityHashCode(this));
1051        sb.append(" telecomCallID: ");
1052        sb.append(getTelecomCallId());
1053        sb.append(" address: ");
1054        sb.append(Rlog.pii(LOG_TAG, getAddress()));
1055        sb.append(" ImsCall: ");
1056        if (mImsCall == null) {
1057            sb.append("null");
1058        } else {
1059            sb.append(mImsCall);
1060        }
1061        sb.append("]");
1062        return sb.toString();
1063    }
1064
1065    /**
1066     * Indicates whether current phone connection is emergency or not
1067     * @return boolean: true if emergency, false otherwise
1068     */
1069    protected boolean isEmergency() {
1070        return mIsEmergency;
1071    }
1072
1073    /**
1074     * Handles notifications from the {@link ImsVideoCallProviderWrapper} of session modification
1075     * responses received.
1076     *
1077     * @param status The status of the original request.
1078     * @param requestProfile The requested video profile.
1079     * @param responseProfile The response upon video profile.
1080     */
1081    @Override
1082    public void onReceiveSessionModifyResponse(int status, VideoProfile requestProfile,
1083            VideoProfile responseProfile) {
1084        if (status == android.telecom.Connection.VideoProvider.SESSION_MODIFY_REQUEST_SUCCESS &&
1085                mShouldIgnoreVideoStateChanges) {
1086            int currentVideoState = getVideoState();
1087            int newVideoState = responseProfile.getVideoState();
1088
1089            // If the current video state is paused, the modem will not send us any changes to
1090            // the TX and RX bits of the video state.  Until the video is un-paused we will
1091            // "fake out" the video state by applying the changes that the modem reports via a
1092            // response.
1093
1094            // First, find out whether there was a change to the TX or RX bits:
1095            int changedBits = currentVideoState ^ newVideoState;
1096            changedBits &= VideoProfile.STATE_BIDIRECTIONAL;
1097            if (changedBits == 0) {
1098                // No applicable change, bail out.
1099                return;
1100            }
1101
1102            // Turn off any existing bits that changed.
1103            currentVideoState &= ~(changedBits & currentVideoState);
1104            // Turn on any new bits that turned on.
1105            currentVideoState |= changedBits & newVideoState;
1106
1107            Rlog.d(LOG_TAG, "onReceiveSessionModifyResponse : received " +
1108                    VideoProfile.videoStateToString(requestProfile.getVideoState()) +
1109                    " / " +
1110                    VideoProfile.videoStateToString(responseProfile.getVideoState()) +
1111                    " while paused ; sending new videoState = " +
1112                    VideoProfile.videoStateToString(currentVideoState));
1113            setVideoState(currentVideoState);
1114        }
1115    }
1116}
1117