aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/protocol/sip/CallSipImpl.java
blob: 62711c72200e36c695af4a8d0f0dc7bac138d1fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Copyright @ 2015 Atlassian Pty Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.java.sip.communicator.impl.protocol.sip;

import java.text.*;
import java.util.*;

import javax.sdp.*;
import javax.sip.*;
import javax.sip.address.*;
import javax.sip.header.*;
import javax.sip.message.*;

import gov.nist.javax.sip.header.*;
import gov.nist.javax.sip.stack.*;

import net.java.sip.communicator.impl.protocol.sip.sdp.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.service.protocol.media.*;
import net.java.sip.communicator.util.*;

import org.jitsi.service.configuration.*;
import org.jitsi.service.neomedia.*;
import org.jitsi.service.neomedia.MediaType;

/**
 * A SIP implementation of the abstract <tt>Call</tt> class encapsulating SIP
 * dialogs.
 *
 * @author Emil Ivov
 * @author Hristo Terezov
 */
public class CallSipImpl
    extends MediaAwareCall<CallPeerSipImpl,
                           OperationSetBasicTelephonySipImpl,
                           ProtocolProviderServiceSipImpl>
    implements CallPeerListener
{
    /**
     * Our class logger.
     */
    private static final Logger logger = Logger.getLogger(CallSipImpl.class);

    /**
     * Name of extra INVITE header which specifies name of MUC room that is
     * hosting the Jitsi Meet conference.
     */
    public String JITSI_MEET_ROOM_HEADER = "Jitsi-Conference-Room";

    /**
     * Property name of extra INVITE header which specifies name of MUC room
     * that is hosting the Jitsi Meet conference.
     */
    private static final String JITSI_MEET_ROOM_HEADER_PROPERTY
        = "JITSI_MEET_ROOM_HEADER_NAME";

    /**
     * Property name of extra INVITE header which specifies password required
     * to enter MUC room that is hosting the Jitsi Meet conference.
     */
    public String JITSI_MEET_ROOM_PASS_HEADER = "Jitsi-Conference-Room-Pass";

    /**
     * Name of extra INVITE header which specifies password required to enter
     * MUC room that is hosting the Jitsi Meet conference.
     */
    private static final String JITSI_MEET_ROOM_PASS_HEADER_PROPERTY
        = "JITSI_MEET_ROOM_PASS_HEADER_NAME";

    /**
     * Custom header included in initial desktop sharing call creation.
     * Not included when we are upgrading an ongoing audio/video call.
     */
    public static final String DS_SHARING_HEADER = "X-Desktop-Share";

    /**
     * Custom header name prefix that can be added to the call instance.
     * Several headers can be specified in the form of:
     * EXTRA_HEADER_NAME.1=...
     * EXTRA_HEADER_NAME.2=...
     * Index starting from 1.
     */
    public static final String EXTRA_HEADER_NAME = "EXTRA_HEADER_NAME";

    /**
     * Custom header value prefix that can be added to the call instance.
     * Several headers can be specified in the form of:
     * EXTRA_HEADER_VALUE.1=...
     * EXTRA_HEADER_VALUE.2=...
     * Index starting from 1.
     */
    public static final String EXTRA_HEADER_VALUE = "EXTRA_HEADER_VALUE";

    /**
     * Maximum number of retransmissions that will be sent.
     */
    private static final int MAX_RETRANSMISSIONS = 3;

    /**
     * The name of the property under which the user may specify the number of
     * milliseconds for the initial interval for retransmissions of response
     * 180.
     */
    private static final String RETRANSMITS_RINGING_INTERVAL
            = "net.java.sip.communicator.impl.protocol.sip"
            + ".RETRANSMITS_RINGING_INTERVAL";

    /**
     * The default amount of time (in milliseconds) for the initial interval for
     *  retransmissions of response 180.
     */
    private static final int DEFAULT_RETRANSMITS_RINGING_INTERVAL = 500;

    /**
     * When starting call we may have quality preferences we must use
     * for the call.
     */
    private QualityPreset initialQualityPreferences;

    /**
     * A reference to the <tt>SipMessageFactory</tt> instance that we should
     * use when creating requests.
     */
    private final SipMessageFactory messageFactory;


    /**
    * The amount of time (in milliseconds) for the initial interval for
    * retransmissions of response 180.
    */
    private final int retransmitsRingingInterval;

    /**
     * Crates a CallSipImpl instance belonging to <tt>sourceProvider</tt> and
     * initiated by <tt>CallCreator</tt>.
     *
     * @param parentOpSet a reference to the operation set that's creating us
     * and that we would be able to use for even dispatching.
     */
    protected CallSipImpl(OperationSetBasicTelephonySipImpl parentOpSet)
    {
        super(parentOpSet);

        this.messageFactory = getProtocolProvider().getMessageFactory();

        ConfigurationService cfg = SipActivator.getConfigurationService();
        int retransmitsRingingInterval = DEFAULT_RETRANSMITS_RINGING_INTERVAL;

        if (cfg != null)
        {
            retransmitsRingingInterval
                = cfg.getInt(
                        RETRANSMITS_RINGING_INTERVAL,
                        retransmitsRingingInterval);
        }
        this.retransmitsRingingInterval = retransmitsRingingInterval;

        AccountID account = parentOpSet.getProtocolProvider().getAccountID();
        // Specify custom header names
        JITSI_MEET_ROOM_HEADER = account.getAccountPropertyString(
            JITSI_MEET_ROOM_HEADER_PROPERTY, JITSI_MEET_ROOM_HEADER);
        JITSI_MEET_ROOM_PASS_HEADER = account.getAccountPropertyString(
            JITSI_MEET_ROOM_PASS_HEADER_PROPERTY, JITSI_MEET_ROOM_PASS_HEADER);

        //let's add ourselves to the calls repo. we are doing it ourselves just
        //to make sure that no one ever forgets.
        parentOpSet.getActiveCallsRepository().addCall(this);
    }

    /**
     * {@inheritDoc}
     *
     * Re-INVITEs the <tt>CallPeer</tt>s associated with this
     * <tt>CallSipImpl</tt> in order to include/exclude the &quot;isfocus&quot;
     * parameter in the Contact header.
     */
    @Override
    protected void conferenceFocusChanged(boolean oldValue, boolean newValue)
    {
        try
        {
            reInvite();
        }
        catch (OperationFailedException ofe)
        {
            logger.info("Failed to re-INVITE this Call: " + this, ofe);
        }
        finally
        {
            super.conferenceFocusChanged(oldValue, newValue);
        }
    }

    /**
     * Returns <tt>true</tt> if <tt>dialog</tt> matches the jain sip dialog
     * established with one of the peers in this call.
     *
     * @param dialog the dialog whose corresponding peer we're looking for.
     *
     * @return true if this call contains a call peer whose jain sip
     * dialog is the same as the specified and false otherwise.
     */
    public boolean contains(Dialog dialog)
    {
        return findCallPeer(dialog) != null;
    }

    /**
     * Creates a new call peer associated with <tt>containingTransaction</tt>
     *
     * @param containingTransaction the transaction that created the call peer.
     * @param sourceProvider the provider that the containingTransaction belongs
     * to.
     * @return a new instance of a <tt>CallPeerSipImpl</tt> corresponding
     * to the <tt>containingTransaction</tt>.
     */
    private CallPeerSipImpl createCallPeerFor(
            Transaction containingTransaction,
            SipProvider sourceProvider)
    {
        CallPeerSipImpl callPeer
            = new CallPeerSipImpl(
                    containingTransaction.getDialog().getRemoteParty(),
                    this,
                    containingTransaction,
                    sourceProvider)
        {
            /**
             * A place where we can handle any headers we need for requests
             * and responses.
             * @param message the SIP <tt>Message</tt> in which a header change
             * is to be reflected
             * @throws ParseException if modifying the specified SIP
             * <tt>Message</tt> to reflect the header change fails
             */
            protected void processExtraHeaders(javax.sip.message.Message message)
                throws ParseException
            {
                super.processExtraHeaders(message);

                CallSipImpl.this.processExtraHeaders(message);
            }
        };

        addCallPeer(callPeer);

        boolean incomingCall
            = (containingTransaction instanceof ServerTransaction);

        callPeer.setState(
                incomingCall
                    ? CallPeerState.INCOMING_CALL
                    : CallPeerState.INITIATING_CALL);

        // if this was the first peer we added in this call then the call is
        // new and we also need to notify everyone of its creation.
        if(getCallPeerCount() == 1)
        {
            Map<MediaType, MediaDirection> mediaDirections
                = new HashMap<MediaType, MediaDirection>();

            mediaDirections.put(MediaType.AUDIO, MediaDirection.INACTIVE);
            mediaDirections.put(MediaType.VIDEO, MediaDirection.INACTIVE);

            boolean hasZrtp = false;
            boolean hasSdes = false;

            //this check is not mandatory catch all to skip if a problem exists
            try
            {
                // lets check the supported media types.
                // for this call
                Request inviteReq = containingTransaction.getRequest();

                if(inviteReq != null && inviteReq.getRawContent() != null)
                {
                    String sdpStr = SdpUtils.getContentAsString(inviteReq);
                    SessionDescription sesDescr
                        = SdpUtils.parseSdpString(sdpStr);
                    List<MediaDescription> remoteDescriptions
                        = SdpUtils.extractMediaDescriptions(sesDescr);

                    for (MediaDescription mediaDescription : remoteDescriptions)
                    {
                        MediaType mediaType
                            = SdpUtils.getMediaType(mediaDescription);

                        mediaDirections.put(
                                mediaType,
                                SdpUtils.getDirection(mediaDescription));

                        // hasZrtp?
                        if (!hasZrtp)
                        {
                            hasZrtp
                                = (mediaDescription.getAttribute(
                                        SdpUtils.ZRTP_HASH_ATTR)
                                    != null);
                        }
                        // hasSdes?
                        if (!hasSdes)
                        {
                            @SuppressWarnings("unchecked")
                            Vector<Attribute> attrs
                                = mediaDescription.getAttributes(true);

                            for (Attribute attr : attrs)
                            {
                                try
                                {
                                    if ("crypto".equals(attr.getName()))
                                    {
                                        hasSdes = true;
                                        break;
                                    }
                                }
                                catch (SdpParseException spe)
                                {
                                    logger.error(
                                            "Failed to parse SDP attribute",
                                            spe);
                                }
                            }
                        }
                    }
                }
            }
            catch(Throwable t)
            {
                logger.warn("Error getting media types", t);
            }

            fireCallEvent(
                incomingCall
                    ? CallEvent.CALL_RECEIVED
                    : CallEvent.CALL_INITIATED,
                this,
                mediaDirections);

            if(hasZrtp)
            {
                callPeer.getMediaHandler().addAdvertisedEncryptionMethod(
                        SrtpControlType.ZRTP);
            }
            if(hasSdes)
            {
                callPeer.getMediaHandler().addAdvertisedEncryptionMethod(
                        SrtpControlType.SDES);
            }
        }

        return callPeer;
    }

    /**
     * Creates and dispatches a <tt>CallEvent</tt> notifying registered
     * listeners that an event with id <tt>eventID</tt> has occurred on
     * <tt>sourceCall</tt>.
     *
     * @param eventID the ID of the event to dispatch
     * @param sourceCall the call on which the event has occurred.
     * @param mediaDirections direction map for media types
     */
    protected void fireCallEvent(
        int eventID,
        Call sourceCall,
        Map<MediaType, MediaDirection> mediaDirections)
    {
        CallEvent callEvent
            = new CallEvent(sourceCall, eventID, mediaDirections);

        // just checks for existence of the custom desktop share header
        // and indicate it in the call event
        if(sourceCall.getCallPeerCount() == 1)
        {
            CallSipImpl callSip = (CallSipImpl)sourceCall;

            CallPeerSipImpl callPeer = callSip.getCallPeers().next();

            Request request
                = callPeer.getLatestInviteTransaction().getRequest();

            Header dsHeader = request.getHeader(DS_SHARING_HEADER);

            if(dsHeader != null)
            {
                callEvent.setDesktopStreaming(true);
            }
        }

        getParentOperationSet().fireCallEvent(callEvent);
    }

    /**
     * Returns the call peer whose associated jain sip dialog matches
     * <tt>dialog</tt>.
     *
     * @param dialog the jain sip dialog whose corresponding peer we're looking
     * for.
     * @return the call peer whose jain sip dialog is the same as the specified
     * or null if no such call peer was found.
     */
    public CallPeerSipImpl findCallPeer(Dialog dialog)
    {
        Iterator<CallPeerSipImpl> callPeers = this.getCallPeers();

        if (logger.isTraceEnabled())
        {
            logger.trace("Looking for peer with dialog: " + dialog
                + "among " + getCallPeerCount() + " calls");
        }
        for (CallPeerSipImpl callPeer : getCallPeerList())
        {
            if (callPeer.getDialog() == dialog)
            {
                if (logger.isTraceEnabled())
                    logger.trace("Returning cp=" + callPeer);
                return callPeer;
            }
            else
            {
                if (logger.isTraceEnabled())
                    logger.trace("Ignoring cp=" + callPeer + " because cp.dialog="
                            + callPeer.getDialog() + " while dialog=" + dialog);
            }
        }
        return null;
    }

    /**
     * Returns a reference to the <tt>ProtocolProviderServiceSipImpl</tt>
     * instance that created this call.
     *
     * @return a reference to the <tt>ProtocolProviderServiceSipImpl</tt>
     * instance that created this call.
     */
    @Override
    public ProtocolProviderServiceSipImpl getProtocolProvider()
    {
        return super.getProtocolProvider();
    }

    /**
     * Creates a <tt>CallPeerSipImpl</tt> from <tt>calleeAddress</tt> and sends
     * them an invite request. The invite request will be initialized according
     * to any relevant parameters in the <tt>cause</tt> message (if different
     * from <tt>null</tt>) that is the reason for creating this call.
     *
     * @param calleeAddress the party that we would like to invite to this call.
     * @param cause the message (e.g. a Refer request), that is the reason for
     * this invite or <tt>null</tt> if this is a user-initiated invitation
     *
     * @return the newly created <tt>CallPeer</tt> corresponding to
     * <tt>calleeAddress</tt>. All following state change events will be
     * delivered through this call peer.
     *
     * @throws OperationFailedException  with the corresponding code if we fail
     *  to create the call.
     */
    public CallPeerSipImpl invite(Address                   calleeAddress,
                                  javax.sip.message.Message cause)
        throws OperationFailedException
    {
        // create the invite request
        Request invite
            = messageFactory.createInviteRequest(calleeAddress, cause);

        // Transport preference
        String forceTransport = null;
        javax.sip.address.URI calleeURI = calleeAddress.getURI();
        if("sips".equals(calleeURI.getScheme().toLowerCase()))
        {
            // MUST use TLS
            forceTransport = "TLS";
            logger.trace("detected SIPS URI, must use TLS");
        }
        else if(calleeURI.isSipURI() && calleeURI instanceof SipURI)
        {
            SipURI _calleeURI = (SipURI)calleeURI;
            // check for a transport parameter
            forceTransport = _calleeURI.getTransportParam();
            if(forceTransport != null)
            {
                logger.trace("got transport parameter: " + forceTransport);
            }
        }

        // Transaction
        ClientTransaction inviteTransaction = null;
        SipProvider jainSipProvider;
        if(forceTransport != null)
        {
            logger.trace("trying to use transport: " + forceTransport);
            jainSipProvider = getProtocolProvider()
                .getJainSipProvider(forceTransport);
        }
        else
        {
            logger.trace("trying default transport");
            jainSipProvider = getProtocolProvider()
                .getDefaultJainSipProvider();
        }

        try
        {
            inviteTransaction = jainSipProvider.getNewClientTransaction(invite);
        }
        catch (TransactionUnavailableException ex)
        {
            ProtocolProviderServiceSipImpl.throwOperationFailedException(
                "Failed to create inviteTransaction.\n"
                    + "This is most probably a network connection error.",
                OperationFailedException.INTERNAL_ERROR, ex, logger);
        }

        // create the call peer
        CallPeerSipImpl callPeer
            = createCallPeerFor(inviteTransaction, jainSipProvider);
        CallPeerMediaHandlerSipImpl mediaHandler = callPeer.getMediaHandler();

        /* enable video if it is a videocall */
        mediaHandler.setLocalVideoTransmissionEnabled(localVideoAllowed);

        if(initialQualityPreferences != null)
        {
            // we are in situation where we init the call and we cannot
            // determine whether the other party supports changing quality
            // so we force it
            mediaHandler.setSupportQualityControls(true);
            mediaHandler.getQualityControl().setRemoteSendMaxPreset(
                    initialQualityPreferences);
        }

        try
        {
            callPeer.invite();
        }
        catch(OperationFailedException ex)
        {
            // if inviting call peer fail for some reason, change its state
            // if not already filed
            callPeer.setState(CallPeerState.FAILED);
            throw ex;
        }

        return callPeer;
    }

    /**
     * Creates a new call and sends a RINGING response.
     *
     * @param jainSipProvider the provider containing
     * <tt>sourceTransaction</tt>.
     * @param serverTran the transaction containing the received request.
     *
     * @return CallPeerSipImpl the newly created call peer (the one that sent
     * the INVITE).
     */
    public CallPeerSipImpl processInvite(SipProvider       jainSipProvider,
                                         ServerTransaction serverTran)
    {
        Request invite = serverTran.getRequest();

        final CallPeerSipImpl peer
            = createCallPeerFor(serverTran, jainSipProvider);

        CallInfoHeader infoHeader
            = (CallInfoHeader) invite.getHeader(CallInfoHeader.NAME);

        // Sets an alternative impp address if such is available in the
        // call-info header.
        String alternativeIMPPAddress = null;
        if (infoHeader != null
            && infoHeader.getParameter("purpose") != null
            && "impp".equals(infoHeader.getParameter("purpose")))
        {
            alternativeIMPPAddress = infoHeader.getInfo().toString();
        }

        if (alternativeIMPPAddress != null)
            peer.setAlternativeIMPPAddress(alternativeIMPPAddress);

        // Parses Jitsi Meet room name header
        SIPHeader joinRoomHeader
            = (SIPHeader) invite.getHeader(JITSI_MEET_ROOM_HEADER);
        // Optional password header
        SIPHeader passwordHeader
            = (SIPHeader) invite.getHeader(JITSI_MEET_ROOM_PASS_HEADER);

        if (joinRoomHeader != null)
        {
            OperationSetJitsiMeetToolsSipImpl jitsiMeetTools
                = (OperationSetJitsiMeetToolsSipImpl) getProtocolProvider()
                        .getOperationSet(OperationSetJitsiMeetTools.class);

            jitsiMeetTools.notifyJoinJitsiMeetRoom(
                this, joinRoomHeader.getValue(),
                passwordHeader != null ? passwordHeader.getValue() : null);
        }

        //send a ringing response
        Response response = null;
        try
        {
            if (logger.isTraceEnabled())
                logger.trace("will send ringing response: ");
            if( CallPeerState.INCOMING_CALL.equals(peer.getState()) )
            {
                response = messageFactory.createResponse(Response.RINGING, invite);

                serverTran.sendResponse(response);

                if(serverTran instanceof SIPTransaction
                    && !((SIPTransaction)serverTran).isReliable())
                {
                    final Timer timer = new Timer();
                    int interval = retransmitsRingingInterval;
                    int delay = 0;
                    for(int i = 0; i < MAX_RETRANSMISSIONS; i++)
                    {
                        delay += interval;
                        timer.schedule(new RingingResponseTask(response,
                            serverTran, peer, timer), delay);
                        interval *= 2;
                    }
                }
                if (logger.isDebugEnabled())
                    logger.debug("sent a ringing response: " + response);
            }
        }
        catch (Exception ex)
        {
            logger.error("Error while trying to send a request", ex);
            peer.setState(CallPeerState.FAILED,
                "Internal Error: " + ex.getMessage());
            return peer;
        }

        return peer;
    }


    /**
     * Processes an incoming INVITE that is meant to replace an existing
     * <tt>CallPeerSipImpl</tt> that is participating in this call. Typically
     * this would happen as a result of an attended transfer.
     *
     * @param jainSipProvider the JAIN-SIP <tt>SipProvider</tt> that received
     * the request.
     * @param serverTransaction the transaction containing the INVITE request.
     * @param callPeerToReplace a reference to the <tt>CallPeer</tt> that this
     * INVITE is trying to replace.
     */
    public void processReplacingInvite(SipProvider       jainSipProvider,
                                       ServerTransaction serverTransaction,
                                       CallPeerSipImpl   callPeerToReplace)
    {
        CallPeerSipImpl newCallPeer
                    = createCallPeerFor(serverTransaction, jainSipProvider);
        try
        {
            newCallPeer.answer();
        }
        catch (OperationFailedException ex)
        {
            logger.error(
                    "Failed to auto-answer the referred call peer "
                        + newCallPeer,
                    ex);
            /*
             * RFC 3891 says an appropriate error response MUST be returned
             * and callPeerToReplace must be left unchanged.
             */
            //TODO should we send a response here?
            return;
        }

        //we just accepted the new peer and if we got here then it went well
        //now let's hangup the other call.
        try
        {
            callPeerToReplace.hangup();
        }
        catch (OperationFailedException ex)
        {
            logger.error("Failed to hangup the referer "
                            + callPeerToReplace, ex);
            callPeerToReplace.setState(
                            CallPeerState.FAILED, "Internal Error: " + ex);
        }
    }

    /**
     * Sends a re-INVITE request to all <tt>CallPeer</tt>s to reflect possible
     * changes in the media setup (video start/stop, ...).
     *
     * @throws OperationFailedException if a problem occurred during the SDP
     * generation or there was a network problem
     */
    public void reInvite() throws OperationFailedException
    {
        for(CallPeerSipImpl peer : getCallPeerList())
        {
            peer.sendReInvite();
        }
    }

    /**
     * Set a quality preferences we may use when we start the call.
     * @param qualityPreferences the initial quality preferences.
     */
    public void setInitialQualityPreferences(QualityPreset qualityPreferences)
    {
        this.initialQualityPreferences = qualityPreferences;
    }

    /**
     * A place where we can handle any headers we need for requests
     * and responses.
     * @param message the SIP <tt>Message</tt> in which a header change
     * is to be reflected
     * @throws java.text.ParseException if modifying the specified SIP
     * <tt>Message</tt> to reflect the header change fails
     */
    protected void processExtraHeaders(javax.sip.message.Message message)
        throws ParseException
    {
        // If there are custom headers added to the call instance, add those
        // headers
        int extraHeaderIx = 1;

        Object name = getData(EXTRA_HEADER_NAME + "." + extraHeaderIx);
        while(name != null)
        {
            Object value = getData(EXTRA_HEADER_VALUE + "." + extraHeaderIx);

            Header header = getProtocolProvider().getHeaderFactory()
                .createHeader((String) name, (String) value);
            message.setHeader(header);

            extraHeaderIx++;
            name = getData(EXTRA_HEADER_NAME + "." + extraHeaderIx);
        }
    }

    /**
     * Task that will retransmit ringing response
     */
    private class RingingResponseTask
        extends TimerTask
    {
        /**
         * The response that will be sent
         */
        private final Response response;

        /**
         * The transaction containing the received request.
         */
        private final ServerTransaction serverTran;

        /**
         * The peer corresponding to the transaction.
         */
        private final CallPeerSipImpl peer;

        /**
         * The timer that starts the task.
         */
        private final Timer timer;

        /**
         * Create ringing response task.
         * @param response the response.
         * @param serverTran the transaction.
         * @param peer the peer.
         * @param timer the timer.
         */
        RingingResponseTask(Response response, ServerTransaction serverTran,
            CallPeerSipImpl peer, Timer timer)
        {
            this.response = response;
            this.serverTran = serverTran;
            this.peer = peer;
            this.timer = timer;
        }

        /**
         * Sends the ringing response.
         */
        @Override
        public void run()
        {
            try
            {
                if( !CallPeerState.INCOMING_CALL.equals(
                        peer.getState()) )
                {
                    timer.cancel();
                }
                else
                {
                    serverTran.sendResponse(response);
                }
            }
            catch (Exception ex)
            {
                timer.cancel();
            }
        }
    }
}