ImsPhoneCallTracker.java revision c7c2aff39afb425b34ea6cc17d172cc28f5ab4f0
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 java.io.FileDescriptor;
20import java.io.PrintWriter;
21import java.util.ArrayList;
22import java.util.List;
23
24import android.app.PendingIntent;
25import android.content.BroadcastReceiver;
26import android.content.Context;
27import android.content.Intent;
28import android.content.IntentFilter;
29import android.content.SharedPreferences;
30import android.os.AsyncResult;
31import android.os.Handler;
32import android.os.Message;
33import android.os.Registrant;
34import android.os.RegistrantList;
35import android.os.RemoteException;
36import android.os.SystemProperties;
37import android.provider.Settings;
38import android.preference.PreferenceManager;
39import android.telecom.ConferenceParticipant;
40import android.telecom.VideoProfile;
41import android.telephony.DisconnectCause;
42import android.telephony.PhoneNumberUtils;
43import android.telephony.Rlog;
44import android.telephony.ServiceState;
45
46import com.android.ims.ImsCall;
47import com.android.ims.ImsCallProfile;
48import com.android.ims.ImsConfig;
49import com.android.ims.ImsConnectionStateListener;
50import com.android.ims.ImsEcbm;
51import com.android.ims.ImsException;
52import com.android.ims.ImsManager;
53import com.android.ims.ImsReasonInfo;
54import com.android.ims.ImsServiceClass;
55import com.android.ims.ImsUtInterface;
56import com.android.ims.internal.IImsVideoCallProvider;
57import com.android.ims.internal.ImsVideoCallProviderWrapper;
58import com.android.internal.telephony.Call;
59import com.android.internal.telephony.CallStateException;
60import com.android.internal.telephony.CallTracker;
61import com.android.internal.telephony.CommandException;
62import com.android.internal.telephony.CommandsInterface;
63import com.android.internal.telephony.Connection;
64import com.android.internal.telephony.Phone;
65import com.android.internal.telephony.PhoneBase;
66import com.android.internal.telephony.PhoneConstants;
67import com.android.internal.telephony.TelephonyProperties;
68
69/**
70 * {@hide}
71 */
72public final class ImsPhoneCallTracker extends CallTracker {
73    static final String LOG_TAG = "ImsPhoneCallTracker";
74
75    private static final boolean DBG = true;
76
77    private boolean mIsVolteEnabled = false;
78    private boolean mIsVtEnabled = false;
79
80    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
81        @Override
82        public void onReceive(Context context, Intent intent) {
83            if (intent.getAction().equals(ImsManager.ACTION_IMS_INCOMING_CALL)) {
84                if (DBG) log("onReceive : incoming call intent");
85
86                if (mImsManager == null) return;
87
88                if (mServiceId < 0) return;
89
90                try {
91                    // Network initiated USSD will be treated by mImsUssdListener
92                    boolean isUssd = intent.getBooleanExtra(ImsManager.EXTRA_USSD, false);
93                    if (isUssd) {
94                        if (DBG) log("onReceive : USSD");
95                        mUssdSession = mImsManager.takeCall(mServiceId, intent, mImsUssdListener);
96                        if (mUssdSession != null) {
97                            mUssdSession.accept(ImsCallProfile.CALL_TYPE_VOICE);
98                        }
99                        return;
100                    }
101
102                    // Normal MT call
103                    ImsCall imsCall = mImsManager.takeCall(mServiceId, intent, mImsCallListener);
104                    ImsPhoneConnection conn = new ImsPhoneConnection(mPhone.getContext(), imsCall,
105                            ImsPhoneCallTracker.this, mRingingCall);
106                    addConnection(conn);
107
108                    IImsVideoCallProvider imsVideoCallProvider =
109                            imsCall.getCallSession().getVideoCallProvider();
110                    if (imsVideoCallProvider != null) {
111                        ImsVideoCallProviderWrapper imsVideoCallProviderWrapper =
112                                new ImsVideoCallProviderWrapper(imsVideoCallProvider);
113                        conn.setVideoProvider(imsVideoCallProviderWrapper);
114                    }
115
116                    if ((mForegroundCall.getState() != ImsPhoneCall.State.IDLE) ||
117                            (mBackgroundCall.getState() != ImsPhoneCall.State.IDLE)) {
118                        conn.update(imsCall, ImsPhoneCall.State.WAITING);
119                    }
120
121                    mPhone.notifyNewRingingConnection(conn);
122                    mPhone.notifyIncomingRing();
123
124                    updatePhoneState();
125                    mPhone.notifyPreciseCallStateChanged();
126                } catch (ImsException e) {
127                    loge("onReceive : exception " + e);
128                } catch (RemoteException e) {
129                }
130            }
131        }
132    };
133
134    //***** Constants
135
136    static final int MAX_CONNECTIONS = 7;
137    static final int MAX_CONNECTIONS_PER_CALL = 5;
138
139    private static final int EVENT_HANGUP_PENDINGMO = 18;
140    private static final int EVENT_RESUME_BACKGROUND = 19;
141    private static final int EVENT_DIAL_PENDINGMO = 20;
142
143    private static final int TIMEOUT_HANGUP_PENDINGMO = 500;
144
145    //***** Instance Variables
146    private ArrayList<ImsPhoneConnection> mConnections = new ArrayList<ImsPhoneConnection>();
147    private RegistrantList mVoiceCallEndedRegistrants = new RegistrantList();
148    private RegistrantList mVoiceCallStartedRegistrants = new RegistrantList();
149
150    ImsPhoneCall mRingingCall = new ImsPhoneCall(this);
151    ImsPhoneCall mForegroundCall = new ImsPhoneCall(this);
152    ImsPhoneCall mBackgroundCall = new ImsPhoneCall(this);
153    ImsPhoneCall mHandoverCall = new ImsPhoneCall(this);
154
155    private ImsPhoneConnection mPendingMO;
156    private int mClirMode = CommandsInterface.CLIR_DEFAULT;
157    private Object mSyncHold = new Object();
158
159    private ImsCall mUssdSession = null;
160    private Message mPendingUssd = null;
161
162    ImsPhone mPhone;
163
164    private boolean mDesiredMute = false;    // false = mute off
165    private boolean mOnHoldToneStarted = false;
166
167    PhoneConstants.State mState = PhoneConstants.State.IDLE;
168
169    private ImsManager mImsManager;
170    private int mServiceId = -1;
171
172    private Call.SrvccState mSrvccState = Call.SrvccState.NONE;
173
174    private boolean mIsInEmergencyCall = false;
175
176    private int pendingCallClirMode;
177    private int pendingCallVideoState;
178    private boolean pendingCallInEcm = false;
179    private boolean mSwitchingFgAndBgCalls = false;
180    private ImsCall mCallExpectedToResume = null;
181
182    //***** Events
183
184
185    //***** Constructors
186
187    ImsPhoneCallTracker(ImsPhone phone) {
188        this.mPhone = phone;
189
190        IntentFilter intentfilter = new IntentFilter();
191        intentfilter.addAction(ImsManager.ACTION_IMS_INCOMING_CALL);
192        mPhone.getContext().registerReceiver(mReceiver, intentfilter);
193
194        Thread t = new Thread() {
195            public void run() {
196                getImsService();
197            }
198        };
199        t.start();
200    }
201
202    private PendingIntent createIncomingCallPendingIntent() {
203        Intent intent = new Intent(ImsManager.ACTION_IMS_INCOMING_CALL);
204        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
205        return PendingIntent.getBroadcast(mPhone.getContext(), 0, intent,
206                PendingIntent.FLAG_UPDATE_CURRENT);
207    }
208
209    private void getImsService() {
210        if (DBG) log("getImsService");
211        mImsManager = ImsManager.getInstance(mPhone.getContext(), mPhone.getPhoneId());
212        try {
213            mServiceId = mImsManager.open(ImsServiceClass.MMTEL,
214                    createIncomingCallPendingIntent(),
215                    mImsConnectionStateListener);
216
217            // Get the ECBM interface and set IMSPhone's listener object for notifications
218            getEcbmInterface().setEcbmStateListener(mPhone.mImsEcbmStateListener);
219            if (mPhone.isInEcm()) {
220                // Call exit ECBM which will invoke onECBMExited
221                mPhone.exitEmergencyCallbackMode();
222            }
223            int mPreferredTtyMode = Settings.Secure.getInt(
224                mPhone.getContext().getContentResolver(),
225                Settings.Secure.PREFERRED_TTY_MODE,
226                Phone.TTY_MODE_OFF);
227           mImsManager.setUiTTYMode(mPhone.getContext(), mServiceId, mPreferredTtyMode, null);
228
229        } catch (ImsException e) {
230            loge("getImsService: " + e);
231            //Leave mImsManager as null, then CallStateException will be thrown when dialing
232            mImsManager = null;
233        }
234    }
235
236    public void dispose() {
237        if (DBG) log("dispose");
238        mRingingCall.dispose();
239        mBackgroundCall.dispose();
240        mForegroundCall.dispose();
241        mHandoverCall.dispose();
242
243        clearDisconnected();
244        mPhone.getContext().unregisterReceiver(mReceiver);
245    }
246
247    @Override
248    protected void finalize() {
249        log("ImsPhoneCallTracker finalized");
250    }
251
252    //***** Instance Methods
253
254    //***** Public Methods
255    @Override
256    public void registerForVoiceCallStarted(Handler h, int what, Object obj) {
257        Registrant r = new Registrant(h, what, obj);
258        mVoiceCallStartedRegistrants.add(r);
259    }
260
261    @Override
262    public void unregisterForVoiceCallStarted(Handler h) {
263        mVoiceCallStartedRegistrants.remove(h);
264    }
265
266    @Override
267    public void registerForVoiceCallEnded(Handler h, int what, Object obj) {
268        Registrant r = new Registrant(h, what, obj);
269        mVoiceCallEndedRegistrants.add(r);
270    }
271
272    @Override
273    public void unregisterForVoiceCallEnded(Handler h) {
274        mVoiceCallEndedRegistrants.remove(h);
275    }
276
277    Connection
278    dial(String dialString, int videoState) throws CallStateException {
279        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mPhone.getContext());
280        int oirMode = sp.getInt(PhoneBase.CLIR_KEY, CommandsInterface.CLIR_DEFAULT);
281        return dial(dialString, oirMode, videoState);
282    }
283
284    /**
285     * oirMode is one of the CLIR_ constants
286     */
287    synchronized Connection
288    dial(String dialString, int clirMode, int videoState) throws CallStateException {
289        boolean isPhoneInEcmMode = SystemProperties.getBoolean(
290                TelephonyProperties.PROPERTY_INECM_MODE, false);
291        boolean isEmergencyNumber = PhoneNumberUtils.isEmergencyNumber(dialString);
292
293        if (DBG) log("dial clirMode=" + clirMode);
294
295        // note that this triggers call state changed notif
296        clearDisconnected();
297
298        if (mImsManager == null) {
299            throw new CallStateException("service not available");
300        }
301
302        if (!canDial()) {
303            throw new CallStateException("cannot dial in current state");
304        }
305
306        if (isPhoneInEcmMode && isEmergencyNumber) {
307            handleEcmTimer(ImsPhone.CANCEL_ECM_TIMER);
308        }
309
310        boolean holdBeforeDial = false;
311
312        // The new call must be assigned to the foreground call.
313        // That call must be idle, so place anything that's
314        // there on hold
315        if (mForegroundCall.getState() == ImsPhoneCall.State.ACTIVE) {
316            if (mBackgroundCall.getState() != ImsPhoneCall.State.IDLE) {
317                //we should have failed in !canDial() above before we get here
318                throw new CallStateException("cannot dial in current state");
319            }
320            // foreground call is empty for the newly dialed connection
321            holdBeforeDial = true;
322            switchWaitingOrHoldingAndActive();
323        }
324
325        ImsPhoneCall.State fgState = ImsPhoneCall.State.IDLE;
326        ImsPhoneCall.State bgState = ImsPhoneCall.State.IDLE;
327
328        mClirMode = clirMode;
329
330        synchronized (mSyncHold) {
331            if (holdBeforeDial) {
332                fgState = mForegroundCall.getState();
333                bgState = mBackgroundCall.getState();
334
335                //holding foreground call failed
336                if (fgState == ImsPhoneCall.State.ACTIVE) {
337                    throw new CallStateException("cannot dial in current state");
338                }
339
340                //holding foreground call succeeded
341                if (bgState == ImsPhoneCall.State.HOLDING) {
342                    holdBeforeDial = false;
343                }
344            }
345
346            mPendingMO = new ImsPhoneConnection(mPhone.getContext(),
347                    checkForTestEmergencyNumber(dialString), this, mForegroundCall);
348        }
349        addConnection(mPendingMO);
350
351        if (!holdBeforeDial) {
352            if ((!isPhoneInEcmMode) || (isPhoneInEcmMode && isEmergencyNumber)) {
353                dialInternal(mPendingMO, clirMode, videoState);
354            } else {
355                try {
356                    getEcbmInterface().exitEmergencyCallbackMode();
357                } catch (ImsException e) {
358                    e.printStackTrace();
359                    throw new CallStateException("service not available");
360                }
361                mPhone.setOnEcbModeExitResponse(this, EVENT_EXIT_ECM_RESPONSE_CDMA, null);
362                pendingCallClirMode = clirMode;
363                pendingCallVideoState = videoState;
364                pendingCallInEcm = true;
365            }
366        }
367
368        updatePhoneState();
369        mPhone.notifyPreciseCallStateChanged();
370
371        return mPendingMO;
372    }
373
374    private void handleEcmTimer(int action) {
375        mPhone.handleTimerInEmergencyCallbackMode(action);
376        switch (action) {
377            case ImsPhone.CANCEL_ECM_TIMER:
378                break;
379            case ImsPhone.RESTART_ECM_TIMER:
380                break;
381            default:
382                log("handleEcmTimer, unsupported action " + action);
383        }
384    }
385
386    private void dialInternal(ImsPhoneConnection conn, int clirMode, int videoState) {
387        if (conn == null) {
388            return;
389        }
390
391        if (conn.getAddress()== null || conn.getAddress().length() == 0
392                || conn.getAddress().indexOf(PhoneNumberUtils.WILD) >= 0) {
393            // Phone number is invalid
394            conn.setDisconnectCause(DisconnectCause.INVALID_NUMBER);
395            sendEmptyMessageDelayed(EVENT_HANGUP_PENDINGMO, TIMEOUT_HANGUP_PENDINGMO);
396            return;
397        }
398
399        // Always unmute when initiating a new call
400        setMute(false);
401        int serviceType = PhoneNumberUtils.isEmergencyNumber(conn.getAddress()) ?
402                ImsCallProfile.SERVICE_TYPE_EMERGENCY : ImsCallProfile.SERVICE_TYPE_NORMAL;
403        int callType = ImsCallProfile.getCallTypeFromVideoState(videoState);
404        //TODO(vt): Is this sufficient?  At what point do we know the video state of the call?
405        conn.setVideoState(videoState);
406
407        try {
408            String[] callees = new String[] { conn.getAddress() };
409            ImsCallProfile profile = mImsManager.createCallProfile(mServiceId,
410                    serviceType, callType);
411            profile.setCallExtraInt(ImsCallProfile.EXTRA_OIR, clirMode);
412
413            ImsCall imsCall = mImsManager.makeCall(mServiceId, profile,
414                    callees, mImsCallListener);
415            conn.setImsCall(imsCall);
416
417            IImsVideoCallProvider imsVideoCallProvider =
418                    imsCall.getCallSession().getVideoCallProvider();
419            if (imsVideoCallProvider != null) {
420                ImsVideoCallProviderWrapper imsVideoCallProviderWrapper =
421                        new ImsVideoCallProviderWrapper(imsVideoCallProvider);
422                conn.setVideoProvider(imsVideoCallProviderWrapper);
423            }
424        } catch (ImsException e) {
425            loge("dialInternal : " + e);
426            conn.setDisconnectCause(DisconnectCause.ERROR_UNSPECIFIED);
427            sendEmptyMessageDelayed(EVENT_HANGUP_PENDINGMO, TIMEOUT_HANGUP_PENDINGMO);
428        } catch (RemoteException e) {
429        }
430    }
431
432    /**
433     * Accepts a call with the specified video state.  The video state is the video state that the
434     * user has agreed upon in the InCall UI.
435     *
436     * @param videoState The video State
437     * @throws CallStateException
438     */
439    void acceptCall (int videoState) throws CallStateException {
440        if (DBG) log("acceptCall");
441
442        if (mForegroundCall.getState().isAlive()
443                && mBackgroundCall.getState().isAlive()) {
444            throw new CallStateException("cannot accept call");
445        }
446
447        if ((mRingingCall.getState() == ImsPhoneCall.State.WAITING)
448                && mForegroundCall.getState().isAlive()) {
449            setMute(false);
450            switchWaitingOrHoldingAndActive();
451        } else if (mRingingCall.getState().isRinging()) {
452            if (DBG) log("acceptCall: incoming...");
453            // Always unmute when answering a new call
454            setMute(false);
455            try {
456                ImsCall imsCall = mRingingCall.getImsCall();
457                if (imsCall != null) {
458                    imsCall.accept(ImsCallProfile.getCallTypeFromVideoState(videoState));
459                } else {
460                    throw new CallStateException("no valid ims call");
461                }
462            } catch (ImsException e) {
463                throw new CallStateException("cannot accept call");
464            }
465        } else {
466            throw new CallStateException("phone not ringing");
467        }
468    }
469
470    void
471    rejectCall () throws CallStateException {
472        if (DBG) log("rejectCall");
473
474        if (mRingingCall.getState().isRinging()) {
475            hangup(mRingingCall);
476        } else {
477            throw new CallStateException("phone not ringing");
478        }
479    }
480
481    void
482    switchWaitingOrHoldingAndActive() throws CallStateException {
483        if (DBG) log("switchWaitingOrHoldingAndActive");
484
485        if (mRingingCall.getState() == ImsPhoneCall.State.INCOMING) {
486            throw new CallStateException("cannot be in the incoming state");
487        }
488
489        if (mForegroundCall.getState() == ImsPhoneCall.State.ACTIVE) {
490            ImsCall imsCall = mForegroundCall.getImsCall();
491            if (imsCall == null) {
492                throw new CallStateException("no ims call");
493            }
494
495            // Swap the ImsCalls pointed to by the foreground and background ImsPhoneCalls.
496            // If hold or resume later fails, we will swap them back.
497            mSwitchingFgAndBgCalls = true;
498            mCallExpectedToResume = mBackgroundCall.getImsCall();
499            mForegroundCall.switchWith(mBackgroundCall);
500
501            // Hold the foreground call; once the foreground call is held, the background call will
502            // be resumed.
503            try {
504                imsCall.hold();
505            } catch (ImsException e) {
506                mForegroundCall.switchWith(mBackgroundCall);
507                throw new CallStateException(e.getMessage());
508            }
509        } else if (mBackgroundCall.getState() == ImsPhoneCall.State.HOLDING) {
510            resumeWaitingOrHolding();
511        }
512    }
513
514    void
515    conference() {
516        if (DBG) log("conference");
517
518        ImsCall fgImsCall = mForegroundCall.getImsCall();
519        if (fgImsCall == null) {
520            log("conference no foreground ims call");
521            return;
522        }
523
524        ImsCall bgImsCall = mBackgroundCall.getImsCall();
525        if (bgImsCall == null) {
526            log("conference no background ims call");
527            return;
528        }
529
530        try {
531            fgImsCall.merge(bgImsCall);
532        } catch (ImsException e) {
533            log("conference " + e.getMessage());
534        }
535    }
536
537    void
538    explicitCallTransfer() {
539        //TODO : implement
540    }
541
542    void
543    clearDisconnected() {
544        if (DBG) log("clearDisconnected");
545
546        internalClearDisconnected();
547
548        updatePhoneState();
549        mPhone.notifyPreciseCallStateChanged();
550    }
551
552    boolean
553    canConference() {
554        return mForegroundCall.getState() == ImsPhoneCall.State.ACTIVE
555            && mBackgroundCall.getState() == ImsPhoneCall.State.HOLDING
556            && !mBackgroundCall.isFull()
557            && !mForegroundCall.isFull();
558    }
559
560    boolean
561    canDial() {
562        boolean ret;
563        int serviceState = mPhone.getServiceState().getState();
564        String disableCall = SystemProperties.get(
565                TelephonyProperties.PROPERTY_DISABLE_CALL, "false");
566
567        ret = (serviceState != ServiceState.STATE_POWER_OFF)
568            && mPendingMO == null
569            && !mRingingCall.isRinging()
570            && !disableCall.equals("true")
571            && (!mForegroundCall.getState().isAlive()
572                    || !mBackgroundCall.getState().isAlive());
573
574        return ret;
575    }
576
577    boolean
578    canTransfer() {
579        return mForegroundCall.getState() == ImsPhoneCall.State.ACTIVE
580            && mBackgroundCall.getState() == ImsPhoneCall.State.HOLDING;
581    }
582
583    //***** Private Instance Methods
584
585    private void
586    internalClearDisconnected() {
587        mRingingCall.clearDisconnected();
588        mForegroundCall.clearDisconnected();
589        mBackgroundCall.clearDisconnected();
590        mHandoverCall.clearDisconnected();
591    }
592
593    private void
594    updatePhoneState() {
595        PhoneConstants.State oldState = mState;
596
597        if (mRingingCall.isRinging()) {
598            mState = PhoneConstants.State.RINGING;
599        } else if (mPendingMO != null ||
600                !(mForegroundCall.isIdle() && mBackgroundCall.isIdle())) {
601            mState = PhoneConstants.State.OFFHOOK;
602        } else {
603            mState = PhoneConstants.State.IDLE;
604        }
605
606        if (mState == PhoneConstants.State.IDLE && oldState != mState) {
607            mVoiceCallEndedRegistrants.notifyRegistrants(
608                    new AsyncResult(null, null, null));
609        } else if (oldState == PhoneConstants.State.IDLE && oldState != mState) {
610            mVoiceCallStartedRegistrants.notifyRegistrants (
611                    new AsyncResult(null, null, null));
612        }
613
614        if (DBG) log("updatePhoneState oldState=" + oldState + ", newState=" + mState);
615
616        if (mState != oldState) {
617            mPhone.notifyPhoneStateChanged();
618        }
619    }
620
621    private void
622    handleRadioNotAvailable() {
623        // handlePollCalls will clear out its
624        // call list when it gets the CommandException
625        // error result from this
626        pollCallsWhenSafe();
627    }
628
629    private void
630    dumpState() {
631        List l;
632
633        log("Phone State:" + mState);
634
635        log("Ringing call: " + mRingingCall.toString());
636
637        l = mRingingCall.getConnections();
638        for (int i = 0, s = l.size(); i < s; i++) {
639            log(l.get(i).toString());
640        }
641
642        log("Foreground call: " + mForegroundCall.toString());
643
644        l = mForegroundCall.getConnections();
645        for (int i = 0, s = l.size(); i < s; i++) {
646            log(l.get(i).toString());
647        }
648
649        log("Background call: " + mBackgroundCall.toString());
650
651        l = mBackgroundCall.getConnections();
652        for (int i = 0, s = l.size(); i < s; i++) {
653            log(l.get(i).toString());
654        }
655
656    }
657
658    //***** Called from ImsPhone
659
660    void setUiTTYMode(int uiTtyMode, Message onComplete) {
661        try {
662            mImsManager.setUiTTYMode(mPhone.getContext(), mServiceId, uiTtyMode, onComplete);
663        } catch (ImsException e) {
664            loge("setTTYMode : " + e);
665            mPhone.sendErrorResponse(onComplete, e);
666        }
667    }
668
669    /*package*/ void setMute(boolean mute) {
670        mDesiredMute = mute;
671        mForegroundCall.setMute(mute);
672    }
673
674    /*package*/ boolean getMute() {
675        return mDesiredMute;
676    }
677
678    /* package */ void sendDtmf(char c, Message result) {
679        if (DBG) log("sendDtmf");
680
681        ImsCall imscall = mForegroundCall.getImsCall();
682        if (imscall != null) {
683            imscall.sendDtmf(c, result);
684        }
685    }
686
687    /*package*/ void
688    startDtmf(char c) {
689        if (DBG) log("startDtmf");
690
691        ImsCall imscall = mForegroundCall.getImsCall();
692        if (imscall != null) {
693            imscall.startDtmf(c);
694        } else {
695            loge("startDtmf : no foreground call");
696        }
697    }
698
699    /*package*/ void
700    stopDtmf() {
701        if (DBG) log("stopDtmf");
702
703        ImsCall imscall = mForegroundCall.getImsCall();
704        if (imscall != null) {
705            imscall.stopDtmf();
706        } else {
707            loge("stopDtmf : no foreground call");
708        }
709    }
710
711    //***** Called from ImsPhoneConnection
712
713    /*package*/ void
714    hangup (ImsPhoneConnection conn) throws CallStateException {
715        if (DBG) log("hangup connection");
716
717        if (conn.getOwner() != this) {
718            throw new CallStateException ("ImsPhoneConnection " + conn
719                    + "does not belong to ImsPhoneCallTracker " + this);
720        }
721
722        hangup(conn.getCall());
723    }
724
725    //***** Called from ImsPhoneCall
726
727    /* package */ void
728    hangup (ImsPhoneCall call) throws CallStateException {
729        if (DBG) log("hangup call");
730
731        if (call.getConnections().size() == 0) {
732            throw new CallStateException("no connections");
733        }
734
735        ImsCall imsCall = call.getImsCall();
736        boolean rejectCall = false;
737
738        if (call == mRingingCall) {
739            if (Phone.DEBUG_PHONE) log("(ringing) hangup incoming");
740            rejectCall = true;
741        } else if (call == mForegroundCall) {
742            if (call.isDialingOrAlerting()) {
743                if (Phone.DEBUG_PHONE) {
744                    log("(foregnd) hangup dialing or alerting...");
745                }
746            } else {
747                if (Phone.DEBUG_PHONE) {
748                    log("(foregnd) hangup foreground");
749                }
750                //held call will be resumed by onCallTerminated
751            }
752        } else if (call == mBackgroundCall) {
753            if (Phone.DEBUG_PHONE) {
754                log("(backgnd) hangup waiting or background");
755            }
756        } else {
757            throw new CallStateException ("ImsPhoneCall " + call +
758                    "does not belong to ImsPhoneCallTracker " + this);
759        }
760
761        call.onHangupLocal();
762
763        try {
764            if (imsCall != null) {
765                if (rejectCall) imsCall.reject(ImsReasonInfo.CODE_USER_DECLINE);
766                else imsCall.terminate(ImsReasonInfo.CODE_USER_TERMINATED);
767            } else if (mPendingMO != null && call == mForegroundCall) {
768                // is holding a foreground call
769                mPendingMO.update(null, ImsPhoneCall.State.DISCONNECTED);
770                mPendingMO.onDisconnect();
771                removeConnection(mPendingMO);
772                mPendingMO = null;
773                updatePhoneState();
774                removeMessages(EVENT_DIAL_PENDINGMO);
775            }
776        } catch (ImsException e) {
777            throw new CallStateException(e.getMessage());
778        }
779
780        mPhone.notifyPreciseCallStateChanged();
781    }
782
783    /* package */
784    void resumeWaitingOrHolding() throws CallStateException {
785        if (DBG) log("resumeWaitingOrHolding");
786
787        try {
788            if (mForegroundCall.getState().isAlive()) {
789                //resume foreground call after holding background call
790                //they were switched before holding
791                ImsCall imsCall = mForegroundCall.getImsCall();
792                if (imsCall != null) imsCall.resume();
793            } else if (mRingingCall.getState() == ImsPhoneCall.State.WAITING) {
794                //accept waiting call after holding background call
795                ImsCall imsCall = mRingingCall.getImsCall();
796                if (imsCall != null) imsCall.accept(ImsCallProfile.CALL_TYPE_VOICE);
797            } else {
798                //Just resume background call.
799                //To distinguish resuming call with swapping calls
800                //we do not switch calls.here
801                //ImsPhoneConnection.update will chnage the parent when completed
802                ImsCall imsCall = mBackgroundCall.getImsCall();
803                if (imsCall != null) imsCall.resume();
804            }
805        } catch (ImsException e) {
806            throw new CallStateException(e.getMessage());
807        }
808    }
809
810    /* package */
811    void sendUSSD (String ussdString, Message response) {
812        if (DBG) log("sendUSSD");
813
814        try {
815            if (mUssdSession != null) {
816                mUssdSession.sendUssd(ussdString);
817                AsyncResult.forMessage(response, null, null);
818                response.sendToTarget();
819                return;
820            }
821
822            String[] callees = new String[] { ussdString };
823            ImsCallProfile profile = mImsManager.createCallProfile(mServiceId,
824                    ImsCallProfile.SERVICE_TYPE_NORMAL, ImsCallProfile.CALL_TYPE_VOICE);
825            profile.setCallExtraInt(ImsCallProfile.EXTRA_DIALSTRING,
826                    ImsCallProfile.DIALSTRING_USSD);
827
828            mUssdSession = mImsManager.makeCall(mServiceId, profile,
829                    callees, mImsUssdListener);
830        } catch (ImsException e) {
831            loge("sendUSSD : " + e);
832            mPhone.sendErrorResponse(response, e);
833        }
834    }
835
836    /* package */
837    void cancelUSSD() {
838        if (mUssdSession == null) return;
839
840        try {
841            mUssdSession.terminate(ImsReasonInfo.CODE_USER_TERMINATED);
842        } catch (ImsException e) {
843        }
844
845    }
846
847    private synchronized ImsPhoneConnection findConnection(ImsCall imsCall) {
848        for (ImsPhoneConnection conn : mConnections) {
849            if (conn.getImsCall() == imsCall) {
850                return conn;
851            }
852        }
853        return null;
854    }
855
856    private synchronized void removeConnection(ImsPhoneConnection conn) {
857        mConnections.remove(conn);
858    }
859
860    private synchronized void addConnection(ImsPhoneConnection conn) {
861        mConnections.add(conn);
862    }
863
864    private void processCallStateChange(ImsCall imsCall, ImsPhoneCall.State state, int cause) {
865        if (DBG) log("processCallStateChange " + imsCall + " state=" + state + " cause=" + cause);
866
867        if (imsCall == null) return;
868
869        boolean changed = false;
870        ImsPhoneConnection conn = findConnection(imsCall);
871
872        if (conn == null) {
873            // TODO : what should be done?
874            return;
875        }
876
877        changed = conn.update(imsCall, state);
878
879        if (state == ImsPhoneCall.State.DISCONNECTED) {
880            changed = conn.onDisconnect(cause) || changed;
881            //detach the disconnected connections
882            conn.getCall().detach(conn);
883            removeConnection(conn);
884        }
885
886        if (changed) {
887            if (conn.getCall() == mHandoverCall) return;
888            updatePhoneState();
889            mPhone.notifyPreciseCallStateChanged();
890        }
891    }
892
893    private int getDisconnectCauseFromReasonInfo(ImsReasonInfo reasonInfo) {
894        int cause = DisconnectCause.ERROR_UNSPECIFIED;
895
896        //int type = reasonInfo.getReasonType();
897        int code = reasonInfo.getCode();
898        switch (code) {
899            case ImsReasonInfo.CODE_SIP_BAD_ADDRESS:
900            case ImsReasonInfo.CODE_SIP_NOT_REACHABLE:
901                return DisconnectCause.NUMBER_UNREACHABLE;
902
903            case ImsReasonInfo.CODE_SIP_BUSY:
904                return DisconnectCause.BUSY;
905
906            case ImsReasonInfo.CODE_USER_TERMINATED:
907                return DisconnectCause.LOCAL;
908
909            case ImsReasonInfo.CODE_LOCAL_CALL_DECLINE:
910                return DisconnectCause.INCOMING_REJECTED;
911
912            case ImsReasonInfo.CODE_USER_TERMINATED_BY_REMOTE:
913                return DisconnectCause.NORMAL;
914
915            case ImsReasonInfo.CODE_SIP_REDIRECTED:
916            case ImsReasonInfo.CODE_SIP_BAD_REQUEST:
917            case ImsReasonInfo.CODE_SIP_FORBIDDEN:
918            case ImsReasonInfo.CODE_SIP_NOT_ACCEPTABLE:
919            case ImsReasonInfo.CODE_SIP_USER_REJECTED:
920            case ImsReasonInfo.CODE_SIP_GLOBAL_ERROR:
921                return DisconnectCause.SERVER_ERROR;
922
923            case ImsReasonInfo.CODE_SIP_SERVICE_UNAVAILABLE:
924            case ImsReasonInfo.CODE_SIP_NOT_FOUND:
925            case ImsReasonInfo.CODE_SIP_SERVER_ERROR:
926                return DisconnectCause.SERVER_UNREACHABLE;
927
928            case ImsReasonInfo.CODE_LOCAL_NETWORK_ROAMING:
929            case ImsReasonInfo.CODE_LOCAL_NETWORK_IP_CHANGED:
930            case ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN:
931            case ImsReasonInfo.CODE_LOCAL_SERVICE_UNAVAILABLE:
932            case ImsReasonInfo.CODE_LOCAL_NOT_REGISTERED:
933            case ImsReasonInfo.CODE_LOCAL_NETWORK_NO_LTE_COVERAGE:
934            case ImsReasonInfo.CODE_LOCAL_NETWORK_NO_SERVICE:
935            case ImsReasonInfo.CODE_LOCAL_CALL_VCC_ON_PROGRESSING:
936                return DisconnectCause.OUT_OF_SERVICE;
937
938            case ImsReasonInfo.CODE_SIP_REQUEST_TIMEOUT:
939            case ImsReasonInfo.CODE_TIMEOUT_1XX_WAITING:
940            case ImsReasonInfo.CODE_TIMEOUT_NO_ANSWER:
941            case ImsReasonInfo.CODE_TIMEOUT_NO_ANSWER_CALL_UPDATE:
942                return DisconnectCause.TIMED_OUT;
943
944            case ImsReasonInfo.CODE_LOCAL_LOW_BATTERY:
945            case ImsReasonInfo.CODE_LOCAL_POWER_OFF:
946                return DisconnectCause.POWER_OFF;
947
948            default:
949        }
950
951        return cause;
952    }
953
954    /**
955     * Listen to the IMS call state change
956     */
957    private ImsCall.Listener mImsCallListener = new ImsCall.Listener() {
958        @Override
959        public void onCallProgressing(ImsCall imsCall) {
960            if (DBG) log("onCallProgressing");
961
962            mPendingMO = null;
963            processCallStateChange(imsCall, ImsPhoneCall.State.ALERTING,
964                    DisconnectCause.NOT_DISCONNECTED);
965        }
966
967        @Override
968        public void onCallStarted(ImsCall imsCall) {
969            if (DBG) log("onCallStarted");
970
971            mPendingMO = null;
972            processCallStateChange(imsCall, ImsPhoneCall.State.ACTIVE,
973                    DisconnectCause.NOT_DISCONNECTED);
974        }
975
976        /**
977         * onCallStartFailed will be invoked when:
978         * case 1) Dialing fails
979         * case 2) Ringing call is disconnected by local or remote user
980         */
981        @Override
982        public void onCallStartFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
983            if (DBG) log("onCallStartFailed reasonCode=" + reasonInfo.getCode());
984
985            if (mPendingMO != null) {
986                // To initiate dialing circuit-switched call
987                if (reasonInfo.getCode() == ImsReasonInfo.CODE_LOCAL_CALL_CS_RETRY_REQUIRED
988                        && mBackgroundCall.getState() == ImsPhoneCall.State.IDLE
989                        && mRingingCall.getState() == ImsPhoneCall.State.IDLE) {
990                    mForegroundCall.detach(mPendingMO);
991                    removeConnection(mPendingMO);
992                    mPendingMO.finalize();
993                    mPendingMO = null;
994                    mPhone.initiateSilentRedial();
995                    return;
996                }
997                mPendingMO = null;
998            }
999        }
1000
1001        @Override
1002        public void onCallTerminated(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1003            if (DBG) log("onCallTerminated reasonCode=" + reasonInfo.getCode());
1004
1005            ImsPhoneCall.State oldState = mForegroundCall.getState();
1006            int cause = getDisconnectCauseFromReasonInfo(reasonInfo);
1007            ImsPhoneConnection conn = findConnection(imsCall);
1008            if (DBG) log("cause = " + cause + " conn = " + conn);
1009
1010            if (conn != null && conn.isIncoming() && conn.getConnectTime() == 0) {
1011                // Missed
1012                if (cause == DisconnectCause.NORMAL) {
1013                    cause = DisconnectCause.INCOMING_MISSED;
1014                }
1015                if (DBG) log("Incoming connection of 0 connect time detected - translated cause = "
1016                        + cause);
1017
1018            }
1019
1020            if (cause == DisconnectCause.NORMAL && conn != null && conn.getImsCall().isMerged()) {
1021                // Call was terminated while it is merged instead of a remote disconnect.
1022                cause = DisconnectCause.IMS_MERGED_SUCCESSFULLY;
1023            }
1024
1025            processCallStateChange(imsCall, ImsPhoneCall.State.DISCONNECTED, cause);
1026        }
1027
1028        @Override
1029        public void onCallHeld(ImsCall imsCall) {
1030            if (DBG) log("onCallHeld");
1031
1032            synchronized (mSyncHold) {
1033                ImsPhoneCall.State oldState = mBackgroundCall.getState();
1034                processCallStateChange(imsCall, ImsPhoneCall.State.HOLDING,
1035                        DisconnectCause.NOT_DISCONNECTED);
1036
1037                // Note: If we're performing a switchWaitingOrHoldingAndActive, the call to
1038                // processCallStateChange above may have caused the mBackgroundCall and
1039                // mForegroundCall references below to change meaning.  Watch out for this if you
1040                // are reading through this code.
1041                if (oldState == ImsPhoneCall.State.ACTIVE) {
1042                    // Note: This case comes up when we have just held a call in response to a
1043                    // switchWaitingOrHoldingAndActive.  We now need to resume the background call.
1044                    // The EVENT_RESUME_BACKGROUND causes resumeWaitingOrHolding to be called.
1045                    if ((mForegroundCall.getState() == ImsPhoneCall.State.HOLDING)
1046                            || (mRingingCall.getState() == ImsPhoneCall.State.WAITING)) {
1047
1048                            sendEmptyMessage(EVENT_RESUME_BACKGROUND);
1049                    } else {
1050                        //when multiple connections belong to background call,
1051                        //only the first callback reaches here
1052                        //otherwise the oldState is already HOLDING
1053                        if (mPendingMO != null) {
1054                            sendEmptyMessage(EVENT_DIAL_PENDINGMO);
1055                        }
1056
1057                        // In this case there will be no call resumed, so we can assume that we
1058                        // are done switching fg and bg calls now.
1059                        // This may happen if there is no BG call and we are holding a call so that
1060                        // we can dial another one.
1061                        mSwitchingFgAndBgCalls = false;
1062                    }
1063                }
1064            }
1065        }
1066
1067        @Override
1068        public void onCallHoldFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1069            if (DBG) log("onCallHoldFailed reasonCode=" + reasonInfo.getCode());
1070
1071            synchronized (mSyncHold) {
1072                ImsPhoneCall.State bgState = mBackgroundCall.getState();
1073                if (reasonInfo.getCode() == ImsReasonInfo.CODE_LOCAL_CALL_TERMINATED) {
1074                    // disconnected while processing hold
1075                    if (mPendingMO != null) {
1076                        sendEmptyMessage(EVENT_DIAL_PENDINGMO);
1077                    }
1078                } else if (bgState == ImsPhoneCall.State.ACTIVE) {
1079                    mForegroundCall.switchWith(mBackgroundCall);
1080
1081                    if (mPendingMO != null) {
1082                        mPendingMO.setDisconnectCause(DisconnectCause.ERROR_UNSPECIFIED);
1083                        sendEmptyMessageDelayed(EVENT_HANGUP_PENDINGMO, TIMEOUT_HANGUP_PENDINGMO);
1084                    }
1085                }
1086            }
1087        }
1088
1089        @Override
1090        public void onCallResumed(ImsCall imsCall) {
1091            if (DBG) log("onCallResumed");
1092
1093            // If we are the in midst of swapping FG and BG calls and the call we end up resuming
1094            // is not the one we expected, we likely had a resume failure and we need to swap the
1095            // FG and BG calls back.
1096            if (mSwitchingFgAndBgCalls && imsCall != mCallExpectedToResume) {
1097                mForegroundCall.switchWith(mBackgroundCall);
1098                mSwitchingFgAndBgCalls = false;
1099                mCallExpectedToResume = null;
1100            }
1101            processCallStateChange(imsCall, ImsPhoneCall.State.ACTIVE,
1102                    DisconnectCause.NOT_DISCONNECTED);
1103        }
1104
1105        @Override
1106        public void onCallResumeFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1107            // TODO : What should be done?
1108            // If we are in the midst of swapping the FG and BG calls and we got a resume fail, we
1109            // need to swap back the FG and BG calls.
1110            if (mSwitchingFgAndBgCalls && imsCall == mCallExpectedToResume) {
1111                mForegroundCall.switchWith(mBackgroundCall);
1112                mCallExpectedToResume = null;
1113                mSwitchingFgAndBgCalls = false;
1114            }
1115            mPhone.notifySuppServiceFailed(Phone.SuppService.RESUME);
1116        }
1117
1118        @Override
1119        public void onCallResumeReceived(ImsCall imsCall) {
1120            if (DBG) log("onCallResumeReceived");
1121
1122            if (mOnHoldToneStarted) {
1123                mPhone.stopOnHoldTone();
1124                mOnHoldToneStarted = false;
1125            }
1126        }
1127
1128        @Override
1129        public void onCallHoldReceived(ImsCall imsCall) {
1130            if (DBG) log("onCallHoldReceived");
1131
1132            ImsPhoneConnection conn = findConnection(imsCall);
1133            if (conn != null && conn.getState() == ImsPhoneCall.State.ACTIVE) {
1134                if (!mOnHoldToneStarted && ImsPhoneCall.isLocalTone(imsCall)) {
1135                    mPhone.startOnHoldTone();
1136                    mOnHoldToneStarted = true;
1137                }
1138            }
1139        }
1140
1141        @Override
1142        public void onCallMerged(ImsCall call) {
1143            if (DBG) log("onCallMerged");
1144
1145            mForegroundCall.merge(mBackgroundCall, mForegroundCall.getState());
1146            updatePhoneState();
1147            mPhone.notifyPreciseCallStateChanged();
1148        }
1149
1150        @Override
1151        public void onCallMergeFailed(ImsCall call, ImsReasonInfo reasonInfo) {
1152            if (DBG) log("onCallMergeFailed reasonInfo=" + reasonInfo);
1153            mPhone.notifySuppServiceFailed(Phone.SuppService.CONFERENCE);
1154        }
1155
1156        /**
1157         * Called when the state of IMS conference participant(s) has changed.
1158         *
1159         * @param call the call object that carries out the IMS call.
1160         * @param participants the participant(s) and their new state information.
1161         */
1162        @Override
1163        public void onConferenceParticipantsStateChanged(ImsCall call,
1164                List<ConferenceParticipant> participants) {
1165            if (DBG) log("onConferenceParticipantsStateChanged");
1166
1167            ImsPhoneConnection conn = findConnection(call);
1168            if (conn != null) {
1169                conn.updateConferenceParticipants(participants);
1170            }
1171        }
1172
1173        @Override
1174        public void onCallSessionTtyModeReceived(ImsCall call, int mode) {
1175            mPhone.onTtyModeReceived(mode);
1176        }
1177    };
1178
1179    /**
1180     * Listen to the IMS call state change
1181     */
1182    private ImsCall.Listener mImsUssdListener = new ImsCall.Listener() {
1183        @Override
1184        public void onCallStarted(ImsCall imsCall) {
1185            if (DBG) log("mImsUssdListener onCallStarted");
1186
1187            if (imsCall == mUssdSession) {
1188                if (mPendingUssd != null) {
1189                    AsyncResult.forMessage(mPendingUssd);
1190                    mPendingUssd.sendToTarget();
1191                    mPendingUssd = null;
1192                }
1193            }
1194        }
1195
1196        @Override
1197        public void onCallStartFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1198            if (DBG) log("mImsUssdListener onCallStartFailed reasonCode=" + reasonInfo.getCode());
1199
1200            onCallTerminated(imsCall, reasonInfo);
1201        }
1202
1203        @Override
1204        public void onCallTerminated(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1205            if (DBG) log("mImsUssdListener onCallTerminated reasonCode=" + reasonInfo.getCode());
1206
1207            if (imsCall == mUssdSession) {
1208                mUssdSession = null;
1209                if (mPendingUssd != null) {
1210                    CommandException ex =
1211                            new CommandException(CommandException.Error.GENERIC_FAILURE);
1212                    AsyncResult.forMessage(mPendingUssd, null, ex);
1213                    mPendingUssd.sendToTarget();
1214                    mPendingUssd = null;
1215                }
1216            }
1217            imsCall.close();
1218        }
1219
1220        @Override
1221        public void onCallUssdMessageReceived(ImsCall call,
1222                int mode, String ussdMessage) {
1223            if (DBG) log("mImsUssdListener onCallUssdMessageReceived mode=" + mode);
1224
1225            int ussdMode = -1;
1226
1227            switch(mode) {
1228                case ImsCall.USSD_MODE_REQUEST:
1229                    ussdMode = CommandsInterface.USSD_MODE_REQUEST;
1230                    break;
1231
1232                case ImsCall.USSD_MODE_NOTIFY:
1233                    ussdMode = CommandsInterface.USSD_MODE_NOTIFY;
1234                    break;
1235            }
1236
1237            mPhone.onIncomingUSSD(ussdMode, ussdMessage);
1238        }
1239    };
1240
1241    /**
1242     * Listen to the IMS service state change
1243     *
1244     */
1245    private ImsConnectionStateListener mImsConnectionStateListener =
1246        new ImsConnectionStateListener() {
1247        @Override
1248        public void onImsConnected() {
1249            if (DBG) log("onImsConnected");
1250            mPhone.setServiceState(ServiceState.STATE_IN_SERVICE);
1251            mPhone.setImsRegistered(true);
1252        }
1253
1254        @Override
1255        public void onImsDisconnected() {
1256            if (DBG) log("onImsDisconnected");
1257            mPhone.setServiceState(ServiceState.STATE_OUT_OF_SERVICE);
1258            mPhone.setImsRegistered(false);
1259        }
1260
1261        @Override
1262        public void onImsResumed() {
1263            if (DBG) log("onImsResumed");
1264            mPhone.setServiceState(ServiceState.STATE_IN_SERVICE);
1265        }
1266
1267        @Override
1268        public void onImsSuspended() {
1269            if (DBG) log("onImsSuspended");
1270            mPhone.setServiceState(ServiceState.STATE_OUT_OF_SERVICE);
1271        }
1272
1273        @Override
1274        public void onFeatureCapabilityChanged(int serviceClass,
1275                int[] enabledFeatures, int[] disabledFeatures) {
1276            if (serviceClass == ImsServiceClass.MMTEL) {
1277                if (enabledFeatures[ImsConfig.FeatureConstants.FEATURE_TYPE_VOICE_OVER_LTE] ==
1278                        ImsConfig.FeatureConstants.FEATURE_TYPE_VOICE_OVER_LTE) {
1279                    mIsVolteEnabled = true;
1280                }
1281                if (enabledFeatures[ImsConfig.FeatureConstants.FEATURE_TYPE_VIDEO_OVER_LTE] ==
1282                        ImsConfig.FeatureConstants.FEATURE_TYPE_VIDEO_OVER_LTE) {
1283                    mIsVtEnabled = true;
1284                }
1285                if (disabledFeatures[ImsConfig.FeatureConstants.FEATURE_TYPE_VOICE_OVER_LTE] ==
1286                        ImsConfig.FeatureConstants.FEATURE_TYPE_VOICE_OVER_LTE) {
1287                    mIsVolteEnabled = false;
1288                }
1289                if (disabledFeatures[ImsConfig.FeatureConstants.FEATURE_TYPE_VIDEO_OVER_LTE] ==
1290                        ImsConfig.FeatureConstants.FEATURE_TYPE_VIDEO_OVER_LTE) {
1291                    mIsVtEnabled = false;
1292                }
1293            }
1294            if (DBG) log("onFeatureCapabilityChanged, mIsVolteEnabled = " +  mIsVolteEnabled
1295                    + " mIsVtEnabled = " + mIsVtEnabled);
1296        }
1297    };
1298
1299    /* package */
1300    ImsUtInterface getUtInterface() throws ImsException {
1301        if (mImsManager == null) {
1302            throw new ImsException("no ims manager", ImsReasonInfo.CODE_UNSPECIFIED);
1303        }
1304
1305        ImsUtInterface ut = mImsManager.getSupplementaryServiceConfiguration(mServiceId);
1306        return ut;
1307    }
1308
1309    private void transferHandoverConnections(ImsPhoneCall call) {
1310        if (call.mConnections != null) {
1311            for (Connection c : call.mConnections) {
1312                c.mPreHandoverState = call.mState;
1313                log ("Connection state before handover is " + c.getStateBeforeHandover());
1314            }
1315        }
1316        if (mHandoverCall.mConnections == null ) {
1317            mHandoverCall.mConnections = call.mConnections;
1318        } else { // Multi-call SRVCC
1319            mHandoverCall.mConnections.addAll(call.mConnections);
1320        }
1321        if (mHandoverCall.mConnections != null) {
1322            if (call.getImsCall() != null) {
1323                call.getImsCall().close();
1324            }
1325            for (Connection c : mHandoverCall.mConnections) {
1326                ((ImsPhoneConnection)c).changeParent(mHandoverCall);
1327                ((ImsPhoneConnection)c).releaseWakeLock();
1328            }
1329        }
1330        if (call.getState().isAlive()) {
1331            log ("Call is alive and state is " + call.mState);
1332            mHandoverCall.mState = call.mState;
1333        }
1334        call.mConnections.clear();
1335        call.mState = ImsPhoneCall.State.IDLE;
1336    }
1337
1338    /* package */
1339    void notifySrvccState(Call.SrvccState state) {
1340        if (DBG) log("notifySrvccState state=" + state);
1341
1342        mSrvccState = state;
1343
1344        if (mSrvccState == Call.SrvccState.COMPLETED) {
1345            transferHandoverConnections(mForegroundCall);
1346            transferHandoverConnections(mBackgroundCall);
1347            transferHandoverConnections(mRingingCall);
1348        }
1349    }
1350
1351    //****** Overridden from Handler
1352
1353    @Override
1354    public void
1355    handleMessage (Message msg) {
1356        AsyncResult ar;
1357        if (DBG) log("handleMessage what=" + msg.what);
1358
1359        switch (msg.what) {
1360            case EVENT_HANGUP_PENDINGMO:
1361                if (mPendingMO != null) {
1362                    mPendingMO.onDisconnect();
1363                    removeConnection(mPendingMO);
1364                    mPendingMO = null;
1365                }
1366
1367                updatePhoneState();
1368                mPhone.notifyPreciseCallStateChanged();
1369                break;
1370            case EVENT_RESUME_BACKGROUND:
1371                try {
1372                    resumeWaitingOrHolding();
1373                } catch (CallStateException e) {
1374                    if (Phone.DEBUG_PHONE) {
1375                        loge("handleMessage EVENT_RESUME_BACKGROUND exception=" + e);
1376                    }
1377                }
1378                break;
1379            case EVENT_DIAL_PENDINGMO:
1380                dialInternal(mPendingMO, mClirMode, VideoProfile.VideoState.AUDIO_ONLY);
1381                break;
1382
1383            case EVENT_EXIT_ECM_RESPONSE_CDMA:
1384                // no matter the result, we still do the same here
1385                if (pendingCallInEcm) {
1386                    dialInternal(mPendingMO, pendingCallClirMode, pendingCallVideoState);
1387                    pendingCallInEcm = false;
1388                }
1389                mPhone.unsetOnEcbModeExitResponse(this);
1390                break;
1391        }
1392    }
1393
1394    @Override
1395    protected void log(String msg) {
1396        Rlog.d(LOG_TAG, "[ImsPhoneCallTracker] " + msg);
1397    }
1398
1399    protected void loge(String msg) {
1400        Rlog.e(LOG_TAG, "[ImsPhoneCallTracker] " + msg);
1401    }
1402
1403    @Override
1404    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1405        pw.println("ImsPhoneCallTracker extends:");
1406        super.dump(fd, pw, args);
1407        pw.println(" mVoiceCallEndedRegistrants=" + mVoiceCallEndedRegistrants);
1408        pw.println(" mVoiceCallStartedRegistrants=" + mVoiceCallStartedRegistrants);
1409        pw.println(" mRingingCall=" + mRingingCall);
1410        pw.println(" mForegroundCall=" + mForegroundCall);
1411        pw.println(" mBackgroundCall=" + mBackgroundCall);
1412        pw.println(" mHandoverCall=" + mHandoverCall);
1413        pw.println(" mPendingMO=" + mPendingMO);
1414        //pw.println(" mHangupPendingMO=" + mHangupPendingMO);
1415        pw.println(" mPhone=" + mPhone);
1416        pw.println(" mDesiredMute=" + mDesiredMute);
1417        pw.println(" mState=" + mState);
1418    }
1419
1420    @Override
1421    protected void handlePollCalls(AsyncResult ar) {
1422    }
1423
1424    /* package */
1425    ImsEcbm getEcbmInterface() throws ImsException {
1426        if (mImsManager == null) {
1427            throw new ImsException("no ims manager", ImsReasonInfo.CODE_UNSPECIFIED);
1428        }
1429
1430        ImsEcbm ecbm = mImsManager.getEcbmInterface(mServiceId);
1431        return ecbm;
1432    }
1433
1434    public boolean isInEmergencyCall() {
1435        return mIsInEmergencyCall;
1436    }
1437
1438    public boolean isVolteEnabled() {
1439        return mIsVolteEnabled;
1440    }
1441
1442    public boolean isVtEnabled() {
1443        return mIsVtEnabled;
1444    }
1445}
1446