1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.telecom;
18
19import com.android.internal.telecom.IVideoCallback;
20import com.android.internal.telecom.IVideoProvider;
21
22import android.annotation.SystemApi;
23import android.net.Uri;
24import android.os.Handler;
25import android.os.IBinder;
26import android.os.Message;
27import android.os.RemoteException;
28import android.view.Surface;
29
30import java.util.ArrayList;
31import java.util.Collections;
32import java.util.List;
33import java.util.Set;
34import java.util.concurrent.ConcurrentHashMap;
35
36/**
37 * Represents a connection to a remote endpoint that carries voice traffic.
38 * <p>
39 * Implementations create a custom subclass of {@code Connection} and return it to the framework
40 * as the return value of
41 * {@link ConnectionService#onCreateIncomingConnection(PhoneAccountHandle, ConnectionRequest)}
42 * or
43 * {@link ConnectionService#onCreateOutgoingConnection(PhoneAccountHandle, ConnectionRequest)}.
44 * Implementations are then responsible for updating the state of the {@code Connection}, and
45 * must call {@link #destroy()} to signal to the framework that the {@code Connection} is no
46 * longer used and associated resources may be recovered.
47 * @hide
48 */
49@SystemApi
50public abstract class Connection implements IConferenceable {
51
52    public static final int STATE_INITIALIZING = 0;
53
54    public static final int STATE_NEW = 1;
55
56    public static final int STATE_RINGING = 2;
57
58    public static final int STATE_DIALING = 3;
59
60    public static final int STATE_ACTIVE = 4;
61
62    public static final int STATE_HOLDING = 5;
63
64    public static final int STATE_DISCONNECTED = 6;
65
66    /** Connection can currently be put on hold or unheld. */
67    public static final int CAPABILITY_HOLD = 0x00000001;
68
69    /** Connection supports the hold feature. */
70    public static final int CAPABILITY_SUPPORT_HOLD = 0x00000002;
71
72    /**
73     * Connections within a conference can be merged. A {@link ConnectionService} has the option to
74     * add a {@link Conference} before the child {@link Connection}s are merged. This is how
75     * CDMA-based {@link Connection}s are implemented. For these unmerged {@link Conference}s, this
76     * capability allows a merge button to be shown while the conference is in the foreground
77     * of the in-call UI.
78     * <p>
79     * This is only intended for use by a {@link Conference}.
80     */
81    public static final int CAPABILITY_MERGE_CONFERENCE = 0x00000004;
82
83    /**
84     * Connections within a conference can be swapped between foreground and background.
85     * See {@link #CAPABILITY_MERGE_CONFERENCE} for additional information.
86     * <p>
87     * This is only intended for use by a {@link Conference}.
88     */
89    public static final int CAPABILITY_SWAP_CONFERENCE = 0x00000008;
90
91    /**
92     * @hide
93     */
94    public static final int CAPABILITY_UNUSED = 0x00000010;
95
96    /** Connection supports responding via text option. */
97    public static final int CAPABILITY_RESPOND_VIA_TEXT = 0x00000020;
98
99    /** Connection can be muted. */
100    public static final int CAPABILITY_MUTE = 0x00000040;
101
102    /**
103     * Connection supports conference management. This capability only applies to
104     * {@link Conference}s which can have {@link Connection}s as children.
105     */
106    public static final int CAPABILITY_MANAGE_CONFERENCE = 0x00000080;
107
108    /**
109     * Local device supports video telephony.
110     * @hide
111     */
112    public static final int CAPABILITY_SUPPORTS_VT_LOCAL = 0x00000100;
113
114    /**
115     * Remote device supports video telephony.
116     * @hide
117     */
118    public static final int CAPABILITY_SUPPORTS_VT_REMOTE = 0x00000200;
119
120    /**
121     * Connection is using high definition audio.
122     * @hide
123     */
124    public static final int CAPABILITY_HIGH_DEF_AUDIO = 0x00000400;
125
126    /**
127     * Connection is using voice over WIFI.
128     * @hide
129     */
130    public static final int CAPABILITY_VoWIFI = 0x00000800;
131
132    /**
133     * Connection is able to be separated from its parent {@code Conference}, if any.
134     */
135    public static final int CAPABILITY_SEPARATE_FROM_CONFERENCE = 0x00001000;
136
137    /**
138     * Connection is able to be individually disconnected when in a {@code Conference}.
139     */
140    public static final int CAPABILITY_DISCONNECT_FROM_CONFERENCE = 0x00002000;
141
142    /**
143     * Whether the call is a generic conference, where we do not know the precise state of
144     * participants in the conference (eg. on CDMA).
145     *
146     * @hide
147     */
148    public static final int CAPABILITY_GENERIC_CONFERENCE = 0x00004000;
149
150    /**
151     * Speed up audio setup for MT call.
152     * @hide
153    */
154    public static final int CAPABILITY_SPEED_UP_MT_AUDIO = 0x00008000;
155
156    // Flag controlling whether PII is emitted into the logs
157    private static final boolean PII_DEBUG = Log.isLoggable(android.util.Log.DEBUG);
158
159    /**
160     * Whether the given capabilities support the specified capability.
161     *
162     * @param capabilities A capability bit field.
163     * @param capability The capability to check capabilities for.
164     * @return Whether the specified capability is supported.
165     * @hide
166     */
167    public static boolean can(int capabilities, int capability) {
168        return (capabilities & capability) != 0;
169    }
170
171    /**
172     * Whether the capabilities of this {@code Connection} supports the specified capability.
173     *
174     * @param capability The capability to check capabilities for.
175     * @return Whether the specified capability is supported.
176     * @hide
177     */
178    public boolean can(int capability) {
179        return can(mConnectionCapabilities, capability);
180    }
181
182    /**
183     * Removes the specified capability from the set of capabilities of this {@code Connection}.
184     *
185     * @param capability The capability to remove from the set.
186     * @hide
187     */
188    public void removeCapability(int capability) {
189        mConnectionCapabilities &= ~capability;
190    }
191
192    /**
193     * Adds the specified capability to the set of capabilities of this {@code Connection}.
194     *
195     * @param capability The capability to add to the set.
196     * @hide
197     */
198    public void addCapability(int capability) {
199        mConnectionCapabilities |= capability;
200    }
201
202
203    public static String capabilitiesToString(int capabilities) {
204        StringBuilder builder = new StringBuilder();
205        builder.append("[Capabilities:");
206        if (can(capabilities, CAPABILITY_HOLD)) {
207            builder.append(" CAPABILITY_HOLD");
208        }
209        if (can(capabilities, CAPABILITY_SUPPORT_HOLD)) {
210            builder.append(" CAPABILITY_SUPPORT_HOLD");
211        }
212        if (can(capabilities, CAPABILITY_MERGE_CONFERENCE)) {
213            builder.append(" CAPABILITY_MERGE_CONFERENCE");
214        }
215        if (can(capabilities, CAPABILITY_SWAP_CONFERENCE)) {
216            builder.append(" CAPABILITY_SWAP_CONFERENCE");
217        }
218        if (can(capabilities, CAPABILITY_RESPOND_VIA_TEXT)) {
219            builder.append(" CAPABILITY_RESPOND_VIA_TEXT");
220        }
221        if (can(capabilities, CAPABILITY_MUTE)) {
222            builder.append(" CAPABILITY_MUTE");
223        }
224        if (can(capabilities, CAPABILITY_MANAGE_CONFERENCE)) {
225            builder.append(" CAPABILITY_MANAGE_CONFERENCE");
226        }
227        if (can(capabilities, CAPABILITY_SUPPORTS_VT_LOCAL)) {
228            builder.append(" CAPABILITY_SUPPORTS_VT_LOCAL");
229        }
230        if (can(capabilities, CAPABILITY_SUPPORTS_VT_REMOTE)) {
231            builder.append(" CAPABILITY_SUPPORTS_VT_REMOTE");
232        }
233        if (can(capabilities, CAPABILITY_HIGH_DEF_AUDIO)) {
234            builder.append(" CAPABILITY_HIGH_DEF_AUDIO");
235        }
236        if (can(capabilities, CAPABILITY_VoWIFI)) {
237            builder.append(" CAPABILITY_VoWIFI");
238        }
239        if (can(capabilities, CAPABILITY_GENERIC_CONFERENCE)) {
240            builder.append(" CAPABILITY_GENERIC_CONFERENCE");
241        }
242        if (can(capabilities, CAPABILITY_SPEED_UP_MT_AUDIO)) {
243            builder.append(" CAPABILITY_SPEED_UP_IMS_MT_AUDIO");
244        }
245        builder.append("]");
246        return builder.toString();
247    }
248
249    /** @hide */
250    public abstract static class Listener {
251        public void onStateChanged(Connection c, int state) {}
252        public void onAddressChanged(Connection c, Uri newAddress, int presentation) {}
253        public void onCallerDisplayNameChanged(
254                Connection c, String callerDisplayName, int presentation) {}
255        public void onVideoStateChanged(Connection c, int videoState) {}
256        public void onDisconnected(Connection c, DisconnectCause disconnectCause) {}
257        public void onPostDialWait(Connection c, String remaining) {}
258        public void onPostDialChar(Connection c, char nextChar) {}
259        public void onRingbackRequested(Connection c, boolean ringback) {}
260        public void onDestroyed(Connection c) {}
261        public void onConnectionCapabilitiesChanged(Connection c, int capabilities) {}
262        public void onVideoProviderChanged(
263                Connection c, VideoProvider videoProvider) {}
264        public void onAudioModeIsVoipChanged(Connection c, boolean isVoip) {}
265        public void onStatusHintsChanged(Connection c, StatusHints statusHints) {}
266        public void onConferenceablesChanged(
267                Connection c, List<IConferenceable> conferenceables) {}
268        public void onConferenceChanged(Connection c, Conference conference) {}
269        /** @hide */
270        public void onConferenceParticipantsChanged(Connection c,
271                List<ConferenceParticipant> participants) {}
272        public void onConferenceStarted() {}
273    }
274
275    /** @hide */
276    public static abstract class VideoProvider {
277
278        /**
279         * Video is not being received (no protocol pause was issued).
280         */
281        public static final int SESSION_EVENT_RX_PAUSE = 1;
282
283        /**
284         * Video reception has resumed after a SESSION_EVENT_RX_PAUSE.
285         */
286        public static final int SESSION_EVENT_RX_RESUME = 2;
287
288        /**
289         * Video transmission has begun. This occurs after a negotiated start of video transmission
290         * when the underlying protocol has actually begun transmitting video to the remote party.
291         */
292        public static final int SESSION_EVENT_TX_START = 3;
293
294        /**
295         * Video transmission has stopped. This occurs after a negotiated stop of video transmission
296         * when the underlying protocol has actually stopped transmitting video to the remote party.
297         */
298        public static final int SESSION_EVENT_TX_STOP = 4;
299
300        /**
301         * A camera failure has occurred for the selected camera.  The In-Call UI can use this as a
302         * cue to inform the user the camera is not available.
303         */
304        public static final int SESSION_EVENT_CAMERA_FAILURE = 5;
305
306        /**
307         * Issued after {@code SESSION_EVENT_CAMERA_FAILURE} when the camera is once again ready for
308         * operation.  The In-Call UI can use this as a cue to inform the user that the camera has
309         * become available again.
310         */
311        public static final int SESSION_EVENT_CAMERA_READY = 6;
312
313        /**
314         * Session modify request was successful.
315         */
316        public static final int SESSION_MODIFY_REQUEST_SUCCESS = 1;
317
318        /**
319         * Session modify request failed.
320         */
321        public static final int SESSION_MODIFY_REQUEST_FAIL = 2;
322
323        /**
324         * Session modify request ignored due to invalid parameters.
325         */
326        public static final int SESSION_MODIFY_REQUEST_INVALID = 3;
327
328        private static final int MSG_SET_VIDEO_CALLBACK = 1;
329        private static final int MSG_SET_CAMERA = 2;
330        private static final int MSG_SET_PREVIEW_SURFACE = 3;
331        private static final int MSG_SET_DISPLAY_SURFACE = 4;
332        private static final int MSG_SET_DEVICE_ORIENTATION = 5;
333        private static final int MSG_SET_ZOOM = 6;
334        private static final int MSG_SEND_SESSION_MODIFY_REQUEST = 7;
335        private static final int MSG_SEND_SESSION_MODIFY_RESPONSE = 8;
336        private static final int MSG_REQUEST_CAMERA_CAPABILITIES = 9;
337        private static final int MSG_REQUEST_CONNECTION_DATA_USAGE = 10;
338        private static final int MSG_SET_PAUSE_IMAGE = 11;
339
340        private final VideoProvider.VideoProviderHandler
341                mMessageHandler = new VideoProvider.VideoProviderHandler();
342        private final VideoProvider.VideoProviderBinder mBinder;
343        private IVideoCallback mVideoCallback;
344
345        /**
346         * Default handler used to consolidate binder method calls onto a single thread.
347         */
348        private final class VideoProviderHandler extends Handler {
349            @Override
350            public void handleMessage(Message msg) {
351                switch (msg.what) {
352                    case MSG_SET_VIDEO_CALLBACK:
353                        mVideoCallback = IVideoCallback.Stub.asInterface((IBinder) msg.obj);
354                        break;
355                    case MSG_SET_CAMERA:
356                        onSetCamera((String) msg.obj);
357                        break;
358                    case MSG_SET_PREVIEW_SURFACE:
359                        onSetPreviewSurface((Surface) msg.obj);
360                        break;
361                    case MSG_SET_DISPLAY_SURFACE:
362                        onSetDisplaySurface((Surface) msg.obj);
363                        break;
364                    case MSG_SET_DEVICE_ORIENTATION:
365                        onSetDeviceOrientation(msg.arg1);
366                        break;
367                    case MSG_SET_ZOOM:
368                        onSetZoom((Float) msg.obj);
369                        break;
370                    case MSG_SEND_SESSION_MODIFY_REQUEST:
371                        onSendSessionModifyRequest((VideoProfile) msg.obj);
372                        break;
373                    case MSG_SEND_SESSION_MODIFY_RESPONSE:
374                        onSendSessionModifyResponse((VideoProfile) msg.obj);
375                        break;
376                    case MSG_REQUEST_CAMERA_CAPABILITIES:
377                        onRequestCameraCapabilities();
378                        break;
379                    case MSG_REQUEST_CONNECTION_DATA_USAGE:
380                        onRequestConnectionDataUsage();
381                        break;
382                    case MSG_SET_PAUSE_IMAGE:
383                        onSetPauseImage((String) msg.obj);
384                        break;
385                    default:
386                        break;
387                }
388            }
389        }
390
391        /**
392         * IVideoProvider stub implementation.
393         */
394        private final class VideoProviderBinder extends IVideoProvider.Stub {
395            public void setVideoCallback(IBinder videoCallbackBinder) {
396                mMessageHandler.obtainMessage(
397                        MSG_SET_VIDEO_CALLBACK, videoCallbackBinder).sendToTarget();
398            }
399
400            public void setCamera(String cameraId) {
401                mMessageHandler.obtainMessage(MSG_SET_CAMERA, cameraId).sendToTarget();
402            }
403
404            public void setPreviewSurface(Surface surface) {
405                mMessageHandler.obtainMessage(MSG_SET_PREVIEW_SURFACE, surface).sendToTarget();
406            }
407
408            public void setDisplaySurface(Surface surface) {
409                mMessageHandler.obtainMessage(MSG_SET_DISPLAY_SURFACE, surface).sendToTarget();
410            }
411
412            public void setDeviceOrientation(int rotation) {
413                mMessageHandler.obtainMessage(MSG_SET_DEVICE_ORIENTATION, rotation).sendToTarget();
414            }
415
416            public void setZoom(float value) {
417                mMessageHandler.obtainMessage(MSG_SET_ZOOM, value).sendToTarget();
418            }
419
420            public void sendSessionModifyRequest(VideoProfile requestProfile) {
421                mMessageHandler.obtainMessage(
422                        MSG_SEND_SESSION_MODIFY_REQUEST, requestProfile).sendToTarget();
423            }
424
425            public void sendSessionModifyResponse(VideoProfile responseProfile) {
426                mMessageHandler.obtainMessage(
427                        MSG_SEND_SESSION_MODIFY_RESPONSE, responseProfile).sendToTarget();
428            }
429
430            public void requestCameraCapabilities() {
431                mMessageHandler.obtainMessage(MSG_REQUEST_CAMERA_CAPABILITIES).sendToTarget();
432            }
433
434            public void requestCallDataUsage() {
435                mMessageHandler.obtainMessage(MSG_REQUEST_CONNECTION_DATA_USAGE).sendToTarget();
436            }
437
438            public void setPauseImage(String uri) {
439                mMessageHandler.obtainMessage(MSG_SET_PAUSE_IMAGE, uri).sendToTarget();
440            }
441        }
442
443        public VideoProvider() {
444            mBinder = new VideoProvider.VideoProviderBinder();
445        }
446
447        /**
448         * Returns binder object which can be used across IPC methods.
449         * @hide
450         */
451        public final IVideoProvider getInterface() {
452            return mBinder;
453        }
454
455        /**
456         * Sets the camera to be used for video recording in a video connection.
457         *
458         * @param cameraId The id of the camera.
459         */
460        public abstract void onSetCamera(String cameraId);
461
462        /**
463         * Sets the surface to be used for displaying a preview of what the user's camera is
464         * currently capturing.  When video transmission is enabled, this is the video signal which
465         * is sent to the remote device.
466         *
467         * @param surface The surface.
468         */
469        public abstract void onSetPreviewSurface(Surface surface);
470
471        /**
472         * Sets the surface to be used for displaying the video received from the remote device.
473         *
474         * @param surface The surface.
475         */
476        public abstract void onSetDisplaySurface(Surface surface);
477
478        /**
479         * Sets the device orientation, in degrees.  Assumes that a standard portrait orientation of
480         * the device is 0 degrees.
481         *
482         * @param rotation The device orientation, in degrees.
483         */
484        public abstract void onSetDeviceOrientation(int rotation);
485
486        /**
487         * Sets camera zoom ratio.
488         *
489         * @param value The camera zoom ratio.
490         */
491        public abstract void onSetZoom(float value);
492
493        /**
494         * Issues a request to modify the properties of the current session.  The request is
495         * sent to the remote device where it it handled by the In-Call UI.
496         * Some examples of session modification requests: upgrade connection from audio to video,
497         * downgrade connection from video to audio, pause video.
498         *
499         * @param requestProfile The requested connection video properties.
500         */
501        public abstract void onSendSessionModifyRequest(VideoProfile requestProfile);
502
503        /**te
504         * Provides a response to a request to change the current connection session video
505         * properties.
506         * This is in response to a request the InCall UI has received via the InCall UI.
507         *
508         * @param responseProfile The response connection video properties.
509         */
510        public abstract void onSendSessionModifyResponse(VideoProfile responseProfile);
511
512        /**
513         * Issues a request to the video provider to retrieve the camera capabilities.
514         * Camera capabilities are reported back to the caller via the In-Call UI.
515         */
516        public abstract void onRequestCameraCapabilities();
517
518        /**
519         * Issues a request to the video telephony framework to retrieve the cumulative data usage
520         * for the current connection.  Data usage is reported back to the caller via the
521         * InCall UI.
522         */
523        public abstract void onRequestConnectionDataUsage();
524
525        /**
526         * Provides the video telephony framework with the URI of an image to be displayed to remote
527         * devices when the video signal is paused.
528         *
529         * @param uri URI of image to display.
530         */
531        public abstract void onSetPauseImage(String uri);
532
533        /**
534         * Invokes callback method defined in In-Call UI.
535         *
536         * @param videoProfile The requested video connection profile.
537         */
538        public void receiveSessionModifyRequest(VideoProfile videoProfile) {
539            if (mVideoCallback != null) {
540                try {
541                    mVideoCallback.receiveSessionModifyRequest(videoProfile);
542                } catch (RemoteException ignored) {
543                }
544            }
545        }
546
547        /**
548         * Invokes callback method defined in In-Call UI.
549         *
550         * @param status Status of the session modify request.  Valid values are
551         *               {@link VideoProvider#SESSION_MODIFY_REQUEST_SUCCESS},
552         *               {@link VideoProvider#SESSION_MODIFY_REQUEST_FAIL},
553         *               {@link VideoProvider#SESSION_MODIFY_REQUEST_INVALID}
554         * @param requestedProfile The original request which was sent to the remote device.
555         * @param responseProfile The actual profile changes made by the remote device.
556         */
557        public void receiveSessionModifyResponse(int status,
558                VideoProfile requestedProfile, VideoProfile responseProfile) {
559            if (mVideoCallback != null) {
560                try {
561                    mVideoCallback.receiveSessionModifyResponse(
562                            status, requestedProfile, responseProfile);
563                } catch (RemoteException ignored) {
564                }
565            }
566        }
567
568        /**
569         * Invokes callback method defined in In-Call UI.
570         *
571         * Valid values are: {@link VideoProvider#SESSION_EVENT_RX_PAUSE},
572         * {@link VideoProvider#SESSION_EVENT_RX_RESUME},
573         * {@link VideoProvider#SESSION_EVENT_TX_START},
574         * {@link VideoProvider#SESSION_EVENT_TX_STOP}
575         *
576         * @param event The event.
577         */
578        public void handleCallSessionEvent(int event) {
579            if (mVideoCallback != null) {
580                try {
581                    mVideoCallback.handleCallSessionEvent(event);
582                } catch (RemoteException ignored) {
583                }
584            }
585        }
586
587        /**
588         * Invokes callback method defined in In-Call UI.
589         *
590         * @param width  The updated peer video width.
591         * @param height The updated peer video height.
592         */
593        public void changePeerDimensions(int width, int height) {
594            if (mVideoCallback != null) {
595                try {
596                    mVideoCallback.changePeerDimensions(width, height);
597                } catch (RemoteException ignored) {
598                }
599            }
600        }
601
602        /**
603         * Invokes callback method defined in In-Call UI.
604         *
605         * @param dataUsage The updated data usage.
606         */
607        public void changeCallDataUsage(int dataUsage) {
608            if (mVideoCallback != null) {
609                try {
610                    mVideoCallback.changeCallDataUsage(dataUsage);
611                } catch (RemoteException ignored) {
612                }
613            }
614        }
615
616        /**
617         * Invokes callback method defined in In-Call UI.
618         *
619         * @param cameraCapabilities The changed camera capabilities.
620         */
621        public void changeCameraCapabilities(CameraCapabilities cameraCapabilities) {
622            if (mVideoCallback != null) {
623                try {
624                    mVideoCallback.changeCameraCapabilities(cameraCapabilities);
625                } catch (RemoteException ignored) {
626                }
627            }
628        }
629    }
630
631    private final Listener mConnectionDeathListener = new Listener() {
632        @Override
633        public void onDestroyed(Connection c) {
634            if (mConferenceables.remove(c)) {
635                fireOnConferenceableConnectionsChanged();
636            }
637        }
638    };
639
640    private final Conference.Listener mConferenceDeathListener = new Conference.Listener() {
641        @Override
642        public void onDestroyed(Conference c) {
643            if (mConferenceables.remove(c)) {
644                fireOnConferenceableConnectionsChanged();
645            }
646        }
647    };
648
649    /**
650     * ConcurrentHashMap constructor params: 8 is initial table size, 0.9f is
651     * load factor before resizing, 1 means we only expect a single thread to
652     * access the map so make only a single shard
653     */
654    private final Set<Listener> mListeners = Collections.newSetFromMap(
655            new ConcurrentHashMap<Listener, Boolean>(8, 0.9f, 1));
656    private final List<IConferenceable> mConferenceables = new ArrayList<>();
657    private final List<IConferenceable> mUnmodifiableConferenceables =
658            Collections.unmodifiableList(mConferenceables);
659
660    private int mState = STATE_NEW;
661    private AudioState mAudioState;
662    private Uri mAddress;
663    private int mAddressPresentation;
664    private String mCallerDisplayName;
665    private int mCallerDisplayNamePresentation;
666    private boolean mRingbackRequested = false;
667    private int mConnectionCapabilities;
668    private VideoProvider mVideoProvider;
669    private boolean mAudioModeIsVoip;
670    private StatusHints mStatusHints;
671    private int mVideoState;
672    private DisconnectCause mDisconnectCause;
673    private Conference mConference;
674    private ConnectionService mConnectionService;
675
676    /**
677     * Create a new Connection.
678     */
679    public Connection() {}
680
681    /**
682     * @return The address (e.g., phone number) to which this Connection is currently communicating.
683     */
684    public final Uri getAddress() {
685        return mAddress;
686    }
687
688    /**
689     * @return The presentation requirements for the address.
690     *         See {@link TelecomManager} for valid values.
691     */
692    public final int getAddressPresentation() {
693        return mAddressPresentation;
694    }
695
696    /**
697     * @return The caller display name (CNAP).
698     */
699    public final String getCallerDisplayName() {
700        return mCallerDisplayName;
701    }
702
703    /**
704     * @return The presentation requirements for the handle.
705     *         See {@link TelecomManager} for valid values.
706     */
707    public final int getCallerDisplayNamePresentation() {
708        return mCallerDisplayNamePresentation;
709    }
710
711    /**
712     * @return The state of this Connection.
713     */
714    public final int getState() {
715        return mState;
716    }
717
718    /**
719     * Returns the video state of the connection.
720     * Valid values: {@link VideoProfile.VideoState#AUDIO_ONLY},
721     * {@link VideoProfile.VideoState#BIDIRECTIONAL},
722     * {@link VideoProfile.VideoState#TX_ENABLED},
723     * {@link VideoProfile.VideoState#RX_ENABLED}.
724     *
725     * @return The video state of the connection.
726     * @hide
727     */
728    public final int getVideoState() {
729        return mVideoState;
730    }
731
732    /**
733     * @return The audio state of the connection, describing how its audio is currently
734     *         being routed by the system. This is {@code null} if this Connection
735     *         does not directly know about its audio state.
736     */
737    public final AudioState getAudioState() {
738        return mAudioState;
739    }
740
741    /**
742     * @return The conference that this connection is a part of.  Null if it is not part of any
743     *         conference.
744     */
745    public final Conference getConference() {
746        return mConference;
747    }
748
749    /**
750     * Returns whether this connection is requesting that the system play a ringback tone
751     * on its behalf.
752     */
753    public final boolean isRingbackRequested() {
754        return mRingbackRequested;
755    }
756
757    /**
758     * @return True if the connection's audio mode is VOIP.
759     */
760    public final boolean getAudioModeIsVoip() {
761        return mAudioModeIsVoip;
762    }
763
764    /**
765     * @return The status hints for this connection.
766     */
767    public final StatusHints getStatusHints() {
768        return mStatusHints;
769    }
770
771    /**
772     * Assign a listener to be notified of state changes.
773     *
774     * @param l A listener.
775     * @return This Connection.
776     *
777     * @hide
778     */
779    public final Connection addConnectionListener(Listener l) {
780        mListeners.add(l);
781        return this;
782    }
783
784    /**
785     * Remove a previously assigned listener that was being notified of state changes.
786     *
787     * @param l A Listener.
788     * @return This Connection.
789     *
790     * @hide
791     */
792    public final Connection removeConnectionListener(Listener l) {
793        if (l != null) {
794            mListeners.remove(l);
795        }
796        return this;
797    }
798
799    /**
800     * @return The {@link DisconnectCause} for this connection.
801     */
802    public final DisconnectCause getDisconnectCause() {
803        return mDisconnectCause;
804    }
805
806    /**
807     * Inform this Connection that the state of its audio output has been changed externally.
808     *
809     * @param state The new audio state.
810     * @hide
811     */
812    final void setAudioState(AudioState state) {
813        checkImmutable();
814        Log.d(this, "setAudioState %s", state);
815        mAudioState = state;
816        onAudioStateChanged(state);
817    }
818
819    /**
820     * @param state An integer value of a {@code STATE_*} constant.
821     * @return A string representation of the value.
822     */
823    public static String stateToString(int state) {
824        switch (state) {
825            case STATE_INITIALIZING:
826                return "STATE_INITIALIZING";
827            case STATE_NEW:
828                return "STATE_NEW";
829            case STATE_RINGING:
830                return "STATE_RINGING";
831            case STATE_DIALING:
832                return "STATE_DIALING";
833            case STATE_ACTIVE:
834                return "STATE_ACTIVE";
835            case STATE_HOLDING:
836                return "STATE_HOLDING";
837            case STATE_DISCONNECTED:
838                return "DISCONNECTED";
839            default:
840                Log.wtf(Connection.class, "Unknown state %d", state);
841                return "UNKNOWN";
842        }
843    }
844
845    /**
846     * Returns the connection's capabilities, as a bit mask of the {@code CAPABILITY_*} constants.
847     */
848    public final int getConnectionCapabilities() {
849        return mConnectionCapabilities;
850    }
851
852    /** @hide */
853    @SystemApi @Deprecated public final int getCallCapabilities() {
854        return getConnectionCapabilities();
855    }
856
857    /**
858     * Sets the value of the {@link #getAddress()} property.
859     *
860     * @param address The new address.
861     * @param presentation The presentation requirements for the address.
862     *        See {@link TelecomManager} for valid values.
863     */
864    public final void setAddress(Uri address, int presentation) {
865        checkImmutable();
866        Log.d(this, "setAddress %s", address);
867        mAddress = address;
868        mAddressPresentation = presentation;
869        for (Listener l : mListeners) {
870            l.onAddressChanged(this, address, presentation);
871        }
872    }
873
874    /**
875     * Sets the caller display name (CNAP).
876     *
877     * @param callerDisplayName The new display name.
878     * @param presentation The presentation requirements for the handle.
879     *        See {@link TelecomManager} for valid values.
880     */
881    public final void setCallerDisplayName(String callerDisplayName, int presentation) {
882        checkImmutable();
883        Log.d(this, "setCallerDisplayName %s", callerDisplayName);
884        mCallerDisplayName = callerDisplayName;
885        mCallerDisplayNamePresentation = presentation;
886        for (Listener l : mListeners) {
887            l.onCallerDisplayNameChanged(this, callerDisplayName, presentation);
888        }
889    }
890
891    /**
892     * Set the video state for the connection.
893     * Valid values: {@link VideoProfile.VideoState#AUDIO_ONLY},
894     * {@link VideoProfile.VideoState#BIDIRECTIONAL},
895     * {@link VideoProfile.VideoState#TX_ENABLED},
896     * {@link VideoProfile.VideoState#RX_ENABLED}.
897     *
898     * @param videoState The new video state.
899     * @hide
900     */
901    public final void setVideoState(int videoState) {
902        checkImmutable();
903        Log.d(this, "setVideoState %d", videoState);
904        mVideoState = videoState;
905        for (Listener l : mListeners) {
906            l.onVideoStateChanged(this, mVideoState);
907        }
908    }
909
910    /**
911     * Sets state to active (e.g., an ongoing connection where two or more parties can actively
912     * communicate).
913     */
914    public final void setActive() {
915        checkImmutable();
916        setRingbackRequested(false);
917        setState(STATE_ACTIVE);
918    }
919
920    /**
921     * Sets state to ringing (e.g., an inbound ringing connection).
922     */
923    public final void setRinging() {
924        checkImmutable();
925        setState(STATE_RINGING);
926    }
927
928    /**
929     * Sets state to initializing (this Connection is not yet ready to be used).
930     */
931    public final void setInitializing() {
932        checkImmutable();
933        setState(STATE_INITIALIZING);
934    }
935
936    /**
937     * Sets state to initialized (the Connection has been set up and is now ready to be used).
938     */
939    public final void setInitialized() {
940        checkImmutable();
941        setState(STATE_NEW);
942    }
943
944    /**
945     * Sets state to dialing (e.g., dialing an outbound connection).
946     */
947    public final void setDialing() {
948        checkImmutable();
949        setState(STATE_DIALING);
950    }
951
952    /**
953     * Sets state to be on hold.
954     */
955    public final void setOnHold() {
956        checkImmutable();
957        setState(STATE_HOLDING);
958    }
959
960    /**
961     * Sets the video connection provider.
962     * @param videoProvider The video provider.
963     * @hide
964     */
965    public final void setVideoProvider(VideoProvider videoProvider) {
966        checkImmutable();
967        mVideoProvider = videoProvider;
968        for (Listener l : mListeners) {
969            l.onVideoProviderChanged(this, videoProvider);
970        }
971    }
972
973    /** @hide */
974    public final VideoProvider getVideoProvider() {
975        return mVideoProvider;
976    }
977
978    /**
979     * Sets state to disconnected.
980     *
981     * @param disconnectCause The reason for the disconnection, as specified by
982     *         {@link DisconnectCause}.
983     */
984    public final void setDisconnected(DisconnectCause disconnectCause) {
985        checkImmutable();
986        mDisconnectCause = disconnectCause;
987        setState(STATE_DISCONNECTED);
988        Log.d(this, "Disconnected with cause %s", disconnectCause);
989        for (Listener l : mListeners) {
990            l.onDisconnected(this, disconnectCause);
991        }
992    }
993
994    /**
995     * Informs listeners that this {@code Connection} is in a post-dial wait state. This is done
996     * when (a) the {@code Connection} is issuing a DTMF sequence; (b) it has encountered a "wait"
997     * character; and (c) it wishes to inform the In-Call app that it is waiting for the end-user
998     * to send an {@link #onPostDialContinue(boolean)} signal.
999     *
1000     * @param remaining The DTMF character sequence remaining to be emitted once the
1001     *         {@link #onPostDialContinue(boolean)} is received, including any "wait" characters
1002     *         that remaining sequence may contain.
1003     */
1004    public final void setPostDialWait(String remaining) {
1005        checkImmutable();
1006        for (Listener l : mListeners) {
1007            l.onPostDialWait(this, remaining);
1008        }
1009    }
1010
1011    /**
1012     * Informs listeners that this {@code Connection} has processed a character in the post-dial
1013     * started state. This is done when (a) the {@code Connection} is issuing a DTMF sequence;
1014     * (b) it has encountered a "wait" character; and (c) it wishes to signal Telecom to play
1015     * the corresponding DTMF tone locally.
1016     *
1017     * @param nextChar The DTMF character that was just processed by the {@code Connection}.
1018     *
1019     * @hide
1020     */
1021    public final void setNextPostDialWaitChar(char nextChar) {
1022        checkImmutable();
1023        for (Listener l : mListeners) {
1024            l.onPostDialChar(this, nextChar);
1025        }
1026    }
1027
1028    /**
1029     * Requests that the framework play a ringback tone. This is to be invoked by implementations
1030     * that do not play a ringback tone themselves in the connection's audio stream.
1031     *
1032     * @param ringback Whether the ringback tone is to be played.
1033     */
1034    public final void setRingbackRequested(boolean ringback) {
1035        checkImmutable();
1036        if (mRingbackRequested != ringback) {
1037            mRingbackRequested = ringback;
1038            for (Listener l : mListeners) {
1039                l.onRingbackRequested(this, ringback);
1040            }
1041        }
1042    }
1043
1044    /** @hide */
1045    @SystemApi @Deprecated public final void setCallCapabilities(int connectionCapabilities) {
1046        setConnectionCapabilities(connectionCapabilities);
1047    }
1048
1049    /**
1050     * Sets the connection's capabilities as a bit mask of the {@code CAPABILITY_*} constants.
1051     *
1052     * @param connectionCapabilities The new connection capabilities.
1053     */
1054    public final void setConnectionCapabilities(int connectionCapabilities) {
1055        checkImmutable();
1056        if (mConnectionCapabilities != connectionCapabilities) {
1057            mConnectionCapabilities = connectionCapabilities;
1058            for (Listener l : mListeners) {
1059                l.onConnectionCapabilitiesChanged(this, mConnectionCapabilities);
1060            }
1061        }
1062    }
1063
1064    /**
1065     * Tears down the Connection object.
1066     */
1067    public final void destroy() {
1068        for (Listener l : mListeners) {
1069            l.onDestroyed(this);
1070        }
1071    }
1072
1073    /**
1074     * Requests that the framework use VOIP audio mode for this connection.
1075     *
1076     * @param isVoip True if the audio mode is VOIP.
1077     */
1078    public final void setAudioModeIsVoip(boolean isVoip) {
1079        checkImmutable();
1080        mAudioModeIsVoip = isVoip;
1081        for (Listener l : mListeners) {
1082            l.onAudioModeIsVoipChanged(this, isVoip);
1083        }
1084    }
1085
1086    /**
1087     * Sets the label and icon status to display in the in-call UI.
1088     *
1089     * @param statusHints The status label and icon to set.
1090     */
1091    public final void setStatusHints(StatusHints statusHints) {
1092        checkImmutable();
1093        mStatusHints = statusHints;
1094        for (Listener l : mListeners) {
1095            l.onStatusHintsChanged(this, statusHints);
1096        }
1097    }
1098
1099    /**
1100     * Sets the connections with which this connection can be conferenced.
1101     *
1102     * @param conferenceableConnections The set of connections this connection can conference with.
1103     */
1104    public final void setConferenceableConnections(List<Connection> conferenceableConnections) {
1105        checkImmutable();
1106        clearConferenceableList();
1107        for (Connection c : conferenceableConnections) {
1108            // If statement checks for duplicates in input. It makes it N^2 but we're dealing with a
1109            // small amount of items here.
1110            if (!mConferenceables.contains(c)) {
1111                c.addConnectionListener(mConnectionDeathListener);
1112                mConferenceables.add(c);
1113            }
1114        }
1115        fireOnConferenceableConnectionsChanged();
1116    }
1117
1118    /**
1119     * Similar to {@link #setConferenceableConnections(java.util.List)}, sets a list of connections
1120     * or conferences with which this connection can be conferenced.
1121     *
1122     * @param conferenceables The conferenceables.
1123     */
1124    public final void setConferenceables(List<IConferenceable> conferenceables) {
1125        clearConferenceableList();
1126        for (IConferenceable c : conferenceables) {
1127            // If statement checks for duplicates in input. It makes it N^2 but we're dealing with a
1128            // small amount of items here.
1129            if (!mConferenceables.contains(c)) {
1130                if (c instanceof Connection) {
1131                    Connection connection = (Connection) c;
1132                    connection.addConnectionListener(mConnectionDeathListener);
1133                } else if (c instanceof Conference) {
1134                    Conference conference = (Conference) c;
1135                    conference.addListener(mConferenceDeathListener);
1136                }
1137                mConferenceables.add(c);
1138            }
1139        }
1140        fireOnConferenceableConnectionsChanged();
1141    }
1142
1143    /**
1144     * Returns the connections or conferences with which this connection can be conferenced.
1145     */
1146    public final List<IConferenceable> getConferenceables() {
1147        return mUnmodifiableConferenceables;
1148    }
1149
1150    /*
1151     * @hide
1152     */
1153    public final void setConnectionService(ConnectionService connectionService) {
1154        checkImmutable();
1155        if (mConnectionService != null) {
1156            Log.e(this, new Exception(), "Trying to set ConnectionService on a connection " +
1157                    "which is already associated with another ConnectionService.");
1158        } else {
1159            mConnectionService = connectionService;
1160        }
1161    }
1162
1163    /**
1164     * @hide
1165     */
1166    public final void unsetConnectionService(ConnectionService connectionService) {
1167        if (mConnectionService != connectionService) {
1168            Log.e(this, new Exception(), "Trying to remove ConnectionService from a Connection " +
1169                    "that does not belong to the ConnectionService.");
1170        } else {
1171            mConnectionService = null;
1172        }
1173    }
1174
1175    /**
1176     * @hide
1177     */
1178    public final ConnectionService getConnectionService() {
1179        return mConnectionService;
1180    }
1181
1182    /**
1183     * Sets the conference that this connection is a part of. This will fail if the connection is
1184     * already part of a conference. {@link #resetConference} to un-set the conference first.
1185     *
1186     * @param conference The conference.
1187     * @return {@code true} if the conference was successfully set.
1188     * @hide
1189     */
1190    public final boolean setConference(Conference conference) {
1191        checkImmutable();
1192        // We check to see if it is already part of another conference.
1193        if (mConference == null) {
1194            mConference = conference;
1195            if (mConnectionService != null && mConnectionService.containsConference(conference)) {
1196                fireConferenceChanged();
1197            }
1198            return true;
1199        }
1200        return false;
1201    }
1202
1203    /**
1204     * Resets the conference that this connection is a part of.
1205     * @hide
1206     */
1207    public final void resetConference() {
1208        if (mConference != null) {
1209            Log.d(this, "Conference reset");
1210            mConference = null;
1211            fireConferenceChanged();
1212        }
1213    }
1214
1215    /**
1216     * Notifies this Connection that the {@link #getAudioState()} property has a new value.
1217     *
1218     * @param state The new connection audio state.
1219     */
1220    public void onAudioStateChanged(AudioState state) {}
1221
1222    /**
1223     * Notifies this Connection of an internal state change. This method is called after the
1224     * state is changed.
1225     *
1226     * @param state The new state, one of the {@code STATE_*} constants.
1227     */
1228    public void onStateChanged(int state) {}
1229
1230    /**
1231     * Notifies this Connection of a request to play a DTMF tone.
1232     *
1233     * @param c A DTMF character.
1234     */
1235    public void onPlayDtmfTone(char c) {}
1236
1237    /**
1238     * Notifies this Connection of a request to stop any currently playing DTMF tones.
1239     */
1240    public void onStopDtmfTone() {}
1241
1242    /**
1243     * Notifies this Connection of a request to disconnect.
1244     */
1245    public void onDisconnect() {}
1246
1247    /**
1248     * Notifies this Connection of a request to disconnect a participant of the conference managed
1249     * by the connection.
1250     *
1251     * @param endpoint the {@link Uri} of the participant to disconnect.
1252     * @hide
1253     */
1254    public void onDisconnectConferenceParticipant(Uri endpoint) {}
1255
1256    /**
1257     * Notifies this Connection of a request to separate from its parent conference.
1258     */
1259    public void onSeparate() {}
1260
1261    /**
1262     * Notifies this Connection of a request to abort.
1263     */
1264    public void onAbort() {}
1265
1266    /**
1267     * Notifies this Connection of a request to hold.
1268     */
1269    public void onHold() {}
1270
1271    /**
1272     * Notifies this Connection of a request to exit a hold state.
1273     */
1274    public void onUnhold() {}
1275
1276    /**
1277     * Notifies this Connection, which is in {@link #STATE_RINGING}, of
1278     * a request to accept.
1279     *
1280     * @param videoState The video state in which to answer the connection.
1281     * @hide
1282     */
1283    public void onAnswer(int videoState) {}
1284
1285    /**
1286     * Notifies this Connection, which is in {@link #STATE_RINGING}, of
1287     * a request to accept.
1288     */
1289    public void onAnswer() {
1290        onAnswer(VideoProfile.VideoState.AUDIO_ONLY);
1291    }
1292
1293    /**
1294     * Notifies this Connection, which is in {@link #STATE_RINGING}, of
1295     * a request to reject.
1296     */
1297    public void onReject() {}
1298
1299    /**
1300     * Notifies this Connection whether the user wishes to proceed with the post-dial DTMF codes.
1301     */
1302    public void onPostDialContinue(boolean proceed) {}
1303
1304    static String toLogSafePhoneNumber(String number) {
1305        // For unknown number, log empty string.
1306        if (number == null) {
1307            return "";
1308        }
1309
1310        if (PII_DEBUG) {
1311            // When PII_DEBUG is true we emit PII.
1312            return number;
1313        }
1314
1315        // Do exactly same thing as Uri#toSafeString() does, which will enable us to compare
1316        // sanitized phone numbers.
1317        StringBuilder builder = new StringBuilder();
1318        for (int i = 0; i < number.length(); i++) {
1319            char c = number.charAt(i);
1320            if (c == '-' || c == '@' || c == '.') {
1321                builder.append(c);
1322            } else {
1323                builder.append('x');
1324            }
1325        }
1326        return builder.toString();
1327    }
1328
1329    private void setState(int state) {
1330        checkImmutable();
1331        if (mState == STATE_DISCONNECTED && mState != state) {
1332            Log.d(this, "Connection already DISCONNECTED; cannot transition out of this state.");
1333            return;
1334        }
1335        if (mState != state) {
1336            Log.d(this, "setState: %s", stateToString(state));
1337            mState = state;
1338            onStateChanged(state);
1339            for (Listener l : mListeners) {
1340                l.onStateChanged(this, state);
1341            }
1342        }
1343    }
1344
1345    private static class FailureSignalingConnection extends Connection {
1346        private boolean mImmutable = false;
1347        public FailureSignalingConnection(DisconnectCause disconnectCause) {
1348            setDisconnected(disconnectCause);
1349            mImmutable = true;
1350        }
1351
1352        public void checkImmutable() {
1353            if (mImmutable) {
1354                throw new UnsupportedOperationException("Connection is immutable");
1355            }
1356        }
1357    }
1358
1359    /**
1360     * Return a {@code Connection} which represents a failed connection attempt. The returned
1361     * {@code Connection} will have a {@link android.telecom.DisconnectCause} and as specified,
1362     * and a {@link #getState()} of {@link #STATE_DISCONNECTED}.
1363     * <p>
1364     * The returned {@code Connection} can be assumed to {@link #destroy()} itself when appropriate,
1365     * so users of this method need not maintain a reference to its return value to destroy it.
1366     *
1367     * @param disconnectCause The disconnect cause, ({@see android.telecomm.DisconnectCause}).
1368     * @return A {@code Connection} which indicates failure.
1369     */
1370    public static Connection createFailedConnection(DisconnectCause disconnectCause) {
1371        return new FailureSignalingConnection(disconnectCause);
1372    }
1373
1374    /**
1375     * Override to throw an {@link UnsupportedOperationException} if this {@code Connection} is
1376     * not intended to be mutated, e.g., if it is a marker for failure. Only for framework use;
1377     * this should never be un-@hide-den.
1378     *
1379     * @hide
1380     */
1381    public void checkImmutable() {}
1382
1383    /**
1384     * Return a {@code Connection} which represents a canceled connection attempt. The returned
1385     * {@code Connection} will have state {@link #STATE_DISCONNECTED}, and cannot be moved out of
1386     * that state. This connection should not be used for anything, and no other
1387     * {@code Connection}s should be attempted.
1388     * <p>
1389     * so users of this method need not maintain a reference to its return value to destroy it.
1390     *
1391     * @return A {@code Connection} which indicates that the underlying connection should
1392     * be canceled.
1393     */
1394    public static Connection createCanceledConnection() {
1395        return new FailureSignalingConnection(new DisconnectCause(DisconnectCause.CANCELED));
1396    }
1397
1398    private final void fireOnConferenceableConnectionsChanged() {
1399        for (Listener l : mListeners) {
1400            l.onConferenceablesChanged(this, getConferenceables());
1401        }
1402    }
1403
1404    private final void fireConferenceChanged() {
1405        for (Listener l : mListeners) {
1406            l.onConferenceChanged(this, mConference);
1407        }
1408    }
1409
1410    private final void clearConferenceableList() {
1411        for (IConferenceable c : mConferenceables) {
1412            if (c instanceof Connection) {
1413                Connection connection = (Connection) c;
1414                connection.removeConnectionListener(mConnectionDeathListener);
1415            } else if (c instanceof Conference) {
1416                Conference conference = (Conference) c;
1417                conference.removeListener(mConferenceDeathListener);
1418            }
1419        }
1420        mConferenceables.clear();
1421    }
1422
1423    /**
1424     * Notifies listeners of a change to conference participant(s).
1425     *
1426     * @param conferenceParticipants The participants.
1427     * @hide
1428     */
1429    protected final void updateConferenceParticipants(
1430            List<ConferenceParticipant> conferenceParticipants) {
1431        for (Listener l : mListeners) {
1432            l.onConferenceParticipantsChanged(this, conferenceParticipants);
1433        }
1434    }
1435
1436    /**
1437     * Notifies listeners that a conference call has been started.
1438     */
1439    protected void notifyConferenceStarted() {
1440        for (Listener l : mListeners) {
1441            l.onConferenceStarted();
1442        }
1443    }
1444}
1445