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