aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/service/protocol/media/MediaAwareCallPeer.java
blob: 4e150384eab495dc11d0c11391360aa51e8e534f (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
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
/*
 * 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.service.protocol.media;

import java.beans.*;
import java.util.*;

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

import org.jitsi.service.neomedia.*;
import org.jitsi.service.neomedia.event.*;

/**
 * A utility class implementing media control code shared between current
 * telephony implementations. This class is only meant for use by protocol
 * implementations and should/could not be accessed by bundles that are simply
 * using the telephony functionalities.
 *
 * @param <T> the peer extension class like for example <tt>CallSipImpl</tt>
 * or <tt>CallJabberImpl</tt>
 * @param <U> the media handler extension class like for example
 * <tt>CallPeerMediaHandlerSipImpl</tt> or
 * <tt>CallPeerMediaHandlerJabberImpl</tt>
 * @param <V> the provider extension class like for example
 * <tt>ProtocolProviderServiceSipImpl</tt> or
 * <tt>ProtocolProviderServiceJabberImpl</tt>
 *
 * @author Emil Ivov
 * @author Lyubomir Marinov
 * @author Boris Grozev
 */
public abstract class MediaAwareCallPeer
                          <T extends MediaAwareCall<?, ?, V>,
                           U extends CallPeerMediaHandler<?>,
                           V extends ProtocolProviderService>
    extends AbstractCallPeer<T, V>
    implements SrtpListener,
               CallPeerConferenceListener,
               CsrcAudioLevelListener,
               SimpleAudioLevelListener
{
    /**
     * The <tt>Logger</tt> used by the <tt>MediaAwareCallPeer</tt> class and its
     * instances for logging output.
     */
    private static final Logger logger
        = Logger.getLogger(MediaAwareCallPeer.class);

    /**
     * The call this peer belongs to.
     */
    private T call;

    /**
     * The listeners registered for level changes in the audio of participants
     * that this peer might be mixing and that we are not directly communicating
     * with.
     */
    private final List<ConferenceMembersSoundLevelListener>
        conferenceMembersSoundLevelListeners
            = new ArrayList<ConferenceMembersSoundLevelListener>();

    /**
     * A byte array containing the image/photo representing the call peer.
     */
    private byte[] image;

    /**
     * The media handler class handles all media management for a single
     * <tt>CallPeer</tt>. This includes initializing and configuring streams,
     * generating SDP, handling ICE, etc. One instance of <tt>CallPeer</tt>always
     * corresponds to exactly one instance of <tt>CallPeerMediaHandler</tt> and
     * both classes are only separated for reasons of readability.
     */
    private U mediaHandler;

    /**
     * The <tt>PropertyChangeListener</tt> which listens to
     * {@link CallPeerMediaHandler} for changes in the values of its properties.
     */
    private PropertyChangeListener mediaHandlerPropertyChangeListener;

    /**
     * A string uniquely identifying the peer.
     */
    private String peerID;

    /**
     * The protocol provider that this peer belongs to.
     */
    private final V protocolProvider;

    /**
     * The list of <tt>SoundLevelListener</tt>s interested in level changes in
     * the audio we are getting from the remote peer.
     * <p>
     * It is implemented as a copy-on-write storage because the number of
     * additions and removals of <tt>SoundLevelListener</tt>s is expected to be
     * far smaller than the number of audio level changes. The access to it is
     * to be synchronized using {@link #streamSoundLevelListenersSyncRoot}.
     * </p>
     */
    private List<SoundLevelListener> streamSoundLevelListeners;

    /**
     * The <tt>Object</tt> to synchronize the access to
     * {@link #streamSoundLevelListeners}.
     */
    private final Object streamSoundLevelListenersSyncRoot = new Object();

    /**
     * The <tt>List</tt> of <tt>PropertyChangeListener</tt>s listening to this
     * <tt>CallPeer</tt> for changes in the values of its properties related to
     * video.
     */
    private final List<PropertyChangeListener> videoPropertyChangeListeners
        = new LinkedList<PropertyChangeListener>();

    /**
     * Represents the last Conference Information (RFC4575) document sent to
     * this <tt>CallPeer</tt>. This is always a document with state "full", even
     * if the last document actually sent was a "partial"
     */
    private ConferenceInfoDocument lastConferenceInfoSent = null;

    /**
     * The time (as obtained by <tt>System.currentTimeMillis()</tt>) at which
     * a Conference Information (RFC4575) document was last sent to this
     * <tt>CallPeer</tt>.
     */
    private long lastConferenceInfoSentTimestamp = -1;

    /**
     * The last Conference Information (RFC4575) document sent to us by this
     * <tt>CallPeer</tt>. This is always a document with state "full", which is
     * only gets updated by "partial" or "deleted" documents.
     */
    private ConferenceInfoDocument lastConferenceInfoReceived = null;

    /**
     * Whether a conference-info document has been scheduled to be sent to this
     * <tt>CallPeer</tt>
     */
    private boolean confInfoScheduled = false;

    /**
     * Synchronization object for confInfoScheduled
     */
    private final Object confInfoScheduledSyncRoot = new Object();

    /**
     * Creates a new call peer with address <tt>peerAddress</tt>.
     *
     * @param owningCall the call that contains this call peer.
     */
    public MediaAwareCallPeer(T owningCall)
    {
        this.call = owningCall;
        this.protocolProvider = owningCall.getProtocolProvider();

        // create the uid
        this.peerID
            = String.valueOf(System.currentTimeMillis())
                + String.valueOf(hashCode());

        // we listen for events when the call will become focus or not
        // of a conference so we will add or remove our sound level listeners
        super.addCallPeerConferenceListener(this);
    }

    /**
     * Adds a specific <tt>ConferenceMembersSoundLevelListener</tt> to the list
     * of listeners interested in and notified about changes in conference
     * members sound level.
     *
     * @param listener the <tt>ConferenceMembersSoundLevelListener</tt> to add
     * @throws NullPointerException if <tt>listener</tt> is <tt>null</tt>
     */
    public void addConferenceMembersSoundLevelListener(
            ConferenceMembersSoundLevelListener listener)
    {
        /*
         * XXX The uses of the method at the time of this writing rely on being
         * able to add a null listener so make it a no-op here.
         */
        if (listener == null)
            return;

        synchronized (conferenceMembersSoundLevelListeners)
        {
            if (conferenceMembersSoundLevelListeners.size() == 0)
            {
                // if this is the first listener that's being registered with
                // us, we also need to register ourselves as a CSRC audio level
                // listener with the media handler.
                getMediaHandler().setCsrcAudioLevelListener(this);
            }
            conferenceMembersSoundLevelListeners.add(listener);
        }
    }

    /**
     * Adds a specific <tt>SoundLevelListener</tt> to the list of listeners
     * interested in and notified about changes in the sound level of the audio
     * sent by the remote party. When the first listener is being registered
     * the method also registers its single listener with the media handler so
     * that it would receive level change events and delegate them to the
     * listeners that have registered with us.
     *
     * @param listener the <tt>SoundLevelListener</tt> to add
     */
    public void addStreamSoundLevelListener(SoundLevelListener listener)
    {
        synchronized (streamSoundLevelListenersSyncRoot)
        {
            if ((streamSoundLevelListeners == null)
                    || streamSoundLevelListeners.isEmpty())
            {
                CallPeerMediaHandler<?> mediaHandler = getMediaHandler();

                if (isJitsiVideobridge())
                {
                    /*
                     * When the local user/peer has organized a telephony
                     * conference utilizing the Jitsi Videobridge server-side
                     * technology, the server will calculate the audio levels
                     * and not the client.
                     */
                    mediaHandler.setCsrcAudioLevelListener(this);
                }
                else
                {
                    /*
                     * If this is the first listener that's being registered
                     * with us, we also need to register ourselves as an audio
                     * level listener with the media handler. We do this so that
                     * audio levels would only be calculated if anyone is
                     * interested in receiving them.
                     */
                    mediaHandler.setStreamAudioLevelListener(this);
                }
            }

            /*
             * Implement streamAudioLevelListeners as a copy-on-write storage so
             * that iterators over it can iterate without
             * ConcurrentModificationExceptions.
             */
            streamSoundLevelListeners
                = (streamSoundLevelListeners == null)
                    ? new ArrayList<SoundLevelListener>()
                    : new ArrayList<SoundLevelListener>(
                            streamSoundLevelListeners);
            streamSoundLevelListeners.add(listener);
        }
    }

    /**
     * Adds a specific <tt>PropertyChangeListener</tt> to the list of
     * listeners which get notified when the properties (e.g.
     * LOCAL_VIDEO_STREAMING) associated with this <tt>CallPeer</tt> change
     * their values.
     *
     * @param listener the <tt>PropertyChangeListener</tt> to be notified
     * when the properties associated with the specified <tt>Call</tt> change
     * their values
     */
    public void addVideoPropertyChangeListener(PropertyChangeListener listener)
    {
        if (listener == null)
            throw new NullPointerException("listener");

        synchronized (videoPropertyChangeListeners)
        {
            /*
             * The video is part of the media-related functionality and thus it
             * is the responsibility of mediaHandler. So listen to mediaHandler
             * for video-related property changes and re-fire them as
             * originating from this instance.
             */
            if (!videoPropertyChangeListeners.contains(listener)
                    && videoPropertyChangeListeners.add(listener)
                    && (mediaHandlerPropertyChangeListener == null))
            {
                mediaHandlerPropertyChangeListener
                    = new PropertyChangeListener()
                    {
                        public void propertyChange(PropertyChangeEvent event)
                        {
                            Iterable<PropertyChangeListener> listeners;

                            synchronized (videoPropertyChangeListeners)
                            {
                                listeners
                                    = new LinkedList<PropertyChangeListener>(
                                            videoPropertyChangeListeners);
                            }

                            PropertyChangeEvent thisEvent
                                = new PropertyChangeEvent(
                                        this,
                                        event.getPropertyName(),
                                        event.getOldValue(),
                                        event.getNewValue());

                            for (PropertyChangeListener listener : listeners)
                                listener.propertyChange(thisEvent);
                        }
                    };
                getMediaHandler()
                    .addPropertyChangeListener(
                            mediaHandlerPropertyChangeListener);
            }
        }
    }

    /**
     * Notified by its very majesty the media service about changes in the audio
     * level of the stream coming from this peer, the method generates the
     * corresponding events and delivers them to the listeners that have
     * registered here.
     *
     * @param newLevel the new audio level of the audio stream received from the
     * remote peer
     */
    public void audioLevelChanged(int newLevel)
    {
        /*
         * If we're in a conference in which this CallPeer is the focus and
         * we're the only member in it besides the focus, we will not receive
         * audio levels in the RTP and our media will instead measure the audio
         * levels of the received media. In order to make the UI oblivious of
         * the difference, we have to translate the event to the appropriate
         * type of listener.
         *
         * We may end up in a conference call with 0 members if the server
         * for some reason doesn't support sip conference (our subscribes
         * doesn't go to the focus of the conference) and so we must
         * pass the sound levels measured on the stream so we can see
         * the stream activity of the call.
         */
        int conferenceMemberCount = getConferenceMemberCount();

        if ((conferenceMemberCount > 0) && (conferenceMemberCount < 3))
        {
            long audioRemoteSSRC
                = getMediaHandler().getRemoteSSRC(MediaType.AUDIO);

            if (audioRemoteSSRC != CallPeerMediaHandler.SSRC_UNKNOWN)
            {
                audioLevelsReceived(new long[] { audioRemoteSSRC, newLevel });
                return;
            }
        }

        fireStreamSoundLevelChanged(newLevel);
    }


    /**
     * Implements {@link CsrcAudioLevelListener#audioLevelsReceived(long[])}.
     * Delivers the received audio levels to the
     * {@link ConferenceMembersSoundLevelListener}s registered with this
     * <tt>MediaAwareCallPeer</tt>..
     *
     * @param audioLevels the levels that we need to dispatch to all registered
     * <tt>ConferenceMemberSoundLevelListeners</tt>.
     */
    public void audioLevelsReceived(long[] audioLevels)
    {
        /*
         * When the local user/peer has organized a telephony conference
         * utilizing the Jitsi Videobridge server-side technology, the server
         * will calculate the audio levels and not the client.
         */
        if (isJitsiVideobridge())
        {
            long audioRemoteSSRC
                = getMediaHandler().getRemoteSSRC(MediaType.AUDIO);

            if (audioRemoteSSRC != CallPeerMediaHandler.SSRC_UNKNOWN)
            {
                for (int i = 0; i < audioLevels.length; i += 2)
                {
                    if (audioLevels[i] == audioRemoteSSRC)
                    {
                        fireStreamSoundLevelChanged((int) audioLevels[i + 1]);
                        break;
                    }
                }
            }
        }

        if (getConferenceMemberCount() == 0)
            return;

        Map<ConferenceMember, Integer> levelsMap
            = new HashMap<ConferenceMember, Integer>();

        for (int i = 0; i < audioLevels.length; i += 2)
        {
            ConferenceMember mmbr = findConferenceMember(audioLevels[i]);

            if (mmbr != null)
                levelsMap.put(mmbr, (int) audioLevels[i + 1]);
        }

        synchronized (conferenceMembersSoundLevelListeners)
        {
            int conferenceMemberSoundLevelListenerCount
                = conferenceMembersSoundLevelListeners.size();

            if (conferenceMemberSoundLevelListenerCount > 0)
            {
                ConferenceMembersSoundLevelEvent ev
                    = new ConferenceMembersSoundLevelEvent(this, levelsMap);

                for (int i = 0;
                        i < conferenceMemberSoundLevelListenerCount;
                        i++)
                {
                    conferenceMembersSoundLevelListeners
                        .get(i)
                            .soundLevelChanged(ev);
                }
            }
        }
    }

    /**
     * Does nothing.
     * @param evt the event.
     */
    public void callPeerAdded(CallPeerEvent evt) {}

    /**
     * Does nothing.
     * @param evt the event.
     */
    public void callPeerRemoved(CallPeerEvent evt) {}

    /**
     * Dummy implementation of {@link CallPeerConferenceListener
     * #conferenceFocusChanged(CallPeerConferenceEvent)}.
     *
     * @param evt ignored
     */
    public void conferenceFocusChanged(CallPeerConferenceEvent evt)
    {
    }

    /**
     * Called when this peer becomes a mixer. The method add removes this class
     * as the stream audio level listener for the media coming from this peer
     * because the levels it delivers no longer represent the level of a
     * particular member. The method also adds this class as a member (CSRC)
     * audio level listener.
     *
     * @param conferenceEvent the event containing information (that we don't
     * really use) on the newly add member.
     */
    public void conferenceMemberAdded(CallPeerConferenceEvent conferenceEvent)
    {
        if (getConferenceMemberCount() > 2)
        {
            /*
             * This peer is now a conference focus with more than three
             * participants. It means that this peer is mixing and sending us
             * audio for at least two separate participants. We therefore need
             * to switch from stream to CSRC level listening.
             */
            CallPeerMediaHandler<?> mediaHandler = getMediaHandler();

            mediaHandler.setStreamAudioLevelListener(null);
            mediaHandler.setCsrcAudioLevelListener(this);
        }
    }
    
    /**
     * Dummy implementation of {@link CallPeerConferenceListener
     * #conferenceMemberErrorReceived(CallPeerConferenceEvent)}.
     *
     * @param ev the event
     */
    public void conferenceMemberErrorReceived(CallPeerConferenceEvent ev) {};

    /**
     * Called when this peer stops being a mixer. The method add removes this
     * class as the stream audio level listener for the media coming from this
     * peer because the levels it delivers no longer represent the level of a
     * particular member. The method also adds this class as a member (CSRC)
     * audio level listener.
     *
     * @param conferenceEvent the event containing information (that we don't
     * really use) on the freshly removed member.
     */
    public void conferenceMemberRemoved(CallPeerConferenceEvent conferenceEvent)
    {
        if (getConferenceMemberCount() < 3)
        {
            /*
             * This call peer is no longer mixing audio from multiple sources
             * since there's only us and her in the call. We therefore need to
             * switch from CSRC to stream level listening.
             */
            CallPeerMediaHandler<?> mediaHandler = getMediaHandler();

            mediaHandler.setStreamAudioLevelListener(this);
            mediaHandler.setCsrcAudioLevelListener(null);
        }
    }

    /**
     * Invokes {@link SoundLevelListener#soundLevelChanged(Object, int) on
     * the <tt>SoundLevelListener</tt>s interested in the changes of the audio
     * stream received from the remote peer i.e. in
     * {@link #streamSoundLevelListeners}.
     *
     * @param newLevel the new value of the sound level to notify
     * <tt>streamSoundLevelListeners</tt> about
     */
    private void fireStreamSoundLevelChanged(int newLevel)
    {
        List<SoundLevelListener> streamSoundLevelListeners;

        synchronized (streamSoundLevelListenersSyncRoot)
        {
            /*
             * Since the streamAudioLevelListeners field of this
             * MediaAwareCallPeer is implemented as a copy-on-write storage,
             * just get a reference to it and it should be safe to iterate over it
             * without ConcurrentModificationExceptions.
             */
            streamSoundLevelListeners = this.streamSoundLevelListeners;
        }

        if (streamSoundLevelListeners != null)
        {
            /*
             * Iterate over streamAudioLevelListeners using an index rather than
             * an Iterator in order to try to reduce the number of allocations
             * (as the number of audio level changes is expected to be very
             * large).
             */
            int streamSoundLevelListenerCount
                = streamSoundLevelListeners.size();

            for(int i = 0; i < streamSoundLevelListenerCount; i++)
            {
                streamSoundLevelListeners.get(i).soundLevelChanged(
                        this,
                        newLevel);
            }
        }
    }

    /**
     * Returns a reference to the call that this peer belongs to. Calls
     * are created by underlying telephony protocol implementations.
     *
     * @return a reference to the call containing this peer.
     */
    @Override
    public T getCall()
    {
        return call;
    }

    /**
     * The method returns an image representation of the call peer if one is
     * available.
     *
     * @return byte[] a byte array containing the image or null if no image is
     * available.
     */
    public byte[] getImage()
    {
        return image;
    }

    /**
     * Returns a reference to the <tt>CallPeerMediaHandler</tt> used by this
     * peer. The media handler class handles all media management for a single
     * <tt>CallPeer</tt>. This includes initializing and configuring streams,
     * generating SDP, handling ICE, etc. One instance of <tt>CallPeer</tt>
     * always corresponds to exactly one instance of
     * <tt>CallPeerMediaHandler</tt> and both classes are only separated for
     * reasons of readability.
     *
     * @return a reference to the <tt>CallPeerMediaHandler</tt> instance that
     * this peer uses for media related tips and tricks.
     */
    public U getMediaHandler()
    {
        return mediaHandler;
    }

    /**
     * Returns a unique identifier representing this peer.
     *
     * @return an identifier representing this call peer.
     */
    public String getPeerID()
    {
        return peerID;
    }

    /**
     * Returns the protocol provider that this peer belongs to.
     *
     * @return a reference to the <tt>ProtocolProviderService</tt> that this
     * peer belongs to.
     */
    @Override
    public V getProtocolProvider()
    {
        return protocolProvider;
    }

    /**
     * Determines whether this <tt>CallPeer</tt> is participating in a telephony
     * conference organized by the local user/peer utilizing the Jitsi
     * Videobridge server-side technology.
     *
     * @return <tt>true</tt> if this <tt>CallPeer</tt> is participating in a
     * telephony conference organized by the local user/peer utilizing the Jitsi
     * Videobridge server-side technology; otherwise, <tt>false</tt>
     */
    public final boolean isJitsiVideobridge()
    {
        Call call = getCall();

        if (call != null)
        {
            CallConference conference = call.getConference();

            if (conference != null)
                return conference.isJitsiVideobridge();
        }
        return false;
    }

    /**
     * Determines whether we are currently streaming video toward whoever this
     * <tt>MediaAwareCallPeer</tt> represents.
     *
     * @return <tt>true</tt> if we are currently streaming video toward this
     *  <tt>CallPeer</tt> and  <tt>false</tt> otherwise.
     */
    public boolean isLocalVideoStreaming()
    {
        return getMediaHandler().isLocalVideoTransmissionEnabled();
    }

    /**
     * Determines whether the audio stream (if any) being sent to this
     * peer is mute.
     *
     * @return <tt>true</tt> if an audio stream is being sent to this
     *         peer and it is currently mute; <tt>false</tt>, otherwise
     */
    @Override
    public boolean isMute()
    {
        return getMediaHandler().isMute();
    }

    /**
     * Logs <tt>message</tt> and <tt>cause</tt> and sets this <tt>peer</tt>'s
     * state to <tt>CallPeerState.FAILED</tt>
     *
     * @param message a message to log and display to the user.
     * @param throwable the exception that cause the error we are logging
     */
    public void logAndFail(String message, Throwable throwable)
    {
        logger.error(message, throwable);
        setState(CallPeerState.FAILED, message);
    }

    /**
     * Updates the state of this <tt>CallPeer</tt> to match the locally-on-hold
     * status of our media handler.
     */
    public void reevalLocalHoldStatus()
    {
        CallPeerState state = getState();
        boolean locallyOnHold = getMediaHandler().isLocallyOnHold();

        if (CallPeerState.ON_HOLD_LOCALLY.equals(state))
        {
            if (!locallyOnHold)
                setState(CallPeerState.CONNECTED);
        }
        else if (CallPeerState.ON_HOLD_MUTUALLY.equals(state))
        {
            if (!locallyOnHold)
                setState(CallPeerState.ON_HOLD_REMOTELY);
        }
        else if (CallPeerState.ON_HOLD_REMOTELY.equals(state))
        {
            if (locallyOnHold)
                setState(CallPeerState.ON_HOLD_MUTUALLY);
        }
        else if (locallyOnHold)
        {
            setState(CallPeerState.ON_HOLD_LOCALLY);
        }
    }

    /**
     * Updates the state of this <tt>CallPeer</tt> to match the remotely-on-hold
     * status of our media handler.
     */
    public void reevalRemoteHoldStatus()
    {
        boolean remotelyOnHold = getMediaHandler().isRemotelyOnHold();

        CallPeerState state = getState();
        if (CallPeerState.ON_HOLD_LOCALLY.equals(state))
        {
            if (remotelyOnHold)
                setState(CallPeerState.ON_HOLD_MUTUALLY);
        }
        else if (CallPeerState.ON_HOLD_MUTUALLY.equals(state))
        {
            if (!remotelyOnHold)
                setState(CallPeerState.ON_HOLD_LOCALLY);
        }
        else if (CallPeerState.ON_HOLD_REMOTELY.equals(state))
        {
            if (!remotelyOnHold)
                setState(CallPeerState.CONNECTED);
        }
        else if (remotelyOnHold)
        {
            setState(CallPeerState.ON_HOLD_REMOTELY);
        }
    }

    /**
     * Removes a specific <tt>ConferenceMembersSoundLevelListener</tt> of the
     * list of listeners interested in and notified about changes in conference
     * members sound level.
     *
     * @param listener the <tt>ConferenceMembersSoundLevelListener</tt> to
     * remove
     */
    public void removeConferenceMembersSoundLevelListener(
            ConferenceMembersSoundLevelListener listener)
    {
        synchronized (conferenceMembersSoundLevelListeners)
        {
            if (conferenceMembersSoundLevelListeners.remove(listener)
                    && (conferenceMembersSoundLevelListeners.size() == 0))
            {
                // if this was the last listener then we also remove ourselves
                // as a CSRC audio level listener from the handler so that we
                // don't have to create new events and maps for something no one
                // is interested in.
                getMediaHandler().setCsrcAudioLevelListener(null);
            }
        }
    }

    /**
     * Removes a specific <tt>SoundLevelListener</tt> of the list of
     * listeners interested in and notified about changes in stream sound level
     * related information.
     *
     * @param listener the <tt>SoundLevelListener</tt> to remove
     */
    public void removeStreamSoundLevelListener(SoundLevelListener listener)
    {
        synchronized (streamSoundLevelListenersSyncRoot)
        {
            /*
             * Implement streamAudioLevelListeners as a copy-on-write storage so
             * that iterators over it can iterate over it without
             * ConcurrentModificationExceptions.
             */
            if (streamSoundLevelListeners != null)
            {
                streamSoundLevelListeners
                    = new ArrayList<SoundLevelListener>(
                            streamSoundLevelListeners);
                if (streamSoundLevelListeners.remove(listener)
                        && streamSoundLevelListeners.isEmpty())
                    streamSoundLevelListeners = null;
            }

            if ((streamSoundLevelListeners == null)
                    || streamSoundLevelListeners.isEmpty())
            {
                // if this was the last listener then we also need to remove
                // ourselves as an audio level so that audio levels would only
                // be calculated if anyone is interested in receiving them.
                getMediaHandler().setStreamAudioLevelListener(null);
            }
        }
    }

    /**
     * Removes a specific <tt>PropertyChangeListener</tt> from the list of
     * listeners which get notified when the properties (e.g.
     * LOCAL_VIDEO_STREAMING) associated with this <tt>CallPeer</tt> change
     * their values.
     *
     * @param listener the <tt>PropertyChangeListener</tt> to no longer be
     * notified when the properties associated with the specified <tt>Call</tt>
     * change their values
     */
    public void removeVideoPropertyChangeListener(
                                               PropertyChangeListener listener)
    {
        if (listener != null)
            synchronized (videoPropertyChangeListeners)
            {
                /*
                 * The video is part of the media-related functionality and thus
                 * it is the responsibility of mediaHandler. So we're listening
                 * to mediaHandler for video-related property changes and w're
                 * re-firing them as originating from this instance. Make sure
                 * that we're not listening to mediaHandler if noone is
                 * interested in video-related property changes originating from
                 * this instance.
                 */
                if (videoPropertyChangeListeners.remove(listener)
                        && videoPropertyChangeListeners.isEmpty()
                        && (mediaHandlerPropertyChangeListener != null))
                {
//                    getMediaHandler()
//                        .removePropertyChangeListener(
//                            mediaHandlerPropertyChangeListener);
                    mediaHandlerPropertyChangeListener = null;
                }
            }
    }

    /**
     * Sets the security message associated with a failure/warning or
     * information coming from the encryption protocol.
     *
     * @param messageType the type of the message.
     * @param i18nMessage the message
     * @param severity severity level
     */
    public void securityMessageReceived(
            String messageType,
            String i18nMessage,
            int severity)
    {
        fireCallPeerSecurityMessageEvent(messageType,
                                         i18nMessage,
                                         severity);
    }

    /**
     * Indicates that the other party has timeouted replying to our
     * offer to secure the connection.
     *
     * @param mediaType the <tt>MediaType</tt> of the call session
     * @param sender the security controller that caused the event
     */
    public void securityNegotiationStarted(
            MediaType mediaType,
            SrtpControl sender)
    {
        fireCallPeerSecurityNegotiationStartedEvent(
                new CallPeerSecurityNegotiationStartedEvent(
                        this,
                        toSessionType(mediaType),
                        sender));
    }

    /**
     * Indicates that the other party has timeouted replying to our
     * offer to secure the connection.
     *
     * @param mediaType the <tt>MediaType</tt> of the call session
     */
    public void securityTimeout(MediaType mediaType)
    {
        fireCallPeerSecurityTimeoutEvent(
                new CallPeerSecurityTimeoutEvent(
                        this,
                        toSessionType(mediaType)));
    }

    /**
     * Sets the security status to OFF for this call peer.
     *
     * @param mediaType the <tt>MediaType</tt> of the call session
     */
    public void securityTurnedOff(MediaType mediaType)
    {
        // If this event has been triggered because of a call end event and the
        // call is already ended we don't need to alert the user for
        // security off.
        if((call != null) && !call.getCallState().equals(CallState.CALL_ENDED))
        {
            fireCallPeerSecurityOffEvent(
                    new CallPeerSecurityOffEvent(
                            this,
                            toSessionType(mediaType)));
        }
    }

    /**
     * Sets the security status to ON for this call peer.
     *
     * @param mediaType the <tt>MediaType</tt> of the call session
     * @param cipher the cipher
     * @param sender the security controller that caused the event
     */
    public void securityTurnedOn(
            MediaType mediaType,
            String cipher,
            SrtpControl sender)
    {
        getMediaHandler().startSrtpMultistream(sender);
        fireCallPeerSecurityOnEvent(
                new CallPeerSecurityOnEvent(
                        this,
                        toSessionType(mediaType),
                        cipher,
                        sender));
    }

    /**
     * Sets the call containing this peer.
     *
     * @param call the call that this call peer is participating in.
     */
    public void setCall(T call)
    {
        this.call = call;
    }

    /**
     * Sets the byte array containing an image representation (photo or picture)
     * of the call peer.
     *
     * @param image a byte array containing the image
     */
    public void setImage(byte[] image)
    {
        byte[] oldImage = getImage();
        this.image = image;

        //Fire the Event
        fireCallPeerChangeEvent(
                CallPeerChangeEvent.CALL_PEER_IMAGE_CHANGE,
                oldImage,
                image);
    }

    /**
     * Modifies the local media setup to reflect the requested setting for the
     * streaming of the local video and then re-invites the peer represented by
     * this class using a corresponding SDP description..
     *
     * @param allowed <tt>true</tt> if local video transmission is allowed and
     * <tt>false</tt> otherwise.
     *
     *  @throws OperationFailedException if video initialization fails.
     */
    public void setLocalVideoAllowed(boolean allowed)
        throws OperationFailedException
    {
        CallPeerMediaHandler<?> mediaHandler = getMediaHandler();

        if(mediaHandler.isLocalVideoTransmissionEnabled() != allowed)
        {
            // Modify the local media setup to reflect the requested setting for
            // the streaming of the local video.
            mediaHandler.setLocalVideoTransmissionEnabled(allowed);
        }
    }

    /**
     * Sets a reference to the <tt>CallPeerMediaHandler</tt> used by this
     * peer. The media handler class handles all media management for a single
     * <tt>CallPeer</tt>. This includes initializing and configuring streams,
     * generating SDP, handling ICE, etc. One instance of <tt>CallPeer</tt>
     * always corresponds to exactly one instance of
     * <tt>CallPeerMediaHandler</tt> and both classes are only separated for
     * reasons of readability.
     *
     * @param mediaHandler a reference to the <tt>CallPeerMediaHandler</tt>
     * instance that this peer uses for media related tips and tricks.
     */
    protected void setMediaHandler(U mediaHandler)
    {
        this.mediaHandler = mediaHandler;
    }

    /**
     * Sets the mute property for this call peer.
     *
     * @param newMuteValue the new value of the mute property for this call peer
     */
    @Override
    public void setMute(boolean newMuteValue)
    {
        getMediaHandler().setMute(newMuteValue);
        super.setMute(newMuteValue);
    }

    /**
     * Sets the String that serves as a unique identifier of this
     * CallPeer.
     * @param peerID the ID of this call peer.
     */
    public void setPeerID(String peerID)
    {
        this.peerID = peerID;
    }

    /**
     * Overrides the parent set state method in order to make sure that we
     * close our media handler whenever we enter a disconnected state.
     *
     * @param newState the <tt>CallPeerState</tt> that we are about to enter and
     * that we pass to our predecessor.
     * @param reason a reason phrase explaining the state (e.g. if newState
     * indicates a failure) and that we pass to our predecessor.
     * @param reasonCode the code for the reason of the state change.
     */
    @Override
    public void setState(CallPeerState newState, String reason, int reasonCode)
    {
        // synchronized to mediaHandler if there are currently jobs of
        // initializing, configuring and starting streams (method processAnswer
        // of CallPeerMediaHandler) we won't set and fire the current state
        // to Disconnected. Before closing the mediaHandler is setting the state
        // in order to deliver states as quick as possible.
        CallPeerMediaHandler<?> mediaHandler = getMediaHandler();

        synchronized(mediaHandler)
        {
            try
            {
                super.setState(newState, reason, reasonCode);
            }
            finally
            {
                // make sure whatever happens to close the media
                if (CallPeerState.DISCONNECTED.equals(newState)
                        || CallPeerState.FAILED.equals(newState))
                    mediaHandler.close();
            }
        }
    }

    /**
     * Returns the last <tt>ConferenceInfoDocument</tt> sent by us to this
     * <tt>CallPeer</tt>. It is a document with state <tt>full</tt>
     * @return the last <tt>ConferenceInfoDocument</tt> sent by us to this
     * <tt>CallPeer</tt>. It is a document with state <tt>full</tt>
     */
    public ConferenceInfoDocument getLastConferenceInfoSent()
    {
        return lastConferenceInfoSent;
    }

    /**
     * Sets the last <tt>ConferenceInfoDocument</tt> sent by us to this
     * <tt>CallPeer</tt>.
     * @param confInfo the document to set.
     */
    public void setLastConferenceInfoSent(ConferenceInfoDocument confInfo)
    {
        lastConferenceInfoSent = confInfo;
    }

    /**
     * Gets the time (as obtained by <tt>System.currentTimeMillis()</tt>)
     * at which we last sent a <tt>ConferenceInfoDocument</tt> to this
     * <tt>CallPeer</tt>.
     * @return the time (as obtained by <tt>System.currentTimeMillis()</tt>)
     * at which we last sent a <tt>ConferenceInfoDocument</tt> to this
     * <tt>CallPeer</tt>.
     */
    public long getLastConferenceInfoSentTimestamp()
    {
        return lastConferenceInfoSentTimestamp;
    }

    /**
     * Sets the time (as obtained by <tt>System.currentTimeMillis()</tt>)
     * at which we last sent a <tt>ConferenceInfoDocument</tt> to this
     * <tt>CallPeer</tt>.
     * @param newTimestamp the time to set
     */
    public void setLastConferenceInfoSentTimestamp(long newTimestamp)
    {
        lastConferenceInfoSentTimestamp = newTimestamp;
    }

    /**
     * Gets the last <tt>ConferenceInfoDocument</tt> sent to us by this
     * <tt>CallPeer</tt>.
     * @return the last <tt>ConferenceInfoDocument</tt> sent to us by this
     * <tt>CallPeer</tt>.
     */
    public ConferenceInfoDocument getLastConferenceInfoReceived()
    {
        return lastConferenceInfoReceived;
    }

    /**
     * Gets the last <tt>ConferenceInfoDocument</tt> sent to us by this
     * <tt>CallPeer</tt>.
     * @return the last <tt>ConferenceInfoDocument</tt> sent to us by this
     * <tt>CallPeer</tt>.
     */
    public void setLastConferenceInfoReceived(ConferenceInfoDocument confInfo)
    {
        lastConferenceInfoReceived = confInfo;
    }

    /**
     * Gets the <tt>version</tt> of the last <tt>ConferenceInfoDocument</tt>
     * sent to us by this <tt>CallPeer</tt>, or -1 if we haven't (yet) received
     * a <tt>ConferenceInformationDocument</tt> from this <tt>CallPeer</tt>.
     * @return
     */
    public int getLastConferenceInfoReceivedVersion()
    {
        return (lastConferenceInfoReceived == null)
                ? -1
                : lastConferenceInfoReceived.getVersion();
    }

    /**
     * Gets the <tt>String</tt> to be used for this <tt>CallPeer</tt> when
     * we describe it in a <tt>ConferenceInfoDocument</tt> (e.g. the
     * <tt>entity</tt> key attribute which to use for the <tt>user</tt>
     * element corresponding to this <tt>CallPeer</tt>)
     *
     * @return the <tt>String</tt> to be used for this <tt>CallPeer</tt> when
     * we describe it in a <tt>ConferenceInfoDocument</tt> (e.g. the
     * <tt>entity</tt> key attribute which to use for the <tt>user</tt>
     * element corresponding to this <tt>CallPeer</tt>)
     */
    public abstract String getEntity();

    /**
     * Check whether a conference-info document is scheduled to be sent to
     * this <tt>CallPeer</tt> (i.e. there is a thread which will eventually
     * (after sleeping a certain amount of time) trigger a document to be sent)
     * @return <tt>true</tt> if there is a conference-info document  scheduled
     * to be sent to this <tt>CallPeer</tt> and <tt>false</tt> otherwise.
     */
    public boolean isConfInfoScheduled()
    {
        synchronized (confInfoScheduledSyncRoot)
        {
            return confInfoScheduled;
        }
    }

    /**
     * Sets the property which indicates whether a conference-info document
     * is scheduled to be sent to this <tt>CallPeer</tt>.
     * @param confInfoScheduled
     */
    public void setConfInfoScheduled(boolean confInfoScheduled)
    {
        synchronized (confInfoScheduledSyncRoot)
        {
            this.confInfoScheduled = confInfoScheduled;
        }
    }

    /**
     * Returns the direction of the session for media of type <tt>mediaType</tt>
     * that we have with this <tt>CallPeer</tt>. This is the direction of the
     * session negotiated in the signaling protocol, and it may or may not
     * coincide with the direction of the media stream.
     * For example, if we are the focus of a videobridge conference and another
     * peer is sending video to us, we have a <tt>RECVONLY</tt> video stream,
     * but <tt>SENDONLY</tt> or <tt>SENDRECV</tt> (Jingle) sessions with the
     * rest of the conference members.
     * Should always return non-null.
     *
     * @param mediaType the <tt>MediaType</tt> to use
     * @return Returns the direction of the session for media of type
     * <tt>mediaType</tt> that we have with this <tt>CallPeer</tt>.
     */
    public abstract MediaDirection getDirection(MediaType mediaType);

    /**
     * {@inheritDoc}
     *
     * When a <tt>ConferenceMember</tt> is removed from a conference with a
     * Jitsi-videobridge, an RTCP BYE packet is not always sent. Therefore,
     * if the <tt>ConferenceMember</tt> had an associated video SSRC, the stream
     * isn't be removed until it times out, leaving a blank video container in
     * the interface for a few seconds.
     * TODO: This works around the problem by removing the
     * <tt>ConferenceMember</tt>'s <tt>ReceiveStream</tt> when the
     * <tt>ConferenceMember</tt> is removed. The proper solution is to ensure
     * that RTCP BYEs are sent whenever necessary, and when it is deployed this
     * code should be removed.
     *
     * @param conferenceMember a <tt>ConferenceMember</tt> to be removed from
     * the list of <tt>ConferenceMember</tt> reported by this peer. If the
     * specified <tt>ConferenceMember</tt> is no contained in the list, no event
     */
    @Override
    public void removeConferenceMember(ConferenceMember conferenceMember)
    {
        MediaStream videoStream = getMediaHandler().getStream(MediaType.VIDEO);
        if (videoStream != null)
            videoStream.removeReceiveStreamForSsrc(
                    conferenceMember.getVideoSsrc());

        super.removeConferenceMember(conferenceMember);
    }

    /**
     * Converts a specific <tt>MediaType</tt> into a <tt>sessionType</tt> value
     * in the terms of the <tt>CallPeerSecurityStatusEvent</tt> class.
     *
     * @param mediaType the <tt>MediaType</tt> to be converted
     * @return the <tt>sessionType</tt> value in the terms of the
     * <tt>CallPeerSecurityStatusEvent</tt> class that is equivalent to the
     * specified <tt>mediaType</tt>
     */
    private static int toSessionType(MediaType mediaType)
    {
        switch (mediaType)
        {
        case AUDIO:
            return CallPeerSecurityStatusEvent.AUDIO_SESSION;
        case VIDEO:
            return CallPeerSecurityStatusEvent.VIDEO_SESSION;
        default:
            throw new IllegalArgumentException("mediaType");
        }
    }
}