ImsPhoneCallTracker.java revision d6adcf507cdd3e10fab019c9848733d006287e83
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.app.PendingIntent;
20import android.content.BroadcastReceiver;
21import android.content.Context;
22import android.content.Intent;
23import android.content.IntentFilter;
24import android.content.SharedPreferences;
25import android.net.ConnectivityManager;
26import android.net.NetworkInfo;
27import android.net.Uri;
28import android.os.AsyncResult;
29import android.os.Bundle;
30import android.os.Handler;
31import android.os.Message;
32import android.os.PersistableBundle;
33import android.os.Registrant;
34import android.os.RegistrantList;
35import android.os.RemoteException;
36import android.os.SystemProperties;
37import android.preference.PreferenceManager;
38import android.provider.Settings;
39import android.telecom.ConferenceParticipant;
40import android.telecom.VideoProfile;
41import android.telephony.CarrierConfigManager;
42import android.telephony.DisconnectCause;
43import android.telephony.PhoneNumberUtils;
44import android.telephony.PreciseDisconnectCause;
45import android.telephony.Rlog;
46import android.telephony.ServiceState;
47import android.telephony.SubscriptionManager;
48import android.telephony.TelephonyManager;
49import android.telephony.ims.ImsServiceProxy;
50import android.telephony.ims.feature.ImsFeature;
51import android.text.TextUtils;
52import android.util.ArrayMap;
53import android.util.Log;
54import android.util.Pair;
55import android.util.SparseIntArray;
56
57import com.android.ims.ImsCall;
58import com.android.ims.ImsCallProfile;
59import com.android.ims.ImsConfig;
60import com.android.ims.ImsConfigListener;
61import com.android.ims.ImsConnectionStateListener;
62import com.android.ims.ImsEcbm;
63import com.android.ims.ImsException;
64import com.android.ims.ImsManager;
65import com.android.ims.ImsMultiEndpoint;
66import com.android.ims.ImsReasonInfo;
67import com.android.ims.ImsServiceClass;
68import com.android.ims.ImsSuppServiceNotification;
69import com.android.ims.ImsUtInterface;
70import com.android.ims.internal.IImsVideoCallProvider;
71import com.android.ims.internal.ImsVideoCallProviderWrapper;
72import com.android.ims.internal.VideoPauseTracker;
73import com.android.internal.annotations.VisibleForTesting;
74import com.android.internal.telephony.Call;
75import com.android.internal.telephony.CallStateException;
76import com.android.internal.telephony.CallTracker;
77import com.android.internal.telephony.CommandException;
78import com.android.internal.telephony.CommandsInterface;
79import com.android.internal.telephony.Connection;
80import com.android.internal.telephony.Phone;
81import com.android.internal.telephony.PhoneConstants;
82import com.android.internal.telephony.TelephonyProperties;
83import com.android.internal.telephony.dataconnection.DataEnabledSettings;
84import com.android.internal.telephony.gsm.SuppServiceNotification;
85import com.android.internal.telephony.metrics.TelephonyMetrics;
86import com.android.internal.telephony.nano.TelephonyProto.ImsConnectionState;
87import com.android.internal.telephony.nano.TelephonyProto.TelephonyCallSession;
88import com.android.internal.telephony.nano.TelephonyProto.TelephonyCallSession.Event.ImsCommand;
89
90import java.io.FileDescriptor;
91import java.io.PrintWriter;
92import java.util.ArrayList;
93import java.util.HashMap;
94import java.util.List;
95import java.util.Map;
96import java.util.regex.Pattern;
97
98/**
99 * {@hide}
100 */
101public class ImsPhoneCallTracker extends CallTracker implements ImsPullCall {
102    static final String LOG_TAG = "ImsPhoneCallTracker";
103    static final String VERBOSE_STATE_TAG = "IPCTState";
104
105    public interface PhoneStateListener {
106        void onPhoneStateChanged(PhoneConstants.State oldState, PhoneConstants.State newState);
107    }
108
109    private static final boolean DBG = true;
110
111    // When true, dumps the state of ImsPhoneCallTracker after changes to foreground and background
112    // calls.  This is helpful for debugging.  It is also possible to enable this at runtime by
113    // setting the IPCTState log tag to VERBOSE.
114    private static final boolean FORCE_VERBOSE_STATE_LOGGING = false; /* stopship if true */
115    private static final boolean VERBOSE_STATE_LOGGING = FORCE_VERBOSE_STATE_LOGGING ||
116            Rlog.isLoggable(VERBOSE_STATE_TAG, Log.VERBOSE);
117
118    //Indices map to ImsConfig.FeatureConstants
119    private boolean[] mImsFeatureEnabled = {false, false, false, false, false, false};
120    private final String[] mImsFeatureStrings = {"VoLTE", "ViLTE", "VoWiFi", "ViWiFi",
121            "UTLTE", "UTWiFi"};
122
123    private TelephonyMetrics mMetrics;
124
125    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
126        @Override
127        public void onReceive(Context context, Intent intent) {
128            if (intent.getAction().equals(ImsManager.ACTION_IMS_INCOMING_CALL)) {
129                if (DBG) log("onReceive : incoming call intent");
130
131                if (mImsManager == null) return;
132
133                if (mServiceId < 0) return;
134
135                try {
136                    // Network initiated USSD will be treated by mImsUssdListener
137                    boolean isUssd = intent.getBooleanExtra(ImsManager.EXTRA_USSD, false);
138                    if (isUssd) {
139                        if (DBG) log("onReceive : USSD");
140                        mUssdSession = mImsManager.takeCall(mServiceId, intent, mImsUssdListener);
141                        if (mUssdSession != null) {
142                            mUssdSession.accept(ImsCallProfile.CALL_TYPE_VOICE);
143                        }
144                        return;
145                    }
146
147                    boolean isUnknown = intent.getBooleanExtra(ImsManager.EXTRA_IS_UNKNOWN_CALL,
148                            false);
149                    if (DBG) {
150                        log("onReceive : isUnknown = " + isUnknown +
151                                " fg = " + mForegroundCall.getState() +
152                                " bg = " + mBackgroundCall.getState());
153                    }
154
155                    // Normal MT/Unknown call
156                    ImsCall imsCall = mImsManager.takeCall(mServiceId, intent, mImsCallListener);
157                    ImsPhoneConnection conn = new ImsPhoneConnection(mPhone, imsCall,
158                            ImsPhoneCallTracker.this,
159                            (isUnknown? mForegroundCall: mRingingCall), isUnknown);
160
161                    // If there is an active call.
162                    if (mForegroundCall.hasConnections()) {
163                        ImsCall activeCall = mForegroundCall.getFirstConnection().getImsCall();
164                        if (activeCall != null && imsCall != null) {
165                            // activeCall could be null if the foreground call is in a disconnected
166                            // state.  If either of the calls is null there is no need to check if
167                            // one will be disconnected on answer.
168                            boolean answeringWillDisconnect =
169                                    shouldDisconnectActiveCallOnAnswer(activeCall, imsCall);
170                            conn.setActiveCallDisconnectedOnAnswer(answeringWillDisconnect);
171                        }
172                    }
173                    conn.setAllowAddCallDuringVideoCall(mAllowAddCallDuringVideoCall);
174                    addConnection(conn);
175
176                    setVideoCallProvider(conn, imsCall);
177
178                    TelephonyMetrics.getInstance().writeOnImsCallReceive(mPhone.getPhoneId(),
179                            imsCall.getSession());
180
181                    if (isUnknown) {
182                        mPhone.notifyUnknownConnection(conn);
183                    } else {
184                        if ((mForegroundCall.getState() != ImsPhoneCall.State.IDLE) ||
185                                (mBackgroundCall.getState() != ImsPhoneCall.State.IDLE)) {
186                            conn.update(imsCall, ImsPhoneCall.State.WAITING);
187                        }
188
189                        mPhone.notifyNewRingingConnection(conn);
190                        mPhone.notifyIncomingRing();
191                    }
192
193                    updatePhoneState();
194                    mPhone.notifyPreciseCallStateChanged();
195                } catch (ImsException e) {
196                    loge("onReceive : exception " + e);
197                } catch (RemoteException e) {
198                }
199            } else if (intent.getAction().equals(
200                    CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED)) {
201                int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY,
202                        SubscriptionManager.INVALID_SUBSCRIPTION_ID);
203                if (subId == mPhone.getSubId()) {
204                    cacheCarrierConfiguration(subId);
205                    log("onReceive : Updating mAllowEmergencyVideoCalls = " +
206                            mAllowEmergencyVideoCalls);
207                }
208            }
209        }
210    };
211
212    //***** Constants
213
214    static final int MAX_CONNECTIONS = 7;
215    static final int MAX_CONNECTIONS_PER_CALL = 5;
216
217    private static final int EVENT_HANGUP_PENDINGMO = 18;
218    private static final int EVENT_RESUME_BACKGROUND = 19;
219    private static final int EVENT_DIAL_PENDINGMO = 20;
220    private static final int EVENT_EXIT_ECBM_BEFORE_PENDINGMO = 21;
221    private static final int EVENT_VT_DATA_USAGE_UPDATE = 22;
222    private static final int EVENT_DATA_ENABLED_CHANGED = 23;
223    private static final int EVENT_GET_IMS_SERVICE = 24;
224    private static final int EVENT_CHECK_FOR_WIFI_HANDOVER = 25;
225
226    private static final int TIMEOUT_HANGUP_PENDINGMO = 500;
227
228    // Initial condition for ims connection retry.
229    private static final int IMS_RETRY_STARTING_TIMEOUT_MS = 500; // ms
230    // Ceiling bitshift amount for service query timeout, calculated as:
231    // 2^mImsServiceRetryCount * IMS_RETRY_STARTING_TIMEOUT_MS, where
232    // mImsServiceRetryCount ∊ [0, CEILING_SERVICE_RETRY_COUNT].
233    private static final int CEILING_SERVICE_RETRY_COUNT = 6;
234
235    private static final int HANDOVER_TO_WIFI_TIMEOUT_MS = 60000; // ms
236
237    //***** Instance Variables
238    private ArrayList<ImsPhoneConnection> mConnections = new ArrayList<ImsPhoneConnection>();
239    private RegistrantList mVoiceCallEndedRegistrants = new RegistrantList();
240    private RegistrantList mVoiceCallStartedRegistrants = new RegistrantList();
241
242    public ImsPhoneCall mRingingCall = new ImsPhoneCall(this, ImsPhoneCall.CONTEXT_RINGING);
243    public ImsPhoneCall mForegroundCall = new ImsPhoneCall(this,
244            ImsPhoneCall.CONTEXT_FOREGROUND);
245    public ImsPhoneCall mBackgroundCall = new ImsPhoneCall(this,
246            ImsPhoneCall.CONTEXT_BACKGROUND);
247    public ImsPhoneCall mHandoverCall = new ImsPhoneCall(this, ImsPhoneCall.CONTEXT_HANDOVER);
248
249    // Hold aggregated video call data usage for each video call since boot.
250    // The ImsCall's call id is the key of the map.
251    private final HashMap<Integer, Long> mVtDataUsageMap = new HashMap<>();
252    private volatile long mTotalVtDataUsage = 0;
253
254    private ImsPhoneConnection mPendingMO;
255    private int mClirMode = CommandsInterface.CLIR_DEFAULT;
256    private Object mSyncHold = new Object();
257
258    private ImsCall mUssdSession = null;
259    private Message mPendingUssd = null;
260
261    ImsPhone mPhone;
262
263    private boolean mDesiredMute = false;    // false = mute off
264    private boolean mOnHoldToneStarted = false;
265    private int mOnHoldToneId = -1;
266
267    private PhoneConstants.State mState = PhoneConstants.State.IDLE;
268
269    private int mImsServiceRetryCount;
270    private ImsManager mImsManager;
271    private int mServiceId = -1;
272
273    private Call.SrvccState mSrvccState = Call.SrvccState.NONE;
274
275    private boolean mIsInEmergencyCall = false;
276    private boolean mIsDataEnabled = false;
277
278    private int pendingCallClirMode;
279    private int mPendingCallVideoState;
280    private Bundle mPendingIntentExtras;
281    private boolean pendingCallInEcm = false;
282    private boolean mSwitchingFgAndBgCalls = false;
283    private ImsCall mCallExpectedToResume = null;
284    private boolean mAllowEmergencyVideoCalls = false;
285    private boolean mIgnoreDataEnabledChangedForVideoCalls = false;
286
287    /**
288     * Listeners to changes in the phone state.  Intended for use by other interested IMS components
289     * without the need to register a full blown {@link android.telephony.PhoneStateListener}.
290     */
291    private List<PhoneStateListener> mPhoneStateListeners = new ArrayList<>();
292
293    /**
294     * Carrier configuration option which determines if video calls which have been downgraded to an
295     * audio call should be treated as if they are still video calls.
296     */
297    private boolean mTreatDowngradedVideoCallsAsVideoCalls = false;
298
299    /**
300     * Carrier configuration option which determines if an ongoing video call over wifi should be
301     * dropped when an audio call is answered.
302     */
303    private boolean mDropVideoCallWhenAnsweringAudioCall = false;
304
305    /**
306     * Carrier configuration option which determines whether adding a call during a video call
307     * should be allowed.
308     */
309    private boolean mAllowAddCallDuringVideoCall = true;
310
311    /**
312     * Carrier configuration option which determines whether to notify the connection if a handover
313     * to wifi fails.
314     */
315    private boolean mNotifyVtHandoverToWifiFail = false;
316
317    /**
318     * Carrier configuration option which determines whether the carrier supports downgrading a
319     * TX/RX/TX-RX video call directly to an audio-only call.
320     */
321    private boolean mSupportDowngradeVtToAudio = false;
322
323    /**
324     * Stores the mapping of {@code ImsReasonInfo#CODE_*} to {@code PreciseDisconnectCause#*}
325     */
326    private static final SparseIntArray PRECISE_CAUSE_MAP = new SparseIntArray();
327    static {
328        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_ILLEGAL_ARGUMENT,
329                PreciseDisconnectCause.LOCAL_ILLEGAL_ARGUMENT);
330        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_ILLEGAL_STATE,
331                PreciseDisconnectCause.LOCAL_ILLEGAL_STATE);
332        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_INTERNAL_ERROR,
333                PreciseDisconnectCause.LOCAL_INTERNAL_ERROR);
334        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN,
335                PreciseDisconnectCause.LOCAL_IMS_SERVICE_DOWN);
336        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_NO_PENDING_CALL,
337                PreciseDisconnectCause.LOCAL_NO_PENDING_CALL);
338        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_ENDED_BY_CONFERENCE_MERGE,
339                PreciseDisconnectCause.NORMAL);
340        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_POWER_OFF,
341                PreciseDisconnectCause.LOCAL_POWER_OFF);
342        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_LOW_BATTERY,
343                PreciseDisconnectCause.LOCAL_LOW_BATTERY);
344        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_NETWORK_NO_SERVICE,
345                PreciseDisconnectCause.LOCAL_NETWORK_NO_SERVICE);
346        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_NETWORK_NO_LTE_COVERAGE,
347                PreciseDisconnectCause.LOCAL_NETWORK_NO_LTE_COVERAGE);
348        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_NETWORK_ROAMING,
349                PreciseDisconnectCause.LOCAL_NETWORK_ROAMING);
350        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_NETWORK_IP_CHANGED,
351                PreciseDisconnectCause.LOCAL_NETWORK_IP_CHANGED);
352        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_SERVICE_UNAVAILABLE,
353                PreciseDisconnectCause.LOCAL_SERVICE_UNAVAILABLE);
354        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_NOT_REGISTERED,
355                PreciseDisconnectCause.LOCAL_NOT_REGISTERED);
356        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_CALL_EXCEEDED,
357                PreciseDisconnectCause.LOCAL_MAX_CALL_EXCEEDED);
358        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_CALL_DECLINE,
359                PreciseDisconnectCause.LOCAL_CALL_DECLINE);
360        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_CALL_VCC_ON_PROGRESSING,
361                PreciseDisconnectCause.LOCAL_CALL_VCC_ON_PROGRESSING);
362        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_CALL_RESOURCE_RESERVATION_FAILED,
363                PreciseDisconnectCause.LOCAL_CALL_RESOURCE_RESERVATION_FAILED);
364        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_CALL_CS_RETRY_REQUIRED,
365                PreciseDisconnectCause.LOCAL_CALL_CS_RETRY_REQUIRED);
366        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_CALL_VOLTE_RETRY_REQUIRED,
367                PreciseDisconnectCause.LOCAL_CALL_VOLTE_RETRY_REQUIRED);
368        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_CALL_TERMINATED,
369                PreciseDisconnectCause.LOCAL_CALL_TERMINATED);
370        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOCAL_HO_NOT_FEASIBLE,
371                PreciseDisconnectCause.LOCAL_HO_NOT_FEASIBLE);
372        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_TIMEOUT_1XX_WAITING,
373                PreciseDisconnectCause.TIMEOUT_1XX_WAITING);
374        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_TIMEOUT_NO_ANSWER,
375                PreciseDisconnectCause.TIMEOUT_NO_ANSWER);
376        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_TIMEOUT_NO_ANSWER_CALL_UPDATE,
377                PreciseDisconnectCause.TIMEOUT_NO_ANSWER_CALL_UPDATE);
378        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_FDN_BLOCKED,
379                PreciseDisconnectCause.FDN_BLOCKED);
380        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SIP_REDIRECTED,
381                PreciseDisconnectCause.SIP_REDIRECTED);
382        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SIP_BAD_REQUEST,
383                PreciseDisconnectCause.SIP_BAD_REQUEST);
384        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SIP_FORBIDDEN,
385                PreciseDisconnectCause.SIP_FORBIDDEN);
386        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SIP_NOT_FOUND,
387                PreciseDisconnectCause.SIP_NOT_FOUND);
388        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SIP_NOT_SUPPORTED,
389                PreciseDisconnectCause.SIP_NOT_SUPPORTED);
390        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SIP_REQUEST_TIMEOUT,
391                PreciseDisconnectCause.SIP_REQUEST_TIMEOUT);
392        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SIP_TEMPRARILY_UNAVAILABLE,
393                PreciseDisconnectCause.SIP_TEMPRARILY_UNAVAILABLE);
394        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SIP_BAD_ADDRESS,
395                PreciseDisconnectCause.SIP_BAD_ADDRESS);
396        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SIP_BUSY,
397                PreciseDisconnectCause.SIP_BUSY);
398        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SIP_REQUEST_CANCELLED,
399                PreciseDisconnectCause.SIP_REQUEST_CANCELLED);
400        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SIP_NOT_ACCEPTABLE,
401                PreciseDisconnectCause.SIP_NOT_ACCEPTABLE);
402        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SIP_NOT_REACHABLE,
403                PreciseDisconnectCause.SIP_NOT_REACHABLE);
404        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SIP_CLIENT_ERROR,
405                PreciseDisconnectCause.SIP_CLIENT_ERROR);
406        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SIP_SERVER_INTERNAL_ERROR,
407                PreciseDisconnectCause.SIP_SERVER_INTERNAL_ERROR);
408        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SIP_SERVICE_UNAVAILABLE,
409                PreciseDisconnectCause.SIP_SERVICE_UNAVAILABLE);
410        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SIP_SERVER_TIMEOUT,
411                PreciseDisconnectCause.SIP_SERVER_TIMEOUT);
412        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SIP_SERVER_ERROR,
413                PreciseDisconnectCause.SIP_SERVER_ERROR);
414        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SIP_USER_REJECTED,
415                PreciseDisconnectCause.SIP_USER_REJECTED);
416        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SIP_GLOBAL_ERROR,
417                PreciseDisconnectCause.SIP_GLOBAL_ERROR);
418        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_EMERGENCY_TEMP_FAILURE,
419                PreciseDisconnectCause.EMERGENCY_TEMP_FAILURE);
420        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_EMERGENCY_PERM_FAILURE,
421                PreciseDisconnectCause.EMERGENCY_PERM_FAILURE);
422        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_MEDIA_INIT_FAILED,
423                PreciseDisconnectCause.MEDIA_INIT_FAILED);
424        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_MEDIA_NO_DATA,
425                PreciseDisconnectCause.MEDIA_NO_DATA);
426        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_MEDIA_NOT_ACCEPTABLE,
427                PreciseDisconnectCause.MEDIA_NOT_ACCEPTABLE);
428        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_MEDIA_UNSPECIFIED,
429                PreciseDisconnectCause.MEDIA_UNSPECIFIED);
430        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_USER_TERMINATED,
431                PreciseDisconnectCause.USER_TERMINATED);
432        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_USER_NOANSWER,
433                PreciseDisconnectCause.USER_NOANSWER);
434        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_USER_IGNORE,
435                PreciseDisconnectCause.USER_IGNORE);
436        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_USER_DECLINE,
437                PreciseDisconnectCause.USER_DECLINE);
438        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_LOW_BATTERY,
439                PreciseDisconnectCause.LOW_BATTERY);
440        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_BLACKLISTED_CALL_ID,
441                PreciseDisconnectCause.BLACKLISTED_CALL_ID);
442        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_USER_TERMINATED_BY_REMOTE,
443                PreciseDisconnectCause.USER_TERMINATED_BY_REMOTE);
444        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_UT_NOT_SUPPORTED,
445                PreciseDisconnectCause.UT_NOT_SUPPORTED);
446        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_UT_SERVICE_UNAVAILABLE,
447                PreciseDisconnectCause.UT_SERVICE_UNAVAILABLE);
448        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_UT_OPERATION_NOT_ALLOWED,
449                PreciseDisconnectCause.UT_OPERATION_NOT_ALLOWED);
450        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_UT_NETWORK_ERROR,
451                PreciseDisconnectCause.UT_NETWORK_ERROR);
452        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_UT_CB_PASSWORD_MISMATCH,
453                PreciseDisconnectCause.UT_CB_PASSWORD_MISMATCH);
454        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_ECBM_NOT_SUPPORTED,
455                PreciseDisconnectCause.ECBM_NOT_SUPPORTED);
456        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_MULTIENDPOINT_NOT_SUPPORTED,
457                PreciseDisconnectCause.MULTIENDPOINT_NOT_SUPPORTED);
458        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_CALL_DROP_IWLAN_TO_LTE_UNAVAILABLE,
459                PreciseDisconnectCause.CALL_DROP_IWLAN_TO_LTE_UNAVAILABLE);
460        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_ANSWERED_ELSEWHERE,
461                PreciseDisconnectCause.ANSWERED_ELSEWHERE);
462        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_CALL_PULL_OUT_OF_SYNC,
463                PreciseDisconnectCause.CALL_PULL_OUT_OF_SYNC);
464        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_CALL_END_CAUSE_CALL_PULL,
465                PreciseDisconnectCause.CALL_PULLED);
466        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SUPP_SVC_FAILED,
467                PreciseDisconnectCause.SUPP_SVC_FAILED);
468        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SUPP_SVC_CANCELLED,
469                PreciseDisconnectCause.SUPP_SVC_CANCELLED);
470        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_SUPP_SVC_REINVITE_COLLISION,
471                PreciseDisconnectCause.SUPP_SVC_REINVITE_COLLISION);
472        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_IWLAN_DPD_FAILURE,
473                PreciseDisconnectCause.IWLAN_DPD_FAILURE);
474        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_EPDG_TUNNEL_ESTABLISH_FAILURE,
475                PreciseDisconnectCause.EPDG_TUNNEL_ESTABLISH_FAILURE);
476        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_EPDG_TUNNEL_REKEY_FAILURE,
477                PreciseDisconnectCause.EPDG_TUNNEL_REKEY_FAILURE);
478        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_EPDG_TUNNEL_LOST_CONNECTION,
479                PreciseDisconnectCause.EPDG_TUNNEL_LOST_CONNECTION);
480        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_MAXIMUM_NUMBER_OF_CALLS_REACHED,
481                PreciseDisconnectCause.MAXIMUM_NUMBER_OF_CALLS_REACHED);
482        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_REMOTE_CALL_DECLINE,
483                PreciseDisconnectCause.REMOTE_CALL_DECLINE);
484        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_DATA_LIMIT_REACHED,
485                PreciseDisconnectCause.DATA_LIMIT_REACHED);
486        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_DATA_DISABLED,
487                PreciseDisconnectCause.DATA_DISABLED);
488        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_WIFI_LOST,
489                PreciseDisconnectCause.WIFI_LOST);
490        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_RADIO_OFF,
491                PreciseDisconnectCause.RADIO_OFF);
492        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_NO_VALID_SIM,
493                PreciseDisconnectCause.NO_VALID_SIM);
494        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_RADIO_INTERNAL_ERROR,
495                PreciseDisconnectCause.RADIO_INTERNAL_ERROR);
496        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_NETWORK_RESP_TIMEOUT,
497                PreciseDisconnectCause.NETWORK_RESP_TIMEOUT);
498        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_NETWORK_REJECT,
499                PreciseDisconnectCause.NETWORK_REJECT);
500        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_RADIO_ACCESS_FAILURE,
501                PreciseDisconnectCause.RADIO_ACCESS_FAILURE);
502        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_RADIO_LINK_FAILURE,
503                PreciseDisconnectCause.RADIO_LINK_FAILURE);
504        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_RADIO_LINK_LOST,
505                PreciseDisconnectCause.RADIO_LINK_LOST);
506        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_RADIO_UPLINK_FAILURE,
507                PreciseDisconnectCause.RADIO_UPLINK_FAILURE);
508        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_RADIO_SETUP_FAILURE,
509                PreciseDisconnectCause.RADIO_SETUP_FAILURE);
510        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_RADIO_RELEASE_NORMAL,
511                PreciseDisconnectCause.RADIO_RELEASE_NORMAL);
512        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_RADIO_RELEASE_ABNORMAL,
513                PreciseDisconnectCause.RADIO_RELEASE_ABNORMAL);
514        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_ACCESS_CLASS_BLOCKED,
515                PreciseDisconnectCause.ACCESS_CLASS_BLOCKED);
516        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_NETWORK_DETACH,
517                PreciseDisconnectCause.NETWORK_DETACH);
518        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_OEM_CAUSE_1,
519                PreciseDisconnectCause.OEM_CAUSE_1);
520        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_OEM_CAUSE_2,
521                PreciseDisconnectCause.OEM_CAUSE_2);
522        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_OEM_CAUSE_3,
523                PreciseDisconnectCause.OEM_CAUSE_3);
524        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_OEM_CAUSE_4,
525                PreciseDisconnectCause.OEM_CAUSE_4);
526        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_OEM_CAUSE_5,
527                PreciseDisconnectCause.OEM_CAUSE_5);
528        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_OEM_CAUSE_6,
529                PreciseDisconnectCause.OEM_CAUSE_6);
530        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_OEM_CAUSE_7,
531                PreciseDisconnectCause.OEM_CAUSE_7);
532        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_OEM_CAUSE_8,
533                PreciseDisconnectCause.OEM_CAUSE_8);
534        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_OEM_CAUSE_9,
535                PreciseDisconnectCause.OEM_CAUSE_9);
536        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_OEM_CAUSE_10,
537                PreciseDisconnectCause.OEM_CAUSE_10);
538        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_OEM_CAUSE_11,
539                PreciseDisconnectCause.OEM_CAUSE_11);
540        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_OEM_CAUSE_12,
541                PreciseDisconnectCause.OEM_CAUSE_12);
542        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_OEM_CAUSE_13,
543                PreciseDisconnectCause.OEM_CAUSE_13);
544        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_OEM_CAUSE_14,
545                PreciseDisconnectCause.OEM_CAUSE_14);
546        PRECISE_CAUSE_MAP.append(ImsReasonInfo.CODE_OEM_CAUSE_15,
547                PreciseDisconnectCause.OEM_CAUSE_15);
548    }
549
550    /**
551     * Carrier configuration option which determines whether the carrier wants to inform the user
552     * when a video call is handed over from WIFI to LTE.
553     * See {@link CarrierConfigManager#KEY_NOTIFY_HANDOVER_VIDEO_FROM_WIFI_TO_LTE_BOOL} for more
554     * information.
555     */
556    private boolean mNotifyHandoverVideoFromWifiToLTE = false;
557
558    /**
559     * Carrier configuration option which determines whether the carrier supports the
560     * {@link VideoProfile#STATE_PAUSED} signalling.
561     * See {@link CarrierConfigManager#KEY_SUPPORT_PAUSE_IMS_VIDEO_CALLS_BOOL} for more information.
562     */
563    private boolean mSupportPauseVideo = false;
564
565    /**
566     * Carrier configuration option which defines a mapping from pairs of
567     * {@link ImsReasonInfo#getCode()} and {@link ImsReasonInfo#getExtraMessage()} values to a new
568     * {@code ImsReasonInfo#CODE_*} value.
569     *
570     * See {@link CarrierConfigManager#KEY_IMS_REASONINFO_MAPPING_STRING_ARRAY}.
571     */
572    private Map<Pair<Integer, String>, Integer> mImsReasonCodeMap = new ArrayMap<>();
573
574
575    /**
576     * TODO: Remove this code; it is a workaround.
577     * When {@code true}, forces {@link ImsManager#updateImsServiceConfig(Context, int, boolean)} to
578     * be called when an ongoing video call is disconnected.  In some cases, where video pause is
579     * supported by the carrier, when {@link #onDataEnabledChanged(boolean, int)} reports that data
580     * has been disabled we will pause the video rather than disconnecting the call.  When this
581     * happens we need to prevent the IMS service config from being updated, as this will cause VT
582     * to be disabled mid-call, resulting in an inability to un-pause the video.
583     */
584    private boolean mShouldUpdateImsConfigOnDisconnect = false;
585
586    // Callback fires when ImsManager MMTel Feature changes state
587    private ImsServiceProxy.INotifyStatusChanged mNotifyStatusChangedCallback = () -> {
588        try {
589            int status = mImsManager.getImsServiceStatus();
590            log("Status Changed: " + status);
591            switch(status) {
592                case ImsFeature.STATE_READY: {
593                    startListeningForCalls();
594                    break;
595                }
596                case ImsFeature.STATE_INITIALIZING:
597                    // fall through
598                case ImsFeature.STATE_NOT_AVAILABLE: {
599                    stopListeningForCalls();
600                    break;
601                }
602                default: {
603                    Log.w(LOG_TAG, "Unexpected State!");
604                }
605            }
606        } catch (ImsException e) {
607            // Could not get the ImsService, retry!
608            retryGetImsService();
609        }
610    };
611
612    @VisibleForTesting
613    public interface IRetryTimeout {
614        int get();
615    }
616
617    /**
618     * Default implementation of interface that calculates the ImsService retry timeout.
619     * Override-able for testing.
620     */
621    @VisibleForTesting
622    public IRetryTimeout mRetryTimeout = () -> {
623        int timeout = (1 << mImsServiceRetryCount) * IMS_RETRY_STARTING_TIMEOUT_MS;
624        if (mImsServiceRetryCount <= CEILING_SERVICE_RETRY_COUNT) {
625            mImsServiceRetryCount++;
626        }
627        return timeout;
628    };
629
630    //***** Events
631
632
633    //***** Constructors
634
635    public ImsPhoneCallTracker(ImsPhone phone) {
636        this.mPhone = phone;
637
638        mMetrics = TelephonyMetrics.getInstance();
639
640        IntentFilter intentfilter = new IntentFilter();
641        intentfilter.addAction(ImsManager.ACTION_IMS_INCOMING_CALL);
642        intentfilter.addAction(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
643        mPhone.getContext().registerReceiver(mReceiver, intentfilter);
644        cacheCarrierConfiguration(mPhone.getSubId());
645
646        mPhone.getDefaultPhone().registerForDataEnabledChanged(
647                this, EVENT_DATA_ENABLED_CHANGED, null);
648
649        mImsServiceRetryCount = 0;
650        // Send a message to connect to the Ims Service and open a connection through
651        // getImsService().
652        sendEmptyMessage(EVENT_GET_IMS_SERVICE);
653    }
654
655    private PendingIntent createIncomingCallPendingIntent() {
656        Intent intent = new Intent(ImsManager.ACTION_IMS_INCOMING_CALL);
657        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
658        return PendingIntent.getBroadcast(mPhone.getContext(), 0, intent,
659                PendingIntent.FLAG_UPDATE_CURRENT);
660    }
661
662    private void getImsService() throws ImsException {
663        if (DBG) log("getImsService");
664        mImsManager = ImsManager.getInstance(mPhone.getContext(), mPhone.getPhoneId());
665        // Adding to set, will be safe adding multiple times. If the ImsService is not active yet,
666        // this method will throw an ImsException.
667        mImsManager.addNotifyStatusChangedCallbackIfAvailable(mNotifyStatusChangedCallback);
668        // Wait for ImsService.STATE_READY to start listening for calls.
669        // Call the callback right away for compatibility with older devices that do not use states.
670        mNotifyStatusChangedCallback.notifyStatusChanged();
671    }
672
673    private void startListeningForCalls() throws ImsException {
674        mImsServiceRetryCount = 0;
675        mServiceId = mImsManager.open(ImsServiceClass.MMTEL,
676                createIncomingCallPendingIntent(),
677                mImsConnectionStateListener);
678
679        mImsManager.setImsConfigListener(mImsConfigListener);
680
681        // Get the ECBM interface and set IMSPhone's listener object for notifications
682        getEcbmInterface().setEcbmStateListener(mPhone.getImsEcbmStateListener());
683        if (mPhone.isInEcm()) {
684            // Call exit ECBM which will invoke onECBMExited
685            mPhone.exitEmergencyCallbackMode();
686        }
687        int mPreferredTtyMode = Settings.Secure.getInt(
688                mPhone.getContext().getContentResolver(),
689                Settings.Secure.PREFERRED_TTY_MODE,
690                Phone.TTY_MODE_OFF);
691        mImsManager.setUiTTYMode(mPhone.getContext(), mPreferredTtyMode, null);
692
693        ImsMultiEndpoint multiEndpoint = getMultiEndpointInterface();
694        if (multiEndpoint != null) {
695            multiEndpoint.setExternalCallStateListener(
696                    mPhone.getExternalCallTracker().getExternalCallStateListener());
697        }
698    }
699
700    private void stopListeningForCalls() {
701        try {
702            // Only close on valid session.
703            if (mImsManager != null && mServiceId > 0) {
704                mImsManager.close(mServiceId);
705                mServiceId = -1;
706            }
707        } catch (ImsException e) {
708            // If the binder is unavailable, then the ImsService doesn't need to close.
709        }
710    }
711
712    public void dispose() {
713        if (DBG) log("dispose");
714        mRingingCall.dispose();
715        mBackgroundCall.dispose();
716        mForegroundCall.dispose();
717        mHandoverCall.dispose();
718
719        clearDisconnected();
720        mPhone.getContext().unregisterReceiver(mReceiver);
721        mPhone.getDefaultPhone().unregisterForDataEnabledChanged(this);
722        removeMessages(EVENT_GET_IMS_SERVICE);
723    }
724
725    @Override
726    protected void finalize() {
727        log("ImsPhoneCallTracker finalized");
728    }
729
730    //***** Instance Methods
731
732    //***** Public Methods
733    @Override
734    public void registerForVoiceCallStarted(Handler h, int what, Object obj) {
735        Registrant r = new Registrant(h, what, obj);
736        mVoiceCallStartedRegistrants.add(r);
737    }
738
739    @Override
740    public void unregisterForVoiceCallStarted(Handler h) {
741        mVoiceCallStartedRegistrants.remove(h);
742    }
743
744    @Override
745    public void registerForVoiceCallEnded(Handler h, int what, Object obj) {
746        Registrant r = new Registrant(h, what, obj);
747        mVoiceCallEndedRegistrants.add(r);
748    }
749
750    @Override
751    public void unregisterForVoiceCallEnded(Handler h) {
752        mVoiceCallEndedRegistrants.remove(h);
753    }
754
755    public Connection dial(String dialString, int videoState, Bundle intentExtras) throws
756            CallStateException {
757        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mPhone.getContext());
758        int oirMode = sp.getInt(Phone.CLIR_KEY, CommandsInterface.CLIR_DEFAULT);
759        return dial(dialString, oirMode, videoState, intentExtras);
760    }
761
762    /**
763     * oirMode is one of the CLIR_ constants
764     */
765    synchronized Connection
766    dial(String dialString, int clirMode, int videoState, Bundle intentExtras)
767            throws CallStateException {
768        boolean isPhoneInEcmMode = isPhoneInEcbMode();
769        boolean isEmergencyNumber = PhoneNumberUtils.isEmergencyNumber(dialString);
770
771        if (DBG) log("dial clirMode=" + clirMode);
772
773        // note that this triggers call state changed notif
774        clearDisconnected();
775
776        if (mImsManager == null) {
777            throw new CallStateException("service not available");
778        }
779
780        if (!canDial()) {
781            throw new CallStateException("cannot dial in current state");
782        }
783
784        if (isPhoneInEcmMode && isEmergencyNumber) {
785            handleEcmTimer(ImsPhone.CANCEL_ECM_TIMER);
786        }
787
788        // If the call is to an emergency number and the carrier does not support video emergency
789        // calls, dial as an audio-only call.
790        if (isEmergencyNumber && VideoProfile.isVideo(videoState) &&
791                !mAllowEmergencyVideoCalls) {
792            loge("dial: carrier does not support video emergency calls; downgrade to audio-only");
793            videoState = VideoProfile.STATE_AUDIO_ONLY;
794        }
795
796        boolean holdBeforeDial = false;
797
798        // The new call must be assigned to the foreground call.
799        // That call must be idle, so place anything that's
800        // there on hold
801        if (mForegroundCall.getState() == ImsPhoneCall.State.ACTIVE) {
802            if (mBackgroundCall.getState() != ImsPhoneCall.State.IDLE) {
803                //we should have failed in !canDial() above before we get here
804                throw new CallStateException("cannot dial in current state");
805            }
806            // foreground call is empty for the newly dialed connection
807            holdBeforeDial = true;
808            // Cache the video state for pending MO call.
809            mPendingCallVideoState = videoState;
810            mPendingIntentExtras = intentExtras;
811            switchWaitingOrHoldingAndActive();
812        }
813
814        ImsPhoneCall.State fgState = ImsPhoneCall.State.IDLE;
815        ImsPhoneCall.State bgState = ImsPhoneCall.State.IDLE;
816
817        mClirMode = clirMode;
818
819        synchronized (mSyncHold) {
820            if (holdBeforeDial) {
821                fgState = mForegroundCall.getState();
822                bgState = mBackgroundCall.getState();
823
824                //holding foreground call failed
825                if (fgState == ImsPhoneCall.State.ACTIVE) {
826                    throw new CallStateException("cannot dial in current state");
827                }
828
829                //holding foreground call succeeded
830                if (bgState == ImsPhoneCall.State.HOLDING) {
831                    holdBeforeDial = false;
832                }
833            }
834
835            mPendingMO = new ImsPhoneConnection(mPhone,
836                    checkForTestEmergencyNumber(dialString), this, mForegroundCall,
837                    isEmergencyNumber);
838            mPendingMO.setVideoState(videoState);
839        }
840        addConnection(mPendingMO);
841
842        if (!holdBeforeDial) {
843            if ((!isPhoneInEcmMode) || (isPhoneInEcmMode && isEmergencyNumber)) {
844                dialInternal(mPendingMO, clirMode, videoState, intentExtras);
845            } else {
846                try {
847                    getEcbmInterface().exitEmergencyCallbackMode();
848                } catch (ImsException e) {
849                    e.printStackTrace();
850                    throw new CallStateException("service not available");
851                }
852                mPhone.setOnEcbModeExitResponse(this, EVENT_EXIT_ECM_RESPONSE_CDMA, null);
853                pendingCallClirMode = clirMode;
854                mPendingCallVideoState = videoState;
855                pendingCallInEcm = true;
856            }
857        }
858
859        updatePhoneState();
860        mPhone.notifyPreciseCallStateChanged();
861
862        return mPendingMO;
863    }
864
865    /**
866     * Caches frequently used carrier configuration items locally.
867     *
868     * @param subId The sub id.
869     */
870    private void cacheCarrierConfiguration(int subId) {
871        CarrierConfigManager carrierConfigManager = (CarrierConfigManager)
872                mPhone.getContext().getSystemService(Context.CARRIER_CONFIG_SERVICE);
873        if (carrierConfigManager == null) {
874            loge("cacheCarrierConfiguration: No carrier config service found.");
875            return;
876        }
877
878        PersistableBundle carrierConfig = carrierConfigManager.getConfigForSubId(subId);
879        if (carrierConfig == null) {
880            loge("cacheCarrierConfiguration: Empty carrier config.");
881            return;
882        }
883
884        mAllowEmergencyVideoCalls =
885                carrierConfig.getBoolean(CarrierConfigManager.KEY_ALLOW_EMERGENCY_VIDEO_CALLS_BOOL);
886        mTreatDowngradedVideoCallsAsVideoCalls =
887                carrierConfig.getBoolean(
888                        CarrierConfigManager.KEY_TREAT_DOWNGRADED_VIDEO_CALLS_AS_VIDEO_CALLS_BOOL);
889        mDropVideoCallWhenAnsweringAudioCall =
890                carrierConfig.getBoolean(
891                        CarrierConfigManager.KEY_DROP_VIDEO_CALL_WHEN_ANSWERING_AUDIO_CALL_BOOL);
892        mAllowAddCallDuringVideoCall =
893                carrierConfig.getBoolean(
894                        CarrierConfigManager.KEY_ALLOW_ADD_CALL_DURING_VIDEO_CALL_BOOL);
895        mNotifyVtHandoverToWifiFail = carrierConfig.getBoolean(
896                CarrierConfigManager.KEY_NOTIFY_VT_HANDOVER_TO_WIFI_FAILURE_BOOL);
897        mSupportDowngradeVtToAudio = carrierConfig.getBoolean(
898                CarrierConfigManager.KEY_SUPPORT_DOWNGRADE_VT_TO_AUDIO_BOOL);
899        mNotifyHandoverVideoFromWifiToLTE = carrierConfig.getBoolean(
900                CarrierConfigManager.KEY_NOTIFY_VT_HANDOVER_TO_WIFI_FAILURE_BOOL);
901        mIgnoreDataEnabledChangedForVideoCalls = carrierConfig.getBoolean(
902                CarrierConfigManager.KEY_IGNORE_DATA_ENABLED_CHANGED_FOR_VIDEO_CALLS);
903        mSupportPauseVideo = carrierConfig.getBoolean(
904                CarrierConfigManager.KEY_SUPPORT_PAUSE_IMS_VIDEO_CALLS_BOOL);
905
906        String[] mappings = carrierConfig
907                .getStringArray(CarrierConfigManager.KEY_IMS_REASONINFO_MAPPING_STRING_ARRAY);
908        if (mappings != null && mappings.length > 0) {
909            for (String mapping : mappings) {
910                String[] values = mapping.split(Pattern.quote("|"));
911                if (values.length != 3) {
912                    continue;
913                }
914
915                try {
916                    Integer fromCode;
917                    if (values[0].equals("*")) {
918                        fromCode = null;
919                    } else {
920                        fromCode = Integer.parseInt(values[0]);
921                    }
922                    String message = values[1];
923                    int toCode = Integer.parseInt(values[2]);
924
925                    addReasonCodeRemapping(fromCode, message, toCode);
926                    log("Loaded ImsReasonInfo mapping : fromCode = " +
927                            fromCode == null ? "any" : fromCode + " ; message = " +
928                            message + " ; toCode = " + toCode);
929                } catch (NumberFormatException nfe) {
930                    loge("Invalid ImsReasonInfo mapping found: " + mapping);
931                }
932            }
933        } else {
934            log("No carrier ImsReasonInfo mappings defined.");
935        }
936    }
937
938    private void handleEcmTimer(int action) {
939        mPhone.handleTimerInEmergencyCallbackMode(action);
940        switch (action) {
941            case ImsPhone.CANCEL_ECM_TIMER:
942                break;
943            case ImsPhone.RESTART_ECM_TIMER:
944                break;
945            default:
946                log("handleEcmTimer, unsupported action " + action);
947        }
948    }
949
950    private void dialInternal(ImsPhoneConnection conn, int clirMode, int videoState,
951            Bundle intentExtras) {
952
953        if (conn == null) {
954            return;
955        }
956
957        if (conn.getAddress()== null || conn.getAddress().length() == 0
958                || conn.getAddress().indexOf(PhoneNumberUtils.WILD) >= 0) {
959            // Phone number is invalid
960            conn.setDisconnectCause(DisconnectCause.INVALID_NUMBER);
961            sendEmptyMessageDelayed(EVENT_HANGUP_PENDINGMO, TIMEOUT_HANGUP_PENDINGMO);
962            return;
963        }
964
965        // Always unmute when initiating a new call
966        setMute(false);
967        int serviceType = PhoneNumberUtils.isEmergencyNumber(conn.getAddress()) ?
968                ImsCallProfile.SERVICE_TYPE_EMERGENCY : ImsCallProfile.SERVICE_TYPE_NORMAL;
969        int callType = ImsCallProfile.getCallTypeFromVideoState(videoState);
970        //TODO(vt): Is this sufficient?  At what point do we know the video state of the call?
971        conn.setVideoState(videoState);
972
973        try {
974            String[] callees = new String[] { conn.getAddress() };
975            ImsCallProfile profile = mImsManager.createCallProfile(mServiceId,
976                    serviceType, callType);
977            profile.setCallExtraInt(ImsCallProfile.EXTRA_OIR, clirMode);
978
979            // Translate call subject intent-extra from Telecom-specific extra key to the
980            // ImsCallProfile key.
981            if (intentExtras != null) {
982                if (intentExtras.containsKey(android.telecom.TelecomManager.EXTRA_CALL_SUBJECT)) {
983                    intentExtras.putString(ImsCallProfile.EXTRA_DISPLAY_TEXT,
984                            cleanseInstantLetteringMessage(intentExtras.getString(
985                                    android.telecom.TelecomManager.EXTRA_CALL_SUBJECT))
986                    );
987                }
988
989                if (intentExtras.containsKey(ImsCallProfile.EXTRA_IS_CALL_PULL)) {
990                    profile.mCallExtras.putBoolean(ImsCallProfile.EXTRA_IS_CALL_PULL,
991                            intentExtras.getBoolean(ImsCallProfile.EXTRA_IS_CALL_PULL));
992                    int dialogId = intentExtras.getInt(
993                            ImsExternalCallTracker.EXTRA_IMS_EXTERNAL_CALL_ID);
994                    conn.setIsPulledCall(true);
995                    conn.setPulledDialogId(dialogId);
996                }
997
998                // Pack the OEM-specific call extras.
999                profile.mCallExtras.putBundle(ImsCallProfile.EXTRA_OEM_EXTRAS, intentExtras);
1000
1001                // NOTE: Extras to be sent over the network are packed into the
1002                // intentExtras individually, with uniquely defined keys.
1003                // These key-value pairs are processed by IMS Service before
1004                // being sent to the lower layers/to the network.
1005            }
1006
1007            ImsCall imsCall = mImsManager.makeCall(mServiceId, profile,
1008                    callees, mImsCallListener);
1009            conn.setImsCall(imsCall);
1010
1011            mMetrics.writeOnImsCallStart(mPhone.getPhoneId(),
1012                    imsCall.getSession());
1013
1014            setVideoCallProvider(conn, imsCall);
1015            conn.setAllowAddCallDuringVideoCall(mAllowAddCallDuringVideoCall);
1016        } catch (ImsException e) {
1017            loge("dialInternal : " + e);
1018            conn.setDisconnectCause(DisconnectCause.ERROR_UNSPECIFIED);
1019            sendEmptyMessageDelayed(EVENT_HANGUP_PENDINGMO, TIMEOUT_HANGUP_PENDINGMO);
1020            retryGetImsService();
1021        } catch (RemoteException e) {
1022        }
1023    }
1024
1025    /**
1026     * Accepts a call with the specified video state.  The video state is the video state that the
1027     * user has agreed upon in the InCall UI.
1028     *
1029     * @param videoState The video State
1030     * @throws CallStateException
1031     */
1032    public void acceptCall (int videoState) throws CallStateException {
1033        if (DBG) log("acceptCall");
1034
1035        if (mForegroundCall.getState().isAlive()
1036                && mBackgroundCall.getState().isAlive()) {
1037            throw new CallStateException("cannot accept call");
1038        }
1039
1040        if ((mRingingCall.getState() == ImsPhoneCall.State.WAITING)
1041                && mForegroundCall.getState().isAlive()) {
1042            setMute(false);
1043
1044            boolean answeringWillDisconnect = false;
1045            ImsCall activeCall = mForegroundCall.getImsCall();
1046            ImsCall ringingCall = mRingingCall.getImsCall();
1047            if (mForegroundCall.hasConnections() && mRingingCall.hasConnections()) {
1048                answeringWillDisconnect =
1049                        shouldDisconnectActiveCallOnAnswer(activeCall, ringingCall);
1050            }
1051
1052            // Cache video state for pending MT call.
1053            mPendingCallVideoState = videoState;
1054
1055            if (answeringWillDisconnect) {
1056                // We need to disconnect the foreground call before answering the background call.
1057                mForegroundCall.hangup();
1058                try {
1059                    ringingCall.accept(ImsCallProfile.getCallTypeFromVideoState(videoState));
1060                } catch (ImsException e) {
1061                    throw new CallStateException("cannot accept call");
1062                }
1063            } else {
1064                switchWaitingOrHoldingAndActive();
1065            }
1066        } else if (mRingingCall.getState().isRinging()) {
1067            if (DBG) log("acceptCall: incoming...");
1068            // Always unmute when answering a new call
1069            setMute(false);
1070            try {
1071                ImsCall imsCall = mRingingCall.getImsCall();
1072                if (imsCall != null) {
1073                    imsCall.accept(ImsCallProfile.getCallTypeFromVideoState(videoState));
1074                    mMetrics.writeOnImsCommand(mPhone.getPhoneId(), imsCall.getSession(),
1075                            ImsCommand.IMS_CMD_ACCEPT);
1076                } else {
1077                    throw new CallStateException("no valid ims call");
1078                }
1079            } catch (ImsException e) {
1080                throw new CallStateException("cannot accept call");
1081            }
1082        } else {
1083            throw new CallStateException("phone not ringing");
1084        }
1085    }
1086
1087    public void rejectCall () throws CallStateException {
1088        if (DBG) log("rejectCall");
1089
1090        if (mRingingCall.getState().isRinging()) {
1091            hangup(mRingingCall);
1092        } else {
1093            throw new CallStateException("phone not ringing");
1094        }
1095    }
1096
1097
1098    private void switchAfterConferenceSuccess() {
1099        if (DBG) log("switchAfterConferenceSuccess fg =" + mForegroundCall.getState() +
1100                ", bg = " + mBackgroundCall.getState());
1101
1102        if (mBackgroundCall.getState() == ImsPhoneCall.State.HOLDING) {
1103            log("switchAfterConferenceSuccess");
1104            mForegroundCall.switchWith(mBackgroundCall);
1105        }
1106    }
1107
1108    public void switchWaitingOrHoldingAndActive() throws CallStateException {
1109        if (DBG) log("switchWaitingOrHoldingAndActive");
1110
1111        if (mRingingCall.getState() == ImsPhoneCall.State.INCOMING) {
1112            throw new CallStateException("cannot be in the incoming state");
1113        }
1114
1115        if (mForegroundCall.getState() == ImsPhoneCall.State.ACTIVE) {
1116            ImsCall imsCall = mForegroundCall.getImsCall();
1117            if (imsCall == null) {
1118                throw new CallStateException("no ims call");
1119            }
1120
1121            // Swap the ImsCalls pointed to by the foreground and background ImsPhoneCalls.
1122            // If hold or resume later fails, we will swap them back.
1123            boolean switchingWithWaitingCall = mBackgroundCall.getImsCall() == null &&
1124                    mRingingCall != null &&
1125                    mRingingCall.getState() == ImsPhoneCall.State.WAITING;
1126
1127            mSwitchingFgAndBgCalls = true;
1128            if (switchingWithWaitingCall) {
1129                mCallExpectedToResume = mRingingCall.getImsCall();
1130            } else {
1131                mCallExpectedToResume = mBackgroundCall.getImsCall();
1132            }
1133            mForegroundCall.switchWith(mBackgroundCall);
1134
1135            // Hold the foreground call; once the foreground call is held, the background call will
1136            // be resumed.
1137            try {
1138                imsCall.hold();
1139                mMetrics.writeOnImsCommand(mPhone.getPhoneId(), imsCall.getSession(),
1140                        ImsCommand.IMS_CMD_HOLD);
1141
1142                // If there is no background call to resume, then don't expect there to be a switch.
1143                if (mCallExpectedToResume == null) {
1144                    log("mCallExpectedToResume is null");
1145                    mSwitchingFgAndBgCalls = false;
1146                }
1147            } catch (ImsException e) {
1148                mForegroundCall.switchWith(mBackgroundCall);
1149                throw new CallStateException(e.getMessage());
1150            }
1151        } else if (mBackgroundCall.getState() == ImsPhoneCall.State.HOLDING) {
1152            resumeWaitingOrHolding();
1153        }
1154    }
1155
1156    public void
1157    conference() {
1158        if (DBG) log("conference");
1159
1160        ImsCall fgImsCall = mForegroundCall.getImsCall();
1161        if (fgImsCall == null) {
1162            log("conference no foreground ims call");
1163            return;
1164        }
1165
1166        ImsCall bgImsCall = mBackgroundCall.getImsCall();
1167        if (bgImsCall == null) {
1168            log("conference no background ims call");
1169            return;
1170        }
1171
1172        // Keep track of the connect time of the earliest call so that it can be set on the
1173        // {@code ImsConference} when it is created.
1174        long foregroundConnectTime = mForegroundCall.getEarliestConnectTime();
1175        long backgroundConnectTime = mBackgroundCall.getEarliestConnectTime();
1176        long conferenceConnectTime;
1177        if (foregroundConnectTime > 0 && backgroundConnectTime > 0) {
1178            conferenceConnectTime = Math.min(mForegroundCall.getEarliestConnectTime(),
1179                    mBackgroundCall.getEarliestConnectTime());
1180            log("conference - using connect time = " + conferenceConnectTime);
1181        } else if (foregroundConnectTime > 0) {
1182            log("conference - bg call connect time is 0; using fg = " + foregroundConnectTime);
1183            conferenceConnectTime = foregroundConnectTime;
1184        } else {
1185            log("conference - fg call connect time is 0; using bg = " + backgroundConnectTime);
1186            conferenceConnectTime = backgroundConnectTime;
1187        }
1188
1189        ImsPhoneConnection foregroundConnection = mForegroundCall.getFirstConnection();
1190        if (foregroundConnection != null) {
1191            foregroundConnection.setConferenceConnectTime(conferenceConnectTime);
1192        }
1193
1194        try {
1195            fgImsCall.merge(bgImsCall);
1196        } catch (ImsException e) {
1197            log("conference " + e.getMessage());
1198        }
1199    }
1200
1201    public void
1202    explicitCallTransfer() {
1203        //TODO : implement
1204    }
1205
1206    public void
1207    clearDisconnected() {
1208        if (DBG) log("clearDisconnected");
1209
1210        internalClearDisconnected();
1211
1212        updatePhoneState();
1213        mPhone.notifyPreciseCallStateChanged();
1214    }
1215
1216    public boolean
1217    canConference() {
1218        return mForegroundCall.getState() == ImsPhoneCall.State.ACTIVE
1219            && mBackgroundCall.getState() == ImsPhoneCall.State.HOLDING
1220            && !mBackgroundCall.isFull()
1221            && !mForegroundCall.isFull();
1222    }
1223
1224    public boolean
1225    canDial() {
1226        boolean ret;
1227        int serviceState = mPhone.getServiceState().getState();
1228        String disableCall = SystemProperties.get(
1229                TelephonyProperties.PROPERTY_DISABLE_CALL, "false");
1230
1231        ret = (serviceState != ServiceState.STATE_POWER_OFF)
1232            && mPendingMO == null
1233            && !mRingingCall.isRinging()
1234            && !disableCall.equals("true")
1235            && (!mForegroundCall.getState().isAlive()
1236                    || !mBackgroundCall.getState().isAlive());
1237
1238        return ret;
1239    }
1240
1241    public boolean
1242    canTransfer() {
1243        return mForegroundCall.getState() == ImsPhoneCall.State.ACTIVE
1244            && mBackgroundCall.getState() == ImsPhoneCall.State.HOLDING;
1245    }
1246
1247    //***** Private Instance Methods
1248
1249    private void
1250    internalClearDisconnected() {
1251        mRingingCall.clearDisconnected();
1252        mForegroundCall.clearDisconnected();
1253        mBackgroundCall.clearDisconnected();
1254        mHandoverCall.clearDisconnected();
1255    }
1256
1257    private void
1258    updatePhoneState() {
1259        PhoneConstants.State oldState = mState;
1260
1261        boolean isPendingMOIdle = mPendingMO == null || !mPendingMO.getState().isAlive();
1262
1263        if (mRingingCall.isRinging()) {
1264            mState = PhoneConstants.State.RINGING;
1265        } else if (!isPendingMOIdle || !mForegroundCall.isIdle() || !mBackgroundCall.isIdle()) {
1266            // There is a non-idle call, so we're off the hook.
1267            mState = PhoneConstants.State.OFFHOOK;
1268        } else {
1269            mState = PhoneConstants.State.IDLE;
1270        }
1271
1272        if (mState == PhoneConstants.State.IDLE && oldState != mState) {
1273            mVoiceCallEndedRegistrants.notifyRegistrants(
1274                    new AsyncResult(null, null, null));
1275        } else if (oldState == PhoneConstants.State.IDLE && oldState != mState) {
1276            mVoiceCallStartedRegistrants.notifyRegistrants (
1277                    new AsyncResult(null, null, null));
1278        }
1279
1280        if (DBG) {
1281            log("updatePhoneState pendingMo = " + (mPendingMO == null ? "null"
1282                    : mPendingMO.getState()) + ", fg= " + mForegroundCall.getState() + "("
1283                    + mForegroundCall.getConnections().size() + "), bg= " + mBackgroundCall
1284                    .getState() + "(" + mBackgroundCall.getConnections().size() + ")");
1285            log("updatePhoneState oldState=" + oldState + ", newState=" + mState);
1286        }
1287
1288        if (mState != oldState) {
1289            mPhone.notifyPhoneStateChanged();
1290            mMetrics.writePhoneState(mPhone.getPhoneId(), mState);
1291            notifyPhoneStateChanged(oldState, mState);
1292        }
1293    }
1294
1295    private void
1296    handleRadioNotAvailable() {
1297        // handlePollCalls will clear out its
1298        // call list when it gets the CommandException
1299        // error result from this
1300        pollCallsWhenSafe();
1301    }
1302
1303    private void
1304    dumpState() {
1305        List l;
1306
1307        log("Phone State:" + mState);
1308
1309        log("Ringing call: " + mRingingCall.toString());
1310
1311        l = mRingingCall.getConnections();
1312        for (int i = 0, s = l.size(); i < s; i++) {
1313            log(l.get(i).toString());
1314        }
1315
1316        log("Foreground call: " + mForegroundCall.toString());
1317
1318        l = mForegroundCall.getConnections();
1319        for (int i = 0, s = l.size(); i < s; i++) {
1320            log(l.get(i).toString());
1321        }
1322
1323        log("Background call: " + mBackgroundCall.toString());
1324
1325        l = mBackgroundCall.getConnections();
1326        for (int i = 0, s = l.size(); i < s; i++) {
1327            log(l.get(i).toString());
1328        }
1329
1330    }
1331
1332    //***** Called from ImsPhone
1333
1334    public void setUiTTYMode(int uiTtyMode, Message onComplete) {
1335        if (mImsManager == null) {
1336            mPhone.sendErrorResponse(onComplete, getImsManagerIsNullException());
1337            return;
1338        }
1339
1340        try {
1341            mImsManager.setUiTTYMode(mPhone.getContext(), uiTtyMode, onComplete);
1342        } catch (ImsException e) {
1343            loge("setTTYMode : " + e);
1344            mPhone.sendErrorResponse(onComplete, e);
1345            retryGetImsService();
1346        }
1347    }
1348
1349    public void setMute(boolean mute) {
1350        mDesiredMute = mute;
1351        mForegroundCall.setMute(mute);
1352    }
1353
1354    public boolean getMute() {
1355        return mDesiredMute;
1356    }
1357
1358    public void sendDtmf(char c, Message result) {
1359        if (DBG) log("sendDtmf");
1360
1361        ImsCall imscall = mForegroundCall.getImsCall();
1362        if (imscall != null) {
1363            imscall.sendDtmf(c, result);
1364        }
1365    }
1366
1367    public void
1368    startDtmf(char c) {
1369        if (DBG) log("startDtmf");
1370
1371        ImsCall imscall = mForegroundCall.getImsCall();
1372        if (imscall != null) {
1373            imscall.startDtmf(c);
1374        } else {
1375            loge("startDtmf : no foreground call");
1376        }
1377    }
1378
1379    public void
1380    stopDtmf() {
1381        if (DBG) log("stopDtmf");
1382
1383        ImsCall imscall = mForegroundCall.getImsCall();
1384        if (imscall != null) {
1385            imscall.stopDtmf();
1386        } else {
1387            loge("stopDtmf : no foreground call");
1388        }
1389    }
1390
1391    //***** Called from ImsPhoneConnection
1392
1393    public void hangup (ImsPhoneConnection conn) throws CallStateException {
1394        if (DBG) log("hangup connection");
1395
1396        if (conn.getOwner() != this) {
1397            throw new CallStateException ("ImsPhoneConnection " + conn
1398                    + "does not belong to ImsPhoneCallTracker " + this);
1399        }
1400
1401        hangup(conn.getCall());
1402    }
1403
1404    //***** Called from ImsPhoneCall
1405
1406    public void hangup (ImsPhoneCall call) throws CallStateException {
1407        if (DBG) log("hangup call");
1408
1409        if (call.getConnections().size() == 0) {
1410            throw new CallStateException("no connections");
1411        }
1412
1413        ImsCall imsCall = call.getImsCall();
1414        boolean rejectCall = false;
1415
1416        if (call == mRingingCall) {
1417            if (Phone.DEBUG_PHONE) log("(ringing) hangup incoming");
1418            rejectCall = true;
1419        } else if (call == mForegroundCall) {
1420            if (call.isDialingOrAlerting()) {
1421                if (Phone.DEBUG_PHONE) {
1422                    log("(foregnd) hangup dialing or alerting...");
1423                }
1424            } else {
1425                if (Phone.DEBUG_PHONE) {
1426                    log("(foregnd) hangup foreground");
1427                }
1428                //held call will be resumed by onCallTerminated
1429            }
1430        } else if (call == mBackgroundCall) {
1431            if (Phone.DEBUG_PHONE) {
1432                log("(backgnd) hangup waiting or background");
1433            }
1434        } else {
1435            throw new CallStateException ("ImsPhoneCall " + call +
1436                    "does not belong to ImsPhoneCallTracker " + this);
1437        }
1438
1439        call.onHangupLocal();
1440
1441        try {
1442            if (imsCall != null) {
1443                if (rejectCall) {
1444                    imsCall.reject(ImsReasonInfo.CODE_USER_DECLINE);
1445                    mMetrics.writeOnImsCommand(mPhone.getPhoneId(), imsCall.getSession(),
1446                            ImsCommand.IMS_CMD_REJECT);
1447                } else {
1448                    imsCall.terminate(ImsReasonInfo.CODE_USER_TERMINATED);
1449                    mMetrics.writeOnImsCommand(mPhone.getPhoneId(), imsCall.getSession(),
1450                            ImsCommand.IMS_CMD_TERMINATE);
1451                }
1452            } else if (mPendingMO != null && call == mForegroundCall) {
1453                // is holding a foreground call
1454                mPendingMO.update(null, ImsPhoneCall.State.DISCONNECTED);
1455                mPendingMO.onDisconnect();
1456                removeConnection(mPendingMO);
1457                mPendingMO = null;
1458                updatePhoneState();
1459                removeMessages(EVENT_DIAL_PENDINGMO);
1460            }
1461        } catch (ImsException e) {
1462            throw new CallStateException(e.getMessage());
1463        }
1464
1465        mPhone.notifyPreciseCallStateChanged();
1466    }
1467
1468    void callEndCleanupHandOverCallIfAny() {
1469        if (mHandoverCall.mConnections.size() > 0) {
1470            if (DBG) log("callEndCleanupHandOverCallIfAny, mHandoverCall.mConnections="
1471                    + mHandoverCall.mConnections);
1472            mHandoverCall.mConnections.clear();
1473            mConnections.clear();
1474            mState = PhoneConstants.State.IDLE;
1475        }
1476    }
1477
1478    /* package */
1479    void resumeWaitingOrHolding() throws CallStateException {
1480        if (DBG) log("resumeWaitingOrHolding");
1481
1482        try {
1483            if (mForegroundCall.getState().isAlive()) {
1484                //resume foreground call after holding background call
1485                //they were switched before holding
1486                ImsCall imsCall = mForegroundCall.getImsCall();
1487                if (imsCall != null) {
1488                    imsCall.resume();
1489                    mMetrics.writeOnImsCommand(mPhone.getPhoneId(), imsCall.getSession(),
1490                            ImsCommand.IMS_CMD_RESUME);
1491                }
1492            } else if (mRingingCall.getState() == ImsPhoneCall.State.WAITING) {
1493                //accept waiting call after holding background call
1494                ImsCall imsCall = mRingingCall.getImsCall();
1495                if (imsCall != null) {
1496                    imsCall.accept(
1497                        ImsCallProfile.getCallTypeFromVideoState(mPendingCallVideoState));
1498                    mMetrics.writeOnImsCommand(mPhone.getPhoneId(), imsCall.getSession(),
1499                            ImsCommand.IMS_CMD_ACCEPT);
1500                }
1501            } else {
1502                //Just resume background call.
1503                //To distinguish resuming call with swapping calls
1504                //we do not switch calls.here
1505                //ImsPhoneConnection.update will chnage the parent when completed
1506                ImsCall imsCall = mBackgroundCall.getImsCall();
1507                if (imsCall != null) {
1508                    imsCall.resume();
1509                    mMetrics.writeOnImsCommand(mPhone.getPhoneId(), imsCall.getSession(),
1510                            ImsCommand.IMS_CMD_RESUME);
1511                }
1512            }
1513        } catch (ImsException e) {
1514            throw new CallStateException(e.getMessage());
1515        }
1516    }
1517
1518    public void sendUSSD (String ussdString, Message response) {
1519        if (DBG) log("sendUSSD");
1520
1521        try {
1522            if (mUssdSession != null) {
1523                mUssdSession.sendUssd(ussdString);
1524                AsyncResult.forMessage(response, null, null);
1525                response.sendToTarget();
1526                return;
1527            }
1528
1529            if (mImsManager == null) {
1530                mPhone.sendErrorResponse(response, getImsManagerIsNullException());
1531                return;
1532            }
1533
1534            String[] callees = new String[] { ussdString };
1535            ImsCallProfile profile = mImsManager.createCallProfile(mServiceId,
1536                    ImsCallProfile.SERVICE_TYPE_NORMAL, ImsCallProfile.CALL_TYPE_VOICE);
1537            profile.setCallExtraInt(ImsCallProfile.EXTRA_DIALSTRING,
1538                    ImsCallProfile.DIALSTRING_USSD);
1539
1540            mUssdSession = mImsManager.makeCall(mServiceId, profile,
1541                    callees, mImsUssdListener);
1542        } catch (ImsException e) {
1543            loge("sendUSSD : " + e);
1544            mPhone.sendErrorResponse(response, e);
1545            retryGetImsService();
1546        }
1547    }
1548
1549    public void cancelUSSD() {
1550        if (mUssdSession == null) return;
1551
1552        try {
1553            mUssdSession.terminate(ImsReasonInfo.CODE_USER_TERMINATED);
1554        } catch (ImsException e) {
1555        }
1556
1557    }
1558
1559    private synchronized ImsPhoneConnection findConnection(final ImsCall imsCall) {
1560        for (ImsPhoneConnection conn : mConnections) {
1561            if (conn.getImsCall() == imsCall) {
1562                return conn;
1563            }
1564        }
1565        return null;
1566    }
1567
1568    private synchronized void removeConnection(ImsPhoneConnection conn) {
1569        mConnections.remove(conn);
1570        // If not emergency call is remaining, notify emergency call registrants
1571        if (mIsInEmergencyCall) {
1572            boolean isEmergencyCallInList = false;
1573            // if no emergency calls pending, set this to false
1574            for (ImsPhoneConnection imsPhoneConnection : mConnections) {
1575                if (imsPhoneConnection != null && imsPhoneConnection.isEmergency() == true) {
1576                    isEmergencyCallInList = true;
1577                    break;
1578                }
1579            }
1580
1581            if (!isEmergencyCallInList) {
1582                mIsInEmergencyCall = false;
1583                mPhone.sendEmergencyCallStateChange(false);
1584            }
1585        }
1586    }
1587
1588    private synchronized void addConnection(ImsPhoneConnection conn) {
1589        mConnections.add(conn);
1590        if (conn.isEmergency()) {
1591            mIsInEmergencyCall = true;
1592            mPhone.sendEmergencyCallStateChange(true);
1593        }
1594    }
1595
1596    private void processCallStateChange(ImsCall imsCall, ImsPhoneCall.State state, int cause) {
1597        if (DBG) log("processCallStateChange " + imsCall + " state=" + state + " cause=" + cause);
1598        // This method is called on onCallUpdate() where there is not necessarily a call state
1599        // change. In these situations, we'll ignore the state related updates and only process
1600        // the change in media capabilities (as expected).  The default is to not ignore state
1601        // changes so we do not change existing behavior.
1602        processCallStateChange(imsCall, state, cause, false /* do not ignore state update */);
1603    }
1604
1605    private void processCallStateChange(ImsCall imsCall, ImsPhoneCall.State state, int cause,
1606            boolean ignoreState) {
1607        if (DBG) {
1608            log("processCallStateChange state=" + state + " cause=" + cause
1609                    + " ignoreState=" + ignoreState);
1610        }
1611
1612        if (imsCall == null) return;
1613
1614        boolean changed = false;
1615        ImsPhoneConnection conn = findConnection(imsCall);
1616
1617        if (conn == null) {
1618            // TODO : what should be done?
1619            return;
1620        }
1621
1622        // processCallStateChange is triggered for onCallUpdated as well.
1623        // onCallUpdated should not modify the state of the call
1624        // It should modify only other capabilities of call through updateMediaCapabilities
1625        // State updates will be triggered through individual callbacks
1626        // i.e. onCallHeld, onCallResume, etc and conn.update will be responsible for the update
1627        conn.updateMediaCapabilities(imsCall);
1628        if (ignoreState) {
1629            conn.updateAddressDisplay(imsCall);
1630            conn.updateExtras(imsCall);
1631
1632            maybeSetVideoCallProvider(conn, imsCall);
1633            return;
1634        }
1635
1636        changed = conn.update(imsCall, state);
1637        if (state == ImsPhoneCall.State.DISCONNECTED) {
1638            changed = conn.onDisconnect(cause) || changed;
1639            //detach the disconnected connections
1640            conn.getCall().detach(conn);
1641            removeConnection(conn);
1642        }
1643
1644        if (changed) {
1645            if (conn.getCall() == mHandoverCall) return;
1646            updatePhoneState();
1647            mPhone.notifyPreciseCallStateChanged();
1648        }
1649    }
1650
1651    private void maybeSetVideoCallProvider(ImsPhoneConnection conn, ImsCall imsCall) {
1652        android.telecom.Connection.VideoProvider connVideoProvider = conn.getVideoProvider();
1653        if (connVideoProvider != null || imsCall.getCallSession().getVideoCallProvider() == null) {
1654            return;
1655        }
1656
1657        try {
1658            setVideoCallProvider(conn, imsCall);
1659        } catch (RemoteException e) {
1660            loge("maybeSetVideoCallProvider: exception " + e);
1661        }
1662    }
1663
1664    /**
1665     * Adds a reason code remapping, for test purposes.
1666     *
1667     * @param fromCode The from code, or {@code null} if all.
1668     * @param message The message to map.
1669     * @param toCode The code to remap to.
1670     */
1671    @VisibleForTesting
1672    public void addReasonCodeRemapping(Integer fromCode, String message, Integer toCode) {
1673        mImsReasonCodeMap.put(new Pair<>(fromCode, message), toCode);
1674    }
1675
1676    /**
1677     * Returns the {@link ImsReasonInfo#getCode()}, potentially remapping to a new value based on
1678     * the {@link ImsReasonInfo#getCode()} and {@link ImsReasonInfo#getExtraMessage()}.
1679     *
1680     * See {@link #mImsReasonCodeMap}.
1681     *
1682     * @param reasonInfo The {@link ImsReasonInfo}.
1683     * @return The remapped code.
1684     */
1685    @VisibleForTesting
1686    public int maybeRemapReasonCode(ImsReasonInfo reasonInfo) {
1687        int code = reasonInfo.getCode();
1688
1689        Pair<Integer, String> toCheck = new Pair<>(code, reasonInfo.getExtraMessage());
1690        Pair<Integer, String> wildcardToCheck = new Pair<>(null, reasonInfo.getExtraMessage());
1691        if (mImsReasonCodeMap.containsKey(toCheck)) {
1692            int toCode = mImsReasonCodeMap.get(toCheck);
1693
1694            log("maybeRemapReasonCode : fromCode = " + reasonInfo.getCode() + " ; message = "
1695                    + reasonInfo.getExtraMessage() + " ; toCode = " + toCode);
1696            return toCode;
1697        } else if (mImsReasonCodeMap.containsKey(wildcardToCheck)) {
1698            // Handle the case where a wildcard is specified for the fromCode; in this case we will
1699            // match without caring about the fromCode.
1700            int toCode = mImsReasonCodeMap.get(wildcardToCheck);
1701
1702            log("maybeRemapReasonCode : fromCode(wildcard) = " + reasonInfo.getCode() +
1703                    " ; message = " + reasonInfo.getExtraMessage() + " ; toCode = " + toCode);
1704            return toCode;
1705        }
1706        return code;
1707    }
1708
1709    private int getDisconnectCauseFromReasonInfo(ImsReasonInfo reasonInfo) {
1710        int cause = DisconnectCause.ERROR_UNSPECIFIED;
1711
1712        //int type = reasonInfo.getReasonType();
1713        int code = maybeRemapReasonCode(reasonInfo);
1714        switch (code) {
1715            case ImsReasonInfo.CODE_SIP_BAD_ADDRESS:
1716            case ImsReasonInfo.CODE_SIP_NOT_REACHABLE:
1717                return DisconnectCause.NUMBER_UNREACHABLE;
1718
1719            case ImsReasonInfo.CODE_SIP_BUSY:
1720                return DisconnectCause.BUSY;
1721
1722            case ImsReasonInfo.CODE_USER_TERMINATED:
1723            case ImsReasonInfo.CODE_LOCAL_ENDED_BY_CONFERENCE_MERGE:
1724                return DisconnectCause.LOCAL;
1725
1726            case ImsReasonInfo.CODE_LOCAL_CALL_DECLINE:
1727            case ImsReasonInfo.CODE_REMOTE_CALL_DECLINE:
1728                // If the call has been declined locally (on this device), or on remotely (on
1729                // another device using multiendpoint functionality), mark it as rejected.
1730                return DisconnectCause.INCOMING_REJECTED;
1731
1732            case ImsReasonInfo.CODE_USER_TERMINATED_BY_REMOTE:
1733                return DisconnectCause.NORMAL;
1734
1735            case ImsReasonInfo.CODE_SIP_FORBIDDEN:
1736                return DisconnectCause.SERVER_ERROR;
1737
1738            case ImsReasonInfo.CODE_SIP_REDIRECTED:
1739            case ImsReasonInfo.CODE_SIP_BAD_REQUEST:
1740            case ImsReasonInfo.CODE_SIP_NOT_ACCEPTABLE:
1741            case ImsReasonInfo.CODE_SIP_USER_REJECTED:
1742            case ImsReasonInfo.CODE_SIP_GLOBAL_ERROR:
1743                return DisconnectCause.SERVER_ERROR;
1744
1745            case ImsReasonInfo.CODE_SIP_SERVICE_UNAVAILABLE:
1746            case ImsReasonInfo.CODE_SIP_NOT_FOUND:
1747            case ImsReasonInfo.CODE_SIP_SERVER_ERROR:
1748                return DisconnectCause.SERVER_UNREACHABLE;
1749
1750            case ImsReasonInfo.CODE_LOCAL_NETWORK_ROAMING:
1751            case ImsReasonInfo.CODE_LOCAL_NETWORK_IP_CHANGED:
1752            case ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN:
1753            case ImsReasonInfo.CODE_LOCAL_SERVICE_UNAVAILABLE:
1754            case ImsReasonInfo.CODE_LOCAL_NOT_REGISTERED:
1755            case ImsReasonInfo.CODE_LOCAL_NETWORK_NO_LTE_COVERAGE:
1756            case ImsReasonInfo.CODE_LOCAL_NETWORK_NO_SERVICE:
1757            case ImsReasonInfo.CODE_LOCAL_CALL_VCC_ON_PROGRESSING:
1758                return DisconnectCause.OUT_OF_SERVICE;
1759
1760            case ImsReasonInfo.CODE_SIP_REQUEST_TIMEOUT:
1761            case ImsReasonInfo.CODE_TIMEOUT_1XX_WAITING:
1762            case ImsReasonInfo.CODE_TIMEOUT_NO_ANSWER:
1763            case ImsReasonInfo.CODE_TIMEOUT_NO_ANSWER_CALL_UPDATE:
1764                return DisconnectCause.TIMED_OUT;
1765
1766            case ImsReasonInfo.CODE_LOCAL_LOW_BATTERY:
1767            case ImsReasonInfo.CODE_LOCAL_POWER_OFF:
1768                return DisconnectCause.POWER_OFF;
1769
1770            case ImsReasonInfo.CODE_FDN_BLOCKED:
1771                return DisconnectCause.FDN_BLOCKED;
1772
1773            case ImsReasonInfo.CODE_ANSWERED_ELSEWHERE:
1774                return DisconnectCause.ANSWERED_ELSEWHERE;
1775
1776            case ImsReasonInfo.CODE_CALL_END_CAUSE_CALL_PULL:
1777                return DisconnectCause.CALL_PULLED;
1778
1779            case ImsReasonInfo.CODE_MAXIMUM_NUMBER_OF_CALLS_REACHED:
1780                return DisconnectCause.MAXIMUM_NUMBER_OF_CALLS_REACHED;
1781
1782            case ImsReasonInfo.CODE_DATA_DISABLED:
1783                return DisconnectCause.DATA_DISABLED;
1784
1785            case ImsReasonInfo.CODE_DATA_LIMIT_REACHED:
1786                return DisconnectCause.DATA_LIMIT_REACHED;
1787
1788            case ImsReasonInfo.CODE_WIFI_LOST:
1789                return DisconnectCause.WIFI_LOST;
1790            default:
1791        }
1792
1793        return cause;
1794    }
1795
1796    private int getPreciseDisconnectCauseFromReasonInfo(ImsReasonInfo reasonInfo) {
1797        return PRECISE_CAUSE_MAP.get(maybeRemapReasonCode(reasonInfo),
1798                PreciseDisconnectCause.ERROR_UNSPECIFIED);
1799    }
1800
1801    /**
1802     * @return true if the phone is in Emergency Callback mode, otherwise false
1803     */
1804    private boolean isPhoneInEcbMode() {
1805        return mPhone.isInEcm();
1806    }
1807
1808    /**
1809     * Before dialing pending MO request, check for the Emergency Callback mode.
1810     * If device is in Emergency callback mode, then exit the mode before dialing pending MO.
1811     */
1812    private void dialPendingMO() {
1813        boolean isPhoneInEcmMode = isPhoneInEcbMode();
1814        boolean isEmergencyNumber = mPendingMO.isEmergency();
1815        if ((!isPhoneInEcmMode) || (isPhoneInEcmMode && isEmergencyNumber)) {
1816            sendEmptyMessage(EVENT_DIAL_PENDINGMO);
1817        } else {
1818            sendEmptyMessage(EVENT_EXIT_ECBM_BEFORE_PENDINGMO);
1819        }
1820    }
1821
1822    /**
1823     * Listen to the IMS call state change
1824     */
1825    private ImsCall.Listener mImsCallListener = new ImsCall.Listener() {
1826        @Override
1827        public void onCallProgressing(ImsCall imsCall) {
1828            if (DBG) log("onCallProgressing");
1829
1830            mPendingMO = null;
1831            processCallStateChange(imsCall, ImsPhoneCall.State.ALERTING,
1832                    DisconnectCause.NOT_DISCONNECTED);
1833            mMetrics.writeOnImsCallProgressing(mPhone.getPhoneId(), imsCall.getCallSession());
1834        }
1835
1836        @Override
1837        public void onCallStarted(ImsCall imsCall) {
1838            if (DBG) log("onCallStarted");
1839
1840            if (mSwitchingFgAndBgCalls) {
1841                // If we put a call on hold to answer an incoming call, we should reset the
1842                // variables that keep track of the switch here.
1843                if (mCallExpectedToResume != null && mCallExpectedToResume == imsCall) {
1844                    if (DBG) log("onCallStarted: starting a call as a result of a switch.");
1845                    mSwitchingFgAndBgCalls = false;
1846                    mCallExpectedToResume = null;
1847                }
1848            }
1849
1850            mPendingMO = null;
1851            processCallStateChange(imsCall, ImsPhoneCall.State.ACTIVE,
1852                    DisconnectCause.NOT_DISCONNECTED);
1853
1854            if (mNotifyVtHandoverToWifiFail &&
1855                    !imsCall.isWifiCall() && imsCall.isVideoCall() && isWifiConnected()) {
1856                // Schedule check to see if handover succeeded.
1857                sendMessageDelayed(obtainMessage(EVENT_CHECK_FOR_WIFI_HANDOVER, imsCall),
1858                        HANDOVER_TO_WIFI_TIMEOUT_MS);
1859            }
1860
1861            mMetrics.writeOnImsCallStarted(mPhone.getPhoneId(), imsCall.getCallSession());
1862        }
1863
1864        @Override
1865        public void onCallUpdated(ImsCall imsCall) {
1866            if (DBG) log("onCallUpdated");
1867            if (imsCall == null) {
1868                return;
1869            }
1870            ImsPhoneConnection conn = findConnection(imsCall);
1871            if (conn != null) {
1872                processCallStateChange(imsCall, conn.getCall().mState,
1873                        DisconnectCause.NOT_DISCONNECTED, true /*ignore state update*/);
1874                mMetrics.writeImsCallState(mPhone.getPhoneId(),
1875                        imsCall.getCallSession(), conn.getCall().mState);
1876            }
1877        }
1878
1879        /**
1880         * onCallStartFailed will be invoked when:
1881         * case 1) Dialing fails
1882         * case 2) Ringing call is disconnected by local or remote user
1883         */
1884        @Override
1885        public void onCallStartFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1886            if (DBG) log("onCallStartFailed reasonCode=" + reasonInfo.getCode());
1887
1888            if (mSwitchingFgAndBgCalls) {
1889                // If we put a call on hold to answer an incoming call, we should reset the
1890                // variables that keep track of the switch here.
1891                if (mCallExpectedToResume != null && mCallExpectedToResume == imsCall) {
1892                    if (DBG) log("onCallStarted: starting a call as a result of a switch.");
1893                    mSwitchingFgAndBgCalls = false;
1894                    mCallExpectedToResume = null;
1895                }
1896            }
1897
1898            if (mPendingMO != null) {
1899                // To initiate dialing circuit-switched call
1900                if (reasonInfo.getCode() == ImsReasonInfo.CODE_LOCAL_CALL_CS_RETRY_REQUIRED
1901                        && mBackgroundCall.getState() == ImsPhoneCall.State.IDLE
1902                        && mRingingCall.getState() == ImsPhoneCall.State.IDLE) {
1903                    mForegroundCall.detach(mPendingMO);
1904                    removeConnection(mPendingMO);
1905                    mPendingMO.finalize();
1906                    mPendingMO = null;
1907                    mPhone.initiateSilentRedial();
1908                    return;
1909                } else {
1910                    mPendingMO = null;
1911                    int cause = getDisconnectCauseFromReasonInfo(reasonInfo);
1912                    ImsPhoneConnection conn = findConnection(imsCall);
1913
1914                    if(conn != null) {
1915                        conn.setPreciseDisconnectCause(
1916                                getPreciseDisconnectCauseFromReasonInfo(reasonInfo));
1917                    }
1918
1919                    processCallStateChange(imsCall, ImsPhoneCall.State.DISCONNECTED, cause);
1920                }
1921                mMetrics.writeOnImsCallStartFailed(mPhone.getPhoneId(), imsCall.getCallSession(),
1922                        reasonInfo);
1923            }
1924        }
1925
1926        @Override
1927        public void onCallTerminated(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1928            if (DBG) log("onCallTerminated reasonCode=" + reasonInfo.getCode());
1929
1930            int cause = getDisconnectCauseFromReasonInfo(reasonInfo);
1931            ImsPhoneConnection conn = findConnection(imsCall);
1932            if (DBG) log("cause = " + cause + " conn = " + conn);
1933
1934            if (conn != null) {
1935                android.telecom.Connection.VideoProvider videoProvider = conn.getVideoProvider();
1936                if (videoProvider instanceof ImsVideoCallProviderWrapper) {
1937                    ImsVideoCallProviderWrapper wrapper = (ImsVideoCallProviderWrapper)
1938                            videoProvider;
1939
1940                    wrapper.removeImsVideoProviderCallback(conn);
1941                }
1942            }
1943            if (mOnHoldToneId == System.identityHashCode(conn)) {
1944                if (conn != null && mOnHoldToneStarted) {
1945                    mPhone.stopOnHoldTone(conn);
1946                }
1947                mOnHoldToneStarted = false;
1948                mOnHoldToneId = -1;
1949            }
1950            if (conn != null) {
1951                if (conn.isPulledCall() && (
1952                        reasonInfo.getCode() == ImsReasonInfo.CODE_CALL_PULL_OUT_OF_SYNC ||
1953                        reasonInfo.getCode() == ImsReasonInfo.CODE_SIP_TEMPRARILY_UNAVAILABLE ||
1954                        reasonInfo.getCode() == ImsReasonInfo.CODE_SIP_FORBIDDEN) &&
1955                        mPhone != null && mPhone.getExternalCallTracker() != null) {
1956
1957                    log("Call pull failed.");
1958                    // Call was being pulled, but the call pull has failed -- inform the associated
1959                    // TelephonyConnection that the pull failed, and provide it with the original
1960                    // external connection which was pulled so that it can be swapped back.
1961                    conn.onCallPullFailed(mPhone.getExternalCallTracker()
1962                            .getConnectionById(conn.getPulledDialogId()));
1963                    // Do not mark as disconnected; the call will just change from being a regular
1964                    // call to being an external call again.
1965                    cause = DisconnectCause.NOT_DISCONNECTED;
1966
1967                } else if (conn.isIncoming() && conn.getConnectTime() == 0
1968                        && cause != DisconnectCause.ANSWERED_ELSEWHERE) {
1969                    // Missed
1970                    if (cause == DisconnectCause.NORMAL) {
1971                        cause = DisconnectCause.INCOMING_MISSED;
1972                    } else {
1973                        cause = DisconnectCause.INCOMING_REJECTED;
1974                    }
1975                    if (DBG) log("Incoming connection of 0 connect time detected - translated " +
1976                            "cause = " + cause);
1977                }
1978            }
1979
1980            if (cause == DisconnectCause.NORMAL && conn != null && conn.getImsCall().isMerged()) {
1981                // Call was terminated while it is merged instead of a remote disconnect.
1982                cause = DisconnectCause.IMS_MERGED_SUCCESSFULLY;
1983            }
1984
1985            mMetrics.writeOnImsCallTerminated(mPhone.getPhoneId(), imsCall.getCallSession(),
1986                    reasonInfo);
1987
1988            if(conn != null) {
1989                conn.setPreciseDisconnectCause(getPreciseDisconnectCauseFromReasonInfo(reasonInfo));
1990            }
1991
1992            processCallStateChange(imsCall, ImsPhoneCall.State.DISCONNECTED, cause);
1993            if (mForegroundCall.getState() != ImsPhoneCall.State.ACTIVE) {
1994                if (mRingingCall.getState().isRinging()) {
1995                    // Drop pending MO. We should address incoming call first
1996                    mPendingMO = null;
1997                } else if (mPendingMO != null) {
1998                    sendEmptyMessage(EVENT_DIAL_PENDINGMO);
1999                }
2000            }
2001
2002            if (mSwitchingFgAndBgCalls) {
2003                if (DBG) {
2004                    log("onCallTerminated: Call terminated in the midst of Switching " +
2005                            "Fg and Bg calls.");
2006                }
2007                // If we are the in midst of swapping FG and BG calls and the call that was
2008                // terminated was the one that we expected to resume, we need to swap the FG and
2009                // BG calls back.
2010                if (imsCall == mCallExpectedToResume) {
2011                    if (DBG) {
2012                        log("onCallTerminated: switching " + mForegroundCall + " with "
2013                                + mBackgroundCall);
2014                    }
2015                    mForegroundCall.switchWith(mBackgroundCall);
2016                }
2017                // This call terminated in the midst of a switch after the other call was held, so
2018                // resume it back to ACTIVE state since the switch failed.
2019                log("onCallTerminated: foreground call in state " + mForegroundCall.getState() +
2020                        " and ringing call in state " + (mRingingCall == null ? "null" :
2021                        mRingingCall.getState().toString()));
2022
2023                if (mForegroundCall.getState() == ImsPhoneCall.State.HOLDING ||
2024                        mRingingCall.getState() == ImsPhoneCall.State.WAITING) {
2025                    sendEmptyMessage(EVENT_RESUME_BACKGROUND);
2026                    mSwitchingFgAndBgCalls = false;
2027                    mCallExpectedToResume = null;
2028                }
2029            }
2030
2031            if (mShouldUpdateImsConfigOnDisconnect) {
2032                // Ensure we update the IMS config when the call is disconnected; we delayed this
2033                // because a video call was paused.
2034                ImsManager.updateImsServiceConfig(mPhone.getContext(), mPhone.getPhoneId(), true);
2035                mShouldUpdateImsConfigOnDisconnect = false;
2036            }
2037        }
2038
2039        @Override
2040        public void onCallHeld(ImsCall imsCall) {
2041            if (DBG) {
2042                if (mForegroundCall.getImsCall() == imsCall) {
2043                    log("onCallHeld (fg) " + imsCall);
2044                } else if (mBackgroundCall.getImsCall() == imsCall) {
2045                    log("onCallHeld (bg) " + imsCall);
2046                }
2047            }
2048
2049            synchronized (mSyncHold) {
2050                ImsPhoneCall.State oldState = mBackgroundCall.getState();
2051                processCallStateChange(imsCall, ImsPhoneCall.State.HOLDING,
2052                        DisconnectCause.NOT_DISCONNECTED);
2053
2054                // Note: If we're performing a switchWaitingOrHoldingAndActive, the call to
2055                // processCallStateChange above may have caused the mBackgroundCall and
2056                // mForegroundCall references below to change meaning.  Watch out for this if you
2057                // are reading through this code.
2058                if (oldState == ImsPhoneCall.State.ACTIVE) {
2059                    // Note: This case comes up when we have just held a call in response to a
2060                    // switchWaitingOrHoldingAndActive.  We now need to resume the background call.
2061                    // The EVENT_RESUME_BACKGROUND causes resumeWaitingOrHolding to be called.
2062                    if ((mForegroundCall.getState() == ImsPhoneCall.State.HOLDING)
2063                            || (mRingingCall.getState() == ImsPhoneCall.State.WAITING)) {
2064                            sendEmptyMessage(EVENT_RESUME_BACKGROUND);
2065                    } else {
2066                        //when multiple connections belong to background call,
2067                        //only the first callback reaches here
2068                        //otherwise the oldState is already HOLDING
2069                        if (mPendingMO != null) {
2070                            dialPendingMO();
2071                        }
2072
2073                        // In this case there will be no call resumed, so we can assume that we
2074                        // are done switching fg and bg calls now.
2075                        // This may happen if there is no BG call and we are holding a call so that
2076                        // we can dial another one.
2077                        mSwitchingFgAndBgCalls = false;
2078                    }
2079                } else if (oldState == ImsPhoneCall.State.IDLE && mSwitchingFgAndBgCalls) {
2080                    // The other call terminated in the midst of a switch before this call was held,
2081                    // so resume the foreground call back to ACTIVE state since the switch failed.
2082                    if (mForegroundCall.getState() == ImsPhoneCall.State.HOLDING) {
2083                        sendEmptyMessage(EVENT_RESUME_BACKGROUND);
2084                        mSwitchingFgAndBgCalls = false;
2085                        mCallExpectedToResume = null;
2086                    }
2087                }
2088            }
2089            mMetrics.writeOnImsCallHeld(mPhone.getPhoneId(), imsCall.getCallSession());
2090        }
2091
2092        @Override
2093        public void onCallHoldFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
2094            if (DBG) log("onCallHoldFailed reasonCode=" + reasonInfo.getCode());
2095
2096            synchronized (mSyncHold) {
2097                ImsPhoneCall.State bgState = mBackgroundCall.getState();
2098                if (reasonInfo.getCode() == ImsReasonInfo.CODE_LOCAL_CALL_TERMINATED) {
2099                    // disconnected while processing hold
2100                    if (mPendingMO != null) {
2101                        dialPendingMO();
2102                    }
2103                } else if (bgState == ImsPhoneCall.State.ACTIVE) {
2104                    mForegroundCall.switchWith(mBackgroundCall);
2105
2106                    if (mPendingMO != null) {
2107                        mPendingMO.setDisconnectCause(DisconnectCause.ERROR_UNSPECIFIED);
2108                        sendEmptyMessageDelayed(EVENT_HANGUP_PENDINGMO, TIMEOUT_HANGUP_PENDINGMO);
2109                    }
2110                }
2111                mPhone.notifySuppServiceFailed(Phone.SuppService.HOLD);
2112            }
2113            mMetrics.writeOnImsCallHoldFailed(mPhone.getPhoneId(), imsCall.getCallSession(),
2114                    reasonInfo);
2115        }
2116
2117        @Override
2118        public void onCallResumed(ImsCall imsCall) {
2119            if (DBG) log("onCallResumed");
2120
2121            // If we are the in midst of swapping FG and BG calls and the call we end up resuming
2122            // is not the one we expected, we likely had a resume failure and we need to swap the
2123            // FG and BG calls back.
2124            if (mSwitchingFgAndBgCalls) {
2125                if (imsCall != mCallExpectedToResume) {
2126                    // If the call which resumed isn't as expected, we need to swap back to the
2127                    // previous configuration; the swap has failed.
2128                    if (DBG) {
2129                        log("onCallResumed : switching " + mForegroundCall + " with "
2130                                + mBackgroundCall);
2131                    }
2132                    mForegroundCall.switchWith(mBackgroundCall);
2133                } else {
2134                    // The call which resumed is the one we expected to resume, so we can clear out
2135                    // the mSwitchingFgAndBgCalls flag.
2136                    if (DBG) {
2137                        log("onCallResumed : expected call resumed.");
2138                    }
2139                }
2140                mSwitchingFgAndBgCalls = false;
2141                mCallExpectedToResume = null;
2142            }
2143            processCallStateChange(imsCall, ImsPhoneCall.State.ACTIVE,
2144                    DisconnectCause.NOT_DISCONNECTED);
2145            mMetrics.writeOnImsCallResumed(mPhone.getPhoneId(), imsCall.getCallSession());
2146        }
2147
2148        @Override
2149        public void onCallResumeFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
2150            if (mSwitchingFgAndBgCalls) {
2151                // If we are in the midst of swapping the FG and BG calls and
2152                // we got a resume fail, we need to swap back the FG and BG calls.
2153                // Since the FG call was held, will also try to resume the same.
2154                if (imsCall == mCallExpectedToResume) {
2155                    if (DBG) {
2156                        log("onCallResumeFailed : switching " + mForegroundCall + " with "
2157                                + mBackgroundCall);
2158                    }
2159                    mForegroundCall.switchWith(mBackgroundCall);
2160                    if (mForegroundCall.getState() == ImsPhoneCall.State.HOLDING) {
2161                            sendEmptyMessage(EVENT_RESUME_BACKGROUND);
2162                    }
2163                }
2164
2165                //Call swap is done, reset the relevant variables
2166                mCallExpectedToResume = null;
2167                mSwitchingFgAndBgCalls = false;
2168            }
2169            mPhone.notifySuppServiceFailed(Phone.SuppService.RESUME);
2170            mMetrics.writeOnImsCallResumeFailed(mPhone.getPhoneId(), imsCall.getCallSession(),
2171                    reasonInfo);
2172        }
2173
2174        @Override
2175        public void onCallResumeReceived(ImsCall imsCall) {
2176            if (DBG) log("onCallResumeReceived");
2177            ImsPhoneConnection conn = findConnection(imsCall);
2178            if (conn != null) {
2179                if (mOnHoldToneStarted) {
2180                    mPhone.stopOnHoldTone(conn);
2181                    mOnHoldToneStarted = false;
2182                }
2183
2184                conn.onConnectionEvent(android.telecom.Connection.EVENT_CALL_REMOTELY_UNHELD, null);
2185            }
2186
2187            SuppServiceNotification supp = new SuppServiceNotification();
2188            // Type of notification: 0 = MO; 1 = MT
2189            // Refer SuppServiceNotification class documentation.
2190            supp.notificationType = 1;
2191            supp.code = SuppServiceNotification.MT_CODE_CALL_RETRIEVED;
2192            mPhone.notifySuppSvcNotification(supp);
2193            mMetrics.writeOnImsCallResumeReceived(mPhone.getPhoneId(), imsCall.getCallSession());
2194        }
2195
2196        @Override
2197        public void onCallHoldReceived(ImsCall imsCall) {
2198            if (DBG) log("onCallHoldReceived");
2199
2200            ImsPhoneConnection conn = findConnection(imsCall);
2201            if (conn != null) {
2202                if (!mOnHoldToneStarted && ImsPhoneCall.isLocalTone(imsCall) &&
2203                        conn.getState() == ImsPhoneCall.State.ACTIVE) {
2204                    mPhone.startOnHoldTone(conn);
2205                    mOnHoldToneStarted = true;
2206                    mOnHoldToneId = System.identityHashCode(conn);
2207                }
2208
2209                conn.onConnectionEvent(android.telecom.Connection.EVENT_CALL_REMOTELY_HELD, null);
2210            }
2211
2212            SuppServiceNotification supp = new SuppServiceNotification();
2213            // Type of notification: 0 = MO; 1 = MT
2214            // Refer SuppServiceNotification class documentation.
2215            supp.notificationType = 1;
2216            supp.code = SuppServiceNotification.MT_CODE_CALL_ON_HOLD;
2217            mPhone.notifySuppSvcNotification(supp);
2218            mMetrics.writeOnImsCallHoldReceived(mPhone.getPhoneId(), imsCall.getCallSession());
2219        }
2220
2221        @Override
2222        public void onCallSuppServiceReceived(ImsCall call,
2223                ImsSuppServiceNotification suppServiceInfo) {
2224            if (DBG) log("onCallSuppServiceReceived: suppServiceInfo=" + suppServiceInfo);
2225
2226            SuppServiceNotification supp = new SuppServiceNotification();
2227            supp.notificationType = suppServiceInfo.notificationType;
2228            supp.code = suppServiceInfo.code;
2229            supp.index = suppServiceInfo.index;
2230            supp.number = suppServiceInfo.number;
2231            supp.history = suppServiceInfo.history;
2232
2233            mPhone.notifySuppSvcNotification(supp);
2234        }
2235
2236        @Override
2237        public void onCallMerged(final ImsCall call, final ImsCall peerCall, boolean swapCalls) {
2238            if (DBG) log("onCallMerged");
2239
2240            ImsPhoneCall foregroundImsPhoneCall = findConnection(call).getCall();
2241            ImsPhoneConnection peerConnection = findConnection(peerCall);
2242            ImsPhoneCall peerImsPhoneCall = peerConnection == null ? null
2243                    : peerConnection.getCall();
2244
2245            if (swapCalls) {
2246                switchAfterConferenceSuccess();
2247            }
2248            foregroundImsPhoneCall.merge(peerImsPhoneCall, ImsPhoneCall.State.ACTIVE);
2249
2250            try {
2251                final ImsPhoneConnection conn = findConnection(call);
2252                log("onCallMerged: ImsPhoneConnection=" + conn);
2253                log("onCallMerged: CurrentVideoProvider=" + conn.getVideoProvider());
2254                setVideoCallProvider(conn, call);
2255                log("onCallMerged: CurrentVideoProvider=" + conn.getVideoProvider());
2256            } catch (Exception e) {
2257                loge("onCallMerged: exception " + e);
2258            }
2259
2260            // After merge complete, update foreground as Active
2261            // and background call as Held, if background call exists
2262            processCallStateChange(mForegroundCall.getImsCall(), ImsPhoneCall.State.ACTIVE,
2263                    DisconnectCause.NOT_DISCONNECTED);
2264            if (peerConnection != null) {
2265                processCallStateChange(mBackgroundCall.getImsCall(), ImsPhoneCall.State.HOLDING,
2266                    DisconnectCause.NOT_DISCONNECTED);
2267            }
2268
2269            // Check if the merge was requested by an existing conference call. In that
2270            // case, no further action is required.
2271            if (!call.isMergeRequestedByConf()) {
2272                log("onCallMerged :: calling onMultipartyStateChanged()");
2273                onMultipartyStateChanged(call, true);
2274            } else {
2275                log("onCallMerged :: Merge requested by existing conference.");
2276                // Reset the flag.
2277                call.resetIsMergeRequestedByConf(false);
2278            }
2279            logState();
2280        }
2281
2282        @Override
2283        public void onCallMergeFailed(ImsCall call, ImsReasonInfo reasonInfo) {
2284            if (DBG) log("onCallMergeFailed reasonInfo=" + reasonInfo);
2285
2286            // TODO: the call to notifySuppServiceFailed throws up the "merge failed" dialog
2287            // We should move this into the InCallService so that it is handled appropriately
2288            // based on the user facing UI.
2289            mPhone.notifySuppServiceFailed(Phone.SuppService.CONFERENCE);
2290
2291            // Start plumbing this even through Telecom so other components can take
2292            // appropriate action.
2293            ImsPhoneConnection conn = findConnection(call);
2294            if (conn != null) {
2295                conn.onConferenceMergeFailed();
2296            }
2297        }
2298
2299        /**
2300         * Called when the state of IMS conference participant(s) has changed.
2301         *
2302         * @param call the call object that carries out the IMS call.
2303         * @param participants the participant(s) and their new state information.
2304         */
2305        @Override
2306        public void onConferenceParticipantsStateChanged(ImsCall call,
2307                List<ConferenceParticipant> participants) {
2308            if (DBG) log("onConferenceParticipantsStateChanged");
2309
2310            ImsPhoneConnection conn = findConnection(call);
2311            if (conn != null) {
2312                conn.updateConferenceParticipants(participants);
2313            }
2314        }
2315
2316        @Override
2317        public void onCallSessionTtyModeReceived(ImsCall call, int mode) {
2318            mPhone.onTtyModeReceived(mode);
2319        }
2320
2321        @Override
2322        public void onCallHandover(ImsCall imsCall, int srcAccessTech, int targetAccessTech,
2323            ImsReasonInfo reasonInfo) {
2324            if (DBG) {
2325                log("onCallHandover ::  srcAccessTech=" + srcAccessTech + ", targetAccessTech=" +
2326                    targetAccessTech + ", reasonInfo=" + reasonInfo);
2327            }
2328
2329            boolean isHandoverToWifi = srcAccessTech != ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN &&
2330                    targetAccessTech == ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN;
2331            if (isHandoverToWifi) {
2332                // If we handed over to wifi successfully, don't check for failure in the future.
2333                removeMessages(EVENT_CHECK_FOR_WIFI_HANDOVER);
2334            }
2335
2336            boolean isHandoverFromWifi =
2337                    srcAccessTech == ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN &&
2338                            targetAccessTech != ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN;
2339            if (mNotifyHandoverVideoFromWifiToLTE && isHandoverFromWifi && imsCall.isVideoCall()) {
2340                log("onCallHandover :: notifying of WIFI to LTE handover.");
2341                ImsPhoneConnection conn = findConnection(imsCall);
2342                if (conn != null) {
2343                    conn.onConnectionEvent(
2344                            TelephonyManager.EVENT_HANDOVER_VIDEO_FROM_WIFI_TO_LTE, null);
2345                } else {
2346                    loge("onCallHandover :: failed to notify of handover; connection is null.");
2347                }
2348            }
2349
2350            mMetrics.writeOnImsCallHandoverEvent(mPhone.getPhoneId(),
2351                    TelephonyCallSession.Event.Type.IMS_CALL_HANDOVER, imsCall.getCallSession(),
2352                    srcAccessTech, targetAccessTech, reasonInfo);
2353        }
2354
2355        @Override
2356        public void onCallHandoverFailed(ImsCall imsCall, int srcAccessTech, int targetAccessTech,
2357            ImsReasonInfo reasonInfo) {
2358            if (DBG) {
2359                log("onCallHandoverFailed :: srcAccessTech=" + srcAccessTech +
2360                    ", targetAccessTech=" + targetAccessTech + ", reasonInfo=" + reasonInfo);
2361            }
2362            mMetrics.writeOnImsCallHandoverEvent(mPhone.getPhoneId(),
2363                    TelephonyCallSession.Event.Type.IMS_CALL_HANDOVER_FAILED,
2364                    imsCall.getCallSession(), srcAccessTech, targetAccessTech, reasonInfo);
2365
2366            boolean isHandoverToWifi = srcAccessTech != ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN &&
2367                    targetAccessTech == ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN;
2368            ImsPhoneConnection conn = findConnection(imsCall);
2369            if (conn != null && isHandoverToWifi) {
2370                log("onCallHandoverFailed - handover to WIFI Failed");
2371
2372                // If we know we failed to handover, don't check for failure in the future.
2373                removeMessages(EVENT_CHECK_FOR_WIFI_HANDOVER);
2374
2375                if (mNotifyVtHandoverToWifiFail) {
2376                    // Only notify others if carrier config indicates to do so.
2377                    conn.onHandoverToWifiFailed();
2378                }
2379            }
2380        }
2381
2382        /**
2383         * Handles a change to the multiparty state for an {@code ImsCall}.  Notifies the associated
2384         * {@link ImsPhoneConnection} of the change.
2385         *
2386         * @param imsCall The IMS call.
2387         * @param isMultiParty {@code true} if the call became multiparty, {@code false}
2388         *      otherwise.
2389         */
2390        @Override
2391        public void onMultipartyStateChanged(ImsCall imsCall, boolean isMultiParty) {
2392            if (DBG) log("onMultipartyStateChanged to " + (isMultiParty ? "Y" : "N"));
2393
2394            ImsPhoneConnection conn = findConnection(imsCall);
2395            if (conn != null) {
2396                conn.updateMultipartyState(isMultiParty);
2397            }
2398        }
2399    };
2400
2401    /**
2402     * Listen to the IMS call state change
2403     */
2404    private ImsCall.Listener mImsUssdListener = new ImsCall.Listener() {
2405        @Override
2406        public void onCallStarted(ImsCall imsCall) {
2407            if (DBG) log("mImsUssdListener onCallStarted");
2408
2409            if (imsCall == mUssdSession) {
2410                if (mPendingUssd != null) {
2411                    AsyncResult.forMessage(mPendingUssd);
2412                    mPendingUssd.sendToTarget();
2413                    mPendingUssd = null;
2414                }
2415            }
2416        }
2417
2418        @Override
2419        public void onCallStartFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
2420            if (DBG) log("mImsUssdListener onCallStartFailed reasonCode=" + reasonInfo.getCode());
2421
2422            onCallTerminated(imsCall, reasonInfo);
2423        }
2424
2425        @Override
2426        public void onCallTerminated(ImsCall imsCall, ImsReasonInfo reasonInfo) {
2427            if (DBG) log("mImsUssdListener onCallTerminated reasonCode=" + reasonInfo.getCode());
2428            removeMessages(EVENT_CHECK_FOR_WIFI_HANDOVER);
2429
2430            if (imsCall == mUssdSession) {
2431                mUssdSession = null;
2432                if (mPendingUssd != null) {
2433                    CommandException ex =
2434                            new CommandException(CommandException.Error.GENERIC_FAILURE);
2435                    AsyncResult.forMessage(mPendingUssd, null, ex);
2436                    mPendingUssd.sendToTarget();
2437                    mPendingUssd = null;
2438                }
2439            }
2440            imsCall.close();
2441        }
2442
2443        @Override
2444        public void onCallUssdMessageReceived(ImsCall call,
2445                int mode, String ussdMessage) {
2446            if (DBG) log("mImsUssdListener onCallUssdMessageReceived mode=" + mode);
2447
2448            int ussdMode = -1;
2449
2450            switch(mode) {
2451                case ImsCall.USSD_MODE_REQUEST:
2452                    ussdMode = CommandsInterface.USSD_MODE_REQUEST;
2453                    break;
2454
2455                case ImsCall.USSD_MODE_NOTIFY:
2456                    ussdMode = CommandsInterface.USSD_MODE_NOTIFY;
2457                    break;
2458            }
2459
2460            mPhone.onIncomingUSSD(ussdMode, ussdMessage);
2461        }
2462    };
2463
2464    /**
2465     * Listen to the IMS service state change
2466     *
2467     */
2468    private ImsConnectionStateListener mImsConnectionStateListener =
2469        new ImsConnectionStateListener() {
2470        @Override
2471        public void onImsConnected(int imsRadioTech) {
2472            if (DBG) log("onImsConnected imsRadioTech=" + imsRadioTech);
2473            mPhone.setServiceState(ServiceState.STATE_IN_SERVICE);
2474            mPhone.setImsRegistered(true);
2475            mMetrics.writeOnImsConnectionState(mPhone.getPhoneId(),
2476                    ImsConnectionState.State.CONNECTED, null);
2477        }
2478
2479        @Override
2480        public void onImsDisconnected(ImsReasonInfo imsReasonInfo) {
2481            if (DBG) log("onImsDisconnected imsReasonInfo=" + imsReasonInfo);
2482            mPhone.setServiceState(ServiceState.STATE_OUT_OF_SERVICE);
2483            mPhone.setImsRegistered(false);
2484            mPhone.processDisconnectReason(imsReasonInfo);
2485            mMetrics.writeOnImsConnectionState(mPhone.getPhoneId(),
2486                    ImsConnectionState.State.DISCONNECTED, imsReasonInfo);
2487        }
2488
2489        @Override
2490        public void onImsProgressing(int imsRadioTech) {
2491            if (DBG) log("onImsProgressing imsRadioTech=" + imsRadioTech);
2492            mPhone.setServiceState(ServiceState.STATE_OUT_OF_SERVICE);
2493            mPhone.setImsRegistered(false);
2494            mMetrics.writeOnImsConnectionState(mPhone.getPhoneId(),
2495                    ImsConnectionState.State.PROGRESSING, null);
2496        }
2497
2498        @Override
2499        public void onImsResumed() {
2500            if (DBG) log("onImsResumed");
2501            mPhone.setServiceState(ServiceState.STATE_IN_SERVICE);
2502            mMetrics.writeOnImsConnectionState(mPhone.getPhoneId(),
2503                    ImsConnectionState.State.RESUMED, null);
2504        }
2505
2506        @Override
2507        public void onImsSuspended() {
2508            if (DBG) log("onImsSuspended");
2509            mPhone.setServiceState(ServiceState.STATE_OUT_OF_SERVICE);
2510            mMetrics.writeOnImsConnectionState(mPhone.getPhoneId(),
2511                    ImsConnectionState.State.SUSPENDED, null);
2512
2513        }
2514
2515        @Override
2516        public void onFeatureCapabilityChanged(int serviceClass,
2517                int[] enabledFeatures, int[] disabledFeatures) {
2518            if (serviceClass == ImsServiceClass.MMTEL) {
2519                boolean tmpIsVideoCallEnabled = isVideoCallEnabled();
2520                // Check enabledFeatures to determine capabilities. We ignore disabledFeatures.
2521                StringBuilder sb;
2522                if (DBG) {
2523                    sb = new StringBuilder(120);
2524                    sb.append("onFeatureCapabilityChanged: ");
2525                }
2526                for (int  i = ImsConfig.FeatureConstants.FEATURE_TYPE_VOICE_OVER_LTE;
2527                        i <= ImsConfig.FeatureConstants.FEATURE_TYPE_UT_OVER_WIFI &&
2528                        i < enabledFeatures.length; i++) {
2529                    if (enabledFeatures[i] == i) {
2530                        // If the feature is set to its own integer value it is enabled.
2531                        if (DBG) {
2532                            sb.append(mImsFeatureStrings[i]);
2533                            sb.append(":true ");
2534                        }
2535
2536                        mImsFeatureEnabled[i] = true;
2537                    } else if (enabledFeatures[i]
2538                            == ImsConfig.FeatureConstants.FEATURE_TYPE_UNKNOWN) {
2539                        // FEATURE_TYPE_UNKNOWN indicates that a feature is disabled.
2540                        if (DBG) {
2541                            sb.append(mImsFeatureStrings[i]);
2542                            sb.append(":false ");
2543                        }
2544
2545                        mImsFeatureEnabled[i] = false;
2546                    } else {
2547                        // Feature has unknown state; it is not its own value or -1.
2548                        if (DBG) {
2549                            loge("onFeatureCapabilityChanged(" + i + ", " + mImsFeatureStrings[i]
2550                                    + "): unexpectedValue=" + enabledFeatures[i]);
2551                        }
2552                    }
2553                }
2554                if (DBG) {
2555                    log(sb.toString());
2556                }
2557                if (tmpIsVideoCallEnabled != isVideoCallEnabled()) {
2558                    mPhone.notifyForVideoCapabilityChanged(isVideoCallEnabled());
2559                }
2560
2561                if (DBG) log("onFeatureCapabilityChanged: isVolteEnabled=" + isVolteEnabled()
2562                            + ", isVideoCallEnabled=" + isVideoCallEnabled()
2563                            + ", isVowifiEnabled=" + isVowifiEnabled()
2564                            + ", isUtEnabled=" + isUtEnabled());
2565
2566                mPhone.onFeatureCapabilityChanged();
2567
2568                mMetrics.writeOnImsCapabilities(
2569                        mPhone.getPhoneId(), mImsFeatureEnabled);
2570            }
2571        }
2572
2573        @Override
2574        public void onVoiceMessageCountChanged(int count) {
2575            if (DBG) log("onVoiceMessageCountChanged :: count=" + count);
2576            mPhone.mDefaultPhone.setVoiceMessageCount(count);
2577        }
2578
2579        @Override
2580        public void registrationAssociatedUriChanged(Uri[] uris) {
2581            if (DBG) log("registrationAssociatedUriChanged");
2582            mPhone.setCurrentSubscriberUris(uris);
2583        }
2584    };
2585
2586    private ImsConfigListener.Stub mImsConfigListener = new ImsConfigListener.Stub() {
2587        @Override
2588        public void onGetFeatureResponse(int feature, int network, int value, int status) {}
2589
2590        @Override
2591        public void onSetFeatureResponse(int feature, int network, int value, int status) {
2592            mMetrics.writeImsSetFeatureValue(
2593                    mPhone.getPhoneId(), feature, network, value, status);
2594        }
2595
2596        @Override
2597        public void onGetVideoQuality(int status, int quality) {}
2598
2599        @Override
2600        public void onSetVideoQuality(int status) {}
2601
2602    };
2603
2604    public ImsUtInterface getUtInterface() throws ImsException {
2605        if (mImsManager == null) {
2606            throw getImsManagerIsNullException();
2607        }
2608
2609        ImsUtInterface ut = mImsManager.getSupplementaryServiceConfiguration();
2610        return ut;
2611    }
2612
2613    private void transferHandoverConnections(ImsPhoneCall call) {
2614        if (call.mConnections != null) {
2615            for (Connection c : call.mConnections) {
2616                c.mPreHandoverState = call.mState;
2617                log ("Connection state before handover is " + c.getStateBeforeHandover());
2618            }
2619        }
2620        if (mHandoverCall.mConnections == null ) {
2621            mHandoverCall.mConnections = call.mConnections;
2622        } else { // Multi-call SRVCC
2623            mHandoverCall.mConnections.addAll(call.mConnections);
2624        }
2625        if (mHandoverCall.mConnections != null) {
2626            if (call.getImsCall() != null) {
2627                call.getImsCall().close();
2628            }
2629            for (Connection c : mHandoverCall.mConnections) {
2630                ((ImsPhoneConnection)c).changeParent(mHandoverCall);
2631                ((ImsPhoneConnection)c).releaseWakeLock();
2632            }
2633        }
2634        if (call.getState().isAlive()) {
2635            log ("Call is alive and state is " + call.mState);
2636            mHandoverCall.mState = call.mState;
2637        }
2638        call.mConnections.clear();
2639        call.mState = ImsPhoneCall.State.IDLE;
2640    }
2641
2642    /* package */
2643    void notifySrvccState(Call.SrvccState state) {
2644        if (DBG) log("notifySrvccState state=" + state);
2645
2646        mSrvccState = state;
2647
2648        if (mSrvccState == Call.SrvccState.COMPLETED) {
2649            transferHandoverConnections(mForegroundCall);
2650            transferHandoverConnections(mBackgroundCall);
2651            transferHandoverConnections(mRingingCall);
2652        }
2653    }
2654
2655    //****** Overridden from Handler
2656
2657    @Override
2658    public void
2659    handleMessage (Message msg) {
2660        AsyncResult ar;
2661        if (DBG) log("handleMessage what=" + msg.what);
2662
2663        switch (msg.what) {
2664            case EVENT_HANGUP_PENDINGMO:
2665                if (mPendingMO != null) {
2666                    mPendingMO.onDisconnect();
2667                    removeConnection(mPendingMO);
2668                    mPendingMO = null;
2669                }
2670                mPendingIntentExtras = null;
2671                updatePhoneState();
2672                mPhone.notifyPreciseCallStateChanged();
2673                break;
2674            case EVENT_RESUME_BACKGROUND:
2675                try {
2676                    resumeWaitingOrHolding();
2677                } catch (CallStateException e) {
2678                    if (Phone.DEBUG_PHONE) {
2679                        loge("handleMessage EVENT_RESUME_BACKGROUND exception=" + e);
2680                    }
2681                }
2682                break;
2683            case EVENT_DIAL_PENDINGMO:
2684                dialInternal(mPendingMO, mClirMode, mPendingCallVideoState, mPendingIntentExtras);
2685                mPendingIntentExtras = null;
2686                break;
2687
2688            case EVENT_EXIT_ECBM_BEFORE_PENDINGMO:
2689                if (mPendingMO != null) {
2690                    //Send ECBM exit request
2691                    try {
2692                        getEcbmInterface().exitEmergencyCallbackMode();
2693                        mPhone.setOnEcbModeExitResponse(this, EVENT_EXIT_ECM_RESPONSE_CDMA, null);
2694                        pendingCallClirMode = mClirMode;
2695                        pendingCallInEcm = true;
2696                    } catch (ImsException e) {
2697                        e.printStackTrace();
2698                        mPendingMO.setDisconnectCause(DisconnectCause.ERROR_UNSPECIFIED);
2699                        sendEmptyMessageDelayed(EVENT_HANGUP_PENDINGMO, TIMEOUT_HANGUP_PENDINGMO);
2700                    }
2701                }
2702                break;
2703
2704            case EVENT_EXIT_ECM_RESPONSE_CDMA:
2705                // no matter the result, we still do the same here
2706                if (pendingCallInEcm) {
2707                    dialInternal(mPendingMO, pendingCallClirMode,
2708                            mPendingCallVideoState, mPendingIntentExtras);
2709                    mPendingIntentExtras = null;
2710                    pendingCallInEcm = false;
2711                }
2712                mPhone.unsetOnEcbModeExitResponse(this);
2713                break;
2714            case EVENT_VT_DATA_USAGE_UPDATE:
2715                ar = (AsyncResult) msg.obj;
2716                ImsCall call = (ImsCall) ar.userObj;
2717                Long usage = (long) ar.result;
2718                log("VT data usage update. usage = " + usage + ", imsCall = " + call);
2719
2720                Long oldUsage = 0L;
2721                if (mVtDataUsageMap.containsKey(call.uniqueId)) {
2722                    oldUsage = mVtDataUsageMap.get(call.uniqueId);
2723                }
2724                mTotalVtDataUsage += (usage - oldUsage);
2725                mVtDataUsageMap.put(call.uniqueId, usage);
2726                break;
2727            case EVENT_DATA_ENABLED_CHANGED:
2728                ar = (AsyncResult) msg.obj;
2729                if (ar.result instanceof Pair) {
2730                    Pair<Boolean, Integer> p = (Pair<Boolean, Integer>) ar.result;
2731                    onDataEnabledChanged(p.first, p.second);
2732                }
2733                break;
2734            case EVENT_GET_IMS_SERVICE:
2735                try {
2736                    getImsService();
2737                } catch (ImsException e) {
2738                    loge("getImsService: " + e);
2739                    retryGetImsService();
2740                }
2741                break;
2742            case EVENT_CHECK_FOR_WIFI_HANDOVER:
2743                if (msg.obj instanceof ImsCall) {
2744                    ImsCall imsCall = (ImsCall) msg.obj;
2745                    if (!imsCall.isWifiCall()) {
2746                        // Call did not handover to wifi, notify of handover failure.
2747                        ImsPhoneConnection conn = findConnection(imsCall);
2748                        if (conn != null) {
2749                            conn.onHandoverToWifiFailed();
2750                        }
2751                    }
2752                }
2753                break;
2754        }
2755    }
2756
2757    @Override
2758    protected void log(String msg) {
2759        Rlog.d(LOG_TAG, "[ImsPhoneCallTracker] " + msg);
2760    }
2761
2762    protected void loge(String msg) {
2763        Rlog.e(LOG_TAG, "[ImsPhoneCallTracker] " + msg);
2764    }
2765
2766    /**
2767     * Logs the current state of the ImsPhoneCallTracker.  Useful for debugging issues with
2768     * call tracking.
2769     */
2770    /* package */
2771    void logState() {
2772        if (!VERBOSE_STATE_LOGGING) {
2773            return;
2774        }
2775
2776        StringBuilder sb = new StringBuilder();
2777        sb.append("Current IMS PhoneCall State:\n");
2778        sb.append(" Foreground: ");
2779        sb.append(mForegroundCall);
2780        sb.append("\n");
2781        sb.append(" Background: ");
2782        sb.append(mBackgroundCall);
2783        sb.append("\n");
2784        sb.append(" Ringing: ");
2785        sb.append(mRingingCall);
2786        sb.append("\n");
2787        sb.append(" Handover: ");
2788        sb.append(mHandoverCall);
2789        sb.append("\n");
2790        Rlog.v(LOG_TAG, sb.toString());
2791    }
2792
2793    @Override
2794    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2795        pw.println("ImsPhoneCallTracker extends:");
2796        super.dump(fd, pw, args);
2797        pw.println(" mVoiceCallEndedRegistrants=" + mVoiceCallEndedRegistrants);
2798        pw.println(" mVoiceCallStartedRegistrants=" + mVoiceCallStartedRegistrants);
2799        pw.println(" mRingingCall=" + mRingingCall);
2800        pw.println(" mForegroundCall=" + mForegroundCall);
2801        pw.println(" mBackgroundCall=" + mBackgroundCall);
2802        pw.println(" mHandoverCall=" + mHandoverCall);
2803        pw.println(" mPendingMO=" + mPendingMO);
2804        //pw.println(" mHangupPendingMO=" + mHangupPendingMO);
2805        pw.println(" mPhone=" + mPhone);
2806        pw.println(" mDesiredMute=" + mDesiredMute);
2807        pw.println(" mState=" + mState);
2808        for (int i = 0; i < mImsFeatureEnabled.length; i++) {
2809            pw.println(" " + mImsFeatureStrings[i] + ": "
2810                    + ((mImsFeatureEnabled[i]) ? "enabled" : "disabled"));
2811        }
2812        pw.println(" mTotalVtDataUsage=" + mTotalVtDataUsage);
2813        for (Map.Entry<Integer, Long> entry : mVtDataUsageMap.entrySet()) {
2814            pw.println("    id=" + entry.getKey() + " ,usage=" + entry.getValue());
2815        }
2816
2817        pw.flush();
2818        pw.println("++++++++++++++++++++++++++++++++");
2819
2820        try {
2821            if (mImsManager != null) {
2822                mImsManager.dump(fd, pw, args);
2823            }
2824        } catch (Exception e) {
2825            e.printStackTrace();
2826        }
2827
2828        if (mConnections != null && mConnections.size() > 0) {
2829            pw.println("mConnections:");
2830            for (int i = 0; i < mConnections.size(); i++) {
2831                pw.println("  [" + i + "]: " + mConnections.get(i));
2832            }
2833        }
2834    }
2835
2836    @Override
2837    protected void handlePollCalls(AsyncResult ar) {
2838    }
2839
2840    /* package */
2841    ImsEcbm getEcbmInterface() throws ImsException {
2842        if (mImsManager == null) {
2843            throw getImsManagerIsNullException();
2844        }
2845
2846        ImsEcbm ecbm = mImsManager.getEcbmInterface(mServiceId);
2847        return ecbm;
2848    }
2849
2850    /* package */
2851    ImsMultiEndpoint getMultiEndpointInterface() throws ImsException {
2852        if (mImsManager == null) {
2853            throw getImsManagerIsNullException();
2854        }
2855
2856        try {
2857            return mImsManager.getMultiEndpointInterface(mServiceId);
2858        } catch (ImsException e) {
2859            if (e.getCode() == ImsReasonInfo.CODE_MULTIENDPOINT_NOT_SUPPORTED) {
2860                return null;
2861            } else {
2862                throw e;
2863            }
2864
2865        }
2866    }
2867
2868    public boolean isInEmergencyCall() {
2869        return mIsInEmergencyCall;
2870    }
2871
2872    public boolean isVolteEnabled() {
2873        return mImsFeatureEnabled[ImsConfig.FeatureConstants.FEATURE_TYPE_VOICE_OVER_LTE];
2874    }
2875
2876    public boolean isVowifiEnabled() {
2877        return mImsFeatureEnabled[ImsConfig.FeatureConstants.FEATURE_TYPE_VOICE_OVER_WIFI];
2878    }
2879
2880    public boolean isVideoCallEnabled() {
2881        return (mImsFeatureEnabled[ImsConfig.FeatureConstants.FEATURE_TYPE_VIDEO_OVER_LTE]
2882                || mImsFeatureEnabled[ImsConfig.FeatureConstants.FEATURE_TYPE_VIDEO_OVER_WIFI]);
2883    }
2884
2885    @Override
2886    public PhoneConstants.State getState() {
2887        return mState;
2888    }
2889
2890    private void retryGetImsService() {
2891        // The binder connection is already up. Do not try to get it again.
2892        if (mImsManager.isServiceAvailable()) {
2893            return;
2894        }
2895        //Leave mImsManager as null, then CallStateException will be thrown when dialing
2896        mImsManager = null;
2897        // Exponential backoff during retry, limited to 32 seconds.
2898        loge("getImsService: Retrying getting ImsService...");
2899        removeMessages(EVENT_GET_IMS_SERVICE);
2900        sendEmptyMessageDelayed(EVENT_GET_IMS_SERVICE, mRetryTimeout.get());
2901    }
2902
2903    private void setVideoCallProvider(ImsPhoneConnection conn, ImsCall imsCall)
2904            throws RemoteException {
2905        IImsVideoCallProvider imsVideoCallProvider =
2906                imsCall.getCallSession().getVideoCallProvider();
2907        if (imsVideoCallProvider != null) {
2908            ImsVideoCallProviderWrapper imsVideoCallProviderWrapper =
2909                    new ImsVideoCallProviderWrapper(imsVideoCallProvider);
2910            conn.setVideoProvider(imsVideoCallProviderWrapper);
2911            imsVideoCallProviderWrapper.registerForDataUsageUpdate
2912                    (this, EVENT_VT_DATA_USAGE_UPDATE, imsCall);
2913            imsVideoCallProviderWrapper.addImsVideoProviderCallback(conn);
2914        }
2915    }
2916
2917    public boolean isUtEnabled() {
2918        return (mImsFeatureEnabled[ImsConfig.FeatureConstants.FEATURE_TYPE_UT_OVER_LTE]
2919            || mImsFeatureEnabled[ImsConfig.FeatureConstants.FEATURE_TYPE_UT_OVER_WIFI]);
2920    }
2921
2922    /**
2923     * Given a call subject, removes any characters considered by the current carrier to be
2924     * invalid, as well as escaping (using \) any characters which the carrier requires to be
2925     * escaped.
2926     *
2927     * @param callSubject The call subject.
2928     * @return The call subject with invalid characters removed and escaping applied as required.
2929     */
2930    private String cleanseInstantLetteringMessage(String callSubject) {
2931        if (TextUtils.isEmpty(callSubject)) {
2932            return callSubject;
2933        }
2934
2935        // Get the carrier config for the current sub.
2936        CarrierConfigManager configMgr = (CarrierConfigManager)
2937                mPhone.getContext().getSystemService(Context.CARRIER_CONFIG_SERVICE);
2938        // Bail if we can't find the carrier config service.
2939        if (configMgr == null) {
2940            return callSubject;
2941        }
2942
2943        PersistableBundle carrierConfig = configMgr.getConfigForSubId(mPhone.getSubId());
2944        // Bail if no carrier config found.
2945        if (carrierConfig == null) {
2946            return callSubject;
2947        }
2948
2949        // Try to replace invalid characters
2950        String invalidCharacters = carrierConfig.getString(
2951                CarrierConfigManager.KEY_CARRIER_INSTANT_LETTERING_INVALID_CHARS_STRING);
2952        if (!TextUtils.isEmpty(invalidCharacters)) {
2953            callSubject = callSubject.replaceAll(invalidCharacters, "");
2954        }
2955
2956        // Try to escape characters which need to be escaped.
2957        String escapedCharacters = carrierConfig.getString(
2958                CarrierConfigManager.KEY_CARRIER_INSTANT_LETTERING_ESCAPED_CHARS_STRING);
2959        if (!TextUtils.isEmpty(escapedCharacters)) {
2960            callSubject = escapeChars(escapedCharacters, callSubject);
2961        }
2962        return callSubject;
2963    }
2964
2965    /**
2966     * Given a source string, return a string where a set of characters are escaped using the
2967     * backslash character.
2968     *
2969     * @param toEscape The characters to escape with a backslash.
2970     * @param source The source string.
2971     * @return The source string with characters escaped.
2972     */
2973    private String escapeChars(String toEscape, String source) {
2974        StringBuilder escaped = new StringBuilder();
2975        for (char c : source.toCharArray()) {
2976            if (toEscape.contains(Character.toString(c))) {
2977                escaped.append("\\");
2978            }
2979            escaped.append(c);
2980        }
2981
2982        return escaped.toString();
2983    }
2984
2985    /**
2986     * Initiates a pull of an external call.
2987     *
2988     * Initiates a pull by making a dial request with the {@link ImsCallProfile#EXTRA_IS_CALL_PULL}
2989     * extra specified.  We call {@link ImsPhone#notifyUnknownConnection(Connection)} which notifies
2990     * Telecom of the new dialed connection.  The
2991     * {@code PstnIncomingCallNotifier#maybeSwapWithUnknownConnection} logic ensures that the new
2992     * {@link ImsPhoneConnection} resulting from the dial gets swapped with the
2993     * {@link ImsExternalConnection}, which effectively makes the external call become a regular
2994     * call.  Magic!
2995     *
2996     * @param number The phone number of the call to be pulled.
2997     * @param videoState The desired video state of the pulled call.
2998     * @param dialogId The {@link ImsExternalConnection#getCallId()} dialog id associated with the
2999     *                 call which is being pulled.
3000     */
3001    @Override
3002    public void pullExternalCall(String number, int videoState, int dialogId) {
3003        Bundle extras = new Bundle();
3004        extras.putBoolean(ImsCallProfile.EXTRA_IS_CALL_PULL, true);
3005        extras.putInt(ImsExternalCallTracker.EXTRA_IMS_EXTERNAL_CALL_ID, dialogId);
3006        try {
3007            Connection connection = dial(number, videoState, extras);
3008            mPhone.notifyUnknownConnection(connection);
3009        } catch (CallStateException e) {
3010            loge("pullExternalCall failed - " + e);
3011        }
3012    }
3013
3014    private ImsException getImsManagerIsNullException() {
3015        return new ImsException("no ims manager", ImsReasonInfo.CODE_LOCAL_ILLEGAL_STATE);
3016    }
3017
3018    /**
3019     * Determines if answering an incoming call will cause the active call to be disconnected.
3020     * <p>
3021     * This will be the case if
3022     * {@link CarrierConfigManager#KEY_DROP_VIDEO_CALL_WHEN_ANSWERING_AUDIO_CALL_BOOL} is
3023     * {@code true} for the carrier, the active call is a video call over WIFI, and the incoming
3024     * call is an audio call.
3025     *
3026     * @param activeCall The active call.
3027     * @param incomingCall The incoming call.
3028     * @return {@code true} if answering the incoming call will cause the active call to be
3029     *      disconnected, {@code false} otherwise.
3030     */
3031    private boolean shouldDisconnectActiveCallOnAnswer(ImsCall activeCall,
3032            ImsCall incomingCall) {
3033
3034        if (activeCall == null || incomingCall == null) {
3035            return false;
3036        }
3037
3038        if (!mDropVideoCallWhenAnsweringAudioCall) {
3039            return false;
3040        }
3041
3042        boolean isActiveCallVideo = activeCall.isVideoCall() ||
3043                (mTreatDowngradedVideoCallsAsVideoCalls && activeCall.wasVideoCall());
3044        boolean isActiveCallOnWifi = activeCall.isWifiCall();
3045        boolean isVoWifiEnabled = mImsManager.isWfcEnabledByPlatform(mPhone.getContext()) &&
3046                mImsManager.isWfcEnabledByUser(mPhone.getContext());
3047        boolean isIncomingCallAudio = !incomingCall.isVideoCall();
3048        log("shouldDisconnectActiveCallOnAnswer : isActiveCallVideo=" + isActiveCallVideo +
3049                " isActiveCallOnWifi=" + isActiveCallOnWifi + " isIncomingCallAudio=" +
3050                isIncomingCallAudio + " isVowifiEnabled=" + isVoWifiEnabled);
3051
3052        return isActiveCallVideo && isActiveCallOnWifi && isIncomingCallAudio && !isVoWifiEnabled;
3053    }
3054
3055    /** Get aggregated video call data usage since boot.
3056     *
3057     * @return data usage in bytes
3058     */
3059    public long getVtDataUsage() {
3060
3061        // If there is an ongoing VT call, request the latest VT usage from the modem. The latest
3062        // usage will return asynchronously so it won't be counted in this round, but it will be
3063        // eventually counted when next getVtDataUsage is called.
3064        if (mState != PhoneConstants.State.IDLE) {
3065            for (ImsPhoneConnection conn : mConnections) {
3066                android.telecom.Connection.VideoProvider videoProvider = conn.getVideoProvider();
3067                if (videoProvider != null) {
3068                    videoProvider.onRequestConnectionDataUsage();
3069                }
3070            }
3071        }
3072
3073        return mTotalVtDataUsage;
3074    }
3075
3076    public void registerPhoneStateListener(PhoneStateListener listener) {
3077        mPhoneStateListeners.add(listener);
3078    }
3079
3080    public void unregisterPhoneStateListener(PhoneStateListener listener) {
3081        mPhoneStateListeners.remove(listener);
3082    }
3083
3084    /**
3085     * Notifies local telephony listeners of changes to the IMS phone state.
3086     *
3087     * @param oldState The old state.
3088     * @param newState The new state.
3089     */
3090    private void notifyPhoneStateChanged(PhoneConstants.State oldState,
3091            PhoneConstants.State newState) {
3092
3093        for (PhoneStateListener listener : mPhoneStateListeners) {
3094            listener.onPhoneStateChanged(oldState, newState);
3095        }
3096    }
3097
3098    /** Modify video call to a new video state.
3099     *
3100     * @param imsCall IMS call to be modified
3101     * @param newVideoState New video state. (Refer to VideoProfile)
3102     */
3103    private void modifyVideoCall(ImsCall imsCall, int newVideoState) {
3104        ImsPhoneConnection conn = findConnection(imsCall);
3105        if (conn != null) {
3106            int oldVideoState = conn.getVideoState();
3107            if (conn.getVideoProvider() != null) {
3108                conn.getVideoProvider().onSendSessionModifyRequest(
3109                        new VideoProfile(oldVideoState), new VideoProfile(newVideoState));
3110            }
3111        }
3112    }
3113
3114    /**
3115     * Handler of data enabled changed event
3116     * @param enabled True if data is enabled, otherwise disabled.
3117     * @param reason Reason for data enabled/disabled (see {@code REASON_*} in
3118     *      {@link DataEnabledSettings}.
3119     */
3120    private void onDataEnabledChanged(boolean enabled, int reason) {
3121
3122        log("onDataEnabledChanged: enabled=" + enabled + ", reason=" + reason);
3123
3124        ImsManager.getInstance(mPhone.getContext(), mPhone.getPhoneId()).setDataEnabled(enabled);
3125        mIsDataEnabled = enabled;
3126
3127        if (mIgnoreDataEnabledChangedForVideoCalls) {
3128            log("Ignore data " + ((enabled) ? "enabled" : "disabled") + " due to carrier policy.");
3129            return;
3130        }
3131
3132        if (mIgnoreDataEnabledChangedForVideoCalls) {
3133            log("Ignore data " + ((enabled) ? "enabled" : "disabled") + " due to carrier policy.");
3134            return;
3135        }
3136
3137        if (!enabled) {
3138            int reasonCode;
3139            if (reason == DataEnabledSettings.REASON_POLICY_DATA_ENABLED) {
3140                reasonCode = ImsReasonInfo.CODE_DATA_LIMIT_REACHED;
3141            } else if (reason == DataEnabledSettings.REASON_USER_DATA_ENABLED) {
3142                reasonCode = ImsReasonInfo.CODE_DATA_DISABLED;
3143            } else {
3144                // Unexpected code, default to data disabled.
3145                reasonCode = ImsReasonInfo.CODE_DATA_DISABLED;
3146            }
3147
3148            // If data is disabled while there are ongoing VT calls which are not taking place over
3149            // wifi, then they should be disconnected to prevent the user from incurring further
3150            // data charges.
3151            for (ImsPhoneConnection conn : mConnections) {
3152                ImsCall imsCall = conn.getImsCall();
3153                if (imsCall != null && imsCall.isVideoCall() && !imsCall.isWifiCall()) {
3154                    if (conn.hasCapabilities(
3155                            Connection.Capability.SUPPORTS_DOWNGRADE_TO_VOICE_LOCAL |
3156                                    Connection.Capability.SUPPORTS_DOWNGRADE_TO_VOICE_REMOTE)) {
3157
3158                        // If the carrier supports downgrading to voice, then we can simply issue a
3159                        // downgrade to voice instead of terminating the call.
3160                        if (reasonCode == ImsReasonInfo.CODE_DATA_DISABLED) {
3161                            conn.onConnectionEvent(TelephonyManager.EVENT_DOWNGRADE_DATA_DISABLED,
3162                                    null);
3163                        } else if (reasonCode == ImsReasonInfo.CODE_DATA_LIMIT_REACHED) {
3164                            conn.onConnectionEvent(
3165                                    TelephonyManager.EVENT_DOWNGRADE_DATA_LIMIT_REACHED, null);
3166                        }
3167                        modifyVideoCall(imsCall, VideoProfile.STATE_AUDIO_ONLY);
3168                    } else if (mSupportPauseVideo) {
3169                        // The carrier supports video pause signalling, so pause the video.
3170                        mShouldUpdateImsConfigOnDisconnect = true;
3171                        conn.pauseVideo(VideoPauseTracker.SOURCE_DATA_ENABLED);
3172                    } else {
3173                        // At this point the only choice we have is to terminate the call.
3174                        try {
3175                            imsCall.terminate(ImsReasonInfo.CODE_USER_TERMINATED, reasonCode);
3176                        } catch (ImsException ie) {
3177                            loge("Couldn't terminate call " + imsCall);
3178                        }
3179                    }
3180                }
3181            }
3182        } else if (mSupportPauseVideo) {
3183            // Data was re-enabled, so un-pause previously paused video calls.
3184            for (ImsPhoneConnection conn : mConnections) {
3185                // If video is paused, check to see if there are any pending pauses due to enabled
3186                // state of data changing.
3187                log("onDataEnabledChanged - resuming " + conn);
3188                if (VideoProfile.isPaused(conn.getVideoState()) &&
3189                        conn.wasVideoPausedFromSource(VideoPauseTracker.SOURCE_DATA_ENABLED)) {
3190                    // The data enabled state was a cause of a pending pause, so potentially
3191                    // resume the video now.
3192                    conn.resumeVideo(VideoPauseTracker.SOURCE_DATA_ENABLED);
3193                }
3194            }
3195            mShouldUpdateImsConfigOnDisconnect = false;
3196        }
3197
3198        if (!mShouldUpdateImsConfigOnDisconnect) {
3199            // This will call into updateVideoCallFeatureValue and eventually all clients will be
3200            // asynchronously notified that the availability of VT over LTE has changed.
3201            ImsManager.updateImsServiceConfig(mPhone.getContext(), mPhone.getPhoneId(), true);
3202        }
3203    }
3204
3205    /**
3206     * @return {@code true} if the device is connected to a WIFI network, {@code false} otherwise.
3207     */
3208    private boolean isWifiConnected() {
3209        ConnectivityManager cm = (ConnectivityManager) mPhone.getContext()
3210                .getSystemService(Context.CONNECTIVITY_SERVICE);
3211        if (cm != null) {
3212            NetworkInfo ni = cm.getActiveNetworkInfo();
3213            if (ni != null && ni.isConnected()) {
3214                return ni.getType() == ConnectivityManager.TYPE_WIFI;
3215            }
3216        }
3217        return false;
3218    }
3219
3220    /**
3221     * @return {@code true} if downgrading of a video call to audio is supported.
3222     */
3223    public boolean isCarrierDowngradeOfVtCallSupported() {
3224        return mSupportDowngradeVtToAudio;
3225    }
3226}
3227